(()=>{var e,t,n={"?2ce3": /*!**********************************!*\ !*** onnxruntime-node (ignored) ***! \**********************************/()=>{},"?9c66": /*!****************************************!*\ !*** onnxruntime-web/webgpu (ignored) ***! \****************************************/()=>{},"?7a2c": /*!********************!*\ !*** fs (ignored) ***! \********************/()=>{},"?a42a": /*!**********************!*\ !*** path (ignored) ***! \**********************/()=>{},"?2b25": /*!***********************!*\ !*** sharp (ignored) ***! \***********************/()=>{},"?569f": /*!********************!*\ !*** fs (ignored) ***! \********************/()=>{},"?3f59": /*!**********************!*\ !*** path (ignored) ***! \**********************/()=>{},"?154a": /*!*********************!*\ !*** url (ignored) ***! \*********************/()=>{},"./node_modules/@huggingface/jinja/dist/index.js": /*!*******************************************************!*\ !*** ./node_modules/@huggingface/jinja/dist/index.js ***! \*******************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{Environment:()=>X,Interpreter:()=>Q,Template:()=>Y,parse:()=>L,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),r=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,true:s.BooleanLiteral,false:s.BooleanLiteral}),o=class{constructor(e,t){this.value=e,this.type=t}};function i(e){return/\w/.test(e)}function a(e){return/[0-9]/.test(e)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const n=[],d=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(e,t);let u=0;const h=e=>{let t="";for(;e(d[u]);)if("\\"!==d[u]){if(t+=d[u++],u>=d.length)throw new SyntaxError("Unexpected end of input")}else{if(++u,u>=d.length)throw new SyntaxError("Unexpected end of input");const e=d[u++],n=c.get(e);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=n}return t};e:for(;u0){n.push(new o(e,s.Text));continue}}h((e=>/\s/.test(e)));const t=d[u];if("-"===t||"+"===t){const e=n.at(-1)?.type;if(e===s.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++u;const e=h(a);n.push(new o(`${t}${e}`,e.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(u,u+e.length)===e){n.push(new o(e,t)),u+=e.length;continue e}}if("'"!==t&&'"'!==t)if(a(t)){const e=h(a);n.push(new o(e,s.NumericLiteral))}else{if(!i(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=h(i),t=Object.hasOwn(r,e)?r[e]:s.Identifier;t===s.In&&n.at(-1)?.type===s.Not?(n.pop(),n.push(new o("not in",s.NotIn))):n.push(new o(e,t))}}else{++u;const e=h((e=>e!==t));n.push(new o(e,s.StringLiteral)),++u}}return n}var u=class{type="Statement"},h=class extends u{constructor(e){super(),this.body=e}type="Program"},p=class extends u{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type="If"},_=class extends u{constructor(e,t,n){super(),this.loopvar=e,this.iterable=t,this.body=n}type="For"},m=class extends u{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},f=class extends u{type="Expression"},g=class extends f{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type="MemberExpression"},w=class extends f{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},y=class extends f{constructor(e){super(),this.value=e}type="Identifier"},M=class extends f{constructor(e){super(),this.value=e}type="Literal"},b=class extends M{type="NumericLiteral"},x=class extends M{type="StringLiteral"},k=class extends M{type="BooleanLiteral"},T=class extends M{type="ArrayLiteral"},v=class extends M{type="TupleLiteral"},C=class extends M{type="ObjectLiteral"},F=class extends f{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type="BinaryExpression"},P=class extends f{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},S=class extends f{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type="TestExpression"},A=class extends f{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},E=class extends f{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type="SliceExpression"},z=class extends f{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function L(e){const t=new h([]);let n=0;function r(t,s){const r=e[n++];if(!r||r.type!==t)throw new Error(`Parser Error: ${s}. ${r.type} !== ${t}.`);return r}function o(){switch(e[n].type){case s.Text:return new x(r(s.Text,"Expected text token").value);case s.OpenStatement:return function(){let t;switch(r(s.OpenStatement,"Expected opening statement token"),e[n].type){case s.Set:++n,t=l(),r(s.CloseStatement,"Expected closing statement token");break;case s.If:++n,t=c(),r(s.OpenStatement,"Expected {% token"),r(s.EndIf,"Expected endif token"),r(s.CloseStatement,"Expected %} token");break;case s.For:++n,t=function(){const e=d(!0);if(!(e instanceof y||e instanceof v))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);r(s.In,"Expected `in` keyword following loop variable");const t=u();r(s.CloseStatement,"Expected closing statement token");const n=[];for(;i(s.OpenStatement,s.EndFor);)n.push(o());return new _(e,t,n)}(),r(s.OpenStatement,"Expected {% token"),r(s.EndFor,"Expected endfor token"),r(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}();case s.OpenExpression:return function(){r(s.OpenExpression,"Expected opening expression token");const e=u();return r(s.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function i(...t){return n+t.length<=e.length&&t.some(((t,s)=>t!==e[n+s].type))}function a(...t){return n+t.length<=e.length&&t.every(((t,s)=>t===e[n+s].type))}function l(){const e=u();if(a(s.Equals)){++n;const t=l();return new m(e,t)}return e}function c(){const t=u();r(s.CloseStatement,"Expected closing statement token");const i=[],l=[];for(;e[n]?.type!==s.OpenStatement||e[n+1]?.type!==s.ElseIf&&e[n+1]?.type!==s.Else&&e[n+1]?.type!==s.EndIf;)i.push(o());if(e[n]?.type===s.OpenStatement&&e[n+1]?.type!==s.EndIf)if(++n,a(s.ElseIf))r(s.ElseIf,"Expected elseif token"),l.push(c());else for(r(s.Else,"Expected else token"),r(s.CloseStatement,"Expected closing statement token");e[n]?.type!==s.OpenStatement||e[n+1]?.type!==s.EndIf;)l.push(o());return new p(t,i,l)}function d(e=!1){const t=e?R:u,r=[t()],o=a(s.Comma);for(;o&&(++n,r.push(t()),a(s.Comma)););return o?new v(r):r[0]}function u(){return function(){const e=f();if(a(s.If)){++n;const t=f();r(s.Else,"Expected else token");const o=f();return new p(t,[e],[o])}return e}()}function f(){let t=M();for(;a(s.Or);){const s=e[n];++n;const r=M();t=new F(s,t,r)}return t}function M(){let t=L();for(;a(s.And);){const s=e[n];++n;const r=L();t=new F(s,t,r)}return t}function L(){let t;for(;a(s.Not);){const s=e[n];++n;const r=L();t=new A(s,r)}return t??function(){let t=I();for(;a(s.ComparisonBinaryOperator)||a(s.In)||a(s.NotIn);){const s=e[n];++n;const r=I();t=new F(s,t,r)}return t}()}function I(){let t=N();for(;a(s.AdditiveBinaryOperator);){const s=e[n];++n;const r=N();t=new F(s,t,r)}return t}function B(){const t=function(){let t=R();for(;a(s.Dot)||a(s.OpenSquareBracket);){const o=e[n];let i;++n;const a=o.type!==s.Dot;if(a)i=j(),r(s.CloseSquareBracket,"Expected closing square bracket");else if(i=R(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");t=new g(t,i,a)}return t}();return a(s.OpenParen)?O(t):t}function O(e){let t=new w(e,function(){r(s.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!a(s.CloseParen);){let t=u();if(a(s.Equals)){if(++n,!(t instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const e=u();t=new z(t,e)}e.push(t),a(s.Comma)&&++n}return e}();return r(s.CloseParen,"Expected closing parenthesis for arguments list"),e}());return a(s.OpenParen)&&(t=O(t)),t}function j(){const e=[];let t=!1;for(;!a(s.CloseSquareBracket);)a(s.Colon)?(e.push(void 0),++n,t=!0):(e.push(u()),a(s.Colon)&&(++n,t=!0));if(0===e.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new E(...e)}return e[0]}function N(){let t=D();for(;a(s.MultiplicativeBinaryOperator);){const s=e[n];++n;const r=D();t=new F(s,t,r)}return t}function D(){let e=function(){let e=B();for(;a(s.Pipe);){++n;let t=R();if(!(t instanceof y))throw new SyntaxError("Expected identifier for the filter");a(s.OpenParen)&&(t=O(t)),e=new P(e,t)}return e}();for(;a(s.Is);){++n;const t=a(s.Not);t&&++n;let r=R();if(r instanceof k&&(r=new y(r.value.toString())),!(r instanceof y))throw new SyntaxError("Expected identifier for the test");e=new S(e,t,r)}return e}function R(){const t=e[n];switch(t.type){case s.NumericLiteral:return++n,new b(Number(t.value));case s.StringLiteral:return++n,new x(t.value);case s.BooleanLiteral:return++n,new k("true"===t.value);case s.Identifier:return++n,new y(t.value);case s.OpenParen:{++n;const t=d();if(e[n].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`);return++n,t}case s.OpenSquareBracket:{++n;const e=[];for(;!a(s.CloseSquareBracket);)e.push(u()),a(s.Comma)&&++n;return++n,new T(e)}case s.OpenCurlyBracket:{++n;const e=new Map;for(;!a(s.CloseCurlyBracket);){const t=u();r(s.Colon,"Expected colon between key and value in object literal");const o=u();e.set(t,o),a(s.Comma)&&++n}return++n,new C(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;n=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));const o=[];for(let i=t;r*ie.toUpperCase()))}var j=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new R(!!this.value)}},N=class extends j{type="NumericValue"},D=class extends j{type="StringValue";builtins=new Map([["upper",new U((()=>new D(this.value.toUpperCase())))],["lower",new U((()=>new D(this.value.toLowerCase())))],["strip",new U((()=>new D(this.value.trim())))],["title",new U((()=>new D(O(this.value))))],["length",new N(this.value.length)]])},R=class extends j{type="BooleanValue"},V=class extends j{type="ObjectValue";__bool__(){return new R(this.value.size>0)}builtins=new Map([["get",new U((([e,t])=>{if(!(e instanceof D))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new $}))],["items",new U((()=>new G(Array.from(this.value.entries()).map((([e,t])=>new G([new D(e),t]))))))]])},G=class extends j{type="ArrayValue";builtins=new Map([["length",new N(this.value.length)]]);__bool__(){return new R(this.value.length>0)}},q=class extends G{type="TupleValue"},U=class extends j{type="FunctionValue"},$=class extends j{type="NullValue"},W=class extends j{type="UndefinedValue"},X=class{constructor(e){this.parent=e}variables=new Map([["namespace",new U((e=>{if(0===e.length)return new V(new Map);if(1!==e.length||!(e[0]instanceof V))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]}))]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof U],["odd",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!=0}],["even",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>e instanceof G||e instanceof D],["lower",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,H(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new W}catch{return new W}}},Q=class{global;constructor(e){this.global=e??new X}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const s=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new R(n.value==s.value);case"!=":return new R(n.value!=s.value)}if(n instanceof W||s instanceof W)throw new Error("Cannot perform operation on undefined values");if(n instanceof $||s instanceof $)throw new Error("Cannot perform operation on null values");if(n instanceof N&&s instanceof N)switch(e.operator.value){case"+":return new N(n.value+s.value);case"-":return new N(n.value-s.value);case"*":return new N(n.value*s.value);case"/":return new N(n.value/s.value);case"%":return new N(n.value%s.value);case"<":return new R(n.value":return new R(n.value>s.value);case">=":return new R(n.value>=s.value);case"<=":return new R(n.value<=s.value)}else if(n instanceof G&&s instanceof G){if("+"===e.operator.value)return new G(n.value.concat(s.value))}else if(s instanceof G){const t=void 0!==s.value.find((e=>e.value===n.value));switch(e.operator.value){case"in":return new R(t);case"not in":return new R(!t)}}if((n instanceof D||s instanceof D)&&"+"===e.operator.value)return new D(n.value.toString()+s.value.toString());if(n instanceof D&&s instanceof D)switch(e.operator.value){case"in":return new R(s.value.includes(n.value));case"not in":return new R(!s.value.includes(n.value))}if(n instanceof D&&s instanceof V)switch(e.operator.value){case"in":return new R(s.value.has(n.value));case"not in":return new R(!s.value.has(n.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${s.type}`)}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if(n instanceof G)switch(t.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new N(n.value.length);case"reverse":return new G(n.value.reverse());case"sort":return new G(n.value.sort(((e,t)=>{if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}else if(n instanceof D)switch(t.value){case"length":return new N(n.value.length);case"upper":return new D(n.value.toUpperCase());case"lower":return new D(n.value.toLowerCase());case"title":return new D(O(n.value));case"capitalize":return new D(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new D(n.value.trim());default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(n instanceof N){if("abs"===t.value)return new N(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(n instanceof V)switch(t.value){case"items":return new G(Array.from(n.value.entries()).map((([e,t])=>new G([new D(e),t]))));case"length":return new N(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${n.type}`)}if("CallExpression"===e.filter.type){const s=e.filter;if("Identifier"!==s.callee.type)throw new Error(`Unknown filter: ${s.callee.type}`);const r=s.callee.value;if(n instanceof G){if("selectattr"===r){if(n.value.some((e=>!(e instanceof V))))throw new Error("`selectattr` can only be applied to array of objects");if(s.args.some((e=>"StringLiteral"!==e.type)))throw new Error("arguments of `selectattr` must be strings");const[e,r,o]=s.args.map((e=>this.evaluate(e,t)));let i;if(r){const e=t.tests.get(r.value);if(!e)throw new Error(`Unknown test: ${r.value}`);i=e}else i=(...e)=>e[0].__bool__().value;const a=n.value.filter((t=>{const n=t.value.get(e.value);return!!n&&i(n,o)}));return new G(a)}throw new Error(`Unknown ArrayValue filter: ${r}`)}throw new Error(`Cannot apply filter "${r}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const r=s(n);return new R(e.negate?!r:r)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);if("not"===e.operator.value)return new R(!n.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const s of e){const e=this.evaluate(s,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(n+=e.value)}return new D(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const n=[],s=new Map;for(const r of e.args)if("KeywordArgumentExpression"===r.type){const e=r;s.set(e.key.value,this.evaluate(e.value,t))}else n.push(this.evaluate(r,t));s.size>0&&n.push(new V(s));const r=this.evaluate(e.callee,t);if("FunctionValue"!==r.type)throw new Error(`Cannot call something that is not a function: got ${r.type}`);return r.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof G||e instanceof D))throw new Error("Slice object must be an array or string");const s=this.evaluate(t.start,n),r=this.evaluate(t.stop,n),o=this.evaluate(t.step,n);if(!(s instanceof N||s instanceof W))throw new Error("Slice start must be numeric or undefined");if(!(r instanceof N||r instanceof W))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof N||o instanceof W))throw new Error("Slice step must be numeric or undefined");return e instanceof G?new G(B(e.value,s.value,r.value,o.value)):new D(B(Array.from(e.value),s.value,r.value,o.value).join(""))}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let s,r;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(n,e.property,t);s=this.evaluate(e.property,t)}else s=new D(e.property.value);if(n instanceof V){if(!(s instanceof D))throw new Error(`Cannot access property with non-string: got ${s.type}`);r=n.value.get(s.value)??n.builtins.get(s.value)}else if(n instanceof G||n instanceof D)if(s instanceof N)r=n.value.at(s.value),n instanceof D&&(r=new D(n.value.at(s.value)));else{if(!(s instanceof D))throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);r=n.builtins.get(s.value)}else{if(!(s instanceof D))throw new Error(`Cannot access property with non-string: got ${s.type}`);r=n.builtins.get(s.value)}return r instanceof j?r:new W}evaluateSet(e,t){const n=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const s=e.assignee.value;t.setVariable(s,n)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const s=e.assignee,r=this.evaluate(s.object,t);if(!(r instanceof V))throw new Error("Cannot assign to member of non-object");if("Identifier"!==s.property.type)throw new Error("Cannot assign to member with non-identifier property");r.value.set(s.property.value,n)}}return new $}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new X(t),s=this.evaluate(e.iterable,n);if(!(s instanceof G))throw new Error(`Expected iterable type in for loop: got ${s.type}`);let r="";for(let t=0;t0?s.value[t-1]:new W],["nextitem",ts.value.length?"few":"many"} items to unpack`);for(let e=0;ethis.evaluate(e,t))));case"TupleLiteral":return new q(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const n=new Map;for(const[s,r]of e.value){const e=this.evaluate(s,t);if(!(e instanceof D))throw new Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(r,t))}return new V(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function H(e){switch(typeof e){case"number":return new N(e);case"string":return new D(e);case"boolean":return new R(e);case"object":return null===e?new $:Array.isArray(e)?new G(e.map(H)):new V(new Map(Object.entries(e).map((([e,t])=>[e,H(t)]))));case"function":return new U(((t,n)=>H(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Y=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=L(t)}render(e){const t=new X;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",I);for(const[n,s]of Object.entries(e))t.set(n,s);return new Q(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js": /*!******************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***! \******************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{registerBackend:()=>o,resolveBackend:()=>i});const s=new Map,r=[],o=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{const o=s.get(e);if(void 0===o)s.set(e,{backend:t,priority:n});else{if(o.priority>n)return;if(o.priority===n&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){const t=r.indexOf(e);-1!==t&&r.splice(t,1);for(let t=0;t{const t=0===e.length?r:e,n=[];for(const e of t){const t=s.get(e);if(t){if(t.initialized)return t.backend;if(t.aborted)continue;const s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(r){s||n.push({name:e,err:r}),t.aborted=!0}finally{delete t.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`)}},"./node_modules/onnxruntime-common/dist/esm/backend.js": /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend.js ***! \*************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{registerBackend:()=>s.registerBackend});var s=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js": /*!**************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env-impl.js ***! \**************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{env:()=>o});var s=n(/*! ./version.js */"./node_modules/onnxruntime-common/dist/esm/version.js");let r="warning";const o={wasm:{},webgl:{},webgpu:{},versions:{common:s.version},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);r=e}},get logLevel(){return r}};Object.defineProperty(o,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js": /*!*********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env.js ***! \*********************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{env:()=>s});const s=n(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js").env},"./node_modules/onnxruntime-common/dist/esm/index.js": /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/index.js ***! \***********************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{InferenceSession:()=>o.InferenceSession,TRACE:()=>a.TRACE,TRACE_FUNC_BEGIN:()=>a.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>a.TRACE_FUNC_END,Tensor:()=>i.Tensor,TrainingSession:()=>l.TrainingSession,env:()=>r.env,registerBackend:()=>s.registerBackend});var s=n(/*! ./backend.js */"./node_modules/onnxruntime-common/dist/esm/backend.js"),r=n(/*! ./env.js */"./node_modules/onnxruntime-common/dist/esm/env.js"),o=n(/*! ./inference-session.js */"./node_modules/onnxruntime-common/dist/esm/inference-session.js"),i=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),a=n(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js"),l=(n(/*! ./onnx-value.js */"./node_modules/onnxruntime-common/dist/esm/onnx-value.js"),n(/*! ./training-session.js */"./node_modules/onnxruntime-common/dist/esm/training-session.js"))},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js": /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js ***! \****************************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{InferenceSession:()=>i});var s=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),r=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),o=n(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js");class i{constructor(e){this.handler=e}async run(e,t,n){(0,o.TRACE_FUNC_BEGIN)();const s={};let i={};if("object"!=typeof e||null===e||e instanceof r.Tensor||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof r.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(const e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);s[e]=null}if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else{let e=!1;const o=Object.getOwnPropertyNames(t);for(const n of this.outputNames)if(-1!==o.indexOf(n)){const o=t[n];(null===o||o instanceof r.Tensor)&&(e=!0,a=!1,s[n]=o)}if(e){if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else i=t}}else if(void 0!==t)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of this.inputNames)if(void 0===e[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(a)for(const e of this.outputNames)s[e]=null;const l=await this.handler.run(e,s,i),c={};for(const e in l)if(Object.hasOwnProperty.call(l,e)){const t=l[e];t instanceof r.Tensor?c[e]=t:c[e]=new r.Tensor(t.type,t.data,t.dims)}return(0,o.TRACE_FUNC_END)(),c}async release(){return this.handler.dispose()}static async create(e,t,n,r){let a;(0,o.TRACE_FUNC_BEGIN)();let l={};if("string"==typeof e){if(a=e,"object"==typeof t&&null!==t)l=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(a=e,"object"==typeof t&&null!==t)l=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else{if(!(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{const s=e;let o=0,i=e.byteLength;if("object"==typeof t&&null!==t)l=t;else if("number"==typeof t){if(o=t,!Number.isSafeInteger(o))throw new RangeError("'byteOffset' must be an integer.");if(o<0||o>=s.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${s.byteLength}).`);if(i=e.byteLength-o,"number"==typeof n){if(i=n,!Number.isSafeInteger(i))throw new RangeError("'byteLength' must be an integer.");if(i<=0||o+i>s.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${s.byteLength-o}].`);if("object"==typeof r&&null!==r)l=r;else if(void 0!==r)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");a=new Uint8Array(s,o,i)}}const c=(l.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),d=await(0,s.resolveBackend)(c),u=await d.createInferenceSessionHandler(a,l);return(0,o.TRACE_FUNC_END)(),new i(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js": /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session.js ***! \***********************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{InferenceSession:()=>s});const s=n(/*! ./inference-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js").InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js": /*!****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/onnx-value.js ***! \****************************************************************/(e,t,n)=>{"use strict";n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js": /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js ***! \****************************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{tensorToDataURL:()=>s,tensorToImageData:()=>r});const s=(e,t)=>{const n="undefined"!=typeof document?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];const s=n.getContext("2d");if(null!=s){let r,o;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],o=e.dims[3]):(r=e.dims[3],o=e.dims[2]);const i=void 0!==t?.format?t.format:"RGB",a=t?.norm;let l,c;void 0===a||void 0===a.mean?l=[255,255,255,255]:"number"==typeof a.mean?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],void 0!==a.mean[3]&&(l[3]=a.mean[3])),void 0===a||void 0===a.bias?c=[0,0,0,0]:"number"==typeof a.bias?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],void 0!==a.bias[3]&&(c[3]=a.bias[3]));const d=o*r;let u=0,h=d,p=2*d,_=-1;"RGBA"===i?(u=0,h=d,p=2*d,_=3*d):"RGB"===i?(u=0,h=d,p=2*d):"RBG"===i&&(u=0,p=d,h=2*d);for(let t=0;t{const n="undefined"!=typeof document?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(null==n)throw new Error("Can not access image data");{let r,o,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],o=e.dims[1],i=e.dims[3]):(r=e.dims[3],o=e.dims[2],i=e.dims[1]);const a=void 0!==t&&void 0!==t.format?t.format:"RGB",l=t?.norm;let c,d;void 0===l||void 0===l.mean?c=[255,255,255,255]:"number"==typeof l.mean?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],void 0!==l.mean[3]&&(c[3]=l.mean[3])),void 0===l||void 0===l.bias?d=[0,0,0,0]:"number"==typeof l.bias?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(d[3]=l.bias[3]));const u=o*r;if(void 0!==t&&(void 0!==t.format&&4===i&&"RGBA"!==t.format||3===i&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let p=0,_=1,m=2,f=3,g=0,w=u,y=2*u,M=-1;"RGBA"===a?(g=0,w=u,y=2*u,M=3*u):"RGB"===a?(g=0,w=u,y=2*u):"RBG"===a&&(g=0,y=u,w=2*u),s=n.createImageData(r,o);for(let t=0;t{"use strict";n.r(t),n.d(t,{bufferToTensor:()=>r,tensorFromGpuBuffer:()=>a,tensorFromImage:()=>o,tensorFromPinnedBuffer:()=>l,tensorFromTexture:()=>i});var s=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const r=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:r}=t,o=t.norm??{mean:255,bias:0};let i,a;i="number"==typeof o.mean?[o.mean,o.mean,o.mean,o.mean]:[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],a="number"==typeof o.bias?[o.bias,o.bias,o.bias,o.bias]:[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const l=void 0!==t.format?t.format:"RGBA",c=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",d=n*r,u="RGBA"===c?new Float32Array(4*d):new Float32Array(3*d);let h=4,p=0,_=1,m=2,f=3,g=0,w=d,y=2*d,M=-1;"RGB"===l&&(h=3,p=0,_=1,m=2,f=-1),"RGBA"===c?M=3*d:"RBG"===c?(g=0,y=d,w=2*d):"BGR"===c&&(y=0,w=d,g=2*d);for(let t=0;t{const n="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,s="undefined"!=typeof ImageData&&e instanceof ImageData,o="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,i="string"==typeof e;let a,l=t??{};const c=()=>{if("undefined"!=typeof document)return document.createElement("canvas");if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=e=>e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(n){const n=c();n.width=e.width,n.height=e.height;const s=d(n);if(null==s)throw new Error("Can not access image data");{let n=e.height,r=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(n=t.resizedHeight,r=t.resizedWidth),void 0!==t){if(l=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=n,l.width=r}else l.tensorFormat="RGBA",l.height=n,l.width=r;s.drawImage(e,0,0),a=s.getImageData(0,0,r,n).data}}else{if(!s){if(o){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");const n=c();n.width=e.width,n.height=e.height;const s=d(n);if(null!=s){const t=e.height,n=e.width;return s.drawImage(e,0,0,n,t),a=s.getImageData(0,0,n,t).data,l.height=t,l.width=n,r(a,l)}throw new Error("Can not access image data")}if(i)return new Promise(((t,n)=>{const s=c(),o=d(s);if(!e||!o)return n();const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>{s.width=i.width,s.height=i.height,o.drawImage(i,0,0,s.width,s.height);const e=o.getImageData(0,0,s.width,s.height);l.height=s.height,l.width=s.width,t(r(e.data,l))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let n,s;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(n=t.resizedHeight,s=t.resizedWidth):(n=e.height,s=e.width),void 0!==t&&(l=t),l.format="RGBA",l.height=n,l.width=s,void 0!==t){const t=c();t.width=s,t.height=n;const r=d(t);if(null==r)throw new Error("Can not access image data");r.putImageData(e,0,0),a=r.getImageData(0,0,s,n).data}else a=e.data}}if(void 0!==a)return r(a,l);throw new Error("Input data provided is not supported - aborted tensor creation")},i=(e,t)=>{const{width:n,height:r,download:o,dispose:i}=t,a=[1,r,n,4];return new s.Tensor({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},a=(e,t)=>{const{dataType:n,dims:r,download:o,dispose:i}=t;return new s.Tensor({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:o,dispose:i})},l=(e,t,n)=>new s.Tensor({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js": /*!******************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js ***! \******************************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>r,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>s,checkBigInt:()=>i});const s=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),r=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let o=!1;const i=()=>{if(!o){o=!0;const e="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from;e&&(s.set("int64",BigInt64Array),r.set(BigInt64Array,"int64")),t&&(s.set("uint64",BigUint64Array),r.set(BigUint64Array,"uint64"))}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js": /*!*****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl.js ***! \*****************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{Tensor:()=>a});var s=n(/*! ./tensor-conversion-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),r=n(/*! ./tensor-factory-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),o=n(/*! ./tensor-impl-type-mapping.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),i=n(/*! ./tensor-utils-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class a{constructor(e,t,n){let s,r;if((0,o.checkBigInt)(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,s=e.type,r=e.dims,e.location){case"cpu-pinned":{const t=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(s);if(!t)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==s)throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==s&&"float16"!==s&&"int32"!==s&&"int64"!==s&&"uint32"!==s&&"bool"!==s)throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if("string"==typeof e)if(s=e,a=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{const n=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");i="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else{if(!(t instanceof n))throw new TypeError(`A ${s} tensor's data must be type of ${n}`);i=t}}else if(a=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const t=typeof e[0];if("string"===t)s="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);s="bool",i=Uint8Array.from(e)}}else{const t=o.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=t,i=e}if(void 0===a)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");r=a,this.cpuData=i,this.dataLocation="cpu"}const a=(0,i.calculateSize)(r);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=r,this.size=a}static async fromImage(e,t){return(0,r.tensorFromImage)(e,t)}static fromTexture(e,t){return(0,r.tensorFromTexture)(e,t)}static fromGpuBuffer(e,t){return(0,r.tensorFromGpuBuffer)(e,t)}static fromPinnedBuffer(e,t,n){return(0,r.tensorFromPinnedBuffer)(e,t,n)}toDataURL(e){return(0,s.tensorToDataURL)(this,e)}toImageData(e){return(0,s.tensorToImageData)(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,i.tensorReshape)(this,e)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js": /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js ***! \***********************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{calculateSize:()=>r,tensorReshape:()=>o});var s=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const r=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new s.Tensor(e.type,e.data,t);case"cpu-pinned":return new s.Tensor({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new s.Tensor({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new s.Tensor({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js": /*!************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor.js ***! \************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{Tensor:()=>s});const s=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js").Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js": /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/trace.js ***! \***********************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{TRACE:()=>r,TRACE_FUNC_BEGIN:()=>i,TRACE_FUNC_END:()=>a});var s=n(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js");const r=(e,t)=>{s.env.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},o=(e,t)=>{const n=(new Error).stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let o=0;o{s.env.wasm.trace&&o("BEGIN",e)},a=e=>{s.env.wasm.trace&&o("END",e)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js": /*!***************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session-impl.js ***! \***************************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{TrainingSession:()=>o});var s=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),r=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js");class o{constructor(e,t,n){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,t){const n=e.evalModel||"",r=e.optimizerModel||"",i=t||{},a=(i.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),l=await(0,s.resolveBackend)(a);if(l.createTrainingSessionHandler){const t=await l.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,r,i);return new o(t,!!e.optimizerModel,!!e.evalModel)}throw new Error("Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.")}typeNarrowingForRunStep(e,t,n,s,o){const i={};let a={};if("object"!=typeof n||null===n||n instanceof r.Tensor||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if("object"==typeof s){if(null===s)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof r.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(0===s.length)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const e of s){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===t.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);i[e]=null}if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else{let e=!1;const n=Object.getOwnPropertyNames(s);for(const o of t)if(-1!==n.indexOf(o)){const t=s[o];(null===t||t instanceof r.Tensor)&&(e=!0,l=!1,i[o]=t)}if(e){if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else a=s}}else if(void 0!==s)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of e)if(void 0===n[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(l)for(const e of t)i[e]=null;return[i,a]}convertHandlerReturnTypeToMapOfTensors(e){const t={};for(const n in e)if(Object.hasOwnProperty.call(e,n)){const s=e[n];s instanceof r.Tensor?t[n]=s:t[n]=new r.Tensor(s.type,s.data,s.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,n){const[s,r]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,n),o=await this.handler.runTrainStep(e,s,r);return this.convertHandlerReturnTypeToMapOfTensors(o)}async runOptimizerStep(e){if(!this.hasOptimizerModel)throw new Error("This TrainingSession has no OptimizerModel loaded.");await this.handler.runOptimizerStep(e||{})}async runEvalStep(e,t,n){if(this.hasEvalModel){const[s,r]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,n),o=await this.handler.runEvalStep(e,s,r);return this.convertHandlerReturnTypeToMapOfTensors(o)}throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){const n=await this.getParametersSize(t);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js": /*!**********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session.js ***! \**********************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{TrainingSession:()=>s});const s=n(/*! ./training-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js").TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js": /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/version.js ***! \*************************************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{version:()=>s});const s="1.17.0"},"./src/backends/onnx.js": /*!******************************!*\ !*** ./src/backends/onnx.js ***! \******************************/(e,t,n)=>{"use strict";var s,r;n.r(t),n.d(t,{Tensor:()=>l.Tensor,createInferenceSession:()=>_,deviceToExecutionProviders:()=>p,isONNXProxy:()=>g,isONNXTensor:()=>m});var o=n(/*! ../env.js */"./src/env.js"),i=n(/*! onnxruntime-node */"?2ce3"),a=n(/*! onnxruntime-web/webgpu */"?9c66"),l=n(/*! onnxruntime-common */"./node_modules/onnxruntime-common/dist/esm/index.js");const c=[];let d,u;o.apis.IS_NODE_ENV?(u=i??(s||(s=n.t(i,2))),c.push("cpu"),d=["cpu"]):(u=r||(r=n.t(a,2)),o.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),d=["wasm"]);const h=u.InferenceSession;function p(e){let t=d;if(e){if(!c.includes(e))throw new Error(`Unsupported device: "${e}". Should be one of: ${c.join(", ")}.`);t=[e]}return t}async function _(e,t){return await h.create(e,t)}function m(e){return e instanceof u.Tensor}const f=u?.env;if(f?.wasm){f.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.3/dist/",f.wasm.proxy=!o.apis.IS_WEBWORKER_ENV,"undefined"!=typeof crossOriginIsolated&&crossOriginIsolated||(f.wasm.numThreads=1);"undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(f.wasm.simd=!1)}function g(){return f?.wasm?.proxy}o.env.backends.onnx=f},"./src/configs.js": /*!************************!*\ !*** ./src/configs.js ***! \************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{AutoConfig:()=>o,PretrainedConfig:()=>r});var s=n(/*! ./utils/hub.js */"./src/utils/hub.js");class r{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main"}={}){let a=n??await async function(e,t){return await(0,s.getModelJSON)(e,"config.json",!0,t)}(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:o,revision:i});return new this(a)}}class o{static async from_pretrained(...e){return r.from_pretrained(...e)}}},"./src/env.js": /*!********************!*\ !*** ./src/env.js ***! \********************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{apis:()=>p,env:()=>w});var s=n(/*! fs */"?569f"),r=n(/*! path */"?3f59"),o=n(/*! url */"?154a");const i="undefined"!=typeof self,a=i&&"DedicatedWorkerGlobalScope"===self.constructor.name,l=i&&"caches"in self,c="undefined"!=typeof navigator&&"gpu"in navigator,d="undefined"!=typeof process&&"node"===process?.release?.name,u=!y(s),h=!y(r),p=Object.freeze({IS_BROWSER_ENV:i,IS_WEBWORKER_ENV:a,IS_WEB_CACHE_AVAILABLE:l,IS_WEBGPU_AVAILABLE:c,IS_NODE_ENV:d,IS_FS_AVAILABLE:u,IS_PATH_AVAILABLE:h}),_=u&&h,m=_?r.dirname(r.dirname(o.fileURLToPath("file:///Users/ajr/Documents/GitHub/transformers.js/src/env.js"))):"./",f=_?r.join(m,"/.cache/"):null,g="/models/",w={version:"3.0.0-alpha.0",backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!i,localModelPath:_?r.join(m,g):g,useFS:u,useBrowserCache:l,useFSCache:u,cacheDir:f,useCustomCache:!1,customCache:null};function y(e){return 0===Object.keys(e).length}},"./src/generation/configuration_utils.js": /*!***********************************************!*\ !*** ./src/generation/configuration_utils.js ***! \***********************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{GenerationConfig:()=>r});var s=n(/*! ../utils/core.js */"./src/utils/core.js");class r{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,(0,s.pick)(e,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js": /*!******************************************!*\ !*** ./src/generation/logits_process.js ***! \******************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>m,NoBadWordsLogitsProcessor:()=>f,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>p,SuppressTokensAtBeginLogitsProcessor:()=>d,TemperatureLogitsWarper:()=>w,TopKLogitsWarper:()=>M,TopPLogitsWarper:()=>y,WhisperTimeStampLogitsProcessor:()=>u});var s=n(/*! ../utils/generic.js */"./src/utils/generic.js"),r=(n(/*! ../utils/tensor.js */"./src/utils/tensor.js"),n(/*! ../utils/maths.js */"./src/utils/maths.js"));class o extends s.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(const t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&o[o.length-1]>=this.timestamp_begin,a=o.length<2||o[o.length-2]>=this.timestamp_begin;if(i&&(a?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&null!==this.max_initial_timestamp_index){const e=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(e+1).fill(-1/0)}const l=(0,r.log_softmax)(s);Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)))>(0,r.max)(l.subarray(0,this.timestamp_begin))[0]&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class h extends o{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,n=[];for(let s=0;s1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const n=e.length,s=t.slice([0,n],null),r=t.slice([n,t.dims[0]],null);for(let e=0;e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(n)||n<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${n}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=n}}class M extends i{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:n=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,n),this.filter_value=t}}},"./src/generation/logits_sampler.js": /*!******************************************!*\ !*** ./src/generation/logits_sampler.js ***! \******************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{LogitsSampler:()=>o});var s=n(/*! ../utils/generic.js */"./src/utils/generic.js"),r=(n(/*! ../utils/tensor.js */"./src/utils/tensor.js"),n(/*! ../utils/maths.js */"./src/utils/maths.js"));n(/*! ../generation/configuration_utils.js */"./src/generation/configuration_utils.js");class o extends s.Callable{constructor(e){super(),this.generation_config=e}_call(e,t=-1){return this.sample(e,t)}sample(e,t){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let n=e.dims.at(-1),s=e.data;if(-1===t)s=s.slice(-n);else{let e=t*n;s=s.slice(e,e+n)}return s}randomSelect(e){let t=e.reduce(((e,t)=>e+t),0),n=Math.random()*t;for(let t=0;t1)return new l(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 i(e)}}class i extends o{sample(e,t=-1){let n=this.getLogits(e,t);return[[(0,r.max)(n)[1],0]]}}class a extends o{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const s=this.getLogits(e,t),o=(0,r.getTopItems)(s,n),i=(0,r.softmax)(o.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(i);return[o[e][0],Math.log(i[e])]}))}}class l extends o{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const s=this.getLogits(e,t),o=(0,r.getTopItems)(s,n),i=(0,r.softmax)(o.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},((e,t)=>[o[t][0],Math.log(i[t])]))}}},"./src/generation/stopping_criteria.js": /*!*********************************************!*\ !*** ./src/generation/stopping_criteria.js ***! \*********************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{EosTokenCriteria:()=>a,MaxLengthCriteria:()=>i,StoppingCriteria:()=>r,StoppingCriteriaList:()=>o});var s=n(/*! ../utils/generic.js */"./src/utils/generic.js");class r extends s.Callable{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class o extends s.Callable{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof o&&(e=e.criteria),this.criteria.push(...e)}_call(e,t){const n=new Array(e.length).fill(!1);for(const s of this.criteria){const r=s(e,t);for(let e=0;ee.length>=this.max_length))}}class a extends r{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map((e=>this.eos_token_id.includes(e.at(-1))))}}},"./src/generation/streamers.js": /*!*************************************!*\ !*** ./src/generation/streamers.js ***! \*************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{BaseStreamer:()=>s});class s{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}},"./src/models.js": /*!***********************!*\ !*** ./src/models.js ***! \***********************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{ASTForAudioClassification:()=>Yt,ASTModel:()=>Ht,ASTPreTrainedModel:()=>Qt,AlbertForMaskedLM:()=>ot,AlbertForQuestionAnswering:()=>rt,AlbertForSequenceClassification:()=>st,AlbertModel:()=>nt,AlbertPreTrainedModel:()=>tt,AutoModel:()=>ii,AutoModelForAudioClassification:()=>Ti,AutoModelForAudioFrameClassification:()=>Ci,AutoModelForCTC:()=>ki,AutoModelForCausalLM:()=>pi,AutoModelForDepthEstimation:()=>Ai,AutoModelForDocumentQuestionAnswering:()=>Fi,AutoModelForImageClassification:()=>gi,AutoModelForImageFeatureExtraction:()=>Ei,AutoModelForImageMatting:()=>Pi,AutoModelForImageSegmentation:()=>wi,AutoModelForImageToImage:()=>Si,AutoModelForMaskGeneration:()=>xi,AutoModelForMaskedLM:()=>_i,AutoModelForObjectDetection:()=>Mi,AutoModelForQuestionAnswering:()=>mi,AutoModelForSemanticSegmentation:()=>yi,AutoModelForSeq2SeqLM:()=>ci,AutoModelForSequenceClassification:()=>ai,AutoModelForSpeechSeq2Seq:()=>di,AutoModelForTextToSpectrogram:()=>ui,AutoModelForTextToWaveform:()=>hi,AutoModelForTokenClassification:()=>li,AutoModelForVision2Seq:()=>fi,AutoModelForXVector:()=>vi,AutoModelForZeroShotObjectDetection:()=>bi,BartForConditionalGeneration:()=>gt,BartForSequenceClassification:()=>wt,BartModel:()=>ft,BartPretrainedModel:()=>mt,BaseModelOutput:()=>j,BeitForImageClassification:()=>fs,BeitModel:()=>ms,BeitPreTrainedModel:()=>_s,BertForMaskedLM:()=>R,BertForQuestionAnswering:()=>q,BertForSequenceClassification:()=>V,BertForTokenClassification:()=>G,BertModel:()=>D,BertPreTrainedModel:()=>N,BlenderbotForConditionalGeneration:()=>Ct,BlenderbotModel:()=>vt,BlenderbotPreTrainedModel:()=>Tt,BlenderbotSmallForConditionalGeneration:()=>St,BlenderbotSmallModel:()=>Pt,BlenderbotSmallPreTrainedModel:()=>Ft,BloomForCausalLM:()=>Xn,BloomModel:()=>Wn,BloomPreTrainedModel:()=>$n,CLIPModel:()=>on,CLIPPreTrainedModel:()=>rn,CLIPSegForImageSegmentation:()=>gn,CLIPSegModel:()=>fn,CLIPSegPreTrainedModel:()=>mn,CLIPTextModelWithProjection:()=>an,CLIPVisionModelWithProjection:()=>ln,CamembertForMaskedLM:()=>he,CamembertForQuestionAnswering:()=>me,CamembertForSequenceClassification:()=>pe,CamembertForTokenClassification:()=>_e,CamembertModel:()=>ue,CamembertPreTrainedModel:()=>de,CausalLMOutput:()=>Ni,CausalLMOutputWithPast:()=>Di,ChineseCLIPModel:()=>_n,ChineseCLIPPreTrainedModel:()=>pn,ClapAudioModelWithProjection:()=>uo,ClapModel:()=>lo,ClapPreTrainedModel:()=>ao,ClapTextModelWithProjection:()=>co,CodeGenForCausalLM:()=>Bn,CodeGenModel:()=>In,CodeGenPreTrainedModel:()=>Ln,ConvBertForMaskedLM:()=>ee,ConvBertForQuestionAnswering:()=>se,ConvBertForSequenceClassification:()=>te,ConvBertForTokenClassification:()=>ne,ConvBertModel:()=>Z,ConvBertPreTrainedModel:()=>K,ConvNextForImageClassification:()=>Js,ConvNextModel:()=>Ys,ConvNextPreTrainedModel:()=>Hs,ConvNextV2ForImageClassification:()=>er,ConvNextV2Model:()=>Zs,ConvNextV2PreTrainedModel:()=>Ks,DPTForDepthEstimation:()=>Vs,DPTModel:()=>Rs,DPTPreTrainedModel:()=>Ds,DebertaForMaskedLM:()=>we,DebertaForQuestionAnswering:()=>be,DebertaForSequenceClassification:()=>ye,DebertaForTokenClassification:()=>Me,DebertaModel:()=>ge,DebertaPreTrainedModel:()=>fe,DebertaV2ForMaskedLM:()=>Te,DebertaV2ForQuestionAnswering:()=>Fe,DebertaV2ForSequenceClassification:()=>ve,DebertaV2ForTokenClassification:()=>Ce,DebertaV2Model:()=>ke,DebertaV2PreTrainedModel:()=>xe,DeiTForImageClassification:()=>Ss,DeiTModel:()=>Ps,DeiTPreTrainedModel:()=>Fs,DepthAnythingForDepthEstimation:()=>qs,DepthAnythingPreTrainedModel:()=>Gs,DetrForObjectDetection:()=>ys,DetrForSegmentation:()=>Ms,DetrModel:()=>ws,DetrObjectDetectionOutput:()=>bs,DetrPreTrainedModel:()=>gs,DetrSegmentationOutput:()=>xs,Dinov2ForImageClassification:()=>sr,Dinov2Model:()=>nr,Dinov2PreTrainedModel:()=>tr,DistilBertForMaskedLM:()=>Le,DistilBertForQuestionAnswering:()=>ze,DistilBertForSequenceClassification:()=>Ae,DistilBertForTokenClassification:()=>Ee,DistilBertModel:()=>Se,DistilBertPreTrainedModel:()=>Pe,DonutSwinModel:()=>Qs,DonutSwinPreTrainedModel:()=>Xs,EfficientNetForImageClassification:()=>ko,EfficientNetModel:()=>xo,EfficientNetPreTrainedModel:()=>bo,ElectraForMaskedLM:()=>ie,ElectraForQuestionAnswering:()=>ce,ElectraForSequenceClassification:()=>ae,ElectraForTokenClassification:()=>le,ElectraModel:()=>oe,ElectraPreTrainedModel:()=>re,EsmForMaskedLM:()=>Oe,EsmForSequenceClassification:()=>je,EsmForTokenClassification:()=>Ne,EsmModel:()=>Be,EsmPreTrainedModel:()=>Ie,FalconForCausalLM:()=>io,FalconModel:()=>oo,FalconPreTrainedModel:()=>ro,GLPNForDepthEstimation:()=>Ws,GLPNModel:()=>$s,GLPNPreTrainedModel:()=>Us,GPT2LMHeadModel:()=>Mn,GPT2Model:()=>yn,GPT2PreTrainedModel:()=>wn,GPTBigCodeForCausalLM:()=>zn,GPTBigCodeModel:()=>En,GPTBigCodePreTrainedModel:()=>An,GPTJForCausalLM:()=>Sn,GPTJModel:()=>Pn,GPTJPreTrainedModel:()=>Fn,GPTNeoForCausalLM:()=>kn,GPTNeoModel:()=>xn,GPTNeoPreTrainedModel:()=>bn,GPTNeoXForCausalLM:()=>Cn,GPTNeoXModel:()=>vn,GPTNeoXPreTrainedModel:()=>Tn,HubertForCTC:()=>jr,HubertForSequenceClassification:()=>Nr,HubertModel:()=>Or,HubertPreTrainedModel:()=>Br,ImageMattingOutput:()=>Ri,LlamaForCausalLM:()=>Nn,LlamaModel:()=>jn,LlamaPreTrainedModel:()=>On,LlavaForConditionalGeneration:()=>sn,LlavaPreTrainedModel:()=>nn,LongT5ForConditionalGeneration:()=>ut,LongT5Model:()=>dt,LongT5PreTrainedModel:()=>ct,M2M100ForConditionalGeneration:()=>fr,M2M100Model:()=>mr,M2M100PreTrainedModel:()=>_r,MBartForCausalLM:()=>kt,MBartForConditionalGeneration:()=>bt,MBartForSequenceClassification:()=>xt,MBartModel:()=>Mt,MBartPreTrainedModel:()=>yt,MPNetForMaskedLM:()=>We,MPNetForQuestionAnswering:()=>He,MPNetForSequenceClassification:()=>Xe,MPNetForTokenClassification:()=>Qe,MPNetModel:()=>$e,MPNetPreTrainedModel:()=>Ue,MT5ForConditionalGeneration:()=>_t,MT5Model:()=>pt,MT5PreTrainedModel:()=>ht,MarianMTModel:()=>pr,MarianModel:()=>hr,MarianPreTrainedModel:()=>ur,MaskedLMOutput:()=>Oi,MistralForCausalLM:()=>eo,MistralModel:()=>Zr,MistralPreTrainedModel:()=>Kr,MobileBertForMaskedLM:()=>Ve,MobileBertForQuestionAnswering:()=>qe,MobileBertForSequenceClassification:()=>Ge,MobileBertModel:()=>Re,MobileBertPreTrainedModel:()=>De,MobileViTForImageClassification:()=>as,MobileViTModel:()=>is,MobileViTPreTrainedModel:()=>os,ModelOutput:()=>O,MptForCausalLM:()=>Yn,MptModel:()=>Hn,MptPreTrainedModel:()=>Qn,MusicgenForCausalLM:()=>Co,MusicgenForConditionalGeneration:()=>Fo,MusicgenModel:()=>vo,MusicgenPreTrainedModel:()=>To,NomicBertModel:()=>$,NomicBertPreTrainedModel:()=>U,OPTForCausalLM:()=>Zn,OPTModel:()=>Kn,OPTPreTrainedModel:()=>Jn,OwlViTForObjectDetection:()=>ds,OwlViTModel:()=>cs,OwlViTPreTrainedModel:()=>ls,Owlv2ForObjectDetection:()=>ps,Owlv2Model:()=>hs,Owlv2PreTrainedModel:()=>us,PhiForCausalLM:()=>Un,PhiModel:()=>qn,PhiPreTrainedModel:()=>Gn,PreTrainedModel:()=>B,PretrainedMixin:()=>Po,QuestionAnsweringModelOutput:()=>ji,Qwen2ForCausalLM:()=>Vn,Qwen2Model:()=>Rn,Qwen2PreTrainedModel:()=>Dn,ResNetForImageClassification:()=>zs,ResNetModel:()=>Es,ResNetPreTrainedModel:()=>As,RoFormerForMaskedLM:()=>Q,RoFormerForQuestionAnswering:()=>J,RoFormerForSequenceClassification:()=>H,RoFormerForTokenClassification:()=>Y,RoFormerModel:()=>X,RoFormerPreTrainedModel:()=>W,RobertaForMaskedLM:()=>zt,RobertaForQuestionAnswering:()=>Bt,RobertaForSequenceClassification:()=>Lt,RobertaForTokenClassification:()=>It,RobertaModel:()=>Et,RobertaPreTrainedModel:()=>At,SamImageSegmentationOutput:()=>dr,SamModel:()=>cr,SamPreTrainedModel:()=>lr,SegformerForImageClassification:()=>fo,SegformerForSemanticSegmentation:()=>go,SegformerModel:()=>mo,SegformerPreTrainedModel:()=>_o,Seq2SeqLMOutput:()=>zi,SequenceClassifierOutput:()=>Li,SiglipModel:()=>dn,SiglipPreTrainedModel:()=>cn,SiglipTextModel:()=>un,SiglipVisionModel:()=>hn,SpeechT5ForSpeechToText:()=>Xr,SpeechT5ForTextToSpeech:()=>Qr,SpeechT5HifiGan:()=>Hr,SpeechT5Model:()=>Wr,SpeechT5PreTrainedModel:()=>$r,SqueezeBertForMaskedLM:()=>Ke,SqueezeBertForQuestionAnswering:()=>et,SqueezeBertForSequenceClassification:()=>Ze,SqueezeBertModel:()=>Je,SqueezeBertPreTrainedModel:()=>Ye,StableLmForCausalLM:()=>Mo,StableLmModel:()=>yo,StableLmPreTrainedModel:()=>wo,Starcoder2ForCausalLM:()=>so,Starcoder2Model:()=>no,Starcoder2PreTrainedModel:()=>to,Swin2SRForImageSuperResolution:()=>Ns,Swin2SRModel:()=>js,Swin2SRPreTrainedModel:()=>Os,SwinForImageClassification:()=>Bs,SwinModel:()=>Is,SwinPreTrainedModel:()=>Ls,T5ForConditionalGeneration:()=>lt,T5Model:()=>at,T5PreTrainedModel:()=>it,TableTransformerForObjectDetection:()=>vs,TableTransformerModel:()=>Ts,TableTransformerObjectDetectionOutput:()=>Cs,TableTransformerPreTrainedModel:()=>ks,TokenClassifierOutput:()=>Bi,TrOCRForCausalLM:()=>Jr,TrOCRPreTrainedModel:()=>Yr,UniSpeechForCTC:()=>Tr,UniSpeechForSequenceClassification:()=>vr,UniSpeechModel:()=>kr,UniSpeechPreTrainedModel:()=>xr,UniSpeechSatForAudioFrameClassification:()=>Ar,UniSpeechSatForCTC:()=>Pr,UniSpeechSatForSequenceClassification:()=>Sr,UniSpeechSatModel:()=>Fr,UniSpeechSatPreTrainedModel:()=>Cr,ViTForImageClassification:()=>ns,ViTModel:()=>ts,ViTPreTrainedModel:()=>es,VisionEncoderDecoderModel:()=>tn,VitMatteForImageMatting:()=>rs,VitMattePreTrainedModel:()=>ss,VitsModel:()=>po,VitsModelOutput:()=>Vi,VitsPreTrainedModel:()=>ho,Wav2Vec2BertForCTC:()=>Lr,Wav2Vec2BertForSequenceClassification:()=>Ir,Wav2Vec2BertModel:()=>zr,Wav2Vec2BertPreTrainedModel:()=>Er,Wav2Vec2ForAudioFrameClassification:()=>br,Wav2Vec2ForCTC:()=>yr,Wav2Vec2ForSequenceClassification:()=>Mr,Wav2Vec2Model:()=>wr,Wav2Vec2PreTrainedModel:()=>gr,WavLMForAudioFrameClassification:()=>Ur,WavLMForCTC:()=>Vr,WavLMForSequenceClassification:()=>Gr,WavLMForXVector:()=>qr,WavLMModel:()=>Rr,WavLMPreTrainedModel:()=>Dr,WhisperForConditionalGeneration:()=>en,WhisperModel:()=>Kt,WhisperPreTrainedModel:()=>Jt,XLMForQuestionAnswering:()=>Vt,XLMForSequenceClassification:()=>Dt,XLMForTokenClassification:()=>Rt,XLMModel:()=>jt,XLMPreTrainedModel:()=>Ot,XLMRobertaForMaskedLM:()=>Ut,XLMRobertaForQuestionAnswering:()=>Xt,XLMRobertaForSequenceClassification:()=>$t,XLMRobertaForTokenClassification:()=>Wt,XLMRobertaModel:()=>qt,XLMRobertaPreTrainedModel:()=>Gt,XLMWithLMHeadModel:()=>Nt,XVectorOutput:()=>Ii,YolosForObjectDetection:()=>ir,YolosModel:()=>or,YolosObjectDetectionOutput:()=>ar,YolosPreTrainedModel:()=>rr});var s=n(/*! ./configs.js */"./src/configs.js"),r=n(/*! ./backends/onnx.js */"./src/backends/onnx.js"),o=n(/*! ./utils/dtypes.js */"./src/utils/dtypes.js"),i=n(/*! ./utils/generic.js */"./src/utils/generic.js"),a=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/hub.js */"./src/utils/hub.js"),c=n(/*! ./generation/logits_process.js */"./src/generation/logits_process.js"),d=n(/*! ./generation/configuration_utils.js */"./src/generation/configuration_utils.js"),u=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),h=n(/*! ./utils/maths.js */"./src/utils/maths.js"),p=n(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),_=n(/*! ./generation/logits_sampler.js */"./src/generation/logits_sampler.js");const m=0,f=1,g=2,w=3,y=4,M=5,b=6,x=7,k=new Map,T=new Map,v=new Map;async function C(e,t,n){const s=Object.keys(t),i=await Promise.all(s.map((async s=>async function(e,t,n){let s=n.device;s&&"string"!=typeof s&&(s.hasOwnProperty(t)?s=s[t]:(console.warn(`Device not specified for ${t}. Using the default device.`),s=null));const i=(0,r.deviceToExecutionProviders)(s);let a=n.dtype;if("string"!=typeof a&&(a&&a.hasOwnProperty(t)?a=a[t]:(a=o.DEFAULT_DEVICE_DTYPE_MAPPING[i[0]],console.warn(`Dtype not specified for ${t}. Using the default dtype: ${a}.`))),!o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(a))throw new Error(`Invalid dtype: ${a}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);if(a===o.DATA_TYPES.fp16&&!await(0,o.isFp16Supported)())throw new Error("The device does not support fp16.");const c=o.DEFAULT_DTYPE_SUFFIX_MAPPING[a],d=`${n.subfolder??""}/${t}${c}.onnx`,u=await(0,l.getModelFile)(e,d,!0,n),h={...n.session_options}??{};if(h.executionProviders??=i,void 0!==h.externalData)for(let t=0;t0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);const o=Object.keys(t).length,i=e.inputNames.length;if(o>i){let n=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${o} > ${i}). The following inputs will be ignored: "${n.join(", ")}".`)}return n}(e,t);try{const t=Object.fromEntries(Object.entries(n).map((([e,t])=>[e,t.ort_tensor])));let s=await e.run(t);s=P(s);for(const[e,t]of Object.entries(n))e.startsWith("past_key_values")&&t.dispose();return s}catch(e){throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",n),e}}function P(e){for(let t in e)(0,r.isONNXTensor)(e[t])?e[t]=new u.Tensor(e[t]):"object"==typeof e[t]&&P(e[t]);return e}function S(e){return new u.Tensor("bool",[e],[1])}async function A(e,t){let{encoder_outputs:n,past_key_values:s}=t;if(!n){const s=(0,a.pick)(t,e.sessions.model.inputNames);n=(await E(e,s)).last_hidden_state}const{input_ids:r,decoder_input_ids:o,...i}=t;i.input_ids=o,i.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask);return await z(e,i,!0)}async function E(e,t){const n=e.sessions.model,s=Object.create(null);for(const e of n.inputNames)s[e]=t[e];return n.inputNames.includes("token_type_ids")&&!s.token_type_ids&&(s.token_type_ids=new u.Tensor("int64",new BigInt64Array(s.input_ids.data.length),s.input_ids.dims)),await F(n,s)}async function z(e,t,n=!1){const s=e.sessions[n?"decoder_model_merged":"model"],{past_key_values:r,...o}=t;s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=S(!!r)),e.addPastKeyValues(o,r);const i=(0,a.pick)(o,s.inputNames);return await F(s,i)}function L(e,t,n,s){if(e.sessions.model.inputNames.includes("position_ids")&&n.attention_mask&&!n.position_ids){const[e,t]=n.attention_mask.dims,s=new BigInt64Array(n.attention_mask.data.length);for(let r=0;r[e.at(-1)]))),r.decoder_input_ids=function(e){if(e instanceof u.Tensor)return e;if(0===e.length)throw Error("items must be non-empty");if(Array.isArray(e[0])){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 u.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new u.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}(t),r}class B extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t){super(),this.config=e,this.sessions=t;const n=v.get(this.constructor),s=k.get(n);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,s===y?(this.can_generate=!0,this._forward=z,this._prepare_inputs_for_generation=L):s===g||s===w||s===x?(this.can_generate=!0,this._forward=A,this._prepare_inputs_for_generation=I):s===f?this._forward=A:s===b?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=E}async dispose(){const e=[];for(let t of Object.keys(this)){let n=this[t];void 0!==n?.handler?.dispose&&e.push(n.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:c="onnx",device:d=null,dtype:u=null,session_options:h={}}={}){let p={progress_callback:t,config:n,cache_dir:r,local_files_only:o,revision:i,model_file_name:a,subfolder:c,device:d,dtype:u,session_options:h};const _=v.get(this),T=k.get(_);let F;return T===y?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:p.model_file_name??"model"},p),(0,l.getModelJSON)(e,"generation_config.json",!1,p)]):T===g||T===w?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p),(0,l.getModelJSON)(e,"generation_config.json",!1,p)]):T===M?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},p)]):T===f?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p)]):T===b?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},p),(0,l.getModelJSON)(e,"generation_config.json",!1,p)]):T===x?F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},p),(0,l.getModelJSON)(e,"generation_config.json",!1,p)]):(T!==m&&console.warn(`Model type for '${_??n?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),F=await Promise.all([s.AutoConfig.from_pretrained(e,p),C(e,{model:p.model_file_name??"model"},p)])),new this(...F)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_warper(e){const t=new c.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new c.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new c.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new c.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,n=null){const s=new c.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&s.push(new c.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&s.push(new c.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&s.push(new c.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&s.push(new c.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&s.push(new c.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&s.push(new c.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&s.push(new c.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){let n=t>1||null===e.forced_bos_token_id?t:t+1;null!==e.forced_decoder_ids&&(n+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),s.push(new c.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}return null!==e.guidance_scale&&e.guidance_scale>1&&s.push(new c.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==n&&s.extend(n),s}_prepare_generation_config(e,t){const n=new d.GenerationConfig(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e&&Object.assign(n,e),t&&Object.assign(n,(0,a.pick)(t,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,t=null){const n=new p.StoppingCriteriaList;return null!==e.max_length&&n.push(new p.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&n.push(new p.EosTokenCriteria(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){const e=[No,Vo,jo,zo],t=v.get(this.constructor),n=new Set,s=this.config.model_type;for(const t of e){const e=t.get(s);e&&n.add(e[0])}let r=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(r+=` Please use the following class instead: ${[...n].join(", ")}`),Error(r)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:s}){return n.past_key_values=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new u.Tensor("int64",e,[e.length,1]),s||(n.attention_mask=(0,u.cat)([n.attention_mask,(0,u.ones)([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){const s=(0,a.pick)(n,this.forward_params),r=this.main_input_name;if(r in s){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[r]=e;return{inputs_tensor:s[r],model_inputs:s,model_input_name:r}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:s}){const r=(0,a.pick)(t,this.sessions.model.inputNames);let{last_hidden_state:o}=await E(this,r);return null!==s.guidance_scale&&s.guidance_scale>1&&(o=(0,u.cat)([o,(0,u.full_like)(o,0)],0),"attention_mask"in t&&(t.attention_mask=(0,u.cat)([t.attention_mask,(0,u.zeros_like)(t.attention_mask)],0))),t.encoder_outputs=o,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:s,bos_token_id:r,generation_config:o}){let i;if(s=s??r,"musicgen"===this.config.model_type)i=new Array(e*this.config.decoder.num_codebooks).fill(s);else if(Array.isArray(s)){if(s.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${s.length}`);i=s}else i=new Array(e).fill(s);const a=new u.Tensor("int64",i,[i.length,1]);return n.decoder_attention_mask=(0,u.ones_like)(a),{input_ids:a,model_inputs:n}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:s=null,streamer:r=null,...o}){this._validate_model_class(),t=this._prepare_generation_config(t,o);let{inputs_tensor:i,model_inputs:a,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:o});const c=this.config.is_encoder_decoder;let d;c&&("encoder_outputs"in a||(a=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:a,model_input_name:l,generation_config:t}))),c?({input_ids:d,model_inputs:a}=this._prepare_decoder_input_ids_for_generation({batch_size:a[l].dims.at(0),model_input_name:l,model_kwargs:a,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t})):d=a[l];let h=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=h+t.max_new_tokens);const p=this._get_logits_processor(t,h,n),m=this._get_stopping_criteria(t,s),f=a[l].dims.at(0),g=_.LogitsSampler.getSampler(t),w=new Array(f).fill(0),y=d.tolist();for(r&&r.put(y);;){a=this.prepare_inputs_for_generation(y,a,t);const e=await this.forward(a),n=p(y,e.logits.slice(null,-1,null)),s=[];for(let e=0;ee)))break;a=this._update_model_kwargs_for_generation({generated_input_ids:s,outputs:e,model_inputs:a,is_encoder_decoder:c})}return r&&r.end(),new u.Tensor("int64",y.flat(),[y.length,y[0].length])}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){const t=Object.create(null);for(const n of e)void 0===t[n.id]?t[n.id]=[n]:t[n.id].push(n);return Object.values(t)}getPastKeyValues(e,t){const n=Object.create(null);for(const s in e)if(s.startsWith("present")){let r=s.replace("present","past_key_values");t&&s.includes("encoder")?n[r]=t[r]:n[r]=e[s]}return n}getAttentions(e){const t=Object.create(null);for(const n of["cross_attentions","decoder_attentions"]){const s=[];for(const t in e)if(t.startsWith(n)){s[t.split(".").pop()]=e[t]}t[n]=s}return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=1,n="float32",s=[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??1)){let r=[t,this.num_encoder_heads,0,this.encoder_dim_kv],o=[t,this.num_decoder_heads,0,this.decoder_dim_kv];for(let t=0;t{let s=Array.from({length:this.config.decoder_layers},((t,n)=>(0,u.cat)(e.map((e=>e[n])),2))),o=(0,u.stack)(t.map((([e,t])=>n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t))));o=o.transpose(1,0,2,3);let[i,a]=(0,u.std_mean)(o,-2,0,!0),l=o.clone();for(let e=0;en[t+1]-n[t])),c=(0,a.mergeArrays)([1],i).map((e=>!!e)),d=[];for(let e=0;ee.findIndex((e=>e==r)))),i=o.every((e=>-1===e)),a=o.every((e=>-1!==e));if(!i&&!a)throw new Error("Every input should contain either 0 or 1 image token.");if(i)return{inputs_embeds:e,attention_mask:s,position_ids:null};let l=[],c=[];for(let n=0;ne*t),1);e.input_labels=new u.Tensor("int64",new BigInt64Array(n).fill(1n),t)}const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await F(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new dr(await super._call(e))}}class dr extends O{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class ur extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class hr extends ur{}class pr extends ur{}class _r extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class mr extends _r{}class fr extends _r{}class gr extends B{}class wr extends gr{}class yr extends gr{async _call(e){return new Ni(await super._call(e))}}class Mr extends gr{async _call(e){return new Li(await super._call(e))}}class br extends gr{async _call(e){return new Bi(await super._call(e))}}class xr extends B{}class kr extends xr{}class Tr extends xr{async _call(e){return new Ni(await super._call(e))}}class vr extends xr{async _call(e){return new Li(await super._call(e))}}class Cr extends B{}class Fr extends Cr{}class Pr extends Cr{async _call(e){return new Ni(await super._call(e))}}class Sr extends Cr{async _call(e){return new Li(await super._call(e))}}class Ar extends Cr{async _call(e){return new Bi(await super._call(e))}}class Er extends B{}class zr extends Er{}class Lr extends Er{async _call(e){return new Ni(await super._call(e))}}class Ir extends Er{async _call(e){return new Li(await super._call(e))}}class Br extends B{}class Or extends gr{}class jr extends gr{async _call(e){return new Ni(await super._call(e))}}class Nr extends gr{async _call(e){return new Li(await super._call(e))}}class Dr extends B{}class Rr extends Dr{}class Vr extends Dr{async _call(e){return new Ni(await super._call(e))}}class Gr extends Dr{async _call(e){return new Li(await super._call(e))}}class qr extends Dr{async _call(e){return new Ii(await super._call(e))}}class Ur extends Dr{async _call(e){return new Bi(await super._call(e))}}class $r extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}}class Wr extends $r{}class Xr extends $r{}class Qr extends $r{async generate_speech(e,t,{threshold:n=.5,minlenratio:s=0,maxlenratio:r=20,vocoder:o=null}={}){const i={input_ids:e},{encoder_outputs:a,encoder_attention_mask:l}=await E(this,i),c=a.dims[1]/this.config.reduction_factor,d=Math.floor(c*r),h=Math.floor(c*s),p=this.config.num_mel_bins;let _=[],m=null,f=null,g=0;for(;;){++g;const e=S(!!f);let s;s=f?f.output_sequence_out:new u.Tensor("float32",new Float32Array(p),[1,1,p]);let r={use_cache_branch:e,output_sequence:s,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:a};this.addPastKeyValues(r,m),f=await F(this.sessions.decoder_model_merged,r),m=this.getPastKeyValues(f,m);const{prob:o,spectrum:i}=f;if(_.push(i),g>=h&&(Array.from(o.data).filter((e=>e>=n)).length>0||g>=d))break}const w=(0,u.cat)(_),{waveform:y}=await F(o.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:y}}}class Hr extends B{main_input_name="spectrogram"}class Yr extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class Jr extends Yr{}class Kr extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Zr extends Kr{}class eo extends Kr{}class to extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class no extends to{}class so extends to{}class ro extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class oo extends ro{}class io extends ro{}class ao extends B{}class lo extends ao{}class co extends ao{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class uo extends ao{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class ho extends B{}class po extends ho{async _call(e){return new Vi(await super._call(e))}}class _o extends B{}class mo extends _o{}class fo extends _o{}class go extends _o{}class wo extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class yo extends wo{}class Mo extends wo{}class bo extends B{}class xo extends bo{}class ko extends bo{async _call(e){return new Li(await super._call(e))}}class To extends B{}class vo extends To{}class Co extends To{}class Fo extends B{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,t,n){super(e,t),this.generation_config=n;const s=e.decoder;this.num_encoder_layers=this.num_decoder_layers=s.num_hidden_layers,this.num_encoder_heads=this.num_decoder_heads=s.num_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=s.hidden_size/this.num_decoder_heads}_apply_and_filter_by_delay_pattern_mask(e){const[t,n]=e.dims,s=this.config.decoder.num_codebooks,r=n-s;let o=0;for(let t=0;t0&&i<=r&&(e.data[o++]=e.data[t])}const i=Math.floor(t/s),a=o/(i*s);return new u.Tensor(e.type,e.data.slice(0,o),[i,s,a])}prepare_inputs_for_generation(e,t,n){let s=structuredClone(e);for(let e=0;e=t&&(s[e][t]=BigInt(this.config.decoder.pad_token_id));null!==n.guidance_scale&&n.guidance_scale>1&&(s=s.concat(s));return super.prepare_inputs_for_generation(s,t,n)}async generate(e){const t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:s}=await F(this.sessions.encodec_decode,{audio_codes:n});return s}}class Po{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:l="onnx",device:c=null,dtype:d=null,session_options:u={}}={}){let h={progress_callback:t,config:n,cache_dir:r,local_files_only:o,revision:i,model_file_name:a,subfolder:l,device:c,dtype:d,session_options:u};if(n=await s.AutoConfig.from_pretrained(e,h),h.config||(h.config=n),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let t of this.MODEL_CLASS_MAPPINGS){const s=t.get(n.model_type);if(s)return await s[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${n.model_type}", attempting to construct from base class.`),await B.from_pretrained(e,h);throw Error(`Unsupported model type: ${n.model_type}`)}}const So=new Map([["bert",["BertModel",D]],["nomic_bert",["NomicBertModel",$]],["roformer",["RoFormerModel",X]],["electra",["ElectraModel",oe]],["esm",["EsmModel",Be]],["convbert",["ConvBertModel",Z]],["camembert",["CamembertModel",ue]],["deberta",["DebertaModel",ge]],["deberta-v2",["DebertaV2Model",ke]],["mpnet",["MPNetModel",$e]],["albert",["AlbertModel",nt]],["distilbert",["DistilBertModel",Se]],["roberta",["RobertaModel",Et]],["xlm",["XLMModel",jt]],["xlm-roberta",["XLMRobertaModel",qt]],["clap",["ClapModel",lo]],["clip",["CLIPModel",on]],["clipseg",["CLIPSegModel",fn]],["chinese_clip",["ChineseCLIPModel",_n]],["siglip",["SiglipModel",dn]],["mobilebert",["MobileBertModel",Re]],["squeezebert",["SqueezeBertModel",Je]],["wav2vec2",["Wav2Vec2Model",wr]],["wav2vec2-bert",["Wav2Vec2BertModel",zr]],["unispeech",["UniSpeechModel",kr]],["unispeech-sat",["UniSpeechSatModel",Fr]],["hubert",["HubertModel",Or]],["wavlm",["WavLMModel",Rr]],["audio-spectrogram-transformer",["ASTModel",Ht]],["vits",["VitsModel",po]],["detr",["DetrModel",ws]],["table-transformer",["TableTransformerModel",Ts]],["vit",["ViTModel",ts]],["mobilevit",["MobileViTModel",is]],["owlvit",["OwlViTModel",cs]],["owlv2",["Owlv2Model",hs]],["beit",["BeitModel",ms]],["deit",["DeiTModel",Ps]],["convnext",["ConvNextModel",Ys]],["convnextv2",["ConvNextV2Model",Zs]],["dinov2",["Dinov2Model",nr]],["resnet",["ResNetModel",Es]],["swin",["SwinModel",Is]],["swin2sr",["Swin2SRModel",js]],["donut-swin",["DonutSwinModel",Qs]],["yolos",["YolosModel",or]],["dpt",["DPTModel",Rs]],["glpn",["GLPNModel",$s]],["hifigan",["SpeechT5HifiGan",Hr]],["efficientnet",["EfficientNetModel",xo]]]),Ao=new Map([["t5",["T5Model",at]],["longt5",["LongT5Model",dt]],["mt5",["MT5Model",pt]],["bart",["BartModel",ft]],["mbart",["MBartModel",Mt]],["marian",["MarianModel",hr]],["whisper",["WhisperModel",Kt]],["m2m_100",["M2M100Model",mr]],["blenderbot",["BlenderbotModel",vt]],["blenderbot-small",["BlenderbotSmallModel",Pt]]]),Eo=new Map([["bloom",["BloomModel",Wn]],["gpt2",["GPT2Model",yn]],["gptj",["GPTJModel",Pn]],["gpt_bigcode",["GPTBigCodeModel",En]],["gpt_neo",["GPTNeoModel",xn]],["gpt_neox",["GPTNeoXModel",vn]],["codegen",["CodeGenModel",In]],["llama",["LlamaModel",jn]],["qwen2",["Qwen2Model",Rn]],["phi",["PhiModel",qn]],["mpt",["MptModel",Hn]],["opt",["OPTModel",Kn]],["mistral",["MistralModel",Zr]],["starcoder2",["Starcoder2Model",no]],["falcon",["FalconModel",oo]]]),zo=new Map([["speecht5",["SpeechT5ForSpeechToText",Xr]],["whisper",["WhisperForConditionalGeneration",en]]]),Lo=new Map([["speecht5",["SpeechT5ForTextToSpeech",Qr]]]),Io=new Map([["vits",["VitsModel",po]],["musicgen",["MusicgenForConditionalGeneration",Fo]]]),Bo=new Map([["bert",["BertForSequenceClassification",V]],["roformer",["RoFormerForSequenceClassification",H]],["electra",["ElectraForSequenceClassification",ae]],["esm",["EsmForSequenceClassification",je]],["convbert",["ConvBertForSequenceClassification",te]],["camembert",["CamembertForSequenceClassification",pe]],["deberta",["DebertaForSequenceClassification",ye]],["deberta-v2",["DebertaV2ForSequenceClassification",ve]],["mpnet",["MPNetForSequenceClassification",Xe]],["albert",["AlbertForSequenceClassification",st]],["distilbert",["DistilBertForSequenceClassification",Ae]],["roberta",["RobertaForSequenceClassification",Lt]],["xlm",["XLMForSequenceClassification",Dt]],["xlm-roberta",["XLMRobertaForSequenceClassification",$t]],["bart",["BartForSequenceClassification",wt]],["mbart",["MBartForSequenceClassification",xt]],["mobilebert",["MobileBertForSequenceClassification",Ge]],["squeezebert",["SqueezeBertForSequenceClassification",Ze]]]),Oo=new Map([["bert",["BertForTokenClassification",G]],["roformer",["RoFormerForTokenClassification",Y]],["electra",["ElectraForTokenClassification",le]],["esm",["EsmForTokenClassification",Ne]],["convbert",["ConvBertForTokenClassification",ne]],["camembert",["CamembertForTokenClassification",_e]],["deberta",["DebertaForTokenClassification",Me]],["deberta-v2",["DebertaV2ForTokenClassification",Ce]],["mpnet",["MPNetForTokenClassification",Qe]],["distilbert",["DistilBertForTokenClassification",Ee]],["roberta",["RobertaForTokenClassification",It]],["xlm",["XLMForTokenClassification",Rt]],["xlm-roberta",["XLMRobertaForTokenClassification",Wt]]]),jo=new Map([["t5",["T5ForConditionalGeneration",lt]],["longt5",["LongT5ForConditionalGeneration",ut]],["mt5",["MT5ForConditionalGeneration",_t]],["bart",["BartForConditionalGeneration",gt]],["mbart",["MBartForConditionalGeneration",bt]],["marian",["MarianMTModel",pr]],["m2m_100",["M2M100ForConditionalGeneration",fr]],["blenderbot",["BlenderbotForConditionalGeneration",Ct]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",St]]]),No=new Map([["bloom",["BloomForCausalLM",Xn]],["gpt2",["GPT2LMHeadModel",Mn]],["gptj",["GPTJForCausalLM",Sn]],["gpt_bigcode",["GPTBigCodeForCausalLM",zn]],["gpt_neo",["GPTNeoForCausalLM",kn]],["gpt_neox",["GPTNeoXForCausalLM",Cn]],["codegen",["CodeGenForCausalLM",Bn]],["llama",["LlamaForCausalLM",Nn]],["qwen2",["Qwen2ForCausalLM",Vn]],["phi",["PhiForCausalLM",Un]],["mpt",["MptForCausalLM",Yn]],["opt",["OPTForCausalLM",Zn]],["mbart",["MBartForCausalLM",kt]],["mistral",["MistralForCausalLM",eo]],["starcoder2",["Starcoder2ForCausalLM",so]],["falcon",["FalconForCausalLM",io]],["trocr",["TrOCRForCausalLM",Jr]],["stablelm",["StableLmForCausalLM",Mo]]]),Do=new Map([["bert",["BertForMaskedLM",R]],["roformer",["RoFormerForMaskedLM",Q]],["electra",["ElectraForMaskedLM",ie]],["esm",["EsmForMaskedLM",Oe]],["convbert",["ConvBertForMaskedLM",ee]],["camembert",["CamembertForMaskedLM",he]],["deberta",["DebertaForMaskedLM",we]],["deberta-v2",["DebertaV2ForMaskedLM",Te]],["mpnet",["MPNetForMaskedLM",We]],["albert",["AlbertForMaskedLM",ot]],["distilbert",["DistilBertForMaskedLM",Le]],["roberta",["RobertaForMaskedLM",zt]],["xlm",["XLMWithLMHeadModel",Nt]],["xlm-roberta",["XLMRobertaForMaskedLM",Ut]],["mobilebert",["MobileBertForMaskedLM",Ve]],["squeezebert",["SqueezeBertForMaskedLM",Ke]]]),Ro=new Map([["bert",["BertForQuestionAnswering",q]],["roformer",["RoFormerForQuestionAnswering",J]],["electra",["ElectraForQuestionAnswering",ce]],["convbert",["ConvBertForQuestionAnswering",se]],["camembert",["CamembertForQuestionAnswering",me]],["deberta",["DebertaForQuestionAnswering",be]],["deberta-v2",["DebertaV2ForQuestionAnswering",Fe]],["mpnet",["MPNetForQuestionAnswering",He]],["albert",["AlbertForQuestionAnswering",rt]],["distilbert",["DistilBertForQuestionAnswering",ze]],["roberta",["RobertaForQuestionAnswering",Bt]],["xlm",["XLMForQuestionAnswering",Vt]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Xt]],["mobilebert",["MobileBertForQuestionAnswering",qe]],["squeezebert",["SqueezeBertForQuestionAnswering",et]]]),Vo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",tn]]]),Go=new Map([["llava",["LlavaForConditionalGeneration",sn]]]),qo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",tn]]]),Uo=new Map([["vit",["ViTForImageClassification",ns]],["mobilevit",["MobileViTForImageClassification",as]],["beit",["BeitForImageClassification",fs]],["deit",["DeiTForImageClassification",Ss]],["convnext",["ConvNextForImageClassification",Js]],["convnextv2",["ConvNextV2ForImageClassification",er]],["dinov2",["Dinov2ForImageClassification",sr]],["resnet",["ResNetForImageClassification",zs]],["swin",["SwinForImageClassification",Bs]],["segformer",["SegformerForImageClassification",fo]],["efficientnet",["EfficientNetForImageClassification",ko]]]),$o=new Map([["detr",["DetrForObjectDetection",ys]],["table-transformer",["TableTransformerForObjectDetection",vs]],["yolos",["YolosForObjectDetection",ir]]]),Wo=new Map([["owlvit",["OwlViTForObjectDetection",ds]],["owlv2",["Owlv2ForObjectDetection",ps]]]),Xo=new Map([["detr",["DetrForSegmentation",Ms]],["clipseg",["CLIPSegForImageSegmentation",gn]]]),Qo=new Map([["segformer",["SegformerForSemanticSegmentation",go]]]),Ho=new Map([["sam",["SamModel",cr]]]),Yo=new Map([["wav2vec2",["Wav2Vec2ForCTC",yr]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Lr]],["unispeech",["UniSpeechForCTC",Tr]],["unispeech-sat",["UniSpeechSatForCTC",Pr]],["wavlm",["WavLMForCTC",Vr]],["hubert",["HubertForCTC",jr]]]),Jo=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Mr]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ir]],["unispeech",["UniSpeechForSequenceClassification",vr]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Sr]],["wavlm",["WavLMForSequenceClassification",Gr]],["hubert",["HubertForSequenceClassification",Nr]],["audio-spectrogram-transformer",["ASTForAudioClassification",Yt]]]),Ko=new Map([["wavlm",["WavLMForXVector",qr]]]),Zo=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ar]],["wavlm",["WavLMForAudioFrameClassification",Ur]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",br]]]),ei=new Map([["vitmatte",["VitMatteForImageMatting",rs]]]),ti=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ns]]]),ni=new Map([["dpt",["DPTForDepthEstimation",Vs]],["depth_anything",["DepthAnythingForDepthEstimation",qs]],["glpn",["GLPNForDepthEstimation",Ws]]]),si=new Map([["clip",["CLIPVisionModelWithProjection",ln]],["siglip",["SiglipVisionModel",hn]]]),ri=[[So,m],[Ao,f],[Eo,y],[Bo,m],[Oo,m],[jo,g],[zo,g],[No,y],[Do,m],[Ro,m],[Vo,w],[Go,b],[Uo,m],[Xo,m],[Qo,m],[ei,m],[ti,m],[ni,m],[$o,m],[Wo,m],[Ho,M],[Yo,m],[Jo,m],[Lo,g],[Io,m],[Ko,m],[Zo,m],[si,m]];for(const[e,t]of ri)for(const[n,s]of e.values())k.set(n,t),v.set(s,n),T.set(n,s);const oi=[["MusicgenForConditionalGeneration",Fo,x],["CLIPTextModelWithProjection",an,m],["SiglipTextModel",un,m],["ClapTextModelWithProjection",co,m],["ClapAudioModelWithProjection",uo,m]];for(const[e,t,n]of oi)k.set(e,n),v.set(t,e),T.set(e,t);class ii extends Po{static MODEL_CLASS_MAPPINGS=ri.map((e=>e[0]));static BASE_IF_FAIL=!0}class ai extends Po{static MODEL_CLASS_MAPPINGS=[Bo]}class li extends Po{static MODEL_CLASS_MAPPINGS=[Oo]}class ci extends Po{static MODEL_CLASS_MAPPINGS=[jo]}class di extends Po{static MODEL_CLASS_MAPPINGS=[zo]}class ui extends Po{static MODEL_CLASS_MAPPINGS=[Lo]}class hi extends Po{static MODEL_CLASS_MAPPINGS=[Io]}class pi extends Po{static MODEL_CLASS_MAPPINGS=[No]}class _i extends Po{static MODEL_CLASS_MAPPINGS=[Do]}class mi extends Po{static MODEL_CLASS_MAPPINGS=[Ro]}class fi extends Po{static MODEL_CLASS_MAPPINGS=[Vo]}class gi extends Po{static MODEL_CLASS_MAPPINGS=[Uo]}class wi extends Po{static MODEL_CLASS_MAPPINGS=[Xo]}class yi extends Po{static MODEL_CLASS_MAPPINGS=[Qo]}class Mi extends Po{static MODEL_CLASS_MAPPINGS=[$o]}class bi extends Po{static MODEL_CLASS_MAPPINGS=[Wo]}class xi extends Po{static MODEL_CLASS_MAPPINGS=[Ho]}class ki extends Po{static MODEL_CLASS_MAPPINGS=[Yo]}class Ti extends Po{static MODEL_CLASS_MAPPINGS=[Jo]}class vi extends Po{static MODEL_CLASS_MAPPINGS=[Ko]}class Ci extends Po{static MODEL_CLASS_MAPPINGS=[Zo]}class Fi extends Po{static MODEL_CLASS_MAPPINGS=[qo]}class Pi extends Po{static MODEL_CLASS_MAPPINGS=[ei]}class Si extends Po{static MODEL_CLASS_MAPPINGS=[ti]}class Ai extends Po{static MODEL_CLASS_MAPPINGS=[ni]}class Ei extends Po{static MODEL_CLASS_MAPPINGS=[si]}class zi extends O{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:s=null,cross_attentions:r=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=s,this.cross_attentions=r}}class Li extends O{constructor({logits:e}){super(),this.logits=e}}class Ii extends O{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class Bi extends O{constructor({logits:e}){super(),this.logits=e}}class Oi extends O{constructor({logits:e}){super(),this.logits=e}}class ji extends O{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class Ni extends O{constructor({logits:e}){super(),this.logits=e}}class Di extends O{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class Ri extends O{constructor({alphas:e}){super(),this.alphas=e}}class Vi extends O{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/ops/registry.js": /*!*****************************!*\ !*** ./src/ops/registry.js ***! \*****************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{TensorOpRegistry:()=>i});var s=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),r=n(/*! ../utils/tensor.js */"./src/utils/tensor.js");const o=async(e,t,n)=>{const o=await(0,s.createInferenceSession)(e,t);return async e=>{const t=Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.ort_tensor]))),s=await o.run(t);return new r.Tensor(s[n])}};class i{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o(new Uint8Array([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20]),this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=o(new Uint8Array([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20]),this.session_options,"y")),this._bicubic_interpolate_4d}}},"./src/pipelines.js": /*!**************************!*\ !*** ./src/pipelines.js ***! \**************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{AudioClassificationPipeline:()=>F,AutomaticSpeechRecognitionPipeline:()=>S,DepthEstimationPipeline:()=>D,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>v,FillMaskPipeline:()=>y,ImageClassificationPipeline:()=>E,ImageFeatureExtractionPipeline:()=>C,ImageSegmentationPipeline:()=>z,ImageToImagePipeline:()=>N,ImageToTextPipeline:()=>A,ObjectDetectionPipeline:()=>I,Pipeline:()=>m,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>b,Text2TextGenerationPipeline:()=>M,TextClassificationPipeline:()=>f,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>j,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>x,ZeroShotAudioClassificationPipeline:()=>P,ZeroShotClassificationPipeline:()=>T,ZeroShotImageClassificationPipeline:()=>L,ZeroShotObjectDetectionPipeline:()=>B,pipeline:()=>G});var s=n(/*! ./tokenizers.js */"./src/tokenizers.js"),r=n(/*! ./models.js */"./src/models.js"),o=n(/*! ./processors.js */"./src/processors.js"),i=n(/*! ./utils/generic.js */"./src/utils/generic.js"),a=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/maths.js */"./src/utils/maths.js"),c=n(/*! ./utils/audio.js */"./src/utils/audio.js"),d=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),u=n(/*! ./utils/image.js */"./src/utils/image.js");async function h(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>u.RawImage.read(e))))}async function p(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>"string"==typeof e||e instanceof URL?(0,c.read_audio)(e,t):e instanceof Float64Array?new Float32Array(e):e)))}function _(e,t){t&&(e=e.map((e=>0|e)));const[n,s,r,o]=e;return{xmin:n,ymin:s,xmax:r,ymax:o}}class m extends i.Callable{constructor({task:e,model:t,tokenizer:n=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=s}async dispose(){await this.model.dispose()}}class f extends m{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(n),r="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),o=this.model.config.id2label,i=[];for(const e of s.logits){const n=r(e),s=(0,l.getTopItems)(n,t).map((e=>({label:o[e[0]],score:e[1]})));1===t?i.push(...s):i.push(s)}return Array.isArray(e)||1===t?i:i[0]}}class g extends m{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const n=Array.isArray(e),s=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),r=(await this.model(s)).logits,o=this.model.config.id2label,i=[];for(let e=0;e[e,t])).filter((e=>e[1]>i)),d=Array.from((0,l.softmax)(r.end_logits[e].data)).map(((e,t)=>[e,t])).filter((e=>e[1]>i)),u=(0,a.product)(c,d).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{const t=[...o];return t[i]=e[0],{score:e[1],token:e[0],token_str:this.tokenizer.model.vocab[e[0]],sequence:this.tokenizer.decode(t,{skip_special_tokens:!0})}})))}return Array.isArray(e)?r:r[0]}}class M extends m{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class b extends M{_key="summary_text";constructor(e){super(e)}}class x extends M{_key="translation_text";constructor(e){super(e)}}class k extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class T extends m{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map((([e,t])=>[e.toLowerCase(),t]))),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:s=!1}={}){const r=Array.isArray(e);r||(e=[e]),Array.isArray(t)||(t=[t]);const o=t.map((e=>n.replace("{}",e))),i=s||1===t.length,a=[];for(const n of e){const e=[];for(const t of o){const s=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),r=await this.model(s);i?e.push([r.logits.data[this.contradiction_id],r.logits.data[this.entailment_id]]):e.push(r.logits.data[this.entailment_id])}const s=(i?e.map((e=>(0,l.softmax)(e)[1])):(0,l.softmax)(e)).map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));a.push({sequence:n,labels:s.map((e=>t[e[1]])),scores:s.map((e=>e[0]))})}return r?a:a[0]}}class v extends m{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=!1,quantize:s=!1,precision:r="binary"}={}){const o=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(o);let a=i.last_hidden_state??i.logits;if("none"===t);else if("mean"===t)a=(0,d.mean_pooling)(a,o.attention_mask);else{if("cls"!==t)throw Error(`Pooling method '${t}' not supported.`);a=a.slice(null,0)}return n&&(a=a.normalize(2,-1)),s&&(a=(0,d.quantize_embeddings)(a,r)),a}}class C extends m{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const n=await h(e),{pixel_values:s}=await this.processor(n),r=await this.model({pixel_values:s});let o;if(t){if(!("pooler_output"in r))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");o=r.pooler_output}else o=r.last_hidden_state??r.logits??r.image_embeds;return o}}class F extends m{constructor(e){super(e)}async _call(e,{topk:t=null}={}){const n=!Array.isArray(e),s=this.processor.feature_extractor.config.sampling_rate,r=await p(e,s),o=this.model.config.id2label,i=[];for(const e of r){const n=await this.processor(e),s=(await this.model(n)).logits[0],r=(0,l.getTopItems)((0,l.softmax)(s.data),t).map((e=>({label:o[e[0]],score:e[1]})));1===t?i.push(...r):i.push(r)}return n&&1!==t?i[0]:i}}class P extends m{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const r=t.map((e=>n.replace("{}",e))),o=this.tokenizer(r,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,a=await p(e,i),c=[];for(const e of a){const n=await this.processor(e),s=await this.model({...o,...n}),r=(0,l.softmax)(s.logits_per_audio.data);c.push([...r].map(((e,n)=>({score:e,label:t[n]}))))}return s?c[0]:c}}class S extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}async _call_wav2vec2(e,t={}){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(e);n&&(e=[e]);const s=this.processor.feature_extractor.config.sampling_rate,r=await p(e,s),o=[];for(const e of r){const t=await this.processor(e),n=(await this.model(t)).logits[0],s=[];for(const e of n)s.push((0,l.max)(e.data)[1]);const r=this.tokenizer.decode(s);o.push({text:r})}return n?o[0]:o}async _call_whisper(e,t={}){const n=t.return_timestamps??!1,s=t.chunk_length_s??0,r=t.chunk_callback??null,o=t.force_full_sequences??!1;let i=t.stride_length_s??null;"word"===n&&(t.return_token_timestamps=!0);const c=(0,a.pop)(t,"language",null),d=(0,a.pop)(t,"task",null);if(c||d||n){if(t.forced_decoder_ids)throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");const e=this.tokenizer.get_decoder_prompt_ids({language:c,task:d,no_timestamps:!n});e.length>0&&(t.forced_decoder_ids=e)}const u=!Array.isArray(e);u&&(e=[e]);const h=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,_=this.processor.feature_extractor.config.hop_length,m=this.processor.feature_extractor.config.sampling_rate,f=await p(e,m),g=[];for(const e of f){let a=[];if(s>0){if(null===i)i=s/6;else if(s<=i)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const t=m*s,n=m*i,r=t-2*n;let o=0;for(;o=e.length;a.push({stride:[s.length,l?0:n,c?0:n],input_features:i.input_features,is_last:c}),o+=r}}else a=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of a){t.num_frames=Math.floor(e.stride[0]/_);const s=await this.model.generate({inputs:e.input_features,...t});"word"===n?(e.tokens=s.sequences[0],e.token_timestamps=s.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=s[0],e.stride=e.stride.map((e=>e/m)),null!==r&&r(e)}const[c,d]=this.tokenizer._decode_asr(a,{time_precision:h,return_timestamps:n,force_full_sequences:o});g.push({text:c,...d})}return u?g[0]:g}}class A extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class E extends m{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=Array.isArray(e),s=await h(e),{pixel_values:r}=await this.processor(s),o=await this.model({pixel_values:r}),i=this.model.config.id2label,a=[];for(const e of o.logits){const n=(0,l.getTopItems)((0,l.softmax)(e.data),t).map((e=>({label:i[e[0]],score:e[1]})));1===t?a.push(...n):a.push(n)}return n||1===t?a:a[0]}}class z extends m{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:r=null,target_sizes:o=null,subtask:i=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const a=await h(e),l=a.map((e=>[e.height,e.width])),{pixel_values:c,pixel_mask:d}=await this.processor(a),p=await this.model({pixel_values:c,pixel_mask:d});let _=null;if(null!==i)_=this.subtasks_mapping[i];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){_=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),i=e;break}const m=this.model.config.id2label,f=[];if("panoptic"===i||"instance"===i){const e=_(p,t,n,s,r,o??l)[0],i=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(i.data.length);for(let n=0;nn.replace("{}",e))),i=this.tokenizer(o,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:a}=await this.processor(r),c=await this.model({...i,pixel_values:a}),d="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),u=[];for(const e of c.logits_per_image){const n=[...d(e)].map(((e,n)=>({score:e,label:t[n]})));n.sort(((e,t)=>t.score-e.score)),u.push(n)}return s?u:u[0]}}class I extends m{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=!1}={}){const s=Array.isArray(e);if(s&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const r=await h(e),o=n?null:r.map((e=>[e.height,e.width])),{pixel_values:i,pixel_mask:a}=await this.processor(r),l=await this.model({pixel_values:i,pixel_mask:a}),c=this.processor.feature_extractor.post_process_object_detection(l,t,o),d=this.model.config.id2label,u=c.map((e=>e.boxes.map(((t,s)=>({score:e.scores[s],label:d[e.classes[s]],box:_(t,!n)})))));return s?u:u[0]}}class B extends m{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,topk:s=null,percentage:r=!1}={}){const o=Array.isArray(e),i=await h(e),a=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(i),c=[];for(let e=0;e({score:p.scores[n],label:t[p.classes[n]],box:_(e,!r)}))).sort(((e,t)=>t.score-e.score));null!==s&&(m=m.slice(0,s)),c.push(m)}return o?c:c[0]}}class O extends m{constructor(e){super(e)}async _call(e,t,n={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class j extends m{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),s=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:s}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await r.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new d.Tensor("float32",t,[1,t.length]);else if(!(t instanceof d.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return{audio:s.data,sampling_rate:o}}}class N extends m{constructor(e){super(e)}async _call(e){const t=await h(e),n=await this.processor(t),s=await this.model(n),r=[];for(const e of s.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");r.push(u.RawImage.fromTensor(t))}return r.length>1?r:r[0]}}class D extends m{constructor(e){super(e)}async _call(e){const t=await h(e),n=await this.processor(t),{predicted_depth:s}=await this.model(n),r=[];for(let e=0;e1?r:r[0]}}const R=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:f,model:r.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:g,model:r.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:w,model:r.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:y,model:r.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:b,model:r.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:x,model:r.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:M,model:r.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:k,model:r.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:T,model:r.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:F,model:r.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:P,model:r.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:S,model:[r.AutoModelForSpeechSeq2Seq,r.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:j,model:[r.AutoModelForTextToWaveform,r.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:A,model:r.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:E,model:r.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:z,model:[r.AutoModelForImageSegmentation,r.AutoModelForSemanticSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:L,model:r.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:I,model:r.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:B,model:r.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:O,model:r.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:N,model:r.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:D,model:r.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:v,model:r.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:C,model:[r.AutoModelForImageFeatureExtraction,r.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),V=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function G(e,t=null,{progress_callback:n=null,config:s=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main",device:l=null,dtype:c=null,model_file_name:d=null,session_options:u={}}={}){e=V[e]??e;const h=R[e.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(R)}]`);t||(t=h.default.model,console.log(`No model specified. Using default model: "${t}".`));const p={progress_callback:n,config:s,cache_dir:r,local_files_only:o,revision:i,device:l,dtype:c,model_file_name:d,session_options:u},_=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),m=await async function(e,t,n){const s=Object.create(null),r=[];for(let[o,i]of e.entries()){if(!i)continue;let e;e=Array.isArray(i)?new Promise((async(e,s)=>{let r;for(let o of i){if(null===o)return void e(null);try{return void e(await o.from_pretrained(t,n))}catch(e){if(!e.message?.includes("Unsupported model type"))return void s(e);r=e}}s(r)})):i.from_pretrained(t,n),s[o]=e,r.push(e)}await Promise.all(r);for(let[e,t]of Object.entries(s))s[e]=await t;return s}(_,t,p);m.task=e,(0,a.dispatchCallback)(n,{status:"ready",task:e,model:t});return new(0,h.pipeline)(m)}},"./src/processors.js": /*!***************************!*\ !*** ./src/processors.js ***! \***************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{ASTFeatureExtractor:()=>$,AutoProcessor:()=>ee,BeitFeatureExtractor:()=>I,BitImageProcessor:()=>y,CLIPFeatureExtractor:()=>b,CLIPImageProcessor:()=>x,ChineseCLIPFeatureExtractor:()=>k,ClapFeatureExtractor:()=>W,ConvNextFeatureExtractor:()=>v,ConvNextImageProcessor:()=>C,DPTFeatureExtractor:()=>g,DPTImageProcessor:()=>w,DeiTFeatureExtractor:()=>L,DetrFeatureExtractor:()=>j,DonutFeatureExtractor:()=>B,EfficientNetImageProcessor:()=>S,FeatureExtractor:()=>_,GLPNFeatureExtractor:()=>M,ImageFeatureExtractor:()=>m,MobileViTFeatureExtractor:()=>A,NougatImageProcessor:()=>O,OwlViTFeatureExtractor:()=>E,OwlViTProcessor:()=>Z,Owlv2ImageProcessor:()=>z,Processor:()=>Q,SamImageProcessor:()=>D,SamProcessor:()=>H,SeamlessM4TFeatureExtractor:()=>U,SegformerFeatureExtractor:()=>f,SiglipImageProcessor:()=>T,SpeechT5FeatureExtractor:()=>X,SpeechT5Processor:()=>K,Swin2SRImageProcessor:()=>R,ViTFeatureExtractor:()=>F,ViTImageProcessor:()=>P,VitMatteImageProcessor:()=>V,Wav2Vec2FeatureExtractor:()=>q,Wav2Vec2ProcessorWithLM:()=>J,WhisperFeatureExtractor:()=>G,WhisperProcessor:()=>Y,YolosFeatureExtractor:()=>N});var s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),r=n(/*! ./utils/core.js */"./src/utils/core.js"),o=n(/*! ./utils/hub.js */"./src/utils/hub.js"),i=n(/*! ./utils/maths.js */"./src/utils/maths.js"),a=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=(n(/*! ./utils/image.js */"./src/utils/image.js"),n(/*! ./utils/audio.js */"./src/utils/audio.js"));function c([e,t,n,s]){return[e-n/2,t-s/2,e+n/2,t+s/2]}function d(e,t=.5,n=null,s=!1){const r=e.logits,o=e.pred_boxes,[a,l,d]=r.dims;if(null!==n&&n.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let e=0;et&&o.push(e)}else{let e=(0,i.max)(r.data)[1];if(e===d-1)continue;if(n=(0,i.softmax)(r.data),n[e]e*a[(t+1)%2]))),h.boxes.push(s),h.classes.push(t),h.scores.push(n[t])}}u.push(h)}return u}function u(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function h(e,t,n=0,s=null){const r=e/t;let o=(0,i.bankers_round)(r)*t;return null!==s&&o>s&&(o=Math.floor(r)*t),or?l=Math.floor(r*a/s):r>s&&(a=Math.floor(s*l/r)),await e.resize(l,a,{resample:n}))}async crop_margin(e,t=200){const n=e.clone().grayscale(),s=(0,i.min)(n.data)[0],r=(0,i.max)(n.data)[0]-s;if(0===r)return e;const o=t/255;let a=n.width,l=n.height,c=0,d=0;const u=n.data;for(let e=0;ethis.preprocess(e))));return{pixel_values:(0,a.stack)(n.map((e=>e.pixel_values)),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class f extends m{post_process_semantic_segmentation(e,t=null){const n=e.logits,s=n.dims[0];if(null!==t&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const r=[];for(let e=0;ed[n]&&(d[n]=t[n],u[n]=e)}const h=new Array(o.dims[0]),p=c.data;for(let e=0;evoid 0!==e));r.push({segmentation:c,labels:_})}return r}}class g extends m{}class w extends g{}class y extends m{}class M extends m{}class b extends m{}class x extends b{}class k extends m{}class T extends m{}class v extends m{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){const t=this.size?.shortest_edge;if(void 0===t)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const n=Math.floor(t/this.crop_pct),[s,r]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(s,r,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class C extends v{}class F extends m{}class P extends m{}class S extends m{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map((e=>e*e)))}}class A extends m{}class E extends m{post_process_object_detection(...e){return d(...e)}}class z extends E{}class L extends m{}class I extends m{}class B extends m{pad_image(e,t,n,s={}){const[r,o,i]=t;let a=this.image_mean;Array.isArray(this.image_mean)||(a=new Array(i).fill(a));let l=this.image_std;Array.isArray(l)||(l=new Array(i).fill(a));const c=a.map(((e,t)=>-e/l[t]));return super.pad_image(e,t,n,{center:!0,constant_values:c,...s})}}class O extends B{}class j extends m{async _call(e){const t=await super._call(e),n=[t.pixel_values.dims[0],64,64],s=new a.Tensor("int64",new BigInt64Array(n.reduce(((e,t)=>e*t))).fill(1n),n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return d(...e)}remove_low_and_no_objects(e,t,n,s){let r=[],o=[],a=[];for(let l=0;ln&&(r.push(d),o.push(h),a.push(u))}return[r,o,a]}check_segment_validity(e,t,n,s=.5,r=.8){let o=[],i=0,a=0;const l=t[n].data;for(let t=0;t=s&&++a;let c=i>0&&a>0;if(c){c=i/a>r}return[c,o]}compute_segments(e,t,n,s,r,o=null,i=null){let[l,c]=i??e[0].dims,d=new a.Tensor("int32",new Int32Array(l*c),[l,c]),u=[];if(null!==i)for(let t=0;tp[e]&&(h[e]=n,p[e]=r[e])}let _=0;const m=d.data;for(let o=0;oe!==t.dims[n])))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new a.Tensor("int64",e.flat(1/0).map(BigInt),n)}async _call(e,t=null,n=null,s=null){const r=await super._call(e);if(t&&(r.input_points=this.reshape_input_points(t,r.original_sizes,r.reshaped_input_sizes)),n){if(!r.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");r.input_labels=this.add_input_labels(n,r.input_points)}return s&&(r.input_boxes=this.reshape_input_points(s,r.original_sizes,r.reshaped_input_sizes,!0)),r}async post_process_masks(e,t,n,{mask_threshold:s=0,binarize:r=!0,pad_size:o=null}={}){const i=[],l=[(o=o??this.pad_size).height,o.width];for(let o=0;os&&(t[n]=1);u=new a.Tensor("bool",t,u.dims)}i.push(u)}return i}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:s=512/1500,points_per_crop:r=32,crop_n_points_downscale_factor:o=1}={}){}}class R extends m{pad_image(e,t,n,s={}){const[r,o,i]=t;return super.pad_image(e,t,{width:o+(n-o%n)%n,height:r+(n-r%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...s})}}class V extends m{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=await Promise.all(e.map((e=>this.preprocess(e)))),s=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})))),r=(0,a.stack)(n.map(((e,t)=>(0,a.cat)([e.pixel_values,s[t].pixel_values],0))),0);return{pixel_values:r,original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class G extends _{constructor(e){super(e),this.config.mel_filters??=(0,l.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,l.window_function)(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:t,dims:n}=(0,l.spectrogram)(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),s=(0,i.max)(t)[0];for(let e=0;ethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),t=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples),t.set(e));const{data:n,dims:s}=this._extract_fbank_features(t);return{input_features:new a.Tensor("float32",n,[1,...s])}}}class q extends _{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.reduce(((e,n)=>e+(n-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(n+1e-7)))}async _call(e){u(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const n=[1,t.length];return{input_values:new a.Tensor("float32",t,n),attention_mask:new a.Tensor("int64",new BigInt64Array(t.length).fill(1n),n)}}}class U extends _{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:s=!0,return_attention_mask:r=!0}={}){u(e,"SeamlessM4TFeatureExtractor");let o=this._extract_fbank_features(e,this.config.max_length);const i=o.data;if(s){const[e,t]=o.dims;for(let n=0;n0){const n=new Float32Array(t*(e+s));n.set(i),n.fill(this.config.padding_value,i.length);const c=e+s;o={data:n,dims:[c,t]},r&&(l=new a.Tensor("int64",new BigInt64Array(c),[1,c]),l.data.fill(1n,0,e))}}const[c,d]=o.dims,h=this.config.stride;if(0!==c%h)throw new Error(`The number of frames (${c}) must be a multiple of the stride (${h}).`);const p=new a.Tensor("float32",i,o.dims).view(1,Math.floor(c/h),d*h),_={input_features:p};if(r){const e=p.dims[1],t=new BigInt64Array(e);if(l){const e=l.data;for(let n=1,s=0;n0){if("rand_trunc"!==n)throw new Error(`Truncation strategy "${n}" not implemented`);{o=!0;const n=Math.floor(Math.random()*(i+1));e=e.subarray(n,n+t),r=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples),r.dims=[1,...r.dims]}}else{if(i<0){let n=new Float64Array(t);if(n.set(e),"repeat"===s)for(let s=e.length;s{"use strict";n.r(t),n.d(t,{AlbertTokenizer:()=>ge,AutoTokenizer:()=>ut,BartTokenizer:()=>Ee,BertTokenizer:()=>fe,BlenderbotSmallTokenizer:()=>it,BlenderbotTokenizer:()=>ot,BloomTokenizer:()=>Be,CLIPTokenizer:()=>tt,CamembertTokenizer:()=>Ce,CodeGenTokenizer:()=>et,CodeLlamaTokenizer:()=>Ne,CohereTokenizer:()=>dt,ConvBertTokenizer:()=>ke,DebertaTokenizer:()=>Me,DebertaV2Tokenizer:()=>be,DistilBertTokenizer:()=>ve,ElectraTokenizer:()=>Pe,EsmTokenizer:()=>qe,FalconTokenizer:()=>Ve,GPT2Tokenizer:()=>Ae,GPTNeoXTokenizer:()=>Ge,GemmaTokenizer:()=>$e,Grok1Tokenizer:()=>We,HerbertTokenizer:()=>xe,LlamaTokenizer:()=>je,M2M100Tokenizer:()=>He,MBart50Tokenizer:()=>Le,MBartTokenizer:()=>ze,MPNetTokenizer:()=>Re,MarianTokenizer:()=>st,MobileBertTokenizer:()=>we,NllbTokenizer:()=>Qe,NougatTokenizer:()=>lt,PreTrainedTokenizer:()=>me,Qwen2Tokenizer:()=>Ue,RoFormerTokenizer:()=>Te,RobertaTokenizer:()=>Ie,SiglipTokenizer:()=>nt,SpeechT5Tokenizer:()=>at,SqueezeBertTokenizer:()=>ye,T5Tokenizer:()=>Se,TokenizerModel:()=>y,VitsTokenizer:()=>ct,Wav2Vec2CTCTokenizer:()=>rt,WhisperTokenizer:()=>Ze,XLMRobertaTokenizer:()=>De,XLMTokenizer:()=>Fe});var s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),r=n(/*! ./utils/core.js */"./src/utils/core.js"),o=n(/*! ./utils/hub.js */"./src/utils/hub.js"),i=n(/*! ./utils/maths.js */"./src/utils/maths.js"),a=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=n(/*! ./utils/data-structures.js */"./src/utils/data-structures.js"),c=n(/*! @huggingface/jinja */"./node_modules/@huggingface/jinja/dist/index.js");async function d(e,t){const n=await Promise.all([(0,o.getModelJSON)(e,"tokenizer.json",!0,t),(0,o.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(n[1].legacy=t.legacy),n}function u(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,n]of g)t=t.replaceAll(e,n);return new RegExp(t,"gu")}if(void 0!==e.String){const n=(0,r.escapeRegExp)(e.String);return new RegExp(t?n:`(${n})`,"gu")}return console.warn("Unknown pattern type:",e),null}function h(e){return new Map(Object.entries(e))}function p(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function _(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function m(e){return e.replace(/[\u0300-\u036f]/g,"")}const f="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",g=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]]);class w{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}}class y extends s.Callable{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new M(e);case"Unigram":return new b(e,...t);case"BPE":return new T(e);default:if(e.vocab)return new v(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=function(e,t,n){const s=[];let r=0;for(;rthis.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class M extends y{constructor(e){super(e),this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){const t=[];for(const n of e){const e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,r=0;const o=[];for(;r0&&(s=this.config.continuing_subword_prefix+s),this.tokens_to_ids.has(s)){n=s;break}--t}if(null===n){s=!0;break}o.push(n),r=t}s?t.push(this.unk_token):t.push(...o)}return t}}class b extends y{constructor(e,t){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let t=0;t[e,t]))),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=t.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.sentence,n=t.length;let s=0;for(;s{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))],t=e.slice();let n=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+n),n+=1);const s=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,s[t]])))})(),k=(0,r.reverseDictionary)(x);class T extends y{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;this.bpe_ranks=new Map(e.merges.map(((e,t)=>[e,t]))),this.merges=e.merges.map((e=>e.split(this.BPE_SPLIT_TOKEN))),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let s=[];if(n.length>1){const e=new l.PriorityQueue(((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`))):t.push(this.unk_token)}return t}}class v extends y{constructor(e,t){super(e),this.tokens_to_ids=h(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}}class C extends s.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new O(e);case"Precompiled":return new ae(e);case"Sequence":return new B(e);case"Replace":return new F(e);case"NFC":return new P(e);case"NFKC":return new S(e);case"NFKD":return new A(e);case"Strip":return new E(e);case"StripAccents":return new z(e);case"Lowercase":return new L(e);case"Prepend":return new I(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class F extends C{normalize(e){const t=u(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class P extends C{normalize(e){return e=e.normalize("NFC")}}class S extends C{normalize(e){return e=e.normalize("NFKC")}}class A extends C{normalize(e){return e=e.normalize("NFKD")}}class E extends C{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class z extends C{normalize(e){return e=m(e)}}class L extends C{normalize(e){return e=e.toLowerCase()}}class I extends C{normalize(e){return e=this.config.prepend+e}}class B extends C{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>C.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class O extends C{_tokenize_chinese_chars(e){const t=[];for(let n=0;n=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,"")}_is_control(e){switch(e){case"\t":case"\n":case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}_clean_text(e){const t=[];for(const n of e){const e=n.charCodeAt(0);0===e||65533===e||this._is_control(n)||(/^\s$/.test(n)?t.push(" "):t.push(n))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this._clean_text(e)),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 j extends s.Callable{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new N(e);case"Sequence":return new le(e);case"Whitespace":return new ce(e);case"WhitespaceSplit":return new de(e);case"Metaspace":return new oe(e);case"ByteLevel":return new D(e);case"Split":return new R(e);case"Punctuation":return new V(e);case"Digits":return new G(e);case"Replace":return new ue(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,t){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,t){return(Array.isArray(e)?e.map((e=>this.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class N extends j{constructor(e){super(),this.pattern=new RegExp(`[^\\s${f}]+|[${f}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class D extends j{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=x,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e);return(this.use_regex?e.match(this.pattern)||[]:[e]).map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class R extends j{constructor(e){super(),this.config=e,this.pattern=u(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:function(e,t){const n=[];let s=0;for(const r of e.matchAll(t)){const t=r[0];s0&&n.push(t),s=r.index+t.length}return se.replaceAll(t,this.config.content)))}}class Y extends Q{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let n=[];for(const s of e){let e=null;if(6===s.length&&s.startsWith("<0x")&&s.endsWith(">")){const t=parseInt(s.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)n.push(e);else{if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(s)}}if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}}class J extends Q{decode_chain(e){return[e.join("")]}}class K extends Q{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 n=0;n(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=_(e)),e)))}}class ee extends Q{constructor(e){super(e),this.byte_decoder=k,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),n=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(n)}decode_chain(e){const t=[];let n=[];for(const s of e)void 0!==this.added_tokens.find((e=>e.content===s))?(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(s)):n.push(s);return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}}class te extends Q{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";const t=[e[0]];for(let n=1;ne!==this.pad_token)).join("");return this.cleanup&&(n=_(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class ne extends Q{constructor(e){super(e),this.decoders=e.decoders.map((e=>Q.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class se extends Q{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" ")))}}class re extends Q{decode_chain(e){let t="";for(let n=1;ne.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class le extends j{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>j.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,n)=>n.pre_tokenize(e,t)),[e])}}class ce extends j{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class de extends j{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class ue extends j{constructor(e){super(),this.config=e,this.pattern=u(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const he=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function pe(e,t,n,s){for(const o of Object.keys(e)){const i=t-e[o].length,a=n(o),l=new Array(i).fill(a);e[o]="right"===s?(0,r.mergeArrays)(e[o],l):(0,r.mergeArrays)(l,e[o])}}function _e(e,t){for(const n of Object.keys(e))e[n].length=t}class me extends s.Callable{return_token_type_ids=!1;_default_chat_template="{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=C.fromConfig(e.normalizer),this.pre_tokenizer=j.fromConfig(e.pre_tokenizer),this.model=y.fromConfig(e.model,t),this.post_processor=q.fromConfig(e.post_processor),this.decoder=Q.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new w(t);this.added_tokens.push(e),this.model.tokens_to_ids.set(e.content,e.id),this.model.vocab[e.id]=e.content,e.special&&(this.special_tokens.push(e.content),this.all_special_ids.push(e.id))}if(this.additional_special_tokens=t.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map((e=>`${e.lstrip?"\\s*":""}(${(0,r.escapeRegExp)(e.content)})${e.rstrip?"\\s*":""}`)).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:n}of this.chat_template){if("string"!=typeof t||"string"!=typeof n)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(e){if("object"==typeof e){if("AddedToken"===e.__type)return e.content;throw Error(`Unknown token: ${e}`)}return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:s=null,local_files_only:r=!1,revision:o="main",legacy:i=null}={}){return new this(...await d(e,{progress_callback:t,config:n,cache_dir:s,local_files_only:r,revision:o,legacy:i}))}_call(e,{text_pair:t=null,add_special_tokens:n=!0,padding:s=!1,truncation:r=null,max_length:o=null,return_tensor:l=!0}={}){const c=Array.isArray(e);let d;if(c){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(!Array.isArray(t))throw Error("text_pair must also be an array");if(e.length!==t.length)throw Error("text and text_pair must have the same length");d=e.map(((e,s)=>this._encode_plus(e,{text_pair:t[s],add_special_tokens:n})))}else d=e.map((e=>this._encode_plus(e,{add_special_tokens:n})))}else{if(null==e)throw Error("text may not be null or undefined");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).");d=[this._encode_plus(e,{text_pair:t,add_special_tokens:n})]}if(null===o?o="max_length"===s?this.model_max_length:(0,i.max)(d.map((e=>e.input_ids.length)))[0]:r||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),o=Math.min(o,this.model_max_length),s||r)for(let e=0;eo?r&&_e(d[e],o):s&&pe(d[e],o,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const u={};if(l){if((!s||!r)&&d.some((e=>{for(const t of Object.keys(e))if(e[t].length!==d[0][t]?.length)return!0;return!1})))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.");const e=[d.length,d[0].input_ids.length];for(const t of Object.keys(d[0]))u[t]=new a.Tensor("int64",BigInt64Array.from(d.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(d[0]))u[e]=d.map((t=>t[e]));if(!c)for(const e of Object.keys(u))u[e]=u[e][0]}return u}_encode_text(e){if(null===e)return null;const t=(this.added_tokens_regex?e.split(this.added_tokens_regex).filter((e=>e)):[e]).map(((e,t)=>{if(void 0!==this.added_tokens.find((t=>t.content===e)))return e;{if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=function(e){return m(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const n=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(n)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0}={}){const{tokens:s,token_type_ids:r}=this._tokenize_helper(e,{pair:t,add_special_tokens:n}),o=this.model.convert_tokens_to_ids(s),i={input_ids:o,attention_mask:new Array(o.length).fill(1)};return this.return_token_type_ids&&r&&(i.token_type_ids=r),i}_tokenize_helper(e,{pair:t=null,add_special_tokens:n=!1}={}){const s=this._encode_text(e),o=this._encode_text(t);return this.post_processor?this.post_processor(s,o,{add_special_tokens:n}):{tokens:(0,r.mergeArrays)(s??[],o??[])}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:n}).tokens}encode(e,{text_pair:t=null,add_special_tokens:n=!0}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:n}).input_ids}batch_decode(e,t={}){return e instanceof a.Tensor&&(e=e.tolist()),e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof a.Tensor&&(e=p(e)),!Array.isArray(e)||0===e.length||!(0,r.isIntegralNumber)(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:n=null}){let s=this.model.convert_ids_to_tokens(e);t&&(s=s.filter((e=>!this.special_tokens.includes(e))));let r=this.decoder?this.decoder(s):s.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),t&&(r=r.trim())),(n??this.clean_up_tokenization_spaces)&&(r=_(r)),r}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(e,{chat_template:t=null,add_generation_prompt:n=!1,tokenize:s=!0,padding:r=!1,truncation:o=!1,max_length:i=null,return_tensor:a=!0,tokenizer_kwargs:l={},...d}={}){if(this.chat_template&&"object"==typeof this.chat_template||null===this.chat_template&&this.default_chat_template&&"object"==typeof this.default_chat_template){const e=this.chat_template??this.default_chat_template;if(null!==t&&Object.hasOwn(e,t))t=e[t];else if(null===t&&"default"in e)t=e.default;else if(null===t)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(e).sort()}.`)}else t??=this.chat_template??this.default_chat_template;if("string"!=typeof t)throw Error("chat_template must be a string, but got "+typeof t);let u=this._compiled_template_cache.get(t);void 0===u&&(u=new c.Template(t),this._compiled_template_cache.set(t,u));const h=Object.create(null);for(const e of he){const t=this.getToken(e);t&&(h[e]=t)}const p=u.render({messages:e,add_generation_prompt:n,...h,...d});return s?this._call(p,{add_special_tokens:!1,padding:r,truncation:o,max_length:i,return_tensor:a,...l}).input_ids:p}}class fe extends me{return_token_type_ids=!0}class ge extends me{return_token_type_ids=!0}class we extends me{return_token_type_ids=!0}class ye extends me{return_token_type_ids=!0}class Me extends me{return_token_type_ids=!0}class be extends me{return_token_type_ids=!0}class xe extends me{return_token_type_ids=!0}class ke extends me{return_token_type_ids=!0}class Te extends me{return_token_type_ids=!0}class ve extends me{}class Ce extends me{}class Fe extends me{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Pe extends me{return_token_type_ids=!0}class Se extends me{}class Ae extends me{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}'}class Ee extends me{}class ze extends me{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Xe(this,e,t,n)}}class Le extends ze{}class Ie extends me{}class Be extends Ae{constructor(e,t){const n=".,!?…。,、।۔،",s=e.pre_tokenizer?.pretokenizers[0]?.pattern;s&&s.Regex===` ?[^(\\s|[${n}])]+`&&(s.Regex=` ?[^\\s${n}]+`),super(e,t)}}const Oe="▁";class je extends me{_default_chat_template="{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<>\n' + system_message + '\n<>\n\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<>\n' + content.strip() + '\n<>\n\n' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}";DEFAULT_SYSTEM_PROMPT="You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.";padding_side="left";constructor(e,t){super(e,t),this.use_default_system_prompt=t.use_default_system_prompt??!1,this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new oe({replacement:Oe,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(null===e)return null;if(this.legacy||0===e.length)return super._encode_text(e);let t=super._encode_text(Oe+e.replaceAll(Oe," "));return t.length>1&&t[0]===Oe&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n","\\n").replaceAll("'","\\'"))}}class Ne extends je{}class De extends me{}class Re extends me{}class Ve extends me{}class Ge extends me{}class qe extends me{}class Ue extends me{}class $e extends me{_default_chat_template="{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + '\n' + message['content'] | trim + '\n' }}{% endfor %}{% if add_generation_prompt %}{{'model\n'}}{% endif %}"}class We extends me{}function Xe(e,t,n,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e&&e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const r=s.src_lang,o=s.tgt_lang;if(!e.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==r){if(!e.language_codes.includes(r))throw new Error(`Source language code "${r}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(r);break}}return s.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(o)])[0],e._call(t,n)}class Qe extends me{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Xe(this,e,t,n)}}class He extends me{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2))),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Xe(this,e,t,n)}}const Ye=[["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"]],Je=new Map(Ye),Ke=new Map([...Ye.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 Ze extends me{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:s=null,force_full_sequences:r=!0}={}){if(null===s)throw Error("Must specify time_precision");let o=null;const a="word"===t;function l(){return{language:o,timestamp:[null,null],text:""}}const c=[];let d=l(),u=0;const h=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let p=[],_=[],m=!1,f=null;const g=new Set(this.all_special_ids);for(const n of e){const e=n.tokens,r=a?n.token_timestamps:null;let w=null,y=h;if("stride"in n){const[t,r,o]=n.stride;if(u-=r,f=t-o,r&&(y=r/s+h),o)for(let t=e.length-1;t>=0;--t){const n=e[t];if(n>=h){if(null!==w&&(n-h)*s=h){const e=(f-h)*s+u,t=(0,i.round)(e,2);if(null!==w&&f>=w)m=!0;else if(m||p.length>0&&f0?(p.push(M),a&&_.push(b)):p.every((e=>0===e.length))&&(d=l(),p=[],M=[],_=[],b=[])}if(p.length>0){if(r&&t)throw new 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.");const[e,n]=this.findLongestCommonSequence(p,_),s=this.decode(e);d.text=s,a&&(d.words=this.collateWordTimestamps(e,n,o)),c.push(d)}let w=Object.create(null);const y=c.map((e=>e.text)).join("");if(t||n){for(let e=0;e0;let i=o?[]:null,a=o?t[0]:null;for(let l=1;le===p[t])).length,m=_/e+t;_>1&&m>d&&(d=m,u=[r,o,a,l])}const[p,_,m,f]=u,g=Math.floor((_+p)/2),w=Math.floor((f+m)/2);r.push(...n.slice(0,g)),n=c.slice(w),s=n.length,o&&(i.push(...a.slice(0,g)),a=t[l].slice(w))}return r.push(...n),o?(i.push(...a),[r,i]):[r,[]]}collateWordTimestamps(e,t,n){const[s,r,o]=this.combineTokensIntoWords(e,n),i=[];for(let e=0;e=s){const e=(0,i.round)((t-s)*n,2);r.push(`<|${e}|>`),r.push([])}else r[r.length-1].push(t);return r=r.map((e=>"string"==typeof e?e:super.decode(e,t))),r.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),n=[],s=[],r=[];let o=[],i=[],a=0;for(let l=0;l=this.model.tokens_to_ids.get("<|endoftext|>"),h=l.startsWith(" "),p=l.trim(),_=a.test(p);if(u||h||_||0===r.length)r.push(l),o.push(c),i.push(d);else{const e=r.length-1;r[e]+=l,o[e].push(...c),i[e].push(...d)}}return[r,o,i]}mergePunctuations(e,t,n,s,o){const i=structuredClone(e),a=structuredClone(t),l=structuredClone(n);let c=i.length-2,d=i.length-1;for(;c>=0;)i[c].startsWith(" ")&&s.includes(i[c].trim())?(i[d]=i[c]+i[d],a[d]=(0,r.mergeArrays)(a[c],a[d]),l[d]=(0,r.mergeArrays)(l[c],l[d]),i[c]="",a[c]=[],l[c]=[]):d=c,--c;for(c=0,d=1;de)),a.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:n=!0}={}){const s=[];if(e){e=e.toLowerCase();let t=Ke.get(e);if(void 0===t){if(!Je.has(e)){const t=2===e.length?Je.keys():Je.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(t)}`)}t=e}const n=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===n)throw new Error(`Unable to find language "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);s.push(n)}else s.push(null);if(t){if("transcribe"!==(t=t.toLowerCase())&&"translate"!==t)throw new Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`);const e=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===e)throw new Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);s.push(e)}else s.push(null);if(n){const e=this.model.tokens_to_ids.get("<|notimestamps|>");if(void 0===e)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');s.push(e)}return s.map(((e,t)=>[t+1,e])).filter((e=>null!==e[1]))}}class et extends me{}class tt extends me{}class nt extends me{}class st extends me{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;const[t,...n]=e.trim().split(this.languageRegex);if(0===n.length)return super._encode_text(t);if(2===n.length){const[e,t]=n;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)}`),(0,r.mergeArrays)([e],super._encode_text(t))}}}class rt extends me{}class ot extends me{_default_chat_template="{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"}class it extends ot{}class at extends me{}class lt extends me{}class ct extends me{constructor(e,t){super(e,t),this.decoder=new re({})}}class dt extends me{}class ut{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Se,DistilBertTokenizer:ve,CamembertTokenizer:Ce,DebertaTokenizer:Me,DebertaV2Tokenizer:be,BertTokenizer:fe,HerbertTokenizer:xe,ConvBertTokenizer:ke,RoFormerTokenizer:Te,XLMTokenizer:Fe,ElectraTokenizer:Pe,MobileBertTokenizer:we,SqueezeBertTokenizer:ye,AlbertTokenizer:ge,GPT2Tokenizer:Ae,BartTokenizer:Ee,MBartTokenizer:ze,MBart50Tokenizer:Le,RobertaTokenizer:Ie,WhisperTokenizer:Ze,CodeGenTokenizer:et,CLIPTokenizer:tt,SiglipTokenizer:nt,MarianTokenizer:st,BloomTokenizer:Be,NllbTokenizer:Qe,M2M100Tokenizer:He,LlamaTokenizer:je,CodeLlamaTokenizer:Ne,XLMRobertaTokenizer:De,MPNetTokenizer:Re,FalconTokenizer:Ve,GPTNeoXTokenizer:Ge,EsmTokenizer:qe,Wav2Vec2CTCTokenizer:rt,BlenderbotTokenizer:ot,BlenderbotSmallTokenizer:it,SpeechT5Tokenizer:at,NougatTokenizer:lt,VitsTokenizer:ct,Qwen2Tokenizer:Ue,GemmaTokenizer:$e,Grok1Tokenizer:We,CohereTokenizer:dt,PreTrainedTokenizer:me};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:s=null,local_files_only:r=!1,revision:o="main",legacy:i=null}={}){const[a,l]=await d(e,{progress_callback:t,config:n,cache_dir:s,local_files_only:r,revision:o,legacy:i}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let u=this.TOKENIZER_CLASS_MAPPING[c];return u||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=me),new u(a,l)}}},"./src/utils/audio.js": /*!****************************!*\ !*** ./src/utils/audio.js ***! \****************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{hanning:()=>a,mel_filter_bank:()=>h,read_audio:()=>i,spectrogram:()=>_,window_function:()=>m});var s=n(/*! ./hub.js */"./src/utils/hub.js"),r=n(/*! ./maths.js */"./src/utils/maths.js"),o=n(/*! ./core.js */"./src/utils/core.js");async function i(e,t){if("undefined"==typeof AudioContext)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const n=await(await(0,s.getFile)(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);const o=await r.decodeAudioData(n);let i;if(2===o.numberOfChannels){const e=Math.sqrt(2),t=o.getChannelData(0),n=o.getChannelData(1);i=new Float32Array(t.length);for(let s=0;s2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,s=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*s:3*e/200};function c(e,t="htk"){const n=l[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}const d={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,s=Math.log(6.4)/27)=>e>=n?t*Math.exp(s*(e-n)):200*e/3};function u(e,t,n){const s=(t-e)/(n-1);return Float64Array.from({length:n},((t,n)=>e+s*n))}function h(e,t,n,s,r,o=null,i="htk",a=!1){if(null!==o&&"slaney"!==o)throw new Error('norm must be one of null or "slaney"');const l=u(c(n,i),c(s,i),t+2);let h,p=function(e,t="htk"){const n=d[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}(l,i);if(a){const t=r/(2*e);h=c(Float64Array.from({length:e},((e,n)=>n*t)),i),p=l}else h=u(0,Math.floor(r/2),e);const _=function(e,t){const n=Float64Array.from({length:t.length-1},((e,n)=>t[n+1]-t[n])),s=Array.from({length:e.length},(()=>new Array(t.length)));for(let n=0;nnew Array(e.length)));for(let t=0;ti)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(k!==n)throw new Error(`Length of the window (${k}) must equal frame_length (${n})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(l){if("reflect"!==c)throw new Error(`pad_mode="${c}" not implemented yet.`);const t=Math.floor((i-1)/2)+1;e=function(e,t,n){const s=new e.constructor(e.length+t+n),r=e.length-1;for(let n=0;nT?b&&(F=M):F=C=M);const P=new r.FFT(i),S=new Float64Array(i),A=new Float64Array(P.outputBufferSize),E=new Array(C);for(let r=0;r=1;--e)S[e]-=u*S[e-1];S[0]*=1-u}for(let e=0;eMath.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(n&&(i=i.subarray(0,e)),null===s)return i;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);return i}},"./src/utils/core.js": /*!***************************!*\ !*** ./src/utils/core.js ***! \***************************/(e,t,n)=>{"use strict";function s(e,t){e&&e(t)}function r(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[t,e])))}function o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(e){return"TypedArray"===e?.prototype?.__proto__?.constructor?.name}function a(e){return Number.isInteger(e)||"bigint"==typeof e}function l(e){const t=[];let n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function c(e,t,n=void 0){const s=e[t];if(void 0!==s)return delete e[t],s;if(void 0===n)throw Error(`Key ${t} does not exist in object.`);return n}function d(...e){return Array.prototype.concat.apply([],e)}function u(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function h(e,t){return Math.abs((e+t)%(2*t)-t)}function p(e,t){return Object.assign({},...t.map((t=>{if(void 0!==e[t])return{[t]:e[t]}})))}n.r(t),n.d(t,{calculateDimensions:()=>l,calculateReflectOffset:()=>h,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>a,isTypedArray:()=>i,mergeArrays:()=>d,pick:()=>p,pop:()=>c,product:()=>u,reverseDictionary:()=>r})},"./src/utils/data-structures.js": /*!**************************************!*\ !*** ./src/utils/data-structures.js ***! \**************************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{CharTrie:()=>r,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(e=((e,t)=>e>t)){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)this._heap.push(t),this._siftUp();return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return 1+(e<<1)}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[])),this.endNodes=Array.from({length:this.len+1},(()=>[]));const s=new a(this.bosTokenId,0,0,0,0),r=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(r.clone()),this.beginNodes[this.len].push(r),this.endNodes[0].push(s)}insert(e,t,n,s){const r=this.nodes.length,o=new a(s,r,e,t,n);this.beginNodes[e].push(o),this.endNodes[e+t].push(o),this.nodes.push(o)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(0==this.beginNodes[t].length)return[];for(let e of this.beginNodes[t]){e.prev=null;let n=0,s=null;for(let r of this.endNodes[t]){const t=r.backtraceScore+e.score;(null===s||t>n)&&(s=r.clone(),n=t)}if(null===s)return[];e.prev=s,e.backtraceScore=n}++t}const n=[],s=this.beginNodes[e][0].prev;if(null===s)return[];let r=s.clone();for(;null!==r.prev;){n.push(r.clone());const e=r.clone();r=e.prev.clone()}return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map((e=>this.piece(e)))}tokenIds(){return this.viterbi().map((e=>e.tokenId))}}class a{constructor(e,t,n,s,r){this.tokenId=e,this.nodeId=t,this.pos=n,this.length=s,this.score=r,this.prev=null,this.backtraceScore=0}clone(){const e=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}},"./src/utils/devices.js": /*!******************************!*\ !*** ./src/utils/devices.js ***! \******************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{DEVICE_TYPES:()=>s});const s=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"})},"./src/utils/dtypes.js": /*!*****************************!*\ !*** ./src/utils/dtypes.js ***! \*****************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isFp16Supported:()=>o});var s=n(/*! ../env.js */"./src/env.js"),r=n(/*! ./devices.js */"./src/utils/devices.js");const o=function(){let e;return async function(){if(void 0===e)if(s.apis.IS_NODE_ENV)e=!0;else if(s.apis.IS_WEBGPU_AVAILABLE)try{const t=await navigator.gpu.requestAdapter();e=t.features.has("shader-f16")}catch(t){e=!1}else e=!1;return e}}(),i=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8"}),a=Object.freeze({[r.DEVICE_TYPES.cpu]:i.q8,[r.DEVICE_TYPES.gpu]:i.fp32,[r.DEVICE_TYPES.wasm]:i.q8,[r.DEVICE_TYPES.webgpu]:i.fp32}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized"})},"./src/utils/generic.js": /*!******************************!*\ !*** ./src/utils/generic.js ***! \******************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{Callable:()=>s});const s=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")}}},"./src/utils/hub.js": /*!**************************!*\ !*** ./src/utils/hub.js ***! \**************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{getFile:()=>c,getModelFile:()=>h,getModelJSON:()=>p});var s=n(/*! fs */"?7a2c"),r=n(/*! path */"?a42a"),o=n(/*! ../env.js */"./src/env.js"),i=n(/*! ./core.js */"./src/utils/core.js");class a{_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=s.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=s.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(e){n.arrayBuffer().then((t=>{e.enqueue(new Uint8Array(t)),e.close()}))}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new a(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const e=await s.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function l(e,t=null){let n;try{n=new URL(e)}catch(e){return!1}return!(t&&!t.includes(n.hostname))&&("http:"===n.protocol||"https:"===n.protocol)}async function c(e){if(o.env.useFS&&!l(e))return new a(e);if("undefined"!=typeof process&&"node"===process?.release?.name){const t=!!process.env?.TESTING_REMOTELY,n=o.env.version,s=new Headers;s.set("User-Agent",`transformers.js/${n}; is_ci/${t};`);if(l(e,["huggingface.co","hf.co"])){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&s.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:s})}return fetch(e)}const d={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 u{constructor(e){this.path=e}async match(e){let t=r.join(this.path,e),n=new a(t);return n.exists?n:void 0}async put(e,t){const n=Buffer.from(await t.arrayBuffer());let o=r.join(this.path,e);try{await s.promises.mkdir(r.dirname(o),{recursive:!0}),await s.promises.writeFile(o,n)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function h(e,t,n=!0,s={}){if(!o.env.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let r;if((0,i.dispatchCallback)(s.progress_callback,{status:"initiate",name:e,file:t}),!r&&o.env.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{r=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!r&&o.env.useFSCache&&(r=new u(s.cache_dir??o.env.cacheDir)),!r&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");r=o.env.customCache}const a=s.revision??"main";let h,p,m=_(e,t),f=_(o.env.localModelPath,m),g=_(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(a)),t),w="main"===a?m:_(e,a,t),y=r instanceof u?w:g,M=!1;r&&(p=await async function(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch(e){continue}}(r,f,y));const b=void 0!==p;if(void 0===p){if(o.env.allowLocalModels){if(l(m)){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${m}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${m}.`)}else try{p=await c(f),h=f}catch(e){console.warn(`Unable to load from local path "${f}": "${e}"`)}}if(void 0===p||404===p.status){if(s.local_files_only||!o.env.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${f}".`);return null}if(p=await c(g),200!==p.status)return function(e,t,n){if(!n)return null;const s=d[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}(p.status,g,n);h=y}M=r&&"undefined"!=typeof Response&&p instanceof Response&&200===p.status}(0,i.dispatchCallback)(s.progress_callback,{status:"download",name:e,file:t});const x={status:"progress",name:e,file:t};let k;return s.progress_callback?b&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(k=new Uint8Array(await p.arrayBuffer()),(0,i.dispatchCallback)(s.progress_callback,{...x,progress:100,loaded:k.length,total:k.length})):k=await async function(e,t){const n=e.headers.get("Content-Length");null===n&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(n??"0"),r=new Uint8Array(s),o=0;const i=e.body.getReader();async function a(){const{done:e,value:n}=await i.read();if(e)return;let l=o+n.length;if(l>s){s=l;let e=new Uint8Array(s);e.set(r),r=e}r.set(n,o),o=l;return t({progress:o/s*100,loaded:o,total:s}),a()}return await a(),r}(p,(e=>{(0,i.dispatchCallback)(s.progress_callback,{...x,...e})})):k=new Uint8Array(await p.arrayBuffer()),M&&h&&void 0===await r.match(h)&&await r.put(h,new Response(k,{headers:p.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)})),(0,i.dispatchCallback)(s.progress_callback,{status:"done",name:e,file:t}),k}async function p(e,t,n=!0,s={}){let r=await h(e,t,n,s);if(null===r)return{};let o=new TextDecoder("utf-8").decode(r);return JSON.parse(o)}function _(...e){return(e=e.map(((t,n)=>(n&&(t=t.replace(new RegExp("^/"),"")),n!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)))).join("/")}},"./src/utils/image.js": /*!****************************!*\ !*** ./src/utils/image.js ***! \****************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{RawImage:()=>_});var s=n(/*! ./hub.js */"./src/utils/hub.js"),r=n(/*! ../env.js */"./src/env.js"),o=n(/*! ./tensor.js */"./src/utils/tensor.js"),i=n(/*! sharp */"?2b25");const a="undefined"!=typeof self,l=a&&"DedicatedWorkerGlobalScope"===self.constructor.name;let c,d,u;if(a)c=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},u=self.createImageBitmap,d=self.ImageData;else{if(!i)throw new Error("Unable to load image processing library.");u=async e=>{const t=(await e.metadata()).channels,{data:n,info:s}=await e.raw().toBuffer({resolveWithObject:!0}),r=new _(new Uint8ClampedArray(n),s.width,s.height,s.channels);return void 0!==t&&t!==s.channels&&r.convert(t),r}}const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},p=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(e,t,n,s){this.data=e,this.width=t,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(e){if(e instanceof _)return e;if("string"==typeof e||e instanceof URL)return await this.fromURL(e);throw new Error("Unsupported input type: "+typeof e)}static fromCanvas(e){if(!a)throw new Error("fromCanvas() is only supported in browser environments.");const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new _(t,e.width,e.height,4)}static async fromURL(e){const t=await(0,s.getFile)(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(a){const t=await u(e),n=c(t.width,t.height).getContext("2d");return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=i(await e.arrayBuffer());return await u(t)}}static fromTensor(e,t="CHW"){if(3!==e.dims.length)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if("CHW"===t)e=e.transpose(1,2,0);else if("HWC"!==t)throw new Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new _(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(1===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?a=n:d=-n,s>=0?l=s:u=-s,i.drawImage(o,a,l,e,t,d,u,e,t);return new _(i.getImageData(0,0,e,t).data,e,t,4).convert(r)}{let r=this.toSharp();if(n>=0&&s>=0)r=r.extract({left:Math.floor(n),top:Math.floor(s),width:e,height:t});else if(n<=0&&s<=0){const o=Math.floor(-s),i=Math.floor(-n);r=r.extend({top:o,left:i,right:e-this.width-i,bottom:t-this.height-o})}else{let o=[0,0],i=0;s<0?(o[0]=Math.floor(-s),o[1]=t-this.height-o[0]):i=Math.floor(s);let a=[0,0],l=0;n<0?(a[0]=Math.floor(-n),a[1]=e-this.width-a[0]):l=Math.floor(n),r=r.extend({top:o[0],bottom:o[1],left:a[0],right:a[1]}).extract({left:l,top:i,width:e,height:t})}return await u(r)}}async toBlob(e="image/png",t=1){if(!a)throw new Error("toBlob() is only supported in browser environments.");const n=this.toCanvas();return await n.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new o.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if("HWC"===e);else{if("CHW"!==e)throw new Error(`Unsupported channel format: ${e}`);t=t.permute(2,0,1)}return t}toCanvas(){if(!a)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=c(e.width,e.height),n=new d(e.data,e.width,e.height);return t.getContext("2d").putImageData(n,0,0),t}_update(e,t,n,s=null){return this.data=e,this.width=t,this.height=n,null!==s&&(this.channels=s),this}clone(){return new _(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 new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(!a){if(r.env.useFS){const t=this.toSharp();return await t.toFile(e)}throw new Error("Unable to save the image because filesystem is disabled in this environment.")}{if(l)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),n=p.get(t)??"image/png",s=await this.toBlob(n),r=URL.createObjectURL(s),o=document.createElement("a");o.href=r,o.download=e,o.click(),o.remove()}}toSharp(){if(a)throw new Error("toSharp() is only supported in server-side environments.");return i(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js": /*!****************************!*\ !*** ./src/utils/maths.js ***! \****************************/(e,t,n)=>{"use strict";function s(e,[t,n,s],[r,o],i="bilinear",a=!1){const l=o/s,c=r/n,d=new e.constructor(r*o*t),u=n*s,h=r*o;for(let i=0;i=0;--e)r[e]=o,s[e]=t[n[e]],o*=s[e];const o=n.map(((e,t)=>r[n.indexOf(t)])),i=new e.constructor(e.length);for(let n=0;n=0;--e)s+=r%t[e]*o[e],r=Math.floor(r/t[e]);i[s]=e[n]}return[i,s]}function o(e){const t=h(e)[0],n=e.map((e=>Math.exp(e-t))),s=n.reduce(((e,t)=>e+t),0);return n.map((e=>e/s))}function i(e){return o(e).map((e=>Math.log(e)))}function a(e,t){let n=0;for(let s=0;s[t,e])).sort(((e,t)=>t[1]-e[1])),null!==t&&t>0&&(e=e.slice(0,t)),e}function c(e,t){return a(e,t)/(d(e)*d(t))}function d(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}function u(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let s=1;st&&(t=e[s],n=s);return[Number(t),n]}function p(e){return e>0&&0==(e&e-1)}n.r(t),n.d(t,{FFT:()=>f,bankers_round:()=>y,cos_sim:()=>c,dot:()=>a,getTopItems:()=>l,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>d,max:()=>h,medianFilter:()=>g,min:()=>u,permute_data:()=>r,round:()=>w,softmax:()=>o});class _{constructor(e){if(this.size=0|e,this.size<=1||!p(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){const n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}completeSpectrum(e){const t=this._csize,n=t>>>1;for(let s=2;s>=2;i>=2;i>>=2){a=s/i<<1;const t=a>>>2;for(r=0;r>>1,i>>>1)}else for(r=0,o=0;r>>1,i>>>1,n)}for(i>>=2;i>=2;i>>=2){a=s/i<<1;const t=a>>>2;for(r=0;r>1;++t){const n=(t+1-e)**2/2,s=Math.sqrt(a**2+l**2)**n,i=n*Math.atan2(l,a),c=2*t;r[c]=s*Math.cos(i),r[c+1]=s*Math.sin(i),o[c]=r[c],o[c+1]=-r[c+1]}this._slicedChirpBuffer=r.subarray(t,n),this._f=new _(s>>1),this._f.transform(this._chirpBuffer,o)}_transform(e,t,n){const s=this._buffer1,r=this._buffer2,o=this._outBuffer1,i=this._outBuffer2,a=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(n)for(let e=0;e>1];s[e]=r*l[e],s[n]=r*l[n]}else for(let e=0;e=e.length&&(r=2*(e.length-1)-r),s[o++]=e[r]}s.sort(),n[t]=s[r]}return n}function w(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function y(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}},"./src/utils/tensor.js": /*!*****************************!*\ !*** ./src/utils/tensor.js ***! \*****************************/(e,t,n)=>{"use strict";n.r(t),n.d(t,{Tensor:()=>a,cat:()=>f,dynamicTimeWarping:()=>M,full:()=>x,full_like:()=>k,interpolate:()=>c,interpolate_4d:()=>d,layer_norm:()=>h,mean:()=>y,mean_pooling:()=>u,ones:()=>T,ones_like:()=>v,permute:()=>l,quantize_embeddings:()=>P,stack:()=>g,std_mean:()=>w,zeros:()=>C,zeros_like:()=>F});var s=n(/*! ./maths.js */"./src/utils/maths.js"),r=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),o=n(/*! ../ops/registry.js */"./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class a{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}ort_tensor;constructor(...e){return(0,r.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new r.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const n=t.reduce(((e,t)=>e*t));for(let s=0;s0){const t=n.reduce(((e,t)=>e*t));return this._subarray(e,t,n)}return new a(this.type,[this.data[e]],n)}indexOf(e){const t=this.data;for(let n=0;ne*t));if(n!==s)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce(((n,s)=>{let r=n[n.length-1];return r.lengthr[1])throw new Error(`Invalid slice: ${r}`);let e=[Math.max(r[0],0),Math.min(r[1],this.dims[s])];n.push(e),t.push(e[1]-e[0])}}}let s=n.map((([e,t])=>t-e)),r=s.reduce(((e,t)=>e*t));const o=this.data;let i=new o.constructor(r);const l=this.stride();for(let e=0;e=0;--r){const e=s[r];t+=(o%e+n[r][0])*l[r],o=Math.floor(o/e)}i[e]=o[t]}return new a(this.type,i,t)}permute(...e){return l(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const s=this.data;if(null===t){let t=s.reduce(((t,n)=>t+n**e),0)**(1/e);return new a(this.type,[t],[])}t=m(t,this.dims.length);const r=this.dims.slice();r[t]=1;const o=new s.constructor(s.length/this.dims[t]);for(let n=0;n=0;--e){const n=this.dims[e];if(e!==t){i+=s%n*o,o*=r[e]}s=Math.floor(s/n)}o[i]+=s[n]**e}if(1!==e)for(let t=0;t=0;--n){const e=this.dims[n];if(n!==t){r+=s%e*o,o*=this.dims[n]}s=Math.floor(s/e)}s[e]/=n.data[r]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){const t=new Array(e.length);for(let n=e.length-1,s=1;n>=0;--n)t[n]=s,s*=e[n];return t}(this.dims)}squeeze(e=null){return new a(this.type,this.data,p(this.dims,e))}squeeze_(e=null){return this.dims=p(this.dims,e),this}unsqueeze(e=null){return new a(this.type,this.data,_(this.dims,e))}unsqueeze_(e=null){return this.dims=_(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),s=this.dims.slice(e,t+1),r=this.dims.slice(t+1);return this.dims=[...n,s.reduce(((e,t)=>e*t),1),...r],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;ns!==t?e*n:e),1);e[t]=this.data.length/n}return new a(this.type,this.data,e)}neg_(){const e=this.data;for(let t=0;t1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,n)=>1!==e||!t.includes(n)))),e}function _(e,t){return t=m(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function m(e,t,n=null){if(e<-t||e>=t)throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function f(e,t=0){t=m(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce(((e,n)=>e+n.dims[t]),0);const s=n.reduce(((e,t)=>e*t),1),r=new e[0].data.constructor(s),o=e[0].type;if(0===t){let t=0;for(let n of e)r.set(n.data,t),t+=n.data.length}else{let s=0;for(let o=0;o=0;--r){const e=i.dims[r];let c=a%e;r===t&&(c+=s),o+=c*l,l*=n[r],a=Math.floor(a/e)}r[o]=i.data[e]}s+=i.dims[t]}}return new a(o,r,n)}function g(e,t=0){return f(e.map((e=>e.unsqueeze(t))),t)}function w(e,t=null,n=1,s=!1){if(null===t){const t=e.data.reduce(((e,t)=>e+t),0)/e.data.length,s=Math.sqrt(e.data.reduce(((e,n)=>e+(n-t)**2),0)/(e.data.length-n)),r=new a(e.type,[t],[]);return[new a(e.type,[s],[]),r]}const r=y(e,t=m(t,e.dims.length),s),o=e.dims.slice();o[t]=1;const i=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--r){const n=e.dims[r];if(r!==t){s+=i%n*a,a*=o[r]}i=Math.floor(i/n)}i[s]+=(e.data[n]-r.data[s])**2}for(let s=0;se+t),0);return new a(e.type,[t/e.data.length],[])}t=m(t,e.dims.length);const s=e.dims.slice();s[t]=1;const r=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--r){const n=e.dims[r];if(r!==t){o+=i%n*a,a*=s[r]}i=Math.floor(i/n)}r[o]+=e.data[n]}if(1!==e.dims[t])for(let n=0;n0||l>0;){c.push(i-1),d.push(l-1);switch(o[i][l].item()){case 0:--i,--l;break;case 1:--i;break;case 2:--l;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${l}]. Please file a bug report.`)}}return c.reverse(),d.reverse(),[c,d]}function b(e,t,n,s){const r=e.reduce(((e,t)=>e*t),1);return new a(n,new s(r).fill(t),e)}function x(e,t){let n,s;if("number"==typeof t)n="float32",s=Float32Array;else{if("bigint"!=typeof t)throw new Error("Unsupported data type: "+typeof t);n="int64",s=BigInt64Array}return b(e,t,n,s)}function k(e,t){return x(e.dims,t)}function T(e){return b(e,1n,"int64",BigInt64Array)}function v(e){return T(e.dims)}function C(e){return b(e,0n,"int64",BigInt64Array)}function F(e){return C(e.dims)}function P(e,t){if(2!==e.dims.length)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const n="binary"===t,s=n?"int8":"uint8",r=n?Int8Array:Uint8Array,o=e.data,i=new r(o.length/8);for(let e=0;e0?1:0,s=Math.floor(e/8),r=e%8;i[s]|=t<<7-r,n&&0===r&&(i[s]-=128)}return new a(s,i,[e.dims[0],e.dims[1]/8])}}},s={};function r(e){var t=s[e];if(void 0!==t)return t.exports;var o=s[e]={exports:{}};return n[e](o,o.exports,r),o.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(n,s){if(1&s&&(n=this(n)),8&s)return n;if("object"==typeof n&&n){if(4&s&&n.__esModule)return n;if(16&s&&"function"==typeof n.then)return n}var o=Object.create(null);r.r(o);var i={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>i[e]=()=>n[e]));return i.default=()=>n,r.d(o,i),o},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict"; /*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/r.r(o),r.d(o,{ASTFeatureExtractor:()=>i.ASTFeatureExtractor,ASTForAudioClassification:()=>n.ASTForAudioClassification,ASTModel:()=>n.ASTModel,ASTPreTrainedModel:()=>n.ASTPreTrainedModel,AlbertForMaskedLM:()=>n.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>n.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>n.AlbertForSequenceClassification,AlbertModel:()=>n.AlbertModel,AlbertPreTrainedModel:()=>n.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>a.AutoConfig,AutoModel:()=>n.AutoModel,AutoModelForAudioClassification:()=>n.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>n.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>n.AutoModelForCTC,AutoModelForCausalLM:()=>n.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>n.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>n.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>n.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>n.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>n.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>n.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>n.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>n.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>n.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>n.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>n.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>n.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>n.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>n.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>n.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>n.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>n.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>n.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>n.AutoModelForVision2Seq,AutoModelForXVector:()=>n.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>n.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>i.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>n.BartForConditionalGeneration,BartForSequenceClassification:()=>n.BartForSequenceClassification,BartModel:()=>n.BartModel,BartPretrainedModel:()=>n.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>n.BaseModelOutput,BaseStreamer:()=>h.BaseStreamer,BeitFeatureExtractor:()=>i.BeitFeatureExtractor,BeitForImageClassification:()=>n.BeitForImageClassification,BeitModel:()=>n.BeitModel,BeitPreTrainedModel:()=>n.BeitPreTrainedModel,BertForMaskedLM:()=>n.BertForMaskedLM,BertForQuestionAnswering:()=>n.BertForQuestionAnswering,BertForSequenceClassification:()=>n.BertForSequenceClassification,BertForTokenClassification:()=>n.BertForTokenClassification,BertModel:()=>n.BertModel,BertPreTrainedModel:()=>n.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>i.BitImageProcessor,BlenderbotForConditionalGeneration:()=>n.BlenderbotForConditionalGeneration,BlenderbotModel:()=>n.BlenderbotModel,BlenderbotPreTrainedModel:()=>n.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>n.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>n.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>n.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>n.BloomForCausalLM,BloomModel:()=>n.BloomModel,BloomPreTrainedModel:()=>n.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,CLIPModel:()=>n.CLIPModel,CLIPPreTrainedModel:()=>n.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>n.CLIPSegForImageSegmentation,CLIPSegModel:()=>n.CLIPSegModel,CLIPSegPreTrainedModel:()=>n.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>n.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModelWithProjection:()=>n.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>n.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>n.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>n.CamembertForSequenceClassification,CamembertForTokenClassification:()=>n.CamembertForTokenClassification,CamembertModel:()=>n.CamembertModel,CamembertPreTrainedModel:()=>n.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>n.CausalLMOutput,CausalLMOutputWithPast:()=>n.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>i.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>n.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>n.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>n.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>i.ClapFeatureExtractor,ClapModel:()=>n.ClapModel,ClapPreTrainedModel:()=>n.ClapPreTrainedModel,ClapTextModelWithProjection:()=>n.ClapTextModelWithProjection,CodeGenForCausalLM:()=>n.CodeGenForCausalLM,CodeGenModel:()=>n.CodeGenModel,CodeGenPreTrainedModel:()=>n.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>n.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>n.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>n.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>n.ConvBertForTokenClassification,ConvBertModel:()=>n.ConvBertModel,ConvBertPreTrainedModel:()=>n.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>i.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>n.ConvNextForImageClassification,ConvNextImageProcessor:()=>i.ConvNextImageProcessor,ConvNextModel:()=>n.ConvNextModel,ConvNextPreTrainedModel:()=>n.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>n.ConvNextV2ForImageClassification,ConvNextV2Model:()=>n.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>n.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>i.DPTFeatureExtractor,DPTForDepthEstimation:()=>n.DPTForDepthEstimation,DPTImageProcessor:()=>i.DPTImageProcessor,DPTModel:()=>n.DPTModel,DPTPreTrainedModel:()=>n.DPTPreTrainedModel,DebertaForMaskedLM:()=>n.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>n.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>n.DebertaForSequenceClassification,DebertaForTokenClassification:()=>n.DebertaForTokenClassification,DebertaModel:()=>n.DebertaModel,DebertaPreTrainedModel:()=>n.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>n.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>n.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>n.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>n.DebertaV2ForTokenClassification,DebertaV2Model:()=>n.DebertaV2Model,DebertaV2PreTrainedModel:()=>n.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>i.DeiTFeatureExtractor,DeiTForImageClassification:()=>n.DeiTForImageClassification,DeiTModel:()=>n.DeiTModel,DeiTPreTrainedModel:()=>n.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>n.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>n.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>i.DetrFeatureExtractor,DetrForObjectDetection:()=>n.DetrForObjectDetection,DetrForSegmentation:()=>n.DetrForSegmentation,DetrModel:()=>n.DetrModel,DetrObjectDetectionOutput:()=>n.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>n.DetrPreTrainedModel,DetrSegmentationOutput:()=>n.DetrSegmentationOutput,Dinov2ForImageClassification:()=>n.Dinov2ForImageClassification,Dinov2Model:()=>n.Dinov2Model,Dinov2PreTrainedModel:()=>n.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>n.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>n.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>n.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>n.DistilBertForTokenClassification,DistilBertModel:()=>n.DistilBertModel,DistilBertPreTrainedModel:()=>n.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>i.DonutFeatureExtractor,DonutSwinModel:()=>n.DonutSwinModel,DonutSwinPreTrainedModel:()=>n.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>n.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>i.EfficientNetImageProcessor,EfficientNetModel:()=>n.EfficientNetModel,EfficientNetPreTrainedModel:()=>n.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>n.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>n.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>n.ElectraForSequenceClassification,ElectraForTokenClassification:()=>n.ElectraForTokenClassification,ElectraModel:()=>n.ElectraModel,ElectraPreTrainedModel:()=>n.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EsmForMaskedLM:()=>n.EsmForMaskedLM,EsmForSequenceClassification:()=>n.EsmForSequenceClassification,EsmForTokenClassification:()=>n.EsmForTokenClassification,EsmModel:()=>n.EsmModel,EsmPreTrainedModel:()=>n.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,FFT:()=>u.FFT,FalconForCausalLM:()=>n.FalconForCausalLM,FalconModel:()=>n.FalconModel,FalconPreTrainedModel:()=>n.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>i.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,GLPNFeatureExtractor:()=>i.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>n.GLPNForDepthEstimation,GLPNModel:()=>n.GLPNModel,GLPNPreTrainedModel:()=>n.GLPNPreTrainedModel,GPT2LMHeadModel:()=>n.GPT2LMHeadModel,GPT2Model:()=>n.GPT2Model,GPT2PreTrainedModel:()=>n.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>n.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>n.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>n.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>n.GPTJForCausalLM,GPTJModel:()=>n.GPTJModel,GPTJPreTrainedModel:()=>n.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>n.GPTNeoForCausalLM,GPTNeoModel:()=>n.GPTNeoModel,GPTNeoPreTrainedModel:()=>n.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>n.GPTNeoXForCausalLM,GPTNeoXModel:()=>n.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>n.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,GemmaTokenizer:()=>s.GemmaTokenizer,Grok1Tokenizer:()=>s.Grok1Tokenizer,HerbertTokenizer:()=>s.HerbertTokenizer,HubertForCTC:()=>n.HubertForCTC,HubertForSequenceClassification:()=>n.HubertForSequenceClassification,HubertModel:()=>n.HubertModel,HubertPreTrainedModel:()=>n.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>i.ImageFeatureExtractor,ImageMattingOutput:()=>n.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,LlamaForCausalLM:()=>n.LlamaForCausalLM,LlamaModel:()=>n.LlamaModel,LlamaPreTrainedModel:()=>n.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>n.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>n.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>n.LongT5ForConditionalGeneration,LongT5Model:()=>n.LongT5Model,LongT5PreTrainedModel:()=>n.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>n.M2M100ForConditionalGeneration,M2M100Model:()=>n.M2M100Model,M2M100PreTrainedModel:()=>n.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>n.MBartForCausalLM,MBartForConditionalGeneration:()=>n.MBartForConditionalGeneration,MBartForSequenceClassification:()=>n.MBartForSequenceClassification,MBartModel:()=>n.MBartModel,MBartPreTrainedModel:()=>n.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>n.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>n.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>n.MPNetForSequenceClassification,MPNetForTokenClassification:()=>n.MPNetForTokenClassification,MPNetModel:()=>n.MPNetModel,MPNetPreTrainedModel:()=>n.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>n.MT5ForConditionalGeneration,MT5Model:()=>n.MT5Model,MT5PreTrainedModel:()=>n.MT5PreTrainedModel,MarianMTModel:()=>n.MarianMTModel,MarianModel:()=>n.MarianModel,MarianPreTrainedModel:()=>n.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,MaskedLMOutput:()=>n.MaskedLMOutput,MistralForCausalLM:()=>n.MistralForCausalLM,MistralModel:()=>n.MistralModel,MistralPreTrainedModel:()=>n.MistralPreTrainedModel,MobileBertForMaskedLM:()=>n.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>n.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>n.MobileBertForSequenceClassification,MobileBertModel:()=>n.MobileBertModel,MobileBertPreTrainedModel:()=>n.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileViTFeatureExtractor:()=>i.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>n.MobileViTForImageClassification,MobileViTModel:()=>n.MobileViTModel,MobileViTPreTrainedModel:()=>n.MobileViTPreTrainedModel,ModelOutput:()=>n.ModelOutput,MptForCausalLM:()=>n.MptForCausalLM,MptModel:()=>n.MptModel,MptPreTrainedModel:()=>n.MptPreTrainedModel,MusicgenForCausalLM:()=>n.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>n.MusicgenForConditionalGeneration,MusicgenModel:()=>n.MusicgenModel,MusicgenPreTrainedModel:()=>n.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NomicBertModel:()=>n.NomicBertModel,NomicBertPreTrainedModel:()=>n.NomicBertPreTrainedModel,NougatImageProcessor:()=>i.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>n.OPTForCausalLM,OPTModel:()=>n.OPTModel,OPTPreTrainedModel:()=>n.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OwlViTFeatureExtractor:()=>i.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>n.OwlViTForObjectDetection,OwlViTModel:()=>n.OwlViTModel,OwlViTPreTrainedModel:()=>n.OwlViTPreTrainedModel,OwlViTProcessor:()=>i.OwlViTProcessor,Owlv2ForObjectDetection:()=>n.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>i.Owlv2ImageProcessor,Owlv2Model:()=>n.Owlv2Model,Owlv2PreTrainedModel:()=>n.Owlv2PreTrainedModel,PhiForCausalLM:()=>n.PhiForCausalLM,PhiModel:()=>n.PhiModel,PhiPreTrainedModel:()=>n.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>n.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>a.PretrainedConfig,PretrainedMixin:()=>n.PretrainedMixin,Processor:()=>i.Processor,QuestionAnsweringModelOutput:()=>n.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>n.Qwen2ForCausalLM,Qwen2Model:()=>n.Qwen2Model,Qwen2PreTrainedModel:()=>n.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,RawImage:()=>c.RawImage,ResNetForImageClassification:()=>n.ResNetForImageClassification,ResNetModel:()=>n.ResNetModel,ResNetPreTrainedModel:()=>n.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>n.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>n.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>n.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>n.RoFormerForTokenClassification,RoFormerModel:()=>n.RoFormerModel,RoFormerPreTrainedModel:()=>n.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>n.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>n.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>n.RobertaForSequenceClassification,RobertaForTokenClassification:()=>n.RobertaForTokenClassification,RobertaModel:()=>n.RobertaModel,RobertaPreTrainedModel:()=>n.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>i.SamImageProcessor,SamImageSegmentationOutput:()=>n.SamImageSegmentationOutput,SamModel:()=>n.SamModel,SamPreTrainedModel:()=>n.SamPreTrainedModel,SamProcessor:()=>i.SamProcessor,SeamlessM4TFeatureExtractor:()=>i.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>i.SegformerFeatureExtractor,SegformerForImageClassification:()=>n.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>n.SegformerForSemanticSegmentation,SegformerModel:()=>n.SegformerModel,SegformerPreTrainedModel:()=>n.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>n.Seq2SeqLMOutput,SequenceClassifierOutput:()=>n.SequenceClassifierOutput,SiglipImageProcessor:()=>i.SiglipImageProcessor,SiglipModel:()=>n.SiglipModel,SiglipPreTrainedModel:()=>n.SiglipPreTrainedModel,SiglipTextModel:()=>n.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>n.SiglipVisionModel,SpeechT5FeatureExtractor:()=>i.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>n.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>n.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>n.SpeechT5HifiGan,SpeechT5Model:()=>n.SpeechT5Model,SpeechT5PreTrainedModel:()=>n.SpeechT5PreTrainedModel,SpeechT5Processor:()=>i.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>n.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>n.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>n.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>n.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>n.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>n.StableLmForCausalLM,StableLmModel:()=>n.StableLmModel,StableLmPreTrainedModel:()=>n.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>n.Starcoder2ForCausalLM,Starcoder2Model:()=>n.Starcoder2Model,Starcoder2PreTrainedModel:()=>n.Starcoder2PreTrainedModel,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>n.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>i.Swin2SRImageProcessor,Swin2SRModel:()=>n.Swin2SRModel,Swin2SRPreTrainedModel:()=>n.Swin2SRPreTrainedModel,SwinForImageClassification:()=>n.SwinForImageClassification,SwinModel:()=>n.SwinModel,SwinPreTrainedModel:()=>n.SwinPreTrainedModel,T5ForConditionalGeneration:()=>n.T5ForConditionalGeneration,T5Model:()=>n.T5Model,T5PreTrainedModel:()=>n.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>n.TableTransformerForObjectDetection,TableTransformerModel:()=>n.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>n.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>n.TableTransformerPreTrainedModel,Tensor:()=>d.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>n.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TrOCRForCausalLM:()=>n.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>n.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>n.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>n.UniSpeechForSequenceClassification,UniSpeechModel:()=>n.UniSpeechModel,UniSpeechPreTrainedModel:()=>n.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>n.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>n.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>n.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>n.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>n.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>i.ViTFeatureExtractor,ViTForImageClassification:()=>n.ViTForImageClassification,ViTImageProcessor:()=>i.ViTImageProcessor,ViTModel:()=>n.ViTModel,ViTPreTrainedModel:()=>n.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>n.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>n.VitMatteForImageMatting,VitMatteImageProcessor:()=>i.VitMatteImageProcessor,VitMattePreTrainedModel:()=>n.VitMattePreTrainedModel,VitsModel:()=>n.VitsModel,VitsModelOutput:()=>n.VitsModelOutput,VitsPreTrainedModel:()=>n.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>n.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>n.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>n.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>n.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>i.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>n.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>n.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>n.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>n.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>n.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>i.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>n.WavLMForAudioFrameClassification,WavLMForCTC:()=>n.WavLMForCTC,WavLMForSequenceClassification:()=>n.WavLMForSequenceClassification,WavLMForXVector:()=>n.WavLMForXVector,WavLMModel:()=>n.WavLMModel,WavLMPreTrainedModel:()=>n.WavLMPreTrainedModel,WhisperFeatureExtractor:()=>i.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>n.WhisperForConditionalGeneration,WhisperModel:()=>n.WhisperModel,WhisperPreTrainedModel:()=>n.WhisperPreTrainedModel,WhisperProcessor:()=>i.WhisperProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>n.XLMForQuestionAnswering,XLMForSequenceClassification:()=>n.XLMForSequenceClassification,XLMForTokenClassification:()=>n.XLMForTokenClassification,XLMModel:()=>n.XLMModel,XLMPreTrainedModel:()=>n.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>n.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>n.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>n.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>n.XLMRobertaForTokenClassification,XLMRobertaModel:()=>n.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>n.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>n.XLMWithLMHeadModel,XVectorOutput:()=>n.XVectorOutput,YolosFeatureExtractor:()=>i.YolosFeatureExtractor,YolosForObjectDetection:()=>n.YolosForObjectDetection,YolosModel:()=>n.YolosModel,YolosObjectDetectionOutput:()=>n.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>n.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>u.bankers_round,cat:()=>d.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamicTimeWarping:()=>d.dynamicTimeWarping,env:()=>e.env,full:()=>d.full,full_like:()=>d.full_like,getTopItems:()=>u.getTopItems,hanning:()=>l.hanning,interpolate:()=>d.interpolate,interpolate_4d:()=>d.interpolate_4d,interpolate_data:()=>u.interpolate_data,layer_norm:()=>d.layer_norm,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,max:()=>u.max,mean:()=>d.mean,mean_pooling:()=>d.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>l.mel_filter_bank,min:()=>u.min,ones:()=>d.ones,ones_like:()=>d.ones_like,permute:()=>d.permute,permute_data:()=>u.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>d.quantize_embeddings,read_audio:()=>l.read_audio,round:()=>u.round,softmax:()=>u.softmax,spectrogram:()=>l.spectrogram,stack:()=>d.stack,std_mean:()=>d.std_mean,window_function:()=>l.window_function,zeros:()=>d.zeros,zeros_like:()=>d.zeros_like});var e=r(/*! ./env.js */"./src/env.js"),t=r(/*! ./pipelines.js */"./src/pipelines.js"),n=r(/*! ./models.js */"./src/models.js"),s=r(/*! ./tokenizers.js */"./src/tokenizers.js"),i=r(/*! ./processors.js */"./src/processors.js"),a=r(/*! ./configs.js */"./src/configs.js"),l=r(/*! ./utils/audio.js */"./src/utils/audio.js"),c=r(/*! ./utils/image.js */"./src/utils/image.js"),d=r(/*! ./utils/tensor.js */"./src/utils/tensor.js"),u=r(/*! ./utils/maths.js */"./src/utils/maths.js"),h=r(/*! ./generation/streamers.js */"./src/generation/streamers.js")})();var i=exports;for(var a in o)i[a]=o[a];o.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})(); //# sourceMappingURL=transformers.min.cjs.map