diff --git "a/_next/static/chunks/587.7590d497bcece81c.js" "b/_next/static/chunks/587.7590d497bcece81c.js" new file mode 100644--- /dev/null +++ "b/_next/static/chunks/587.7590d497bcece81c.js" @@ -0,0 +1,6 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[587],{4699:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return(r+n)*3/4-n},t.toByteArray=function(e){var t,r,i=l(e),o=i[0],a=i[1],h=new s((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=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,h[c++]=255&t),1===a&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,h[c++]=t>>8&255,h[c++]=255&t),h},t.fromByteArray=function(e){for(var t,n=e.length,s=n%3,i=[],o=0,a=n-s;o>18&63]+r[s>>12&63]+r[s>>6&63]+r[63&s]);return i.join("")}(e,o,o+16383>a?a:o+16383));return 1===s?i.push(r[(t=e[n-1])>>2]+r[t<<4&63]+"=="):2===s&&i.push(r[(t=(e[n-2]<<8)+e[n-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),i.join("")};for(var r=[],n=[],s="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 n=r===t?0:4-r%4;return[r,n]}n["-".charCodeAt(0)]=62,n["_".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 n=r(4699),s=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),n=o(r),s=n.write(e,t);return s!==r&&(n=n.slice(0,s)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(I(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(I(e,ArrayBuffer)||e&&I(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(I(e,SharedArrayBuffer)||e&&I(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 n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return a.from(n,t,r);var s=function(e){if(a.isBuffer(e)){var t,r=0|f(e.length),n=o(r);return 0===n.length||e.copy(n,0,0,r),n}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(s)return s;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),n=0;n=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)||I(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,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var s=!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(s)return n?-1:z(e).length;t=(""+t).toLowerCase(),s=!0}}function _(e,t,r){var s,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 n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var s="",i=t;i2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),(i=r=+r)!=i&&(r=s?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return -1;r=e.length-1}else if(r<0){if(!s)return -1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,s);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,s);throw TypeError("val must be string, number or Buffer")}function y(e,t,r,n,s){var i,o=1,a=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){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(s){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(s+u<=r)switch(u){case 1:h<128&&(c=h);break;case 2:(192&(i=e[s+1]))==128&&(l=(31&h)<<6|63&i)>127&&(c=l);break;case 3:i=e[s+1],o=e[s+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[s+1],o=e[s+2],a=e[s+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,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),s+=u}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var r="",n=0;nr)throw RangeError("Trying to access beyond buffer length")}function k(e,t,r,n,s,i){if(!a.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw RangeError("Index out of range")}function v(e,t,r,n,s,i){if(r+n>e.length||r<0)throw RangeError("Index out of range")}function x(e,t,r,n,i){return t=+t,r>>>=0,i||v(e,t,r,4,34028234663852886e22,-34028234663852886e22),s.write(e,t,r,n,23,4),r+4}function A(e,t,r,n,i){return t=+t,r>>>=0,i||v(e,t,r,8,17976931348623157e292,-17976931348623157e292),s.write(e,t,r,n,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(I(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),I(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,n=t.length,s=0,i=Math.min(r,n);sn.length?a.from(i).copy(n,s):Uint8Array.prototype.set.call(n,i,s);else if(a.isBuffer(i))i.copy(n,s);else throw TypeError('"list" argument must be an Array of Buffers');s+=i.length}return n},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,n,s){if(I(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===n&&(n=0),void 0===s&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,s>>>=0,this===e)return 0;for(var i=s-n,o=r-t,l=Math.min(i,o),h=this.slice(n,s),c=e.slice(t,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s,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");n||(n="utf8");for(var f=!1;;)switch(n){case"hex":return function(e,t,r,n){r=Number(r)||0;var s=e.length-r;n?(n=Number(n))>s&&(n=s):n=s;var i=t.length;n>i/2&&(n=i/2);for(var o=0;o>8,s.push(r%256),s.push(n);return s}(e,this.length-c),this,c,u);default:if(f)throw TypeError("Unknown encoding: "+n);n=(""+n).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 n=this[e],s=1,i=0;++i>>=0,t>>>=0,r||b(e,t,this.length);for(var n=this[e+--t],s=1;t>0&&(s*=256);)n+=this[e+--t]*s;return n},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 n=this[e],s=1,i=0;++i=(s*=128)&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var n=t,s=1,i=this[e+--n];n>0&&(s*=256);)i+=this[e+--n]*s;return i>=(s*=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),s.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),s.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),s.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),s.read(this,e,!1,52,8)},a.prototype.writeUintLE=a.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){var s=Math.pow(2,8*r)-1;k(this,e,t,r,s,0)}var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,!n){var s=Math.pow(2,8*r)-1;k(this,e,t,r,s,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||k(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||k(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||k(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||k(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||k(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,n){if(e=+e,t>>>=0,!n){var s=Math.pow(2,8*r-1);k(this,e,t,r,s-1,-s)}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,n){if(e=+e,t>>>=0,!n){var s=Math.pow(2,8*r-1);k(this,e,t,r,s-1,-s)}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||k(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||k(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||k(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||k(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||k(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 x(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return x(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,n){if(!a.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw RangeError("Index out of range");if(n<0)throw RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(s=t;s55295&&r<57344){if(!s){if(r>56319||o+1===n){(t-=3)>-1&&i.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),s=r;continue}r=(s-55296<<10|r-56320)+65536}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=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 n.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 M(e,t,r,n){for(var s=0;s=t.length)&&!(s>=e.length);++s)t[s+r]=e[s];return s}function I(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var B=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var n=16*r,s=0;s<16;++s)t[n+s]=e[r]+e[s];return t}()},9087:function(e,t){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */t.read=function(e,t,r,n,s){var i,o,a=8*s-n-1,l=(1<>1,c=-7,u=r?s-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+=n;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,n),i-=h}return(f?-1:1)*o*Math.pow(2,i-n)},t.write=function(e,t,r,n,s,i){var o,a,l,h=8*i-s-1,c=(1<>1,d=23===s?5960464477539062e-23:0,f=n?0:i-1,p=n?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,s),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));s>=8;e[r+f]=255&a,f+=p,a/=256,s-=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 n,s;e.exports=(null==(n=r.g.process)?void 0:n.env)&&"object"==typeof(null==(s=r.g.process)?void 0:s.env)?r.g.process:r(8960)},692:function(e,t,r){!function(){var t={452:function(e){"use strict";e.exports=r(9875)}},n={};function s(e){var r=n[e];if(void 0!==r)return r.exports;var i=n[e]={exports:{}},o=!0;try{t[e](i,i.exports,s),o=!1}finally{o&&delete n[e]}return i.exports}s.ab="//";var i={};!function(){var e,t=(e=s(452))&&"object"==typeof e&&"default"in e?e.default:e,r=/https?|ftp|gopher|file/;function n(e){"string"==typeof e&&(e=g(e));var n,s,i,o,a,l,h,c,u,d=(s=(n=e).auth,i=n.hostname,o=n.protocol||"",a=n.pathname||"",l=n.hash||"",h=n.query||"",c=!1,s=s?encodeURIComponent(s).replace(/%3A/i,":")+"@":"",n.host?c=s+n.host:i&&(c=s+(~i.indexOf(":")?"["+i+"]":i),n.port&&(c+=":"+n.port)),h&&"object"==typeof h&&(h=t.encode(h)),u=n.search||h&&"?"+h||"",o&&":"!==o.substr(-1)&&(o+=":"),n.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?n(e):e;var s=g(t),i="";r.protocol&&!r.slashes&&(i=r.protocol,e=e.replace(r.protocol,""),i+="/"===t[0]||"/"===e[0]?"/":""),i&&s.protocol&&(i="",s.slashes||(i=s.protocol,t=t.replace(s.protocol,"")));var c=e.match(l);c&&!s.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=s.protocol||r.protocol;return f+=r.slashes||s.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=n,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,s){if(void 0===r&&(r=!1),void 0===s&&(s=!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="",k="";try{c=new URL(e)}catch(t){b=t,h||s||!/^\/\//.test(e)||/^\/\/.+[@.]/.test(e)||(k="/",e=e.substr(1));try{c=new URL(e,a)}catch(e){return w.protocol=h,w.href=h,w}}w.slashes=l&&!k,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 v=e.split("#");!w.search&&~v[0].indexOf("?")&&(w.search="?"),w.hash||""!==v[1]||(w.hash="#"),w.query=r?t.decode(c.search.substr(1)):w.search.substr(1),w.pathname=k+(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=k?""+w.pathname+w.search+w.hash:n(w);var x=/^(file)/.test(w.href)?["host","hostname"]:[];return Object.keys(w).forEach(function(e){~x.indexOf(e)||(w[e]=w[e]||null)}),w}i.parse=g,i.format=n,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,n,s=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&&n&&(h=!1,n.length?l=n.concat(l):c=-1,l.length&&d())}function d(){if(!h){var e=a(u);h=!0;for(var t=l.length;t;){for(n=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)?n(s(e),function(s){var a=encodeURIComponent(t(s))+o;return r(e[s])?n(e[s],function(e){return a+encodeURIComponent(t(e))}).join(i):a+encodeURIComponent(t(e[s]))}).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 n(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n{if(t&&"function"==typeof t.init&&"function"==typeof t.createSessionHandler){let i=n[e];if(void 0===i)n[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=s.indexOf(e);-1!==t&&s.splice(t,1);for(let t=0;t{let t=0===e.length?s:e,r=[];for(let e of t){let t=n[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(s){n||r.push({name:e,err:s}),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 s=document.createElement("canvas"),i=s.getContext("2d");if(!e||!i)return n();let o=new Image;o.crossOrigin="Anonymous",o.src=e,o.onload=()=>{s.width=o.width,s.height=o.height,i.drawImage(o,0,0,s.width,s.height);let e=i.getImageData(0,0,s.width,s.height);if(void 0!==t){if(void 0!==t.height&&t.height!==s.height)throw Error("Image input config height doesn't match ImageBitmap height");if(a.height=s.height,void 0!==t.width&&t.width!==s.width)throw Error("Image input config width doesn't match ImageBitmap width");a.width=s.width}else a.height=s.height,a.width=s.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 n;let s=document.createElement("canvas").getContext("2d");if(null!=s){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),n=s.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 n&&null!==n)i=n;else if(void 0!==n)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.");s=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(s,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=_},4975:function(e,t,r){"use strict";let n,s,i,o;function a(e,t){null!==e&&e(t)}function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}r.d(t,{OBj:function(){return O},qCb:function(){return ee},EUT:function(){return nn}});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 n=e[t];if(void 0!==n)return delete e[t],n;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),k=r.t(b,2),v=r(2018),x=r.t(v,2),A=r(2601);let E=["wasm"];if(void 0!==A&&A?.release?.name==="node")n=b??k,E.unshift("cpu");else{n=v??x;let e="undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);e&&(n.env.wasm.simd=!1)}let{env:z}=n,T="2.4.2",M="undefined"!=typeof self&&"caches"in self,I=!R(g),B=!R(y),S=I&&B,C=S?y.dirname(y.dirname(w.fileURLToPath("file:///workspaces/transformers.js/examples/next/node_modules/@xenova/transformers/src/env.js"))):"./",P=S?y.join(C,"/.cache/"):null,U="/models/",L=S?y.join(C,U):U;z.wasm.wasmPaths=S?y.join(C,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${T}/dist/`;let O={backends:{onnx:z,tfjs:{}},__dirname:C,version:T,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath:L,useFS:I,useBrowserCache:M,useFSCache:I,cacheDir:P};function R(e){return 0===Object.keys(e).length}var j=r(2601),N=r(7133).lW;globalThis.ReadableStream||(globalThis.ReadableStream=m.ReadableStream);class ${_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 $(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 G(e){if(O.useFS&&!F(e))return new $(e);if(void 0===j||j?.release?.name!=="node")return fetch(e);{let t=!!j.env?.TESTING_REMOTELY,r=O.version,n=new Headers;n.set("User-Agent",`transformers.js/${r}; is_ci/${t};`);let s=F(e,["huggingface.co","hf.co"]);if(s){let e=j.env?.HF_ACCESS_TOKEN;e&&n.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:n})}}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 D{constructor(e){this.path=e}async match(e){let t=_.join(this.path,e),r=new $(t);return r.exists?r:void 0}async put(e,t){let r=N.from(await t.arrayBuffer()),n=_.join(this.path,e);try{await p.promises.mkdir(_.dirname(n),{recursive:!0}),await p.promises.writeFile(n,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 K(e,t,r=!0,n={}){let s,i,o,l;if(!O.allowLocalModels){if(n.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(!O.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}if(a(n.progress_callback,{status:"initiate",name:e,file:t}),!s&&O.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{s=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}!s&&O.useFSCache&&(s=new D(n.cache_dir??O.cacheDir));let h=n.revision??"main",c=V(e,t),u=V(O.localModelPath,c),d=V(O.remoteHost,O.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",h),t),f="main"===h?c:V(e,h,t),p=s instanceof D?f:d;if(s&&(l=await W(s,u,p)),void 0===l){if(O.allowLocalModels){let e=F(c);if(e){if(n.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${c}.`);if(!O.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${c}.`)}else try{l=await G(u),i=u}catch(e){console.warn(`Unable to load from local path "${u}": "${e}"`)}}if(void 0===l||404===l.status){if(n.local_files_only||!O.allowRemoteModels){if(!r)return null;throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${u}".`)}if(200!==(l=await G(d)).status)return function(e,t,r){if(!r)return null;let n=q[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}(l.status,d,r);i=p}s&&l instanceof Response&&200===l.status&&(o=l.clone())}a(n.progress_callback,{status:"download",name:e,file:t});let _=await X(l,r=>{a(n.progress_callback,{status:"progress",...r,name:e,file:t})});return o&&i&&await s.match(i)===void 0&&await s.put(i,o).catch(e=>{console.warn(`Unable to add response to browser cache: ${e}.`)}),a(n.progress_callback,{status:"done",name:e,file:t}),_}async function H(e,t,r=!0,n={}){let s=await K(e,t,r,n);return null===s?{}:JSON.parse(new TextDecoder("utf-8").decode(s))}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 n=parseInt(r??"0"),s=new Uint8Array(n),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>n){n=l;let e=new Uint8Array(n);e.set(s),s=e}s.set(r,i),i=l;let h=i/n*100;return t({progress:h,loaded:i,total:n}),a()}return await a(),s}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 J(e){let t=Z(e)[0],r=e.map(e=>Math.exp(e-t)),n=r.reduce((e,t)=>e+t,0),s=r.map(e=>e/n);return s}function Y(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 n=1;nt&&(t=e[n],r=n);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 n=2;n>=2;a>=2;a>>=2){let t=(l=i/a<<1)>>>2;for(n=0;n>>1,i>>>1)}else for(a=0,l=0;a>>1,i>>>1,r)}for(i>>=2;i>=2;i>>=2){o=n/i<<1;let t=o>>>1,s=t>>>1,l=s>>>1;for(a=0;a=e.length&&(s=2*(e.length-1)-s),n[i++]=e[s]}n.sort(),r[t]=n[s]}return r}function et(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}let er=n.Tensor;class en extends er{constructor(...e){return e[0]instanceof n.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 n=0;n0))return new en(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!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let e=t.length-1;e>=0;e--)s=s.reduce((r,n)=>{let s=r[r.length-1];return s.lengths[1])throw Error(`Invalid slice: ${s}`);let e=[Math.max(s[0],0),Math.min(s[1],this.dims[n])];r.push(e),t.push(e[1]-e[0])}else throw Error(`Invalid slice: ${s}`)}let n=r.map(([e,t])=>t-e),s=n.reduce((e,t)=>e*t),i=new this.data.constructor(s),o=this.stride();for(let e=0;e=0;--s){let e=n[s];t+=(i%e+r[s][0])*o[s],i=Math.floor(i/e)}i[e]=this.data[t]}return new en(this.type,i,t)}transpose(...e){return es(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 en(this.type,[t],[])}t=el(t,this.dims.length);let n=this.dims.slice();n[t]=1;let s=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=s%r;i+=t*o,o*=n[e]}s=Math.floor(s/r)}s[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=s%e;n+=t*i,i*=this.dims[r]}s=Math.floor(s/e)}this.data[e]/=r.data[n]}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,n=1;r>=0;--r)t[r]=n,n*=e[r];return t}(this.dims)}squeeze(e=null){return new en(this.type,this.data,eo(this.dims,e))}squeeze_(e=null){return this.dims=eo(this.dims,e),this}unsqueeze(e=null){return new en(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),n=this.dims.slice(e,t+1),s=this.dims.slice(t+1);return this.dims=[...r,n.reduce((e,t)=>e*t,1),...s],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let r=0;rn!==t?e*r:e,1);e[t]=this.data.length/r}return new en(this.type,this.data,e)}neg_(){for(let e=0;e=0;--e)s[e]=i,n[e]=t[r[e]],i*=n[e];let i=r.map((e,t)=>s[r.indexOf(t)]),o=new e.constructor(e.length);for(let r=0;r=0;--e)n+=s%t[e]*i[e],s=Math.floor(s/t[e]);o[n]=e[r]}return[o,n]}(e.data,e.dims,t);return new en(e.type,r,n)}function ei(e,[t,r],n="bilinear",s=!1){let i=e.dims.at(-3)??1,o=e.dims.at(-2),a=e.dims.at(-1),l=function(e,[t,r,n],[s,i],o="bilinear",a=!1){let l=i/n,h=s/r,c=new e.constructor(s*i*t),u=r*n,d=s*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 n=r.reduce((e,t)=>e*t,1),s=new e[0].data.constructor(n),i=e[0].type;if(0===t){let t=0;for(let r of e)s.set(r.data,t),t+=r.data.length}else{let n=0;for(let i=0;i=0;--s){let e=o.dims[s],h=a%e;s===t&&(h+=n),i+=h*l,l*=r[s],a=Math.floor(a/e)}s[i]=o.data[e]}n+=o.dims[t]}}return new en(i,s,r)}function ec(e,t=null,r=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0);return new en(e.type,[t/e.data.length],[])}t=el(t,e.dims.length);let n=e.dims.slice();n[t]=1;let s=new e.data.constructor(e.data.length/e.dims[t]);for(let r=0;r=0;--s){let r=e.dims[s];if(s!==t){let e=o%r;i+=e*a,a*=n[s]}o=Math.floor(o/r)}s[i]+=e.data[r]}if(1!==e.dims[t])for(let r=0;rthis.tokens_to_ids.get(e)??this.unk_token_id);return this.fuse_unk&&(t=function(e,t){let r=[],n=0;for(;nthis.vocab[e]??this.unk_token)}}class em extends e_{constructor(e){for(let[t,r]of(super(e),this.tokens_to_ids=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],n=!1,s=0,i=[];for(;s0&&(n=this.config.continuing_subword_prefix+n),this.tokens_to_ids.has(n)){r=n;break}--t}if(null===r){n=!0;break}i.push(r),s=t}n?t.push(this.unk_token):t.push(...i)}return t}}class eg extends e_{constructor(e,t){super(e),this.vocab=Array(e.vocab.size),this.scores=Array(e.vocab.size);let r=0;e.vocab.forEach((e,t)=>{this.vocab[r]=t,this.scores[r]=e,++r}),this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,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 n=1;n{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 n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);let n=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,n[t]]))})(),ew=Object.fromEntries(Object.entries(ey).map(([e,t])=>[t,e]));class eb extends e_{constructor(e){for(let[t,r]of(super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=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=Object.fromEntries(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=Object.create(null),this.fuse_unk??=this.config.fuse_unk}get_pairs(e){let t=new Set,r=e[0];for(let n=1;n(this.bpe_ranks[e]??1/0)<=(this.bpe_ranks[t]??1/0)?e:t);if(!(e in this.bpe_ranks))break;let[n,s]=e.split(this.BPE_SPLIT_TOKEN),i=[],o=0,a=-1;for(;o`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`)):t.push(this.unk_token);return t}}class ek extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new eI(e);case"Precompiled":return new eJ(e);case"Sequence":return new eM(e);case"Replace":return new ev(e);case"NFC":return new ex(e);case"NFKD":return new eA(e);case"StripAccents":return new eE(e);case"Lowercase":return new ez(e);case"Prepend":return new eT(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 ev extends ek{normalize(e){let t=ed(this.config.pattern);return null===t?e:e=e.replaceAll(t,this.config.content)}}class ex extends ek{normalize(e){return e=e.normalize("NFC")}}class eA extends ek{normalize(e){return e=e.normalize("NFKD")}}class eE extends ek{normalize(e){return e=e.replace(/[\u0300-\u036f]/g,"")}}class ez extends ek{normalize(e){return e=e.toLowerCase()}}class eT extends ek{normalize(e){return e=this.config.prepend+e}}class eM extends ek{constructor(e){super(e),this.normalizers=e.normalizers.map(e=>ek.fromConfig(e))}normalize(e){return this.normalizers.reduce((e,t)=>t.normalize(e),e)}}class eI extends ek{_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 eB extends h{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new eS(e);case"Sequence":return new eY(e);case"WhitespaceSplit":return new eZ(e);case"Metaspace":return new eX(e);case"ByteLevel":return new eC(e);case"Split":return new eP(e);case"Punctuation":return new eU(e);case"Digits":return new eL(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 eS extends eB{constructor(e){super(),this.pattern=RegExp(`[^\\s${ep}]+|[${ep}]`,"gu")}pre_tokenize_text(e){return e.trim().match(this.pattern)||[]}}class eC extends eB{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=ey,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 eP extends eB{constructor(e){super(),this.config=e,this.pattern=ed(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 eU extends eB{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${ep}]+|[${ep}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}}class eL extends eB{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 eO extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new ej(e);case"ByteLevel":return new eN(e);case"RobertaProcessing":return new eR(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 eR extends eO{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 ej extends eO{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,n=[];for(let s of r)"SpecialToken"in s?n.push(s.SpecialToken.id):"Sequence"in s&&("A"===s.Sequence.id?n=f(n,e):"B"===s.Sequence.id&&(n=f(n,t)));return n}}class eN extends eO{post_process(e){return e}}class e$ 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 eW(e);case"Metaspace":return new eV(e);case"ByteLevel":return new eK(e);case"Replace":return new eF(e);case"ByteFallback":return new eG(e);case"Fuse":return new eq(e);case"Strip":return new eD(e);case"Sequence":return new eH(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 eF extends e${constructor(e){super(e)}decode_chain(e){let t=ed(this.config.pattern);return null===t?e:e.map(e=>e.replaceAll(t,this.config.content))}}class eG extends e${constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let n of e){let e=null;if(6===n.length&&n.startsWith("<0x")&&n.endsWith(">")){let t=parseInt(n.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(n)}}if(r.length>0){let e=this.text_decoder.decode(Uint8Array.from(r));t.push(e),r=[]}return t}}class eq extends e${constructor(e){super(e)}decode_chain(e){return[e.join("")]}}class eD extends e${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=ef(e)),e))}}class eK extends e${constructor(e){super(e),this.byte_decoder=ew,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 n of e)this.added_tokens.includes(n)?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}}class eH extends e${constructor(e){super(e),this.decoders=e.decoders.map(e=>e$.fromConfig(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}}class eX extends eB{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 eV extends e${constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){let t=[];for(let r=0;reB.fromConfig(e))}pre_tokenize_text(e){return"string"==typeof e&&(e=[e]),this.tokenizers.reduce((e,t)=>t.pre_tokenize(e),e)}}class eZ extends eB{constructor(e){super()}pre_tokenize_text(e){return e.match(/\S+/g)||[]}}class eQ extends h{constructor(e,t){for(let r of(super(),this.normalizer=ek.fromConfig(e.normalizer),this.pre_tokenizer=eB.fromConfig(e.pre_tokenizer),e.model.vocab&&(Array.isArray(e.model.vocab)||(e.model.vocab=Object.entries(e.model.vocab)),e.model.vocab=new Map(e.model.vocab)),this.model=e_.fromConfig(e.model,t),this.post_processor=eO.fromConfig(e.post_processor),this.decoder=e$.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.decoder.added_tokens=this.added_tokens,this.added_tokens_regex=RegExp("("+this.added_tokens.map(l).join("|")+")"),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.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:n=null,local_files_only:s=!1,revision:i="main"}={}){let o=await eu(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:i});return new this(...o)}prepare_model_inputs(e){return e}_call(e,{text_pair:t=null,padding:r=!1,truncation:n=null,max_length:s=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===s&&(s=a),s=Math.min(s,this.model_max_length);let l=[];if(r||n)for(let e=0;es)n&&(o[e]=o[e].slice(0,s)),l.push(Array(o[e].length).fill(1));else if(r){let t=s-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&&n)&&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 en("int64",BigInt64Array.from(o.flat().map(BigInt)),e),l=new en("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=e.split(this.added_tokens_regex).filter(e=>e);return t.map(e=>{if(this.added_tokens.includes(e))return e;{!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),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),n=this._encode_text(t),s=null!==this.post_processor?this.post_processor(r,n):f(r??[],n??[]);return this.model.convert_tokens_to_ids(s)}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 n=this.model.convert_ids_to_tokens(e);t&&(n=n.filter(e=>!this.special_tokens.includes(e)));let s=this.decoder(n);return this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t&&(s=s.trim())),(r??this.clean_up_tokenization_spaces)&&(s=ef(s)),s}}function e0(e){if(e.input_ids instanceof en)e.token_type_ids=new en("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 e1 extends eQ{prepare_model_inputs(e){return e0(e)}}class e2 extends eQ{prepare_model_inputs(e){return e0(e)}}class e3 extends eQ{prepare_model_inputs(e){return e0(e)}}class e6 extends eQ{prepare_model_inputs(e){return e0(e)}}class e4 extends eQ{}class e5 extends eQ{}class e8 extends eQ{}class e7 extends eQ{}class e9 extends eQ{}class te extends eQ{}class tt extends eQ{}class tr extends eQ{}class tn extends eQ{}class ts extends eQ{prepare_model_inputs(e){return e0(e)}}class ti extends eQ{}class to extends eQ{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))}_build_translation_inputs(e,t,r){if(!this.language_codes.includes(r.tgt_lang))throw Error(`Target language code "${r.tgt_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);if(void 0!==r.src_lang){if(!this.language_codes.includes(r.src_lang))throw Error(`Source language code "${r.src_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);for(let e of this.post_processor.config.single)if("SpecialToken"in e&&this.languageRegex.test(e.SpecialToken.id)){e.SpecialToken.id=r.src_lang;break}}return r.forced_bos_token_id=this.model.convert_tokens_to_ids([r.tgt_lang])[0],this._call(e,t)}}let ta=[["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"]],tl=new Map(ta),th=new Map([...ta.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 tc extends eQ{_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(null===n)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,s=o?r.token_timestamps:null,g=null,y=u;if("stride"in r){let[t,s,i]=r.stride;if(c-=s,_=t-i,s&&(y=s/n+u),i)for(let t=e.length-1;t>=0;--t){let r=e[t];if(r>=u){if(null!==g&&(r-u)*n<_)break;g=r}}}let w=[],b=[];for(let r=0;r=u){let e=(_-u)*n+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(s&&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),n=this.decode(e);h.text=n,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=[s,i,a,l])}let[f,p,_,m]=u,g=Math.floor((p+f)/2),y=Math.floor((m+_)/2);s.push(...r.slice(0,g)),n=(r=h.slice(y)).length,i&&(o.push(...a.slice(0,g)),a=t[l].slice(y))}return(s.push(...r),i)?(o.push(...a),[s,o]):[s,[]]}collateWordTimestamps(e,t,r){let[n,s,i]=this.combineTokensIntoWords(e,r),o=[];for(let e=0;e=n){let e=(t-n)*r;e=et(e,2),s.push(`<|${e}|>`),s.push([])}else s[s.length-1].push(t);return(s=s.map(e=>"string"==typeof e?e:super.decode(e,t))).join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),r=[],n=[],s=[],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===s.length)s.push(l),i.push(h),o.push(c);else{let e=s.length-1;s[e]+=l,i[e].push(...h),o[e].push(...c)}}return[s,i,o]}mergePunctuations(e,t,r,n,s){let i=structuredClone(e),o=structuredClone(t),a=structuredClone(r),l=i.length-2,h=i.length-1;for(;l>=0;)i[l].startsWith(" ")&&n.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 n=[];if(e){e=e.toLowerCase();let t=th.get(e);if(void 0===t){if(tl.has(e))t=e;else{let t=2===e.length,r=t?tl.keys():tl.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.`);n.push(r)}else n.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.`);n.push(e)}else n.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.');n.push(e)}return n.map((e,t)=>[t+1,e]).filter(e=>null!==e[1])}}class tu extends eQ{}class td extends eQ{}class tf extends eQ{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 tp{constructor(){this.root=t_.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let e=t.children.get(r);void 0===e&&(e=t_.default(),t.children.set(r,e)),t=e}t.isLeaf=!0}*commonPrefixSearch(e){let t=this.root,r="";for(let n=0;nr)&&(n=s.clone(),r=t)}if(null===n)return[];e.prev=n,e.backtraceScore=r}++t}let r=[],n=this.beginNodes[e][0],s=n.prev;if(null===s)return[];let i=s.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 tg{constructor(e,t,r,n,s){this.tokenId=e,this.nodeId=t,this.pos=r,this.length=n,this.score=s,this.prev=null,this.backtraceScore=0}clone(){let e=new tg(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}class ty{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:e5,DistilBertTokenizer:e4,BertTokenizer:e1,MobileBertTokenizer:e3,SqueezeBertTokenizer:e6,AlbertTokenizer:e2,GPT2Tokenizer:e8,BartTokenizer:e7,RobertaTokenizer:e9,WhisperTokenizer:tc,CodeGenTokenizer:tu,CLIPTokenizer:td,MarianTokenizer:tf,BloomTokenizer:te,NllbTokenizer:to,LlamaTokenizer:tt,XLMRobertaTokenizer:tr,MPNetTokenizer:tn,FalconTokenizer:ts,GPTNeoXTokenizer:ti,PreTrainedTokenizer:eQ};static async from_pretrained(e,{quantized:t=!0,progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main"}={}){let[a,l]=await eu(e,{quantized:t,progress_callback:r,config:n,cache_dir:s,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=eQ),new c(a,l)}}async function tw(e,t){return await H(e,"config.json",!0,t)}class tb{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:n=null,local_files_only:s=!1,revision:i="main"}={}){let o=r??await tw(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:i});return new this(o)}}class tk{static async from_pretrained(...e){return tb.from_pretrained(...e)}}class tv 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 tx extends h{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class tA extends tx{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 tE extends tx{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 tz extends tx{constructor(e,t){super(),this.max_length=e,this.forced_eos_token_id=t}_call(e,t){}}class tT extends tx{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 tM extends tx{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),n=r.length>=1&&r[r.length-1]>=this.timestamp_begin,s=r.length<2||r[r.length-2]>=this.timestamp_begin;if(n&&(s?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=J(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 tI extends tx{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,r=[];for(let n=0;n0&&(n=n.map(e=>e/this.generation_config.temperature)),n}randomSelect(e){let t=Math.random()*e.reduce((e,t)=>e+t,0);for(let r=0;r1)return new tL(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 tP(e)}}class tP extends tC{sample(e,t=-1){return[[Z(this.getLogits(e,t))[1],0]]}}class tU extends tC{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 n=this.getLogits(e,t),s=Y(n,r),i=J(s.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[s[e][0],Math.log(i[e])]})}}class tL extends tC{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 n=this.getLogits(e,t),s=Y(n,r),i=J(s.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},(e,t)=>[s[t][0],Math.log(i[t])])}}let{InferenceSession:tO,Tensor:tR}=n;class tj{}class tN extends tj{}class t$ extends tj{}class tF extends t${}class tG extends tj{}let tq=new Map,tD=new Map;async function tW(e,t){return tq.get(e.constructor.name)===tG?await t1(e,t):await t0(e,t)}async function tK(e,t,r){let n=`onnx/${t}${r.quantized?"_quantized":""}.onnx`,s=await K(e,n,!0,r);try{return await tO.create(s,{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 tO.create(s,{executionProviders:["wasm"]})}}async function tH(e,t){let r={},n=[];for(let s of e.inputNames)void 0===t[s]?n.push(s):r[s]=t[s];if(n.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);let s=Object.keys(t).length,i=e.inputNames.length;return s>i&&console.warn(`WARNING: Too many inputs were provided (${s} > ${i}). The following inputs will be ignored: "${Object.keys(t).filter(t=>!e.inputNames.includes(t)).join(", ")}".`),r}async function tX(e,t){let r=await tH(e,t);try{let t=await e.run(r);return t=function e(t){for(let r in t)t[r]instanceof tR?t[r]=new en(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 tV(e,t){let r=e.config.pad_token_id??null,n=e.config.eos_token_id??null;u(n)&&(n=[n]);let s=-1!==t.indexOf(r),i=null===n||!n.includes(r);if(!s||!i)return new en("int64",new BigInt64Array(t.data.length).fill(1n),t.dims);{let e=BigInt64Array.from(t.data.map(e=>e!=r));return new en("int64",e,t.dims)}}function tJ(e){return new en("bool",[e],[1])}async function tY(e,t,{add_decoder_pkv:r=!0}={}){let{encoder_outputs:n,past_key_values:s}=t;n||(n=(await t0(e,t)).last_hidden_state);let i={input_ids:t.decoder_input_ids,encoder_hidden_states:n,use_cache_branch:tJ(!!s)};e.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),e.addPastKeyValues(i,s,r);let o=await tX(e.decoder_merged_session,i),a=o.logits;s=e.getPastKeyValues(o,s);let l=e.getAttentions(o);return new r$({logits:a,past_key_values:s,encoder_outputs:n,...l})}function tZ(e,t,r,n=!0){let s=[],i=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:i++};n&&(t.attention_mask=tV(e,r)),s.push(t)}return s}async function tQ(e,t,{input_name:r="input_ids"}={}){let n={[r]:t.inputs,decoder_input_ids:function(e){if(e instanceof en)return e;if(0===e.length)throw Error("items must be non-empty");if(!Array.isArray(e[0]))return new en("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 en("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&&(n.attention_mask=t.attention_mask);let s=await e.forward(n);return t.prev_model_outputs=s,t.encoder_outputs=s.encoder_outputs,s}async function t0(e,t){let r={};for(let n of e.session.inputNames)r[n]=t[n];return await tX(e.session,r)}async function t1(e,t){let{input_ids:r,past_key_values:n,attention_mask:s}=t,i={input_ids:r,attention_mask:s??tV(e,r),use_cache_branch:tJ(null!==n)};e.addPastKeyValues(i,n);let o=await tX(e.session,i);return{logits:o.logits,past_key_values:n=e.getPastKeyValues(o,n)}}function t2(e,t,r,n){let s=[],i=0;for(let o of t){let t,a=o.tolist().map(Number);o.dims=[1,...o.dims],n?(t=n[i]).dims=[1,...t.dims]:t=tV(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++};s.push(l)}return s}async function t3(e,t){let r=new BigInt64Array(t.output_token_ids.length).fill(1n),n={input_ids:t.model_input_ids,attention_mask:new en("int64",r,[1,r.length]),past_key_values:t.prev_model_outputs?.past_key_values},s=await e.forward(n);return t.prev_model_outputs=s,s}function t6(e,t){e.output_token_ids=[...e.output_token_ids,t],e.model_input_ids=new en("int64",[BigInt(t)],[1,1])}class t4 extends h{constructor(e,t){super(),this.config=e,this.session=t}async dispose(){let e=[];for(let t of Object.keys(this)){let r=this[t];r instanceof tO&&e.push(r.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{quantized:t=!0,progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main"}={}){let a,l={quantized:t,progress_callback:r,config:n,cache_dir:s,local_files_only:i,revision:o},h=tq.get(this.name);if(h===tG)a=await Promise.all([tk.from_pretrained(e,l),tK(e,"decoder_model_merged",l)]);else if(h===tF)a=await Promise.all([tk.from_pretrained(e,l),tK(e,"encoder_model",l),tK(e,"decoder_model_merged",l),H(e,"generation_config.json",!1,l)]);else if(h===t$)a=await Promise.all([tk.from_pretrained(e,l),tK(e,"encoder_model",l),tK(e,"decoder_model_merged",l)]);else if(h===tN)a=await Promise.all([tk.from_pretrained(e,l),tK(e,"model",l)]);else throw console.warn("Malformed class definition.",this),Error(`Unable to load model: ${e}. Please report this bug at https://github.com/xenova/transformers.js/issues/new/choose.`);return new this(...a)}async _call(e){return await this.forward(e)}async forward(e){return await tW(this,e)}_get_logits_processor(e,t,r=null){let n=new tv;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&n.push(new tB(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&n.push(new tI(e.no_repeat_ngram_size)),null!==e.forced_bos_token_id&&n.push(new tE(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&n.push(new tz(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]),n.push(new tT(e.begin_suppress_tokens,r))}return null!==e.forced_decoder_ids&&n.push(new tA(e.forced_decoder_ids)),null!==r&&n.extend(r),n}_get_generation_config(e){let t=new tS;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:n=null}={}){let s;if(!(e instanceof en)&&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)s=0;else if(0===(s=e instanceof en?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 tv,r=this._get_logits_processor(t,s,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=tC.getSampler(t),h=this.getStartBeams(e,i,n);for(;h.some(e=>!e.done)&&i=t.max_length){n.done=!0,e.push(n);continue}let s=await this.runBeam(n);t.output_attentions&&this.addAttentionsToBeam(n,s),t.output_scores;let i=s.logits.slice(null,-1,null);for(let[t,s]of(r(n.output_token_ids,i),l(i))){let r={...n};this.updateBeam(r,t),r.score+=s,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 n in e)if(n.startsWith("present")){let s=n.replace("present","past_key_values");t&&n.includes("encoder")?r[s]=t[s]:r[s]=e[n]}return r}getAttentions(e){let t=Object.create(null);for(let r of["cross_attentions","decoder_attentions"]){let n=[];for(let t in e)if(t.startsWith(r)){let r=t.split(".").pop();n[r]=e[t]}t[r]=n}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 r=Array.from({length:this.config.decoder_layers},(t,r)=>eh(e.map(e=>e[r]),2)),s=function(e,t=0){return eh(e.map(e=>e.unsqueeze(t)),t)}(t.map(([e,t])=>r[e].slice(null,t))),[i,o]=function(e,t=null,r=1,n=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0),n=t/e.data.length,s=Math.sqrt(e.data.reduce((e,t)=>e+(t-n)**2,0)/(e.data.length-r)),i=new en(e.type,[n],[]),o=new en(e.type,[s],[]);return[o,i]}t=el(t,e.dims.length);let s=ec(e,t,n),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;--s){let r=e.dims[s];if(s!==t){let e=o%r;n+=e*a,a*=i[s]}o=Math.floor(o/r)}o[n]+=(e.data[r]-s.data[n])**2}for(let n=0;n0||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),a=f([1],Array.from({length:n.length-1},(e,t)=>n[t+1]-n[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(rW)o=async e=>{let t=await e.metadata(),r=t.channels,{data:n,info:s}=await e.raw().toBuffer({resolveWithObject:!0}),i=new rX(new Uint8ClampedArray(n),s.width,s.height,s.channels);return void 0!==r&&r!==s.channels&&i.convert(r),i};else throw Error("Unable to load image processing library.");let rH={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"};class rX{constructor(e,t,r,n){this._update(e,t,r,n)}static async read(e){if(e instanceof rX)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 G(e),r=await t.blob();return this.fromBlob(r)}static async fromBlob(e){if(rK){let t=await o(e),r=s(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=rW(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,n>=0?h=n:u=-n,a.drawImage(o,l,h,e,t,c,u,e,t),new rX(a.getImageData(0,0,e,t).data,e,t,4).convert(i)}{let s=rW(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}});if(r>=0&&n>=0)s=s.extract({left:Math.floor(r),top:Math.floor(n),width:e,height:t});else if(r<=0&&n<=0){let i=Math.floor(-n),o=Math.floor(-r);s=s.extend({top:i,left:o,right:e-this.width-o,bottom:t-this.height-i})}else{let i=[0,0],o=0;n<0?(i[0]=Math.floor(-n),i[1]=t-this.height-i[0]):o=Math.floor(n);let a=[0,0],l=0;r<0?(a[0]=Math.floor(-r),a[1]=e-this.width-a[0]):l=Math.floor(r),s=s.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(s)}}toCanvas(){let e=this.clone().rgba(),t=s(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,n=null){return this.data=e,this.width=t,this.height=r,null!==n&&(this.channels=n),this}clone(){return new rX(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,t="image/png"){if(!O.useFS)throw Error("Unable to save the image because filesystem is disabled in this environment.");let r=this.toCanvas(),n=r.toBuffer(t);p.writeFileSync(e,n)}}async function rV(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/tutorials/node-audio-processing.");let n=await (await G(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let i=await s.decodeAudioData(n);if(2===i.numberOfChannels){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);r=new Float32Array(t.length);for(let s=0;sthis.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 rZ extends rY{}class rQ extends rY{}class r0 extends rY{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64];return t.pixel_mask=new en("int64",new BigInt64Array(r.reduce((e,t)=>e*t)).fill(1n),r),t}center_to_corners_format([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}post_process_object_detection(e,t=.5,r=null){let n=e.logits,s=e.pred_boxes,[i,o,a]=n.dims;if(null!==r&&r.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let l=[];for(let e=0;et){let t=u[e].data;t=this.center_to_corners_format(t),null!==i&&(t=t.map((e,t)=>e*i[(t+1)%2])),h.boxes.push(t),h.classes.push(n),h.scores.push(s)}}l.push(h)}return l}remove_low_and_no_objects(e,t,r,n){let s=[],i=[],o=[];for(let a=0;ar&&(s.push(h),i.push(u),o.push(c))}return[s,i,o]}check_segment_validity(e,t,r,n=.5,s=.8){let i=[],o=0,a=0;for(let s=0;s=n&&++a;let l=o>0&&a>0;return l&&(l=o/a>s),[l,i]}compute_segments(e,t,r,n,s,i=null,o=null){let[a,l]=o??e[0].dims,h=new en("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:n=0,binarize:s=!0,pad_size:i=null}={}){let o=[],a=[(i=i??this.pad_size).height,i.width];for(let i=0;ie>n),t.dims)),t.dims=[1,...t.dims],u.push(t)}let d=eh(u);o.push(d)}return o}}class r2 extends rJ{constructor(e){super(e),this.config.mel_filters??=function(e,t,r=128){r=Math.floor(r);let n=Math.floor(1+t/2),s=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),n=Math.floor(e/2)+1,s=Array(n);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,n=Math.sqrt(m**2+g**2)**t,s=t*Math.atan2(g,m),i=2*e;l[i]=n*Math.cos(s),l[i+1]=n*Math.sin(s),h[i]=l[i],h[i+1]=-l[i+1]}let y=l.subarray(n,s),w=new Q(i>>1);w.transform(d,h);for(let r=0;r>1,i=s[n]*t[n];c[e]=i*y[e],c[r]=i*y[r]}w.transform(f,c);for(let e=0;en?i-n: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 en("float32",r.data,[1,...r.dims])}}}class r3 extends h{constructor(e){super(),this.feature_extractor=e}async _call(e){return await this.feature_extractor(e)}}class r6 extends r3{async _call(e,t){return await this.feature_extractor(e,t)}post_process_masks(...e){return this.feature_extractor.post_process_masks(...e)}}class r4 extends r3{async _call(e){return await this.feature_extractor(e)}}class r5{static FEATURE_EXTRACTOR_CLASS_MAPPING={WhisperFeatureExtractor:r2,ViTFeatureExtractor:rZ,MobileViTFeatureExtractor:rQ,DetrFeatureExtractor:r0,SamImageProcessor:r1};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:r4,SamProcessor:r6};static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:i="main"}={}){let o=r??await H(e,"preprocessor_config.json",!0,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,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=rY;else throw Error(`Unknown Feature Extractor type: ${o.feature_extractor_type}`)}let h=this.PROCESSOR_CLASS_MAPPING[o.processor_class]??r3,c=new l(o);return new h(c)}}async function r8(e){return Array.isArray(e)||(e=[e]),e=await Promise.all(e.map(e=>rX.read(e)))}class r7 extends h{constructor(e,t,r){super(),this.task=e,this.tokenizer=t,this.model=r}async dispose(){await this.model.dispose()}async _call(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(t);return[t,r]}}class r9 extends r7{_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 n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let s={padding:!0,truncation:!0};r=this instanceof ne&&"_build_translation_inputs"in this.tokenizer?this.tokenizer._build_translation_inputs(e,s,t).input_ids:this.tokenizer(e,s).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 ne extends r9{_key="translation_text"}let nt={"text-classification":{tokenizer:ty,pipeline:class extends r7{async _call(e,{topk:t=1}={}){let[r,n]=await super._call(e),s=this.model.config.id2label,i=[];for(let e of n.logits){let r=Y(J(e.data),t).map(function(e){return{label:s[e[0]],score:e[1]}});1===t?i.push(...r):i.push(r)}return Array.isArray(e)||1===t?i:i[0]}},model:rj,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:ty,pipeline:class extends r7{async _call(e,{ignore_labels:t=["O"]}={}){let r=Array.isArray(e);r||(e=[e]);let n=this.tokenizer,[s,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(J(s.start_logits[e].data)).map((e,t)=>[e,t]).filter(e=>e[1]>o),Array.from(J(s.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:s.model.vocab[e[0]],sequence:s.decode(t,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}},model:class extends rv{static MODEL_CLASS_MAPPINGS=[rB]},default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:ty,pipeline:class extends r9{_key="summary_text"},model:rN,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:ty,pipeline:ne,model:rN,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:ty,pipeline:r9,model:rN,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:ty,pipeline:class extends r7{async _call(e,t={}){let r="string"==typeof e||e instanceof String;r&&(e=[e]),this.tokenizer.padding_side="left";let n=this.tokenizer(e,{padding:!0,truncation:!0}),s=n.input_ids,i=n.attention_mask,o=await this.model.generate(s,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,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:n=!1}={}){let s=Array.isArray(e);s||(e=[e]),Array.isArray(t)||(t=[t]);let i=t.map(e=>r.replace("{}",e)),o=n||1===t.length,a=[];for(let r of e){let e=[];for(let t of i){let n=this.tokenizer(r,{text_pair:t,padding:!0,truncation:!0}),s=await this.model(n);o?e.push([s.logits.data[this.contradiction_id],s.logits.data[this.entailment_id]]):e.push(s.logits.data[this.entailment_id])}let n=(o?e.map(e=>J(e)[1]):J(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);a.push({sequence:r,labels:n.map(e=>t[e[1]]),scores:n.map(e=>e[0])})}return s?a:a[0]}},model:rj,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"automatic-speech-recognition":{tokenizer:ty,pipeline:class extends r7{constructor(e,t,r,n){super(e,t,r),this.processor=n}async _preprocess(e,t){return c(e)&&(e=await rV(e,t)),e}async _call(e,t={}){let r=t.return_timestamps??!1,n=t.chunk_length_s??0,s=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=[];for(let a of e){a=await this._preprocess(a,c);let e=[];if(n>0){if(null===s)s=n/6;else if(n<=s)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let t=c*n,r=c*s,i=t-2*r,o=0;for(;o=a.length;e.push({stride:[n.length,l?0:r,h?0:r],input_features:s.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 n of e){let e=await this.model.generate(n.input_features,t);"word"===r?(n.tokens=e.sequences[0],n.token_timestamps=e.token_timestamps.tolist()[0].map(e=>et(e,2))):n.tokens=e[0],n.stride=n.stride.map(e=>e/c),null!==i&&i(n)}let[l,h]=this.tokenizer._decode_asr(e,{time_precision:u,return_timestamps:r,force_full_sequences:o});f.push({text:l,...h})}return h?f[0]:f}},model:rN,processor:r5,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"image-to-text":{tokenizer:ty,pipeline:class extends r7{constructor(e,t,r,n){super(e,t,r),this.processor=n}async _call(e,t={}){let r=Array.isArray(e);e=await r8(e);let{pixel_values:n}=await this.processor(e),s=[];for(let e of n){e.dims=[1,...e.dims];let r=await this.model.generate(e,t),n=this.tokenizer.batch_decode(r,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));s.push(n)}return r?s:s[0]}},model:class extends rv{static MODEL_CLASS_MAPPINGS=[rC]},processor:r5,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:class extends r7{constructor(e,t,r){super(e,null,t),this.processor=r}async _call(e,{topk:t=1}={}){let r=Array.isArray(e);e=await r8(e);let{pixel_values:n}=await this.processor(e),s=await this.model({pixel_values:n}),i=this.model.config.id2label,o=[];for(let e of s.logits){let r=Y(J(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 rv{static MODEL_CLASS_MAPPINGS=[rP]},processor:r5,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:class extends r7{constructor(e,t,r){super(e,null,t),this.processor=r,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:n=.8,label_ids_to_fuse:s=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 r8(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,n,s,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(s,{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=J(e.data);l.push([...r].map((e,r)=>({score:e,label:t[r]})))}return n?l:l[0]}},model:rR,processor:r5,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:class extends r7{constructor(e,t,r){super(e,null,t),this.processor=r}async _call(e,{threshold:t=.9,percentage:r=!1}={}){let n=Array.isArray(e);if(n&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");e=await r8(e);let s=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,s),h=this.model.config.id2label,c=l.map(e=>e.boxes.map((t,n)=>({score:e.scores[n],label:h[e.classes[n]],box:this._get_bounding_box(t,!r)})));return n?c:c[0]}_get_bounding_box(e,t){t&&(e=e.map(e=>0|e));let[r,n,s,i]=e;return{xmin:r,ymin:n,xmax:s,ymax:i}}},model:class extends rv{static MODEL_CLASS_MAPPINGS=[rU]},processor:r5,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"feature-extraction":{tokenizer:ty,pipeline:class extends r7{async _call(e,{pooling:t="none",normalize:r=!1}={}){let[n,s]=await super._call(e),i=s.last_hidden_state??s.logits;if("none"===t);else if("mean"===t)i=function(e,t){let r=[e.dims[0],e.dims[2]],n=new e.data.constructor(r[0]*r[1]),[s,i,o]=e.dims,a=0;for(let r=0;r