@huggingface/transformers 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/dist/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/dist/transformers.cjs +1062 -183
- package/dist/transformers.cjs.map +1 -1
- package/dist/transformers.js +2239 -1232
- package/dist/transformers.js.map +1 -1
- package/dist/transformers.min.cjs +1 -358
- package/dist/transformers.min.cjs.map +1 -1
- package/dist/transformers.min.js +1 -421
- package/dist/transformers.min.js.map +1 -1
- package/dist/transformers.min.mjs +1 -358
- package/dist/transformers.min.mjs.map +1 -1
- package/dist/transformers.mjs +1082 -181
- package/dist/transformers.mjs.map +1 -1
- package/package.json +11 -16
- package/src/backends/onnx.js +2 -7
- package/src/base/image_processors_utils.js +3 -1
- package/src/configs.js +11 -2
- package/src/env.js +1 -1
- package/src/models/feature_extractors.js +1 -0
- package/src/models/idefics3/image_processing_idefics3.js +24 -13
- package/src/models/image_processors.js +1 -0
- package/src/models/moonshine/feature_extraction_moonshine.js +26 -0
- package/src/models/moonshine/processing_moonshine.js +20 -0
- package/src/models/paligemma/processing_paligemma.js +82 -0
- package/src/models/phi3_v/image_processing_phi3_v.js +163 -0
- package/src/models/phi3_v/processing_phi3_v.js +53 -0
- package/src/models/processors.js +3 -0
- package/src/models/pyannote/feature_extraction_pyannote.js +56 -0
- package/src/models/pyannote/processing_pyannote.js +7 -54
- package/src/models.js +233 -35
- package/src/ops/registry.js +11 -0
- package/src/pipelines.js +30 -0
- package/src/tokenizers.js +12 -1
- package/src/utils/core.js +39 -9
- package/src/utils/hub.js +8 -12
- package/src/utils/image.js +40 -0
- package/src/utils/tensor.js +51 -1
- package/types/backends/onnx.d.ts +2 -2
- package/types/backends/onnx.d.ts.map +1 -1
- package/types/base/feature_extraction_utils.d.ts +1 -1
- package/types/base/feature_extraction_utils.d.ts.map +1 -1
- package/types/base/image_processors_utils.d.ts +4 -4
- package/types/base/image_processors_utils.d.ts.map +1 -1
- package/types/base/processing_utils.d.ts +4 -4
- package/types/base/processing_utils.d.ts.map +1 -1
- package/types/configs.d.ts +7 -7
- package/types/configs.d.ts.map +1 -1
- package/types/env.d.ts +1 -1
- package/types/env.d.ts.map +1 -1
- package/types/generation/configuration_utils.d.ts +2 -2
- package/types/generation/logits_process.d.ts +2 -2
- package/types/generation/logits_process.d.ts.map +1 -1
- package/types/generation/logits_sampler.d.ts.map +1 -1
- package/types/generation/parameters.d.ts +5 -5
- package/types/generation/stopping_criteria.d.ts +1 -1
- package/types/generation/stopping_criteria.d.ts.map +1 -1
- package/types/generation/streamers.d.ts +2 -2
- package/types/generation/streamers.d.ts.map +1 -1
- package/types/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.d.ts +1 -1
- package/types/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.d.ts.map +1 -1
- package/types/models/auto/feature_extraction_auto.d.ts.map +1 -1
- package/types/models/auto/image_processing_auto.d.ts.map +1 -1
- package/types/models/auto/processing_auto.d.ts +1 -1
- package/types/models/auto/processing_auto.d.ts.map +1 -1
- package/types/models/clap/feature_extraction_clap.d.ts +1 -1
- package/types/models/clap/feature_extraction_clap.d.ts.map +1 -1
- package/types/models/detr/image_processing_detr.d.ts +11 -11
- package/types/models/detr/image_processing_detr.d.ts.map +1 -1
- package/types/models/donut/image_processing_donut.d.ts +1 -1
- package/types/models/donut/image_processing_donut.d.ts.map +1 -1
- package/types/models/feature_extractors.d.ts +1 -0
- package/types/models/florence2/processing_florence2.d.ts.map +1 -1
- package/types/models/idefics3/image_processing_idefics3.d.ts.map +1 -1
- package/types/models/idefics3/processing_idefics3.d.ts.map +1 -1
- package/types/models/image_processors.d.ts +1 -0
- package/types/models/janus/image_processing_janus.d.ts +1 -1
- package/types/models/janus/image_processing_janus.d.ts.map +1 -1
- package/types/models/janus/processing_janus.d.ts.map +1 -1
- package/types/models/maskformer/image_processing_maskformer.d.ts +8 -8
- package/types/models/maskformer/image_processing_maskformer.d.ts.map +1 -1
- package/types/models/mgp_str/processing_mgp_str.d.ts +2 -2
- package/types/models/mgp_str/processing_mgp_str.d.ts.map +1 -1
- package/types/models/moonshine/feature_extraction_moonshine.d.ts +13 -0
- package/types/models/moonshine/feature_extraction_moonshine.d.ts.map +1 -0
- package/types/models/moonshine/processing_moonshine.d.ts +17 -0
- package/types/models/moonshine/processing_moonshine.d.ts.map +1 -0
- package/types/models/owlvit/image_processing_owlvit.d.ts.map +1 -1
- package/types/models/paligemma/processing_paligemma.d.ts +12 -0
- package/types/models/paligemma/processing_paligemma.d.ts.map +1 -0
- package/types/models/phi3_v/image_processing_phi3_v.d.ts +17 -0
- package/types/models/phi3_v/image_processing_phi3_v.d.ts.map +1 -0
- package/types/models/phi3_v/processing_phi3_v.d.ts +17 -0
- package/types/models/phi3_v/processing_phi3_v.d.ts.map +1 -0
- package/types/models/processors.d.ts +3 -0
- package/types/models/pyannote/feature_extraction_pyannote.d.ts +18 -0
- package/types/models/pyannote/feature_extraction_pyannote.d.ts.map +1 -1
- package/types/models/pyannote/processing_pyannote.d.ts +4 -15
- package/types/models/pyannote/processing_pyannote.d.ts.map +1 -1
- package/types/models/qwen2_vl/processing_qwen2_vl.d.ts.map +1 -1
- package/types/models/rt_detr/image_processing_rt_detr.d.ts.map +1 -1
- package/types/models/sam/image_processing_sam.d.ts.map +1 -1
- package/types/models/seamless_m4t/feature_extraction_seamless_m4t.d.ts +1 -1
- package/types/models/seamless_m4t/feature_extraction_seamless_m4t.d.ts.map +1 -1
- package/types/models/segformer/image_processing_segformer.d.ts.map +1 -1
- package/types/models/speecht5/processing_speecht5.d.ts.map +1 -1
- package/types/models/swin2sr/image_processing_swin2sr.d.ts +1 -1
- package/types/models/swin2sr/image_processing_swin2sr.d.ts.map +1 -1
- package/types/models/vitmatte/image_processing_vitmatte.d.ts.map +1 -1
- package/types/models/vitpose/image_processing_vitpose.d.ts +1 -1
- package/types/models/vitpose/image_processing_vitpose.d.ts.map +1 -1
- package/types/models/wav2vec2/feature_extraction_wav2vec2.d.ts.map +1 -1
- package/types/models/wav2vec2/processing_wav2vec2.d.ts.map +1 -1
- package/types/models/wespeaker/feature_extraction_wespeaker.d.ts +1 -1
- package/types/models/wespeaker/feature_extraction_wespeaker.d.ts.map +1 -1
- package/types/models/whisper/feature_extraction_whisper.d.ts +1 -1
- package/types/models/whisper/feature_extraction_whisper.d.ts.map +1 -1
- package/types/models/whisper/generation_whisper.d.ts.map +1 -1
- package/types/models/whisper/processing_whisper.d.ts.map +1 -1
- package/types/models/yolos/image_processing_yolos.d.ts.map +1 -1
- package/types/models.d.ts +61 -5
- package/types/models.d.ts.map +1 -1
- package/types/ops/registry.d.ts +1 -0
- package/types/ops/registry.d.ts.map +1 -1
- package/types/pipelines.d.ts +31 -51
- package/types/pipelines.d.ts.map +1 -1
- package/types/tokenizers.d.ts +10 -6
- package/types/tokenizers.d.ts.map +1 -1
- package/types/utils/audio.d.ts.map +1 -1
- package/types/utils/constants.d.ts.map +1 -1
- package/types/utils/core.d.ts +87 -22
- package/types/utils/core.d.ts.map +1 -1
- package/types/utils/data-structures.d.ts.map +1 -1
- package/types/utils/devices.d.ts.map +1 -1
- package/types/utils/dtypes.d.ts.map +1 -1
- package/types/utils/generic.d.ts.map +1 -1
- package/types/utils/hub.d.ts +3 -3
- package/types/utils/hub.d.ts.map +1 -1
- package/types/utils/image.d.ts +10 -1
- package/types/utils/image.d.ts.map +1 -1
- package/types/utils/maths.d.ts +10 -10
- package/types/utils/maths.d.ts.map +1 -1
- package/types/utils/tensor.d.ts +22 -6
- package/types/utils/tensor.d.ts.map +1 -1
|
@@ -1,359 +1,2 @@
|
|
|
1
|
-
(()=>{var e,t,s={fs:
|
|
2
|
-
/*!*********************!*\
|
|
3
|
-
!*** external "fs" ***!
|
|
4
|
-
\*********************/e=>{"use strict";e.exports=require("fs")},"onnxruntime-node":
|
|
5
|
-
/*!***********************************!*\
|
|
6
|
-
!*** external "onnxruntime-node" ***!
|
|
7
|
-
\***********************************/e=>{"use strict";e.exports=require("onnxruntime-node")},path:
|
|
8
|
-
/*!***********************!*\
|
|
9
|
-
!*** external "path" ***!
|
|
10
|
-
\***********************/e=>{"use strict";e.exports=require("path")},sharp:
|
|
11
|
-
/*!************************!*\
|
|
12
|
-
!*** external "sharp" ***!
|
|
13
|
-
\************************/e=>{"use strict";e.exports=require("sharp")},url:
|
|
14
|
-
/*!**********************!*\
|
|
15
|
-
!*** external "url" ***!
|
|
16
|
-
\**********************/e=>{"use strict";e.exports=require("url")},"?cb4d":
|
|
17
|
-
/*!*************************************!*\
|
|
18
|
-
!*** #onnxruntime-webgpu (ignored) ***!
|
|
19
|
-
\*************************************/()=>{},"./node_modules/@huggingface/jinja/dist/index.js":
|
|
20
|
-
/*!*******************************************************!*\
|
|
21
|
-
!*** ./node_modules/@huggingface/jinja/dist/index.js ***!
|
|
22
|
-
\*******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Environment:()=>Y,Interpreter:()=>K,Template:()=>te,parse:()=>N,tokenize:()=>d});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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",Macro:"Macro",EndMacro:"EndMacro"}),n=Object.freeze({set:r.Set,for:r.For,in:r.In,is:r.Is,if:r.If,else:r.Else,endif:r.EndIf,elif:r.ElseIf,endfor:r.EndFor,and:r.And,or:r.Or,not:r.Not,"not in":r.NotIn,macro:r.Macro,endmacro:r.EndMacro,true:r.BooleanLiteral,false:r.BooleanLiteral,none:r.NullLiteral,True:r.BooleanLiteral,False:r.BooleanLiteral,None:r.NullLiteral}),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=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],c=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const s=[],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 p=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++],s=c.get(e);if(void 0===s)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=s}return t};e:for(;u<d.length;){const e=s.at(-1)?.type;if(void 0===e||e===r.CloseStatement||e===r.CloseExpression){let e="";for(;u<d.length&&("{"!==d[u]||"%"!==d[u+1]&&"{"!==d[u+1]);)e+=d[u++];if(e.length>0){s.push(new o(e,r.Text));continue}}p((e=>/\s/.test(e)));const t=d[u];if("-"===t||"+"===t){const e=s.at(-1)?.type;if(e===r.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case r.Identifier:case r.NumericLiteral:case r.BooleanLiteral:case r.NullLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++u;const e=p(a);s.push(new o(`${t}${e}`,e.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(u,u+e.length)===e){s.push(new o(e,t)),u+=e.length;continue e}}if("'"!==t&&'"'!==t)if(a(t)){const e=p(a);s.push(new o(e,r.NumericLiteral))}else{if(!i(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=p(i),t=Object.hasOwn(n,e)?n[e]:r.Identifier;t===r.In&&s.at(-1)?.type===r.Not?(s.pop(),s.push(new o("not in",r.NotIn))):s.push(new o(e,t))}}else{++u;const e=p((e=>e!==t));s.push(new o(e,r.StringLiteral)),++u}}return s}var u=class{type="Statement"},p=class extends u{constructor(e){super(),this.body=e}type="Program"},_=class extends u{constructor(e,t,s){super(),this.test=e,this.body=t,this.alternate=s}type="If"},m=class extends u{constructor(e,t,s,r){super(),this.loopvar=e,this.iterable=t,this.body=s,this.defaultBlock=r}type="For"},h=class extends u{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},f=class extends u{constructor(e,t,s){super(),this.name=e,this.args=t,this.body=s}type="Macro"},g=class extends u{type="Expression"},w=class extends g{constructor(e,t,s){super(),this.object=e,this.property=t,this.computed=s}type="MemberExpression"},M=class extends g{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},b=class extends g{constructor(e){super(),this.value=e}type="Identifier"},x=class extends g{constructor(e){super(),this.value=e}type="Literal"},y=class extends x{type="NumericLiteral"},k=class extends x{type="StringLiteral"},T=class extends x{type="BooleanLiteral"},v=class extends x{type="NullLiteral"},P=class extends x{type="ArrayLiteral"},F=class extends x{type="TupleLiteral"},C=class extends x{type="ObjectLiteral"},A=class extends g{constructor(e,t,s){super(),this.operator=e,this.left=t,this.right=s}type="BinaryExpression"},S=class extends g{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},E=class extends g{constructor(e,t){super(),this.iterable=e,this.test=t}type="SelectExpression"},L=class extends g{constructor(e,t,s){super(),this.operand=e,this.negate=t,this.test=s}type="TestExpression"},I=class extends g{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},z=class extends g{constructor(e=void 0,t=void 0,s=void 0){super(),this.start=e,this.stop=t,this.step=s}type="SliceExpression"},j=class extends g{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function N(e){const t=new p([]);let s=0;function n(t,r){const n=e[s++];if(!n||n.type!==t)throw new Error(`Parser Error: ${r}. ${n.type} !== ${t}.`);return n}function o(){switch(e[s].type){case r.Text:return new k(n(r.Text,"Expected text token").value);case r.OpenStatement:return function(){let t;switch(n(r.OpenStatement,"Expected opening statement token"),e[s].type){case r.Set:++s,t=l(),n(r.CloseStatement,"Expected closing statement token");break;case r.If:++s,t=c(),n(r.OpenStatement,"Expected {% token"),n(r.EndIf,"Expected endif token"),n(r.CloseStatement,"Expected %} token");break;case r.Macro:++s,t=function(){const e=q();if("Identifier"!==e.type)throw new SyntaxError("Expected identifier following macro statement");const t=D();n(r.CloseStatement,"Expected closing statement token");const s=[];for(;i(r.OpenStatement,r.EndMacro);)s.push(o());return new f(e,t,s)}(),n(r.OpenStatement,"Expected {% token"),n(r.EndMacro,"Expected endmacro token"),n(r.CloseStatement,"Expected %} token");break;case r.For:++s,t=function(){const e=d(!0);if(!(e instanceof b||e instanceof F))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);n(r.In,"Expected `in` keyword following loop variable");const t=u();n(r.CloseStatement,"Expected closing statement token");const l=[];for(;i(r.OpenStatement,r.EndFor)&&i(r.OpenStatement,r.Else);)l.push(o());const c=[];if(a(r.OpenStatement,r.Else))for(++s,++s,n(r.CloseStatement,"Expected closing statement token");i(r.OpenStatement,r.EndFor);)c.push(o());return new m(e,t,l,c)}(),n(r.OpenStatement,"Expected {% token"),n(r.EndFor,"Expected endfor token"),n(r.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[s].type}`)}return t}();case r.OpenExpression:return function(){n(r.OpenExpression,"Expected opening expression token");const e=u();return n(r.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[s].type}`)}}function i(...t){return s+t.length<=e.length&&t.some(((t,r)=>t!==e[s+r].type))}function a(...t){return s+t.length<=e.length&&t.every(((t,r)=>t===e[s+r].type))}function l(){const e=u();if(a(r.Equals)){++s;const t=l();return new h(e,t)}return e}function c(){const t=u();n(r.CloseStatement,"Expected closing statement token");const i=[],l=[];for(;e[s]?.type!==r.OpenStatement||e[s+1]?.type!==r.ElseIf&&e[s+1]?.type!==r.Else&&e[s+1]?.type!==r.EndIf;)i.push(o());if(e[s]?.type===r.OpenStatement&&e[s+1]?.type!==r.EndIf)if(++s,a(r.ElseIf))n(r.ElseIf,"Expected elseif token"),l.push(c());else for(n(r.Else,"Expected else token"),n(r.CloseStatement,"Expected closing statement token");e[s]?.type!==r.OpenStatement||e[s+1]?.type!==r.EndIf;)l.push(o());return new _(t,i,l)}function d(e=!1){const t=e?q:u,n=[t()],o=a(r.Comma);for(;o&&(++s,n.push(t()),a(r.Comma)););return o?new F(n):n[0]}function u(){return function(){const e=g();if(a(r.If)){++s;const t=g();if(a(r.Else)){++s;const r=g();return new _(t,[e],[r])}return new E(e,t)}return e}()}function g(){let t=x();for(;a(r.Or);){const r=e[s];++s;const n=x();t=new A(r,t,n)}return t}function x(){let t=N();for(;a(r.And);){const r=e[s];++s;const n=N();t=new A(r,t,n)}return t}function N(){let t;for(;a(r.Not);){const r=e[s];++s;const n=N();t=new I(r,n)}return t??function(){let t=O();for(;a(r.ComparisonBinaryOperator)||a(r.In)||a(r.NotIn);){const r=e[s];++s;const n=O();t=new A(r,t,n)}return t}()}function O(){let t=G();for(;a(r.AdditiveBinaryOperator);){const r=e[s];++s;const n=G();t=new A(r,t,n)}return t}function B(){const t=function(){let t=q();for(;a(r.Dot)||a(r.OpenSquareBracket);){const o=e[s];let i;++s;const a=o.type!==r.Dot;if(a)i=R(),n(r.CloseSquareBracket,"Expected closing square bracket");else if(i=q(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");t=new w(t,i,a)}return t}();return a(r.OpenParen)?V(t):t}function V(e){let t=new M(e,D());return a(r.OpenParen)&&(t=V(t)),t}function D(){n(r.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!a(r.CloseParen);){let t=u();if(a(r.Equals)){if(++s,!(t instanceof b))throw new SyntaxError("Expected identifier for keyword argument");const e=u();t=new j(t,e)}e.push(t),a(r.Comma)&&++s}return e}();return n(r.CloseParen,"Expected closing parenthesis for arguments list"),e}function R(){const e=[];let t=!1;for(;!a(r.CloseSquareBracket);)a(r.Colon)?(e.push(void 0),++s,t=!0):(e.push(u()),a(r.Colon)&&(++s,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 z(...e)}return e[0]}function G(){let t=$();for(;a(r.MultiplicativeBinaryOperator);){const r=e[s];++s;const n=$();t=new A(r,t,n)}return t}function $(){let e=function(){let e=B();for(;a(r.Pipe);){++s;let t=q();if(!(t instanceof b))throw new SyntaxError("Expected identifier for the filter");a(r.OpenParen)&&(t=V(t)),e=new S(e,t)}return e}();for(;a(r.Is);){++s;const t=a(r.Not);t&&++s;let n=q();if(n instanceof T?n=new b(n.value.toString()):n instanceof v&&(n=new b("none")),!(n instanceof b))throw new SyntaxError("Expected identifier for the test");e=new L(e,t,n)}return e}function q(){const t=e[s];switch(t.type){case r.NumericLiteral:return++s,new y(Number(t.value));case r.StringLiteral:return++s,new k(t.value);case r.BooleanLiteral:return++s,new T("true"===t.value.toLowerCase());case r.NullLiteral:return++s,new v(null);case r.Identifier:return++s,new b(t.value);case r.OpenParen:{++s;const t=d();if(e[s].type!==r.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[s].type} instead`);return++s,t}case r.OpenSquareBracket:{++s;const e=[];for(;!a(r.CloseSquareBracket);)e.push(u()),a(r.Comma)&&++s;return++s,new P(e)}case r.OpenCurlyBracket:{++s;const e=new Map;for(;!a(r.CloseCurlyBracket);){const t=u();n(r.Colon,"Expected colon between key and value in object literal");const o=u();e.set(t,o),a(r.Comma)&&++s}return++s,new C(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;s<e.length;)t.body.push(o());return t}function O(e,t,s=1){void 0===t&&(t=e,e=0);const r=[];for(let n=e;n<t;n+=s)r.push(n);return r}function B(e,t,s,r=1){const n=Math.sign(r);n>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),s=(s??=e.length)<0?Math.max(e.length+s,0):Math.min(s,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),s=(s??=-1)<-1?Math.max(e.length+s,-1):Math.min(s,e.length-1));const o=[];for(let i=t;n*i<n*s;i+=r)o.push(e[i]);return o}function V(e){return e.replace(/\b\w/g,(e=>e.toUpperCase()))}var D=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new $(!!this.value)}},R=class extends D{type="NumericValue"},G=class extends D{type="StringValue";builtins=new Map([["upper",new Q((()=>new G(this.value.toUpperCase())))],["lower",new Q((()=>new G(this.value.toLowerCase())))],["strip",new Q((()=>new G(this.value.trim())))],["title",new Q((()=>new G(V(this.value))))],["length",new R(this.value.length)],["rstrip",new Q((()=>new G(this.value.trimEnd())))],["lstrip",new Q((()=>new G(this.value.trimStart())))]])},$=class extends D{type="BooleanValue"},q=class extends D{type="ObjectValue";__bool__(){return new $(this.value.size>0)}builtins=new Map([["get",new Q((([e,t])=>{if(!(e instanceof G))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new H}))],["items",new Q((()=>new W(Array.from(this.value.entries()).map((([e,t])=>new W([new G(e),t]))))))]])},U=class extends q{type="KeywordArgumentsValue"},W=class extends D{type="ArrayValue";builtins=new Map([["length",new R(this.value.length)]]);__bool__(){return new $(this.value.length>0)}},X=class extends W{type="TupleValue"},Q=class extends D{type="FunctionValue"},H=class extends D{type="NullValue"},J=class extends D{type="UndefinedValue"},Y=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Q((e=>{if(0===e.length)return new q(new Map);if(1!==e.length||!(e[0]instanceof q))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 Q],["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],["none",e=>"NullValue"===e.type],["string",e=>"StringValue"===e.type],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>"ArrayValue"===e.type||"StringValue"===e.type],["mapping",e=>"ObjectValue"===e.type],["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],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Z(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 J}catch{return new J}}},K=class{global;constructor(e){this.global=e??new Y}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const s=this.evaluate(e.left,t);switch(e.operator.value){case"and":return s.__bool__().value?this.evaluate(e.right,t):s;case"or":return s.__bool__().value?s:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new $(s.value==r.value);case"!=":return new $(s.value!=r.value)}if(s instanceof J||r instanceof J)throw new Error("Cannot perform operation on undefined values");if(s instanceof H||r instanceof H)throw new Error("Cannot perform operation on null values");if(s instanceof R&&r instanceof R)switch(e.operator.value){case"+":return new R(s.value+r.value);case"-":return new R(s.value-r.value);case"*":return new R(s.value*r.value);case"/":return new R(s.value/r.value);case"%":return new R(s.value%r.value);case"<":return new $(s.value<r.value);case">":return new $(s.value>r.value);case">=":return new $(s.value>=r.value);case"<=":return new $(s.value<=r.value)}else if(s instanceof W&&r instanceof W){if("+"===e.operator.value)return new W(s.value.concat(r.value))}else if(r instanceof W){const t=void 0!==r.value.find((e=>e.value===s.value));switch(e.operator.value){case"in":return new $(t);case"not in":return new $(!t)}}if((s instanceof G||r instanceof G)&&"+"===e.operator.value)return new G(s.value.toString()+r.value.toString());if(s instanceof G&&r instanceof G)switch(e.operator.value){case"in":return new $(r.value.includes(s.value));case"not in":return new $(!r.value.includes(s.value))}if(s instanceof G&&r instanceof q)switch(e.operator.value){case"in":return new $(r.value.has(s.value));case"not in":return new $(!r.value.has(s.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${s.type} and ${r.type}`)}evaluateArguments(e,t){const s=[],r=new Map;for(const n of e)if("KeywordArgumentExpression"===n.type){const e=n;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");s.push(this.evaluate(n,t))}return[s,r]}evaluateFilterExpression(e,t){const s=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if("tojson"===t.value)return new G(ee(s));if(s instanceof W)switch(t.value){case"list":return s;case"first":return s.value[0];case"last":return s.value[s.value.length-1];case"length":return new R(s.value.length);case"reverse":return new W(s.value.reverse());case"sort":return new W(s.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(s instanceof G)switch(t.value){case"length":return new R(s.value.length);case"upper":return new G(s.value.toUpperCase());case"lower":return new G(s.value.toLowerCase());case"title":return new G(V(s.value));case"capitalize":return new G(s.value.charAt(0).toUpperCase()+s.value.slice(1));case"trim":return new G(s.value.trim());case"indent":return new G(s.value.split("\n").map(((e,t)=>0===t||0===e.length?e:" "+e)).join("\n"));case"string":return s;default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(s instanceof R){if("abs"===t.value)return new R(Math.abs(s.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(s instanceof q)switch(t.value){case"items":return new W(Array.from(s.value.entries()).map((([e,t])=>new W([new G(e),t]))));case"length":return new R(s.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${s.type}`)}if("CallExpression"===e.filter.type){const r=e.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const n=r.callee.value;if("tojson"===n){const[,e]=this.evaluateArguments(r.args,t),n=e.get("indent")??new H;if(!(n instanceof R||n instanceof H))throw new Error("If set, indent must be a number");return new G(ee(s,n.value))}if(s instanceof W){switch(n){case"selectattr":case"rejectattr":{const e="selectattr"===n;if(s.value.some((e=>!(e instanceof q))))throw new Error(`\`${n}\` can only be applied to array of objects`);if(r.args.some((e=>"StringLiteral"!==e.type)))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,a]=r.args.map((e=>this.evaluate(e,t)));let l;if(i){const e=t.tests.get(i.value);if(!e)throw new Error(`Unknown test: ${i.value}`);l=e}else l=(...e)=>e[0].__bool__().value;const c=s.value.filter((t=>{const s=t.value.get(o.value),r=!!s&&l(s,a);return e?r:!r}));return new W(c)}case"map":{const[,e]=this.evaluateArguments(r.args,t);if(e.has("attribute")){const t=e.get("attribute");if(!(t instanceof G))throw new Error("attribute must be a string");const r=e.get("default"),n=s.value.map((e=>{if(!(e instanceof q))throw new Error("items in map must be an object");return e.value.get(t.value)??r??new J}));return new W(n)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}if(s instanceof G){if("indent"===n){const[e,n]=this.evaluateArguments(r.args,t),o=e.at(0)??n.get("width")??new R(4);if(!(o instanceof R))throw new Error("width must be a number");const i=e.at(1)??n.get("first")??new $(!1),a=e.at(2)??n.get("blank")??new $(!1),l=s.value.split("\n"),c=" ".repeat(o.value),d=l.map(((e,t)=>!i.value&&0===t||!a.value&&0===e.length?e:c+e));return new G(d.join("\n"))}throw new Error(`Unknown StringValue filter: ${n}`)}throw new Error(`Cannot apply filter "${n}" to type: ${s.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const s=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const n=r(s);return new $(e.negate?!n:n)}evaluateUnaryExpression(e,t){const s=this.evaluate(e.argument,t);if("not"===e.operator.value)return new $(!s.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let s="";for(const r of e){const e=this.evaluate(r,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(s+=e.value)}return new G(s)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[s,r]=this.evaluateArguments(e.args,t);r.size>0&&s.push(new U(r));const n=this.evaluate(e.callee,t);if("FunctionValue"!==n.type)throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(s,t)}evaluateSliceExpression(e,t,s){if(!(e instanceof W||e instanceof G))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,s),n=this.evaluate(t.stop,s),o=this.evaluate(t.step,s);if(!(r instanceof R||r instanceof J))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof R||n instanceof J))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof R||o instanceof J))throw new Error("Slice step must be numeric or undefined");return e instanceof W?new W(B(e.value,r.value,n.value,o.value)):new G(B(Array.from(e.value),r.value,n.value,o.value).join(""))}evaluateMemberExpression(e,t){const s=this.evaluate(e.object,t);let r,n;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(s,e.property,t);r=this.evaluate(e.property,t)}else r=new G(e.property.value);if(s instanceof q){if(!(r instanceof G))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.value.get(r.value)??s.builtins.get(r.value)}else if(s instanceof W||s instanceof G)if(r instanceof R)n=s.value.at(r.value),s instanceof G&&(n=new G(s.value.at(r.value)));else{if(!(r instanceof G))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);n=s.builtins.get(r.value)}else{if(!(r instanceof G))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.builtins.get(r.value)}return n instanceof D?n:new J}evaluateSet(e,t){const s=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const r=e.assignee.value;t.setVariable(r,s)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const r=e.assignee,n=this.evaluate(r.object,t);if(!(n instanceof q))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");n.value.set(r.property.value,s)}}return new H}evaluateIf(e,t){const s=this.evaluate(e.test,t);return this.evaluateBlock(s.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const s=new Y(t);let r,n;if("SelectExpression"===e.iterable.type){const t=e.iterable;n=this.evaluate(t.iterable,s),r=t.test}else n=this.evaluate(e.iterable,s);if(!(n instanceof W))throw new Error(`Expected iterable type in for loop: got ${n.type}`);const o=[],i=[];for(let t=0;t<n.value.length;++t){const a=new Y(s),l=n.value[t];let c;if("Identifier"===e.loopvar.type)c=t=>t.setVariable(e.loopvar.value,l);else{if("TupleLiteral"!==e.loopvar.type)throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);{const t=e.loopvar;if("ArrayValue"!==l.type)throw new Error(`Cannot unpack non-iterable type: ${l.type}`);const s=l;if(t.value.length!==s.value.length)throw new Error(`Too ${t.value.length>s.value.length?"few":"many"} items to unpack`);c=e=>{for(let r=0;r<t.value.length;++r){if("Identifier"!==t.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,s.value[r])}}}}if(r){c(a);if(!this.evaluate(r,a).__bool__().value)continue}o.push(l),i.push(c)}let a="",l=!0;for(let t=0;t<o.length;++t){const r=new Map([["index",new R(t+1)],["index0",new R(t)],["revindex",new R(o.length-t)],["revindex0",new R(o.length-t-1)],["first",new $(0===t)],["last",new $(t===o.length-1)],["length",new R(o.length)],["previtem",t>0?o[t-1]:new J],["nextitem",t<o.length-1?o[t+1]:new J]]);s.setVariable("loop",new q(r)),i[t](s);a+=this.evaluateBlock(e.body,s).value,l=!1}if(l){a+=this.evaluateBlock(e.defaultBlock,s).value}return new G(a)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Q(((t,s)=>{const r=new Y(s);let n;t=t.slice(),"KeywordArgumentsValue"===t.at(-1)?.type&&(n=t.pop());for(let s=0;s<e.args.length;++s){const o=e.args[s],i=t[s];if("Identifier"===o.type){const e=o;if(!i)throw new Error(`Missing positional argument: ${e.value}`);r.setVariable(e.value,i)}else{if("KeywordArgumentExpression"!==o.type)throw new Error(`Unknown argument type: ${o.type}`);{const e=o,t=i??n?.value.get(e.key.value)??this.evaluate(e.value,r);r.setVariable(e.key.value,t)}}}return this.evaluateBlock(e.body,r)}))),new H}evaluate(e,t){if(void 0===e)return new J;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"NumericLiteral":return new R(Number(e.value));case"StringLiteral":return new G(e.value);case"BooleanLiteral":return new $(e.value);case"NullLiteral":return new H(e.value);case"ArrayLiteral":return new W(e.value.map((e=>this.evaluate(e,t))));case"TupleLiteral":return new X(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const s=new Map;for(const[r,n]of e.value){const e=this.evaluate(r,t);if(!(e instanceof G))throw new Error(`Object keys must be strings: got ${e.type}`);s.set(e.value,this.evaluate(n,t))}return new q(s)}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 Z(e){switch(typeof e){case"number":return new R(e);case"string":return new G(e);case"boolean":return new $(e);case"undefined":return new J;case"object":return null===e?new H:Array.isArray(e)?new W(e.map(Z)):new q(new Map(Object.entries(e).map((([e,t])=>[e,Z(t)]))));case"function":return new Q(((t,s)=>Z(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function ee(e,t,s){const r=s??0;switch(e.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(e.value);case"ArrayValue":case"ObjectValue":{const s=t?" ".repeat(t):"",n="\n"+s.repeat(r),o=n+s;if("ArrayValue"===e.type){const s=e.value.map((e=>ee(e,t,r+1)));return t?`[${o}${s.join(`,${o}`)}${n}]`:`[${s.join(", ")}]`}{const s=Array.from(e.value.entries()).map((([e,s])=>{const n=`"${e}": ${ee(s,t,r+1)}`;return t?`${o}${n}`:n}));return t?`{${s.join(",")}${n}}`:`{${s.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var te=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(t)}render(e){const t=new Y;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",O);for(const[s,r]of Object.entries(e))t.set(s,r);return new K(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":
|
|
23
|
-
/*!******************************************************************!*\
|
|
24
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***!
|
|
25
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{registerBackend:()=>o,resolveBackendAndExecutionProviders:()=>a});const r=new Map,n=[],o=(e,t,s)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{const o=r.get(e);if(void 0===o)r.set(e,{backend:t,priority:s});else{if(o.priority>s)return;if(o.priority===s&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){const t=n.indexOf(e);-1!==t&&n.splice(t,1);for(let t=0;t<n.length;t++)if(r.get(n[t]).priority<=s)return void n.splice(t,0,e);n.push(e)}}},i=async e=>{const t=r.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{const s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return s||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},a=async e=>{const t=e.executionProviders||[],s=t.map((e=>"string"==typeof e?e:e.name)),r=0===s.length?n:s;let o;const a=[],l=new Set;for(const e of r){const t=await i(e);"string"==typeof t?a.push({name:e,err:t}):(o||(o=t),o===t&&l.add(e))}if(!o)throw new Error(`no available backend found. ERR: ${a.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(const{name:e,err:t}of a)s.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);const c=t.filter((e=>l.has("string"==typeof e?e:e.name)));return[o,new Proxy(e,{get:(e,t)=>"executionProviders"===t?c:Reflect.get(e,t)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":
|
|
26
|
-
/*!*************************************************************!*\
|
|
27
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/backend.js ***!
|
|
28
|
-
\*************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{registerBackend:()=>r.registerBackend});var r=s(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":
|
|
29
|
-
/*!**************************************************************!*\
|
|
30
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/env-impl.js ***!
|
|
31
|
-
\**************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{env:()=>o});var r=s(/*! ./version.js */"./node_modules/onnxruntime-common/dist/esm/version.js");let n="warning";const o={wasm:{},webgl:{},webgpu:{},versions:{common:r.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}`);n=e}},get logLevel(){return n}};Object.defineProperty(o,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":
|
|
32
|
-
/*!*********************************************************!*\
|
|
33
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/env.js ***!
|
|
34
|
-
\*********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{env:()=>r});const r=s(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js").env},"./node_modules/onnxruntime-common/dist/esm/index.js":
|
|
35
|
-
/*!***********************************************************!*\
|
|
36
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/index.js ***!
|
|
37
|
-
\***********************************************************/(e,t,s)=>{"use strict";s.r(t),s.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:()=>n.env,registerBackend:()=>r.registerBackend});var r=s(/*! ./backend.js */"./node_modules/onnxruntime-common/dist/esm/backend.js"),n=s(/*! ./env.js */"./node_modules/onnxruntime-common/dist/esm/env.js"),o=s(/*! ./inference-session.js */"./node_modules/onnxruntime-common/dist/esm/inference-session.js"),i=s(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),a=(s(/*! ./tensor-conversion.js */"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),s(/*! ./tensor-factory.js */"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js"),s(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js")),l=(s(/*! ./onnx-model.js */"./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),s(/*! ./onnx-value.js */"./node_modules/onnxruntime-common/dist/esm/onnx-value.js"),s(/*! ./training-session.js */"./node_modules/onnxruntime-common/dist/esm/training-session.js"))},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":
|
|
38
|
-
/*!****************************************************************************!*\
|
|
39
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js ***!
|
|
40
|
-
\****************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{InferenceSession:()=>i});var r=s(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),n=s(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),o=s(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js");class i{constructor(e){this.handler=e}async run(e,t,s){(0,o.TRACE_FUNC_BEGIN)();const r={};let i={};if("object"!=typeof e||null===e||e instanceof n.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 n.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}.`);r[e]=null}if("object"==typeof s&&null!==s)i=s;else if(void 0!==s)throw new TypeError("'options' must be an object.")}else{let e=!1;const o=Object.getOwnPropertyNames(t);for(const s of this.outputNames)if(-1!==o.indexOf(s)){const o=t[s];(null===o||o instanceof n.Tensor)&&(e=!0,a=!1,r[s]=o)}if(e){if("object"==typeof s&&null!==s)i=s;else if(void 0!==s)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)r[e]=null;const l=await this.handler.run(e,r,i),c={};for(const e in l)if(Object.hasOwnProperty.call(l,e)){const t=l[e];t instanceof n.Tensor?c[e]=t:c[e]=new n.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,s,n){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 r=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>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(i=e.byteLength-o,"number"==typeof s){if(i=s,!Number.isSafeInteger(i))throw new RangeError("'byteLength' must be an integer.");if(i<=0||o+i>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-o}].`);if("object"==typeof n&&null!==n)l=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else if(void 0!==s)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");a=new Uint8Array(r,o,i)}}const[c,d]=await(0,r.resolveBackendAndExecutionProviders)(l),u=await c.createInferenceSessionHandler(a,d);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":
|
|
41
|
-
/*!***********************************************************************!*\
|
|
42
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/inference-session.js ***!
|
|
43
|
-
\***********************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{InferenceSession:()=>r});const r=s(/*! ./inference-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js").InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":
|
|
44
|
-
/*!****************************************************************!*\
|
|
45
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/onnx-model.js ***!
|
|
46
|
-
\****************************************************************/(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":
|
|
47
|
-
/*!****************************************************************!*\
|
|
48
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/onnx-value.js ***!
|
|
49
|
-
\****************************************************************/(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":
|
|
50
|
-
/*!****************************************************************************!*\
|
|
51
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js ***!
|
|
52
|
-
\****************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{tensorToDataURL:()=>r,tensorToImageData:()=>n});const r=(e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];const r=s.getContext("2d");if(null!=r){let n,o;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(n=e.dims[2],o=e.dims[3]):(n=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*n;let u=0,p=d,_=2*d,m=-1;"RGBA"===i?(u=0,p=d,_=2*d,m=3*d):"RGB"===i?(u=0,p=d,_=2*d):"RBG"===i&&(u=0,_=d,p=2*d);for(let t=0;t<o;t++)for(let s=0;s<n;s++){const n=(e.data[u++]-c[0])*l[0],o=(e.data[p++]-c[1])*l[1],i=(e.data[_++]-c[2])*l[2],a=-1===m?255:(e.data[m++]-c[3])*l[3];r.fillStyle="rgba("+n+","+o+","+i+","+a+")",r.fillRect(s,t,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},n=(e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(null==s)throw new Error("Can not access image data");{let n,o,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=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*n;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 p=4;let _=0,m=1,h=2,f=3,g=0,w=u,M=2*u,b=-1;"RGBA"===a?(g=0,w=u,M=2*u,b=3*u):"RGB"===a?(g=0,w=u,M=2*u):"RBG"===a&&(g=0,M=u,w=2*u),r=s.createImageData(n,o);for(let t=0;t<o*n;_+=p,m+=p,h+=p,f+=p,t++)r.data[_]=(e.data[g++]-d[0])*c[0],r.data[m]=(e.data[w++]-d[1])*c[1],r.data[h]=(e.data[M++]-d[2])*c[2],r.data[f]=-1===b?255:(e.data[b++]-d[3])*c[3]}return r}},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js":
|
|
53
|
-
/*!***********************************************************************!*\
|
|
54
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js ***!
|
|
55
|
-
\***********************************************************************/(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":
|
|
56
|
-
/*!*************************************************************************!*\
|
|
57
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js ***!
|
|
58
|
-
\*************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{bufferToTensor:()=>n,tensorFromGpuBuffer:()=>a,tensorFromImage:()=>o,tensorFromMLTensor:()=>l,tensorFromPinnedBuffer:()=>c,tensorFromTexture:()=>i});var r=s(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const n=(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:s,width:n}=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=s*n,u="RGBA"===c?new Float32Array(4*d):new Float32Array(3*d);let p=4,_=0,m=1,h=2,f=3,g=0,w=d,M=2*d,b=-1;"RGB"===l&&(p=3,_=0,m=1,h=2,f=-1),"RGBA"===c?b=3*d:"RBG"===c?(g=0,M=d,w=2*d):"BGR"===c&&(M=0,w=d,g=2*d);for(let t=0;t<d;t++,_+=p,h+=p,m+=p,f+=p)u[g++]=(e[_]+a[0])/i[0],u[w++]=(e[m]+a[1])/i[1],u[M++]=(e[h]+a[2])/i[2],-1!==b&&-1!==f&&(u[b++]=(e[f]+a[3])/i[3]);return"RGBA"===c?new r.Tensor("float32",u,[1,4,s,n]):new r.Tensor("float32",u,[1,3,s,n])},o=async(e,t)=>{const s="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,r="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=>"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(s){const s=c();s.width=e.width,s.height=e.height;const r=d(s);if(null==r)throw new Error("Can not access image data");{let s=e.height,n=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(s=t.resizedHeight,n=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=s,l.width=n}else l.tensorFormat="RGBA",l.height=s,l.width=n;r.drawImage(e,0,0),a=r.getImageData(0,0,n,s).data}}else{if(!r){if(o){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");const s=c();s.width=e.width,s.height=e.height;const r=d(s);if(null!=r){const t=e.height,s=e.width;return r.drawImage(e,0,0,s,t),a=r.getImageData(0,0,s,t).data,l.height=t,l.width=s,n(a,l)}throw new Error("Can not access image data")}if(i)return new Promise(((t,s)=>{const r=c(),o=d(r);if(!e||!o)return s();const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>{r.width=i.width,r.height=i.height,o.drawImage(i,0,0,r.width,r.height);const e=o.getImageData(0,0,r.width,r.height);l.height=r.height,l.width=r.width,t(n(e.data,l))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let s,r;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(s=t.resizedHeight,r=t.resizedWidth):(s=e.height,r=e.width),void 0!==t&&(l=t),l.format="RGBA",l.height=s,l.width=r,void 0!==t){const t=c();t.width=r,t.height=s;const n=d(t);if(null==n)throw new Error("Can not access image data");n.putImageData(e,0,0),a=n.getImageData(0,0,r,s).data}else a=e.data}}if(void 0!==a)return n(a,l);throw new Error("Input data provided is not supported - aborted tensor creation")},i=(e,t)=>{const{width:s,height:n,download:o,dispose:i}=t,a=[1,n,s,4];return new r.Tensor({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},a=(e,t)=>{const{dataType:s,dims:n,download:o,dispose:i}=t;return new r.Tensor({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},l=(e,t)=>{const{dataType:s,dims:n,download:o,dispose:i}=t;return new r.Tensor({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:i})},c=(e,t,s)=>new r.Tensor({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":
|
|
59
|
-
/*!********************************************************************!*\
|
|
60
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory.js ***!
|
|
61
|
-
\********************************************************************/(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":
|
|
62
|
-
/*!******************************************************************************!*\
|
|
63
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js ***!
|
|
64
|
-
\******************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>n,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>r,checkTypedArray:()=>i});const r=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),n=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&&BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&BigUint64Array.from,s="undefined"!=typeof Float16Array&&Float16Array.from;e&&(r.set("int64",BigInt64Array),n.set(BigInt64Array,"int64")),t&&(r.set("uint64",BigUint64Array),n.set(BigUint64Array,"uint64")),s?(r.set("float16",Float16Array),n.set(Float16Array,"float16")):r.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":
|
|
65
|
-
/*!*****************************************************************!*\
|
|
66
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl.js ***!
|
|
67
|
-
\*****************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>a});var r=s(/*! ./tensor-conversion-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),n=s(/*! ./tensor-factory-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),o=s(/*! ./tensor-impl-type-mapping.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),i=s(/*! ./tensor-utils-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class a{constructor(e,t,s){let r,n;if((0,o.checkTypedArray)(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,n=e.dims,e.location){case"cpu-pinned":{const t=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(r);if(!t)throw new TypeError(`unsupported type "${r}" 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"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint64"!==r&&"int8"!==r&&"uint8"!==r&&"bool"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,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(r=e,a=s,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{const s=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(void 0===s)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&s===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);i="uint64"===e||"int64"===e?s.from(t,BigInt):s.from(t)}else if(t instanceof s)i=t;else{if(!(t instanceof Uint8ClampedArray))throw new TypeError(`A ${r} tensor's data must be type of ${s}`);if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");i=Uint8Array.from(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)r="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",i=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)r="uint8",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}.`);r=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");n=a,this.cpuData=i,this.dataLocation="cpu"}const a=(0,i.calculateSize)(n);if(this.cpuData&&a!==this.cpuData.length&&("uint4"!==r&&"int4"!==r||Math.ceil(a/2)!==this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=n,this.size=a}static async fromImage(e,t){return(0,n.tensorFromImage)(e,t)}static fromTexture(e,t){return(0,n.tensorFromTexture)(e,t)}static fromGpuBuffer(e,t){return(0,n.tensorFromGpuBuffer)(e,t)}static fromMLTensor(e,t){return(0,n.tensorFromMLTensor)(e,t)}static fromPinnedBuffer(e,t,s){return(0,n.tensorFromPinnedBuffer)(e,t,s)}toDataURL(e){return(0,r.tensorToDataURL)(this,e)}toImageData(e){return(0,r.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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":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.mlTensorData=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":
|
|
68
|
-
/*!***********************************************************************!*\
|
|
69
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js ***!
|
|
70
|
-
\***********************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{calculateSize:()=>n,tensorReshape:()=>o});var r=s(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const n=e=>{let t=1;for(let s=0;s<e.length;s++){const r=e[s];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${s}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${r}`);t*=r}return t},o=(e,t)=>{switch(e.location){case"cpu":return new r.Tensor(e.type,e.data,t);case"cpu-pinned":return new r.Tensor({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new r.Tensor({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new r.Tensor({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new r.Tensor({location:"ml-tensor",mlTensor:e.mlTensor,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":
|
|
71
|
-
/*!************************************************************!*\
|
|
72
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/tensor.js ***!
|
|
73
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>r});const r=s(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js").Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":
|
|
74
|
-
/*!***********************************************************!*\
|
|
75
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/trace.js ***!
|
|
76
|
-
\***********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{TRACE:()=>n,TRACE_FUNC_BEGIN:()=>i,TRACE_FUNC_END:()=>a});var r=s(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js");const n=(e,t)=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&console.timeStamp(`${e}::ORT::${t}`)},o=(e,t)=>{const s=(new Error).stack?.split(/\r\n|\r|\n/g)||[];let r=!1;for(let o=0;o<s.length;o++){if(r&&!s[o].includes("TRACE_FUNC")){let r=`FUNC_${e}::${s[o].trim().split(" ")[1]}`;return t&&(r+=`::${t}`),void n("CPU",r)}s[o].includes("TRACE_FUNC")&&(r=!0)}},i=e=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&o("BEGIN",e)},a=e=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&o("END",e)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":
|
|
77
|
-
/*!***************************************************************************!*\
|
|
78
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/training-session-impl.js ***!
|
|
79
|
-
\***************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{TrainingSession:()=>o});var r=s(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),n=s(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js");class o{constructor(e,t,s){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=s}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 s=e.evalModel||"",n=e.optimizerModel||"",i=t||{},[a,l]=await(0,r.resolveBackendAndExecutionProviders)(i);if(a.createTrainingSessionHandler){const t=await a.createTrainingSessionHandler(e.checkpointState,e.trainModel,s,n,l);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,s,r,o){const i={};let a={};if("object"!=typeof s||null===s||s instanceof n.Tensor||Array.isArray(s))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 r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof n.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const e of r){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 s=Object.getOwnPropertyNames(r);for(const o of t)if(-1!==s.indexOf(o)){const t=r[o];(null===t||t instanceof n.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=r}}else if(void 0!==r)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of e)if(void 0===s[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 s in e)if(Object.hasOwnProperty.call(e,s)){const r=e[s];r instanceof n.Tensor?t[s]=r:t[s]=new n.Tensor(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,s){const[r,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,s),o=await this.handler.runTrainStep(e,r,n);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,s){if(this.hasEvalModel){const[r,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,s),o=await this.handler.runEvalStep(e,r,n);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 s=await this.getParametersSize(t);if(e.length!==4*s)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":
|
|
80
|
-
/*!**********************************************************************!*\
|
|
81
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/training-session.js ***!
|
|
82
|
-
\**********************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{TrainingSession:()=>r});const r=s(/*! ./training-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js").TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":
|
|
83
|
-
/*!*************************************************************!*\
|
|
84
|
-
!*** ./node_modules/onnxruntime-common/dist/esm/version.js ***!
|
|
85
|
-
\*************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{version:()=>r});const r="1.20.1"},"./src/backends/onnx.js":
|
|
86
|
-
/*!******************************!*\
|
|
87
|
-
!*** ./src/backends/onnx.js ***!
|
|
88
|
-
\******************************/(e,t,s)=>{"use strict";var r,n;s.r(t),s.d(t,{Tensor:()=>l.Tensor,createInferenceSession:()=>g,deviceToExecutionProviders:()=>h,isONNXProxy:()=>b,isONNXTensor:()=>w});var o=s(/*! ../env.js */"./src/env.js"),i=s(/*! onnxruntime-node */"onnxruntime-node"),a=s(/*! #onnxruntime-webgpu */"?cb4d"),l=s(/*! onnxruntime-common */"./node_modules/onnxruntime-common/dist/esm/index.js");const c=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),d=[];let u,p;const _=Symbol.for("onnxruntime");if(_ in globalThis)p=globalThis[_];else if(o.apis.IS_NODE_ENV){switch(p=i??(r||(r=s.t(i,2))),process.platform){case"win32":d.push("dml");break;case"linux":"x64"===process.arch&&d.push("cuda")}d.push("cpu"),u=["cpu"]}else p=n||(n=s.t(a,2)),o.apis.IS_WEBNN_AVAILABLE&&d.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&d.push("webgpu"),d.push("wasm"),u=["wasm"];const m=p.InferenceSession;function h(e=null){if(!e)return u;switch(e){case"auto":return d;case"gpu":return d.filter((e=>["webgpu","cuda","dml","webnn-gpu"].includes(e)))}if(d.includes(e))return[c[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${d.join(", ")}.`)}let f=null;async function g(e,t,s){f&&await f;const r=m.create(e,t);f??=r;const n=await r;return n.config=s,n}function w(e){return e instanceof p.Tensor}const M=p?.env;function b(){return M?.wasm?.proxy}M?.wasm&&(M.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`,M.wasm.proxy=!1,"undefined"!=typeof crossOriginIsolated&&crossOriginIsolated||(M.wasm.numThreads=1)),M?.webgpu&&(M.webgpu.powerPreference="high-performance"),o.env.backends.onnx=M},"./src/base/feature_extraction_utils.js":
|
|
89
|
-
/*!**********************************************!*\
|
|
90
|
-
!*** ./src/base/feature_extraction_utils.js ***!
|
|
91
|
-
\**********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var r=s(/*! ../utils/constants.js */"./src/utils/constants.js"),n=s(/*! ../utils/generic.js */"./src/utils/generic.js"),o=s(/*! ../utils/hub.js */"./src/utils/hub.js");class i extends n.Callable{constructor(e){super(),this.config=e}static async from_pretrained(e,t){return new this(await(0,o.getModelJSON)(e,r.FEATURE_EXTRACTOR_NAME,!0,t))}}function a(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.`)}},"./src/base/image_processors_utils.js":
|
|
92
|
-
/*!********************************************!*\
|
|
93
|
-
!*** ./src/base/image_processors_utils.js ***!
|
|
94
|
-
\********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ImageProcessor:()=>M,post_process_instance_segmentation:()=>w,post_process_object_detection:()=>p,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});var r=s(/*! ../utils/generic.js */"./src/utils/generic.js"),n=s(/*! ../utils/tensor.js */"./src/utils/tensor.js"),o=s(/*! ../utils/maths.js */"./src/utils/maths.js"),i=(s(/*! ../utils/image.js */"./src/utils/image.js"),s(/*! ../utils/core.js */"./src/utils/core.js")),a=s(/*! ../utils/hub.js */"./src/utils/hub.js"),l=s(/*! ../utils/constants.js */"./src/utils/constants.js");function c(e,t,s=0,r=null){const n=e/t;let i=(0,o.bankers_round)(n)*t;return null!==r&&i>r&&(i=Math.floor(n)*t),i<s&&(i=Math.ceil(n)*t),i}function d([e,t],s){return[Math.max(Math.floor(e/s),1)*s,Math.max(Math.floor(t/s),1)*s]}function u([e,t,s,r]){return[e-s/2,t-r/2,e+s/2,t+r/2]}function p(e,t=.5,s=null,r=!1){const n=e.logits,i=e.pred_boxes,[a,l,c]=n.dims;if(null!==s&&s.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let d=[];for(let e=0;e<a;++e){let a=null!==s?s[e]:null,p={boxes:[],classes:[],scores:[]},_=n[e],m=i[e];for(let e=0;e<l;++e){let s,n=_[e],i=[];if(r){s=n.sigmoid().data;for(let e=0;e<s.length;++e)s[e]>t&&i.push(e)}else{let e=(0,o.max)(n.data)[1];if(e===c-1)continue;if(s=(0,o.softmax)(n.data),s[e]<t)continue;i.push(e)}for(const t of i){let r=m[e].data;r=u(r),null!==a&&(r=r.map(((e,t)=>e*a[(t+1)%2]))),p.boxes.push(r),p.classes.push(t),p.scores.push(s[t])}}d.push(p)}return d}function _(e,t=null){const s=e.logits,r=s.dims[0];if(null!==t&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const o=[];for(let e=0;e<r;++e){const r=null!==t?t[e]:null;let i=s[e];null!==r&&(i=(0,n.interpolate)(i,r,"bilinear",!1));const[a,l]=r??i.dims.slice(-2),c=new n.Tensor("int32",new Int32Array(a*l),[a,l]),d=i[0].data,u=c.data;for(let e=1;e<i.dims[0];++e){const t=i[e].data;for(let s=0;s<t.length;++s)t[s]>d[s]&&(d[s]=t[s],u[s]=e)}const p=new Array(i.dims[0]);for(let e=0;e<u.length;++e){const t=u[e];p[t]=t}const _=p.filter((e=>void 0!==e));o.push({segmentation:c,labels:_})}return o}function m(e,t,s,r){const n=[],i=[],a=[];for(let l=0;l<e.dims[0];++l){const c=e[l],d=t[l],u=(0,o.max)(c.data)[1];if(u===r)continue;const p=(0,o.softmax)(c.data)[u];p>s&&(n.push(d),i.push(p),a.push(u))}return[n,i,a]}function h(e,t,s,r=.5,n=.8){const o=[];let i=0,a=0;const l=t[s].data;for(let t=0;t<e.length;++t)e[t]===s&&(o.push(t),++i),l[t]>=r&&++a;let c=i>0&&a>0;if(c){c=i/a>n}return[c,o]}function f(e,t,s,r,o,i=null,a=null){const[l,c]=a??e[0].dims,d=new n.Tensor("int32",new Int32Array(l*c),[l,c]),u=[];if(null!==a)for(let t=0;t<e.length;++t)e[t]=(0,n.interpolate)(e[t],a,"bilinear",!1);const p=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let s=0;s<e.length;++s){let r=t[s];const n=e[s].data;for(let e=0;e<n.length;++e)n[e]*=r,n[e]>_[e]&&(p[e]=s,_[e]=n[e])}let m=0;const f=d.data;for(let n=0;n<s.length;++n){const i=s[n],[a,l]=h(p,e,n,r,o);if(a){++m;for(const e of l)f[e]=m;u.push({id:m,label_id:i,score:t[n]})}}return[d,u]}function g(e,t=.5,s=.5,r=.8,o=null,i=null){null===o&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),o=new Set);const a=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,u]=a.dims;if(u-=1,null!==i&&i.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let p=[];for(let e=0;e<c;++e){let c=null!==i?i[e]:null,d=a[e],_=l[e],[h,g,w]=m(d,_,t,u);if(0===w.length){let[e,t]=c??_.dims.slice(-2),s=new n.Tensor("int32",new Int32Array(e*t).fill(-1),[e,t]);p.push({segmentation:s,segments_info:[]});continue}let[M,b]=f(h,g,w,s,r,o,c);p.push({segmentation:M,segments_info:b})}return p}function w(e,t=.5,s=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}class M extends r.Callable{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??void 0!==this.size,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.do_pad&&!this.pad_size&&this.size&&void 0!==this.size.width&&void 0!==this.size.height&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,s=2){const r=e.height,n=e.width,o=t.height,i=t.width;let a=Math.min(r,o),l=Math.min(n,i);return a===r&&l===n?e:(r>n?l=Math.floor(n*a/r):n>r&&(a=Math.floor(r*l/n)),await e.resize(l,a,{resample:s}))}async crop_margin(e,t=200){const s=e.clone().grayscale(),r=(0,o.min)(s.data)[0],n=(0,o.max)(s.data)[0]-r;if(0===n)return e;const i=t/255;let a=s.width,l=s.height,c=0,d=0;const u=s.data;for(let e=0;e<s.height;++e){const t=e*s.width;for(let o=0;o<s.width;++o)(u[t+o]-r)/n<i&&(a=Math.min(a,o),l=Math.min(l,e),c=Math.max(c,o),d=Math.max(d,e))}return e=await e.crop([a,l,c,d])}pad_image(e,t,s,{mode:r="constant",center:n=!1,constant_values:o=0}={}){const[a,l,c]=t;let d,u;if("number"==typeof s?(d=s,u=s):(d=s.width,u=s.height),d!==l||u!==a){const s=new Float32Array(d*u*c);if(Array.isArray(o))for(let e=0;e<s.length;++e)s[e]=o[e%c];else 0!==o&&s.fill(o);const[p,_]=n?[Math.floor((d-l)/2),Math.floor((u-a)/2)]:[0,0];for(let t=0;t<a;++t){const r=(t+_)*d,n=t*l;for(let t=0;t<l;++t){const o=(r+t+p)*c,i=(n+t)*c;for(let t=0;t<c;++t)s[o+t]=e[i+t]}}if("symmetric"===r){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const t=a-1,r=l-1;for(let n=0;n<u;++n){const o=n*d,u=(0,i.calculateReflectOffset)(n,t)*l;for(let t=0;t<d;++t){if(n<a&&t<l)continue;const d=(o+t)*c,p=(u+(0,i.calculateReflectOffset)(t,r))*c;for(let t=0;t<c;++t)s[d+t]=e[p+t]}}}e=s,t=[u,d,c]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[s,r]=e.size;let n,o;if(this.do_thumbnail){const{height:e,width:s}=t;n=Math.min(e,s)}else Number.isInteger(t)?(n=t,o=this.config.max_size??n):void 0!==t&&(n=t.shortest_edge,o=t.longest_edge);if(void 0!==n||void 0!==o){const e=void 0===n?1:Math.max(n/s,n/r),t=s*e,i=r*e,a=void 0===o?1:Math.min(o/t,o/i);let l=Math.floor(Number((t*a).toFixed(2))),c=Math.floor(Number((i*a).toFixed(2)));return void 0!==this.size_divisibility&&([l,c]=d([l,c],this.size_divisibility)),[l,c]}if(void 0!==t&&void 0!==t.width&&void 0!==t.height){let e=t.width,n=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=n/r,o=e/s;Math.abs(1-o)<Math.abs(1-t)?t=o:o=t,n=c(t*r,this.config.ensure_multiple_of),e=c(o*s,this.config.ensure_multiple_of)}return[e,n]}if(void 0!==this.size_divisibility)return d([s,r],this.size_divisibility);if(void 0!==t.min_pixels&&void 0!==t.max_pixels){const{min_pixels:e,max_pixels:n}=t;return function(e,t,s=28,r=3136,n=1003520){if(e<s||t<s)throw new Error(`height:${e} or width:${t} must be larger than factor:${s}`);if(Math.max(e,t)/Math.min(e,t)>200)throw new Error("absolute aspect ratio must be smaller than 200, got "+Math.max(e,t)/Math.min(e,t));let o=Math.round(e/s)*s,i=Math.round(t/s)*s;if(o*i>n){const r=Math.sqrt(e*t/n);o=Math.floor(e/r/s)*s,i=Math.floor(t/r/s)*s}else if(o*i<r){const n=Math.sqrt(r/(e*t));o=Math.ceil(e*n/s)*s,i=Math.ceil(t*n/s)*s}return[o,i]}(r,s,this.config.patch_size*this.config.merge_size,e,n)}throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}async resize(e){const[t,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,s,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:s=null,do_convert_rgb:r=null,do_convert_grayscale:o=null,do_flip_channel_order:i=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[a,l]=e.size;if(r??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let t,s;Number.isInteger(this.crop_size)?(t=this.crop_size,s=this.crop_size):(t=this.crop_size.width,s=this.crop_size.height),e=await e.center_crop(t,s)}const c=[e.height,e.width];let u=Float32Array.from(e.data),p=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(u),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=new Array(e.channels).fill(t));let s=this.image_std;if(Array.isArray(this.image_std)||(s=new Array(e.channels).fill(t)),t.length!==e.channels||s.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${t.length}) and \`image_std\` (${s.length}) must match the number of channels in the image (${e.channels}).`);for(let r=0;r<u.length;r+=e.channels)for(let n=0;n<e.channels;++n)u[r+n]=(u[r+n]-t[n])/s[n]}if(s??this.do_pad)if(this.pad_size){const t=this.pad_image(u,[e.height,e.width,e.channels],this.pad_size);[u,p]=t}else if(this.size_divisibility){const[e,t]=d([p[1],p[0]],this.size_divisibility);[u,p]=this.pad_image(u,p,{width:e,height:t})}if(i??this.do_flip_channel_order){if(3!==p[2])throw new Error("Flipping channel order is only supported for RGB images.");for(let e=0;e<u.length;e+=3){const t=u[e];u[e]=u[e+2],u[e+2]=t}}return{original_size:[l,a],reshaped_input_size:c,pixel_values:new n.Tensor("float32",u,p).permute(2,0,1)}}async _call(e,...t){Array.isArray(e)||(e=[e]);const s=await Promise.all(e.map((e=>this.preprocess(e))));return{pixel_values:(0,n.stack)(s.map((e=>e.pixel_values)),0),original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}static async from_pretrained(e,t){return new this(await(0,a.getModelJSON)(e,l.IMAGE_PROCESSOR_NAME,!0,t))}}},"./src/base/processing_utils.js":
|
|
95
|
-
/*!**************************************!*\
|
|
96
|
-
!*** ./src/base/processing_utils.js ***!
|
|
97
|
-
\**************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Processor:()=>i});var r=s(/*! ../utils/constants.js */"./src/utils/constants.js"),n=s(/*! ../utils/generic.js */"./src/utils/generic.js"),o=s(/*! ../utils/hub.js */"./src/utils/hub.js");class i extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(e,t){super(),this.config=e,this.components=t}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}async _call(e,...t){for(const s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t){const[s,n]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(e,r.PROCESSOR_NAME,!0,t):{},Promise.all(this.classes.filter((e=>e in this)).map((async s=>{const r=await this[s].from_pretrained(e,t);return[s.replace(/_class$/,""),r]}))).then(Object.fromEntries)]);return new this(s,n)}}},"./src/configs.js":
|
|
98
|
-
/*!************************!*\
|
|
99
|
-
!*** ./src/configs.js ***!
|
|
100
|
-
\************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoConfig:()=>l,PretrainedConfig:()=>a,getKeyValueShapes:()=>i});var r=s(/*! ./utils/core.js */"./src/utils/core.js"),n=s(/*! ./utils/hub.js */"./src/utils/hub.js");function o(e){const t={};let s={};switch(e.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":s=o(e.text_config);break;case"moondream1":s=o(e.phi_config);break;case"musicgen":s=o(e.decoder);break;case"multi_modality":s=o(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"llama":case"olmo":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const n=o(e.decoder),i="num_decoder_layers"in n,a=(0,r.pick)(e,["model_type","is_encoder_decoder"]);return i?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}const n={...s,...(0,r.pick)(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function i(e,{prefix:t="past_key_values",batch_size:s=1}={}){const r={},n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){const e=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,o=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[s,n.num_encoder_heads,0,e],a=[s,n.num_decoder_heads,0,o];for(let e=0;e<n.num_decoder_layers;++e)r[`${t}.${e}.encoder.key`]=i,r[`${t}.${e}.encoder.value`]=i,r[`${t}.${e}.decoder.key`]=a,r[`${t}.${e}.decoder.value`]=a}else{const e=n.num_heads,o=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??e);if("falcon"===n.model_type){const n=[s*e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=n}else if(n.multi_query){const n=[s*e,0,2*i];for(let e=0;e<o;++e)r[`${t}.${e}.key_value`]=n}else if("bloom"===n.model_type){const n=[s*e,i,0],a=[s*e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=a}else if("openelm"===n.model_type)for(let n=0;n<o;++n){const o=[s,e[n],0,i];r[`${t}.${n}.key`]=o,r[`${t}.${n}.value`]=o}else{const n=[s,e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=n}}return r}class a{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=o(this)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main"}={}){!s||s instanceof a||(s=new a(s));const l=s??await async function(e,t){return await(0,n.getModelJSON)(e,"config.json",!0,t)}(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:o,revision:i});return new this(l)}}class l{static async from_pretrained(...e){return a.from_pretrained(...e)}}},"./src/env.js":
|
|
101
|
-
/*!********************!*\
|
|
102
|
-
!*** ./src/env.js ***!
|
|
103
|
-
\********************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{apis:()=>h,env:()=>b});var r=s(/*! fs */"fs"),n=s(/*! path */"path"),o=s(/*! url */"url");const i="undefined"!=typeof window&&void 0!==window.document,a="undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor?.name,l="undefined"!=typeof self&&"caches"in self,c="undefined"!=typeof navigator&&"gpu"in navigator,d="undefined"!=typeof navigator&&"ml"in navigator,u="undefined"!=typeof process,p=u&&"node"===process?.release?.name,_=!x(r),m=!x(n),h=Object.freeze({IS_BROWSER_ENV:i,IS_WEBWORKER_ENV:a,IS_WEB_CACHE_AVAILABLE:l,IS_WEBGPU_AVAILABLE:c,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:p,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:m}),f=_&&m;let g="./";if(f){const e=Object({}).url;e?g=n.dirname(n.dirname(o.fileURLToPath(e))):"undefined"!=typeof __dirname&&(g=n.dirname(__dirname))}const w=f?n.join(g,"/.cache/"):null,M="/models/",b={version:"3.1.1",backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(i||a),localModelPath:f?n.join(g,M):M,useFS:_,useBrowserCache:l,useFSCache:_,cacheDir:w,useCustomCache:!1,customCache:null};function x(e){return 0===Object.keys(e).length}},"./src/generation/configuration_utils.js":
|
|
104
|
-
/*!***********************************************!*\
|
|
105
|
-
!*** ./src/generation/configuration_utils.js ***!
|
|
106
|
-
\***********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{GenerationConfig:()=>n});var r=s(/*! ../utils/core.js */"./src/utils/core.js");class n{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;streamer=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,r.pick)(e,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":
|
|
107
|
-
/*!******************************************!*\
|
|
108
|
-
!*** ./src/generation/logits_process.js ***!
|
|
109
|
-
\******************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>m,MinNewTokensLengthLogitsProcessor:()=>h,NoBadWordsLogitsProcessor:()=>f,NoRepeatNGramLogitsProcessor:()=>p,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>d,TemperatureLogitsWarper:()=>w,TopKLogitsWarper:()=>b,TopPLogitsWarper:()=>M,WhisperTimeStampLogitsProcessor:()=>u});var r=s(/*! ../utils/generic.js */"./src/utils/generic.js"),n=(s(/*! ../utils/tensor.js */"./src/utils/tensor.js"),s(/*! ../utils/maths.js */"./src/utils/maths.js"));class o extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class i extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class a extends r.Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let s=t;for(const t of this.processors)s=t(e,s);return s}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let s=0;s<e.length;++s)if(1===e[s].length){const e=t[s].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}}class c extends o{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){const e=t[s].data;e.fill(-1/0);for(const t of this.eos_token_id)e[t]=0}return t}}class d extends o{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){const e=t[s].data;for(const t of this.begin_suppress_tokens)e[t]=-1/0}return t}}class u extends o{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;if(r[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){r.fill(-1/0),r[this.timestamp_begin]=0;continue}const o=e[s].slice(this.begin_index),i=o.length>=1&&o[o.length-1]>=this.timestamp_begin,a=o.length<2||o[o.length-2]>=this.timestamp_begin;if(i&&(a?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&null!==this.max_initial_timestamp_index){const e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}const l=(0,n.log_softmax)(r);Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)))>(0,n.max)(l.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class p extends o{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,s=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){const t=[];for(let s=0;s<this.no_repeat_ngram_size;++s)t.push(e[r+s]);s.push(t.map(Number))}const r=new Map;for(const e of s){const t=e.slice(0,e.length-1),s=JSON.stringify(t),n=r.get(s)??[];n.push(e[e.length-1]),r.set(s,n)}return r}getGeneratedNgrams(e,t){const s=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=this.calcBannedNgramTokens(e[s]);for(const e of n)r[e]=-1/0}return t}}class _ extends o{constructor(e){super(),this.penalty=e}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;for(const t of new Set(e[s])){const e=Number(t);r[e]<0?r[e]*=this.penalty:r[e]/=this.penalty}}return t}}class m extends o{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}return t}}class h extends o{constructor(e,t,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,t){for(let s=0;s<e.length;++s){if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}}return t}}class f extends o{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=e[s];for(const e of this.bad_words_ids){let t=!0;for(let s=1;s<=e.length-1&&e.length<n.length;++s)if(e.at(-s-1)!=n.at(-s)){t=!1;break}t&&(r[e.at(-1)]=-1/0)}}return t}}class g extends o{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 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 s=e.length,r=t.slice([0,s],null),n=t.slice([s,t.dims[0]],null);for(let e=0;e<n.data.length;++e)n.data[e]+=(r.data[e]-n.data[e])*this.guidance_scale;return n}}class w extends i{constructor(e){if(super(),"number"!=typeof e||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;0===e&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){const s=t.data;for(let e=0;e<s.length;++e)s[e]/=this.temperature;return t}}class M extends i{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=s}}class b extends i{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=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,s),this.filter_value=t}}},"./src/generation/logits_sampler.js":
|
|
110
|
-
/*!******************************************!*\
|
|
111
|
-
!*** ./src/generation/logits_sampler.js ***!
|
|
112
|
-
\******************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{LogitsSampler:()=>i});var r=s(/*! ../utils/generic.js */"./src/utils/generic.js"),n=s(/*! ../utils/tensor.js */"./src/utils/tensor.js"),o=s(/*! ../utils/maths.js */"./src/utils/maths.js");s(/*! ../generation/configuration_utils.js */"./src/generation/configuration_utils.js");class i extends r.Callable{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let s=e.dims.at(-1),r=e.data;if(-1===t)r=r.slice(-s);else{let e=t*s;r=r.slice(e,e+s)}return r}randomSelect(e){let t=0;for(let s=0;s<e.length;++s)t+=e[s];let s=Math.random()*t;for(let t=0;t<e.length;++t)if(s-=e[t],s<=0)return t;return 0}static getSampler(e){if(e.do_sample)return new l(e);if(e.num_beams>1)return new c(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 a(e)}}class a extends i{async sample(e){const t=(0,o.max)(e.data)[1];return[[BigInt(t),0]]}}class l extends i{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await(0,n.topk)(e,t),i=(0,o.softmax)(s.data);return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]}))}}class c extends i{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await(0,n.topk)(e,t),i=(0,o.softmax)(s.data);return Array.from({length:this.generation_config.num_beams},((e,t)=>[r.data[t],Math.log(i[t])]))}}},"./src/generation/stopping_criteria.js":
|
|
113
|
-
/*!*********************************************!*\
|
|
114
|
-
!*** ./src/generation/stopping_criteria.js ***!
|
|
115
|
-
\*********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var r=s(/*! ../utils/generic.js */"./src/utils/generic.js");class n extends r.Callable{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class o extends r.Callable{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof o?e=e.criteria:e instanceof n&&(e=[e]),this.criteria.push(...e)}_call(e,t){const s=new Array(e.length).fill(!1);for(const r of this.criteria){const n=r(e,t);for(let e=0;e<s.length;++e)s[e]||=n[e]}return s}[Symbol.iterator](){return this.criteria.values()}}class i extends n{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map((e=>e.length>=this.max_length))}}class a extends n{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map((e=>{const t=e.at(-1);return this.eos_token_id.some((e=>t==e))}))}}class l extends n{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}}},"./src/generation/streamers.js":
|
|
116
|
-
/*!*************************************!*\
|
|
117
|
-
!*** ./src/generation/streamers.js ***!
|
|
118
|
-
\*************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var r=s(/*! ../utils/core.js */"./src/utils/core.js"),n=s(/*! ../tokenizers.js */"./src/tokenizers.js"),o=s(/*! ../env.js */"./src/env.js");class i{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=o.apis.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e);class l extends i{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:r=null,decode_kwargs:n={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=s??a,this.token_callback_function=r,this.decode_kwargs={...n,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt)return void(this.next_tokens_are_prompt=!1);const t=e[0];this.token_callback_function?.(t),this.token_cache=(0,r.mergeArrays)(this.token_cache,t);const s=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let o;s.endsWith("\n")?(o=s.slice(this.print_len),this.token_cache=[],this.print_len=0):s.length>0&&(0,n.is_chinese_char)(s.charCodeAt(s.length-1))?(o=s.slice(this.print_len),this.print_len+=o.length):(o=s.slice(this.print_len,s.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;if(this.token_cache.length>0){e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0}else e="";this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===a&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.("\n")}}class c extends l{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:r=null,on_chunk_start:n=null,on_chunk_end:o=null,on_finalize:i=null,time_precision:a=.02,skip_special_tokens:l=!0,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,callback_function:s,token_callback_function:r,decode_kwargs:{skip_special_tokens:l,...c}}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=n,this.on_chunk_end=o,this.on_finalize=i,this.time_precision=a,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const t=e[0];if(1===t.length){const s=Number(t[0])-this.timestamp_begin;if(s>=0){const t=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(t):this.on_chunk_start?.(t),this.waiting_for_timestamp=!this.waiting_for_timestamp,e=[[]]}}return super.put(e)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":
|
|
119
|
-
/*!***********************!*\
|
|
120
|
-
!*** ./src/models.js ***!
|
|
121
|
-
\***********************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTForAudioClassification:()=>cs,ASTModel:()=>ls,ASTPreTrainedModel:()=>as,AlbertForMaskedLM:()=>wt,AlbertForQuestionAnswering:()=>gt,AlbertForSequenceClassification:()=>ft,AlbertModel:()=>ht,AlbertPreTrainedModel:()=>mt,AutoModel:()=>bl,AutoModelForAudioClassification:()=>Vl,AutoModelForAudioFrameClassification:()=>Rl,AutoModelForCTC:()=>Bl,AutoModelForCausalLM:()=>Fl,AutoModelForDepthEstimation:()=>Ul,AutoModelForDocumentQuestionAnswering:()=>Gl,AutoModelForImageClassification:()=>El,AutoModelForImageFeatureExtraction:()=>Ql,AutoModelForImageMatting:()=>$l,AutoModelForImageSegmentation:()=>Ll,AutoModelForImageToImage:()=>ql,AutoModelForMaskGeneration:()=>Ol,AutoModelForMaskedLM:()=>Cl,AutoModelForNormalEstimation:()=>Wl,AutoModelForObjectDetection:()=>jl,AutoModelForPoseEstimation:()=>Xl,AutoModelForQuestionAnswering:()=>Al,AutoModelForSemanticSegmentation:()=>Il,AutoModelForSeq2SeqLM:()=>kl,AutoModelForSequenceClassification:()=>xl,AutoModelForSpeechSeq2Seq:()=>Tl,AutoModelForTextToSpectrogram:()=>vl,AutoModelForTextToWaveform:()=>Pl,AutoModelForTokenClassification:()=>yl,AutoModelForUniversalSegmentation:()=>zl,AutoModelForVision2Seq:()=>Sl,AutoModelForXVector:()=>Dl,AutoModelForZeroShotObjectDetection:()=>Nl,BartForConditionalGeneration:()=>St,BartForSequenceClassification:()=>Et,BartModel:()=>At,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>J,BeitForImageClassification:()=>In,BeitModel:()=>Ln,BeitPreTrainedModel:()=>En,BertForMaskedLM:()=>Z,BertForQuestionAnswering:()=>se,BertForSequenceClassification:()=>ee,BertForTokenClassification:()=>te,BertModel:()=>K,BertPreTrainedModel:()=>Y,BlenderbotForConditionalGeneration:()=>Vt,BlenderbotModel:()=>Bt,BlenderbotPreTrainedModel:()=>Ot,BlenderbotSmallForConditionalGeneration:()=>Gt,BlenderbotSmallModel:()=>Rt,BlenderbotSmallPreTrainedModel:()=>Dt,BloomForCausalLM:()=>Ur,BloomModel:()=>qr,BloomPreTrainedModel:()=>$r,CLIPModel:()=>ks,CLIPPreTrainedModel:()=>ys,CLIPSegForImageSegmentation:()=>Ds,CLIPSegModel:()=>Vs,CLIPSegPreTrainedModel:()=>Bs,CLIPTextModel:()=>Ts,CLIPTextModelWithProjection:()=>vs,CLIPVisionModel:()=>Ps,CLIPVisionModelWithProjection:()=>Fs,CamembertForMaskedLM:()=>ve,CamembertForQuestionAnswering:()=>Ce,CamembertForSequenceClassification:()=>Pe,CamembertForTokenClassification:()=>Fe,CamembertModel:()=>Te,CamembertPreTrainedModel:()=>ke,CausalLMOutput:()=>tc,CausalLMOutputWithPast:()=>sc,ChineseCLIPModel:()=>Is,ChineseCLIPPreTrainedModel:()=>Ls,ClapAudioModelWithProjection:()=>Hi,ClapModel:()=>Xi,ClapPreTrainedModel:()=>Wi,ClapTextModelWithProjection:()=>Qi,CodeGenForCausalLM:()=>ar,CodeGenModel:()=>ir,CodeGenPreTrainedModel:()=>or,CohereForCausalLM:()=>yr,CohereModel:()=>xr,CoherePreTrainedModel:()=>br,ConvBertForMaskedLM:()=>_e,ConvBertForQuestionAnswering:()=>fe,ConvBertForSequenceClassification:()=>me,ConvBertForTokenClassification:()=>he,ConvBertModel:()=>pe,ConvBertPreTrainedModel:()=>ue,ConvNextForImageClassification:()=>Eo,ConvNextModel:()=>So,ConvNextPreTrainedModel:()=>Ao,ConvNextV2ForImageClassification:()=>zo,ConvNextV2Model:()=>Io,ConvNextV2PreTrainedModel:()=>Lo,DPTForDepthEstimation:()=>po,DPTModel:()=>uo,DPTPreTrainedModel:()=>co,DebertaForMaskedLM:()=>Ee,DebertaForQuestionAnswering:()=>ze,DebertaForSequenceClassification:()=>Le,DebertaForTokenClassification:()=>Ie,DebertaModel:()=>Se,DebertaPreTrainedModel:()=>Ae,DebertaV2ForMaskedLM:()=>Oe,DebertaV2ForQuestionAnswering:()=>De,DebertaV2ForSequenceClassification:()=>Be,DebertaV2ForTokenClassification:()=>Ve,DebertaV2Model:()=>Ne,DebertaV2PreTrainedModel:()=>je,DecisionTransformerModel:()=>va,DecisionTransformerPreTrainedModel:()=>Ta,DeiTForImageClassification:()=>Jn,DeiTModel:()=>Hn,DeiTPreTrainedModel:()=>Qn,DepthAnythingForDepthEstimation:()=>mo,DepthAnythingPreTrainedModel:()=>_o,DepthProForDepthEstimation:()=>bo,DepthProPreTrainedModel:()=>Mo,DetrForObjectDetection:()=>Nn,DetrForSegmentation:()=>On,DetrModel:()=>jn,DetrObjectDetectionOutput:()=>Bn,DetrPreTrainedModel:()=>zn,DetrSegmentationOutput:()=>Vn,Dinov2ForImageClassification:()=>Oo,Dinov2Model:()=>No,Dinov2PreTrainedModel:()=>jo,DistilBertForMaskedLM:()=>We,DistilBertForQuestionAnswering:()=>Ue,DistilBertForSequenceClassification:()=>$e,DistilBertForTokenClassification:()=>qe,DistilBertModel:()=>Ge,DistilBertPreTrainedModel:()=>Re,DonutSwinModel:()=>Co,DonutSwinPreTrainedModel:()=>Fo,EfficientNetForImageClassification:()=>aa,EfficientNetModel:()=>ia,EfficientNetPreTrainedModel:()=>oa,ElectraForMaskedLM:()=>Me,ElectraForQuestionAnswering:()=>ye,ElectraForSequenceClassification:()=>be,ElectraForTokenClassification:()=>xe,ElectraModel:()=>we,ElectraPreTrainedModel:()=>ge,EsmForMaskedLM:()=>He,EsmForSequenceClassification:()=>Je,EsmForTokenClassification:()=>Ye,EsmModel:()=>Qe,EsmPreTrainedModel:()=>Xe,FalconForCausalLM:()=>Ui,FalconModel:()=>qi,FalconPreTrainedModel:()=>$i,FastViTForImageClassification:()=>fn,FastViTModel:()=>hn,FastViTPreTrainedModel:()=>mn,Florence2ForConditionalGeneration:()=>Ms,Florence2PreTrainedModel:()=>ws,GLPNForDepthEstimation:()=>Po,GLPNModel:()=>vo,GLPNPreTrainedModel:()=>To,GPT2LMHeadModel:()=>$s,GPT2Model:()=>Gs,GPT2PreTrainedModel:()=>Rs,GPTBigCodeForCausalLM:()=>nr,GPTBigCodeModel:()=>rr,GPTBigCodePreTrainedModel:()=>sr,GPTJForCausalLM:()=>tr,GPTJModel:()=>er,GPTJPreTrainedModel:()=>Zs,GPTNeoForCausalLM:()=>Hs,GPTNeoModel:()=>Qs,GPTNeoPreTrainedModel:()=>Xs,GPTNeoXForCausalLM:()=>Ks,GPTNeoXModel:()=>Ys,GPTNeoXPreTrainedModel:()=>Js,Gemma2ForCausalLM:()=>Cr,Gemma2Model:()=>Fr,Gemma2PreTrainedModel:()=>Pr,GemmaForCausalLM:()=>vr,GemmaModel:()=>Tr,GemmaPreTrainedModel:()=>kr,GraniteForCausalLM:()=>Mr,GraniteModel:()=>wr,GranitePreTrainedModel:()=>gr,GroupViTModel:()=>_n,GroupViTPreTrainedModel:()=>pn,HieraForImageClassification:()=>Zn,HieraModel:()=>Kn,HieraPreTrainedModel:()=>Yn,HubertForCTC:()=>yi,HubertForSequenceClassification:()=>ki,HubertModel:()=>xi,HubertPreTrainedModel:()=>bi,Idefics3ForConditionalGeneration:()=>xs,Idefics3PreTrainedModel:()=>bs,ImageMattingOutput:()=>rc,JAISLMHeadModel:()=>Ws,JAISModel:()=>Us,JAISPreTrainedModel:()=>qs,JinaCLIPModel:()=>js,JinaCLIPPreTrainedModel:()=>zs,JinaCLIPTextModel:()=>Ns,JinaCLIPVisionModel:()=>Os,LlamaForCausalLM:()=>dr,LlamaModel:()=>cr,LlamaPreTrainedModel:()=>lr,LlavaForConditionalGeneration:()=>hs,LlavaOnevisionForConditionalGeneration:()=>fs,LlavaPreTrainedModel:()=>ms,LongT5ForConditionalGeneration:()=>Tt,LongT5Model:()=>kt,LongT5PreTrainedModel:()=>yt,M2M100ForConditionalGeneration:()=>Jo,M2M100Model:()=>Ho,M2M100PreTrainedModel:()=>Qo,MBartForCausalLM:()=>Nt,MBartForConditionalGeneration:()=>zt,MBartForSequenceClassification:()=>jt,MBartModel:()=>It,MBartPreTrainedModel:()=>Lt,MPNetForMaskedLM:()=>ot,MPNetForQuestionAnswering:()=>lt,MPNetForSequenceClassification:()=>it,MPNetForTokenClassification:()=>at,MPNetModel:()=>nt,MPNetPreTrainedModel:()=>rt,MT5ForConditionalGeneration:()=>Ft,MT5Model:()=>Pt,MT5PreTrainedModel:()=>vt,MarianMTModel:()=>Xo,MarianModel:()=>Wo,MarianPreTrainedModel:()=>Uo,MaskFormerForInstanceSegmentation:()=>ko,MaskFormerModel:()=>yo,MaskFormerPreTrainedModel:()=>xo,MaskedLMOutput:()=>Zl,MgpstrForSceneTextRecognition:()=>Sa,MgpstrModelOutput:()=>Ca,MgpstrPreTrainedModel:()=>Aa,MistralForCausalLM:()=>Vi,MistralModel:()=>Bi,MistralPreTrainedModel:()=>Oi,MobileBertForMaskedLM:()=>et,MobileBertForQuestionAnswering:()=>st,MobileBertForSequenceClassification:()=>tt,MobileBertModel:()=>Ze,MobileBertPreTrainedModel:()=>Ke,MobileLLMForCausalLM:()=>_r,MobileLLMModel:()=>pr,MobileLLMPreTrainedModel:()=>ur,MobileNetV1ForImageClassification:()=>ma,MobileNetV1Model:()=>_a,MobileNetV1PreTrainedModel:()=>pa,MobileNetV2ForImageClassification:()=>ga,MobileNetV2Model:()=>fa,MobileNetV2PreTrainedModel:()=>ha,MobileNetV3ForImageClassification:()=>ba,MobileNetV3Model:()=>Ma,MobileNetV3PreTrainedModel:()=>wa,MobileNetV4ForImageClassification:()=>ka,MobileNetV4Model:()=>ya,MobileNetV4PreTrainedModel:()=>xa,MobileViTForImageClassification:()=>xn,MobileViTModel:()=>bn,MobileViTPreTrainedModel:()=>Mn,MobileViTV2ForImageClassification:()=>Tn,MobileViTV2Model:()=>kn,MobileViTV2PreTrainedModel:()=>yn,ModelOutput:()=>H,Moondream1ForConditionalGeneration:()=>gs,MptForCausalLM:()=>Qr,MptModel:()=>Xr,MptPreTrainedModel:()=>Wr,MultiModalityCausalLM:()=>Fa,MultiModalityPreTrainedModel:()=>Pa,MusicgenForCausalLM:()=>da,MusicgenForConditionalGeneration:()=>ua,MusicgenModel:()=>ca,MusicgenPreTrainedModel:()=>la,NomicBertModel:()=>ne,NomicBertPreTrainedModel:()=>re,OPTForCausalLM:()=>Yr,OPTModel:()=>Jr,OPTPreTrainedModel:()=>Hr,OlmoForCausalLM:()=>fr,OlmoModel:()=>hr,OlmoPreTrainedModel:()=>mr,OpenELMForCausalLM:()=>Er,OpenELMModel:()=>Sr,OpenELMPreTrainedModel:()=>Ar,OwlViTForObjectDetection:()=>Fn,OwlViTModel:()=>Pn,OwlViTPreTrainedModel:()=>vn,Owlv2ForObjectDetection:()=>Sn,Owlv2Model:()=>An,Owlv2PreTrainedModel:()=>Cn,PatchTSMixerForPrediction:()=>Na,PatchTSMixerModel:()=>ja,PatchTSMixerPreTrainedModel:()=>za,PatchTSTForPrediction:()=>Ia,PatchTSTModel:()=>La,PatchTSTPreTrainedModel:()=>Ea,Phi3ForCausalLM:()=>Gr,Phi3Model:()=>Rr,Phi3PreTrainedModel:()=>Dr,PhiForCausalLM:()=>Vr,PhiModel:()=>Br,PhiPreTrainedModel:()=>Or,PreTrainedModel:()=>Q,PretrainedMixin:()=>Oa,PvtForImageClassification:()=>on,PvtModel:()=>nn,PvtPreTrainedModel:()=>rn,PyAnnoteForAudioFrameClassification:()=>ni,PyAnnoteModel:()=>ri,PyAnnotePreTrainedModel:()=>si,QuestionAnsweringModelOutput:()=>ec,Qwen2ForCausalLM:()=>zr,Qwen2Model:()=>Ir,Qwen2PreTrainedModel:()=>Lr,Qwen2VLForConditionalGeneration:()=>Nr,Qwen2VLPreTrainedModel:()=>jr,RTDetrForObjectDetection:()=>Gn,RTDetrModel:()=>Rn,RTDetrObjectDetectionOutput:()=>$n,RTDetrPreTrainedModel:()=>Dn,ResNetForImageClassification:()=>so,ResNetModel:()=>to,ResNetPreTrainedModel:()=>eo,RoFormerForMaskedLM:()=>ae,RoFormerForQuestionAnswering:()=>de,RoFormerForSequenceClassification:()=>le,RoFormerForTokenClassification:()=>ce,RoFormerModel:()=>ie,RoFormerPreTrainedModel:()=>oe,RobertaForMaskedLM:()=>Ut,RobertaForQuestionAnswering:()=>Qt,RobertaForSequenceClassification:()=>Wt,RobertaForTokenClassification:()=>Xt,RobertaModel:()=>qt,RobertaPreTrainedModel:()=>$t,SamImageSegmentationOutput:()=>qo,SamModel:()=>$o,SamPreTrainedModel:()=>Go,SapiensForDepthEstimation:()=>go,SapiensForNormalEstimation:()=>wo,SapiensForSemanticSegmentation:()=>fo,SapiensPreTrainedModel:()=>ho,SegformerForImageClassification:()=>ea,SegformerForSemanticSegmentation:()=>ta,SegformerModel:()=>Zi,SegformerPreTrainedModel:()=>Ki,Seq2SeqLMOutput:()=>Hl,SequenceClassifierOutput:()=>Jl,SiglipModel:()=>As,SiglipPreTrainedModel:()=>Cs,SiglipTextModel:()=>Ss,SiglipVisionModel:()=>Es,SpeechT5ForSpeechToText:()=>Li,SpeechT5ForTextToSpeech:()=>Ii,SpeechT5HifiGan:()=>zi,SpeechT5Model:()=>Ei,SpeechT5PreTrainedModel:()=>Si,SqueezeBertForMaskedLM:()=>ut,SqueezeBertForQuestionAnswering:()=>_t,SqueezeBertForSequenceClassification:()=>pt,SqueezeBertModel:()=>dt,SqueezeBertPreTrainedModel:()=>ct,StableLmForCausalLM:()=>na,StableLmModel:()=>ra,StableLmPreTrainedModel:()=>sa,Starcoder2ForCausalLM:()=>Gi,Starcoder2Model:()=>Ri,Starcoder2PreTrainedModel:()=>Di,Swin2SRForImageSuperResolution:()=>lo,Swin2SRModel:()=>ao,Swin2SRPreTrainedModel:()=>io,SwinForImageClassification:()=>oo,SwinModel:()=>no,SwinPreTrainedModel:()=>ro,T5ForConditionalGeneration:()=>xt,T5Model:()=>bt,T5PreTrainedModel:()=>Mt,TableTransformerForObjectDetection:()=>Wn,TableTransformerModel:()=>Un,TableTransformerObjectDetectionOutput:()=>Xn,TableTransformerPreTrainedModel:()=>qn,TokenClassifierOutput:()=>Kl,TrOCRForCausalLM:()=>Ni,TrOCRPreTrainedModel:()=>ji,UniSpeechForCTC:()=>ci,UniSpeechForSequenceClassification:()=>di,UniSpeechModel:()=>li,UniSpeechPreTrainedModel:()=>ai,UniSpeechSatForAudioFrameClassification:()=>hi,UniSpeechSatForCTC:()=>_i,UniSpeechSatForSequenceClassification:()=>mi,UniSpeechSatModel:()=>pi,UniSpeechSatPreTrainedModel:()=>ui,ViTForImageClassification:()=>en,ViTMAEModel:()=>ln,ViTMAEPreTrainedModel:()=>an,ViTMSNForImageClassification:()=>un,ViTMSNModel:()=>dn,ViTMSNPreTrainedModel:()=>cn,ViTModel:()=>Zr,ViTPreTrainedModel:()=>Kr,VisionEncoderDecoderModel:()=>_s,VitMatteForImageMatting:()=>wn,VitMattePreTrainedModel:()=>gn,VitPoseForPoseEstimation:()=>sn,VitPosePreTrainedModel:()=>tn,VitsModel:()=>Yi,VitsModelOutput:()=>nc,VitsPreTrainedModel:()=>Ji,Wav2Vec2BertForCTC:()=>wi,Wav2Vec2BertForSequenceClassification:()=>Mi,Wav2Vec2BertModel:()=>gi,Wav2Vec2BertPreTrainedModel:()=>fi,Wav2Vec2ForAudioFrameClassification:()=>ti,Wav2Vec2ForCTC:()=>Zo,Wav2Vec2ForSequenceClassification:()=>ei,Wav2Vec2Model:()=>Ko,Wav2Vec2PreTrainedModel:()=>Yo,WavLMForAudioFrameClassification:()=>Ai,WavLMForCTC:()=>Pi,WavLMForSequenceClassification:()=>Fi,WavLMForXVector:()=>Ci,WavLMModel:()=>vi,WavLMPreTrainedModel:()=>Ti,WeSpeakerResNetModel:()=>ii,WeSpeakerResNetPreTrainedModel:()=>oi,WhisperForConditionalGeneration:()=>ps,WhisperModel:()=>us,WhisperPreTrainedModel:()=>ds,XLMForQuestionAnswering:()=>es,XLMForSequenceClassification:()=>Kt,XLMForTokenClassification:()=>Zt,XLMModel:()=>Jt,XLMPreTrainedModel:()=>Ht,XLMRobertaForMaskedLM:()=>rs,XLMRobertaForQuestionAnswering:()=>is,XLMRobertaForSequenceClassification:()=>ns,XLMRobertaForTokenClassification:()=>os,XLMRobertaModel:()=>ss,XLMRobertaPreTrainedModel:()=>ts,XLMWithLMHeadModel:()=>Yt,XVectorOutput:()=>Yl,YolosForObjectDetection:()=>Do,YolosModel:()=>Vo,YolosObjectDetectionOutput:()=>Ro,YolosPreTrainedModel:()=>Bo});var r=s(/*! ./configs.js */"./src/configs.js"),n=s(/*! ./backends/onnx.js */"./src/backends/onnx.js"),o=s(/*! ./utils/dtypes.js */"./src/utils/dtypes.js"),i=s(/*! ./utils/generic.js */"./src/utils/generic.js"),a=s(/*! ./utils/core.js */"./src/utils/core.js"),l=s(/*! ./utils/hub.js */"./src/utils/hub.js"),c=s(/*! ./utils/constants.js */"./src/utils/constants.js"),d=s(/*! ./generation/logits_process.js */"./src/generation/logits_process.js"),u=s(/*! ./generation/configuration_utils.js */"./src/generation/configuration_utils.js"),p=s(/*! ./utils/tensor.js */"./src/utils/tensor.js"),_=s(/*! ./utils/image.js */"./src/utils/image.js"),m=s(/*! ./utils/maths.js */"./src/utils/maths.js"),h=s(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),f=s(/*! ./generation/logits_sampler.js */"./src/generation/logits_sampler.js"),g=s(/*! ./env.js */"./src/env.js"),w=s(/*! ./models/whisper/generation_whisper.js */"./src/models/whisper/generation_whisper.js"),M=s(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");const b=0,x=1,y=2,k=3,T=4,v=5,P=6,F=7,C=8,A=new Map,S=new Map,E=new Map;async function L(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async i=>{const{buffer:a,session_options:c,session_config:d}=await async function(e,t,s){const i=s.config?.["transformers.js_config"]??{};let a=s.device??i.device;a&&"string"!=typeof a&&(a.hasOwnProperty(t)?a=a[t]:(console.warn(`device not specified for "${t}". Using the default device.`),a=null));const c=a??(g.apis.IS_NODE_ENV?"cpu":"wasm"),d=(0,n.deviceToExecutionProviders)(c);let u=s.dtype??i.dtype;if("string"!=typeof u&&(u&&u.hasOwnProperty(t)?u=u[t]:(u=o.DEFAULT_DEVICE_DTYPE_MAPPING[c]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${t}". Using the default dtype (${u}) for this device (${c}).`))),u===o.DATA_TYPES.auto){let e=i.dtype;"string"!=typeof e&&(e=e[t]),u=e&&e!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(e)?e:o.DEFAULT_DEVICE_DTYPE_MAPPING[c]??o.DATA_TYPES.fp32}const p=u;if(!o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(p))throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);if(p===o.DATA_TYPES.fp16&&"webgpu"===c&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${c}) does not support fp16.`);const _=i.kv_cache_dtype?"string"==typeof i.kv_cache_dtype?i.kv_cache_dtype:i.kv_cache_dtype[p]??"float32":void 0;if(_&&!["float32","float16"].includes(_))throw new Error(`Invalid kv_cache_dtype: ${_}. Should be one of: float32, float16`);const m={dtype:p,kv_cache_dtype:_},h=o.DEFAULT_DTYPE_SUFFIX_MAPPING[p],f=`${s.subfolder??""}/${t}${h}.onnx`,w={...s.session_options};w.executionProviders??=d;const M=i.free_dimension_overrides;M?w.freeDimensionOverrides??=M:c.startsWith("webnn")&&!w.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const b=(0,l.getModelFile)(e,f,!0,s),x=s.use_external_data_format??i.use_external_data_format;let y=[];if(x&&(!0===x||"object"==typeof x&&x.hasOwnProperty(t)&&!0===x[t])){if(g.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const r=`${t}${h}.onnx_data`,n=`${s.subfolder??""}/${r}`;y.push(new Promise((async(t,o)=>{const i=await(0,l.getModelFile)(e,n,!0,s);t({path:r,data:i})})))}else void 0!==w.externalData&&(y=w.externalData.map((async t=>{if("string"==typeof t.data){const r=await(0,l.getModelFile)(e,t.data,!0,s);return{...t,data:r}}return t})));if(y.length>0&&(w.externalData=await Promise.all(y)),"webgpu"===c){const e=(0,r.getKeyValueShapes)(s.config,{prefix:"present"});if(Object.keys(e).length>0&&!(0,n.isONNXProxy)()){const t={};for(const s in e)t[s]="gpu-buffer";w.preferredOutputLocation=t}}return{buffer:await b,session_options:w,session_config:m}}(e,t[i],s);return[i,await(0,n.createInferenceSession)(a,c,d)]}))))}async function I(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async r=>[r,await(0,l.getModelJSON)(e,t[r],!1,s)]))))}async function z(e,t){const s=function(e,t){const s=Object.create(null),r=[];for(const o of e.inputNames){const e=t[o];e instanceof p.Tensor?s[o]=(0,n.isONNXProxy)()?e.clone():e:r.push(o)}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const o=Object.keys(t).length,i=e.inputNames.length;if(o>i){let s=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: "${s.join(", ")}".`)}return s}(e,t);try{const t=Object.fromEntries(Object.entries(s).map((([e,t])=>[e,t.ort_tensor])));let r=await e.run(t);return r=j(r),r}catch(e){const t=Object.fromEntries(Object.entries(s).map((([e,{type:t,dims:s,data:r}])=>[e,{type:t,dims:s,data:r}])));throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",t),e}}function j(e){for(let t in e)(0,n.isONNXTensor)(e[t])?e[t]=new p.Tensor(e[t]):"object"==typeof e[t]&&j(e[t]);return e}function N(e){if(e instanceof p.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 p.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new p.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}function O(e){return new p.Tensor("bool",[e],[1])}async function B(e,t){let{encoder_outputs:s,input_ids:r,decoder_input_ids:n,...o}=t;if(!s){const r=(0,a.pick)(t,e.sessions.model.inputNames);s=(await V(e,r)).last_hidden_state}o.input_ids=n,o.encoder_hidden_states=s,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=t.attention_mask);return await D(e,o,!0)}async function V(e,t){const s=e.sessions.model,r=(0,a.pick)(t,s.inputNames);if(s.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}return s.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new p.Tensor("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await z(s,r)}async function D(e,t,s=!1){const r=e.sessions[s?"decoder_model_merged":"model"],{past_key_values:n,...o}=t;r.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=O(!!n)),r.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids&&(o.position_ids=function(e,t=null){const{input_ids:s,inputs_embeds:r,attention_mask:n}=e,{data:o,dims:i}=$(n);let a=new p.Tensor("int64",o,i);if(t){const e=-(s??r).dims.at(1);a=a.slice(null,[e,null])}return a}(o,n)),e.addPastKeyValues(o,n);const i=(0,a.pick)(o,r.inputNames);return await z(r,i)}function R({image_token_id:e,inputs_embeds:t,image_features:s,input_ids:r,attention_mask:n}){const o=r.tolist().map((t=>t.reduce(((t,s,r)=>(s==e&&t.push(r),t)),[]))),i=o.reduce(((e,t)=>e+t.length),0),a=s.dims[0];if(i!==a)throw new Error(`Image features and image tokens do not match: tokens: ${i}, features ${a}`);let l=0;for(let e=0;e<o.length;++e){const r=o[e],n=t[e];for(let e=0;e<r.length;++e)n[r[e]].data.set(s[l++].data)}return{inputs_embeds:t,attention_mask:n}}async function G(e,{input_ids:t=null,attention_mask:s=null,pixel_values:r=null,position_ids:n=null,inputs_embeds:o=null,past_key_values:i=null,generation_config:a=null,logits_processor:l=null,...c}){if(!o)if(o=await e.encode_text({input_ids:t,...c}),r&&1!==t.dims[1]){const n=await e.encode_image({pixel_values:r,...c});({inputs_embeds:o,attention_mask:s}=e._merge_input_ids_with_image_features({image_features:n,inputs_embeds:o,input_ids:t,attention_mask:s}))}else if(i&&r&&1===t.dims[1]){const e=t.dims[1],r=Object.values(i)[0].dims.at(-2);s=(0,p.cat)([(0,p.ones)([t.dims[0],r]),s.slice(null,[s.dims[1]-e,s.dims[1]])],1)}if(!n&&"qwen2_vl"===e.config.model_type){const{image_grid_thw:r,video_grid_thw:o}=c;[n]=e.get_rope_index(t,r,o,s)}return await D(e,{inputs_embeds:o,past_key_values:i,attention_mask:s,position_ids:n,generation_config:a,logits_processor:l},!0)}function $(e){const[t,s]=e.dims,r=e.data,n=new BigInt64Array(r.length);for(let e=0;e<t;++e){const t=e*s;let o=BigInt(0);for(let e=0;e<s;++e){const s=t+e;0n===r[s]?n[s]=BigInt(1):(n[s]=o,o+=r[s])}}return{data:n,dims:e.dims}}function q(e,t,s,r){if(s.past_key_values){const t=Object.values(s.past_key_values)[0].dims.at(-2),{input_ids:r,attention_mask:n}=s;if(n&&n.dims[1]>r.dims[1]);else if(t<r.dims[1])s.input_ids=r.slice(null,[t,null]);else if(null!=e.config.image_token_index&&r.data.some((t=>t==e.config.image_token_index))){const n=e.config.num_image_tokens;if(!n)throw new Error("`num_image_tokens` is missing in the model configuration.");const o=r.dims[1]-(t-n);s.input_ids=r.slice(null,[-o,null]),s.attention_mask=(0,p.ones)([1,t+o])}}return s}function U(e,t,s,r){return s.past_key_values&&(t=t.map((e=>[e.at(-1)]))),{...s,decoder_input_ids:N(t)}}function W(e,...t){return e.config.is_encoder_decoder?U(e,...t):q(e,...t)}function X(e,t,s,r){const n=!!s.past_key_values;if(null!==r.guidance_scale&&r.guidance_scale>1&&(n?s.input_ids=(0,p.cat)([s.input_ids,s.input_ids],0):(s.input_ids=(0,p.cat)([s.input_ids,(0,p.full_like)(s.input_ids,BigInt(r.pad_token_id))],0),s.attention_mask=(0,p.cat)([s.attention_mask,(0,p.full_like)(s.attention_mask,0n)],0))),!n&&s.pixel_values||(s.pixel_values=(0,p.full)([0,0,3,384,384],1)),n){const e=0,t=1,r=e>0?1:0,n=1;s.images_seq_mask=new p.Tensor("bool",new Array(e+t).fill(!0).fill(!1,0,t),[n,e+t]),s.images_emb_mask=new p.Tensor("bool",new Array(e).fill(!!r),[n,1,e])}return s}class Q extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t,s){super(),this.config=e,this.sessions=t,this.configs=s;const r=E.get(this.constructor),n=A.get(r);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,n){case T:this.can_generate=!0,this._forward=D,this._prepare_inputs_for_generation=q;break;case y:case k:case F:this.can_generate=!0,this._forward=B,this._prepare_inputs_for_generation=U;break;case x:this._forward=B;break;case P:this.can_generate=!0,this._forward=G,this._prepare_inputs_for_generation=W;break;case C:this.can_generate=!0,this._prepare_inputs_for_generation=X;break;default:this._forward=V}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:l="onnx",device:d=null,dtype:u=null,use_external_data_format:p=null,session_options:_={}}={}){let m={progress_callback:t,config:s,cache_dir:n,local_files_only:o,revision:i,model_file_name:a,subfolder:l,device:d,dtype:u,use_external_data_format:p,session_options:_};const h=E.get(this),f=A.get(h);let g;if(s=m.config=await r.AutoConfig.from_pretrained(e,m),f===T)g=await Promise.all([L(e,{model:m.model_file_name??"model"},m),I(e,{generation_config:"generation_config.json"},m)]);else if(f===y||f===k)g=await Promise.all([L(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),I(e,{generation_config:"generation_config.json"},m)]);else if(f===v)g=await Promise.all([L(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(f===x)g=await Promise.all([L(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m)]);else if(f===P){const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(t.model="encoder_model"),g=await Promise.all([L(e,t,m),I(e,{generation_config:"generation_config.json"},m)])}else if(f===F)g=await Promise.all([L(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),I(e,{generation_config:"generation_config.json"},m)]);else if(f===C)g=await Promise.all([L(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},m),I(e,{generation_config:"generation_config.json"},m)]);else{if(f!==b){const e=h??s?.model_type;"custom"!==e&&console.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}g=await Promise.all([L(e,{model:m.model_file_name??"model"},m)])}return new this(s,...g)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(e){const t=new d.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new d.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new d.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new d.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,s=null){const r=new d.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new d.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new d.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&r.push(new d.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new d.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new d.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new d.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new d.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){const s=t>1||null===e.forced_bos_token_id?t:t+1;r.push(new d.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,s))}return null!==e.guidance_scale&&e.guidance_scale>1&&r.push(new d.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==s&&r.extend(s),r}_prepare_generation_config(e,t,s=u.GenerationConfig){const r={...this.config};for(const e of["decoder","generator","text_config"])e in r&&Object.assign(r,r[e]);const n=new s(r);return 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 s=new h.StoppingCriteriaList;return null!==e.max_length&&s.push(new h.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&s.push(new h.EosTokenCriteria(e.eos_token_id)),t&&s.extend(t),s}_validate_model_class(){if(!this.can_generate){const e=[Xa,Ya,Wa,Ra],t=E.get(this.constructor),s=new Set,r=this.config.model_type;for(const t of e){const e=t.get(r);e&&s.add(e[0])}let n=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(n+=` Please use the following class instead: ${[...s].join(", ")}`),Error(n)}}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:s,is_encoder_decoder:r}){return s.past_key_values=this.getPastKeyValues(t,s.past_key_values),s.input_ids=new p.Tensor("int64",e.flat(),[e.length,1]),r||(s.attention_mask=(0,p.cat)([s.attention_mask,(0,p.ones)([s.attention_mask.dims[0],1])],1)),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:s}){const r=(0,a.pick)(s,this.forward_params),n=this.main_input_name;if(n in r){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 r[n]=e;return{inputs_tensor:r[n],model_inputs:r,model_input_name:n}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:s,generation_config:r}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:e,pixel_values:s,attention_mask:r,...n}=t,o=await this._prepare_inputs_embeds(t);t={...n,...(0,a.pick)(o,["inputs_embeds","attention_mask"])}}let{last_hidden_state:n}=await V(this,t);if(null!==r.guidance_scale&&r.guidance_scale>1)n=(0,p.cat)([n,(0,p.full_like)(n,0)],0),"attention_mask"in t&&(t.attention_mask=(0,p.cat)([t.attention_mask,(0,p.zeros_like)(t.attention_mask)],0));else if(t.decoder_input_ids){const e=N(t.decoder_input_ids).dims[0];if(e!==n.dims[0]){if(1!==n.dims[0])throw new Error(`The encoder outputs have a different batch size (${n.dims[0]}) than the decoder inputs (${e}).`);n=(0,p.cat)(Array.from({length:e},(()=>n)),0)}}return t.encoder_outputs=n,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:s,decoder_start_token_id:r,bos_token_id:n,generation_config:o}){let{decoder_input_ids:i,...a}=s;if(!(i instanceof p.Tensor)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},(()=>i)));else if(r??=n,"musicgen"===this.config.model_type)i=Array.from({length:e*this.config.decoder.num_codebooks},(()=>[r]));else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);i=r}else i=Array.from({length:e},(()=>[r]));i=N(i)}return s.decoder_attention_mask=(0,p.ones_like)(i),{input_ids:i,model_inputs:a}}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,streamer:n=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 u=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=u+t.max_new_tokens);const _=this._get_logits_processor(t,u,s),m=this._get_stopping_criteria(t,r),h=a[l].dims.at(0),g=f.LogitsSampler.getSampler(t),w=new Array(h).fill(0),M=d.tolist();let b;n&&n.put(M);let x={};for(;;){if(a=this.prepare_inputs_for_generation(M,a,t),b=await this.forward(a),t.output_attentions&&t.return_dict_in_generate){const e=this.getAttentions(b);for(const t in e)t in x||(x[t]=[]),x[t].push(e[t])}const e=_(M,b.logits.slice(null,-1,null)),s=[];for(let t=0;t<e.dims.at(0);++t){const r=e[t],n=await g(r);for(const[e,r]of n){const n=BigInt(e);w[t]+=r,M[t].push(n),s.push([n]);break}}n&&n.put(s);if(m(M).every((e=>e)))break;a=this._update_model_kwargs_for_generation({generated_input_ids:s,outputs:b,model_inputs:a,is_encoder_decoder:c})}n&&n.end();const y=this.getPastKeyValues(b,a.past_key_values,!0),k=new p.Tensor("int64",M.flat(),[M.length,M[0].length]);if(t.return_dict_in_generate)return{sequences:k,past_key_values:y,...x};for(const e of Object.values(b))"gpu-buffer"===e.location&&e.dispose();return k}getPastKeyValues(e,t,s=!1){const r=Object.create(null);for(const n in e)if(n.startsWith("present")){const o=n.replace("present","past_key_values"),i=n.includes("encoder");if(r[o]=i&&t?t[o]:e[n],t&&(!i||s)){const e=t[o];"gpu-buffer"===e.location&&e.dispose()}}return r}getAttentions(e){const t={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const r in e)r.startsWith(s)&&(s in t||(t[s]=[]),t[s].push(e[r]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=this.sessions.decoder_model_merged??this.sessions.model,s=t?.config?.kv_cache_dtype??"float32",n="float16"===s?new Uint16Array:[],o=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,i=(0,r.getKeyValueShapes)(this.config,{batch_size:o});for(const t in i)e[t]=new p.Tensor(s,n,i[t])}}async encode_image({pixel_values:e}){const t=(await z(this.sessions.vision_encoder,{pixel_values:e})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${t.dims[1]}).`),this.config.num_image_tokens=t.dims[1]),t}async encode_text({input_ids:e}){return(await z(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}}class H{}class J extends H{constructor({last_hidden_state:e,hidden_states:t=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=s}}class Y extends Q{}class K extends Y{}class Z extends Y{async _call(e){return new Zl(await super._call(e))}}class ee extends Y{async _call(e){return new Jl(await super._call(e))}}class te extends Y{async _call(e){return new Kl(await super._call(e))}}class se extends Y{async _call(e){return new ec(await super._call(e))}}class re extends Q{}class ne extends re{}class oe extends Q{}class ie extends oe{}class ae extends oe{async _call(e){return new Zl(await super._call(e))}}class le extends oe{async _call(e){return new Jl(await super._call(e))}}class ce extends oe{async _call(e){return new Kl(await super._call(e))}}class de extends oe{async _call(e){return new ec(await super._call(e))}}class ue extends Q{}class pe extends ue{}class _e extends ue{async _call(e){return new Zl(await super._call(e))}}class me extends ue{async _call(e){return new Jl(await super._call(e))}}class he extends ue{async _call(e){return new Kl(await super._call(e))}}class fe extends ue{async _call(e){return new ec(await super._call(e))}}class ge extends Q{}class we extends ge{}class Me extends ge{async _call(e){return new Zl(await super._call(e))}}class be extends ge{async _call(e){return new Jl(await super._call(e))}}class xe extends ge{async _call(e){return new Kl(await super._call(e))}}class ye extends ge{async _call(e){return new ec(await super._call(e))}}class ke extends Q{}class Te extends ke{}class ve extends ke{async _call(e){return new Zl(await super._call(e))}}class Pe extends ke{async _call(e){return new Jl(await super._call(e))}}class Fe extends ke{async _call(e){return new Kl(await super._call(e))}}class Ce extends ke{async _call(e){return new ec(await super._call(e))}}class Ae extends Q{}class Se extends Ae{}class Ee extends Ae{async _call(e){return new Zl(await super._call(e))}}class Le extends Ae{async _call(e){return new Jl(await super._call(e))}}class Ie extends Ae{async _call(e){return new Kl(await super._call(e))}}class ze extends Ae{async _call(e){return new ec(await super._call(e))}}class je extends Q{}class Ne extends je{}class Oe extends je{async _call(e){return new Zl(await super._call(e))}}class Be extends je{async _call(e){return new Jl(await super._call(e))}}class Ve extends je{async _call(e){return new Kl(await super._call(e))}}class De extends je{async _call(e){return new ec(await super._call(e))}}class Re extends Q{}class Ge extends Re{}class $e extends Re{async _call(e){return new Jl(await super._call(e))}}class qe extends Re{async _call(e){return new Kl(await super._call(e))}}class Ue extends Re{async _call(e){return new ec(await super._call(e))}}class We extends Re{async _call(e){return new Zl(await super._call(e))}}class Xe extends Q{}class Qe extends Xe{}class He extends Xe{async _call(e){return new Zl(await super._call(e))}}class Je extends Xe{async _call(e){return new Jl(await super._call(e))}}class Ye extends Xe{async _call(e){return new Kl(await super._call(e))}}class Ke extends Q{}class Ze extends Ke{}class et extends Ke{async _call(e){return new Zl(await super._call(e))}}class tt extends Ke{async _call(e){return new Jl(await super._call(e))}}class st extends Ke{async _call(e){return new ec(await super._call(e))}}class rt extends Q{}class nt extends rt{}class ot extends rt{async _call(e){return new Zl(await super._call(e))}}class it extends rt{async _call(e){return new Jl(await super._call(e))}}class at extends rt{async _call(e){return new Kl(await super._call(e))}}class lt extends rt{async _call(e){return new ec(await super._call(e))}}class ct extends Q{}class dt extends ct{}class ut extends ct{async _call(e){return new Zl(await super._call(e))}}class pt extends ct{async _call(e){return new Jl(await super._call(e))}}class _t extends ct{async _call(e){return new ec(await super._call(e))}}class mt extends Q{}class ht extends mt{}class ft extends mt{async _call(e){return new Jl(await super._call(e))}}class gt extends mt{async _call(e){return new ec(await super._call(e))}}class wt extends mt{async _call(e){return new Zl(await super._call(e))}}class Mt extends Q{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class bt extends Mt{}class xt extends Mt{}class yt extends Q{}class kt extends yt{}class Tt extends yt{}class vt extends Q{}class Pt extends vt{}class Ft extends vt{}class Ct extends Q{}class At extends Ct{}class St extends Ct{}class Et extends Ct{async _call(e){return new Jl(await super._call(e))}}class Lt extends Q{}class It extends Lt{}class zt extends Lt{}class jt extends Lt{async _call(e){return new Jl(await super._call(e))}}class Nt extends Lt{}class Ot extends Q{}class Bt extends Ot{}class Vt extends Ot{}class Dt extends Q{}class Rt extends Dt{}class Gt extends Dt{}class $t extends Q{}class qt extends $t{}class Ut extends $t{async _call(e){return new Zl(await super._call(e))}}class Wt extends $t{async _call(e){return new Jl(await super._call(e))}}class Xt extends $t{async _call(e){return new Kl(await super._call(e))}}class Qt extends $t{async _call(e){return new ec(await super._call(e))}}class Ht extends Q{}class Jt extends Ht{}class Yt extends Ht{async _call(e){return new Zl(await super._call(e))}}class Kt extends Ht{async _call(e){return new Jl(await super._call(e))}}class Zt extends Ht{async _call(e){return new Kl(await super._call(e))}}class es extends Ht{async _call(e){return new ec(await super._call(e))}}class ts extends Q{}class ss extends ts{}class rs extends ts{async _call(e){return new Zl(await super._call(e))}}class ns extends ts{async _call(e){return new Jl(await super._call(e))}}class os extends ts{async _call(e){return new Kl(await super._call(e))}}class is extends ts{async _call(e){return new ec(await super._call(e))}}class as extends Q{}class ls extends as{}class cs extends as{}class ds extends Q{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class us extends ds{}class ps extends ds{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,w.WhisperGenerationConfig)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let s=e.language;const r=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");const n=`<|${(0,M.whisper_language_to_code)(s)}|>`;t.push(e.lang_to_id[n]),t.push(e.task_to_id[r??"transcribe"])}else if(s||r)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter((e=>null!=e))}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,...n}){t=this._prepare_generation_config(t,n);const o=n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(s??=new d.LogitsProcessorList,s.push(new d.WhisperTimeStampLogitsProcessor(t,o))),t.begin_suppress_tokens&&(s??=new d.LogitsProcessorList,s.push(new d.SuppressTokensAtBeginLogitsProcessor(t.begin_suppress_tokens,o.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");"translate"===t.task&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const i=await super.generate({inputs:e,generation_config:t,logits_processor:s,decoder_input_ids:o,...n});return t.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,t.alignment_heads,t.num_frames)),i}_extract_token_timestamps(e,t,s=null,r=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");null==s&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let n=this.config.median_filter_width;void 0===n&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),n=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},((e,t)=>(0,p.cat)(o.map((e=>e[t])),2))),l=(0,p.stack)(t.map((([e,t])=>{if(e>=i.length)throw new Error(`Layer index ${e} is out of bounds for cross attentions (length ${i.length}).`);return s?i[e].slice(null,t,null,[0,s]):i[e].slice(null,t)}))).transpose(1,0,2,3),[c,d]=(0,p.std_mean)(l,-2,0,!0),u=l.clone();for(let e=0;e<u.dims[0];++e){const t=u[e];for(let s=0;s<t.dims[0];++s){const r=t[s],o=c[e][s][0].data,i=d[e][s][0].data;for(let e=0;e<r.dims[0];++e){let t=r[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-i[e])/o[e];t.set((0,m.medianFilter)(t,n))}}}const _=[(0,p.mean)(u,1)],h=e.sequences.dims,f=new p.Tensor("float32",new Float32Array(h[0]*h[1]),h);for(let e=0;e<h[0];++e){const t=_[e].neg().squeeze_(0),[s,n]=(0,m.dynamic_time_warping)(t.tolist()),o=Array.from({length:s.length-1},((e,t)=>s[t+1]-s[t])),i=(0,a.mergeArrays)([1],o).map((e=>!!e)),l=[];for(let e=0;e<i.length;++e)i[e]&&l.push(n[e]*r);f[e].data.set(l,1)}return f}}class _s extends Q{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]}class ms extends Q{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]}class hs extends ms{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:r}){const n=this.config.image_token_index,o=s.tolist().map((e=>e.findIndex((e=>e==n)))),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:r};const l=[],c=[];for(let s=0;s<o.length;++s){const n=o[s],i=e[s],a=t[s],d=r[s];l.push((0,p.cat)([i.slice([0,n]),a,i.slice([n+1,i.dims[0]])],0)),c.push((0,p.cat)([d.slice([0,n]),(0,p.ones)([a.dims[0]]),d.slice([n+1,d.dims[0]])],0))}return{inputs_embeds:(0,p.stack)(l,0),attention_mask:(0,p.stack)(c,0)}}}class fs extends hs{}class gs extends hs{}class ws extends Q{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"}class Ms extends ws{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:r}){return{inputs_embeds:(0,p.cat)([t,e],1),attention_mask:(0,p.cat)([(0,p.ones)(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:r}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,o;return e&&(n=await this.encode_text({input_ids:e})),t&&(o=await this.encode_image({pixel_values:t})),n&&o?({inputs_embeds:s,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:o,input_ids:e,attention_mask:r})):s=n||o,{inputs_embeds:s,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:s,decoder_input_ids:r,decoder_attention_mask:n,encoder_outputs:o,past_key_values:i,inputs_embeds:a,decoder_inputs_embeds:l}){if(a||({inputs_embeds:a,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:a,attention_mask:s})),!o){let{last_hidden_state:e}=await V(this,{inputs_embeds:a,attention_mask:s});o=e}if(!l){if(!r)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:r})}const c={inputs_embeds:l,attention_mask:n,encoder_attention_mask:s,encoder_hidden_states:o,past_key_values:i};return await D(this,c,!0)}}class bs extends Q{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]}class xs extends bs{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await z(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:t})).image_features}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return R({image_token_id:this.config.image_token_id,...e,image_features:s})}}class ys extends Q{}class ks extends ys{}class Ts extends ys{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class vs extends ys{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Ps extends ys{static async from_pretrained(e,t={}){return t.model_file_name??="vision_model",super.from_pretrained(e,t)}}class Fs extends ys{static async from_pretrained(e,t={}){return t.model_file_name??="vision_model",super.from_pretrained(e,t)}}class Cs extends Q{}class As extends Cs{}class Ss extends Cs{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Es extends ys{static async from_pretrained(e,t={}){return t.model_file_name??="vision_model",super.from_pretrained(e,t)}}class Ls extends Q{}class Is extends Ls{}class zs extends Q{}class js extends zs{async forward(e){const t=!e.input_ids,s=!e.pixel_values;if(t&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=(0,p.ones)([e.pixel_values.dims[0],1])),s){const{image_size:t}=this.config.vision_config;e.pixel_values=(0,p.full)([0,3,t,t],0)}const{text_embeddings:r,image_embeddings:n,l2norm_text_embeddings:o,l2norm_image_embeddings:i}=await super.forward(e),a={};return t||(a.text_embeddings=r,a.l2norm_text_embeddings=o),s||(a.image_embeddings=n,a.l2norm_image_embeddings=i),a}}class Ns extends zs{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Os extends zs{static async from_pretrained(e,t={}){return t.model_file_name??="vision_model",super.from_pretrained(e,t)}}class Bs extends Q{}class Vs extends Bs{}class Ds extends Bs{}class Rs extends Q{}class Gs extends Rs{}class $s extends Rs{}class qs extends Q{}class Us extends qs{}class Ws extends qs{}class Xs extends Q{}class Qs extends Xs{}class Hs extends Xs{}class Js extends Q{}class Ys extends Js{}class Ks extends Js{}class Zs extends Q{}class er extends Zs{}class tr extends Zs{}class sr extends Q{}class rr extends sr{}class nr extends sr{}class or extends Q{}class ir extends or{}class ar extends or{}class lr extends Q{}class cr extends lr{}class dr extends lr{}class ur extends Q{}class pr extends ur{}class _r extends ur{}class mr extends Q{}class hr extends mr{}class fr extends mr{}class gr extends Q{}class wr extends gr{}class Mr extends gr{}class br extends Q{}class xr extends br{}class yr extends br{}class kr extends Q{}class Tr extends kr{}class vr extends kr{}class Pr extends Q{}class Fr extends Pr{}class Cr extends Pr{}class Ar extends Q{}class Sr extends Ar{}class Er extends Ar{}class Lr extends Q{}class Ir extends Lr{}class zr extends Lr{}class jr extends Q{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]}class Nr extends jr{get_rope_index(e,t,s,r){const{vision_config:n,image_token_id:o,video_token_id:i,vision_start_token_id:a}=this.config,l=n.spatial_merge_size??2,c=[];if(t||s){let n=e.tolist();r||(r=(0,p.ones_like)(e));const d=r.tolist(),u=Array.from({length:3},(t=>Array.from({length:e.dims[0]},(t=>Array.from({length:e.dims[1]},(e=>1)))))),_=t?t.tolist():[],h=s?s.tolist():[];let f=0,g=0;for(let e=0;e<n.length;++e){const t=n[e].filter(((t,s)=>1==d[e][s])),s=t.reduce(((e,t,s)=>(t==a&&e.push(s),e)),[]).map((e=>t[e+1])),r=s.filter((e=>e==o)).length,p=s.filter((e=>e==i)).length;let w=[],M=0,b=r,x=p;for(let e=0;e<s.length;++e){const e=t.findIndex(((e,t)=>t>M&&e==o)),s=t.findIndex(((e,t)=>t>M&&e==i)),r=b>0&&-1!==e?e:t.length+1,n=x>0&&-1!==s?s:t.length+1;let a,c,d,u;r<n?([c,d,u]=_[f],++f,--b,a=r):([c,d,u]=h[g],++g,--x,a=n);const[p,y,k]=[Number(c),Math.floor(Number(d)/l),Math.floor(Number(u)/l)],T=a-M,v=w.length>0?(0,m.max)(w.at(-1))[0]+1:0;w.push(Array.from({length:3*T},((e,t)=>v+t%T)));const P=T+v,F=p*y*k,C=Array.from({length:F},((e,t)=>P+Math.floor(t/(y*k)))),A=Array.from({length:F},((e,t)=>P+Math.floor(t/k)%y)),S=Array.from({length:F},((e,t)=>P+t%k));w.push([C,A,S].flat()),M=a+F}if(M<t.length){const e=w.length>0?(0,m.max)(w.at(-1))[0]+1:0,s=t.length-M;w.push(Array.from({length:3*s},((t,r)=>e+r%s)))}const y=w.reduce(((e,t)=>e+t.length),0),k=new Array(y);let T=0;for(let e=0;e<3;++e)for(let t=0;t<w.length;++t){const s=w[t],r=s.length/3;for(let t=e*r;t<(e+1)*r;++t)k[T++]=s[t]}let v=0;const P=d[e];for(let t=0;t<P.length;++t)if(1==P[t]){for(let s=0;s<3;++s)u[s][e][t]=k[s*y/3+v];++v}const F=(0,m.max)(k)[0];c.push(F+1-n[e].length)}return[new p.Tensor("int64",u.flat(1/0),[3,e.dims[0],e.dims[1]]),new p.Tensor("int64",c,[c.length,1])]}if(r){const{data:e,dims:t}=$(r),s=BigInt64Array.from({length:3*e.length},((t,s)=>e[s%e.length])),n=Array.from({length:t[0]},((s,r)=>(0,m.max)(e.subarray(t[1]*r,t[1]*(r+1)))[0]+1+t[1]));return[new p.Tensor("int64",s,[3,...t]),new p.Tensor("int64",n,[n.length,1])]}{const[t,s]=e.dims,r=BigInt64Array.from({length:3*t*s},((e,r)=>BigInt(Math.floor(r%s/t))));return[new p.Tensor("int64",r,[3,...e.dims]),(0,p.zeros)([t,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await z(this.sessions.vision_encoder,{pixel_values:e,grid_thw:t})).image_features}_merge_input_ids_with_image_features(e){return R({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,s){if(t.attention_mask&&!t.position_ids)if(t.past_key_values){t.pixel_values=null;const e=BigInt(Object.values(t.past_key_values)[0].dims.at(-2)),s=t.rope_deltas.map((t=>e+t));t.position_ids=(0,p.stack)([s,s,s],0)}else[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);return t}}class Or extends Q{}class Br extends Or{}class Vr extends Or{}class Dr extends Q{}class Rr extends Dr{}class Gr extends Dr{}class $r extends Q{}class qr extends $r{}class Ur extends $r{}class Wr extends Q{}class Xr extends Wr{}class Qr extends Wr{}class Hr extends Q{}class Jr extends Hr{}class Yr extends Hr{}class Kr extends Q{}class Zr extends Kr{}class en extends Kr{async _call(e){return new Jl(await super._call(e))}}class tn extends Q{}class sn extends tn{}class rn extends Q{}class nn extends rn{}class on extends rn{async _call(e){return new Jl(await super._call(e))}}class an extends Q{}class ln extends an{}class cn extends Q{}class dn extends cn{}class un extends cn{async _call(e){return new Jl(await super._call(e))}}class pn extends Q{}class _n extends pn{}class mn extends Q{}class hn extends mn{}class fn extends mn{async _call(e){return new Jl(await super._call(e))}}class gn extends Q{}class wn extends gn{async _call(e){return new rc(await super._call(e))}}class Mn extends Q{}class bn extends Mn{}class xn extends Mn{async _call(e){return new Jl(await super._call(e))}}class yn extends Q{}class kn extends yn{}class Tn extends yn{async _call(e){return new Jl(await super._call(e))}}class vn extends Q{}class Pn extends vn{}class Fn extends vn{}class Cn extends Q{}class An extends Cn{}class Sn extends Cn{}class En extends Q{}class Ln extends En{}class In extends En{async _call(e){return new Jl(await super._call(e))}}class zn extends Q{}class jn extends zn{}class Nn extends zn{async _call(e){return new Bn(await super._call(e))}}class On extends zn{async _call(e){return new Vn(await super._call(e))}}class Bn extends H{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class Vn extends H{constructor({logits:e,pred_boxes:t,pred_masks:s}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=s}}class Dn extends Q{}class Rn extends Dn{}class Gn extends Dn{async _call(e){return new $n(await super._call(e))}}class $n extends H{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class qn extends Q{}class Un extends qn{}class Wn extends qn{async _call(e){return new Xn(await super._call(e))}}class Xn extends Bn{}class Qn extends Q{}class Hn extends Qn{}class Jn extends Qn{async _call(e){return new Jl(await super._call(e))}}class Yn extends Q{}class Kn extends Yn{}class Zn extends Yn{async _call(e){return new Jl(await super._call(e))}}class eo extends Q{}class to extends eo{}class so extends eo{async _call(e){return new Jl(await super._call(e))}}class ro extends Q{}class no extends ro{}class oo extends ro{async _call(e){return new Jl(await super._call(e))}}class io extends Q{}class ao extends io{}class lo extends io{}class co extends Q{}class uo extends co{}class po extends co{}class _o extends Q{}class mo extends _o{}class ho extends Q{}class fo extends ho{}class go extends ho{}class wo extends ho{}class Mo extends Q{}class bo extends Mo{}class xo extends Q{}class yo extends xo{}class ko extends xo{}class To extends Q{}class vo extends To{}class Po extends To{}class Fo extends Q{}class Co extends Fo{}class Ao extends Q{}class So extends Ao{}class Eo extends Ao{async _call(e){return new Jl(await super._call(e))}}class Lo extends Q{}class Io extends Lo{}class zo extends Lo{async _call(e){return new Jl(await super._call(e))}}class jo extends Q{}class No extends jo{}class Oo extends jo{async _call(e){return new Jl(await super._call(e))}}class Bo extends Q{}class Vo extends Bo{}class Do extends Bo{async _call(e){return new Ro(await super._call(e))}}class Ro extends H{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class Go extends Q{}class $o extends Go{async get_image_embeddings({pixel_values:e}){return await V(this,{pixel_values:e})}async forward(e){if(e.image_embeddings&&e.image_positional_embeddings||(e={...e,...await this.get_image_embeddings(e)}),!e.input_labels&&e.input_points){const t=e.input_points.dims.slice(0,-1),s=t.reduce(((e,t)=>e*t),1);e.input_labels=new p.Tensor("int64",new BigInt64Array(s).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 z(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new qo(await super._call(e))}}class qo extends H{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class Uo extends Q{}class Wo extends Uo{}class Xo extends Uo{}class Qo extends Q{}class Ho extends Qo{}class Jo extends Qo{}class Yo extends Q{}class Ko extends Yo{}class Zo extends Yo{async _call(e){return new tc(await super._call(e))}}class ei extends Yo{async _call(e){return new Jl(await super._call(e))}}class ti extends Yo{async _call(e){return new Kl(await super._call(e))}}class si extends Q{}class ri extends si{}class ni extends si{async _call(e){return new Kl(await super._call(e))}}class oi extends Q{}class ii extends oi{}class ai extends Q{}class li extends ai{}class ci extends ai{async _call(e){return new tc(await super._call(e))}}class di extends ai{async _call(e){return new Jl(await super._call(e))}}class ui extends Q{}class pi extends ui{}class _i extends ui{async _call(e){return new tc(await super._call(e))}}class mi extends ui{async _call(e){return new Jl(await super._call(e))}}class hi extends ui{async _call(e){return new Kl(await super._call(e))}}class fi extends Q{}class gi extends fi{}class wi extends fi{async _call(e){return new tc(await super._call(e))}}class Mi extends fi{async _call(e){return new Jl(await super._call(e))}}class bi extends Q{}class xi extends Yo{}class yi extends Yo{async _call(e){return new tc(await super._call(e))}}class ki extends Yo{async _call(e){return new Jl(await super._call(e))}}class Ti extends Q{}class vi extends Ti{}class Pi extends Ti{async _call(e){return new tc(await super._call(e))}}class Fi extends Ti{async _call(e){return new Jl(await super._call(e))}}class Ci extends Ti{async _call(e){return new Yl(await super._call(e))}}class Ai extends Ti{async _call(e){return new Kl(await super._call(e))}}class Si extends Q{}class Ei extends Si{}class Li extends Si{}class Ii extends Si{async generate_speech(e,t,{threshold:s=.5,minlenratio:r=0,maxlenratio:n=20,vocoder:o=null}={}){const i={input_ids:e},{encoder_outputs:a,encoder_attention_mask:l}=await V(this,i),c=a.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),u=Math.floor(c*r),_=this.config.num_mel_bins;let m=[],h=null,f=null,g=0;for(;;){++g;const e=O(!!f);let r;r=f?f.output_sequence_out:new p.Tensor("float32",new Float32Array(_),[1,1,_]);let n={use_cache_branch:e,output_sequence:r,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:a};this.addPastKeyValues(n,h),f=await z(this.sessions.decoder_model_merged,n),h=this.getPastKeyValues(f,h);const{prob:o,spectrum:i}=f;if(m.push(i),g>=u&&(Array.from(o.data).filter((e=>e>=s)).length>0||g>=d))break}const w=(0,p.cat)(m),{waveform:M}=await z(o.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:M}}}class zi extends Q{main_input_name="spectrogram"}class ji extends Q{}class Ni extends ji{}class Oi extends Q{}class Bi extends Oi{}class Vi extends Oi{}class Di extends Q{}class Ri extends Di{}class Gi extends Di{}class $i extends Q{}class qi extends $i{}class Ui extends $i{}class Wi extends Q{}class Xi extends Wi{}class Qi extends Wi{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Hi extends Wi{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class Ji extends Q{}class Yi extends Ji{async _call(e){return new nc(await super._call(e))}}class Ki extends Q{}class Zi extends Ki{}class ea extends Ki{}class ta extends Ki{}class sa extends Q{}class ra extends sa{}class na extends sa{}class oa extends Q{}class ia extends oa{}class aa extends oa{async _call(e){return new Jl(await super._call(e))}}class la extends Q{}class ca extends la{}class da extends la{}class ua extends Q{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,s]=e.dims,r=this.config.decoder.num_codebooks,n=s-r;let o=0;for(let t=0;t<e.size;++t){if(e.data[t]===this.config.decoder.pad_token_id)continue;const i=t%s-Math.floor(t/s)%r;i>0&&i<=n&&(e.data[o++]=e.data[t])}const i=Math.floor(t/r),a=o/(i*r);return new p.Tensor(e.type,e.data.slice(0,o),[i,r,a])}prepare_inputs_for_generation(e,t,s){let r=structuredClone(e);for(let e=0;e<r.length;++e)for(let t=0;t<r[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(r[e][t]=BigInt(this.config.decoder.pad_token_id));null!==s.guidance_scale&&s.guidance_scale>1&&(r=r.concat(r));return super.prepare_inputs_for_generation(r,t,s)}async generate(e){const t=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await z(this.sessions.encodec_decode,{audio_codes:s});return r}}class pa extends Q{}class _a extends pa{}class ma extends pa{async _call(e){return new Jl(await super._call(e))}}class ha extends Q{}class fa extends ha{}class ga extends ha{async _call(e){return new Jl(await super._call(e))}}class wa extends Q{}class Ma extends wa{}class ba extends wa{async _call(e){return new Jl(await super._call(e))}}class xa extends Q{}class ya extends xa{}class ka extends xa{async _call(e){return new Jl(await super._call(e))}}class Ta extends Q{}class va extends Ta{}class Pa extends Q{}class Fa extends Pa{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let s;if("text"!==t&&e.past_key_values){const t=this.sessions.gen_img_embeds,r=(0,a.pick)({image_ids:e.input_ids},t.inputNames);s=await z(t,r)}else{const t=this.sessions.prepare_inputs_embeds,r=(0,a.pick)(e,t.inputNames);s=await z(t,r)}const r={...e,...s},n=await D(this,r),o=this.sessions["text"===t?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await z(o,(0,a.pick)(n,o.inputNames));return{...s,...n,...i}}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:n}=await z(r,{generated_tokens:s}),o=n.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),i=[];for(const e of o){const t=_.RawImage.fromTensor(e);i.push(t)}return i}}class Ca extends H{constructor({char_logits:e,bpe_logits:t,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Aa extends Q{}class Sa extends Aa{async _call(e){return new Ca(await super._call(e))}}class Ea extends Q{}class La extends Ea{}class Ia extends Ea{}class za extends Q{}class ja extends za{}class Na extends za{}class Oa{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:u=null,session_options:p={}}={}){const _={progress_callback:t,config:s,cache_dir:n,local_files_only:o,revision:i,model_file_name:a,subfolder:l,device:c,dtype:d,use_external_data_format:u,session_options:p};if(_.config=await r.AutoConfig.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const t of this.MODEL_CLASS_MAPPINGS){const s=t.get(_.config.model_type);if(s)return await s[1].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_.config.model_type}", attempting to construct from base class.`),await Q.from_pretrained(e,_);throw Error(`Unsupported model type: ${_.config.model_type}`)}}const Ba=new Map([["bert",["BertModel",K]],["nomic_bert",["NomicBertModel",ne]],["roformer",["RoFormerModel",ie]],["electra",["ElectraModel",we]],["esm",["EsmModel",Qe]],["convbert",["ConvBertModel",pe]],["camembert",["CamembertModel",Te]],["deberta",["DebertaModel",Se]],["deberta-v2",["DebertaV2Model",Ne]],["mpnet",["MPNetModel",nt]],["albert",["AlbertModel",ht]],["distilbert",["DistilBertModel",Ge]],["roberta",["RobertaModel",qt]],["xlm",["XLMModel",Jt]],["xlm-roberta",["XLMRobertaModel",ss]],["clap",["ClapModel",Xi]],["clip",["CLIPModel",ks]],["clipseg",["CLIPSegModel",Vs]],["chinese_clip",["ChineseCLIPModel",Is]],["siglip",["SiglipModel",As]],["jina_clip",["JinaCLIPModel",js]],["mobilebert",["MobileBertModel",Ze]],["squeezebert",["SqueezeBertModel",dt]],["wav2vec2",["Wav2Vec2Model",Ko]],["wav2vec2-bert",["Wav2Vec2BertModel",gi]],["unispeech",["UniSpeechModel",li]],["unispeech-sat",["UniSpeechSatModel",pi]],["hubert",["HubertModel",xi]],["wavlm",["WavLMModel",vi]],["audio-spectrogram-transformer",["ASTModel",ls]],["vits",["VitsModel",Yi]],["pyannote",["PyAnnoteModel",ri]],["wespeaker-resnet",["WeSpeakerResNetModel",ii]],["detr",["DetrModel",jn]],["rt_detr",["RTDetrModel",Rn]],["table-transformer",["TableTransformerModel",Un]],["vit",["ViTModel",Zr]],["pvt",["PvtModel",nn]],["vit_msn",["ViTMSNModel",dn]],["vit_mae",["ViTMAEModel",ln]],["groupvit",["GroupViTModel",_n]],["fastvit",["FastViTModel",hn]],["mobilevit",["MobileViTModel",bn]],["mobilevitv2",["MobileViTV2Model",kn]],["owlvit",["OwlViTModel",Pn]],["owlv2",["Owlv2Model",An]],["beit",["BeitModel",Ln]],["deit",["DeiTModel",Hn]],["hiera",["HieraModel",Kn]],["convnext",["ConvNextModel",So]],["convnextv2",["ConvNextV2Model",Io]],["dinov2",["Dinov2Model",No]],["resnet",["ResNetModel",to]],["swin",["SwinModel",no]],["swin2sr",["Swin2SRModel",ao]],["donut-swin",["DonutSwinModel",Co]],["yolos",["YolosModel",Vo]],["dpt",["DPTModel",uo]],["glpn",["GLPNModel",vo]],["hifigan",["SpeechT5HifiGan",zi]],["efficientnet",["EfficientNetModel",ia]],["decision_transformer",["DecisionTransformerModel",va]],["patchtst",["PatchTSTForPrediction",La]],["patchtsmixer",["PatchTSMixerForPrediction",ja]],["mobilenet_v1",["MobileNetV1Model",_a]],["mobilenet_v2",["MobileNetV2Model",fa]],["mobilenet_v3",["MobileNetV3Model",Ma]],["mobilenet_v4",["MobileNetV4Model",ya]],["maskformer",["MaskFormerModel",yo]],["mgp-str",["MgpstrForSceneTextRecognition",Sa]]]),Va=new Map([["t5",["T5Model",bt]],["longt5",["LongT5Model",kt]],["mt5",["MT5Model",Pt]],["bart",["BartModel",At]],["mbart",["MBartModel",It]],["marian",["MarianModel",Wo]],["whisper",["WhisperModel",us]],["m2m_100",["M2M100Model",Ho]],["blenderbot",["BlenderbotModel",Bt]],["blenderbot-small",["BlenderbotSmallModel",Rt]]]),Da=new Map([["bloom",["BloomModel",qr]],["jais",["JAISModel",Us]],["gpt2",["GPT2Model",Gs]],["gptj",["GPTJModel",er]],["gpt_bigcode",["GPTBigCodeModel",rr]],["gpt_neo",["GPTNeoModel",Qs]],["gpt_neox",["GPTNeoXModel",Ys]],["codegen",["CodeGenModel",ir]],["llama",["LlamaModel",cr]],["olmo",["OlmoModel",hr]],["mobilellm",["MobileLLMModel",pr]],["granite",["GraniteModel",wr]],["cohere",["CohereModel",xr]],["gemma",["GemmaModel",Tr]],["gemma2",["Gemma2Model",Fr]],["openelm",["OpenELMModel",Sr]],["qwen2",["Qwen2Model",Ir]],["phi",["PhiModel",Br]],["phi3",["Phi3Model",Rr]],["mpt",["MptModel",Xr]],["opt",["OPTModel",Jr]],["mistral",["MistralModel",Bi]],["starcoder2",["Starcoder2Model",Ri]],["falcon",["FalconModel",qi]],["stablelm",["StableLmModel",ra]]]),Ra=new Map([["speecht5",["SpeechT5ForSpeechToText",Li]],["whisper",["WhisperForConditionalGeneration",ps]]]),Ga=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ii]]]),$a=new Map([["vits",["VitsModel",Yi]],["musicgen",["MusicgenForConditionalGeneration",ua]]]),qa=new Map([["bert",["BertForSequenceClassification",ee]],["roformer",["RoFormerForSequenceClassification",le]],["electra",["ElectraForSequenceClassification",be]],["esm",["EsmForSequenceClassification",Je]],["convbert",["ConvBertForSequenceClassification",me]],["camembert",["CamembertForSequenceClassification",Pe]],["deberta",["DebertaForSequenceClassification",Le]],["deberta-v2",["DebertaV2ForSequenceClassification",Be]],["mpnet",["MPNetForSequenceClassification",it]],["albert",["AlbertForSequenceClassification",ft]],["distilbert",["DistilBertForSequenceClassification",$e]],["roberta",["RobertaForSequenceClassification",Wt]],["xlm",["XLMForSequenceClassification",Kt]],["xlm-roberta",["XLMRobertaForSequenceClassification",ns]],["bart",["BartForSequenceClassification",Et]],["mbart",["MBartForSequenceClassification",jt]],["mobilebert",["MobileBertForSequenceClassification",tt]],["squeezebert",["SqueezeBertForSequenceClassification",pt]]]),Ua=new Map([["bert",["BertForTokenClassification",te]],["roformer",["RoFormerForTokenClassification",ce]],["electra",["ElectraForTokenClassification",xe]],["esm",["EsmForTokenClassification",Ye]],["convbert",["ConvBertForTokenClassification",he]],["camembert",["CamembertForTokenClassification",Fe]],["deberta",["DebertaForTokenClassification",Ie]],["deberta-v2",["DebertaV2ForTokenClassification",Ve]],["mpnet",["MPNetForTokenClassification",at]],["distilbert",["DistilBertForTokenClassification",qe]],["roberta",["RobertaForTokenClassification",Xt]],["xlm",["XLMForTokenClassification",Zt]],["xlm-roberta",["XLMRobertaForTokenClassification",os]]]),Wa=new Map([["t5",["T5ForConditionalGeneration",xt]],["longt5",["LongT5ForConditionalGeneration",Tt]],["mt5",["MT5ForConditionalGeneration",Ft]],["bart",["BartForConditionalGeneration",St]],["mbart",["MBartForConditionalGeneration",zt]],["marian",["MarianMTModel",Xo]],["m2m_100",["M2M100ForConditionalGeneration",Jo]],["blenderbot",["BlenderbotForConditionalGeneration",Vt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Gt]]]),Xa=new Map([["bloom",["BloomForCausalLM",Ur]],["gpt2",["GPT2LMHeadModel",$s]],["jais",["JAISLMHeadModel",Ws]],["gptj",["GPTJForCausalLM",tr]],["gpt_bigcode",["GPTBigCodeForCausalLM",nr]],["gpt_neo",["GPTNeoForCausalLM",Hs]],["gpt_neox",["GPTNeoXForCausalLM",Ks]],["codegen",["CodeGenForCausalLM",ar]],["llama",["LlamaForCausalLM",dr]],["olmo",["OlmoForCausalLM",fr]],["mobilellm",["MobileLLMForCausalLM",_r]],["granite",["GraniteForCausalLM",Mr]],["cohere",["CohereForCausalLM",yr]],["gemma",["GemmaForCausalLM",vr]],["gemma2",["Gemma2ForCausalLM",Cr]],["openelm",["OpenELMForCausalLM",Er]],["qwen2",["Qwen2ForCausalLM",zr]],["phi",["PhiForCausalLM",Vr]],["phi3",["Phi3ForCausalLM",Gr]],["mpt",["MptForCausalLM",Qr]],["opt",["OPTForCausalLM",Yr]],["mbart",["MBartForCausalLM",Nt]],["mistral",["MistralForCausalLM",Vi]],["starcoder2",["Starcoder2ForCausalLM",Gi]],["falcon",["FalconForCausalLM",Ui]],["trocr",["TrOCRForCausalLM",Ni]],["stablelm",["StableLmForCausalLM",na]]]),Qa=new Map([["multi_modality",["MultiModalityCausalLM",Fa]]]),Ha=new Map([["bert",["BertForMaskedLM",Z]],["roformer",["RoFormerForMaskedLM",ae]],["electra",["ElectraForMaskedLM",Me]],["esm",["EsmForMaskedLM",He]],["convbert",["ConvBertForMaskedLM",_e]],["camembert",["CamembertForMaskedLM",ve]],["deberta",["DebertaForMaskedLM",Ee]],["deberta-v2",["DebertaV2ForMaskedLM",Oe]],["mpnet",["MPNetForMaskedLM",ot]],["albert",["AlbertForMaskedLM",wt]],["distilbert",["DistilBertForMaskedLM",We]],["roberta",["RobertaForMaskedLM",Ut]],["xlm",["XLMWithLMHeadModel",Yt]],["xlm-roberta",["XLMRobertaForMaskedLM",rs]],["mobilebert",["MobileBertForMaskedLM",et]],["squeezebert",["SqueezeBertForMaskedLM",ut]]]),Ja=new Map([["bert",["BertForQuestionAnswering",se]],["roformer",["RoFormerForQuestionAnswering",de]],["electra",["ElectraForQuestionAnswering",ye]],["convbert",["ConvBertForQuestionAnswering",fe]],["camembert",["CamembertForQuestionAnswering",Ce]],["deberta",["DebertaForQuestionAnswering",ze]],["deberta-v2",["DebertaV2ForQuestionAnswering",De]],["mpnet",["MPNetForQuestionAnswering",lt]],["albert",["AlbertForQuestionAnswering",gt]],["distilbert",["DistilBertForQuestionAnswering",Ue]],["roberta",["RobertaForQuestionAnswering",Qt]],["xlm",["XLMForQuestionAnswering",es]],["xlm-roberta",["XLMRobertaForQuestionAnswering",is]],["mobilebert",["MobileBertForQuestionAnswering",st]],["squeezebert",["SqueezeBertForQuestionAnswering",_t]]]),Ya=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",_s]],["idefics3",["Idefics3ForConditionalGeneration",xs]]]),Ka=new Map([["llava",["LlavaForConditionalGeneration",hs]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",fs]],["moondream1",["Moondream1ForConditionalGeneration",gs]],["florence2",["Florence2ForConditionalGeneration",Ms]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Nr]],["idefics3",["Idefics3ForConditionalGeneration",xs]]]),Za=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",_s]]]),el=new Map([["vit",["ViTForImageClassification",en]],["pvt",["PvtForImageClassification",on]],["vit_msn",["ViTMSNForImageClassification",un]],["fastvit",["FastViTForImageClassification",fn]],["mobilevit",["MobileViTForImageClassification",xn]],["mobilevitv2",["MobileViTV2ForImageClassification",Tn]],["beit",["BeitForImageClassification",In]],["deit",["DeiTForImageClassification",Jn]],["hiera",["HieraForImageClassification",Zn]],["convnext",["ConvNextForImageClassification",Eo]],["convnextv2",["ConvNextV2ForImageClassification",zo]],["dinov2",["Dinov2ForImageClassification",Oo]],["resnet",["ResNetForImageClassification",so]],["swin",["SwinForImageClassification",oo]],["segformer",["SegformerForImageClassification",ea]],["efficientnet",["EfficientNetForImageClassification",aa]],["mobilenet_v1",["MobileNetV1ForImageClassification",ma]],["mobilenet_v2",["MobileNetV2ForImageClassification",ga]],["mobilenet_v3",["MobileNetV3ForImageClassification",ba]],["mobilenet_v4",["MobileNetV4ForImageClassification",ka]]]),tl=new Map([["detr",["DetrForObjectDetection",Nn]],["rt_detr",["RTDetrForObjectDetection",Gn]],["table-transformer",["TableTransformerForObjectDetection",Wn]],["yolos",["YolosForObjectDetection",Do]]]),sl=new Map([["owlvit",["OwlViTForObjectDetection",Fn]],["owlv2",["Owlv2ForObjectDetection",Sn]]]),rl=new Map([["detr",["DetrForSegmentation",On]],["clipseg",["CLIPSegForImageSegmentation",Ds]]]),nl=new Map([["segformer",["SegformerForSemanticSegmentation",ta]],["sapiens",["SapiensForSemanticSegmentation",fo]]]),ol=new Map([["detr",["DetrForSegmentation",On]],["maskformer",["MaskFormerForInstanceSegmentation",ko]]]),il=new Map([["sam",["SamModel",$o]]]),al=new Map([["wav2vec2",["Wav2Vec2ForCTC",Zo]],["wav2vec2-bert",["Wav2Vec2BertForCTC",wi]],["unispeech",["UniSpeechForCTC",ci]],["unispeech-sat",["UniSpeechSatForCTC",_i]],["wavlm",["WavLMForCTC",Pi]],["hubert",["HubertForCTC",yi]]]),ll=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ei]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Mi]],["unispeech",["UniSpeechForSequenceClassification",di]],["unispeech-sat",["UniSpeechSatForSequenceClassification",mi]],["wavlm",["WavLMForSequenceClassification",Fi]],["hubert",["HubertForSequenceClassification",ki]],["audio-spectrogram-transformer",["ASTForAudioClassification",cs]]]),cl=new Map([["wavlm",["WavLMForXVector",Ci]]]),dl=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",hi]],["wavlm",["WavLMForAudioFrameClassification",Ai]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ti]],["pyannote",["PyAnnoteForAudioFrameClassification",ni]]]),ul=new Map([["vitmatte",["VitMatteForImageMatting",wn]]]),pl=new Map([["patchtst",["PatchTSTForPrediction",Ia]],["patchtsmixer",["PatchTSMixerForPrediction",Na]]]),_l=new Map([["swin2sr",["Swin2SRForImageSuperResolution",lo]]]),ml=new Map([["dpt",["DPTForDepthEstimation",po]],["depth_anything",["DepthAnythingForDepthEstimation",mo]],["glpn",["GLPNForDepthEstimation",Po]],["sapiens",["SapiensForDepthEstimation",go]],["depth_pro",["DepthProForDepthEstimation",bo]]]),hl=new Map([["sapiens",["SapiensForNormalEstimation",wo]]]),fl=new Map([["vitpose",["VitPoseForPoseEstimation",sn]]]),gl=new Map([["clip",["CLIPVisionModelWithProjection",Fs]],["siglip",["SiglipVisionModel",Es]],["jina_clip",["JinaCLIPVisionModel",Os]]]),wl=[[Ba,b],[Va,x],[Da,T],[qa,b],[Ua,b],[Wa,y],[Ra,y],[Xa,T],[Qa,C],[Ha,b],[Ja,b],[Ya,k],[Ka,P],[el,b],[rl,b],[ol,b],[nl,b],[ul,b],[pl,b],[_l,b],[ml,b],[hl,b],[fl,b],[tl,b],[sl,b],[il,v],[al,b],[ll,b],[Ga,y],[$a,b],[cl,b],[dl,b],[gl,b]];for(const[e,t]of wl)for(const[s,r]of e.values())A.set(s,t),E.set(r,s),S.set(s,r);const Ml=[["MusicgenForConditionalGeneration",ua,F],["CLIPTextModelWithProjection",vs,b],["SiglipTextModel",Ss,b],["JinaCLIPTextModel",Ns,b],["ClapTextModelWithProjection",Qi,b],["ClapAudioModelWithProjection",Hi,b]];for(const[e,t,s]of Ml)A.set(e,s),E.set(t,e),S.set(e,t);class bl extends Oa{static MODEL_CLASS_MAPPINGS=wl.map((e=>e[0]));static BASE_IF_FAIL=!0}class xl extends Oa{static MODEL_CLASS_MAPPINGS=[qa]}class yl extends Oa{static MODEL_CLASS_MAPPINGS=[Ua]}class kl extends Oa{static MODEL_CLASS_MAPPINGS=[Wa]}class Tl extends Oa{static MODEL_CLASS_MAPPINGS=[Ra]}class vl extends Oa{static MODEL_CLASS_MAPPINGS=[Ga]}class Pl extends Oa{static MODEL_CLASS_MAPPINGS=[$a]}class Fl extends Oa{static MODEL_CLASS_MAPPINGS=[Xa]}class Cl extends Oa{static MODEL_CLASS_MAPPINGS=[Ha]}class Al extends Oa{static MODEL_CLASS_MAPPINGS=[Ja]}class Sl extends Oa{static MODEL_CLASS_MAPPINGS=[Ya]}class El extends Oa{static MODEL_CLASS_MAPPINGS=[el]}class Ll extends Oa{static MODEL_CLASS_MAPPINGS=[rl]}class Il extends Oa{static MODEL_CLASS_MAPPINGS=[nl]}class zl extends Oa{static MODEL_CLASS_MAPPINGS=[ol]}class jl extends Oa{static MODEL_CLASS_MAPPINGS=[tl]}class Nl extends Oa{static MODEL_CLASS_MAPPINGS=[sl]}class Ol extends Oa{static MODEL_CLASS_MAPPINGS=[il]}class Bl extends Oa{static MODEL_CLASS_MAPPINGS=[al]}class Vl extends Oa{static MODEL_CLASS_MAPPINGS=[ll]}class Dl extends Oa{static MODEL_CLASS_MAPPINGS=[cl]}class Rl extends Oa{static MODEL_CLASS_MAPPINGS=[dl]}class Gl extends Oa{static MODEL_CLASS_MAPPINGS=[Za]}class $l extends Oa{static MODEL_CLASS_MAPPINGS=[ul]}class ql extends Oa{static MODEL_CLASS_MAPPINGS=[_l]}class Ul extends Oa{static MODEL_CLASS_MAPPINGS=[ml]}class Wl extends Oa{static MODEL_CLASS_MAPPINGS=[hl]}class Xl extends Oa{static MODEL_CLASS_MAPPINGS=[fl]}class Ql extends Oa{static MODEL_CLASS_MAPPINGS=[gl]}class Hl extends H{constructor({logits:e,past_key_values:t,encoder_outputs:s,decoder_attentions:r=null,cross_attentions:n=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=s,this.decoder_attentions=r,this.cross_attentions=n}}class Jl extends H{constructor({logits:e}){super(),this.logits=e}}class Yl extends H{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class Kl extends H{constructor({logits:e}){super(),this.logits=e}}class Zl extends H{constructor({logits:e}){super(),this.logits=e}}class ec extends H{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class tc extends H{constructor({logits:e}){super(),this.logits=e}}class sc extends H{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class rc extends H{constructor({alphas:e}){super(),this.alphas=e}}class nc extends H{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":
|
|
122
|
-
/*!******************************************************************************************************!*\
|
|
123
|
-
!*** ./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js ***!
|
|
124
|
-
\******************************************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTFeatureExtractor:()=>o});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=(s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),s(/*! ../../utils/audio.js */"./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return(0,n.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){(0,r.validate_audio_inputs)(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const e=2*this.std,s=t.data;for(let t=0;t<s.length;++t)s[t]=(s[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}}},"./src/models/auto/feature_extraction_auto.js":
|
|
125
|
-
/*!****************************************************!*\
|
|
126
|
-
!*** ./src/models/auto/feature_extraction_auto.js ***!
|
|
127
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoFeatureExtractor:()=>i});var r=s(/*! ../../utils/constants.js */"./src/utils/constants.js"),n=s(/*! ../../utils/hub.js */"./src/utils/hub.js"),o=(s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),s(/*! ../feature_extractors.js */"./src/models/feature_extractors.js"));class i{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.FEATURE_EXTRACTOR_NAME,!0,t),i=s.feature_extractor_type,a=o[i];if(!a)throw new Error(`Unknown feature_extractor_type: '${i}'. Please report this at ${r.GITHUB_ISSUE_URL}.`);return new a(s)}}},"./src/models/auto/image_processing_auto.js":
|
|
128
|
-
/*!**************************************************!*\
|
|
129
|
-
!*** ./src/models/auto/image_processing_auto.js ***!
|
|
130
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoImageProcessor:()=>a});var r=s(/*! ../../utils/constants.js */"./src/utils/constants.js"),n=s(/*! ../../utils/hub.js */"./src/utils/hub.js"),o=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),i=s(/*! ../image_processors.js */"./src/models/image_processors.js");class a{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.IMAGE_PROCESSOR_NAME,!0,t),a=s.image_processor_type??s.feature_extractor_type;let l=i[a];return l||(void 0!==a&&console.warn(`Image processor type '${a}' not found, assuming base ImageProcessor. Please report this at ${r.GITHUB_ISSUE_URL}.`),l=o.ImageProcessor),new l(s)}}},"./src/models/auto/processing_auto.js":
|
|
131
|
-
/*!********************************************!*\
|
|
132
|
-
!*** ./src/models/auto/processing_auto.js ***!
|
|
133
|
-
\********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoProcessor:()=>c});var r=s(/*! ../../utils/constants.js */"./src/utils/constants.js"),n=s(/*! ../../utils/hub.js */"./src/utils/hub.js"),o=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),i=s(/*! ../processors.js */"./src/models/processors.js"),a=s(/*! ../image_processors.js */"./src/models/image_processors.js"),l=s(/*! ../feature_extractors.js */"./src/models/feature_extractors.js");class c{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.IMAGE_PROCESSOR_NAME,!0,t),{image_processor_type:c,feature_extractor_type:d,processor_class:u}=s;if(u&&i[u])return i[u].from_pretrained(e,t);if(!c&&!d)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const p={};if(c){const e=a[c];if(!e)throw new Error(`Unknown image_processor_type: '${c}'.`);p.image_processor=new e(s)}if(d){const e=a[d];if(e)p.image_processor=new e(s);else{const e=l[d];if(!e)throw new Error(`Unknown feature_extractor_type: '${d}'.`);p.feature_extractor=new e(s)}}return new o.Processor({},p)}}},"./src/models/beit/image_processing_beit.js":
|
|
134
|
-
/*!**************************************************!*\
|
|
135
|
-
!*** ./src/models/beit/image_processing_beit.js ***!
|
|
136
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{BeitFeatureExtractor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":
|
|
137
|
-
/*!************************************************!*\
|
|
138
|
-
!*** ./src/models/bit/image_processing_bit.js ***!
|
|
139
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{BitImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":
|
|
140
|
-
/*!******************************************************************!*\
|
|
141
|
-
!*** ./src/models/chinese_clip/image_processing_chinese_clip.js ***!
|
|
142
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ChineseCLIPFeatureExtractor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":
|
|
143
|
-
/*!****************************************************!*\
|
|
144
|
-
!*** ./src/models/clap/feature_extraction_clap.js ***!
|
|
145
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ClapFeatureExtractor:()=>o});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=(s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),s(/*! ../../utils/audio.js */"./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e),this.mel_filters=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,s,r){let n,o=!1;const i=e.length-t;if(i>0){if("rand_trunc"!==s)throw new Error(`Truncation strategy "${s}" not implemented`);{o=!0;const s=Math.floor(Math.random()*(i+1));e=e.subarray(s,s+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}}else{if(i<0){let s=new Float64Array(t);if(s.set(e),"repeat"===r)for(let r=e.length;r<t;r+=e.length)s.set(e.subarray(0,Math.min(e.length,t-r)),r);else if("repeatpad"===r)for(let t=e.length;t<-i;t+=e.length)s.set(e,t);e=s}if("fusion"===s)throw new Error(`Truncation strategy "${s}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,s=null){return(0,n.spectrogram)(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){(0,r.validate_audio_inputs)(e,"ClapFeatureExtractor");return{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}},"./src/models/clip/image_processing_clip.js":
|
|
146
|
-
/*!**************************************************!*\
|
|
147
|
-
!*** ./src/models/clip/image_processing_clip.js ***!
|
|
148
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/convnext/image_processing_convnext.js":
|
|
149
|
-
/*!**********************************************************!*\
|
|
150
|
-
!*** ./src/models/convnext/image_processing_convnext.js ***!
|
|
151
|
-
\**********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{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 s=Math.floor(t/this.crop_pct),[r,n]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(r,n,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class o extends n{}},"./src/models/deit/image_processing_deit.js":
|
|
152
|
-
/*!**************************************************!*\
|
|
153
|
-
!*** ./src/models/deit/image_processing_deit.js ***!
|
|
154
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/detr/image_processing_detr.js":
|
|
155
|
-
/*!**************************************************!*\
|
|
156
|
-
!*** ./src/models/detr/image_processing_detr.js ***!
|
|
157
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e){const t=await super._call(e),s=[t.pixel_values.dims[0],64,64],r=(0,n.full)(s,1n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}post_process_panoptic_segmentation(...e){return(0,r.post_process_panoptic_segmentation)(...e)}post_process_instance_segmentation(...e){return(0,r.post_process_instance_segmentation)(...e)}}class i extends o{}},"./src/models/donut/image_processing_donut.js":
|
|
158
|
-
/*!****************************************************!*\
|
|
159
|
-
!*** ./src/models/donut/image_processing_donut.js ***!
|
|
160
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{pad_image(e,t,s,r={}){const[n,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,s,{center:!0,constant_values:c,...r})}}class o extends n{}},"./src/models/dpt/image_processing_dpt.js":
|
|
161
|
-
/*!************************************************!*\
|
|
162
|
-
!*** ./src/models/dpt/image_processing_dpt.js ***!
|
|
163
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/efficientnet/image_processing_efficientnet.js":
|
|
164
|
-
/*!******************************************************************!*\
|
|
165
|
-
!*** ./src/models/efficientnet/image_processing_efficientnet.js ***!
|
|
166
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{EfficientNetImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{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)))}}},"./src/models/feature_extractors.js":
|
|
167
|
-
/*!******************************************!*\
|
|
168
|
-
!*** ./src/models/feature_extractors.js ***!
|
|
169
|
-
\******************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTFeatureExtractor:()=>r.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,ImageFeatureExtractor:()=>u.ImageProcessor,PyAnnoteFeatureExtractor:()=>o.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>i.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>a.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>l.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>c.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor});var r=s(/*! ./audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js */"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=s(/*! ./clap/feature_extraction_clap.js */"./src/models/clap/feature_extraction_clap.js"),o=s(/*! ./pyannote/feature_extraction_pyannote.js */"./src/models/pyannote/feature_extraction_pyannote.js"),i=s(/*! ./seamless_m4t/feature_extraction_seamless_m4t.js */"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),a=s(/*! ./speecht5/feature_extraction_speecht5.js */"./src/models/speecht5/feature_extraction_speecht5.js"),l=s(/*! ./wav2vec2/feature_extraction_wav2vec2.js */"./src/models/wav2vec2/feature_extraction_wav2vec2.js"),c=s(/*! ./wespeaker/feature_extraction_wespeaker.js */"./src/models/wespeaker/feature_extraction_wespeaker.js"),d=s(/*! ./whisper/feature_extraction_whisper.js */"./src/models/whisper/feature_extraction_whisper.js"),u=s(/*! ../base/image_processors_utils.js */"./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":
|
|
170
|
-
/*!******************************************************!*\
|
|
171
|
-
!*** ./src/models/florence2/processing_florence2.js ***!
|
|
172
|
-
\******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Florence2Processor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(e,t){super(e,t);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:r,task_prompts_with_input:n}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(r??{})),this.task_prompts_with_input=new Map(Object.entries(n??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){"string"==typeof e&&(e=[e]);const t=[];for(const s of e)if(this.task_prompts_without_inputs.has(s))t.push(this.task_prompts_without_inputs.get(s));else{for(const[e,r]of this.task_prompts_with_input)if(s.includes(e)){t.push(r.replaceAll("{input}",s).replaceAll(e,""));break}t.length!==e.length&&t.push(s)}return t}post_process_generation(e,t,s){const r=this.tasks_answer_post_processing_type.get(t)??"pure_text";let n;switch(e=e.replaceAll("<s>","").replaceAll("</s>",""),r){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const o="ocr"===r?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[o]),a=[],l=[];for(const[e,t,...r]of i)a.push(t?t.trim():a.at(-1)??""),l.push(r.map(((e,t)=>(Number(e)+.5)/this.size_per_bin*s[t%2])));n={labels:a,[o]:l};break;default:throw new Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...await this.image_processor(e,s),...t?this.tokenizer(t,s):{}}}}},"./src/models/glpn/image_processing_glpn.js":
|
|
173
|
-
/*!**************************************************!*\
|
|
174
|
-
!*** ./src/models/glpn/image_processing_glpn.js ***!
|
|
175
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{GLPNFeatureExtractor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":
|
|
176
|
-
/*!**********************************************************!*\
|
|
177
|
-
!*** ./src/models/idefics3/image_processing_idefics3.js ***!
|
|
178
|
-
\**********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Idefics3ImageProcessor:()=>o});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.ImageProcessor{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[s,r]=e.dims.slice(-2);const n=r/s;return r>=s?(r=Math.ceil(r/t)*t,s=Math.floor(r/n),s=Math.ceil(s/t)*t):(s=Math.ceil(s/t)*t,r=Math.floor(s*n),r=Math.ceil(r/t)*t),{height:s,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:s=!1}={}){let r;if(Array.isArray(e)){if(0===e.length||!e[0])throw new Error("No images provided.");r=Array.isArray(e[0])?e:[e]}else r=[[e]];let o=[],i=[],a=[];const l=[],c=[];for(const e of r){let s=await Promise.all(e.map((e=>this.preprocess(e))));l.push(...s.map((e=>e.original_size))),c.push(...s.map((e=>e.reshaped_input_size))),s.forEach((e=>e.pixel_values.unsqueeze_(0)));const{longest_edge:r}=this.max_image_size;let d;if(t??this.do_image_splitting){let e=new Array(s.length),t=new Array(s.length);d=await Promise.all(s.map((async(s,o)=>{const i=this.get_resize_for_vision_encoder(s.pixel_values,r),a=await(0,n.interpolate_4d)(s.pixel_values,{size:[i.height,i.width]}),{frames:l,num_splits_h:c,num_splits_w:d}=await this.split_image(a,this.max_image_size);return e[o]=c,t[o]=d,(0,n.cat)(l,0)}))),i.push(e),a.push(t)}else{const e=[r,r];d=await Promise.all(s.map((t=>(0,n.interpolate_4d)(t.pixel_values,{size:e})))),i.push(new Array(s.length).fill(0)),a.push(new Array(s.length).fill(0))}o.push((0,n.cat)(d,0))}const d=o.length,[u,p,_,m]=o[0].dims;let h,f;if(1===d)h=o[0].unsqueeze_(0),f=(0,n.full)([d,u,_,m],!0);else{const e=Math.max(...o.map((e=>e.dims.at(0))));f=(0,n.full)([d,e,_,m],!0);const t=f.data,s=e*_*m;for(let r=0;r<d;++r){const i=o[r].dims[0];if(i<e){o[r]=(0,n.cat)([o[r],(0,n.full)([e-i,p,_,m],0)],0);const a=r*s+i*_*m,l=(r+1)*s;t.fill(!1,a,l)}}h=(0,n.stack)(o,0)}return{pixel_values:h,pixel_attention_mask:f,original_sizes:l,reshaped_input_sizes:c,...s?{rows:i,cols:a}:{}}}async split_image(e,{longest_edge:t}){const s=t,r=t,o=[],[i,a]=e.dims.slice(-2);let l=0,c=0;if(i>s||a>r){l=Math.ceil(i/s),c=Math.ceil(a/r);const t=Math.ceil(i/l),d=Math.ceil(a/c);for(let s=0;s<l;s++)for(let r=0;r<c;r++){const n=r*d,l=s*t,c=Math.min(n+d,a),u=Math.min(l+t,i);o.push(e.slice(null,null,[l,u],[n,c]))}const u=s,p=r;i===u&&a===p||(e=await(0,n.interpolate_4d)(e,{size:[u,p]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}}},"./src/models/idefics3/processing_idefics3.js":
|
|
179
|
-
/*!****************************************************!*\
|
|
180
|
-
!*** ./src/models/idefics3/processing_idefics3.js ***!
|
|
181
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Idefics3Processor:()=>l});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js"),i=(s(/*! ../../utils/image.js */"./src/utils/image.js"),s(/*! ../../utils/core.js */"./src/utils/core.js"));function a(e,t,s,r,n,o){return 0===e&&0===t?function(e,t,s,r){return`${t}${r}`+s.repeat(e)+`${t}`}(s,r,n,o):function(e,t,s,r,n,o){let i="";for(let o=0;o<t;++o){for(let t=0;t<s;++t)i+=r+`<row_${o+1}_col_${t+1}>`+n.repeat(e);i+="\n"}return i+=`\n${r}${o}`+n.repeat(e)+`${r}`,i}(s,e,t,r,n,o)}class l extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,s={}){let r;s.return_row_col_info??=!0,t&&(r=await this.image_processor(t,s)),Array.isArray(e)||(e=[e]);const n=r.rows??[new Array(e.length).fill(0)],o=r.cols??[new Array(e.length).fill(0)],l=this.config.image_seq_len,c=[],d=[];for(let t=0;t<e.length;++t){const s=e[t],r=n[t],u=o[t];c.push((0,i.count)(s,this.image_token));const p=r.map(((e,t)=>a(e,u[t],l,this.fake_image_token,this.image_token,this.global_img_token))),_=s.split(this.image_token);if(0===_.length)throw new Error("The image token should be present in the text.");let m=_[0];for(let e=0;e<p.length;++e)m+=p[e]+_[e+1];d.push(m)}return{...this.tokenizer(d),...r}}}},"./src/models/image_processors.js":
|
|
182
|
-
/*!****************************************!*\
|
|
183
|
-
!*** ./src/models/image_processors.js ***!
|
|
184
|
-
\****************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{BeitFeatureExtractor:()=>r.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>p.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>m.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>w.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>M.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>M.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>b.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>b.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>y.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>y.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>v.NougatImageProcessor,OwlViTFeatureExtractor:()=>F.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>F.OwlViTImageProcessor,Owlv2ImageProcessor:()=>P.Owlv2ImageProcessor,PvtImageProcessor:()=>C.PvtImageProcessor,Qwen2VLImageProcessor:()=>A.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>S.RTDetrImageProcessor,SamImageProcessor:()=>E.SamImageProcessor,SegformerFeatureExtractor:()=>L.SegformerFeatureExtractor,SegformerImageProcessor:()=>L.SegformerImageProcessor,SiglipImageProcessor:()=>I.SiglipImageProcessor,Swin2SRImageProcessor:()=>z.Swin2SRImageProcessor,VLMImageProcessor:()=>h.VLMImageProcessor,ViTFeatureExtractor:()=>j.ViTFeatureExtractor,ViTImageProcessor:()=>j.ViTImageProcessor,VitMatteImageProcessor:()=>N.VitMatteImageProcessor,VitPoseImageProcessor:()=>O.VitPoseImageProcessor,YolosFeatureExtractor:()=>B.YolosFeatureExtractor,YolosImageProcessor:()=>B.YolosImageProcessor});var r=s(/*! ./beit/image_processing_beit.js */"./src/models/beit/image_processing_beit.js"),n=s(/*! ./bit/image_processing_bit.js */"./src/models/bit/image_processing_bit.js"),o=s(/*! ./chinese_clip/image_processing_chinese_clip.js */"./src/models/chinese_clip/image_processing_chinese_clip.js"),i=s(/*! ./clip/image_processing_clip.js */"./src/models/clip/image_processing_clip.js"),a=s(/*! ./convnext/image_processing_convnext.js */"./src/models/convnext/image_processing_convnext.js"),l=s(/*! ./deit/image_processing_deit.js */"./src/models/deit/image_processing_deit.js"),c=s(/*! ./detr/image_processing_detr.js */"./src/models/detr/image_processing_detr.js"),d=s(/*! ./donut/image_processing_donut.js */"./src/models/donut/image_processing_donut.js"),u=s(/*! ./dpt/image_processing_dpt.js */"./src/models/dpt/image_processing_dpt.js"),p=s(/*! ./efficientnet/image_processing_efficientnet.js */"./src/models/efficientnet/image_processing_efficientnet.js"),_=s(/*! ./glpn/image_processing_glpn.js */"./src/models/glpn/image_processing_glpn.js"),m=s(/*! ./idefics3/image_processing_idefics3.js */"./src/models/idefics3/image_processing_idefics3.js"),h=s(/*! ./janus/image_processing_janus.js */"./src/models/janus/image_processing_janus.js"),f=s(/*! ./jina_clip/image_processing_jina_clip.js */"./src/models/jina_clip/image_processing_jina_clip.js"),g=s(/*! ./llava_onevision/image_processing_llava_onevision.js */"./src/models/llava_onevision/image_processing_llava_onevision.js"),w=s(/*! ./mask2former/image_processing_mask2former.js */"./src/models/mask2former/image_processing_mask2former.js"),M=s(/*! ./maskformer/image_processing_maskformer.js */"./src/models/maskformer/image_processing_maskformer.js"),b=s(/*! ./mobilenet_v1/image_processing_mobilenet_v1.js */"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=s(/*! ./mobilenet_v2/image_processing_mobilenet_v2.js */"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),y=s(/*! ./mobilenet_v3/image_processing_mobilenet_v3.js */"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=s(/*! ./mobilenet_v4/image_processing_mobilenet_v4.js */"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=s(/*! ./mobilevit/image_processing_mobilevit.js */"./src/models/mobilevit/image_processing_mobilevit.js"),v=s(/*! ./nougat/image_processing_nougat.js */"./src/models/nougat/image_processing_nougat.js"),P=s(/*! ./owlv2/image_processing_owlv2.js */"./src/models/owlv2/image_processing_owlv2.js"),F=s(/*! ./owlvit/image_processing_owlvit.js */"./src/models/owlvit/image_processing_owlvit.js"),C=s(/*! ./pvt/image_processing_pvt.js */"./src/models/pvt/image_processing_pvt.js"),A=s(/*! ./qwen2_vl/image_processing_qwen2_vl.js */"./src/models/qwen2_vl/image_processing_qwen2_vl.js"),S=s(/*! ./rt_detr/image_processing_rt_detr.js */"./src/models/rt_detr/image_processing_rt_detr.js"),E=s(/*! ./sam/image_processing_sam.js */"./src/models/sam/image_processing_sam.js"),L=s(/*! ./segformer/image_processing_segformer.js */"./src/models/segformer/image_processing_segformer.js"),I=s(/*! ./siglip/image_processing_siglip.js */"./src/models/siglip/image_processing_siglip.js"),z=s(/*! ./swin2sr/image_processing_swin2sr.js */"./src/models/swin2sr/image_processing_swin2sr.js"),j=s(/*! ./vit/image_processing_vit.js */"./src/models/vit/image_processing_vit.js"),N=s(/*! ./vitmatte/image_processing_vitmatte.js */"./src/models/vitmatte/image_processing_vitmatte.js"),O=s(/*! ./vitpose/image_processing_vitpose.js */"./src/models/vitpose/image_processing_vitpose.js"),B=s(/*! ./yolos/image_processing_yolos.js */"./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":
|
|
185
|
-
/*!****************************************************!*\
|
|
186
|
-
!*** ./src/models/janus/image_processing_janus.js ***!
|
|
187
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{VLMImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map((e=>e*this.rescale_factor))}pad_image(e,t,s,r){return super.pad_image(e,t,s,{constant_values:this.constant_values,center:!0,...r})}}},"./src/models/janus/processing_janus.js":
|
|
188
|
-
/*!**********************************************!*\
|
|
189
|
-
!*** ./src/models/janus/processing_janus.js ***!
|
|
190
|
-
\**********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{VLChatProcessor:()=>c});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js"),i=s(/*! ../../utils/core.js */"./src/utils/core.js"),a=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),l=s(/*! ../../utils/image.js */"./src/utils/image.js");class c extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(e,t){super(e,t),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:s="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter((e=>e.images)).flatMap((e=>e.images)).map((e=>l.RawImage.read(e))));const r=this.tokenizer,n=e=>r.encode(e,{add_special_tokens:!1}),o=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}).split(this.image_tag),c=o.length-1;if(t.length!==c)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${c})`);const[d,u,p]=r.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let _=n(o[0]),m=new Array(_.length).fill(!1);for(let e=1;e<o.length;++e){const t=new Array(this.num_image_tokens).fill(d),s=n(o[e]);_=(0,i.mergeArrays)(_,[u],t,[p],s);const r=new Array(this.num_image_tokens).fill(!0);m=(0,i.mergeArrays)(m,[!1],r,[!1],new Array(s.length).fill(!1))}const h=[1,_.length],f={input_ids:new a.Tensor("int64",_,h),attention_mask:new a.Tensor("int64",new Array(_.length).fill(1),h),images_seq_mask:new a.Tensor("bool",m,h),images_emb_mask:new a.Tensor("bool",new Array(c*this.num_image_tokens).fill(!0),[1,c,this.num_image_tokens])};if(t&&t.length>0){const e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...f,...e}}return f}}},"./src/models/jina_clip/image_processing_jina_clip.js":
|
|
191
|
-
/*!************************************************************!*\
|
|
192
|
-
!*** ./src/models/jina_clip/image_processing_jina_clip.js ***!
|
|
193
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{JinaCLIPImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{constructor(e){const{resize_mode:t,fill_color:s,interpolation:r,size:n,...o}=e;super({...o,size:"squash"===t?{width:n,height:n}:"shortest"===t?{shortest_edge:n}:{longest_edge:n},resample:"bicubic"===r?3:2,do_center_crop:!0,crop_size:n,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":
|
|
194
|
-
/*!******************************************************!*\
|
|
195
|
-
!*** ./src/models/jina_clip/processing_jina_clip.js ***!
|
|
196
|
-
\******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{JinaCLIPProcessor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(e=null,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...e?this.tokenizer(e,s):{},...t?await this.image_processor(t,s):{}}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":
|
|
197
|
-
/*!************************************************************************!*\
|
|
198
|
-
!*** ./src/models/llava_onevision/image_processing_llava_onevision.js ***!
|
|
199
|
-
\************************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{LlavaOnevisionImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":
|
|
200
|
-
/*!****************************************************************!*\
|
|
201
|
-
!*** ./src/models/mask2former/image_processing_mask2former.js ***!
|
|
202
|
-
\****************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Mask2FormerImageProcessor:()=>n});var r=s(/*! ../maskformer/image_processing_maskformer.js */"./src/models/maskformer/image_processing_maskformer.js");class n extends r.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":
|
|
203
|
-
/*!**************************************************************!*\
|
|
204
|
-
!*** ./src/models/maskformer/image_processing_maskformer.js ***!
|
|
205
|
-
\**************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_panoptic_segmentation(...e){return(0,r.post_process_panoptic_segmentation)(...e)}post_process_instance_segmentation(...e){return(0,r.post_process_instance_segmentation)(...e)}}class o extends n{}},"./src/models/mgp_str/processing_mgp_str.js":
|
|
206
|
-
/*!**************************************************!*\
|
|
207
|
-
!*** ./src/models/mgp_str/processing_mgp_str.js ***!
|
|
208
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MgpstrProcessor:()=>l});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js"),i=s(/*! ../../utils/maths.js */"./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!a.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[s,r]=a[t],n=this[s].bind(this),[o,l]=e.dims,c=[],d=[],u=e.tolist();for(let e=0;e<o;++e){const t=u[e],s=[],n=[];for(let e=1;e<l;++e){const[o,a]=(0,i.max)((0,i.softmax)(t[e]));if(n.push(o),a==r)break;s.push(a)}const o=n.length>0?n.reduce(((e,t)=>e*t),1):0;d.push(s),c.push(o)}return[n(d),c]}char_decode(e){return this.char_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}batch_decode([e,t,s]){const[r,n]=this._decode_helper(e,"char"),[o,a]=this._decode_helper(t,"bpe"),[l,c]=this._decode_helper(s,"wp"),d=[],u=[];for(let e=0;e<r.length;++e){const[t,s]=(0,i.max)([n[e],a[e],c[e]]);d.push([r[e],o[e],l[e]][s]),u.push(t)}return{generated_text:d,scores:u,char_preds:r,bpe_preds:o,wp_preds:l}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),s=await o.AutoTokenizer.from_pretrained("Xenova/gpt2"),r=await o.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:s,wp_tokenizer:r},t}async _call(e,t=null){const s=await this.image_processor(e);return t&&(s.labels=this.tokenizer(t).input_ids),s}}},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":
|
|
209
|
-
/*!******************************************************************!*\
|
|
210
|
-
!*** ./src/models/mobilenet_v1/image_processing_mobilenet_v1.js ***!
|
|
211
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":
|
|
212
|
-
/*!******************************************************************!*\
|
|
213
|
-
!*** ./src/models/mobilenet_v2/image_processing_mobilenet_v2.js ***!
|
|
214
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":
|
|
215
|
-
/*!******************************************************************!*\
|
|
216
|
-
!*** ./src/models/mobilenet_v3/image_processing_mobilenet_v3.js ***!
|
|
217
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":
|
|
218
|
-
/*!******************************************************************!*\
|
|
219
|
-
!*** ./src/models/mobilenet_v4/image_processing_mobilenet_v4.js ***!
|
|
220
|
-
\******************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilevit/image_processing_mobilevit.js":
|
|
221
|
-
/*!************************************************************!*\
|
|
222
|
-
!*** ./src/models/mobilevit/image_processing_mobilevit.js ***!
|
|
223
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/nougat/image_processing_nougat.js":
|
|
224
|
-
/*!******************************************************!*\
|
|
225
|
-
!*** ./src/models/nougat/image_processing_nougat.js ***!
|
|
226
|
-
\******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{NougatImageProcessor:()=>n});var r=s(/*! ../donut/image_processing_donut.js */"./src/models/donut/image_processing_donut.js");class n extends r.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":
|
|
227
|
-
/*!****************************************************!*\
|
|
228
|
-
!*** ./src/models/owlv2/image_processing_owlv2.js ***!
|
|
229
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Owlv2ImageProcessor:()=>n});var r=s(/*! ../owlvit/image_processing_owlvit.js */"./src/models/owlvit/image_processing_owlvit.js");class n extends r.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":
|
|
230
|
-
/*!******************************************************!*\
|
|
231
|
-
!*** ./src/models/owlvit/image_processing_owlvit.js ***!
|
|
232
|
-
\******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}class o extends n{}},"./src/models/owlvit/processing_owlvit.js":
|
|
233
|
-
/*!************************************************!*\
|
|
234
|
-
!*** ./src/models/owlvit/processing_owlvit.js ***!
|
|
235
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{OwlViTProcessor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor}},"./src/models/processors.js":
|
|
236
|
-
/*!**********************************!*\
|
|
237
|
-
!*** ./src/models/processors.js ***!
|
|
238
|
-
\**********************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Florence2Processor:()=>r.Florence2Processor,Idefics3Processor:()=>o.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>n.MgpstrProcessor,OwlViTProcessor:()=>l.OwlViTProcessor,PyAnnoteProcessor:()=>c.PyAnnoteProcessor,Qwen2VLProcessor:()=>d.Qwen2VLProcessor,SamProcessor:()=>u.SamProcessor,SpeechT5Processor:()=>p.SpeechT5Processor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>_.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>m.WhisperProcessor});var r=s(/*! ./florence2/processing_florence2.js */"./src/models/florence2/processing_florence2.js"),n=s(/*! ./mgp_str/processing_mgp_str.js */"./src/models/mgp_str/processing_mgp_str.js"),o=s(/*! ./idefics3/processing_idefics3.js */"./src/models/idefics3/processing_idefics3.js"),i=s(/*! ./janus/processing_janus.js */"./src/models/janus/processing_janus.js"),a=s(/*! ./jina_clip/processing_jina_clip.js */"./src/models/jina_clip/processing_jina_clip.js"),l=s(/*! ./owlvit/processing_owlvit.js */"./src/models/owlvit/processing_owlvit.js"),c=s(/*! ./pyannote/processing_pyannote.js */"./src/models/pyannote/processing_pyannote.js"),d=s(/*! ./qwen2_vl/processing_qwen2_vl.js */"./src/models/qwen2_vl/processing_qwen2_vl.js"),u=s(/*! ./sam/processing_sam.js */"./src/models/sam/processing_sam.js"),p=s(/*! ./speecht5/processing_speecht5.js */"./src/models/speecht5/processing_speecht5.js"),_=s(/*! ./wav2vec2/processing_wav2vec2.js */"./src/models/wav2vec2/processing_wav2vec2.js"),m=s(/*! ./whisper/processing_whisper.js */"./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":
|
|
239
|
-
/*!************************************************!*\
|
|
240
|
-
!*** ./src/models/pvt/image_processing_pvt.js ***!
|
|
241
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{PvtImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":
|
|
242
|
-
/*!************************************************************!*\
|
|
243
|
-
!*** ./src/models/pyannote/feature_extraction_pyannote.js ***!
|
|
244
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{PyAnnoteFeatureExtractor:()=>o});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.FeatureExtractor{async _call(e){(0,r.validate_audio_inputs)(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new n.Tensor("float32",e,t)}}}},"./src/models/pyannote/processing_pyannote.js":
|
|
245
|
-
/*!****************************************************!*\
|
|
246
|
-
!*** ./src/models/pyannote/processing_pyannote.js ***!
|
|
247
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{PyAnnoteProcessor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/feature_extraction_auto.js */"./src/models/auto/feature_extraction_auto.js"),o=s(/*! ../../utils/maths.js */"./src/utils/maths.js");class i extends r.Processor{static feature_extractor_class=n.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const s=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(const t of e.tolist()){const e=[];let n=-1;for(let s=0;s<t.length;++s){const r=(0,o.softmax)(t[s]),[i,a]=(0,o.max)(r),[l,c]=[s,s+1];a!==n?(n=a,e.push({id:a,start:l,end:c,score:i})):(e.at(-1).end=c,e.at(-1).score+=i)}r.push(e.map((({id:e,start:t,end:r,score:n})=>({id:e,start:t*s,end:r*s,confidence:n/(r-t)}))))}return r}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":
|
|
248
|
-
/*!**********************************************************!*\
|
|
249
|
-
!*** ./src/models/qwen2_vl/image_processing_qwen2_vl.js ***!
|
|
250
|
-
\**********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Qwen2VLImageProcessor:()=>o});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e,...t){const{pixel_values:s,original_sizes:r,reshaped_input_sizes:o}=await super._call(e,...t);let i=s;const{temporal_patch_size:a,merge_size:l,patch_size:c}=this.config;1===i.dims[0]&&(i=(0,n.cat)(Array.from({length:a},(()=>i)),0));const d=i.dims[0]/a,u=i.dims[1],p=Math.floor(i.dims[2]/c),_=Math.floor(i.dims[3]/c);return{pixel_values:i.view(d,a,u,Math.floor(p/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(d*p*_,u*a*c*c),image_grid_thw:new n.Tensor("int64",[d,p,_],[1,3]),original_sizes:r,reshaped_input_sizes:o}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":
|
|
251
|
-
/*!****************************************************!*\
|
|
252
|
-
!*** ./src/models/qwen2_vl/processing_qwen2_vl.js ***!
|
|
253
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Qwen2VLProcessor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),o=s(/*! ../../tokenizers.js */"./src/tokenizers.js");s(/*! ../../utils/image.js */"./src/utils/image.js");class i extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(e,t=null,...s){let r,n;if(Array.isArray(e)||(e=[e]),t&&(r=await this.image_processor(t),n=r.image_grid_thw),n){let t=this.image_processor.config.merge_size**2,s=0;const r=n.tolist();e=e.map((e=>{for(;e.includes("<|image_pad|>");){const n=Number(r[s++].reduce(((e,t)=>e*t),1n));e=e.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(n/t)))}return e.replaceAll("<|placeholder|>","<|image_pad|>")}))}return{...this.tokenizer(e),...r}}}},"./src/models/rt_detr/image_processing_rt_detr.js":
|
|
254
|
-
/*!********************************************************!*\
|
|
255
|
-
!*** ./src/models/rt_detr/image_processing_rt_detr.js ***!
|
|
256
|
-
\********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{RTDetrImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}},"./src/models/sam/image_processing_sam.js":
|
|
257
|
-
/*!************************************************!*\
|
|
258
|
-
!*** ./src/models/sam/image_processing_sam.js ***!
|
|
259
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SamImageProcessor:()=>i});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),n=s(/*! ../../utils/core.js */"./src/utils/core.js"),o=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class i extends r.ImageProcessor{reshape_input_points(e,t,s,r=!1){e=structuredClone(e);let i=(0,n.calculateDimensions)(e);if(3===i.length)r||(i=[1,...i]),e=[e];else if(4!==i.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;r<e.length;++r){let n=t[r],o=s[r],i=[o[0]/n[0],o[1]/n[1]];for(let t=0;t<e[r].length;++t)for(let s=0;s<e[r][t].length;++s)for(let n=0;n<e[r][t][s].length;++n)e[r][t][s][n]*=i[n%2]}return new o.Tensor("float32",Float32Array.from(e.flat(1/0)),i)}add_input_labels(e,t){let s=(0,n.calculateDimensions)(e);if(2===s.length)s=[1,...s],e=[e];else if(3!==s.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some(((e,s)=>e!==t.dims[s])))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:t=null,input_labels:s=null,input_boxes:r=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),s){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(s,n.input_points)}return r&&(n.input_boxes=this.reshape_input_points(r,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,s,{mask_threshold:r=0,binarize:n=!0,pad_size:i=null}={}){const a=[],l=[(i=i??this.pad_size).height,i.width];for(let i=0;i<t.length;++i){const c=t[i],d=s[i];let u=await(0,o.interpolate_4d)(e[i],{mode:"bilinear",size:l});if(u=u.slice(null,null,[0,d[0]],[0,d[1]]),u=await(0,o.interpolate_4d)(u,{mode:"bilinear",size:c}),n){const e=u.data,t=new Uint8Array(e.length);for(let s=0;s<e.length;++s)e[s]>r&&(t[s]=1);u=new o.Tensor("bool",t,u.dims)}a.push(u)}return a}generate_crop_boxes(e,t,{crop_n_layers:s=0,overlap_ratio:r=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:o=1}={}){}}},"./src/models/sam/processing_sam.js":
|
|
260
|
-
/*!******************************************!*\
|
|
261
|
-
!*** ./src/models/sam/processing_sam.js ***!
|
|
262
|
-
\******************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SamProcessor:()=>o});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js");class o extends r.Processor{static image_processor_class=n.AutoImageProcessor;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":
|
|
263
|
-
/*!********************************************************************!*\
|
|
264
|
-
!*** ./src/models/seamless_m4t/feature_extraction_seamless_m4t.js ***!
|
|
265
|
-
\********************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SeamlessM4TFeatureExtractor:()=>i});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),o=s(/*! ../../utils/audio.js */"./src/utils/audio.js");class i extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,o.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map((e=>32768*e)),(0,o.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:s=2,do_normalize_per_mel_bins:o=!0,return_attention_mask:i=!0}={}){(0,r.validate_audio_inputs)(e,"SeamlessM4TFeatureExtractor");let a,l=await this._extract_fbank_features(e,this.config.max_length);if(o){const[e,t]=l.dims,s=l.data;for(let r=0;r<t;++r){let n=0;for(let o=0;o<e;++o)n+=s[o*t+r];const o=n/e;let i=0;for(let n=0;n<e;++n)i+=(s[n*t+r]-o)**2;i/=e-1;const a=Math.sqrt(i+1e-7);for(let n=0;n<e;++n){const e=n*t+r;s[e]=(s[e]-o)/a}}}if(t){const[e,t]=l.dims,r=l.data,o=e%s;if(o>0){const s=new Float32Array(t*(e+o));s.set(r),s.fill(this.config.padding_value,r.length);const c=e+o;l=new n.Tensor(l.type,s,[c,t]),i&&(a=new n.Tensor("int64",new BigInt64Array(c),[1,c]),a.data.fill(1n,0,e))}}const[c,d]=l.dims,u=this.config.stride;if(0!==c%u)throw new Error(`The number of frames (${c}) must be a multiple of the stride (${u}).`);const p=l.view(1,Math.floor(c/u),d*u),_={input_features:p};if(i){const e=p.dims[1],t=new BigInt64Array(e);if(a){const e=a.data;for(let s=1,r=0;s<c;s+=u,++r)t[r]=e[s]}else t.fill(1n);_.attention_mask=new n.Tensor("int64",t,[1,e])}return _}}},"./src/models/segformer/image_processing_segformer.js":
|
|
266
|
-
/*!************************************************************!*\
|
|
267
|
-
!*** ./src/models/segformer/image_processing_segformer.js ***!
|
|
268
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_semantic_segmentation(...e){return(0,r.post_process_semantic_segmentation)(...e)}}class o extends n{}},"./src/models/siglip/image_processing_siglip.js":
|
|
269
|
-
/*!******************************************************!*\
|
|
270
|
-
!*** ./src/models/siglip/image_processing_siglip.js ***!
|
|
271
|
-
\******************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SiglipImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":
|
|
272
|
-
/*!************************************************************!*\
|
|
273
|
-
!*** ./src/models/speecht5/feature_extraction_speecht5.js ***!
|
|
274
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SpeechT5FeatureExtractor:()=>n});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js");class n extends r.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":
|
|
275
|
-
/*!****************************************************!*\
|
|
276
|
-
!*** ./src/models/speecht5/processing_speecht5.js ***!
|
|
277
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{SpeechT5Processor:()=>i});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../../tokenizers.js */"./src/tokenizers.js"),o=s(/*! ../auto/feature_extraction_auto.js */"./src/models/auto/feature_extraction_auto.js");class i extends r.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/swin2sr/image_processing_swin2sr.js":
|
|
278
|
-
/*!********************************************************!*\
|
|
279
|
-
!*** ./src/models/swin2sr/image_processing_swin2sr.js ***!
|
|
280
|
-
\********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Swin2SRImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{pad_image(e,t,s,r={}){const[n,o,i]=t;return super.pad_image(e,t,{width:o+(s-o%s)%s,height:n+(s-n%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...r})}}},"./src/models/vit/image_processing_vit.js":
|
|
281
|
-
/*!************************************************!*\
|
|
282
|
-
!*** ./src/models/vit/image_processing_vit.js ***!
|
|
283
|
-
\************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/vitmatte/image_processing_vitmatte.js":
|
|
284
|
-
/*!**********************************************************!*\
|
|
285
|
-
!*** ./src/models/vitmatte/image_processing_vitmatte.js ***!
|
|
286
|
-
\**********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{VitMatteImageProcessor:()=>o});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=await Promise.all(e.map((e=>this.preprocess(e)))),r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})))),o=(0,n.stack)(s.map(((e,t)=>(0,n.cat)([e.pixel_values,r[t].pixel_values],0))),0);return{pixel_values:o,original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}}},"./src/models/vitpose/image_processing_vitpose.js":
|
|
287
|
-
/*!********************************************************!*\
|
|
288
|
-
!*** ./src/models/vitpose/image_processing_vitpose.js ***!
|
|
289
|
-
\********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{VitPoseImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_pose_estimation(e,t,{threshold:s=null}={}){const r=e.tolist(),[n,o,i,a]=e.dims,l=[];for(let e=0;e<n;++e){const n=r[e],o=t[e],c=[];for(let e=0;e<o.length;++e){const t=o[e],r=[],l=[],d=[],u=t.at(-2)/a,p=t.at(-1)/i;for(let e=0;e<n.length;++e){let[t,o]=[0,0],i=0,a=-1/0;const c=n[e];for(let e=0;e<c.length;++e){const s=c[e];for(let r=0;r<s.length;++r){const n=s[r];i+=n,a=Math.max(a,n),t+=(r+.5)*n,o+=e*n}}if(null!=s&&a<s)continue;const _=[u*t/i,p*o/i];r.push(_),d.push(e),l.push(a)}c.push({bbox:t,scores:l,labels:d,keypoints:r})}l.push(c)}return l}}},"./src/models/wav2vec2/feature_extraction_wav2vec2.js":
|
|
290
|
-
/*!************************************************************!*\
|
|
291
|
-
!*** ./src/models/wav2vec2/feature_extraction_wav2vec2.js ***!
|
|
292
|
-
\************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Wav2Vec2FeatureExtractor:()=>o});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=s(/*! ../../utils/tensor.js */"./src/utils/tensor.js");class o extends r.FeatureExtractor{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,s=e.reduce(((e,s)=>e+(s-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(s+1e-7)))}async _call(e){(0,r.validate_audio_inputs)(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const s=[1,t.length];return{input_values:new n.Tensor("float32",t,s),attention_mask:new n.Tensor("int64",new BigInt64Array(t.length).fill(1n),s)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":
|
|
293
|
-
/*!****************************************************!*\
|
|
294
|
-
!*** ./src/models/wav2vec2/processing_wav2vec2.js ***!
|
|
295
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Wav2Vec2ProcessorWithLM:()=>o});var r=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js"),n=s(/*! ../auto/feature_extraction_auto.js */"./src/models/auto/feature_extraction_auto.js");class o extends r.Processor{static feature_extractor_class=n.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":
|
|
296
|
-
/*!**************************************************************!*\
|
|
297
|
-
!*** ./src/models/wespeaker/feature_extraction_wespeaker.js ***!
|
|
298
|
-
\**************************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{WeSpeakerFeatureExtractor:()=>o});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=(s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),s(/*! ../../utils/audio.js */"./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,n.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map((e=>32768*e)),(0,n.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,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){(0,r.validate_audio_inputs)(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){const e=t.mean(1).data,s=t.data,[r,n,o]=t.dims;for(let t=0;t<r;++t){const r=t*n*o,i=t*o;for(let t=0;t<n;++t){const n=r+t*o;for(let t=0;t<o;++t)s[n+t]-=e[i+t]}}}return{input_features:t}}}},"./src/models/whisper/common_whisper.js":
|
|
299
|
-
/*!**********************************************!*\
|
|
300
|
-
!*** ./src/models/whisper/common_whisper.js ***!
|
|
301
|
-
\**********************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{WHISPER_LANGUAGE_MAPPING:()=>n,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>i});const r=[["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"]],n=new Map(r),o=new Map([...r.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"]]);function i(e){e=e.toLowerCase();let t=o.get(e);if(void 0===t){if(!n.has(e)){const t=2===e.length?n.keys():n.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(t)}`)}t=e}return t}},"./src/models/whisper/feature_extraction_whisper.js":
|
|
302
|
-
/*!**********************************************************!*\
|
|
303
|
-
!*** ./src/models/whisper/feature_extraction_whisper.js ***!
|
|
304
|
-
\**********************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperFeatureExtractor:()=>i});var r=s(/*! ../../base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),n=(s(/*! ../../utils/tensor.js */"./src/utils/tensor.js"),s(/*! ../../utils/audio.js */"./src/utils/audio.js")),o=s(/*! ../../utils/maths.js */"./src/utils/maths.js");class i extends r.FeatureExtractor{constructor(e){super(e),this.config.mel_filters??=(0,n.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,n.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await(0,n.spectrogram)(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),s=t.data,r=(0,o.max)(s)[0];for(let e=0;e<s.length;++e)s[e]=(Math.max(s[e],r-8)+4)/4;return t}async _call(e){let t;(0,r.validate_audio_inputs)(e,"WhisperFeatureExtractor"),e.length>this.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));return{input_features:(await this._extract_fbank_features(t)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":
|
|
305
|
-
/*!**************************************************!*\
|
|
306
|
-
!*** ./src/models/whisper/generation_whisper.js ***!
|
|
307
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperGenerationConfig:()=>n});var r=s(/*! ../../generation/configuration_utils.js */"./src/generation/configuration_utils.js");class n extends r.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}},"./src/models/whisper/processing_whisper.js":
|
|
308
|
-
/*!**************************************************!*\
|
|
309
|
-
!*** ./src/models/whisper/processing_whisper.js ***!
|
|
310
|
-
\**************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperProcessor:()=>i});var r=s(/*! ../auto/feature_extraction_auto.js */"./src/models/auto/feature_extraction_auto.js"),n=s(/*! ../../tokenizers.js */"./src/tokenizers.js"),o=s(/*! ../../base/processing_utils.js */"./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=r.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/yolos/image_processing_yolos.js":
|
|
311
|
-
/*!****************************************************!*\
|
|
312
|
-
!*** ./src/models/yolos/image_processing_yolos.js ***!
|
|
313
|
-
\****************************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>n});var r=s(/*! ../../base/image_processors_utils.js */"./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}class o extends n{}},"./src/ops/registry.js":
|
|
314
|
-
/*!*****************************!*\
|
|
315
|
-
!*** ./src/ops/registry.js ***!
|
|
316
|
-
\*****************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{TensorOpRegistry:()=>i});var r=s(/*! ../backends/onnx.js */"./src/backends/onnx.js"),n=s(/*! ../utils/tensor.js */"./src/utils/tensor.js");const o=async(e,t,s)=>{const o=await(0,r.createInferenceSession)(new Uint8Array(e),t);return async e=>{const t=Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.ort_tensor]))),r=await o.run(t);return Array.isArray(s)?s.map((e=>new n.Tensor(r[e]))):new n.Tensor(r[s])}};class i{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o([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([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}static get matmul(){return this._matmul||(this._matmul=o([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=o([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=o([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=o([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}},"./src/pipelines.js":
|
|
317
|
-
/*!**************************!*\
|
|
318
|
-
!*** ./src/pipelines.js ***!
|
|
319
|
-
\**************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AudioClassificationPipeline:()=>C,AutomaticSpeechRecognitionPipeline:()=>S,DepthEstimationPipeline:()=>D,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>P,FillMaskPipeline:()=>M,ImageClassificationPipeline:()=>L,ImageFeatureExtractionPipeline:()=>F,ImageSegmentationPipeline:()=>I,ImageToImagePipeline:()=>V,ImageToTextPipeline:()=>E,ObjectDetectionPipeline:()=>j,Pipeline:()=>h,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>b,TextClassificationPipeline:()=>f,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>B,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>y,ZeroShotAudioClassificationPipeline:()=>A,ZeroShotClassificationPipeline:()=>v,ZeroShotImageClassificationPipeline:()=>z,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>$});var r=s(/*! ./tokenizers.js */"./src/tokenizers.js"),n=s(/*! ./models.js */"./src/models.js"),o=s(/*! ./models/auto/processing_auto.js */"./src/models/auto/processing_auto.js"),i=(s(/*! ./base/processing_utils.js */"./src/base/processing_utils.js"),s(/*! ./utils/generic.js */"./src/utils/generic.js")),a=s(/*! ./utils/core.js */"./src/utils/core.js"),l=s(/*! ./utils/maths.js */"./src/utils/maths.js"),c=s(/*! ./utils/audio.js */"./src/utils/audio.js"),d=s(/*! ./utils/tensor.js */"./src/utils/tensor.js"),u=s(/*! ./utils/image.js */"./src/utils/image.js");async function p(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>u.RawImage.read(e))))}async function _(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 m(e,t){t&&(e=e.map((e=>0|e)));const[s,r,n,o]=e;return{xmin:s,ymin:r,xmax:n,ymax:o}}class h extends i.Callable{constructor({task:e,model:t,tokenizer:s=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=s,this.processor=r}async dispose(){await this.model.dispose()}}class f extends h{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(s),n="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid():e=>new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),o=this.model.config.id2label,i=[];for(const e of r.logits){const s=n(e),r=await(0,d.topk)(s,t),a=r[0].tolist(),l=r[1].tolist().map(((e,t)=>({label:o?o[e]:`LABEL_${e}`,score:a[t]})));1===t?i.push(...l):i.push(l)}return Array.isArray(e)||1===t?i:i[0]}}class g extends h{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const s=Array.isArray(e),r=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),n=(await this.model(r)).logits,o=this.model.config.id2label,i=[];for(let e=0;e<n.dims[0];++e){const s=r.input_ids[e],a=n[e],c=[];for(let e=0;e<a.dims[0];++e){const r=a[e],n=(0,l.max)(r.data)[1],i=o?o[n]:`LABEL_${n}`;if(t.includes(i))continue;const d=this.tokenizer.decode([s[e].item()],{skip_special_tokens:!0});if(""===d)continue;const u=(0,l.softmax)(r.data);c.push({entity:i,score:u[n],index:e,word:d})}i.push(c)}return s?i:i[0]}}class w extends h{constructor(e){super(e)}async _call(e,t,{top_k:s=1}={}){const r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),{start_logits:n,end_logits:o}=await this.model(r),i=r.input_ids.tolist(),c=r.attention_mask.tolist(),d=this.tokenizer.all_special_ids,u=[];for(let e=0;e<n.dims[0];++e){const t=i[e],r=t.findIndex((e=>e==this.tokenizer.sep_token_id)),p=(c[e].map(((e,s)=>1==e&&(0===s||s>r&&-1===d.findIndex((e=>e==t[s]))))),n[e].tolist()),_=o[e].tolist();for(let s=1;s<p.length;++s)(0==c[e]||s<=r||-1!==d.findIndex((e=>e==t[s])))&&(p[s]=-1/0,_[s]=-1/0);const m=(0,l.softmax)(p).map(((e,t)=>[e,t])),h=(0,l.softmax)(_).map(((e,t)=>[e,t]));m[0][0]=0,h[0][0]=0;const f=(0,a.product)(m,h).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<Math.min(f.length,s);++e){const[s,r,n]=f[e],o=t.slice(s,r+1),i=this.tokenizer.decode(o,{skip_special_tokens:!0});u.push({answer:i,score:n})}}return 1===s?u[0]:u}}class M extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:r}=await this.model(s),n=[],o=s.input_ids.tolist();for(let e=0;e<o.length;++e){const s=o[e],i=s.findIndex((e=>e==this.tokenizer.mask_token_id));if(-1===i)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const a=r[e][i],c=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(a.data),a.dims),t),u=c[0].tolist(),p=c[1].tolist();n.push(p.map(((e,t)=>{const r=s.slice();return r[i]=e,{score:u[t],token:Number(e),token_str:this.tokenizer.model.vocab[e],sequence:this.tokenizer.decode(r,{skip_special_tokens:!0})}})))}return Array.isArray(e)?n:n[0]}}class b extends h{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map((e=>this.model.config.prefix+e)));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map((e=>s[this.task].prefix+e)));const r=this.tokenizer,n={padding:!0,truncation:!0};let o;o=this instanceof y&&"_build_translation_inputs"in r?r._build_translation_inputs(e,n,t):r(e,n);const i=await this.model.generate({...o,...t});return r.batch_decode(i,{skip_special_tokens:!0}).map((e=>({[this._key]:e})))}}class x extends b{_key="summary_text";constructor(e){super(e)}}class y extends b{_key="translation_text";constructor(e){super(e)}}function k(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class T extends h{constructor(e){super(e)}async _call(e,t={}){let s,r=!1,n=!1;if("string"==typeof e)s=e=[e];else if(Array.isArray(e)&&e.every((e=>"string"==typeof e)))r=!0,s=e;else{if(k(e))e=[e];else{if(!Array.isArray(e)||!e.every(k))throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");r=!0}n=!0,s=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0})))}const o=t.add_special_tokens??!1,i=!n&&(t.return_full_text??!0);this.tokenizer.padding_side="left";const a=this.tokenizer(s,{add_special_tokens:o,padding:!0,truncation:!0}),l=await this.model.generate({...a,...t}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0});let d;!i&&a.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(a.input_ids,{skip_special_tokens:!0}).map((e=>e.length)));const u=Array.from({length:e.length},(e=>[]));for(let t=0;t<c.length;++t){const s=Math.floor(t/l.dims[0]*e.length);d&&(c[t]=c[t].slice(d[s])),u[s].push({generated_text:n?[...e[s],{role:"assistant",content:c[t]}]:c[t]})}return r||1!==u.length?u:u[0]}}class v extends h{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:s="This example is {}.",multi_label:r=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const o=t.map((e=>s.replace("{}",e))),i=r||1===t.length,a=[];for(const s of e){const e=[];for(const t of o){const r=this.tokenizer(s,{text_pair:t,padding:!0,truncation:!0}),n=await this.model(r);i?e.push([n.logits.data[this.contradiction_id],n.logits.data[this.entailment_id]]):e.push(n.logits.data[this.entailment_id])}const r=(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:s,labels:r.map((e=>t[e[1]])),scores:r.map((e=>e[0]))})}return n?a:a[0]}}class P extends h{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:s=!1,quantize:r=!1,precision:n="binary"}={}){const o=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(o);let a=i.last_hidden_state??i.logits??i.token_embeddings;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 s&&(a=a.normalize(2,-1)),r&&(a=(0,d.quantize_embeddings)(a,n)),a}}class F extends h{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const s=await p(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r});let o;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");o=n.pooler_output}else o=n.last_hidden_state??n.logits??n.image_embeds;return o}}class C extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.processor.feature_extractor.config.sampling_rate,r=await _(e,s),n=this.model.config.id2label,o=[];for(const e of r){const s=await this.processor(e),r=(await this.model(s)).logits[0],i=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(r.data),r.dims),t),a=i[0].tolist(),c=i[1].tolist().map(((e,t)=>({label:n?n[e]:`LABEL_${e}`,score:a[t]})));o.push(c)}return Array.isArray(e)?o:o[0]}}class A extends h{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const n=t.map((e=>s.replace("{}",e))),o=this.tokenizer(n,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,a=await _(e,i),c=[];for(const e of a){const s=await this.processor(e),r=await this.model({...o,...s}),n=(0,l.softmax)(r.logits_per_audio.data);c.push([...n].map(((e,s)=>({score:e,label:t[s]}))))}return r?c[0]:c}}class S extends h{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(e);s&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,n=await _(e,r),o=[];for(const e of n){const t=await this.processor(e),s=(await this.model(t)).logits[0],r=[];for(const e of s)r.push((0,l.max)(e.data)[1]);const n=this.tokenizer.decode(r);o.push({text:n})}return s?o[0]:o}async _call_whisper(e,t){const s=t.return_timestamps??!1,r=t.chunk_length_s??0,n=t.force_full_sequences??!1;let o=t.stride_length_s??null;const i={...t};"word"===s&&(i.return_token_timestamps=!0,i.return_timestamps=!1);const a=!Array.isArray(e);a&&(e=[e]);const c=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,d=this.processor.feature_extractor.config.hop_length,u=this.processor.feature_extractor.config.sampling_rate,p=await _(e,u),m=[];for(const e of p){let t=[];if(r>0){if(null===o)o=r/6;else if(r<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const s=u*r,n=u*o,i=s-2*n;let a=0;for(;;){const r=a+s,o=e.subarray(a,r),l=await this.processor(o),c=0===a,d=r>=e.length;if(t.push({stride:[o.length,c?0:n,d?0:n],input_features:l.input_features,is_last:d}),d)break;a+=i}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of t){i.num_frames=Math.floor(e.stride[0]/d);const t=await this.model.generate({inputs:e.input_features,...i});"word"===s?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=t[0].tolist(),e.stride=e.stride.map((e=>e/u))}const[a,p]=this.tokenizer._decode_asr(t,{time_precision:c,return_timestamps:s,force_full_sequences:n});m.push({text:a,...p})}return a?m[0]:m}}class E extends h{constructor(e){super(e)}async _call(e,t={}){const s=Array.isArray(e),r=await p(e),{pixel_values:n}=await this.processor(r),o=[];for(const e of n){e.dims=[1,...e.dims];const s=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(s,{skip_special_tokens:!0}).map((e=>({generated_text:e.trim()})));o.push(r)}return s?o:o[0]}}class L extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=await p(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r}),o=this.model.config.id2label,i=[];for(const e of n.logits){const s=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),t),r=s[0].tolist(),n=s[1].tolist().map(((e,t)=>({label:o?o[e]:`LABEL_${e}`,score:r[t]})));i.push(n)}return Array.isArray(e)?i:i[0]}}class I extends h{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:s=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:n=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 p(e),l=a.map((e=>[e.height,e.width])),{pixel_values:c,pixel_mask:d}=await this.processor(a),_=await this.model({pixel_values:c,pixel_mask:d});let m=null;if(null!==i)m=this.subtasks_mapping[i];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.image_processor){m=this.processor.image_processor[t].bind(this.processor.image_processor),i=e;break}const h=this.model.config.id2label,f=[];if("panoptic"===i||"instance"===i){const e=m(_,t,s,r,n,o??l)[0],i=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(i.data.length);for(let s=0;s<i.data.length;++s)i.data[s]===t.id&&(e[s]=255);const s=new u.RawImage(e,i.dims[1],i.dims[0],1);f.push({score:t.score,label:h[t.label_id],mask:s})}}else{if("semantic"!==i)throw Error(`Subtask ${i} not supported.`);{const{segmentation:e,labels:t}=m(_,o??l)[0];for(const s of t){const t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r)e.data[r]===s&&(t[r]=255);const r=new u.RawImage(t,e.dims[1],e.dims[0],1);f.push({score:null,label:h[s],mask:r})}}}return f}}class z extends h{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a photo of {}"}={}){const r=Array.isArray(e),n=await p(e),o=t.map((e=>s.replace("{}",e))),i=this.tokenizer(o,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:a}=await this.processor(n),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 s=[...d(e)].map(((e,s)=>({score:e,label:t[s]})));s.sort(((e,t)=>t.score-e.score)),u.push(s)}return r?u:u[0]}}class j extends h{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:s=!1}={}){const r=Array.isArray(e);if(r&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await p(e),o=s?null:n.map((e=>[e.height,e.width])),{pixel_values:i,pixel_mask:a}=await this.processor(n),l=await this.model({pixel_values:i,pixel_mask:a}),c=this.processor.image_processor.post_process_object_detection(l,t,o),d=this.model.config.id2label,u=c.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:d[e.classes[r]],box:m(t,!s)})))));return r?u:u[0]}}class N extends h{constructor(e){super(e)}async _call(e,t,{threshold:s=.1,top_k:r=null,percentage:n=!1}={}){const o=Array.isArray(e),i=await p(e),a=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(i),c=[];for(let e=0;e<i.length;++e){const o=i[e],d=n?null:[[o.height,o.width]],u=l.pixel_values[e].unsqueeze_(0),p=await this.model({...a,pixel_values:u}),_=this.processor.image_processor.post_process_object_detection(p,s,d,!0)[0];let h=_.boxes.map(((e,s)=>({score:_.scores[s],label:t[_.classes[s]],box:m(e,!n)}))).sort(((e,t)=>t.score-e.score));null!==r&&(h=h.slice(0,r)),c.push(h)}return o?c:c[0]}}class O extends h{constructor(e){super(e)}async _call(e,t,s={}){const r=(await p(e))[0],{pixel_values:n}=await this.processor(r),o=`<s_docvqa><s_question>${t}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,a=await this.model.generate({inputs:n,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),l=this.tokenizer.batch_decode(a)[0].match(/<s_answer>(.*?)<\/s_answer>/);let c=null;return l&&l.length>=2&&(c=l[1].trim()),[{answer:c}]}}class B extends h{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(t),r=this.model.config.sampling_rate;return{audio:s.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.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:s}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model.generate_speech(s,t,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:o}}}class V extends h{constructor(e){super(e)}async _call(e){const t=await p(e),s=await this.processor(t),r=await this.model(s),n=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(u.RawImage.fromTensor(t))}return n.length>1?n:n[0]}}class D extends h{constructor(e){super(e)}async _call(e){const t=await p(e),s=await this.processor(t),{predicted_depth:r}=await this.model(s),n=[];for(let e=0;e<t.length;++e){const s=(0,d.interpolate)(r[e],t[e].size.reverse(),"bilinear",!1),o=s.mul_(255/(0,l.max)(s.data)[0]).to("uint8");n.push({predicted_depth:r[e],depth:u.RawImage.fromTensor(o)})}return n.length>1?n:n[0]}}const R=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:f,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:g,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:w,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:M,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:x,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:y,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:b,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:T,model:n.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:v,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:C,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:A,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:S,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:B,model:[n.AutoModelForTextToWaveform,n.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:E,model:n.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:L,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:I,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:z,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:j,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:N,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:O,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:V,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:D,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:P,model:n.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:F,model:[n.AutoModelForImageFeatureExtraction,n.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),G=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $(e,t=null,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",device:l=null,dtype:c=null,model_file_name:d=null,session_options:u={}}={}){e=G[e]??e;const p=R[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(R)}]`);t||(t=p.default.model,console.log(`No model specified. Using default model: "${t}".`));const _={progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i,device:l,dtype:c,model_file_name:d,session_options:u},m=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),h=await async function(e,t,s){const r=Object.create(null),n=[];for(const[o,i]of e.entries()){if(!i)continue;let e;e=Array.isArray(i)?new Promise((async(e,r)=>{let n;for(const o of i){if(null===o)return void e(null);try{return void e(await o.from_pretrained(t,s))}catch(e){if(e.message?.includes("Unsupported model type"))n=e;else{if(!e.message?.includes("Could not locate file"))return void r(e);n=e}}}r(n)})):i.from_pretrained(t,s),r[o]=e,n.push(e)}await Promise.all(n);for(const[e,t]of Object.entries(r))r[e]=await t;return r}(m,t,_);h.task=e,(0,a.dispatchCallback)(s,{status:"ready",task:e,model:t});return new(0,p.pipeline)(h)}},"./src/tokenizers.js":
|
|
320
|
-
/*!***************************!*\
|
|
321
|
-
!*** ./src/tokenizers.js ***!
|
|
322
|
-
\***************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{AlbertTokenizer:()=>ye,AutoTokenizer:()=>mt,BartTokenizer:()=>Ne,BertTokenizer:()=>xe,BlenderbotSmallTokenizer:()=>lt,BlenderbotTokenizer:()=>at,BloomTokenizer:()=>De,CLIPTokenizer:()=>rt,CamembertTokenizer:()=>Ee,CodeGenTokenizer:()=>st,CodeLlamaTokenizer:()=>$e,CohereTokenizer:()=>pt,ConvBertTokenizer:()=>Ce,DebertaTokenizer:()=>ve,DebertaV2Tokenizer:()=>Pe,DistilBertTokenizer:()=>Se,ElectraTokenizer:()=>Ie,EsmTokenizer:()=>Qe,FalconTokenizer:()=>We,GPT2Tokenizer:()=>je,GPTNeoXTokenizer:()=>Xe,GemmaTokenizer:()=>Je,Grok1Tokenizer:()=>Ye,HerbertTokenizer:()=>Fe,LlamaTokenizer:()=>Ge,M2M100Tokenizer:()=>et,MBart50Tokenizer:()=>Be,MBartTokenizer:()=>Oe,MPNetTokenizer:()=>Ue,MarianTokenizer:()=>ot,MgpstrTokenizer:()=>_t,MobileBertTokenizer:()=>ke,NllbTokenizer:()=>Ze,NougatTokenizer:()=>dt,PreTrainedTokenizer:()=>be,Qwen2Tokenizer:()=>He,RoFormerTokenizer:()=>Ae,RobertaTokenizer:()=>Ve,SiglipTokenizer:()=>nt,SpeechT5Tokenizer:()=>ct,SqueezeBertTokenizer:()=>Te,T5Tokenizer:()=>ze,TokenizerModel:()=>k,VitsTokenizer:()=>ut,Wav2Vec2CTCTokenizer:()=>it,WhisperTokenizer:()=>tt,XLMRobertaTokenizer:()=>qe,XLMTokenizer:()=>Le,is_chinese_char:()=>g});var r=s(/*! ./utils/generic.js */"./src/utils/generic.js"),n=s(/*! ./utils/core.js */"./src/utils/core.js"),o=s(/*! ./utils/hub.js */"./src/utils/hub.js"),i=s(/*! ./utils/maths.js */"./src/utils/maths.js"),a=s(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=s(/*! ./utils/data-structures.js */"./src/utils/data-structures.js"),c=s(/*! @huggingface/jinja */"./node_modules/@huggingface/jinja/dist/index.js"),d=s(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");s(/*! ./utils/constants.js */"./src/utils/constants.js");async function u(e,t){const s=await Promise.all([(0,o.getModelJSON)(e,"tokenizer.json",!0,t),(0,o.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(s[1].legacy=t.legacy),s}function p(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,s]of x)t=t.replaceAll(e,s);return new RegExp(t,"gu")}if(void 0!==e.String){const s=(0,n.escapeRegExp)(e.String);return new RegExp(t?s:`(${s})`,"gu")}return console.warn("Unknown pattern type:",e),null}function _(e){return new Map(Object.entries(e))}function m(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 h(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 f(e){return e.replace(/\p{M}/gu,"")}function g(e){return e>=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}const w="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",M=new RegExp(`^[${w}]+$`,"gu"),b=".,!?…。,、।۔،",x=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],[` ?[^(\\s|[${b}])]+`,` ?[^\\s${b}]+`]]);class y{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 k extends r.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 T(e);case"Unigram":return new v(e,...t);case"BPE":return new C(e);default:if(e.vocab)return Array.isArray(e.vocab)?new v(e,...t):new A(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return e=this.encode(e),this.fuse_unk&&(e=function(e,t,s){const r=[];let n=0;for(;n<e.length;)if(r.push(e[n]),(t.get(e[n])??s)===s)for(;++n<e.length&&(t.get(e[n])??s)===s;)t.get(r.at(-1))!==s&&(r[r.length-1]+=e[n]);else++n;return r}(e,this.tokens_to_ids,this.unk_token_id)),e}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){return e.map((e=>this.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 T extends k{constructor(e){super(e),this.tokens_to_ids=_(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.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 s of e){const e=[...s];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,n=0;const o=[];for(;n<e.length;){let t=e.length,s=null;for(;n<t;){let r=e.slice(n,t).join("");if(n>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){s=r;break}--t}if(null===s){r=!0;break}o.push(s),n=t}r?t.push(this.unk_token):t.push(...o)}return t}}class v extends k{constructor(e,t){super(e);const s=e.vocab.length;this.vocab=new Array(s),this.scores=new Array(s);for(let t=0;t<s;++t){const s=e.vocab[t];this.vocab[t]=s[0],this.scores[t]=s[1]}this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map(((e,t)=>[e,t]))),this.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.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.chars;let s=0;for(;s<t.length;){let r=!1;const o=[],i=t.slice(s).join(""),a=this.trie.commonPrefixSearch(i);for(const t of a){o.push(t);const i=this.tokens_to_ids.get(t),a=this.scores[i],l=(0,n.len)(t);e.insert(s,l,a,i),r||1!==l||(r=!0)}r||e.insert(s,1,this.unk_score,this.unk_token_id),s+=1}}tokenize(e){const t=new l.TokenLattice(e,this.bos_token_id,this.eos_token_id);return this.populateNodes(t),t.tokens()}encode(e){const t=[];for(const s of e){const e=this.tokenize(s);t.push(...e)}return t}}const P=(()=>{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 s=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+s),s+=1);const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})(),F=(0,n.reverseDictionary)(P);class C extends k{constructor(e){super(e),this.tokens_to_ids=_(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map((e=>e.split(" ",2))),this.bpe_ranks=new Map(this.merges.map(((e,t)=>[JSON.stringify(e),t]))),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.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const s=Array.from(e);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let r=[];if(s.length>1){const e=new l.PriorityQueue(((e,t)=>e.score<t.score));let t={token:s[0],bias:0,prev:null,next:null},n=t;for(let t=1;t<s.length;++t){const r={bias:t/s.length,token:s[t],prev:n,next:null};n.next=r,this._add_node(e,n),n=r}for(;!e.isEmpty();){const s=e.pop();if(s.deleted||!s.next||s.next.deleted)continue;if(s.deleted=!0,s.next.deleted=!0,s.prev){const e={...s.prev};s.prev.deleted=!0,s.prev=e,e.prev?e.prev.next=e:t=e}const r={token:s.token+s.next.token,bias:s.bias,prev:s.prev,next:s.next.next};r.prev?(r.prev.next=r,this._add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this._add_node(e,r))}for(let e=t;null!==e;e=e.next)r.push(e.token)}else r=s;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return this.cache.set(e,r),r}_add_node(e,t){const s=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));void 0!==s&&(t.score=s+t.bias,e.push(t))}encode(e){const t=[];for(const s of e){if(this.ignore_merges&&this.tokens_to_ids.has(s)){t.push(s);continue}const e=this.bpe(s);for(const s of e)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const e=Array.from(this.text_encoder.encode(s)).map((e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`));e.every((e=>this.tokens_to_ids.has(e)))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}}class A extends k{constructor(e,t){super(e),this.tokens_to_ids=_(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 S extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new D(e);case"Precompiled":return new pe(e);case"Sequence":return new V(e);case"Replace":return new E(e);case"NFC":return new L(e);case"NFKC":return new I(e);case"NFKD":return new z(e);case"Strip":return new j(e);case"StripAccents":return new N(e);case"Lowercase":return new O(e);case"Prepend":return new B(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 E extends S{normalize(e){const t=p(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class L extends S{normalize(e){return e=e.normalize("NFC")}}class I extends S{normalize(e){return e=e.normalize("NFKC")}}class z extends S{normalize(e){return e=e.normalize("NFKD")}}class j extends S{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 N extends S{normalize(e){return e=f(e)}}class O extends S{normalize(e){return e=e.toLowerCase()}}class B extends S{normalize(e){return e=this.config.prepend+e}}class V extends S{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>S.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class D extends S{_tokenize_chinese_chars(e){const t=[];for(let s=0;s<e.length;++s){const r=e[s];g(r.charCodeAt(0))?(t.push(" "),t.push(r),t.push(" ")):t.push(r)}return t.join("")}stripAccents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}_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 s of e){const e=s.charCodeAt(0);0===e||65533===e||this._is_control(s)||(/^\s$/.test(s)?t.push(" "):t.push(s))}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 R extends r.Callable{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new G(e);case"Sequence":return new _e(e);case"Whitespace":return new me(e);case"WhitespaceSplit":return new he(e);case"Metaspace":return new de(e);case"ByteLevel":return new $(e);case"Split":return new q(e);case"Punctuation":return new U(e);case"Digits":return new W(e);case"Replace":return new fe(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 G extends R{constructor(e){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class $ extends R{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=P,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 q extends R{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:"removed"===this.config.behavior?.toLowerCase()?e.split(this.pattern).filter((e=>e)):function(e,t){const s=[];let r=0;for(const n of e.matchAll(t)){const t=n[0];r<n.index&&s.push(e.slice(r,n.index)),t.length>0&&s.push(t),r=n.index+t.length}return r<e.length&&s.push(e.slice(r)),s}(e,this.pattern)}}class U extends R{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class W extends R{constructor(e){super(),this.config=e;const t="[^\\d]+|\\d"+(this.config.individual_digits?"":"+");this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class X extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new J(e);case"ByteLevel":return new Y(e);case"RobertaProcessing":return new H(e);case"BertProcessing":return new Q(e);case"Sequence":return new K(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class Q extends X{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null,{add_special_tokens:s=!0}={}){s&&(e=(0,n.mergeArrays)([this.cls],e,[this.sep]));let r=new Array(e.length).fill(0);if(null!==t){const o=s&&this instanceof H?[this.sep]:[],i=s?[this.sep]:[];e=(0,n.mergeArrays)(e,o,t,i),r=(0,n.mergeArrays)(r,new Array(t.length+o.length+i.length).fill(1))}return{tokens:e,token_type_ids:r}}}class H extends Q{}class J extends X{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null,{add_special_tokens:s=!0}={}){const r=null===t?this.single:this.pair;let o=[],i=[];for(const a of r)"SpecialToken"in a?s&&(o.push(a.SpecialToken.id),i.push(a.SpecialToken.type_id)):"Sequence"in a&&("A"===a.Sequence.id?(o=(0,n.mergeArrays)(o,e),i=(0,n.mergeArrays)(i,new Array(e.length).fill(a.Sequence.type_id))):"B"===a.Sequence.id&&(o=(0,n.mergeArrays)(o,t),i=(0,n.mergeArrays)(i,new Array(t.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:i}}}class Y extends X{post_process(e,t=null){return t&&(e=(0,n.mergeArrays)(e,t)),{tokens:e}}}class K extends X{constructor(e){super(e),this.processors=e.processors.map((e=>X.fromConfig(e)))}post_process(e,t=null,s={}){let r;for(const n of this.processors)if(n instanceof Y){if(e=n.post_process(e).tokens,t){t=n.post_process(t).tokens}}else{const o=n.post_process(e,t,s);e=o.tokens,r=o.token_type_ids}return{tokens:e,token_type_ids:r}}}class Z extends r.Callable{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(null===e)return null;switch(e.type){case"WordPiece":return new ne(e);case"Metaspace":return new ue(e);case"ByteLevel":return new oe(e);case"Replace":return new ee(e);case"ByteFallback":return new te(e);case"Fuse":return new se(e);case"Strip":return new re(e);case"Sequence":return new ae(e);case"CTC":return new ie(e);case"BPEDecoder":return new le(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends Z{decode_chain(e){const t=p(this.config.pattern);return null===t?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class te extends Z{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let s=[];for(const r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)s.push(e);else{if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}t.push(r)}}if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}return t}}class se extends Z{decode_chain(e){return[e.join("")]}}class re extends Z{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 s=0;s<this.start&&e[s]===this.content;++s)t=s+1;let s=e.length;for(let t=0;t<this.stop;++t){const r=e.length-t-1;if(e[r]!==this.content)break;s=r}return e.slice(t,s)}))}}class ne extends Z{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map(((e,t)=>(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=h(e)),e)))}}class oe extends Z{constructor(e){super(e),this.byte_decoder=F,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(""),s=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(s)}decode_chain(e){const t=[];let s=[];for(const r of e)void 0!==this.added_tokens.find((e=>e.content===r))?(s.length>0&&(t.push(this.convert_tokens_to_string(s)),s=[]),t.push(r)):s.push(r);return s.length>0&&t.push(this.convert_tokens_to_string(s)),t}}class ie extends Z{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 s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let s=t.filter((e=>e!==this.pad_token)).join("");return this.cleanup&&(s=h(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class ae extends Z{constructor(e){super(e),this.decoders=e.decoders.map((e=>Z.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class le extends Z{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,s)=>t.replaceAll(this.suffix,s===e.length-1?"":" ")))}}class ce extends Z{decode_chain(e){let t="";for(let s=1;s<e.length;s+=2)t+=e[s];return[t]}}class de extends R{constructor(e){super(),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement,this.strRep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,{section_index:t}={}){let s=e.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!s.startsWith(this.replacement)&&("always"===this.prepend_scheme||"first"===this.prepend_scheme&&0===t)&&(s=this.strRep+s),[s]}}class ue extends Z{constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){const t=[];for(let s=0;s<e.length;++s){let r=e[s].replaceAll(this.replacement," ");this.addPrefixSpace&&0==s&&r.startsWith(" ")&&(r=r.substring(1)),t.push(r)}return t}}class pe extends S{constructor(e){super(e),this.charsmap=e.precompiled_charsmap}normalize(e){if((e=(e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"")).replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," ")).includes("~")){const t=e.split("~");e=t.map((e=>e.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class _e extends R{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>R.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,s)=>s.pre_tokenize(e,t)),[e])}}class me extends R{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class he extends R{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class fe extends R{constructor(e){super(),this.config=e,this.pattern=p(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 ge=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function we(e,t,s,r){for(const o of Object.keys(e)){const i=t-e[o].length,a=s(o),l=new Array(i).fill(a);e[o]="right"===r?(0,n.mergeArrays)(e[o],l):(0,n.mergeArrays)(l,e[o])}}function Me(e,t){for(const s of Object.keys(e))e[s].length=t}class be extends r.Callable{return_token_type_ids=!1;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=S.fromConfig(e.normalizer),this.pre_tokenizer=R.fromConfig(e.pre_tokenizer),this.model=k.fromConfig(e.model,t),this.post_processor=X.fromConfig(e.post_processor),this.decoder=Z.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new y(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.slice().sort(((e,t)=>t.content.length-e.content.length)).map((e=>`${e.lstrip?"\\s*":""}(${(0,n.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:s}of this.chat_template){if("string"!=typeof t||"string"!=typeof s)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=s}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:s=null,cache_dir:r=null,local_files_only:n=!1,revision:o="main",legacy:i=null}={}){return new this(...await u(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:o,legacy:i}))}_call(e,{text_pair:t=null,add_special_tokens:s=!0,padding:r=!1,truncation:n=null,max_length:o=null,return_tensor:l=!0,return_token_type_ids:c=null}={}){const d=Array.isArray(e);let u;if(d){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");u=e.map(((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:s,return_token_type_ids:c})))}else u=e.map((e=>this._encode_plus(e,{add_special_tokens:s,return_token_type_ids:c})))}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).");u=[this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:c})]}if(null===o?o="max_length"===r?this.model_max_length:(0,i.max)(u.map((e=>e.input_ids.length)))[0]:n||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??1/0),r||n)for(let e=0;e<u.length;++e)u[e].input_ids.length!==o&&(u[e].input_ids.length>o?n&&Me(u[e],o):r&&we(u[e],o,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const p={};if(l){if((!r||!n)&&u.some((e=>{for(const t of Object.keys(e))if(e[t].length!==u[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=[u.length,u[0].input_ids.length];for(const t of Object.keys(u[0]))p[t]=new a.Tensor("int64",BigInt64Array.from(u.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(u[0]))p[e]=u.map((t=>t[e]));if(!d)for(const e of Object.keys(p))p[e]=p[e][0]}return p}_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 f(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const s=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(s)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){const{tokens:n,token_type_ids:o}=this._tokenize_helper(e,{pair:t,add_special_tokens:s}),i=this.model.convert_tokens_to_ids(n),a={input_ids:i,attention_mask:new Array(i.length).fill(1)};return(r??this.return_token_type_ids)&&o&&(a.token_type_ids=o),a}_tokenize_helper(e,{pair:t=null,add_special_tokens:s=!1}={}){const r=this._encode_text(e),o=this._encode_text(t);return this.post_processor?this.post_processor(r,o,{add_special_tokens:s}):{tokens:(0,n.mergeArrays)(r??[],o??[])}}tokenize(e,{pair:t=null,add_special_tokens:s=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:s}).tokens}encode(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:r}).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=m(e)),!Array.isArray(e)||0===e.length||!(0,n.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:s=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter((e=>!this.special_tokens.includes(e))));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t&&(n=n.trim())),(s??this.clean_up_tokenization_spaces)&&(n=h(n)),n}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){const s=this.chat_template;if(null!==e&&Object.hasOwn(s,e))e=s[e];else if(null===e)if(null!==t&&"tool_use"in s)e=s.tool_use;else{if(!("default"in s))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(s).sort()}.`);e=s.default}}else if(null===e){if(!this.chat_template)throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");e=this.chat_template}return e}apply_chat_template(e,{tools:t=null,documents:s=null,chat_template:r=null,add_generation_prompt:n=!1,tokenize:o=!0,padding:i=!1,truncation:a=!1,max_length:l=null,return_tensor:d=!0,return_dict:u=!1,tokenizer_kwargs:p={},..._}={}){if("string"!=typeof(r=this.get_chat_template({chat_template:r,tools:t})))throw Error("chat_template must be a string, but got "+typeof r);let m=this._compiled_template_cache.get(r);void 0===m&&(m=new c.Template(r),this._compiled_template_cache.set(r,m));const h=Object.create(null);for(const e of ge){const t=this.getToken(e);t&&(h[e]=t)}const f=m.render({messages:e,add_generation_prompt:n,tools:t,documents:s,...h,..._});if(o){const e=this._call(f,{add_special_tokens:!1,padding:i,truncation:a,max_length:l,return_tensor:d,...p});return u?e:e.input_ids}return f}}class xe extends be{return_token_type_ids=!0}class ye extends be{return_token_type_ids=!0}class ke extends be{return_token_type_ids=!0}class Te extends be{return_token_type_ids=!0}class ve extends be{return_token_type_ids=!0}class Pe extends be{return_token_type_ids=!0}class Fe extends be{return_token_type_ids=!0}class Ce extends be{return_token_type_ids=!0}class Ae extends be{return_token_type_ids=!0}class Se extends be{}class Ee extends be{}class Le extends be{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 Ie extends be{return_token_type_ids=!0}class ze extends be{}class je extends be{}class Ne extends be{}class Oe extends be{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,s){return Ke(this,e,t,s)}}class Be extends Oe{}class Ve extends be{}class De extends be{}const Re="▁";class Ge extends be{padding_side="left";constructor(e,t){super(e,t),this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new de({replacement:Re,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(Re+e.replaceAll(Re," "));return t.length>1&&t[0]===Re&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}}class $e extends be{}class qe extends be{}class Ue extends be{}class We extends be{}class Xe extends be{}class Qe extends be{}class He extends be{}class Je extends be{}class Ye extends be{}function Ke(e,t,s,r){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 n=r.src_lang,o=r.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!==n){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" 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(n);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(o)])[0],e._call(t,s)}class Ze extends be{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,s){return Ke(this,e,t,s)}}class et extends be{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,s){return Ke(this,e,t,s)}}class tt extends be{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:s=!1,time_precision:r=null,force_full_sequences:n=!0}={}){if(null===r)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 u=l(),p=0;const _=this.timestamp_begin;let m=[],h=[],f=!1,g=null;const w=new Set(this.all_special_ids);for(const s of e){const e=s.tokens,n=a?s.token_timestamps:null;let b=null,x=_;if("stride"in s){const[t,n,o]=s.stride;if(p-=n,g=t-o,n&&(x=n/r+_),o)for(let t=e.length-1;t>=0;--t){const s=Number(e[t]);if(s>=_){if(null!==b&&(s-_)*r<g)break;b=s}}}let y=[],k=[];for(let s=0;s<e.length;++s){const g=Number(e[s]);if(w.has(g)){const e=this.decode([g]),s=d.WHISPER_LANGUAGE_MAPPING.get(e.slice(2,-2));if(void 0!==s){if(null!==o&&s!==o&&!t){m.push(y);const e=this.findLongestCommonSequence(m)[0],t=this.decode(e);u.text=t,c.push(u),m=[],y=[],u=l()}o=u.language=s}}else if(g>=_){const e=(g-_)*r+p,t=(0,i.round)(e,2);if(null!==b&&g>=b)f=!0;else if(f||m.length>0&&g<x)f=!1;else if(null===u.timestamp[0])u.timestamp[0]=t;else if(t===u.timestamp[0]);else{u.timestamp[1]=t,m.push(y),a&&h.push(k);const[e,s]=this.findLongestCommonSequence(m,h),r=this.decode(e);u.text=r,a&&(u.words=this.collateWordTimestamps(e,s,o)),c.push(u),m=[],y=[],h=[],k=[],u=l()}}else if(y.push(g),a){let e,t=(0,i.round)(n[s]+p,2);if(s+1<n.length){e=(0,i.round)(n[s+1]+p,2);const o=this.decode([g]);M.test(o)&&(e=(0,i.round)(Math.min(t+r,e),2))}else e=null;k.push([t,e])}}if("stride"in s){const[e,t,r]=s.stride;p+=e-r}y.length>0?(m.push(y),a&&h.push(k)):m.every((e=>0===e.length))&&(u=l(),m=[],y=[],h=[],k=[])}if(m.length>0){if(n&&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,s]=this.findLongestCommonSequence(m,h),r=this.decode(e);u.text=r,a&&(u.words=this.collateWordTimestamps(e,s,o)),c.push(u)}let b=Object.create(null);const x=c.map((e=>e.text)).join("");if(t||s){for(let e=0;e<c.length;++e){const r=c[e];t||delete r.timestamp,s||delete r.language}if(a){const e=[];for(const t of c)for(const s of t.words)e.push(s);b={chunks:e}}else b={chunks:c}}return[x,b]}findLongestCommonSequence(e,t=null){let s=e[0],r=s.length,n=[];const o=Array.isArray(t)&&t.length>0;let i=o?[]:null,a=o?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,u=[r,r,0,0];const p=c.length;for(let e=1;e<r+p;++e){const n=Math.max(0,r-e),i=Math.min(r,r+p-e),_=s.slice(n,i),m=Math.max(0,e-r),h=Math.min(p,e),f=c.slice(m,h);if(_.length!==f.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let g;g=o?_.filter(((e,s)=>e===f[s]&&a[n+s]<=t[l][m+s])).length:_.filter(((e,t)=>e===f[t])).length;const w=g/e+e/1e4;g>1&&w>d&&(d=w,u=[n,i,m,h])}const[_,m,h,f]=u,g=Math.floor((m+_)/2),w=Math.floor((f+h)/2);n.push(...s.slice(0,g)),s=c.slice(w),r=s.length,o&&(i.push(...a.slice(0,g)),a=t[l].slice(w))}return n.push(...s),o?(i.push(...a),[n,i]):[n,[]]}collateWordTimestamps(e,t,s){const[r,n,o]=this.combineTokensIntoWords(e,s),i=[];for(let e=0;e<r.length;++e){const s=o[e];i.push({text:r[e],timestamp:[t[s.at(0)][0],t[s.at(-1)][1]]})}return i}combineTokensIntoWords(e,t,s="\"'“¡¿([{-",r="\"'.。,,!!??::”)]}、"){let n,o,i;return["chinese","japanese","thai","lao","myanmar"].includes(t=t??"english")?[n,o,i]=this.splitTokensOnUnicode(e):[n,o,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,o,i,s,r)}decode(e,t){let s;return t?.decode_with_timestamps?(e instanceof a.Tensor&&(e=m(e)),s=this.decodeWithTimestamps(e,t)):s=super.decode(e,t),s}decodeWithTimestamps(e,t){const s=t?.time_precision??.02,r=Array.from(this.all_special_ids).at(-1)+1;let n=[[]];for(let t of e)if(t=Number(t),t>=r){const e=((t-r)*s).toFixed(2);n.push(`<|${e}|>`),n.push([])}else n[n.length-1].push(t);return n=n.map((e=>"string"==typeof e?e:super.decode(e,t))),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),s=[],r=[],n=[];let o=[],i=[],a=0;for(let l=0;l<e.length;++l){const c=e[l];o.push(c),i.push(l);const d=this.decode(o,{decode_with_timestamps:!0});d.includes("�")&&"�"!==t[a+d.indexOf("�")]||(s.push(d),r.push(o),n.push(i),o=[],i=[],a+=d.length)}return[s,r,n]}splitTokensOnSpaces(e){const[t,s,r]=this.splitTokensOnUnicode(e),n=[],o=[],i=[],a=new RegExp(`^[${w}]$`,"gu");for(let e=0;e<t.length;++e){const l=t[e],c=s[e],d=r[e],u=c[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),p=l.startsWith(" "),_=l.trim(),m=a.test(_);if(u||p||m||0===n.length)n.push(l),o.push(c),i.push(d);else{const e=n.length-1;n[e]+=l,o[e].push(...c),i[e].push(...d)}}return[n,o,i]}mergePunctuations(e,t,s,r,o){const i=structuredClone(e),a=structuredClone(t),l=structuredClone(s);let c=i.length-2,d=i.length-1;for(;c>=0;)i[c].startsWith(" ")&&r.includes(i[c].trim())?(i[d]=i[c]+i[d],a[d]=(0,n.mergeArrays)(a[c],a[d]),l[d]=(0,n.mergeArrays)(l[c],l[d]),i[c]="",a[c]=[],l[c]=[]):d=c,--c;for(c=0,d=1;d<i.length;)!i[c].endsWith(" ")&&o.includes(i[d])?(i[c]+=i[d],a[c]=(0,n.mergeArrays)(a[c],a[d]),l[c]=(0,n.mergeArrays)(l[c],l[d]),i[d]="",a[d]=[],l[d]=[]):c=d,++d;return[i.filter((e=>e)),a.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}}class st extends be{}class rt extends be{}class nt extends be{}class ot extends be{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,...s]=e.trim().split(this.languageRegex);if(0===s.length)return super._encode_text(t);if(2===s.length){const[e,t]=s;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,n.mergeArrays)([e],super._encode_text(t))}}}class it extends be{}class at extends be{}class lt extends be{}class ct extends be{}class dt extends be{}class ut extends be{constructor(e,t){super(e,t),this.decoder=new ce({})}}class pt extends be{}class _t extends be{}class mt{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:ze,DistilBertTokenizer:Se,CamembertTokenizer:Ee,DebertaTokenizer:ve,DebertaV2Tokenizer:Pe,BertTokenizer:xe,HerbertTokenizer:Fe,ConvBertTokenizer:Ce,RoFormerTokenizer:Ae,XLMTokenizer:Le,ElectraTokenizer:Ie,MobileBertTokenizer:ke,SqueezeBertTokenizer:Te,AlbertTokenizer:ye,GPT2Tokenizer:je,BartTokenizer:Ne,MBartTokenizer:Oe,MBart50Tokenizer:Be,RobertaTokenizer:Ve,WhisperTokenizer:tt,CodeGenTokenizer:st,CLIPTokenizer:rt,SiglipTokenizer:nt,MarianTokenizer:ot,BloomTokenizer:De,NllbTokenizer:Ze,M2M100Tokenizer:et,LlamaTokenizer:Ge,CodeLlamaTokenizer:$e,XLMRobertaTokenizer:qe,MPNetTokenizer:Ue,FalconTokenizer:We,GPTNeoXTokenizer:Xe,EsmTokenizer:Qe,Wav2Vec2CTCTokenizer:it,BlenderbotTokenizer:at,BlenderbotSmallTokenizer:lt,SpeechT5Tokenizer:ct,NougatTokenizer:dt,VitsTokenizer:ut,Qwen2Tokenizer:He,GemmaTokenizer:Je,Grok1Tokenizer:Ye,CohereTokenizer:pt,MgpstrTokenizer:_t,PreTrainedTokenizer:be};static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:o="main",legacy:i=null}={}){const[a,l]=await u(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:o,legacy:i}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let d=this.TOKENIZER_CLASS_MAPPING[c];return d||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),d=be),new d(a,l)}}},"./src/utils/audio.js":
|
|
323
|
-
/*!****************************!*\
|
|
324
|
-
!*** ./src/utils/audio.js ***!
|
|
325
|
-
\****************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{hamming:()=>d,hanning:()=>c,mel_filter_bank:()=>h,read_audio:()=>a,spectrogram:()=>g,window_function:()=>w});var r=s(/*! ./hub.js */"./src/utils/hub.js"),n=s(/*! ./maths.js */"./src/utils/maths.js"),o=s(/*! ./core.js */"./src/utils/core.js"),i=s(/*! ./tensor.js */"./src/utils/tensor.js");async function a(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 s=await(await(0,r.getFile)(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const o=await n.decodeAudioData(s);let i;if(2===o.numberOfChannels){const e=Math.sqrt(2),t=o.getChannelData(0),s=o.getChannelData(1);i=new Float32Array(t.length);for(let r=0;r<o.length;++r)i[r]=e*(t[r]+s[r])/2}else i=o.getChannelData(0);return i}function l(e,t){if(e<1)return new Float64Array;if(1===e)return new Float64Array([1]);const s=1-t,r=2*Math.PI/(e-1),n=new Float64Array(e);for(let o=0;o<e;++o)n[o]=t-s*Math.cos(o*r);return n}function c(e){return l(e,.5)}function d(e){return l(e,.54)}const u={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,s=15,r=27/Math.log(6.4))=>e>=t?s+Math.log(e/t)*r:3*e/200};function p(e,t="htk"){const s=u[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}const _={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,s=15,r=Math.log(6.4)/27)=>e>=s?t*Math.exp(r*(e-s)):200*e/3};function m(e,t,s){const r=(t-e)/(s-1);return Float64Array.from({length:s},((t,s)=>e+r*s))}function h(e,t,s,r,n,o=null,i="htk",a=!1){if(null!==o&&"slaney"!==o)throw new Error('norm must be one of null or "slaney"');const l=m(p(s,i),p(r,i),t+2);let c,d=function(e,t="htk"){const s=_[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}(l,i);if(a){const t=n/(2*e);c=p(Float64Array.from({length:e},((e,s)=>s*t)),i),d=l}else c=m(0,Math.floor(n/2),e);const u=function(e,t){const s=Float64Array.from({length:t.length-1},((e,s)=>t[s+1]-t[s])),r=Array.from({length:e.length},(()=>new Array(t.length)));for(let s=0;s<e.length;++s){const n=r[s];for(let r=0;r<t.length;++r)n[r]=t[r]-e[s]}const n=t.length-2,o=Array.from({length:n},(()=>new Array(e.length)));for(let t=0;t<e.length;++t){const e=r[t];for(let r=0;r<n;++r){const n=-e[r]/s[r],i=e[r+2]/s[r+1];o[r][t]=Math.max(0,Math.min(n,i))}}return o}(c,d);if(null!==o&&"slaney"===o)for(let s=0;s<t;++s){const t=u[s],r=2/(d[s+2]-d[s]);for(let s=0;s<e;++s)t[s]*=r}return u}function f(e,t,s,r,o){if(s<=0)throw new Error("reference must be greater than zero");if(r<=0)throw new Error("min_value must be greater than zero");s=Math.max(r,s);const i=Math.log10(s);for(let s=0;s<e.length;++s)e[s]=t*Math.log10(Math.max(r,e[s])-i);if(null!==o){if(o<=0)throw new Error("db_range must be greater than zero");const t=(0,n.max)(e)[0]-o;for(let s=0;s<e.length;++s)e[s]=Math.max(e[s],t)}return e}async function g(e,t,s,r,{fft_length:a=null,power:l=1,center:c=!0,pad_mode:d="reflect",onesided:u=!0,preemphasis:p=null,mel_filters:_=null,mel_floor:m=1e-10,log_mel:h=null,reference:g=1,min_value:w=1e-10,db_range:M=null,remove_dc_offset:b=null,min_num_frames:x=null,max_num_frames:y=null,do_pad:k=!0,transpose:T=!1}={}){const v=t.length;if(null===a&&(a=s),s>a)throw Error(`frame_length (${s}) may not be larger than fft_length (${a})`);if(v!==s)throw new Error(`Length of the window (${v}) must equal frame_length (${s})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(null===l&&null!==_)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(c){if("reflect"!==d)throw new Error(`pad_mode="${d}" not implemented yet.`);const t=Math.floor((a-1)/2)+1;e=function(e,t,s){const r=new e.constructor(e.length+t+s),n=e.length-1;for(let s=0;s<e.length;++s)r[t+s]=e[s];for(let s=1;s<=t;++s)r[t-s]=e[(0,o.calculateReflectOffset)(s,n)];for(let i=1;i<=s;++i)r[n+t+i]=e[(0,o.calculateReflectOffset)(n-i,n)];return r}(e,t,t)}let P=Math.floor(1+Math.floor((e.length-s)/r));null!==x&&P<x&&(P=x);const F=u?Math.floor(a/2)+1:a;let C=P,A=P;null!==y&&(y>P?k&&(A=y):A=C=y);const S=new n.FFT(a),E=new Float64Array(a),L=new Float64Array(S.outputBufferSize),I=new Float32Array(F*A);for(let n=0;n<C;++n){const o=n*r,i=Math.min(e.length-o,s);i!==s&&E.fill(0,0,s);for(let t=0;t<i;++t)E[t]=e[o+t];if(b){let e=0;for(let t=0;t<i;++t)e+=E[t];const t=e/i;for(let e=0;e<i;++e)E[e]-=t}if(null!==p){for(let e=i-1;e>=1;--e)E[e]-=p*E[e-1];E[0]*=1-p}for(let e=0;e<t.length;++e)E[e]*=t[e];S.realTransform(L,E);for(let e=0;e<F;++e){const t=e<<1;I[e*A+n]=L[t]**2+L[t+1]**2}}if(null!==l&&2!==l){const e=2/l;for(let t=0;t<I.length;++t)I[t]**=e}const z=_.length;let j=await(0,i.matmul)(new i.Tensor("float32",_.flat(),[z,F]),new i.Tensor("float32",I,[F,A]));T&&(j=j.transpose(1,0));const N=j.data;for(let e=0;e<N.length;++e)N[e]=Math.max(m,N[e]);if(null!==l&&null!==h){const e=Math.min(N.length,C*z);switch(h){case"log":for(let t=0;t<e;++t)N[t]=Math.log(N[t]);break;case"log10":for(let t=0;t<e;++t)N[t]=Math.log10(N[t]);break;case"dB":if(1===l)!function(e,t=1,s=1e-5,r=null){f(e,20,t,s,r)}(N,g,w,M);else{if(2!==l)throw new Error(`Cannot use log_mel option '${h}' with power ${l}`);!function(e,t=1,s=1e-10,r=null){f(e,10,t,s,r)}(N,g,w,M)}break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return j}function w(e,t,{periodic:s=!0,frame_length:r=null,center:n=!0}={}){const o=s?e+1:e;let i;switch(t){case"boxcar":i=new Float64Array(o).fill(1);break;case"hann":case"hann_window":i=c(o);break;case"hamming":i=d(o);break;case"povey":i=c(o).map((e=>Math.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(s&&(i=i.subarray(0,e)),null===r)return i;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return i}},"./src/utils/constants.js":
|
|
326
|
-
/*!********************************!*\
|
|
327
|
-
!*** ./src/utils/constants.js ***!
|
|
328
|
-
\********************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>r,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const r="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.json",c="generation_config.json"},"./src/utils/core.js":
|
|
329
|
-
/*!***************************!*\
|
|
330
|
-
!*** ./src/utils/core.js ***!
|
|
331
|
-
\***************************/(e,t,s)=>{"use strict";function r(e,t){e&&e(t)}function n(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){return null==e||-1===e}function c(e){const t=[];let s=e;for(;Array.isArray(s);)t.push(s.length),s=s[0];return t}function d(e,t,s=void 0){const r=e[t];if(void 0!==r)return delete e[t],r;if(void 0===s)throw Error(`Key ${t} does not exist in object.`);return s}function u(...e){return Array.prototype.concat.apply([],e)}function p(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function _(e,t){return Math.abs((e+t)%(2*t)-t)}function m(e,t){return Object.assign({},...t.map((t=>{if(void 0!==e[t])return{[t]:e[t]}})))}function h(e){let t=0;for(const s of e)++t;return t}function f(e,t){let s=0;for(const r of e)r===t&&++s;return s}s.r(t),s.d(t,{calculateDimensions:()=>c,calculateReflectOffset:()=>_,count:()=>f,dispatchCallback:()=>r,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>h,mergeArrays:()=>u,pick:()=>m,pop:()=>d,product:()=>p,reverseDictionary:()=>n})},"./src/utils/data-structures.js":
|
|
332
|
-
/*!**************************************!*\
|
|
333
|
-
!*** ./src/utils/data-structures.js ***!
|
|
334
|
-
\**************************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{CharTrie:()=>n,PriorityQueue:()=>r,TokenLattice:()=>i});class r{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._maxSize=t}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)if(this.size<this._maxSize)this._heap.push(t),this._siftUp();else{const e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._siftUpFrom(e))}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 s=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=s}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(e){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.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}}class n{constructor(){this.root=o.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const s of e){let e=t.children.get(s);void 0===e&&(e=o.default(),t.children.set(s,e)),t=e}t.isLeaf=!0}*commonPrefixSearch(e){let t=this.root;if(void 0===t)return;let s="";for(const r of e){if(s+=r,t=t.children.get(r),void 0===t)return;t.isLeaf&&(yield s)}}}class o{constructor(e,t){this.isLeaf=e,this.children=t}static default(){return new o(!1,new Map)}}class i{constructor(e,t,s){this.chars=Array.from(e),this.len=this.chars.length,this.bosTokenId=t,this.eosTokenId=s,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},(()=>[])),this.endNodes=Array.from({length:this.len+1},(()=>[]));const r=new a(this.bosTokenId,0,0,0,0),n=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(n.clone()),this.beginNodes[this.len].push(n),this.endNodes[0].push(r)}insert(e,t,s,r){const n=this.nodes.length,o=new a(r,n,e,t,s);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 s=0,r=null;for(let n of this.endNodes[t]){const t=n.backtraceScore+e.score;(null===r||t>s)&&(r=n.clone(),s=t)}if(null===r)return[];e.prev=r,e.backtraceScore=s}++t}const s=[],r=this.beginNodes[e][0].prev;if(null===r)return[];let n=r.clone();for(;null!==n.prev;){s.push(n.clone());const e=n.clone();n=e.prev.clone()}return s.reverse(),s}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map((e=>this.piece(e)))}tokenIds(){return this.viterbi().map((e=>e.tokenId))}}class a{constructor(e,t,s,r,n){this.tokenId=e,this.nodeId=t,this.pos=s,this.length=r,this.score=n,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":
|
|
335
|
-
/*!******************************!*\
|
|
336
|
-
!*** ./src/utils/devices.js ***!
|
|
337
|
-
\******************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DEVICE_TYPES:()=>r});const r=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":
|
|
338
|
-
/*!*****************************!*\
|
|
339
|
-
!*** ./src/utils/dtypes.js ***!
|
|
340
|
-
\*****************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var r=s(/*! ../env.js */"./src/env.js"),n=s(/*! ./devices.js */"./src/utils/devices.js");const o=function(){let e;return async function(){if(void 0===e)if(r.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({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":
|
|
341
|
-
/*!******************************!*\
|
|
342
|
-
!*** ./src/utils/generic.js ***!
|
|
343
|
-
\******************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Callable:()=>r});const r=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":
|
|
344
|
-
/*!**************************!*\
|
|
345
|
-
!*** ./src/utils/hub.js ***!
|
|
346
|
-
\**************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{getFile:()=>d,getModelFile:()=>_,getModelJSON:()=>m});var r=s(/*! fs */"fs"),n=s(/*! path */"path"),o=s(/*! ../env.js */"./src/env.js"),i=s(/*! ./core.js */"./src/utils/core.js");const a={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"};class l{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=r.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let s=this;this.body=new ReadableStream({start(e){s.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",a[e]??"application/octet-stream")}clone(){let e=new l(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 r.promises.readFile(this.filePath)).buffer}async blob(){const e=await r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function c(e,t=null,s=null){let r;try{r=new URL(e)}catch(e){return!1}return!(t&&!t.includes(r.protocol))&&!(s&&!s.includes(r.hostname))}async function d(e){if(o.env.useFS&&!c(e,["http:","https:","blob:"]))return new l(e);if("undefined"!=typeof process&&"node"===process?.release?.name){const t=!!process.env?.TESTING_REMOTELY,s=o.env.version,r=new Headers;r.set("User-Agent",`transformers.js/${s}; is_ci/${t};`);if(c(e,["http:","https:"],["huggingface.co","hf.co"])){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&r.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:r})}return fetch(e)}const u={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 p{constructor(e){this.path=e}async match(e){let t=n.join(this.path,e),s=new l(t);return s.exists?s:void 0}async put(e,t){const s=Buffer.from(await t.arrayBuffer());let o=n.join(this.path,e);try{await r.promises.mkdir(n.dirname(o),{recursive:!0}),await r.promises.writeFile(o,s)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function _(e,t,s=!0,r={}){if(!o.env.allowLocalModels){if(r.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 n;if((0,i.dispatchCallback)(r.progress_callback,{status:"initiate",name:e,file:t}),!n&&o.env.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{n=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!n&&o.env.useFSCache&&(n=new p(r.cache_dir??o.env.cacheDir)),!n&&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");n=o.env.customCache}const a=r.revision??"main";let l,_,m=h(e,t),f=h(o.env.localModelPath,m),g=h(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(a)),t),w="main"===a?m:h(e,a,t),M=n instanceof p?w:g,b=!1;n&&(_=await async function(e,...t){for(let s of t)try{let t=await e.match(s);if(t)return t}catch(e){continue}}(n,f,M));const x=void 0!==_;if(void 0===_){if(o.env.allowLocalModels){if(c(m,["http:","https:"])){if(r.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{_=await d(f),l=f}catch(e){console.warn(`Unable to load from local path "${f}": "${e}"`)}}if(void 0===_||404===_.status){if(r.local_files_only||!o.env.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${f}".`);return null}if(_=await d(g),200!==_.status)return function(e,t,s){if(!s)return null;const r=u[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}(_.status,g,s);l=M}b=n&&"undefined"!=typeof Response&&_ instanceof Response&&200===_.status}(0,i.dispatchCallback)(r.progress_callback,{status:"download",name:e,file:t});const y={status:"progress",name:e,file:t};let k;return r.progress_callback?x&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(k=new Uint8Array(await _.arrayBuffer()),(0,i.dispatchCallback)(r.progress_callback,{...y,progress:100,loaded:k.length,total:k.length})):k=await async function(e,t){const s=e.headers.get("Content-Length");null===s&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(s??"0"),n=new Uint8Array(r),o=0;const i=e.body.getReader();async function a(){const{done:e,value:s}=await i.read();if(e)return;let l=o+s.length;if(l>r){r=l;let e=new Uint8Array(r);e.set(n),n=e}n.set(s,o),o=l;return t({progress:o/r*100,loaded:o,total:r}),a()}return await a(),n}(_,(e=>{(0,i.dispatchCallback)(r.progress_callback,{...y,...e})})):k=new Uint8Array(await _.arrayBuffer()),b&&l&&void 0===await n.match(l)&&await n.put(l,new Response(k,{headers:_.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)})),(0,i.dispatchCallback)(r.progress_callback,{status:"done",name:e,file:t}),k}async function m(e,t,s=!0,r={}){let n=await _(e,t,s,r);if(null===n)return{};let o=new TextDecoder("utf-8").decode(n);return JSON.parse(o)}function h(...e){return(e=e.map(((t,s)=>(s&&(t=t.replace(new RegExp("^/"),"")),s!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)))).join("/")}},"./src/utils/image.js":
|
|
347
|
-
/*!****************************!*\
|
|
348
|
-
!*** ./src/utils/image.js ***!
|
|
349
|
-
\****************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{RawImage:()=>m,load_image:()=>h});var r=s(/*! ./core.js */"./src/utils/core.js"),n=s(/*! ./hub.js */"./src/utils/hub.js"),o=s(/*! ../env.js */"./src/env.js"),i=s(/*! ./tensor.js */"./src/utils/tensor.js"),a=s(/*! sharp */"sharp");let l,c,d;const u=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(u)l=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},d=self.createImageBitmap,c=self.ImageData;else{if(!a)throw new Error("Unable to load image processing library.");d=async e=>{const t=(await e.metadata()).channels,{data:s,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),n=new m(new Uint8ClampedArray(s),r.width,r.height,r.channels);return void 0!==t&&t!==r.channels&&n.convert(t),n}}const p={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class m{constructor(e,t,s,r){this.data=e,this.width=t,this.height=s,this.channels=r}get size(){return[this.width,this.height]}static async read(e){if(e instanceof m)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(!u)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 m(t,e.width,e.height,4)}static async fromURL(e){const t=await(0,n.getFile)(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const s=await t.blob();return this.fromBlob(s)}static async fromBlob(e){if(u){const t=await d(e),s=l(t.width,t.height).getContext("2d");return s.drawImage(t,0,0),new this(s.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=a(await e.arrayBuffer());return await d(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 m(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,s=0;t<this.data.length;t+=this.channels){const r=this.data[t],n=this.data[t+1],o=this.data[t+2];e[s++]=Math.round(.2989*r+.587*n+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(3===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t];break;case 4:for(let t=0,s=0;t<this.data.length;t+=4)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(4===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=255;break;case 3:for(let t=0,s=0;t<this.data.length;t+=3)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}async resize(e,t,{resample:s=2}={}){if(this.width===e&&this.height===t)return this;let n=p[s]??s;const o=(0,r.isNullishDimension)(e),i=(0,r.isNullishDimension)(t);if(o&&i)return this;if(o?e=t/this.height*this.width:i&&(t=e/this.width*this.height),u){const s=this.channels,r=this.toCanvas(),n=l(e,t).getContext("2d");n.drawImage(r,0,0,e,t);return new m(n.getImageData(0,0,e,t).data,e,t,4).convert(s)}{let s=this.toSharp();switch(n){case"box":case"hamming":"box"!==n&&"hamming"!==n||(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":s=s.affine([e/this.width,0,0,t/this.height],{interpolator:n});break;case"lanczos":s=s.resize({width:e,height:t,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await d(s)}}async pad([e,t,s,r]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.max(s,0),r=Math.max(r,0),0===e&&0===t&&0===s&&0===r)return this;if(u){const n=this.channels,o=this.toCanvas(),i=this.width+e+t,a=this.height+s+r,c=l(i,a).getContext("2d");c.drawImage(o,0,0,this.width,this.height,e,s,this.width,this.height);return new m(c.getImageData(0,0,i,a).data,i,a,4).convert(n)}{const n=this.toSharp().extend({left:e,right:t,top:s,bottom:r});return await d(n)}}async crop([e,t,s,r]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.min(s,this.width-1),r=Math.min(r,this.height-1),0===e&&0===t&&s===this.width-1&&r===this.height-1)return this;const n=s-e+1,o=r-t+1;if(u){const s=this.channels,r=this.toCanvas(),i=l(n,o).getContext("2d");i.drawImage(r,e,t,n,o,0,0,n,o);return new m(i.getImageData(0,0,n,o).data,n,o,4).convert(s)}{const s=this.toSharp().extract({left:e,top:t,width:n,height:o});return await d(s)}}async center_crop(e,t){if(this.width===e&&this.height===t)return this;const s=(this.width-e)/2,r=(this.height-t)/2;if(u){const n=this.channels,o=this.toCanvas(),i=l(e,t).getContext("2d");let a=0,c=0,d=0,u=0;s>=0?a=s:d=-s,r>=0?c=r:u=-r,i.drawImage(o,a,c,e,t,d,u,e,t);return new m(i.getImageData(0,0,e,t).data,e,t,4).convert(n)}{let n=this.toSharp();if(s>=0&&r>=0)n=n.extract({left:Math.floor(s),top:Math.floor(r),width:e,height:t});else if(s<=0&&r<=0){const o=Math.floor(-r),i=Math.floor(-s);n=n.extend({top:o,left:i,right:e-this.width-i,bottom:t-this.height-o})}else{let o=[0,0],i=0;r<0?(o[0]=Math.floor(-r),o[1]=t-this.height-o[0]):i=Math.floor(r);let a=[0,0],l=0;s<0?(a[0]=Math.floor(-s),a[1]=e-this.width-a[0]):l=Math.floor(s),n=n.extend({top:o[0],bottom:o[1],left:a[0],right:a[1]}).extract({left:l,top:i,width:e,height:t})}return await d(n)}}async toBlob(e="image/png",t=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");const s=this.toCanvas();return await s.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new i.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(!u)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=l(e.width,e.height),s=new c(e.data,e.width,e.height);return t.getContext("2d").putImageData(s,0,0),t}split(){const{data:e,width:t,height:s,channels:r}=this,n=e.constructor,o=e.length/r,i=Array.from({length:r},(()=>new n(o)));for(let t=0;t<o;++t){const s=r*t;for(let n=0;n<r;++n)i[n][t]=e[s+n]}return i.map((e=>new m(e,t,s,1)))}_update(e,t,s,r=null){return this.data=e,this.width=t,this.height=s,null!==r&&(this.channels=r),this}clone(){return new m(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(!u){if(o.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(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),s=_.get(t)??"image/png",r=await this.toBlob(s),n=URL.createObjectURL(r),i=document.createElement("a");i.href=n,i.download=e,i.click(),i.remove()}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const h=m.read.bind(m)},"./src/utils/maths.js":
|
|
350
|
-
/*!****************************!*\
|
|
351
|
-
!*** ./src/utils/maths.js ***!
|
|
352
|
-
\****************************/(e,t,s)=>{"use strict";function r(e,[t,s,r],[n,o],i="bilinear",a=!1){const l=o/r,c=n/s,d=new e.constructor(n*o*t),u=s*r,p=n*o;for(let i=0;i<n;++i)for(let n=0;n<o;++n){const a=i*o+n,_=(n+.5)/l-.5,m=(i+.5)/c-.5;let h=Math.floor(_),f=Math.floor(m);const g=Math.min(h+1,r-1),w=Math.min(f+1,s-1);h=Math.max(h,0),f=Math.max(f,0);const M=_-h,b=m-f,x=(1-M)*(1-b),y=M*(1-b),k=(1-M)*b,T=M*b,v=f*r,P=w*r,F=v+h,C=v+g,A=P+h,S=P+g;for(let s=0;s<t;++s){const t=s*u;d[s*p+a]=x*e[t+F]+y*e[t+C]+k*e[t+A]+T*e[t+S]}}return d}function n(e,t,s){const r=new Array(s.length),n=new Array(s.length);for(let e=s.length-1,o=1;e>=0;--e)n[e]=o,r[e]=t[s[e]],o*=r[e];const o=s.map(((e,t)=>n[s.indexOf(t)])),i=new e.constructor(e.length);for(let s=0;s<e.length;++s){let r=0;for(let e=t.length-1,n=s;e>=0;--e)r+=n%t[e]*o[e],n=Math.floor(n/t[e]);i[r]=e[s]}return[i,r]}function o(e){const t=u(e)[0],s=e.map((e=>Math.exp(e-t))),r=s.reduce(((e,t)=>e+t),0);return s.map((e=>e/r))}function i(e){const t=u(e)[0];let s=0;for(let r=0;r<e.length;++r)s+=Math.exp(e[r]-t);const r=Math.log(s);return e.map((e=>e-t-r))}function a(e,t){let s=0;for(let r=0;r<e.length;++r)s+=e[r]*t[r];return s}function l(e,t){return a(e,t)/(c(e)*c(t))}function c(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}function d(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],s=r);return[t,s]}function u(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],s=r);return[Number(t),s]}function p(e){return e>0&&!(e&e-1)}s.r(t),s.d(t,{FFT:()=>h,bankers_round:()=>w,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>M,interpolate_data:()=>r,log_softmax:()=>i,magnitude:()=>c,max:()=>u,medianFilter:()=>f,min:()=>d,permute_data:()=>n,round:()=>g,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;e<this.table.length;e+=2){const t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){const s=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const s=t||new Array(e.length>>>1);for(let t=0;t<e.length;t+=2)s[t>>>1]=e[t];return s}toComplexArray(e,t){const s=t||this.createComplexArray();for(let t=0;t<s.length;t+=2)s[t]=e[t>>>1],s[t+1]=0;return s}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,s){const r=this._csize;let n,o,i=1<<this._width,a=r/i<<1;const l=this._bitrev;if(4===a)for(n=0,o=0;n<r;n+=a,++o){const s=l[o];this._singleTransform2(t,e,n,s,i)}else for(n=0,o=0;n<r;n+=a,++o){const r=l[o];this._singleTransform4(t,e,n,r,i,s)}const c=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;const t=a>>>2;for(n=0;n<r;n+=a){const r=n+t-1;for(let o=n,a=0;o<r;o+=2,a+=i){const r=o,n=r+t,i=n+t,l=i+t,d=e[r],u=e[r+1],p=e[n],_=e[n+1],m=e[i],h=e[i+1],f=e[l],g=e[l+1],w=c[a],M=s*c[a+1],b=p*w-_*M,x=p*M+_*w,y=c[2*a],k=s*c[2*a+1],T=m*y-h*k,v=m*k+h*y,P=c[3*a],F=s*c[3*a+1],C=f*P-g*F,A=f*F+g*P,S=d+T,E=u+v,L=d-T,I=u-v,z=b+C,j=x+A,N=s*(b-C),O=s*(x-A);e[r]=S+z,e[r+1]=E+j,e[n]=L+O,e[n+1]=I-N,e[i]=S-z,e[i+1]=E-j,e[l]=L-O,e[l+1]=I+N}}}}_singleTransform2(e,t,s,r,n){const o=e[r],i=e[r+1],a=e[r+n],l=e[r+n+1];t[s]=o+a,t[s+1]=i+l,t[s+2]=o-a,t[s+3]=i-l}_singleTransform4(e,t,s,r,n,o){const i=2*n,a=3*n,l=e[r],c=e[r+1],d=e[r+n],u=e[r+n+1],p=e[r+i],_=e[r+i+1],m=e[r+a],h=e[r+a+1],f=l+p,g=c+_,w=l-p,M=c-_,b=d+m,x=u+h,y=o*(d-m),k=o*(u-h);t[s]=f+b,t[s+1]=g+x,t[s+2]=w+k,t[s+3]=M-y,t[s+4]=f-b,t[s+5]=g-x,t[s+6]=w-k,t[s+7]=M+y}_realTransform4(e,t,s){const r=this._csize;let n,o,i=1<<this._width,a=r/i<<1;const l=this._bitrev;if(4===a)for(n=0,o=0;n<r;n+=a,++o){const s=l[o];this._singleRealTransform2(t,e,n,s>>>1,i>>>1)}else for(n=0,o=0;n<r;n+=a,++o){const r=l[o];this._singleRealTransform4(t,e,n,r>>>1,i>>>1,s)}const c=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;const t=a>>>1,o=t>>>1,l=o>>>1;for(n=0;n<r;n+=a)for(let r=0,a=0;r<=l;r+=2,a+=i){const i=n+r,d=i+o,u=d+o,p=u+o,_=e[i],m=e[i+1],h=e[d],f=e[d+1],g=e[u],w=e[u+1],M=e[p],b=e[p+1],x=_,y=m,k=c[a],T=s*c[a+1],v=h*k-f*T,P=h*T+f*k,F=c[2*a],C=s*c[2*a+1],A=g*F-w*C,S=g*C+w*F,E=c[3*a],L=s*c[3*a+1],I=M*E-b*L,z=M*L+b*E,j=x+A,N=y+S,O=x-A,B=y-S,V=v+I,D=P+z,R=s*(v-I),G=s*(P-z);if(e[i]=j+V,e[i+1]=N+D,e[d]=O+G,e[d+1]=B-R,0===r){e[u]=j-V,e[u+1]=N-D;continue}if(r===l)continue;const $=n+o-r,q=n+t-r;e[$]=O-s*G,e[$+1]=-B-s*R,e[q]=j-s*V,e[q+1]=s*D-N}}const d=r>>>1;for(let t=2;t<d;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,s,r,n){const o=e[r],i=e[r+n];t[s]=o+i,t[s+1]=0,t[s+2]=o-i,t[s+3]=0}_singleRealTransform4(e,t,s,r,n,o){const i=2*n,a=3*n,l=e[r],c=e[r+n],d=e[r+i],u=e[r+a],p=l+d,_=l-d,m=c+u,h=o*(c-u);t[s]=p+m,t[s+1]=0,t[s+2]=_,t[s+3]=-h,t[s+4]=p-m,t[s+5]=0,t[s+6]=_,t[s+7]=h}}class m{constructor(e){const t=2*(e-1),s=2*(2*e-1),r=2**Math.ceil(Math.log2(s));this.bufferSize=r,this._a=t;const n=new Float64Array(s),o=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);const i=-2*Math.PI/e,a=Math.cos(i),l=Math.sin(i);for(let t=0;t<s>>1;++t){const s=(t+1-e)**2/2,r=Math.sqrt(a**2+l**2)**s,i=s*Math.atan2(l,a),c=2*t;n[c]=r*Math.cos(i),n[c+1]=r*Math.sin(i),o[c]=n[c],o[c+1]=-n[c+1]}this._slicedChirpBuffer=n.subarray(t,s),this._f=new _(r>>1),this._f.transform(this._chirpBuffer,o)}_transform(e,t,s){const r=this._buffer1,n=this._buffer2,o=this._outBuffer1,i=this._outBuffer2,a=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(s)for(let e=0;e<l.length;e+=2){const s=e+1,n=t[e>>1];r[e]=n*l[e],r[s]=n*l[s]}else for(let e=0;e<l.length;e+=2){const s=e+1;r[e]=t[e]*l[e]-t[s]*l[s],r[s]=t[e]*l[s]+t[s]*l[e]}this._f.transform(o,r);for(let e=0;e<a.length;e+=2){const t=e+1;n[e]=o[e]*a[e]-o[t]*a[t],n[t]=o[e]*a[t]+o[t]*a[e]}this._f.inverseTransform(i,n);for(let t=0;t<i.length;t+=2){const s=i[t+c],r=i[t+c+1],n=l[t],o=l[t+1];e[t]=s*n-r*o,e[t+1]=s*o+r*n}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}}class h{constructor(e){this.fft_length=e,this.isPowerOfTwo=p(e),this.isPowerOfTwo?(this.fft=new _(e),this.outputBufferSize=2*e):(this.fft=new m(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}}function f(e,t){if(t%2==0||t<=0)throw new Error("Window size must be a positive odd number");const s=new e.constructor(e.length),r=new e.constructor(t),n=Math.floor(t/2);for(let t=0;t<e.length;++t){let o=0;for(let s=-n;s<=n;++s){let n=t+s;n<0?n=Math.abs(n):n>=e.length&&(n=2*(e.length-1)-n),r[o++]=e[n]}r.sort(),s[t]=r[n]}return s}function g(e,t){const s=Math.pow(10,t);return Math.round(e*s)/s}function w(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function M(e){const t=e.length,s=e[0].length,r=[t+1,s+1],n=Array.from({length:r[0]},(()=>Array(r[1]).fill(1/0)));n[0][0]=0;const o=Array.from({length:r[0]},(()=>Array(r[1]).fill(-1)));for(let t=1;t<r[1];++t)for(let s=1;s<r[0];++s){const r=n[s-1][t-1],i=n[s-1][t],a=n[s][t-1];let l,c;r<i&&r<a?(l=r,c=0):i<r&&i<a?(l=i,c=1):(l=a,c=2),n[s][t]=e[s-1][t-1]+l,o[s][t]=c}for(let e=0;e<r[1];++e)o[0][e]=2;for(let e=0;e<r[0];++e)o[e][0]=1;let i=t,a=s,l=[],c=[];for(;i>0||a>0;)switch(l.push(i-1),c.push(a-1),o[i][a]){case 0:--i,--a;break;case 1:--i;break;case 2:--a;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${a}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}},"./src/utils/tensor.js":
|
|
353
|
-
/*!*****************************!*\
|
|
354
|
-
!*** ./src/utils/tensor.js ***!
|
|
355
|
-
\*****************************/(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>a,cat:()=>M,full:()=>T,full_like:()=>v,interpolate:()=>c,interpolate_4d:()=>d,layer_norm:()=>h,matmul:()=>u,mean:()=>y,mean_pooling:()=>m,ones:()=>P,ones_like:()=>F,permute:()=>l,quantize_embeddings:()=>S,rfft:()=>p,stack:()=>b,std_mean:()=>x,topk:()=>_,zeros:()=>C,zeros_like:()=>A});var r=s(/*! ./maths.js */"./src/utils/maths.js"),n=s(/*! ../backends/onnx.js */"./src/backends/onnx.js"),o=s(/*! ../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,uint4:Uint8Array,int4:Int8Array});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}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return(0,n.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new n.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let s=Number(t);if(Number.isInteger(s))return e._getitem(s)}return e[t]},set:(e,t,s)=>e[t]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const s=t.reduce(((e,t)=>e*t));for(let r=0;r<e;++r)yield this._subarray(r,s,t)}else yield*this.data}_getitem(e){const[t,...s]=this.dims;if(e=w(e,t),s.length>0){const t=s.reduce(((e,t)=>e*t));return this._subarray(e,t,s)}return new a(this.type,[this.data[e]],s)}indexOf(e){const t=this.data;for(let s=0;s<t.length;++s)if(t[s]==e)return s;return-1}_subarray(e,t,s){const r=e*t,n=(e+1)*t,o="subarray"in this.data?this.data.subarray(r,n):this.data.slice(r,n);return new a(this.type,o,s)}item(){const e=this.data;if(1!==e.length)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return function(e,t){const s=e.length,r=t.reduce(((e,t)=>e*t));if(s!==r)throw Error(`cannot reshape array of size ${s} into shape (${t})`);let n=e;for(let e=t.length-1;e>=0;e--)n=n.reduce(((s,r)=>{let n=s[s.length-1];return n.length<t[e]?n.push(r):s.push([r]),s}),[[]]);return n[0]}(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]=e(t[s],s,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]-=e;return this}clone(){return new a(this.type,this.data.slice(),this.dims.slice())}slice(...e){const t=[],s=[];for(let r=0;r<this.dims.length;++r){let n=e[r];if(null==n)s.push([0,this.dims[r]]),t.push(this.dims[r]);else if("number"==typeof n)n=w(n,this.dims[r],r),s.push([n,n+1]);else{if(!Array.isArray(n)||2!==n.length)throw new Error(`Invalid slice: ${n}`);{let[e,o]=n;if(e=null===e?0:w(e,this.dims[r],r,!1),o=null===o?this.dims[r]:w(o,this.dims[r],r,!1),e>o)throw new Error(`Invalid slice: ${n}`);const i=[Math.max(e,0),Math.min(o,this.dims[r])];s.push(i),t.push(i[1]-i[0])}}}const r=s.map((([e,t])=>t-e)),n=r.reduce(((e,t)=>e*t)),o=this.data,i=new o.constructor(n),l=this.stride();for(let e=0;e<n;++e){let t=0;for(let n=r.length-1,o=e;n>=0;--n){const e=r[n];t+=(o%e+s[n][0])*l[n],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,s=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const r=this.data;if(null===t){let t=r.reduce(((t,s)=>t+s**e),0)**(1/e);return new a(this.type,[t],[])}t=w(t,this.dims.length);const n=this.dims.slice();n[t]=1;const o=new r.constructor(r.length/this.dims[t]);for(let s=0;s<r.length;++s){let i=0;for(let e=this.dims.length-1,r=s,o=1;e>=0;--e){const s=this.dims[e];if(e!==t){i+=r%s*o,o*=n[e]}r=Math.floor(r/s)}o[i]+=r[s]**e}if(1!==e)for(let t=0;t<o.length;++t)o[t]=o[t]**(1/e);return s||n.splice(t,1),new a(this.type,o,n)}normalize_(e=2,t=1){t=w(t,this.dims.length);const s=this.norm(e,t,!0),r=this.data,n=s.data;for(let e=0;e<r.length;++e){let s=0;for(let r=this.dims.length-1,n=e,o=1;r>=0;--r){const e=this.dims[r];if(r!==t){s+=n%e*o,o*=this.dims[r]}n=Math.floor(n/e)}r[e]/=n[s]}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 s=e.length-1,r=1;s>=0;--s)t[s]=r,r*=e[s];return t}(this.dims)}squeeze(e=null){return new a(this.type,this.data,f(this.dims,e))}squeeze_(e=null){return this.dims=f(this.dims,e),this}unsqueeze(e=null){return new a(this.type,this.data,g(this.dims,e))}unsqueeze_(e=null){return this.dims=g(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),r=this.dims.slice(e,t+1),n=this.dims.slice(t+1);return this.dims=[...s,r.reduce(((e,t)=>e*t),1),...n],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let s=0;s<e.length;++s)if(-1===e[s]){if(-1!==t)throw new Error("Only one dimension can be inferred");t=s}const s=this.data;if(-1!==t){const r=e.reduce(((e,s,r)=>r!==t?e*s:e),1);e[t]=s.length/r}return new a(this.type,s,e)}neg_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}clamp_(e,t){const s=this.data;for(let r=0;r<s.length;++r)s[r]=Math.min(Math.max(s[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return y(this,e,t)}to(e){if(this.type===e)return this;if(!i.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);return new a(e,i[e].from(this.data),this.dims)}}function l(e,t){const[s,n]=(0,r.permute_data)(e.data,e.dims,t);return new a(e.type,s,n)}function c(e,[t,s],n="bilinear",o=!1){const i=e.dims.at(-3)??1,l=e.dims.at(-2),c=e.dims.at(-1);let d=(0,r.interpolate_data)(e.data,[i,l,c],[t,s],n,o);return new a(e.type,d,[i,t,s])}async function d(e,{size:t=null,mode:s="bilinear"}={}){if(4!==e.dims.length)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let r,n;if(2===t.length)r=[...e.dims.slice(0,2),...t];else if(3===t.length)r=[e.dims[0],...t];else{if(4!==t.length)throw new Error("`size` must be of length 2, 3, or 4.");r=t}if("bilinear"===s)n=await o.TensorOpRegistry.bilinear_interpolate_4d;else{if("bicubic"!==s)throw new Error(`Unsupported mode: ${s}`);n=await o.TensorOpRegistry.bicubic_interpolate_4d}const i=new a("int64",new BigInt64Array(r.map(BigInt)),[r.length]);return await n({x:e,s:i})}async function u(e,t){const s=await o.TensorOpRegistry.matmul;return await s({a:e,b:t})}async function p(e,t){const s=await o.TensorOpRegistry.rfft;return await s({x:e,a:t})}async function _(e,t){const s=await o.TensorOpRegistry.top_k;return t=null===t?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await s({x:e,k:new a("int64",[BigInt(t)],[1])})}function m(e,t){const s=e.data,r=t.data,n=[e.dims[0],e.dims[2]],o=new s.constructor(n[0]*n[1]),[i,l,c]=e.dims;let d=0;for(let e=0;e<i;++e){const t=e*c*l;for(let n=0;n<c;++n){let i=0,a=0;const u=e*l,p=t+n;for(let e=0;e<l;++e){const t=Number(r[u+e]);a+=t,i+=s[p+e*c]*t}const _=i/a;o[d++]=_}}return new a(e.type,o,n)}function h(e,t,{eps:s=1e-5}={}){if(2!==e.dims.length)throw new Error("`layer_norm` currently only supports 2D input.");const[r,n]=e.dims;if(1!==t.length&&t[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[o,i]=x(e,1,0,!0),l=o.data,c=i.data,d=e.data,u=new d.constructor(d.length);for(let e=0;e<r;++e){const t=e*n;for(let r=0;r<n;++r){const n=t+r;u[n]=(d[n]-c[e])/(l[e]+s)}}return new a(e.type,u,e.dims)}function f(e,t){return e=e.slice(),null===t?e=e.filter((e=>1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,s)=>1!==e||!t.includes(s)))),e}function g(e,t){return t=w(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function w(e,t,s=null,r=!0){if(r&&(e<-t||e>=t))throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===s?"":" "+s} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function M(e,t=0){t=w(t,e[0].dims.length);const s=e[0].dims.slice();s[t]=e.reduce(((e,s)=>e+s.dims[t]),0);const r=s.reduce(((e,t)=>e*t),1),n=new e[0].data.constructor(r),o=e[0].type;if(0===t){let t=0;for(const s of e){const e=s.data;n.set(e,t),t+=e.length}}else{let r=0;for(let o=0;o<e.length;++o){const{data:i,dims:a}=e[o];for(let e=0;e<i.length;++e){let o=0;for(let n=a.length-1,i=e,l=1;n>=0;--n){const e=a[n];let c=i%e;n===t&&(c+=r),o+=c*l,l*=s[n],i=Math.floor(i/e)}n[o]=i[e]}r+=a[t]}}return new a(o,n,s)}function b(e,t=0){return M(e.map((e=>e.unsqueeze(t))),t)}function x(e,t=null,s=1,r=!1){const n=e.data,o=e.dims;if(null===t){const t=n.reduce(((e,t)=>e+t),0)/n.length,r=Math.sqrt(n.reduce(((e,s)=>e+(s-t)**2),0)/(n.length-s)),o=new a(e.type,[t],[]);return[new a(e.type,[r],[]),o]}const i=y(e,t=w(t,o.length),r),l=i.data,c=o.slice();c[t]=1;const d=new n.constructor(n.length/o[t]);for(let e=0;e<n.length;++e){let s=0;for(let r=o.length-1,n=e,i=1;r>=0;--r){const e=o[r];if(r!==t){s+=n%e*i,i*=c[r]}n=Math.floor(n/e)}d[s]+=(n[e]-l[s])**2}for(let e=0;e<d.length;++e)d[e]=Math.sqrt(d[e]/(o[t]-s));r||c.splice(t,1);return[new a(e.type,d,c),i]}function y(e,t=null,s=!1){const r=e.data;if(null===t){const t=r.reduce(((e,t)=>e+t),0);return new a(e.type,[t/r.length],[])}const n=e.dims;t=w(t,n.length);const o=n.slice();o[t]=1;const i=new r.constructor(r.length/n[t]);for(let e=0;e<r.length;++e){let s=0;for(let r=n.length-1,i=e,a=1;r>=0;--r){const e=n[r];if(r!==t){s+=i%e*a,a*=o[r]}i=Math.floor(i/e)}i[s]+=r[e]}if(1!==n[t])for(let e=0;e<i.length;++e)i[e]=i[e]/n[t];return s||o.splice(t,1),new a(e.type,i,o)}function k(e,t,s,r){const n=e.reduce(((e,t)=>e*t),1);return new a(s,new r(n).fill(t),e)}function T(e,t){let s,r;if("number"==typeof t)s="float32",r=Float32Array;else if("bigint"==typeof t)s="int64",r=BigInt64Array;else{if("boolean"!=typeof t)throw new Error("Unsupported data type: "+typeof t);s="bool",r=Uint8Array}return k(e,t,s,r)}function v(e,t){return T(e.dims,t)}function P(e){return k(e,1n,"int64",BigInt64Array)}function F(e){return P(e.dims)}function C(e){return k(e,0n,"int64",BigInt64Array)}function A(e){return C(e.dims)}function S(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 s="binary"===t,r=s?"int8":"uint8",n=s?Int8Array:Uint8Array,o=e.data,i=new n(o.length/8);for(let e=0;e<o.length;++e){const t=o[e]>0?1:0,r=Math.floor(e/8),n=e%8;i[r]|=t<<7-n,s&&0===n&&(i[r]-=128)}return new a(r,i,[e.dims[0],e.dims[1]/8])}}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var o=r[e]={exports:{}};return s[e](o,o.exports,n),o.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(s,r){if(1&r&&(s=this(s)),8&r)return s;if("object"==typeof s&&s){if(4&r&&s.__esModule)return s;if(16&r&&"function"==typeof s.then)return s}var o=Object.create(null);n.r(o);var i={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&s;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>i[e]=()=>s[e]));return i.default=()=>s,n.d(o,i),o},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";
|
|
356
|
-
/*!*****************************!*\
|
|
357
|
-
!*** ./src/transformers.js ***!
|
|
358
|
-
\*****************************/n.r(o),n.d(o,{ASTFeatureExtractor:()=>p.ASTFeatureExtractor,ASTForAudioClassification:()=>s.ASTForAudioClassification,ASTModel:()=>s.ASTModel,ASTPreTrainedModel:()=>s.ASTPreTrainedModel,AlbertForMaskedLM:()=>s.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>s.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>s.AlbertForSequenceClassification,AlbertModel:()=>s.AlbertModel,AlbertPreTrainedModel:()=>s.AlbertPreTrainedModel,AlbertTokenizer:()=>r.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>i.AutoConfig,AutoFeatureExtractor:()=>_.AutoFeatureExtractor,AutoImageProcessor:()=>f.AutoImageProcessor,AutoModel:()=>s.AutoModel,AutoModelForAudioClassification:()=>s.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>s.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>s.AutoModelForCTC,AutoModelForCausalLM:()=>s.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>s.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>s.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>s.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>s.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>s.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>s.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>s.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>s.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>s.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>s.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>s.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>s.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>s.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>s.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>s.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>s.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>s.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>s.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>s.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>s.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>s.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>s.AutoModelForVision2Seq,AutoModelForXVector:()=>s.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>s.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>M.AutoProcessor,AutoTokenizer:()=>r.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>s.BartForConditionalGeneration,BartForSequenceClassification:()=>s.BartForSequenceClassification,BartModel:()=>s.BartModel,BartPretrainedModel:()=>s.BartPretrainedModel,BartTokenizer:()=>r.BartTokenizer,BaseModelOutput:()=>s.BaseModelOutput,BaseStreamer:()=>b.BaseStreamer,BeitFeatureExtractor:()=>h.BeitFeatureExtractor,BeitForImageClassification:()=>s.BeitForImageClassification,BeitModel:()=>s.BeitModel,BeitPreTrainedModel:()=>s.BeitPreTrainedModel,BertForMaskedLM:()=>s.BertForMaskedLM,BertForQuestionAnswering:()=>s.BertForQuestionAnswering,BertForSequenceClassification:()=>s.BertForSequenceClassification,BertForTokenClassification:()=>s.BertForTokenClassification,BertModel:()=>s.BertModel,BertPreTrainedModel:()=>s.BertPreTrainedModel,BertTokenizer:()=>r.BertTokenizer,BitImageProcessor:()=>h.BitImageProcessor,BlenderbotForConditionalGeneration:()=>s.BlenderbotForConditionalGeneration,BlenderbotModel:()=>s.BlenderbotModel,BlenderbotPreTrainedModel:()=>s.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>s.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>s.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>s.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>r.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>r.BlenderbotTokenizer,BloomForCausalLM:()=>s.BloomForCausalLM,BloomModel:()=>s.BloomModel,BloomPreTrainedModel:()=>s.BloomPreTrainedModel,BloomTokenizer:()=>r.BloomTokenizer,CLIPFeatureExtractor:()=>h.CLIPFeatureExtractor,CLIPImageProcessor:()=>h.CLIPImageProcessor,CLIPModel:()=>s.CLIPModel,CLIPPreTrainedModel:()=>s.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>s.CLIPSegForImageSegmentation,CLIPSegModel:()=>s.CLIPSegModel,CLIPSegPreTrainedModel:()=>s.CLIPSegPreTrainedModel,CLIPTextModel:()=>s.CLIPTextModel,CLIPTextModelWithProjection:()=>s.CLIPTextModelWithProjection,CLIPTokenizer:()=>r.CLIPTokenizer,CLIPVisionModel:()=>s.CLIPVisionModel,CLIPVisionModelWithProjection:()=>s.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>s.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>s.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>s.CamembertForSequenceClassification,CamembertForTokenClassification:()=>s.CamembertForTokenClassification,CamembertModel:()=>s.CamembertModel,CamembertPreTrainedModel:()=>s.CamembertPreTrainedModel,CamembertTokenizer:()=>r.CamembertTokenizer,CausalLMOutput:()=>s.CausalLMOutput,CausalLMOutputWithPast:()=>s.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>h.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>s.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>s.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>s.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>p.ClapFeatureExtractor,ClapModel:()=>s.ClapModel,ClapPreTrainedModel:()=>s.ClapPreTrainedModel,ClapTextModelWithProjection:()=>s.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>s.CodeGenForCausalLM,CodeGenModel:()=>s.CodeGenModel,CodeGenPreTrainedModel:()=>s.CodeGenPreTrainedModel,CodeGenTokenizer:()=>r.CodeGenTokenizer,CodeLlamaTokenizer:()=>r.CodeLlamaTokenizer,CohereForCausalLM:()=>s.CohereForCausalLM,CohereModel:()=>s.CohereModel,CoherePreTrainedModel:()=>s.CoherePreTrainedModel,CohereTokenizer:()=>r.CohereTokenizer,ConvBertForMaskedLM:()=>s.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>s.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>s.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>s.ConvBertForTokenClassification,ConvBertModel:()=>s.ConvBertModel,ConvBertPreTrainedModel:()=>s.ConvBertPreTrainedModel,ConvBertTokenizer:()=>r.ConvBertTokenizer,ConvNextFeatureExtractor:()=>h.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>s.ConvNextForImageClassification,ConvNextImageProcessor:()=>h.ConvNextImageProcessor,ConvNextModel:()=>s.ConvNextModel,ConvNextPreTrainedModel:()=>s.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>s.ConvNextV2ForImageClassification,ConvNextV2Model:()=>s.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>s.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>h.DPTFeatureExtractor,DPTForDepthEstimation:()=>s.DPTForDepthEstimation,DPTImageProcessor:()=>h.DPTImageProcessor,DPTModel:()=>s.DPTModel,DPTPreTrainedModel:()=>s.DPTPreTrainedModel,DebertaForMaskedLM:()=>s.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>s.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>s.DebertaForSequenceClassification,DebertaForTokenClassification:()=>s.DebertaForTokenClassification,DebertaModel:()=>s.DebertaModel,DebertaPreTrainedModel:()=>s.DebertaPreTrainedModel,DebertaTokenizer:()=>r.DebertaTokenizer,DebertaV2ForMaskedLM:()=>s.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>s.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>s.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>s.DebertaV2ForTokenClassification,DebertaV2Model:()=>s.DebertaV2Model,DebertaV2PreTrainedModel:()=>s.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>r.DebertaV2Tokenizer,DecisionTransformerModel:()=>s.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>s.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>h.DeiTFeatureExtractor,DeiTForImageClassification:()=>s.DeiTForImageClassification,DeiTImageProcessor:()=>h.DeiTImageProcessor,DeiTModel:()=>s.DeiTModel,DeiTPreTrainedModel:()=>s.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>s.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>s.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DepthProForDepthEstimation:()=>s.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>s.DepthProPreTrainedModel,DetrFeatureExtractor:()=>h.DetrFeatureExtractor,DetrForObjectDetection:()=>s.DetrForObjectDetection,DetrForSegmentation:()=>s.DetrForSegmentation,DetrImageProcessor:()=>h.DetrImageProcessor,DetrModel:()=>s.DetrModel,DetrObjectDetectionOutput:()=>s.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>s.DetrPreTrainedModel,DetrSegmentationOutput:()=>s.DetrSegmentationOutput,Dinov2ForImageClassification:()=>s.Dinov2ForImageClassification,Dinov2Model:()=>s.Dinov2Model,Dinov2PreTrainedModel:()=>s.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>s.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>s.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>s.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>s.DistilBertForTokenClassification,DistilBertModel:()=>s.DistilBertModel,DistilBertPreTrainedModel:()=>s.DistilBertPreTrainedModel,DistilBertTokenizer:()=>r.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>h.DonutFeatureExtractor,DonutImageProcessor:()=>h.DonutImageProcessor,DonutSwinModel:()=>s.DonutSwinModel,DonutSwinPreTrainedModel:()=>s.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>s.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,EfficientNetModel:()=>s.EfficientNetModel,EfficientNetPreTrainedModel:()=>s.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>s.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>s.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>s.ElectraForSequenceClassification,ElectraForTokenClassification:()=>s.ElectraForTokenClassification,ElectraModel:()=>s.ElectraModel,ElectraPreTrainedModel:()=>s.ElectraPreTrainedModel,ElectraTokenizer:()=>r.ElectraTokenizer,EosTokenCriteria:()=>x.EosTokenCriteria,EsmForMaskedLM:()=>s.EsmForMaskedLM,EsmForSequenceClassification:()=>s.EsmForSequenceClassification,EsmForTokenClassification:()=>s.EsmForTokenClassification,EsmModel:()=>s.EsmModel,EsmPreTrainedModel:()=>s.EsmPreTrainedModel,EsmTokenizer:()=>r.EsmTokenizer,FFT:()=>d.FFT,FalconForCausalLM:()=>s.FalconForCausalLM,FalconModel:()=>s.FalconModel,FalconPreTrainedModel:()=>s.FalconPreTrainedModel,FalconTokenizer:()=>r.FalconTokenizer,FastViTForImageClassification:()=>s.FastViTForImageClassification,FastViTModel:()=>s.FastViTModel,FastViTPreTrainedModel:()=>s.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>u.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>s.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>s.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>h.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>s.GLPNForDepthEstimation,GLPNModel:()=>s.GLPNModel,GLPNPreTrainedModel:()=>s.GLPNPreTrainedModel,GPT2LMHeadModel:()=>s.GPT2LMHeadModel,GPT2Model:()=>s.GPT2Model,GPT2PreTrainedModel:()=>s.GPT2PreTrainedModel,GPT2Tokenizer:()=>r.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>s.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>s.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>s.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>s.GPTJForCausalLM,GPTJModel:()=>s.GPTJModel,GPTJPreTrainedModel:()=>s.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>s.GPTNeoForCausalLM,GPTNeoModel:()=>s.GPTNeoModel,GPTNeoPreTrainedModel:()=>s.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>s.GPTNeoXForCausalLM,GPTNeoXModel:()=>s.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>s.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>r.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>s.Gemma2ForCausalLM,Gemma2Model:()=>s.Gemma2Model,Gemma2PreTrainedModel:()=>s.Gemma2PreTrainedModel,GemmaForCausalLM:()=>s.GemmaForCausalLM,GemmaModel:()=>s.GemmaModel,GemmaPreTrainedModel:()=>s.GemmaPreTrainedModel,GemmaTokenizer:()=>r.GemmaTokenizer,GraniteForCausalLM:()=>s.GraniteForCausalLM,GraniteModel:()=>s.GraniteModel,GranitePreTrainedModel:()=>s.GranitePreTrainedModel,Grok1Tokenizer:()=>r.Grok1Tokenizer,GroupViTModel:()=>s.GroupViTModel,GroupViTPreTrainedModel:()=>s.GroupViTPreTrainedModel,HerbertTokenizer:()=>r.HerbertTokenizer,HieraForImageClassification:()=>s.HieraForImageClassification,HieraModel:()=>s.HieraModel,HieraPreTrainedModel:()=>s.HieraPreTrainedModel,HubertForCTC:()=>s.HubertForCTC,HubertForSequenceClassification:()=>s.HubertForSequenceClassification,HubertModel:()=>s.HubertModel,HubertPreTrainedModel:()=>s.HubertPreTrainedModel,Idefics3ForConditionalGeneration:()=>s.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>h.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>s.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>p.ImageFeatureExtractor,ImageMattingOutput:()=>s.ImageMattingOutput,ImageProcessor:()=>m.ImageProcessor,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>x.InterruptableStoppingCriteria,JAISLMHeadModel:()=>s.JAISLMHeadModel,JAISModel:()=>s.JAISModel,JAISPreTrainedModel:()=>s.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>h.JinaCLIPImageProcessor,JinaCLIPModel:()=>s.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>s.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>s.JinaCLIPTextModel,JinaCLIPVisionModel:()=>s.JinaCLIPVisionModel,LlamaForCausalLM:()=>s.LlamaForCausalLM,LlamaModel:()=>s.LlamaModel,LlamaPreTrainedModel:()=>s.LlamaPreTrainedModel,LlamaTokenizer:()=>r.LlamaTokenizer,LlavaForConditionalGeneration:()=>s.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>s.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>h.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>s.LlavaPreTrainedModel,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>s.LongT5ForConditionalGeneration,LongT5Model:()=>s.LongT5Model,LongT5PreTrainedModel:()=>s.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>s.M2M100ForConditionalGeneration,M2M100Model:()=>s.M2M100Model,M2M100PreTrainedModel:()=>s.M2M100PreTrainedModel,M2M100Tokenizer:()=>r.M2M100Tokenizer,MBart50Tokenizer:()=>r.MBart50Tokenizer,MBartForCausalLM:()=>s.MBartForCausalLM,MBartForConditionalGeneration:()=>s.MBartForConditionalGeneration,MBartForSequenceClassification:()=>s.MBartForSequenceClassification,MBartModel:()=>s.MBartModel,MBartPreTrainedModel:()=>s.MBartPreTrainedModel,MBartTokenizer:()=>r.MBartTokenizer,MPNetForMaskedLM:()=>s.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>s.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>s.MPNetForSequenceClassification,MPNetForTokenClassification:()=>s.MPNetForTokenClassification,MPNetModel:()=>s.MPNetModel,MPNetPreTrainedModel:()=>s.MPNetPreTrainedModel,MPNetTokenizer:()=>r.MPNetTokenizer,MT5ForConditionalGeneration:()=>s.MT5ForConditionalGeneration,MT5Model:()=>s.MT5Model,MT5PreTrainedModel:()=>s.MT5PreTrainedModel,MarianMTModel:()=>s.MarianMTModel,MarianModel:()=>s.MarianModel,MarianPreTrainedModel:()=>s.MarianPreTrainedModel,MarianTokenizer:()=>r.MarianTokenizer,Mask2FormerImageProcessor:()=>h.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>h.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>s.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>h.MaskFormerImageProcessor,MaskFormerModel:()=>s.MaskFormerModel,MaskFormerPreTrainedModel:()=>s.MaskFormerPreTrainedModel,MaskedLMOutput:()=>s.MaskedLMOutput,MaxLengthCriteria:()=>x.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>s.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>s.MgpstrModelOutput,MgpstrPreTrainedModel:()=>s.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>r.MgpstrTokenizer,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>s.MistralForCausalLM,MistralModel:()=>s.MistralModel,MistralPreTrainedModel:()=>s.MistralPreTrainedModel,MobileBertForMaskedLM:()=>s.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>s.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>s.MobileBertForSequenceClassification,MobileBertModel:()=>s.MobileBertModel,MobileBertPreTrainedModel:()=>s.MobileBertPreTrainedModel,MobileBertTokenizer:()=>r.MobileBertTokenizer,MobileLLMForCausalLM:()=>s.MobileLLMForCausalLM,MobileLLMModel:()=>s.MobileLLMModel,MobileLLMPreTrainedModel:()=>s.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>h.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>s.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>h.MobileNetV1ImageProcessor,MobileNetV1Model:()=>s.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>s.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>h.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>s.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>h.MobileNetV2ImageProcessor,MobileNetV2Model:()=>s.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>s.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>h.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>s.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>h.MobileNetV3ImageProcessor,MobileNetV3Model:()=>s.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>s.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>h.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>s.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>h.MobileNetV4ImageProcessor,MobileNetV4Model:()=>s.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>s.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>h.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>s.MobileViTForImageClassification,MobileViTImageProcessor:()=>h.MobileViTImageProcessor,MobileViTModel:()=>s.MobileViTModel,MobileViTPreTrainedModel:()=>s.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>s.MobileViTV2ForImageClassification,MobileViTV2Model:()=>s.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>s.MobileViTV2PreTrainedModel,ModelOutput:()=>s.ModelOutput,Moondream1ForConditionalGeneration:()=>s.Moondream1ForConditionalGeneration,MptForCausalLM:()=>s.MptForCausalLM,MptModel:()=>s.MptModel,MptPreTrainedModel:()=>s.MptPreTrainedModel,MultiModalityCausalLM:()=>s.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>s.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>s.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>s.MusicgenForConditionalGeneration,MusicgenModel:()=>s.MusicgenModel,MusicgenPreTrainedModel:()=>s.MusicgenPreTrainedModel,NllbTokenizer:()=>r.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>s.NomicBertModel,NomicBertPreTrainedModel:()=>s.NomicBertPreTrainedModel,NougatImageProcessor:()=>h.NougatImageProcessor,NougatTokenizer:()=>r.NougatTokenizer,OPTForCausalLM:()=>s.OPTForCausalLM,OPTModel:()=>s.OPTModel,OPTPreTrainedModel:()=>s.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OlmoForCausalLM:()=>s.OlmoForCausalLM,OlmoModel:()=>s.OlmoModel,OlmoPreTrainedModel:()=>s.OlmoPreTrainedModel,OpenELMForCausalLM:()=>s.OpenELMForCausalLM,OpenELMModel:()=>s.OpenELMModel,OpenELMPreTrainedModel:()=>s.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>h.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>s.OwlViTForObjectDetection,OwlViTImageProcessor:()=>h.OwlViTImageProcessor,OwlViTModel:()=>s.OwlViTModel,OwlViTPreTrainedModel:()=>s.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>s.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>h.Owlv2ImageProcessor,Owlv2Model:()=>s.Owlv2Model,Owlv2PreTrainedModel:()=>s.Owlv2PreTrainedModel,PatchTSMixerForPrediction:()=>s.PatchTSMixerForPrediction,PatchTSMixerModel:()=>s.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>s.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>s.PatchTSTForPrediction,PatchTSTModel:()=>s.PatchTSTModel,PatchTSTPreTrainedModel:()=>s.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>s.Phi3ForCausalLM,Phi3Model:()=>s.Phi3Model,Phi3PreTrainedModel:()=>s.Phi3PreTrainedModel,PhiForCausalLM:()=>s.PhiForCausalLM,PhiModel:()=>s.PhiModel,PhiPreTrainedModel:()=>s.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>s.PreTrainedModel,PreTrainedTokenizer:()=>r.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>s.PretrainedMixin,Processor:()=>g.Processor,PvtForImageClassification:()=>s.PvtForImageClassification,PvtImageProcessor:()=>h.PvtImageProcessor,PvtModel:()=>s.PvtModel,PvtPreTrainedModel:()=>s.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>s.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>s.PyAnnoteModel,PyAnnotePreTrainedModel:()=>s.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>s.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>s.Qwen2ForCausalLM,Qwen2Model:()=>s.Qwen2Model,Qwen2PreTrainedModel:()=>s.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>r.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>s.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>h.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>s.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,RTDetrForObjectDetection:()=>s.RTDetrForObjectDetection,RTDetrImageProcessor:()=>h.RTDetrImageProcessor,RTDetrModel:()=>s.RTDetrModel,RTDetrObjectDetectionOutput:()=>s.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>s.RTDetrPreTrainedModel,RawImage:()=>l.RawImage,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>s.ResNetForImageClassification,ResNetModel:()=>s.ResNetModel,ResNetPreTrainedModel:()=>s.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>s.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>s.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>s.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>s.RoFormerForTokenClassification,RoFormerModel:()=>s.RoFormerModel,RoFormerPreTrainedModel:()=>s.RoFormerPreTrainedModel,RoFormerTokenizer:()=>r.RoFormerTokenizer,RobertaForMaskedLM:()=>s.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>s.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>s.RobertaForSequenceClassification,RobertaForTokenClassification:()=>s.RobertaForTokenClassification,RobertaModel:()=>s.RobertaModel,RobertaPreTrainedModel:()=>s.RobertaPreTrainedModel,RobertaTokenizer:()=>r.RobertaTokenizer,SamImageProcessor:()=>h.SamImageProcessor,SamImageSegmentationOutput:()=>s.SamImageSegmentationOutput,SamModel:()=>s.SamModel,SamPreTrainedModel:()=>s.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>s.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>s.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>s.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>s.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>p.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>h.SegformerFeatureExtractor,SegformerForImageClassification:()=>s.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>s.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>h.SegformerImageProcessor,SegformerModel:()=>s.SegformerModel,SegformerPreTrainedModel:()=>s.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>s.Seq2SeqLMOutput,SequenceClassifierOutput:()=>s.SequenceClassifierOutput,SiglipImageProcessor:()=>h.SiglipImageProcessor,SiglipModel:()=>s.SiglipModel,SiglipPreTrainedModel:()=>s.SiglipPreTrainedModel,SiglipTextModel:()=>s.SiglipTextModel,SiglipTokenizer:()=>r.SiglipTokenizer,SiglipVisionModel:()=>s.SiglipVisionModel,SpeechT5FeatureExtractor:()=>p.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>s.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>s.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>s.SpeechT5HifiGan,SpeechT5Model:()=>s.SpeechT5Model,SpeechT5PreTrainedModel:()=>s.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>r.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>s.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>s.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>s.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>s.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>s.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>r.SqueezeBertTokenizer,StableLmForCausalLM:()=>s.StableLmForCausalLM,StableLmModel:()=>s.StableLmModel,StableLmPreTrainedModel:()=>s.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>s.Starcoder2ForCausalLM,Starcoder2Model:()=>s.Starcoder2Model,Starcoder2PreTrainedModel:()=>s.Starcoder2PreTrainedModel,StoppingCriteria:()=>x.StoppingCriteria,StoppingCriteriaList:()=>x.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>s.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>h.Swin2SRImageProcessor,Swin2SRModel:()=>s.Swin2SRModel,Swin2SRPreTrainedModel:()=>s.Swin2SRPreTrainedModel,SwinForImageClassification:()=>s.SwinForImageClassification,SwinModel:()=>s.SwinModel,SwinPreTrainedModel:()=>s.SwinPreTrainedModel,T5ForConditionalGeneration:()=>s.T5ForConditionalGeneration,T5Model:()=>s.T5Model,T5PreTrainedModel:()=>s.T5PreTrainedModel,T5Tokenizer:()=>r.T5Tokenizer,TableTransformerForObjectDetection:()=>s.TableTransformerForObjectDetection,TableTransformerModel:()=>s.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>s.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>s.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>c.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>b.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>s.TokenClassifierOutput,TokenizerModel:()=>r.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>s.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>s.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>s.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>s.UniSpeechForSequenceClassification,UniSpeechModel:()=>s.UniSpeechModel,UniSpeechPreTrainedModel:()=>s.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>s.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>s.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>s.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>s.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>s.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>h.VLMImageProcessor,ViTFeatureExtractor:()=>h.ViTFeatureExtractor,ViTForImageClassification:()=>s.ViTForImageClassification,ViTImageProcessor:()=>h.ViTImageProcessor,ViTMAEModel:()=>s.ViTMAEModel,ViTMAEPreTrainedModel:()=>s.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>s.ViTMSNForImageClassification,ViTMSNModel:()=>s.ViTMSNModel,ViTMSNPreTrainedModel:()=>s.ViTMSNPreTrainedModel,ViTModel:()=>s.ViTModel,ViTPreTrainedModel:()=>s.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>s.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>s.VitMatteForImageMatting,VitMatteImageProcessor:()=>h.VitMatteImageProcessor,VitMattePreTrainedModel:()=>s.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>s.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>h.VitPoseImageProcessor,VitPosePreTrainedModel:()=>s.VitPosePreTrainedModel,VitsModel:()=>s.VitsModel,VitsModelOutput:()=>s.VitsModelOutput,VitsPreTrainedModel:()=>s.VitsPreTrainedModel,VitsTokenizer:()=>r.VitsTokenizer,Wav2Vec2BertForCTC:()=>s.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>s.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>s.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>s.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>r.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>p.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>s.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>s.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>s.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>s.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>s.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>s.WavLMForAudioFrameClassification,WavLMForCTC:()=>s.WavLMForCTC,WavLMForSequenceClassification:()=>s.WavLMForSequenceClassification,WavLMForXVector:()=>s.WavLMForXVector,WavLMModel:()=>s.WavLMModel,WavLMPreTrainedModel:()=>s.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>p.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>s.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>s.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>p.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>s.WhisperForConditionalGeneration,WhisperModel:()=>s.WhisperModel,WhisperPreTrainedModel:()=>s.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>b.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>r.WhisperTokenizer,XLMForQuestionAnswering:()=>s.XLMForQuestionAnswering,XLMForSequenceClassification:()=>s.XLMForSequenceClassification,XLMForTokenClassification:()=>s.XLMForTokenClassification,XLMModel:()=>s.XLMModel,XLMPreTrainedModel:()=>s.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>s.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>s.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>s.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>s.XLMRobertaForTokenClassification,XLMRobertaModel:()=>s.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>s.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>r.XLMRobertaTokenizer,XLMTokenizer:()=>r.XLMTokenizer,XLMWithLMHeadModel:()=>s.XLMWithLMHeadModel,XVectorOutput:()=>s.XVectorOutput,YolosFeatureExtractor:()=>h.YolosFeatureExtractor,YolosForObjectDetection:()=>s.YolosForObjectDetection,YolosImageProcessor:()=>h.YolosImageProcessor,YolosModel:()=>s.YolosModel,YolosObjectDetectionOutput:()=>s.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>s.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>d.bankers_round,cat:()=>c.cat,cos_sim:()=>d.cos_sim,dot:()=>d.dot,dynamic_time_warping:()=>d.dynamic_time_warping,env:()=>e.env,full:()=>c.full,full_like:()=>c.full_like,getKeyValueShapes:()=>i.getKeyValueShapes,hamming:()=>a.hamming,hanning:()=>a.hanning,interpolate:()=>c.interpolate,interpolate_4d:()=>c.interpolate_4d,interpolate_data:()=>d.interpolate_data,is_chinese_char:()=>r.is_chinese_char,layer_norm:()=>c.layer_norm,load_image:()=>l.load_image,log_softmax:()=>d.log_softmax,magnitude:()=>d.magnitude,matmul:()=>c.matmul,max:()=>d.max,mean:()=>c.mean,mean_pooling:()=>c.mean_pooling,medianFilter:()=>d.medianFilter,mel_filter_bank:()=>a.mel_filter_bank,min:()=>d.min,ones:()=>c.ones,ones_like:()=>c.ones_like,permute:()=>c.permute,permute_data:()=>d.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>c.quantize_embeddings,read_audio:()=>a.read_audio,rfft:()=>c.rfft,round:()=>d.round,softmax:()=>d.softmax,spectrogram:()=>a.spectrogram,stack:()=>c.stack,std_mean:()=>c.std_mean,topk:()=>c.topk,window_function:()=>a.window_function,zeros:()=>c.zeros,zeros_like:()=>c.zeros_like});var e=n(/*! ./env.js */"./src/env.js"),t=n(/*! ./pipelines.js */"./src/pipelines.js"),s=n(/*! ./models.js */"./src/models.js"),r=n(/*! ./tokenizers.js */"./src/tokenizers.js"),i=n(/*! ./configs.js */"./src/configs.js"),a=n(/*! ./utils/audio.js */"./src/utils/audio.js"),l=n(/*! ./utils/image.js */"./src/utils/image.js"),c=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),d=n(/*! ./utils/maths.js */"./src/utils/maths.js"),u=n(/*! ./base/feature_extraction_utils.js */"./src/base/feature_extraction_utils.js"),p=n(/*! ./models/feature_extractors.js */"./src/models/feature_extractors.js"),_=n(/*! ./models/auto/feature_extraction_auto.js */"./src/models/auto/feature_extraction_auto.js"),m=n(/*! ./base/image_processors_utils.js */"./src/base/image_processors_utils.js"),h=n(/*! ./models/image_processors.js */"./src/models/image_processors.js"),f=n(/*! ./models/auto/image_processing_auto.js */"./src/models/auto/image_processing_auto.js"),g=n(/*! ./base/processing_utils.js */"./src/base/processing_utils.js"),w=n(/*! ./models/processors.js */"./src/models/processors.js"),M=n(/*! ./models/auto/processing_auto.js */"./src/models/auto/processing_auto.js"),b=n(/*! ./generation/streamers.js */"./src/generation/streamers.js"),x=n(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),y=n(/*! ./generation/logits_process.js */"./src/generation/logits_process.js")})();var i=exports;for(var a in o)i[a]=o[a];o.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{var e,t,s={fs:e=>{"use strict";e.exports=require("fs")},"onnxruntime-node":e=>{"use strict";e.exports=require("onnxruntime-node")},path:e=>{"use strict";e.exports=require("path")},sharp:e=>{"use strict";e.exports=require("sharp")},url:e=>{"use strict";e.exports=require("url")},"?8b6b":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Environment:()=>Y,Interpreter:()=>K,Template:()=>te,parse:()=>N,tokenize:()=>d});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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",Macro:"Macro",EndMacro:"EndMacro"}),n=Object.freeze({set:r.Set,for:r.For,in:r.In,is:r.Is,if:r.If,else:r.Else,endif:r.EndIf,elif:r.ElseIf,endfor:r.EndFor,and:r.And,or:r.Or,not:r.Not,"not in":r.NotIn,macro:r.Macro,endmacro:r.EndMacro,true:r.BooleanLiteral,false:r.BooleanLiteral,none:r.NullLiteral,True:r.BooleanLiteral,False:r.BooleanLiteral,None:r.NullLiteral}),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=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],c=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const s=[],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 p=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++],s=c.get(e);if(void 0===s)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=s}return t};e:for(;u<d.length;){const e=s.at(-1)?.type;if(void 0===e||e===r.CloseStatement||e===r.CloseExpression){let e="";for(;u<d.length&&("{"!==d[u]||"%"!==d[u+1]&&"{"!==d[u+1]);)e+=d[u++];if(e.length>0){s.push(new o(e,r.Text));continue}}p((e=>/\s/.test(e)));const t=d[u];if("-"===t||"+"===t){const e=s.at(-1)?.type;if(e===r.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case r.Identifier:case r.NumericLiteral:case r.BooleanLiteral:case r.NullLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++u;const e=p(a);s.push(new o(`${t}${e}`,e.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(u,u+e.length)===e){s.push(new o(e,t)),u+=e.length;continue e}}if("'"!==t&&'"'!==t)if(a(t)){const e=p(a);s.push(new o(e,r.NumericLiteral))}else{if(!i(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=p(i),t=Object.hasOwn(n,e)?n[e]:r.Identifier;t===r.In&&s.at(-1)?.type===r.Not?(s.pop(),s.push(new o("not in",r.NotIn))):s.push(new o(e,t))}}else{++u;const e=p((e=>e!==t));s.push(new o(e,r.StringLiteral)),++u}}return s}var u=class{type="Statement"},p=class extends u{constructor(e){super(),this.body=e}type="Program"},_=class extends u{constructor(e,t,s){super(),this.test=e,this.body=t,this.alternate=s}type="If"},m=class extends u{constructor(e,t,s,r){super(),this.loopvar=e,this.iterable=t,this.body=s,this.defaultBlock=r}type="For"},h=class extends u{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},f=class extends u{constructor(e,t,s){super(),this.name=e,this.args=t,this.body=s}type="Macro"},g=class extends u{type="Expression"},w=class extends g{constructor(e,t,s){super(),this.object=e,this.property=t,this.computed=s}type="MemberExpression"},M=class extends g{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},b=class extends g{constructor(e){super(),this.value=e}type="Identifier"},x=class extends g{constructor(e){super(),this.value=e}type="Literal"},y=class extends x{type="NumericLiteral"},k=class extends x{type="StringLiteral"},T=class extends x{type="BooleanLiteral"},v=class extends x{type="NullLiteral"},P=class extends x{type="ArrayLiteral"},F=class extends x{type="TupleLiteral"},C=class extends x{type="ObjectLiteral"},A=class extends g{constructor(e,t,s){super(),this.operator=e,this.left=t,this.right=s}type="BinaryExpression"},S=class extends g{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},E=class extends g{constructor(e,t){super(),this.iterable=e,this.test=t}type="SelectExpression"},I=class extends g{constructor(e,t,s){super(),this.operand=e,this.negate=t,this.test=s}type="TestExpression"},L=class extends g{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},z=class extends g{constructor(e=void 0,t=void 0,s=void 0){super(),this.start=e,this.stop=t,this.step=s}type="SliceExpression"},j=class extends g{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function N(e){const t=new p([]);let s=0;function n(t,r){const n=e[s++];if(!n||n.type!==t)throw new Error(`Parser Error: ${r}. ${n.type} !== ${t}.`);return n}function o(){switch(e[s].type){case r.Text:return new k(n(r.Text,"Expected text token").value);case r.OpenStatement:return function(){let t;switch(n(r.OpenStatement,"Expected opening statement token"),e[s].type){case r.Set:++s,t=l(),n(r.CloseStatement,"Expected closing statement token");break;case r.If:++s,t=c(),n(r.OpenStatement,"Expected {% token"),n(r.EndIf,"Expected endif token"),n(r.CloseStatement,"Expected %} token");break;case r.Macro:++s,t=function(){const e=q();if("Identifier"!==e.type)throw new SyntaxError("Expected identifier following macro statement");const t=D();n(r.CloseStatement,"Expected closing statement token");const s=[];for(;i(r.OpenStatement,r.EndMacro);)s.push(o());return new f(e,t,s)}(),n(r.OpenStatement,"Expected {% token"),n(r.EndMacro,"Expected endmacro token"),n(r.CloseStatement,"Expected %} token");break;case r.For:++s,t=function(){const e=d(!0);if(!(e instanceof b||e instanceof F))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);n(r.In,"Expected `in` keyword following loop variable");const t=u();n(r.CloseStatement,"Expected closing statement token");const l=[];for(;i(r.OpenStatement,r.EndFor)&&i(r.OpenStatement,r.Else);)l.push(o());const c=[];if(a(r.OpenStatement,r.Else))for(++s,++s,n(r.CloseStatement,"Expected closing statement token");i(r.OpenStatement,r.EndFor);)c.push(o());return new m(e,t,l,c)}(),n(r.OpenStatement,"Expected {% token"),n(r.EndFor,"Expected endfor token"),n(r.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[s].type}`)}return t}();case r.OpenExpression:return function(){n(r.OpenExpression,"Expected opening expression token");const e=u();return n(r.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[s].type}`)}}function i(...t){return s+t.length<=e.length&&t.some(((t,r)=>t!==e[s+r].type))}function a(...t){return s+t.length<=e.length&&t.every(((t,r)=>t===e[s+r].type))}function l(){const e=u();if(a(r.Equals)){++s;const t=l();return new h(e,t)}return e}function c(){const t=u();n(r.CloseStatement,"Expected closing statement token");const i=[],l=[];for(;e[s]?.type!==r.OpenStatement||e[s+1]?.type!==r.ElseIf&&e[s+1]?.type!==r.Else&&e[s+1]?.type!==r.EndIf;)i.push(o());if(e[s]?.type===r.OpenStatement&&e[s+1]?.type!==r.EndIf)if(++s,a(r.ElseIf))n(r.ElseIf,"Expected elseif token"),l.push(c());else for(n(r.Else,"Expected else token"),n(r.CloseStatement,"Expected closing statement token");e[s]?.type!==r.OpenStatement||e[s+1]?.type!==r.EndIf;)l.push(o());return new _(t,i,l)}function d(e=!1){const t=e?q:u,n=[t()],o=a(r.Comma);for(;o&&(++s,n.push(t()),a(r.Comma)););return o?new F(n):n[0]}function u(){return function(){const e=g();if(a(r.If)){++s;const t=g();if(a(r.Else)){++s;const r=g();return new _(t,[e],[r])}return new E(e,t)}return e}()}function g(){let t=x();for(;a(r.Or);){const r=e[s];++s;const n=x();t=new A(r,t,n)}return t}function x(){let t=N();for(;a(r.And);){const r=e[s];++s;const n=N();t=new A(r,t,n)}return t}function N(){let t;for(;a(r.Not);){const r=e[s];++s;const n=N();t=new L(r,n)}return t??function(){let t=O();for(;a(r.ComparisonBinaryOperator)||a(r.In)||a(r.NotIn);){const r=e[s];++s;const n=O();t=new A(r,t,n)}return t}()}function O(){let t=G();for(;a(r.AdditiveBinaryOperator);){const r=e[s];++s;const n=G();t=new A(r,t,n)}return t}function B(){const t=function(){let t=q();for(;a(r.Dot)||a(r.OpenSquareBracket);){const o=e[s];let i;++s;const a=o.type!==r.Dot;if(a)i=R(),n(r.CloseSquareBracket,"Expected closing square bracket");else if(i=q(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");t=new w(t,i,a)}return t}();return a(r.OpenParen)?V(t):t}function V(e){let t=new M(e,D());return a(r.OpenParen)&&(t=V(t)),t}function D(){n(r.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!a(r.CloseParen);){let t=u();if(a(r.Equals)){if(++s,!(t instanceof b))throw new SyntaxError("Expected identifier for keyword argument");const e=u();t=new j(t,e)}e.push(t),a(r.Comma)&&++s}return e}();return n(r.CloseParen,"Expected closing parenthesis for arguments list"),e}function R(){const e=[];let t=!1;for(;!a(r.CloseSquareBracket);)a(r.Colon)?(e.push(void 0),++s,t=!0):(e.push(u()),a(r.Colon)&&(++s,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 z(...e)}return e[0]}function G(){let t=$();for(;a(r.MultiplicativeBinaryOperator);){const r=e[s];++s;const n=$();t=new A(r,t,n)}return t}function $(){let e=function(){let e=B();for(;a(r.Pipe);){++s;let t=q();if(!(t instanceof b))throw new SyntaxError("Expected identifier for the filter");a(r.OpenParen)&&(t=V(t)),e=new S(e,t)}return e}();for(;a(r.Is);){++s;const t=a(r.Not);t&&++s;let n=q();if(n instanceof T?n=new b(n.value.toString()):n instanceof v&&(n=new b("none")),!(n instanceof b))throw new SyntaxError("Expected identifier for the test");e=new I(e,t,n)}return e}function q(){const t=e[s];switch(t.type){case r.NumericLiteral:return++s,new y(Number(t.value));case r.StringLiteral:return++s,new k(t.value);case r.BooleanLiteral:return++s,new T("true"===t.value.toLowerCase());case r.NullLiteral:return++s,new v(null);case r.Identifier:return++s,new b(t.value);case r.OpenParen:{++s;const t=d();if(e[s].type!==r.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[s].type} instead`);return++s,t}case r.OpenSquareBracket:{++s;const e=[];for(;!a(r.CloseSquareBracket);)e.push(u()),a(r.Comma)&&++s;return++s,new P(e)}case r.OpenCurlyBracket:{++s;const e=new Map;for(;!a(r.CloseCurlyBracket);){const t=u();n(r.Colon,"Expected colon between key and value in object literal");const o=u();e.set(t,o),a(r.Comma)&&++s}return++s,new C(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;s<e.length;)t.body.push(o());return t}function O(e,t,s=1){void 0===t&&(t=e,e=0);const r=[];for(let n=e;n<t;n+=s)r.push(n);return r}function B(e,t,s,r=1){const n=Math.sign(r);n>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),s=(s??=e.length)<0?Math.max(e.length+s,0):Math.min(s,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),s=(s??=-1)<-1?Math.max(e.length+s,-1):Math.min(s,e.length-1));const o=[];for(let i=t;n*i<n*s;i+=r)o.push(e[i]);return o}function V(e){return e.replace(/\b\w/g,(e=>e.toUpperCase()))}var D=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new $(!!this.value)}},R=class extends D{type="NumericValue"},G=class extends D{type="StringValue";builtins=new Map([["upper",new Q((()=>new G(this.value.toUpperCase())))],["lower",new Q((()=>new G(this.value.toLowerCase())))],["strip",new Q((()=>new G(this.value.trim())))],["title",new Q((()=>new G(V(this.value))))],["length",new R(this.value.length)],["rstrip",new Q((()=>new G(this.value.trimEnd())))],["lstrip",new Q((()=>new G(this.value.trimStart())))]])},$=class extends D{type="BooleanValue"},q=class extends D{type="ObjectValue";__bool__(){return new $(this.value.size>0)}builtins=new Map([["get",new Q((([e,t])=>{if(!(e instanceof G))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new H}))],["items",new Q((()=>new W(Array.from(this.value.entries()).map((([e,t])=>new W([new G(e),t]))))))]])},U=class extends q{type="KeywordArgumentsValue"},W=class extends D{type="ArrayValue";builtins=new Map([["length",new R(this.value.length)]]);__bool__(){return new $(this.value.length>0)}},X=class extends W{type="TupleValue"},Q=class extends D{type="FunctionValue"},H=class extends D{type="NullValue"},J=class extends D{type="UndefinedValue"},Y=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Q((e=>{if(0===e.length)return new q(new Map);if(1!==e.length||!(e[0]instanceof q))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 Q],["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],["none",e=>"NullValue"===e.type],["string",e=>"StringValue"===e.type],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>"ArrayValue"===e.type||"StringValue"===e.type],["mapping",e=>"ObjectValue"===e.type],["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],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Z(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 J}catch{return new J}}},K=class{global;constructor(e){this.global=e??new Y}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const s=this.evaluate(e.left,t);switch(e.operator.value){case"and":return s.__bool__().value?this.evaluate(e.right,t):s;case"or":return s.__bool__().value?s:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new $(s.value==r.value);case"!=":return new $(s.value!=r.value)}if(s instanceof J||r instanceof J)throw new Error("Cannot perform operation on undefined values");if(s instanceof H||r instanceof H)throw new Error("Cannot perform operation on null values");if(s instanceof R&&r instanceof R)switch(e.operator.value){case"+":return new R(s.value+r.value);case"-":return new R(s.value-r.value);case"*":return new R(s.value*r.value);case"/":return new R(s.value/r.value);case"%":return new R(s.value%r.value);case"<":return new $(s.value<r.value);case">":return new $(s.value>r.value);case">=":return new $(s.value>=r.value);case"<=":return new $(s.value<=r.value)}else if(s instanceof W&&r instanceof W){if("+"===e.operator.value)return new W(s.value.concat(r.value))}else if(r instanceof W){const t=void 0!==r.value.find((e=>e.value===s.value));switch(e.operator.value){case"in":return new $(t);case"not in":return new $(!t)}}if((s instanceof G||r instanceof G)&&"+"===e.operator.value)return new G(s.value.toString()+r.value.toString());if(s instanceof G&&r instanceof G)switch(e.operator.value){case"in":return new $(r.value.includes(s.value));case"not in":return new $(!r.value.includes(s.value))}if(s instanceof G&&r instanceof q)switch(e.operator.value){case"in":return new $(r.value.has(s.value));case"not in":return new $(!r.value.has(s.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${s.type} and ${r.type}`)}evaluateArguments(e,t){const s=[],r=new Map;for(const n of e)if("KeywordArgumentExpression"===n.type){const e=n;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");s.push(this.evaluate(n,t))}return[s,r]}evaluateFilterExpression(e,t){const s=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if("tojson"===t.value)return new G(ee(s));if(s instanceof W)switch(t.value){case"list":return s;case"first":return s.value[0];case"last":return s.value[s.value.length-1];case"length":return new R(s.value.length);case"reverse":return new W(s.value.reverse());case"sort":return new W(s.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(s instanceof G)switch(t.value){case"length":return new R(s.value.length);case"upper":return new G(s.value.toUpperCase());case"lower":return new G(s.value.toLowerCase());case"title":return new G(V(s.value));case"capitalize":return new G(s.value.charAt(0).toUpperCase()+s.value.slice(1));case"trim":return new G(s.value.trim());case"indent":return new G(s.value.split("\n").map(((e,t)=>0===t||0===e.length?e:" "+e)).join("\n"));case"string":return s;default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(s instanceof R){if("abs"===t.value)return new R(Math.abs(s.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(s instanceof q)switch(t.value){case"items":return new W(Array.from(s.value.entries()).map((([e,t])=>new W([new G(e),t]))));case"length":return new R(s.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${s.type}`)}if("CallExpression"===e.filter.type){const r=e.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const n=r.callee.value;if("tojson"===n){const[,e]=this.evaluateArguments(r.args,t),n=e.get("indent")??new H;if(!(n instanceof R||n instanceof H))throw new Error("If set, indent must be a number");return new G(ee(s,n.value))}if(s instanceof W){switch(n){case"selectattr":case"rejectattr":{const e="selectattr"===n;if(s.value.some((e=>!(e instanceof q))))throw new Error(`\`${n}\` can only be applied to array of objects`);if(r.args.some((e=>"StringLiteral"!==e.type)))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,a]=r.args.map((e=>this.evaluate(e,t)));let l;if(i){const e=t.tests.get(i.value);if(!e)throw new Error(`Unknown test: ${i.value}`);l=e}else l=(...e)=>e[0].__bool__().value;const c=s.value.filter((t=>{const s=t.value.get(o.value),r=!!s&&l(s,a);return e?r:!r}));return new W(c)}case"map":{const[,e]=this.evaluateArguments(r.args,t);if(e.has("attribute")){const t=e.get("attribute");if(!(t instanceof G))throw new Error("attribute must be a string");const r=e.get("default"),n=s.value.map((e=>{if(!(e instanceof q))throw new Error("items in map must be an object");return e.value.get(t.value)??r??new J}));return new W(n)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}if(s instanceof G){if("indent"===n){const[e,n]=this.evaluateArguments(r.args,t),o=e.at(0)??n.get("width")??new R(4);if(!(o instanceof R))throw new Error("width must be a number");const i=e.at(1)??n.get("first")??new $(!1),a=e.at(2)??n.get("blank")??new $(!1),l=s.value.split("\n"),c=" ".repeat(o.value),d=l.map(((e,t)=>!i.value&&0===t||!a.value&&0===e.length?e:c+e));return new G(d.join("\n"))}throw new Error(`Unknown StringValue filter: ${n}`)}throw new Error(`Cannot apply filter "${n}" to type: ${s.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const s=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const n=r(s);return new $(e.negate?!n:n)}evaluateUnaryExpression(e,t){const s=this.evaluate(e.argument,t);if("not"===e.operator.value)return new $(!s.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let s="";for(const r of e){const e=this.evaluate(r,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(s+=e.value)}return new G(s)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[s,r]=this.evaluateArguments(e.args,t);r.size>0&&s.push(new U(r));const n=this.evaluate(e.callee,t);if("FunctionValue"!==n.type)throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(s,t)}evaluateSliceExpression(e,t,s){if(!(e instanceof W||e instanceof G))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,s),n=this.evaluate(t.stop,s),o=this.evaluate(t.step,s);if(!(r instanceof R||r instanceof J))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof R||n instanceof J))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof R||o instanceof J))throw new Error("Slice step must be numeric or undefined");return e instanceof W?new W(B(e.value,r.value,n.value,o.value)):new G(B(Array.from(e.value),r.value,n.value,o.value).join(""))}evaluateMemberExpression(e,t){const s=this.evaluate(e.object,t);let r,n;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(s,e.property,t);r=this.evaluate(e.property,t)}else r=new G(e.property.value);if(s instanceof q){if(!(r instanceof G))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.value.get(r.value)??s.builtins.get(r.value)}else if(s instanceof W||s instanceof G)if(r instanceof R)n=s.value.at(r.value),s instanceof G&&(n=new G(s.value.at(r.value)));else{if(!(r instanceof G))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);n=s.builtins.get(r.value)}else{if(!(r instanceof G))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.builtins.get(r.value)}return n instanceof D?n:new J}evaluateSet(e,t){const s=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const r=e.assignee.value;t.setVariable(r,s)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const r=e.assignee,n=this.evaluate(r.object,t);if(!(n instanceof q))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");n.value.set(r.property.value,s)}}return new H}evaluateIf(e,t){const s=this.evaluate(e.test,t);return this.evaluateBlock(s.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const s=new Y(t);let r,n;if("SelectExpression"===e.iterable.type){const t=e.iterable;n=this.evaluate(t.iterable,s),r=t.test}else n=this.evaluate(e.iterable,s);if(!(n instanceof W))throw new Error(`Expected iterable type in for loop: got ${n.type}`);const o=[],i=[];for(let t=0;t<n.value.length;++t){const a=new Y(s),l=n.value[t];let c;if("Identifier"===e.loopvar.type)c=t=>t.setVariable(e.loopvar.value,l);else{if("TupleLiteral"!==e.loopvar.type)throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);{const t=e.loopvar;if("ArrayValue"!==l.type)throw new Error(`Cannot unpack non-iterable type: ${l.type}`);const s=l;if(t.value.length!==s.value.length)throw new Error(`Too ${t.value.length>s.value.length?"few":"many"} items to unpack`);c=e=>{for(let r=0;r<t.value.length;++r){if("Identifier"!==t.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,s.value[r])}}}}if(r){c(a);if(!this.evaluate(r,a).__bool__().value)continue}o.push(l),i.push(c)}let a="",l=!0;for(let t=0;t<o.length;++t){const r=new Map([["index",new R(t+1)],["index0",new R(t)],["revindex",new R(o.length-t)],["revindex0",new R(o.length-t-1)],["first",new $(0===t)],["last",new $(t===o.length-1)],["length",new R(o.length)],["previtem",t>0?o[t-1]:new J],["nextitem",t<o.length-1?o[t+1]:new J]]);s.setVariable("loop",new q(r)),i[t](s);a+=this.evaluateBlock(e.body,s).value,l=!1}if(l){a+=this.evaluateBlock(e.defaultBlock,s).value}return new G(a)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Q(((t,s)=>{const r=new Y(s);let n;t=t.slice(),"KeywordArgumentsValue"===t.at(-1)?.type&&(n=t.pop());for(let s=0;s<e.args.length;++s){const o=e.args[s],i=t[s];if("Identifier"===o.type){const e=o;if(!i)throw new Error(`Missing positional argument: ${e.value}`);r.setVariable(e.value,i)}else{if("KeywordArgumentExpression"!==o.type)throw new Error(`Unknown argument type: ${o.type}`);{const e=o,t=i??n?.value.get(e.key.value)??this.evaluate(e.value,r);r.setVariable(e.key.value,t)}}}return this.evaluateBlock(e.body,r)}))),new H}evaluate(e,t){if(void 0===e)return new J;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"NumericLiteral":return new R(Number(e.value));case"StringLiteral":return new G(e.value);case"BooleanLiteral":return new $(e.value);case"NullLiteral":return new H(e.value);case"ArrayLiteral":return new W(e.value.map((e=>this.evaluate(e,t))));case"TupleLiteral":return new X(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const s=new Map;for(const[r,n]of e.value){const e=this.evaluate(r,t);if(!(e instanceof G))throw new Error(`Object keys must be strings: got ${e.type}`);s.set(e.value,this.evaluate(n,t))}return new q(s)}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 Z(e){switch(typeof e){case"number":return new R(e);case"string":return new G(e);case"boolean":return new $(e);case"undefined":return new J;case"object":return null===e?new H:Array.isArray(e)?new W(e.map(Z)):new q(new Map(Object.entries(e).map((([e,t])=>[e,Z(t)]))));case"function":return new Q(((t,s)=>Z(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function ee(e,t,s){const r=s??0;switch(e.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(e.value);case"ArrayValue":case"ObjectValue":{const s=t?" ".repeat(t):"",n="\n"+s.repeat(r),o=n+s;if("ArrayValue"===e.type){const s=e.value.map((e=>ee(e,t,r+1)));return t?`[${o}${s.join(`,${o}`)}${n}]`:`[${s.join(", ")}]`}{const s=Array.from(e.value.entries()).map((([e,s])=>{const n=`"${e}": ${ee(s,t,r+1)}`;return t?`${o}${n}`:n}));return t?`{${s.join(",")}${n}}`:`{${s.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var te=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(t)}render(e){const t=new Y;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",O);for(const[s,r]of Object.entries(e))t.set(s,r);return new K(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{registerBackend:()=>o,resolveBackendAndExecutionProviders:()=>a});const r=new Map,n=[],o=(e,t,s)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{const o=r.get(e);if(void 0===o)r.set(e,{backend:t,priority:s});else{if(o.priority>s)return;if(o.priority===s&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){const t=n.indexOf(e);-1!==t&&n.splice(t,1);for(let t=0;t<n.length;t++)if(r.get(n[t]).priority<=s)return void n.splice(t,0,e);n.push(e)}}},i=async e=>{const t=r.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{const s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return s||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},a=async e=>{const t=e.executionProviders||[],s=t.map((e=>"string"==typeof e?e:e.name)),r=0===s.length?n:s;let o;const a=[],l=new Set;for(const e of r){const t=await i(e);"string"==typeof t?a.push({name:e,err:t}):(o||(o=t),o===t&&l.add(e))}if(!o)throw new Error(`no available backend found. ERR: ${a.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(const{name:e,err:t}of a)s.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);const c=t.filter((e=>l.has("string"==typeof e?e:e.name)));return[o,new Proxy(e,{get:(e,t)=>"executionProviders"===t?c:Reflect.get(e,t)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{registerBackend:()=>r.registerBackend});var r=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{env:()=>o});var r=s("./node_modules/onnxruntime-common/dist/esm/version.js");let n="warning";const o={wasm:{},webgl:{},webgpu:{},versions:{common:r.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}`);n=e}},get logLevel(){return n}};Object.defineProperty(o,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{env:()=>r});const r=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js").env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,s)=>{"use strict";s.r(t),s.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:()=>n.env,registerBackend:()=>r.registerBackend});var r=s("./node_modules/onnxruntime-common/dist/esm/backend.js"),n=s("./node_modules/onnxruntime-common/dist/esm/env.js"),o=s("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),i=s("./node_modules/onnxruntime-common/dist/esm/tensor.js"),a=(s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),s("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js"),s("./node_modules/onnxruntime-common/dist/esm/trace.js")),l=(s("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),s("./node_modules/onnxruntime-common/dist/esm/onnx-value.js"),s("./node_modules/onnxruntime-common/dist/esm/training-session.js"))},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{InferenceSession:()=>i});var r=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),n=s("./node_modules/onnxruntime-common/dist/esm/tensor.js"),o=s("./node_modules/onnxruntime-common/dist/esm/trace.js");class i{constructor(e){this.handler=e}async run(e,t,s){(0,o.TRACE_FUNC_BEGIN)();const r={};let i={};if("object"!=typeof e||null===e||e instanceof n.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 n.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}.`);r[e]=null}if("object"==typeof s&&null!==s)i=s;else if(void 0!==s)throw new TypeError("'options' must be an object.")}else{let e=!1;const o=Object.getOwnPropertyNames(t);for(const s of this.outputNames)if(-1!==o.indexOf(s)){const o=t[s];(null===o||o instanceof n.Tensor)&&(e=!0,a=!1,r[s]=o)}if(e){if("object"==typeof s&&null!==s)i=s;else if(void 0!==s)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)r[e]=null;const l=await this.handler.run(e,r,i),c={};for(const e in l)if(Object.hasOwnProperty.call(l,e)){const t=l[e];t instanceof n.Tensor?c[e]=t:c[e]=new n.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,s,n){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 r=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>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(i=e.byteLength-o,"number"==typeof s){if(i=s,!Number.isSafeInteger(i))throw new RangeError("'byteLength' must be an integer.");if(i<=0||o+i>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-o}].`);if("object"==typeof n&&null!==n)l=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else if(void 0!==s)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");a=new Uint8Array(r,o,i)}}const[c,d]=await(0,r.resolveBackendAndExecutionProviders)(l),u=await c.createInferenceSessionHandler(a,d);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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{InferenceSession:()=>r});const r=s("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js").InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{tensorToDataURL:()=>r,tensorToImageData:()=>n});const r=(e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];const r=s.getContext("2d");if(null!=r){let n,o;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(n=e.dims[2],o=e.dims[3]):(n=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*n;let u=0,p=d,_=2*d,m=-1;"RGBA"===i?(u=0,p=d,_=2*d,m=3*d):"RGB"===i?(u=0,p=d,_=2*d):"RBG"===i&&(u=0,_=d,p=2*d);for(let t=0;t<o;t++)for(let s=0;s<n;s++){const n=(e.data[u++]-c[0])*l[0],o=(e.data[p++]-c[1])*l[1],i=(e.data[_++]-c[2])*l[2],a=-1===m?255:(e.data[m++]-c[3])*l[3];r.fillStyle="rgba("+n+","+o+","+i+","+a+")",r.fillRect(s,t,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},n=(e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(null==s)throw new Error("Can not access image data");{let n,o,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=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*n;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 p=4;let _=0,m=1,h=2,f=3,g=0,w=u,M=2*u,b=-1;"RGBA"===a?(g=0,w=u,M=2*u,b=3*u):"RGB"===a?(g=0,w=u,M=2*u):"RBG"===a&&(g=0,M=u,w=2*u),r=s.createImageData(n,o);for(let t=0;t<o*n;_+=p,m+=p,h+=p,f+=p,t++)r.data[_]=(e.data[g++]-d[0])*c[0],r.data[m]=(e.data[w++]-d[1])*c[1],r.data[h]=(e.data[M++]-d[2])*c[2],r.data[f]=-1===b?255:(e.data[b++]-d[3])*c[3]}return r}},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js":(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{bufferToTensor:()=>n,tensorFromGpuBuffer:()=>a,tensorFromImage:()=>o,tensorFromMLTensor:()=>l,tensorFromPinnedBuffer:()=>c,tensorFromTexture:()=>i});var r=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const n=(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:s,width:n}=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=s*n,u="RGBA"===c?new Float32Array(4*d):new Float32Array(3*d);let p=4,_=0,m=1,h=2,f=3,g=0,w=d,M=2*d,b=-1;"RGB"===l&&(p=3,_=0,m=1,h=2,f=-1),"RGBA"===c?b=3*d:"RBG"===c?(g=0,M=d,w=2*d):"BGR"===c&&(M=0,w=d,g=2*d);for(let t=0;t<d;t++,_+=p,h+=p,m+=p,f+=p)u[g++]=(e[_]+a[0])/i[0],u[w++]=(e[m]+a[1])/i[1],u[M++]=(e[h]+a[2])/i[2],-1!==b&&-1!==f&&(u[b++]=(e[f]+a[3])/i[3]);return"RGBA"===c?new r.Tensor("float32",u,[1,4,s,n]):new r.Tensor("float32",u,[1,3,s,n])},o=async(e,t)=>{const s="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,r="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=>"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(s){const s=c();s.width=e.width,s.height=e.height;const r=d(s);if(null==r)throw new Error("Can not access image data");{let s=e.height,n=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(s=t.resizedHeight,n=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=s,l.width=n}else l.tensorFormat="RGBA",l.height=s,l.width=n;r.drawImage(e,0,0),a=r.getImageData(0,0,n,s).data}}else{if(!r){if(o){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");const s=c();s.width=e.width,s.height=e.height;const r=d(s);if(null!=r){const t=e.height,s=e.width;return r.drawImage(e,0,0,s,t),a=r.getImageData(0,0,s,t).data,l.height=t,l.width=s,n(a,l)}throw new Error("Can not access image data")}if(i)return new Promise(((t,s)=>{const r=c(),o=d(r);if(!e||!o)return s();const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>{r.width=i.width,r.height=i.height,o.drawImage(i,0,0,r.width,r.height);const e=o.getImageData(0,0,r.width,r.height);l.height=r.height,l.width=r.width,t(n(e.data,l))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let s,r;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(s=t.resizedHeight,r=t.resizedWidth):(s=e.height,r=e.width),void 0!==t&&(l=t),l.format="RGBA",l.height=s,l.width=r,void 0!==t){const t=c();t.width=r,t.height=s;const n=d(t);if(null==n)throw new Error("Can not access image data");n.putImageData(e,0,0),a=n.getImageData(0,0,r,s).data}else a=e.data}}if(void 0!==a)return n(a,l);throw new Error("Input data provided is not supported - aborted tensor creation")},i=(e,t)=>{const{width:s,height:n,download:o,dispose:i}=t,a=[1,n,s,4];return new r.Tensor({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},a=(e,t)=>{const{dataType:s,dims:n,download:o,dispose:i}=t;return new r.Tensor({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},l=(e,t)=>{const{dataType:s,dims:n,download:o,dispose:i}=t;return new r.Tensor({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:i})},c=(e,t,s)=>new r.Tensor({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,s)=>{"use strict";s.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>n,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>r,checkTypedArray:()=>i});const r=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),n=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&&BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&BigUint64Array.from,s="undefined"!=typeof Float16Array&&Float16Array.from;e&&(r.set("int64",BigInt64Array),n.set(BigInt64Array,"int64")),t&&(r.set("uint64",BigUint64Array),n.set(BigUint64Array,"uint64")),s?(r.set("float16",Float16Array),n.set(Float16Array,"float16")):r.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>a});var r=s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),n=s("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),o=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),i=s("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class a{constructor(e,t,s){let r,n;if((0,o.checkTypedArray)(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,n=e.dims,e.location){case"cpu-pinned":{const t=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(r);if(!t)throw new TypeError(`unsupported type "${r}" 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"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint64"!==r&&"int8"!==r&&"uint8"!==r&&"bool"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,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(r=e,a=s,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{const s=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(void 0===s)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&s===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);i="uint64"===e||"int64"===e?s.from(t,BigInt):s.from(t)}else if(t instanceof s)i=t;else{if(!(t instanceof Uint8ClampedArray))throw new TypeError(`A ${r} tensor's data must be type of ${s}`);if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");i=Uint8Array.from(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)r="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",i=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)r="uint8",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}.`);r=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");n=a,this.cpuData=i,this.dataLocation="cpu"}const a=(0,i.calculateSize)(n);if(this.cpuData&&a!==this.cpuData.length&&("uint4"!==r&&"int4"!==r||Math.ceil(a/2)!==this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=n,this.size=a}static async fromImage(e,t){return(0,n.tensorFromImage)(e,t)}static fromTexture(e,t){return(0,n.tensorFromTexture)(e,t)}static fromGpuBuffer(e,t){return(0,n.tensorFromGpuBuffer)(e,t)}static fromMLTensor(e,t){return(0,n.tensorFromMLTensor)(e,t)}static fromPinnedBuffer(e,t,s){return(0,n.tensorFromPinnedBuffer)(e,t,s)}toDataURL(e){return(0,r.tensorToDataURL)(this,e)}toImageData(e){return(0,r.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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":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.mlTensorData=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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{calculateSize:()=>n,tensorReshape:()=>o});var r=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const n=e=>{let t=1;for(let s=0;s<e.length;s++){const r=e[s];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${s}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${r}`);t*=r}return t},o=(e,t)=>{switch(e.location){case"cpu":return new r.Tensor(e.type,e.data,t);case"cpu-pinned":return new r.Tensor({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new r.Tensor({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new r.Tensor({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new r.Tensor({location:"ml-tensor",mlTensor:e.mlTensor,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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>r});const r=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js").Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{TRACE:()=>n,TRACE_FUNC_BEGIN:()=>i,TRACE_FUNC_END:()=>a});var r=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const n=(e,t)=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&console.timeStamp(`${e}::ORT::${t}`)},o=(e,t)=>{const s=(new Error).stack?.split(/\r\n|\r|\n/g)||[];let r=!1;for(let o=0;o<s.length;o++){if(r&&!s[o].includes("TRACE_FUNC")){let r=`FUNC_${e}::${s[o].trim().split(" ")[1]}`;return t&&(r+=`::${t}`),void n("CPU",r)}s[o].includes("TRACE_FUNC")&&(r=!0)}},i=e=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&o("BEGIN",e)},a=e=>{(void 0===r.env.trace?r.env.wasm.trace:r.env.trace)&&o("END",e)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{TrainingSession:()=>o});var r=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),n=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");class o{constructor(e,t,s){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=s}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 s=e.evalModel||"",n=e.optimizerModel||"",i=t||{},[a,l]=await(0,r.resolveBackendAndExecutionProviders)(i);if(a.createTrainingSessionHandler){const t=await a.createTrainingSessionHandler(e.checkpointState,e.trainModel,s,n,l);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,s,r,o){const i={};let a={};if("object"!=typeof s||null===s||s instanceof n.Tensor||Array.isArray(s))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 r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof n.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const e of r){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 s=Object.getOwnPropertyNames(r);for(const o of t)if(-1!==s.indexOf(o)){const t=r[o];(null===t||t instanceof n.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=r}}else if(void 0!==r)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of e)if(void 0===s[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 s in e)if(Object.hasOwnProperty.call(e,s)){const r=e[s];r instanceof n.Tensor?t[s]=r:t[s]=new n.Tensor(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,s){const[r,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,s),o=await this.handler.runTrainStep(e,r,n);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,s){if(this.hasEvalModel){const[r,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,s),o=await this.handler.runEvalStep(e,r,n);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 s=await this.getParametersSize(t);if(e.length!==4*s)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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{TrainingSession:()=>r});const r=s("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js").TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{version:()=>r});const r="1.20.1"},"./src/backends/onnx.js":(e,t,s)=>{"use strict";var r,n;s.r(t),s.d(t,{Tensor:()=>l.Tensor,createInferenceSession:()=>g,deviceToExecutionProviders:()=>h,isONNXProxy:()=>b,isONNXTensor:()=>w});var o=s("./src/env.js"),i=s("onnxruntime-node"),a=s("?8b6b"),l=s("./node_modules/onnxruntime-common/dist/esm/index.js");const c=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),d=[];let u,p;const _=Symbol.for("onnxruntime");if(_ in globalThis)p=globalThis[_];else if(o.apis.IS_NODE_ENV){switch(p=i??(r||(r=s.t(i,2))),process.platform){case"win32":d.push("dml");break;case"linux":"x64"===process.arch&&d.push("cuda")}d.push("cpu"),u=["cpu"]}else p=n||(n=s.t(a,2)),o.apis.IS_WEBNN_AVAILABLE&&d.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&d.push("webgpu"),d.push("wasm"),u=["wasm"];const m=p.InferenceSession;function h(e=null){if(!e)return u;switch(e){case"auto":return d;case"gpu":return d.filter((e=>["webgpu","cuda","dml","webnn-gpu"].includes(e)))}if(d.includes(e))return[c[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${d.join(", ")}.`)}let f=null;async function g(e,t,s){f&&await f;const r=m.create(e,t);f??=r;const n=await r;return n.config=s,n}function w(e){return e instanceof p.Tensor}const M=p?.env;function b(){return M?.wasm?.proxy}M?.wasm&&(M.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`,M.wasm.proxy=!1,"undefined"!=typeof crossOriginIsolated&&crossOriginIsolated||(M.wasm.numThreads=1)),M?.webgpu&&(M.webgpu.powerPreference="high-performance"),o.env.backends.onnx=M},"./src/base/feature_extraction_utils.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var r=s("./src/utils/constants.js"),n=s("./src/utils/generic.js"),o=s("./src/utils/hub.js");class i extends n.Callable{constructor(e){super(),this.config=e}static async from_pretrained(e,t){return new this(await(0,o.getModelJSON)(e,r.FEATURE_EXTRACTOR_NAME,!0,t))}}function a(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.`)}},"./src/base/image_processors_utils.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ImageProcessor:()=>M,post_process_instance_segmentation:()=>w,post_process_object_detection:()=>p,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});var r=s("./src/utils/generic.js"),n=s("./src/utils/tensor.js"),o=s("./src/utils/maths.js"),i=(s("./src/utils/image.js"),s("./src/utils/core.js")),a=s("./src/utils/hub.js"),l=s("./src/utils/constants.js");function c(e,t,s=0,r=null){const n=e/t;let i=(0,o.bankers_round)(n)*t;return null!==r&&i>r&&(i=Math.floor(n)*t),i<s&&(i=Math.ceil(n)*t),i}function d([e,t],s){return[Math.max(Math.floor(e/s),1)*s,Math.max(Math.floor(t/s),1)*s]}function u([e,t,s,r]){return[e-s/2,t-r/2,e+s/2,t+r/2]}function p(e,t=.5,s=null,r=!1){const n=e.logits,i=e.pred_boxes,[a,l,c]=n.dims;if(null!==s&&s.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let d=[];for(let e=0;e<a;++e){let a=null!==s?s[e]:null,p={boxes:[],classes:[],scores:[]},_=n[e],m=i[e];for(let e=0;e<l;++e){let s,n=_[e],i=[];if(r){s=n.sigmoid().data;for(let e=0;e<s.length;++e)s[e]>t&&i.push(e)}else{let e=(0,o.max)(n.data)[1];if(e===c-1)continue;if(s=(0,o.softmax)(n.data),s[e]<t)continue;i.push(e)}for(const t of i){let r=m[e].data;r=u(r),null!==a&&(r=r.map(((e,t)=>e*a[(t+1)%2]))),p.boxes.push(r),p.classes.push(t),p.scores.push(s[t])}}d.push(p)}return d}function _(e,t=null){const s=e.logits,r=s.dims[0];if(null!==t&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const o=[];for(let e=0;e<r;++e){const r=null!==t?t[e]:null;let i=s[e];null!==r&&(i=(0,n.interpolate)(i,r,"bilinear",!1));const[a,l]=r??i.dims.slice(-2),c=new n.Tensor("int32",new Int32Array(a*l),[a,l]),d=i[0].data,u=c.data;for(let e=1;e<i.dims[0];++e){const t=i[e].data;for(let s=0;s<t.length;++s)t[s]>d[s]&&(d[s]=t[s],u[s]=e)}const p=new Array(i.dims[0]);for(let e=0;e<u.length;++e){const t=u[e];p[t]=t}const _=p.filter((e=>void 0!==e));o.push({segmentation:c,labels:_})}return o}function m(e,t,s,r){const n=[],i=[],a=[];for(let l=0;l<e.dims[0];++l){const c=e[l],d=t[l],u=(0,o.max)(c.data)[1];if(u===r)continue;const p=(0,o.softmax)(c.data)[u];p>s&&(n.push(d),i.push(p),a.push(u))}return[n,i,a]}function h(e,t,s,r=.5,n=.8){const o=[];let i=0,a=0;const l=t[s].data;for(let t=0;t<e.length;++t)e[t]===s&&(o.push(t),++i),l[t]>=r&&++a;let c=i>0&&a>0;if(c){c=i/a>n}return[c,o]}function f(e,t,s,r,o,i=null,a=null){const[l,c]=a??e[0].dims,d=new n.Tensor("int32",new Int32Array(l*c),[l,c]),u=[];if(null!==a)for(let t=0;t<e.length;++t)e[t]=(0,n.interpolate)(e[t],a,"bilinear",!1);const p=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let s=0;s<e.length;++s){let r=t[s];const n=e[s].data;for(let e=0;e<n.length;++e)n[e]*=r,n[e]>_[e]&&(p[e]=s,_[e]=n[e])}let m=0;const f=d.data;for(let n=0;n<s.length;++n){const i=s[n],[a,l]=h(p,e,n,r,o);if(a){++m;for(const e of l)f[e]=m;u.push({id:m,label_id:i,score:t[n]})}}return[d,u]}function g(e,t=.5,s=.5,r=.8,o=null,i=null){null===o&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),o=new Set);const a=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,u]=a.dims;if(u-=1,null!==i&&i.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let p=[];for(let e=0;e<c;++e){let c=null!==i?i[e]:null,d=a[e],_=l[e],[h,g,w]=m(d,_,t,u);if(0===w.length){let[e,t]=c??_.dims.slice(-2),s=new n.Tensor("int32",new Int32Array(e*t).fill(-1),[e,t]);p.push({segmentation:s,segments_info:[]});continue}let[M,b]=f(h,g,w,s,r,o,c);p.push({segmentation:M,segments_info:b})}return p}function w(e,t=.5,s=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}class M extends r.Callable{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??void 0!==this.size,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.do_pad&&!this.pad_size&&this.size&&void 0!==this.size.width&&void 0!==this.size.height&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,s=2){const r=e.height,n=e.width,o=t.height,i=t.width;let a=Math.min(r,o),l=Math.min(n,i);return a===r&&l===n?e:(r>n?l=Math.floor(n*a/r):n>r&&(a=Math.floor(r*l/n)),await e.resize(l,a,{resample:s}))}async crop_margin(e,t=200){const s=e.clone().grayscale(),r=(0,o.min)(s.data)[0],n=(0,o.max)(s.data)[0]-r;if(0===n)return e;const i=t/255;let a=s.width,l=s.height,c=0,d=0;const u=s.data;for(let e=0;e<s.height;++e){const t=e*s.width;for(let o=0;o<s.width;++o)(u[t+o]-r)/n<i&&(a=Math.min(a,o),l=Math.min(l,e),c=Math.max(c,o),d=Math.max(d,e))}return e=await e.crop([a,l,c,d])}pad_image(e,t,s,{mode:r="constant",center:n=!1,constant_values:o=0}={}){const[a,l,c]=t;let d,u;if("number"==typeof s?(d=s,u=s):"square"===s?d=u=Math.max(a,l):(d=s.width,u=s.height),d!==l||u!==a){const s=new Float32Array(d*u*c);if(Array.isArray(o))for(let e=0;e<s.length;++e)s[e]=o[e%c];else 0!==o&&s.fill(o);const[p,_]=n?[Math.floor((d-l)/2),Math.floor((u-a)/2)]:[0,0];for(let t=0;t<a;++t){const r=(t+_)*d,n=t*l;for(let t=0;t<l;++t){const o=(r+t+p)*c,i=(n+t)*c;for(let t=0;t<c;++t)s[o+t]=e[i+t]}}if("symmetric"===r){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const t=a-1,r=l-1;for(let n=0;n<u;++n){const o=n*d,u=(0,i.calculateReflectOffset)(n,t)*l;for(let t=0;t<d;++t){if(n<a&&t<l)continue;const d=(o+t)*c,p=(u+(0,i.calculateReflectOffset)(t,r))*c;for(let t=0;t<c;++t)s[d+t]=e[p+t]}}}e=s,t=[u,d,c]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[s,r]=e.size;let n,o;if(this.do_thumbnail){const{height:e,width:s}=t;n=Math.min(e,s)}else Number.isInteger(t)?(n=t,o=this.config.max_size??n):void 0!==t&&(n=t.shortest_edge,o=t.longest_edge);if(void 0!==n||void 0!==o){const e=void 0===n?1:Math.max(n/s,n/r),t=s*e,i=r*e,a=void 0===o?1:Math.min(o/t,o/i);let l=Math.floor(Number((t*a).toFixed(2))),c=Math.floor(Number((i*a).toFixed(2)));return void 0!==this.size_divisibility&&([l,c]=d([l,c],this.size_divisibility)),[l,c]}if(void 0!==t&&void 0!==t.width&&void 0!==t.height){let e=t.width,n=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=n/r,o=e/s;Math.abs(1-o)<Math.abs(1-t)?t=o:o=t,n=c(t*r,this.config.ensure_multiple_of),e=c(o*s,this.config.ensure_multiple_of)}return[e,n]}if(void 0!==this.size_divisibility)return d([s,r],this.size_divisibility);if(void 0!==t.min_pixels&&void 0!==t.max_pixels){const{min_pixels:e,max_pixels:n}=t;return function(e,t,s=28,r=3136,n=1003520){if(e<s||t<s)throw new Error(`height:${e} or width:${t} must be larger than factor:${s}`);if(Math.max(e,t)/Math.min(e,t)>200)throw new Error("absolute aspect ratio must be smaller than 200, got "+Math.max(e,t)/Math.min(e,t));let o=Math.round(e/s)*s,i=Math.round(t/s)*s;if(o*i>n){const r=Math.sqrt(e*t/n);o=Math.floor(e/r/s)*s,i=Math.floor(t/r/s)*s}else if(o*i<r){const n=Math.sqrt(r/(e*t));o=Math.ceil(e*n/s)*s,i=Math.ceil(t*n/s)*s}return[o,i]}(r,s,this.config.patch_size*this.config.merge_size,e,n)}throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}async resize(e){const[t,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,s,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:s=null,do_convert_rgb:r=null,do_convert_grayscale:o=null,do_flip_channel_order:i=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[a,l]=e.size;if(r??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let t,s;Number.isInteger(this.crop_size)?(t=this.crop_size,s=this.crop_size):(t=this.crop_size.width,s=this.crop_size.height),e=await e.center_crop(t,s)}const c=[e.height,e.width];let u=Float32Array.from(e.data),p=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(u),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=new Array(e.channels).fill(t));let s=this.image_std;if(Array.isArray(this.image_std)||(s=new Array(e.channels).fill(t)),t.length!==e.channels||s.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${t.length}) and \`image_std\` (${s.length}) must match the number of channels in the image (${e.channels}).`);for(let r=0;r<u.length;r+=e.channels)for(let n=0;n<e.channels;++n)u[r+n]=(u[r+n]-t[n])/s[n]}if(s??this.do_pad)if(this.pad_size){const t=this.pad_image(u,[e.height,e.width,e.channels],this.pad_size);[u,p]=t}else if(this.size_divisibility){const[e,t]=d([p[1],p[0]],this.size_divisibility);[u,p]=this.pad_image(u,p,{width:e,height:t})}if(i??this.do_flip_channel_order){if(3!==p[2])throw new Error("Flipping channel order is only supported for RGB images.");for(let e=0;e<u.length;e+=3){const t=u[e];u[e]=u[e+2],u[e+2]=t}}return{original_size:[l,a],reshaped_input_size:c,pixel_values:new n.Tensor("float32",u,p).permute(2,0,1)}}async _call(e,...t){Array.isArray(e)||(e=[e]);const s=await Promise.all(e.map((e=>this.preprocess(e))));return{pixel_values:(0,n.stack)(s.map((e=>e.pixel_values)),0),original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}static async from_pretrained(e,t){return new this(await(0,a.getModelJSON)(e,l.IMAGE_PROCESSOR_NAME,!0,t))}}},"./src/base/processing_utils.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Processor:()=>i});var r=s("./src/utils/constants.js"),n=s("./src/utils/generic.js"),o=s("./src/utils/hub.js");class i extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(e,t){super(),this.config=e,this.components=t}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}async _call(e,...t){for(const s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t){const[s,n]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(e,r.PROCESSOR_NAME,!0,t):{},Promise.all(this.classes.filter((e=>e in this)).map((async s=>{const r=await this[s].from_pretrained(e,t);return[s.replace(/_class$/,""),r]}))).then(Object.fromEntries)]);return new this(s,n)}}},"./src/configs.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoConfig:()=>l,PretrainedConfig:()=>a,getKeyValueShapes:()=>i});var r=s("./src/utils/core.js"),n=s("./src/utils/hub.js");function o(e){const t={};let s={};switch(e.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":s=o(e.text_config);break;case"moondream1":s=o(e.phi_config);break;case"musicgen":s=o(e.decoder);break;case"multi_modality":s=o(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const n=o(e.decoder),i="num_decoder_layers"in n,a=(0,r.pick)(e,["model_type","is_encoder_decoder"]);return i?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}const n={...s,...(0,r.pick)(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function i(e,{prefix:t="past_key_values",batch_size:s=1}={}){const r={},n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){const e=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,o=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[s,n.num_encoder_heads,0,e],a=[s,n.num_decoder_heads,0,o];for(let e=0;e<n.num_decoder_layers;++e)r[`${t}.${e}.encoder.key`]=i,r[`${t}.${e}.encoder.value`]=i,r[`${t}.${e}.decoder.key`]=a,r[`${t}.${e}.decoder.value`]=a}else{const e=n.num_heads,o=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??e);if("falcon"===n.model_type){const n=[s*e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=n}else if(n.multi_query){const n=[s*e,0,2*i];for(let e=0;e<o;++e)r[`${t}.${e}.key_value`]=n}else if("bloom"===n.model_type){const n=[s*e,i,0],a=[s*e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=a}else if("openelm"===n.model_type)for(let n=0;n<o;++n){const o=[s,e[n],0,i];r[`${t}.${n}.key`]=o,r[`${t}.${n}.value`]=o}else{const n=[s,e,0,i];for(let e=0;e<o;++e)r[`${t}.${e}.key`]=n,r[`${t}.${e}.value`]=n}}return r}class a{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=o(this)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:o=!1,revision:i="main"}={}){!s||s instanceof a||(s=new a(s));const l=s??await async function(e,t){return await(0,n.getModelJSON)(e,"config.json",!0,t)}(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:o,revision:i});return new this(l)}}class l{static async from_pretrained(...e){return a.from_pretrained(...e)}}},"./src/env.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{apis:()=>h,env:()=>b});var r=s("fs"),n=s("path"),o=s("url");const i="undefined"!=typeof window&&void 0!==window.document,a="undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor?.name,l="undefined"!=typeof self&&"caches"in self,c="undefined"!=typeof navigator&&"gpu"in navigator,d="undefined"!=typeof navigator&&"ml"in navigator,u="undefined"!=typeof process,p=u&&"node"===process?.release?.name,_=!x(r),m=!x(n),h=Object.freeze({IS_BROWSER_ENV:i,IS_WEBWORKER_ENV:a,IS_WEB_CACHE_AVAILABLE:l,IS_WEBGPU_AVAILABLE:c,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:p,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:m}),f=_&&m;let g="./";if(f){const e=Object({}).url;e?g=n.dirname(n.dirname(o.fileURLToPath(e))):"undefined"!=typeof __dirname&&(g=n.dirname(__dirname))}const w=f?n.join(g,"/.cache/"):null,M="/models/",b={version:"3.2.0",backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(i||a),localModelPath:f?n.join(g,M):M,useFS:_,useBrowserCache:l,useFSCache:_,cacheDir:w,useCustomCache:!1,customCache:null};function x(e){return 0===Object.keys(e).length}},"./src/generation/configuration_utils.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{GenerationConfig:()=>n});var r=s("./src/utils/core.js");class n{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;streamer=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,r.pick)(e,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>m,MinNewTokensLengthLogitsProcessor:()=>h,NoBadWordsLogitsProcessor:()=>f,NoRepeatNGramLogitsProcessor:()=>p,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>d,TemperatureLogitsWarper:()=>w,TopKLogitsWarper:()=>b,TopPLogitsWarper:()=>M,WhisperTimeStampLogitsProcessor:()=>u});var r=s("./src/utils/generic.js"),n=(s("./src/utils/tensor.js"),s("./src/utils/maths.js"));class o extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class i extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class a extends r.Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let s=t;for(const t of this.processors)s=t(e,s);return s}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let s=0;s<e.length;++s)if(1===e[s].length){const e=t[s].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}}class c extends o{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){const e=t[s].data;e.fill(-1/0);for(const t of this.eos_token_id)e[t]=0}return t}}class d extends o{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){const e=t[s].data;for(const t of this.begin_suppress_tokens)e[t]=-1/0}return t}}class u extends o{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;if(r[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){r.fill(-1/0),r[this.timestamp_begin]=0;continue}const o=e[s].slice(this.begin_index),i=o.length>=1&&o[o.length-1]>=this.timestamp_begin,a=o.length<2||o[o.length-2]>=this.timestamp_begin;if(i&&(a?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&null!==this.max_initial_timestamp_index){const e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}const l=(0,n.log_softmax)(r);Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)))>(0,n.max)(l.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class p extends o{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,s=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){const t=[];for(let s=0;s<this.no_repeat_ngram_size;++s)t.push(e[r+s]);s.push(t.map(Number))}const r=new Map;for(const e of s){const t=e.slice(0,e.length-1),s=JSON.stringify(t),n=r.get(s)??[];n.push(e[e.length-1]),r.set(s,n)}return r}getGeneratedNgrams(e,t){const s=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=this.calcBannedNgramTokens(e[s]);for(const e of n)r[e]=-1/0}return t}}class _ extends o{constructor(e){super(),this.penalty=e}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;for(const t of new Set(e[s])){const e=Number(t);r[e]<0?r[e]*=this.penalty:r[e]/=this.penalty}}return t}}class m extends o{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}return t}}class h extends o{constructor(e,t,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,t){for(let s=0;s<e.length;++s){if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}}return t}}class f extends o{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=e[s];for(const e of this.bad_words_ids){let t=!0;for(let s=1;s<=e.length-1&&e.length<n.length;++s)if(e.at(-s-1)!=n.at(-s)){t=!1;break}t&&(r[e.at(-1)]=-1/0)}}return t}}class g extends o{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 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 s=e.length,r=t.slice([0,s],null),n=t.slice([s,t.dims[0]],null);for(let e=0;e<n.data.length;++e)n.data[e]+=(r.data[e]-n.data[e])*this.guidance_scale;return n}}class w extends i{constructor(e){if(super(),"number"!=typeof e||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;0===e&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){const s=t.data;for(let e=0;e<s.length;++e)s[e]/=this.temperature;return t}}class M extends i{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=s}}class b extends i{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=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,s),this.filter_value=t}}},"./src/generation/logits_sampler.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{LogitsSampler:()=>i});var r=s("./src/utils/generic.js"),n=s("./src/utils/tensor.js"),o=s("./src/utils/maths.js");s("./src/generation/configuration_utils.js");class i extends r.Callable{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let s=e.dims.at(-1),r=e.data;if(-1===t)r=r.slice(-s);else{let e=t*s;r=r.slice(e,e+s)}return r}randomSelect(e){let t=0;for(let s=0;s<e.length;++s)t+=e[s];let s=Math.random()*t;for(let t=0;t<e.length;++t)if(s-=e[t],s<=0)return t;return 0}static getSampler(e){if(e.do_sample)return new l(e);if(e.num_beams>1)return new c(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 a(e)}}class a extends i{async sample(e){const t=(0,o.max)(e.data)[1];return[[BigInt(t),0]]}}class l extends i{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await(0,n.topk)(e,t),i=(0,o.softmax)(s.data);return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]}))}}class c extends i{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await(0,n.topk)(e,t),i=(0,o.softmax)(s.data);return Array.from({length:this.generation_config.num_beams},((e,t)=>[r.data[t],Math.log(i[t])]))}}},"./src/generation/stopping_criteria.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var r=s("./src/utils/generic.js");class n extends r.Callable{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class o extends r.Callable{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof o?e=e.criteria:e instanceof n&&(e=[e]),this.criteria.push(...e)}_call(e,t){const s=new Array(e.length).fill(!1);for(const r of this.criteria){const n=r(e,t);for(let e=0;e<s.length;++e)s[e]||=n[e]}return s}[Symbol.iterator](){return this.criteria.values()}}class i extends n{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map((e=>e.length>=this.max_length))}}class a extends n{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map((e=>{const t=e.at(-1);return this.eos_token_id.some((e=>t==e))}))}}class l extends n{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var r=s("./src/utils/core.js"),n=s("./src/tokenizers.js"),o=s("./src/env.js");class i{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=o.apis.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e);class l extends i{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:r=null,decode_kwargs:n={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=s??a,this.token_callback_function=r,this.decode_kwargs={...n,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt)return void(this.next_tokens_are_prompt=!1);const t=e[0];this.token_callback_function?.(t),this.token_cache=(0,r.mergeArrays)(this.token_cache,t);const s=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let o;s.endsWith("\n")?(o=s.slice(this.print_len),this.token_cache=[],this.print_len=0):s.length>0&&(0,n.is_chinese_char)(s.charCodeAt(s.length-1))?(o=s.slice(this.print_len),this.print_len+=o.length):(o=s.slice(this.print_len,s.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;if(this.token_cache.length>0){e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0}else e="";this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===a&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.("\n")}}class c extends l{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:r=null,on_chunk_start:n=null,on_chunk_end:o=null,on_finalize:i=null,time_precision:a=.02,skip_special_tokens:l=!0,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,callback_function:s,token_callback_function:r,decode_kwargs:{skip_special_tokens:l,...c}}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=n,this.on_chunk_end=o,this.on_finalize=i,this.time_precision=a,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const t=e[0];if(1===t.length){const s=Number(t[0])-this.timestamp_begin;if(s>=0){const t=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(t):this.on_chunk_start?.(t),this.waiting_for_timestamp=!this.waiting_for_timestamp,e=[[]]}}return super.put(e)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTForAudioClassification:()=>ds,ASTModel:()=>cs,ASTPreTrainedModel:()=>ls,AlbertForMaskedLM:()=>Mt,AlbertForQuestionAnswering:()=>wt,AlbertForSequenceClassification:()=>gt,AlbertModel:()=>ft,AlbertPreTrainedModel:()=>ht,AutoModel:()=>Ol,AutoModelForAudioClassification:()=>sc,AutoModelForAudioFrameClassification:()=>nc,AutoModelForCTC:()=>tc,AutoModelForCausalLM:()=>ql,AutoModelForDepthEstimation:()=>lc,AutoModelForDocumentQuestionAnswering:()=>oc,AutoModelForImageClassification:()=>Ql,AutoModelForImageFeatureExtraction:()=>uc,AutoModelForImageMatting:()=>ic,AutoModelForImageSegmentation:()=>Hl,AutoModelForImageToImage:()=>ac,AutoModelForMaskGeneration:()=>ec,AutoModelForMaskedLM:()=>Ul,AutoModelForNormalEstimation:()=>cc,AutoModelForObjectDetection:()=>Kl,AutoModelForPoseEstimation:()=>dc,AutoModelForQuestionAnswering:()=>Wl,AutoModelForSemanticSegmentation:()=>Jl,AutoModelForSeq2SeqLM:()=>Dl,AutoModelForSequenceClassification:()=>Bl,AutoModelForSpeechSeq2Seq:()=>Rl,AutoModelForTextToSpectrogram:()=>Gl,AutoModelForTextToWaveform:()=>$l,AutoModelForTokenClassification:()=>Vl,AutoModelForUniversalSegmentation:()=>Yl,AutoModelForVision2Seq:()=>Xl,AutoModelForXVector:()=>rc,AutoModelForZeroShotObjectDetection:()=>Zl,BartForConditionalGeneration:()=>Et,BartForSequenceClassification:()=>It,BartModel:()=>St,BartPretrainedModel:()=>At,BaseModelOutput:()=>Y,BeitForImageClassification:()=>Jn,BeitModel:()=>Hn,BeitPreTrainedModel:()=>Qn,BertForMaskedLM:()=>ee,BertForQuestionAnswering:()=>re,BertForSequenceClassification:()=>te,BertForTokenClassification:()=>se,BertModel:()=>Z,BertPreTrainedModel:()=>K,BlenderbotForConditionalGeneration:()=>Dt,BlenderbotModel:()=>Vt,BlenderbotPreTrainedModel:()=>Bt,BlenderbotSmallForConditionalGeneration:()=>$t,BlenderbotSmallModel:()=>Gt,BlenderbotSmallPreTrainedModel:()=>Rt,BloomForCausalLM:()=>on,BloomModel:()=>nn,BloomPreTrainedModel:()=>rn,CLIPModel:()=>Es,CLIPPreTrainedModel:()=>Ss,CLIPSegForImageSegmentation:()=>Qs,CLIPSegModel:()=>Xs,CLIPSegPreTrainedModel:()=>Ws,CLIPTextModel:()=>Is,CLIPTextModelWithProjection:()=>Ls,CLIPVisionModel:()=>zs,CLIPVisionModelWithProjection:()=>js,CamembertForMaskedLM:()=>Pe,CamembertForQuestionAnswering:()=>Ae,CamembertForSequenceClassification:()=>Fe,CamembertForTokenClassification:()=>Ce,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Te,CausalLMOutput:()=>wc,CausalLMOutputWithPast:()=>Mc,ChineseCLIPModel:()=>Rs,ChineseCLIPPreTrainedModel:()=>Ds,ClapAudioModelWithProjection:()=>pa,ClapModel:()=>da,ClapPreTrainedModel:()=>ca,ClapTextModelWithProjection:()=>ua,CodeGenForCausalLM:()=>hr,CodeGenModel:()=>mr,CodeGenPreTrainedModel:()=>_r,CohereForCausalLM:()=>Nr,CohereModel:()=>jr,CoherePreTrainedModel:()=>zr,ConvBertForMaskedLM:()=>me,ConvBertForQuestionAnswering:()=>ge,ConvBertForSequenceClassification:()=>he,ConvBertForTokenClassification:()=>fe,ConvBertModel:()=>_e,ConvBertPreTrainedModel:()=>pe,ConvNextForImageClassification:()=>Qo,ConvNextModel:()=>Xo,ConvNextPreTrainedModel:()=>Wo,ConvNextV2ForImageClassification:()=>Yo,ConvNextV2Model:()=>Jo,ConvNextV2PreTrainedModel:()=>Ho,DPTForDepthEstimation:()=>Ao,DPTModel:()=>Co,DPTPreTrainedModel:()=>Fo,DebertaForMaskedLM:()=>Ie,DebertaForQuestionAnswering:()=>je,DebertaForSequenceClassification:()=>Le,DebertaForTokenClassification:()=>ze,DebertaModel:()=>Ee,DebertaPreTrainedModel:()=>Se,DebertaV2ForMaskedLM:()=>Be,DebertaV2ForQuestionAnswering:()=>Re,DebertaV2ForSequenceClassification:()=>Ve,DebertaV2ForTokenClassification:()=>De,DebertaV2Model:()=>Oe,DebertaV2PreTrainedModel:()=>Ne,DecisionTransformerModel:()=>Ga,DecisionTransformerPreTrainedModel:()=>Ra,DeiTForImageClassification:()=>mo,DeiTModel:()=>_o,DeiTPreTrainedModel:()=>po,DepthAnythingForDepthEstimation:()=>Eo,DepthAnythingPreTrainedModel:()=>So,DepthProForDepthEstimation:()=>Oo,DepthProPreTrainedModel:()=>No,DetrForObjectDetection:()=>Zn,DetrForSegmentation:()=>eo,DetrModel:()=>Kn,DetrObjectDetectionOutput:()=>to,DetrPreTrainedModel:()=>Yn,DetrSegmentationOutput:()=>so,Dinov2ForImageClassification:()=>ei,Dinov2Model:()=>Zo,Dinov2PreTrainedModel:()=>Ko,DistilBertForMaskedLM:()=>Xe,DistilBertForQuestionAnswering:()=>We,DistilBertForSequenceClassification:()=>qe,DistilBertForTokenClassification:()=>Ue,DistilBertModel:()=>$e,DistilBertPreTrainedModel:()=>Ge,DonutSwinModel:()=>Uo,DonutSwinPreTrainedModel:()=>qo,EfficientNetForImageClassification:()=>Ta,EfficientNetModel:()=>ka,EfficientNetPreTrainedModel:()=>ya,ElectraForMaskedLM:()=>be,ElectraForQuestionAnswering:()=>ke,ElectraForSequenceClassification:()=>xe,ElectraForTokenClassification:()=>ye,ElectraModel:()=>Me,ElectraPreTrainedModel:()=>we,EsmForMaskedLM:()=>Je,EsmForSequenceClassification:()=>Ye,EsmForTokenClassification:()=>Ke,EsmModel:()=>He,EsmPreTrainedModel:()=>Qe,ExaoneForCausalLM:()=>xr,ExaoneModel:()=>br,ExaonePreTrainedModel:()=>Mr,FalconForCausalLM:()=>la,FalconModel:()=>aa,FalconPreTrainedModel:()=>ia,FastViTForImageClassification:()=>Ln,FastViTModel:()=>In,FastViTPreTrainedModel:()=>En,Florence2ForConditionalGeneration:()=>ks,Florence2PreTrainedModel:()=>ys,GLPNForDepthEstimation:()=>$o,GLPNModel:()=>Go,GLPNPreTrainedModel:()=>Ro,GPT2LMHeadModel:()=>Ys,GPT2Model:()=>Js,GPT2PreTrainedModel:()=>Hs,GPTBigCodeForCausalLM:()=>pr,GPTBigCodeModel:()=>ur,GPTBigCodePreTrainedModel:()=>dr,GPTJForCausalLM:()=>cr,GPTJModel:()=>lr,GPTJPreTrainedModel:()=>ar,GPTNeoForCausalLM:()=>rr,GPTNeoModel:()=>sr,GPTNeoPreTrainedModel:()=>tr,GPTNeoXForCausalLM:()=>ir,GPTNeoXModel:()=>or,GPTNeoXPreTrainedModel:()=>nr,Gemma2ForCausalLM:()=>Gr,Gemma2Model:()=>Rr,Gemma2PreTrainedModel:()=>Dr,GemmaForCausalLM:()=>Vr,GemmaModel:()=>Br,GemmaPreTrainedModel:()=>Or,GraniteForCausalLM:()=>Lr,GraniteModel:()=>Ir,GranitePreTrainedModel:()=>Er,GroupViTModel:()=>Sn,GroupViTPreTrainedModel:()=>An,HieraForImageClassification:()=>go,HieraModel:()=>fo,HieraPreTrainedModel:()=>ho,HubertForCTC:()=>Vi,HubertForSequenceClassification:()=>Di,HubertModel:()=>Bi,HubertPreTrainedModel:()=>Oi,IJepaForImageClassification:()=>wn,IJepaModel:()=>gn,IJepaPreTrainedModel:()=>fn,Idefics3ForConditionalGeneration:()=>Fs,Idefics3PreTrainedModel:()=>Ps,ImageMattingOutput:()=>bc,JAISLMHeadModel:()=>er,JAISModel:()=>Zs,JAISPreTrainedModel:()=>Ks,JinaCLIPModel:()=>$s,JinaCLIPPreTrainedModel:()=>Gs,JinaCLIPTextModel:()=>qs,JinaCLIPVisionModel:()=>Us,LlamaForCausalLM:()=>wr,LlamaModel:()=>gr,LlamaPreTrainedModel:()=>fr,LlavaForConditionalGeneration:()=>Ms,LlavaOnevisionForConditionalGeneration:()=>bs,LlavaPreTrainedModel:()=>ws,LongT5ForConditionalGeneration:()=>vt,LongT5Model:()=>Tt,LongT5PreTrainedModel:()=>kt,M2M100ForConditionalGeneration:()=>_i,M2M100Model:()=>pi,M2M100PreTrainedModel:()=>ui,MBartForCausalLM:()=>Ot,MBartForConditionalGeneration:()=>jt,MBartForSequenceClassification:()=>Nt,MBartModel:()=>zt,MBartPreTrainedModel:()=>Lt,MPNetForMaskedLM:()=>it,MPNetForQuestionAnswering:()=>ct,MPNetForSequenceClassification:()=>at,MPNetForTokenClassification:()=>lt,MPNetModel:()=>ot,MPNetPreTrainedModel:()=>nt,MT5ForConditionalGeneration:()=>Ct,MT5Model:()=>Ft,MT5PreTrainedModel:()=>Pt,MarianMTModel:()=>di,MarianModel:()=>ci,MarianPreTrainedModel:()=>li,MaskFormerForInstanceSegmentation:()=>Do,MaskFormerModel:()=>Vo,MaskFormerPreTrainedModel:()=>Bo,MaskedLMOutput:()=>fc,MgpstrForSceneTextRecognition:()=>Xa,MgpstrModelOutput:()=>Ua,MgpstrPreTrainedModel:()=>Wa,MistralForCausalLM:()=>sa,MistralModel:()=>ta,MistralPreTrainedModel:()=>ea,MobileBertForMaskedLM:()=>tt,MobileBertForQuestionAnswering:()=>rt,MobileBertForSequenceClassification:()=>st,MobileBertModel:()=>et,MobileBertPreTrainedModel:()=>Ze,MobileLLMForCausalLM:()=>Tr,MobileLLMModel:()=>kr,MobileLLMPreTrainedModel:()=>yr,MobileNetV1ForImageClassification:()=>Ea,MobileNetV1Model:()=>Sa,MobileNetV1PreTrainedModel:()=>Aa,MobileNetV2ForImageClassification:()=>za,MobileNetV2Model:()=>La,MobileNetV2PreTrainedModel:()=>Ia,MobileNetV3ForImageClassification:()=>Oa,MobileNetV3Model:()=>Na,MobileNetV3PreTrainedModel:()=>ja,MobileNetV4ForImageClassification:()=>Da,MobileNetV4Model:()=>Va,MobileNetV4PreTrainedModel:()=>Ba,MobileViTForImageClassification:()=>Bn,MobileViTModel:()=>On,MobileViTPreTrainedModel:()=>Nn,MobileViTV2ForImageClassification:()=>Rn,MobileViTV2Model:()=>Dn,MobileViTV2PreTrainedModel:()=>Vn,ModelOutput:()=>J,Moondream1ForConditionalGeneration:()=>xs,MoonshineForConditionalGeneration:()=>fs,MoonshineModel:()=>hs,MoonshinePreTrainedModel:()=>ms,MptForCausalLM:()=>cn,MptModel:()=>ln,MptPreTrainedModel:()=>an,MultiModalityCausalLM:()=>qa,MultiModalityPreTrainedModel:()=>$a,MusicgenForCausalLM:()=>Fa,MusicgenForConditionalGeneration:()=>Ca,MusicgenModel:()=>Pa,MusicgenPreTrainedModel:()=>va,NomicBertModel:()=>oe,NomicBertPreTrainedModel:()=>ne,OPTForCausalLM:()=>pn,OPTModel:()=>un,OPTPreTrainedModel:()=>dn,Olmo2ForCausalLM:()=>Sr,Olmo2Model:()=>Ar,Olmo2PreTrainedModel:()=>Cr,OlmoForCausalLM:()=>Fr,OlmoModel:()=>Pr,OlmoPreTrainedModel:()=>vr,OpenELMForCausalLM:()=>Ur,OpenELMModel:()=>qr,OpenELMPreTrainedModel:()=>$r,OwlViTForObjectDetection:()=>qn,OwlViTModel:()=>$n,OwlViTPreTrainedModel:()=>Gn,Owlv2ForObjectDetection:()=>Xn,Owlv2Model:()=>Wn,Owlv2PreTrainedModel:()=>Un,PaliGemmaForConditionalGeneration:()=>vs,PaliGemmaPreTrainedModel:()=>Ts,PatchTSMixerForPrediction:()=>Za,PatchTSMixerModel:()=>Ka,PatchTSMixerPreTrainedModel:()=>Ya,PatchTSTForPrediction:()=>Ja,PatchTSTModel:()=>Ha,PatchTSTPreTrainedModel:()=>Qa,Phi3ForCausalLM:()=>sn,Phi3Model:()=>tn,Phi3PreTrainedModel:()=>en,Phi3VForCausalLM:()=>As,Phi3VPreTrainedModel:()=>Cs,PhiForCausalLM:()=>Zr,PhiModel:()=>Kr,PhiPreTrainedModel:()=>Yr,PreTrainedModel:()=>H,PretrainedMixin:()=>el,PvtForImageClassification:()=>kn,PvtModel:()=>yn,PvtPreTrainedModel:()=>xn,PyAnnoteForAudioFrameClassification:()=>xi,PyAnnoteModel:()=>bi,PyAnnotePreTrainedModel:()=>Mi,QuestionAnsweringModelOutput:()=>gc,Qwen2ForCausalLM:()=>Qr,Qwen2Model:()=>Xr,Qwen2PreTrainedModel:()=>Wr,Qwen2VLForConditionalGeneration:()=>Jr,Qwen2VLPreTrainedModel:()=>Hr,RTDetrForObjectDetection:()=>oo,RTDetrModel:()=>no,RTDetrObjectDetectionOutput:()=>io,RTDetrPreTrainedModel:()=>ro,ResNetForImageClassification:()=>bo,ResNetModel:()=>Mo,ResNetPreTrainedModel:()=>wo,RoFormerForMaskedLM:()=>le,RoFormerForQuestionAnswering:()=>ue,RoFormerForSequenceClassification:()=>ce,RoFormerForTokenClassification:()=>de,RoFormerModel:()=>ae,RoFormerPreTrainedModel:()=>ie,RobertaForMaskedLM:()=>Wt,RobertaForQuestionAnswering:()=>Ht,RobertaForSequenceClassification:()=>Xt,RobertaForTokenClassification:()=>Qt,RobertaModel:()=>Ut,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>ai,SamModel:()=>ii,SamPreTrainedModel:()=>oi,SapiensForDepthEstimation:()=>zo,SapiensForNormalEstimation:()=>jo,SapiensForSemanticSegmentation:()=>Lo,SapiensPreTrainedModel:()=>Io,SegformerForImageClassification:()=>ga,SegformerForSemanticSegmentation:()=>wa,SegformerModel:()=>fa,SegformerPreTrainedModel:()=>ha,Seq2SeqLMOutput:()=>pc,SequenceClassifierOutput:()=>_c,SiglipModel:()=>Os,SiglipPreTrainedModel:()=>Ns,SiglipTextModel:()=>Bs,SiglipVisionModel:()=>Vs,SpeechT5ForSpeechToText:()=>Hi,SpeechT5ForTextToSpeech:()=>Ji,SpeechT5HifiGan:()=>Yi,SpeechT5Model:()=>Qi,SpeechT5PreTrainedModel:()=>Xi,SqueezeBertForMaskedLM:()=>pt,SqueezeBertForQuestionAnswering:()=>mt,SqueezeBertForSequenceClassification:()=>_t,SqueezeBertModel:()=>ut,SqueezeBertPreTrainedModel:()=>dt,StableLmForCausalLM:()=>xa,StableLmModel:()=>ba,StableLmPreTrainedModel:()=>Ma,Starcoder2ForCausalLM:()=>oa,Starcoder2Model:()=>na,Starcoder2PreTrainedModel:()=>ra,Swin2SRForImageSuperResolution:()=>Po,Swin2SRModel:()=>vo,Swin2SRPreTrainedModel:()=>To,SwinForImageClassification:()=>ko,SwinModel:()=>yo,SwinPreTrainedModel:()=>xo,T5ForConditionalGeneration:()=>yt,T5Model:()=>xt,T5PreTrainedModel:()=>bt,TableTransformerForObjectDetection:()=>co,TableTransformerModel:()=>lo,TableTransformerObjectDetectionOutput:()=>uo,TableTransformerPreTrainedModel:()=>ao,TokenClassifierOutput:()=>hc,TrOCRForCausalLM:()=>Zi,TrOCRPreTrainedModel:()=>Ki,UniSpeechForCTC:()=>Pi,UniSpeechForSequenceClassification:()=>Fi,UniSpeechModel:()=>vi,UniSpeechPreTrainedModel:()=>Ti,UniSpeechSatForAudioFrameClassification:()=>Ii,UniSpeechSatForCTC:()=>Si,UniSpeechSatForSequenceClassification:()=>Ei,UniSpeechSatModel:()=>Ai,UniSpeechSatPreTrainedModel:()=>Ci,ViTForImageClassification:()=>hn,ViTMAEModel:()=>vn,ViTMAEPreTrainedModel:()=>Tn,ViTMSNForImageClassification:()=>Cn,ViTMSNModel:()=>Fn,ViTMSNPreTrainedModel:()=>Pn,ViTModel:()=>mn,ViTPreTrainedModel:()=>_n,VisionEncoderDecoderModel:()=>gs,VitMatteForImageMatting:()=>jn,VitMattePreTrainedModel:()=>zn,VitPoseForPoseEstimation:()=>bn,VitPosePreTrainedModel:()=>Mn,VitsModel:()=>ma,VitsModelOutput:()=>xc,VitsPreTrainedModel:()=>_a,Wav2Vec2BertForCTC:()=>ji,Wav2Vec2BertForSequenceClassification:()=>Ni,Wav2Vec2BertModel:()=>zi,Wav2Vec2BertPreTrainedModel:()=>Li,Wav2Vec2ForAudioFrameClassification:()=>wi,Wav2Vec2ForCTC:()=>fi,Wav2Vec2ForSequenceClassification:()=>gi,Wav2Vec2Model:()=>hi,Wav2Vec2PreTrainedModel:()=>mi,WavLMForAudioFrameClassification:()=>Wi,WavLMForCTC:()=>$i,WavLMForSequenceClassification:()=>qi,WavLMForXVector:()=>Ui,WavLMModel:()=>Gi,WavLMPreTrainedModel:()=>Ri,WeSpeakerResNetModel:()=>ki,WeSpeakerResNetPreTrainedModel:()=>yi,WhisperForConditionalGeneration:()=>_s,WhisperModel:()=>ps,WhisperPreTrainedModel:()=>us,XLMForQuestionAnswering:()=>ts,XLMForSequenceClassification:()=>Zt,XLMForTokenClassification:()=>es,XLMModel:()=>Yt,XLMPreTrainedModel:()=>Jt,XLMRobertaForMaskedLM:()=>ns,XLMRobertaForQuestionAnswering:()=>as,XLMRobertaForSequenceClassification:()=>os,XLMRobertaForTokenClassification:()=>is,XLMRobertaModel:()=>rs,XLMRobertaPreTrainedModel:()=>ss,XLMWithLMHeadModel:()=>Kt,XVectorOutput:()=>mc,YolosForObjectDetection:()=>ri,YolosModel:()=>si,YolosObjectDetectionOutput:()=>ni,YolosPreTrainedModel:()=>ti});var r=s("./src/configs.js"),n=s("./src/backends/onnx.js"),o=s("./src/utils/dtypes.js"),i=s("./src/utils/generic.js"),a=s("./src/utils/core.js"),l=s("./src/utils/hub.js"),c=s("./src/utils/constants.js"),d=s("./src/generation/logits_process.js"),u=s("./src/generation/configuration_utils.js"),p=s("./src/utils/tensor.js"),_=s("./src/utils/image.js"),m=s("./src/utils/maths.js"),h=s("./src/generation/stopping_criteria.js"),f=s("./src/generation/logits_sampler.js"),g=s("./src/env.js"),w=s("./src/models/whisper/generation_whisper.js"),M=s("./src/models/whisper/common_whisper.js");const b=0,x=1,y=2,k=3,T=4,v=5,P=6,F=7,C=8,A=9,S=new Map,E=new Map,I=new Map;async function L(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async i=>{const{buffer:a,session_options:c,session_config:d}=await async function(e,t,s){const i=s.config?.["transformers.js_config"]??{};let a=s.device??i.device;a&&"string"!=typeof a&&(a.hasOwnProperty(t)?a=a[t]:(console.warn(`device not specified for "${t}". Using the default device.`),a=null));const c=a??(g.apis.IS_NODE_ENV?"cpu":"wasm"),d=(0,n.deviceToExecutionProviders)(c);let u=s.dtype??i.dtype;if("string"!=typeof u&&(u&&u.hasOwnProperty(t)?u=u[t]:(u=o.DEFAULT_DEVICE_DTYPE_MAPPING[c]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${t}". Using the default dtype (${u}) for this device (${c}).`))),u===o.DATA_TYPES.auto){let e=i.dtype;"string"!=typeof e&&(e=e[t]),u=e&&e!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(e)?e:o.DEFAULT_DEVICE_DTYPE_MAPPING[c]??o.DATA_TYPES.fp32}const p=u;if(!o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(p))throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);if(p===o.DATA_TYPES.fp16&&"webgpu"===c&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${c}) does not support fp16.`);const _=i.kv_cache_dtype?"string"==typeof i.kv_cache_dtype?i.kv_cache_dtype:i.kv_cache_dtype[p]??"float32":void 0;if(_&&!["float32","float16"].includes(_))throw new Error(`Invalid kv_cache_dtype: ${_}. Should be one of: float32, float16`);const m={dtype:p,kv_cache_dtype:_},h=o.DEFAULT_DTYPE_SUFFIX_MAPPING[p],f=`${s.subfolder??""}/${t}${h}.onnx`,w={...s.session_options};w.executionProviders??=d;const M=i.free_dimension_overrides;M?w.freeDimensionOverrides??=M:c.startsWith("webnn")&&!w.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const b=(0,l.getModelFile)(e,f,!0,s),x=s.use_external_data_format??i.use_external_data_format;let y=[];if(x&&(!0===x||"object"==typeof x&&x.hasOwnProperty(t)&&!0===x[t])){if(g.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const r=`${t}${h}.onnx_data`,n=`${s.subfolder??""}/${r}`;y.push(new Promise((async(t,o)=>{const i=await(0,l.getModelFile)(e,n,!0,s);t({path:r,data:i})})))}else void 0!==w.externalData&&(y=w.externalData.map((async t=>{if("string"==typeof t.data){const r=await(0,l.getModelFile)(e,t.data,!0,s);return{...t,data:r}}return t})));if(y.length>0&&(w.externalData=await Promise.all(y)),"webgpu"===c){const e=(0,r.getKeyValueShapes)(s.config,{prefix:"present"});if(Object.keys(e).length>0&&!(0,n.isONNXProxy)()){const t={};for(const s in e)t[s]="gpu-buffer";w.preferredOutputLocation=t}}return{buffer:await b,session_options:w,session_config:m}}(e,t[i],s);return[i,await(0,n.createInferenceSession)(a,c,d)]}))))}async function z(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async r=>[r,await(0,l.getModelJSON)(e,t[r],!1,s)]))))}async function j(e,t){const s=function(e,t){const s=Object.create(null),r=[];for(const o of e.inputNames){const e=t[o];e instanceof p.Tensor?s[o]=(0,n.isONNXProxy)()?e.clone():e:r.push(o)}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const o=Object.keys(t).length,i=e.inputNames.length;if(o>i){let s=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: "${s.join(", ")}".`)}return s}(e,t);try{const t=Object.fromEntries(Object.entries(s).map((([e,t])=>[e,t.ort_tensor])));let r=await e.run(t);return r=N(r),r}catch(e){const t=Object.fromEntries(Object.entries(s).map((([e,{type:t,dims:s,data:r}])=>[e,{type:t,dims:s,data:r}])));throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",t),e}}function N(e){for(let t in e)(0,n.isONNXTensor)(e[t])?e[t]=new p.Tensor(e[t]):"object"==typeof e[t]&&N(e[t]);return e}function O(e){if(e instanceof p.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 p.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new p.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}function B(e){return new p.Tensor("bool",[e],[1])}async function V(e,t){let{encoder_outputs:s,input_ids:r,decoder_input_ids:n,...o}=t;if(!s){const r=(0,a.pick)(t,e.sessions.model.inputNames);s=(await D(e,r)).last_hidden_state}o.input_ids=n,o.encoder_hidden_states=s,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=t.attention_mask);return await R(e,o,!0)}async function D(e,t){const s=e.sessions.model,r=(0,a.pick)(t,s.inputNames);if(s.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}return s.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new p.Tensor("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await j(s,r)}async function R(e,t,s=!1){const r=e.sessions[s?"decoder_model_merged":"model"],{past_key_values:n,...o}=t;if(r.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=B(!!n)),r.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){const t="paligemma"===e.config.model_type?1:0;o.position_ids=function(e,t=null,s=0){const{input_ids:r,inputs_embeds:n,attention_mask:o}=e,{data:i,dims:a}=q(o,s);let l=new p.Tensor("int64",i,a);if(t){const e=-(r??n).dims.at(1);l=l.slice(null,[e,null])}return l}(o,n,t)}e.addPastKeyValues(o,n);const i=(0,a.pick)(o,r.inputNames);return await j(r,i)}function G({image_token_id:e,inputs_embeds:t,image_features:s,input_ids:r,attention_mask:n}){const o=r.tolist().map((t=>t.reduce(((t,s,r)=>(s==e&&t.push(r),t)),[]))),i=o.reduce(((e,t)=>e+t.length),0),a=s.dims[0];if(i!==a)throw new Error(`Image features and image tokens do not match: tokens: ${i}, features ${a}`);let l=0;for(let e=0;e<o.length;++e){const r=o[e],n=t[e];for(let e=0;e<r.length;++e)n[r[e]].data.set(s[l++].data)}return{inputs_embeds:t,attention_mask:n}}async function $(e,{input_ids:t=null,attention_mask:s=null,pixel_values:r=null,position_ids:n=null,inputs_embeds:o=null,past_key_values:i=null,generation_config:a=null,logits_processor:l=null,...c}){if(!o)if(o=await e.encode_text({input_ids:t,...c}),r&&1!==t.dims[1]){const n=await e.encode_image({pixel_values:r,...c});({inputs_embeds:o,attention_mask:s}=e._merge_input_ids_with_image_features({image_features:n,inputs_embeds:o,input_ids:t,attention_mask:s}))}else if(i&&r&&1===t.dims[1]){const e=t.dims[1],r=Object.values(i)[0].dims.at(-2);s=(0,p.cat)([(0,p.ones)([t.dims[0],r]),s.slice(null,[s.dims[1]-e,s.dims[1]])],1)}if(!n&&"qwen2_vl"===e.config.model_type){const{image_grid_thw:r,video_grid_thw:o}=c;[n]=e.get_rope_index(t,r,o,s)}return await R(e,{inputs_embeds:o,past_key_values:i,attention_mask:s,position_ids:n,generation_config:a,logits_processor:l},!0)}function q(e,t=0){const[s,r]=e.dims,n=e.data,o=new BigInt64Array(n.length);for(let e=0;e<s;++e){const s=e*r;let i=BigInt(t);for(let e=0;e<r;++e){const t=s+e;0n===n[t]?o[t]=BigInt(1):(o[t]=i,i+=n[t])}}return{data:o,dims:e.dims}}function U(e,t,s,r){if(s.past_key_values){const t=Object.values(s.past_key_values)[0].dims.at(-2),{input_ids:r,attention_mask:n}=s;if(n&&n.dims[1]>r.dims[1]);else if(t<r.dims[1])s.input_ids=r.slice(null,[t,null]);else if(null!=e.config.image_token_index&&r.data.some((t=>t==e.config.image_token_index))){const n=e.config.num_image_tokens;if(!n)throw new Error("`num_image_tokens` is missing in the model configuration.");const o=r.dims[1]-(t-n);s.input_ids=r.slice(null,[-o,null]),s.attention_mask=(0,p.ones)([1,t+o])}}return s}function W(e,t,s,r){return s.past_key_values&&(t=t.map((e=>[e.at(-1)]))),{...s,decoder_input_ids:O(t)}}function X(e,...t){return e.config.is_encoder_decoder?W(e,...t):U(e,...t)}function Q(e,t,s,r){const n=!!s.past_key_values;if(null!==r.guidance_scale&&r.guidance_scale>1&&(n?s.input_ids=(0,p.cat)([s.input_ids,s.input_ids],0):(s.input_ids=(0,p.cat)([s.input_ids,(0,p.full_like)(s.input_ids,BigInt(r.pad_token_id))],0),s.attention_mask=(0,p.cat)([s.attention_mask,(0,p.full_like)(s.attention_mask,0n)],0))),!n&&s.pixel_values||(s.pixel_values=(0,p.full)([0,0,3,384,384],1)),n){const e=0,t=1,r=e>0?1:0,n=1;s.images_seq_mask=new p.Tensor("bool",new Array(e+t).fill(!0).fill(!1,0,t),[n,e+t]),s.images_emb_mask=new p.Tensor("bool",new Array(e).fill(!!r),[n,1,e])}return s}class H extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t,s){super(),this.config=e,this.sessions=t,this.configs=s;const r=I.get(this.constructor),n=S.get(r);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,n){case T:this.can_generate=!0,this._forward=R,this._prepare_inputs_for_generation=U;break;case y:case k:case F:this.can_generate=!0,this._forward=V,this._prepare_inputs_for_generation=W;break;case x:this._forward=V;break;case P:this.can_generate=!0,this._forward=$,this._prepare_inputs_for_generation=X;break;case A:this.can_generate=!0,this._prepare_inputs_for_generation=X;break;case C:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;default:this._forward=D}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:l="onnx",device:d=null,dtype:u=null,use_external_data_format:p=null,session_options:_={}}={}){let m={progress_callback:t,config:s,cache_dir:n,local_files_only:o,revision:i,model_file_name:a,subfolder:l,device:d,dtype:u,use_external_data_format:p,session_options:_};const h=I.get(this),f=S.get(h);let g;if(s=m.config=await r.AutoConfig.from_pretrained(e,m),f===T)g=await Promise.all([L(e,{model:m.model_file_name??"model"},m),z(e,{generation_config:"generation_config.json"},m)]);else if(f===y||f===k)g=await Promise.all([L(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),z(e,{generation_config:"generation_config.json"},m)]);else if(f===v)g=await Promise.all([L(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(f===x)g=await Promise.all([L(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m)]);else if(f===P){const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(t.model="encoder_model"),g=await Promise.all([L(e,t,m),z(e,{generation_config:"generation_config.json"},m)])}else if(f===F)g=await Promise.all([L(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),z(e,{generation_config:"generation_config.json"},m)]);else if(f===C)g=await Promise.all([L(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},m),z(e,{generation_config:"generation_config.json"},m)]);else if(f===A)g=await Promise.all([L(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},m),z(e,{generation_config:"generation_config.json"},m)]);else{if(f!==b){const e=h??s?.model_type;"custom"!==e&&console.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}g=await Promise.all([L(e,{model:m.model_file_name??"model"},m)])}return new this(s,...g)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(e){const t=new d.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new d.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new d.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new d.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,s=null){const r=new d.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new d.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new d.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&r.push(new d.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new d.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new d.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new d.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new d.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){const s=t>1||null===e.forced_bos_token_id?t:t+1;r.push(new d.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,s))}return null!==e.guidance_scale&&e.guidance_scale>1&&r.push(new d.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==s&&r.extend(s),r}_prepare_generation_config(e,t,s=u.GenerationConfig){const r={...this.config};for(const e of["decoder","generator","text_config"])e in r&&Object.assign(r,r[e]);const n=new s(r);return 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 s=new h.StoppingCriteriaList;return null!==e.max_length&&s.push(new h.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&s.push(new h.EosTokenCriteria(e.eos_token_id)),t&&s.extend(t),s}_validate_model_class(){if(!this.can_generate){const e=[dl,ml,cl,nl],t=I.get(this.constructor),s=new Set,r=this.config.model_type;for(const t of e){const e=t.get(r);e&&s.add(e[0])}let n=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(n+=` Please use the following class instead: ${[...s].join(", ")}`),Error(n)}}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:s,is_encoder_decoder:r}){return s.past_key_values=this.getPastKeyValues(t,s.past_key_values),s.input_ids=new p.Tensor("int64",e.flat(),[e.length,1]),r||(s.attention_mask=(0,p.cat)([s.attention_mask,(0,p.ones)([s.attention_mask.dims[0],1])],1)),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:s}){const r=(0,a.pick)(s,this.forward_params),n=this.main_input_name;if(n in r){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 r[n]=e;return{inputs_tensor:r[n],model_inputs:r,model_input_name:n}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:s,generation_config:r}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:e,pixel_values:s,attention_mask:r,...n}=t,o=await this._prepare_inputs_embeds(t);t={...n,...(0,a.pick)(o,["inputs_embeds","attention_mask"])}}let{last_hidden_state:n}=await D(this,t);if(null!==r.guidance_scale&&r.guidance_scale>1)n=(0,p.cat)([n,(0,p.full_like)(n,0)],0),"attention_mask"in t&&(t.attention_mask=(0,p.cat)([t.attention_mask,(0,p.zeros_like)(t.attention_mask)],0));else if(t.decoder_input_ids){const e=O(t.decoder_input_ids).dims[0];if(e!==n.dims[0]){if(1!==n.dims[0])throw new Error(`The encoder outputs have a different batch size (${n.dims[0]}) than the decoder inputs (${e}).`);n=(0,p.cat)(Array.from({length:e},(()=>n)),0)}}return t.encoder_outputs=n,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:s,decoder_start_token_id:r,bos_token_id:n,generation_config:o}){let{decoder_input_ids:i,...a}=s;if(!(i instanceof p.Tensor)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},(()=>i)));else if(r??=n,"musicgen"===this.config.model_type)i=Array.from({length:e*this.config.decoder.num_codebooks},(()=>[r]));else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);i=r}else i=Array.from({length:e},(()=>[r]));i=O(i)}return s.decoder_attention_mask=(0,p.ones_like)(i),{input_ids:i,model_inputs:a}}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,streamer:n=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 u=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=u+t.max_new_tokens);const _=this._get_logits_processor(t,u,s),m=this._get_stopping_criteria(t,r),h=a[l].dims.at(0),g=f.LogitsSampler.getSampler(t),w=new Array(h).fill(0),M=d.tolist();let b;n&&n.put(M);let x={};for(;;){if(a=this.prepare_inputs_for_generation(M,a,t),b=await this.forward(a),t.output_attentions&&t.return_dict_in_generate){const e=this.getAttentions(b);for(const t in e)t in x||(x[t]=[]),x[t].push(e[t])}const e=_(M,b.logits.slice(null,-1,null)),s=[];for(let t=0;t<e.dims.at(0);++t){const r=e[t],n=await g(r);for(const[e,r]of n){const n=BigInt(e);w[t]+=r,M[t].push(n),s.push([n]);break}}n&&n.put(s);if(m(M).every((e=>e)))break;a=this._update_model_kwargs_for_generation({generated_input_ids:s,outputs:b,model_inputs:a,is_encoder_decoder:c})}n&&n.end();const y=this.getPastKeyValues(b,a.past_key_values,!0),k=new p.Tensor("int64",M.flat(),[M.length,M[0].length]);if(t.return_dict_in_generate)return{sequences:k,past_key_values:y,...x};for(const e of Object.values(b))"gpu-buffer"===e.location&&e.dispose();return k}getPastKeyValues(e,t,s=!1){const r=Object.create(null);for(const n in e)if(n.startsWith("present")){const o=n.replace("present","past_key_values"),i=n.includes("encoder");if(r[o]=i&&t?t[o]:e[n],t&&(!i||s)){const e=t[o];"gpu-buffer"===e.location&&e.dispose()}}return r}getAttentions(e){const t={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const r in e)r.startsWith(s)&&(s in t||(t[s]=[]),t[s].push(e[r]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=this.sessions.decoder_model_merged??this.sessions.model,s=t?.config?.kv_cache_dtype??"float32",n="float16"===s?new Uint16Array:[],o=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,i=(0,r.getKeyValueShapes)(this.config,{batch_size:o});for(const t in i)e[t]=new p.Tensor(s,n,i[t])}}async encode_image({pixel_values:e}){const t=(await j(this.sessions.vision_encoder,{pixel_values:e})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${t.dims[1]}).`),this.config.num_image_tokens=t.dims[1]),t}async encode_text({input_ids:e}){return(await j(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}}class J{}class Y extends J{constructor({last_hidden_state:e,hidden_states:t=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=s}}class K extends H{}class Z extends K{}class ee extends K{async _call(e){return new fc(await super._call(e))}}class te extends K{async _call(e){return new _c(await super._call(e))}}class se extends K{async _call(e){return new hc(await super._call(e))}}class re extends K{async _call(e){return new gc(await super._call(e))}}class ne extends H{}class oe extends ne{}class ie extends H{}class ae extends ie{}class le extends ie{async _call(e){return new fc(await super._call(e))}}class ce extends ie{async _call(e){return new _c(await super._call(e))}}class de extends ie{async _call(e){return new hc(await super._call(e))}}class ue extends ie{async _call(e){return new gc(await super._call(e))}}class pe extends H{}class _e extends pe{}class me extends pe{async _call(e){return new fc(await super._call(e))}}class he extends pe{async _call(e){return new _c(await super._call(e))}}class fe extends pe{async _call(e){return new hc(await super._call(e))}}class ge extends pe{async _call(e){return new gc(await super._call(e))}}class we extends H{}class Me extends we{}class be extends we{async _call(e){return new fc(await super._call(e))}}class xe extends we{async _call(e){return new _c(await super._call(e))}}class ye extends we{async _call(e){return new hc(await super._call(e))}}class ke extends we{async _call(e){return new gc(await super._call(e))}}class Te extends H{}class ve extends Te{}class Pe extends Te{async _call(e){return new fc(await super._call(e))}}class Fe extends Te{async _call(e){return new _c(await super._call(e))}}class Ce extends Te{async _call(e){return new hc(await super._call(e))}}class Ae extends Te{async _call(e){return new gc(await super._call(e))}}class Se extends H{}class Ee extends Se{}class Ie extends Se{async _call(e){return new fc(await super._call(e))}}class Le extends Se{async _call(e){return new _c(await super._call(e))}}class ze extends Se{async _call(e){return new hc(await super._call(e))}}class je extends Se{async _call(e){return new gc(await super._call(e))}}class Ne extends H{}class Oe extends Ne{}class Be extends Ne{async _call(e){return new fc(await super._call(e))}}class Ve extends Ne{async _call(e){return new _c(await super._call(e))}}class De extends Ne{async _call(e){return new hc(await super._call(e))}}class Re extends Ne{async _call(e){return new gc(await super._call(e))}}class Ge extends H{}class $e extends Ge{}class qe extends Ge{async _call(e){return new _c(await super._call(e))}}class Ue extends Ge{async _call(e){return new hc(await super._call(e))}}class We extends Ge{async _call(e){return new gc(await super._call(e))}}class Xe extends Ge{async _call(e){return new fc(await super._call(e))}}class Qe extends H{}class He extends Qe{}class Je extends Qe{async _call(e){return new fc(await super._call(e))}}class Ye extends Qe{async _call(e){return new _c(await super._call(e))}}class Ke extends Qe{async _call(e){return new hc(await super._call(e))}}class Ze extends H{}class et extends Ze{}class tt extends Ze{async _call(e){return new fc(await super._call(e))}}class st extends Ze{async _call(e){return new _c(await super._call(e))}}class rt extends Ze{async _call(e){return new gc(await super._call(e))}}class nt extends H{}class ot extends nt{}class it extends nt{async _call(e){return new fc(await super._call(e))}}class at extends nt{async _call(e){return new _c(await super._call(e))}}class lt extends nt{async _call(e){return new hc(await super._call(e))}}class ct extends nt{async _call(e){return new gc(await super._call(e))}}class dt extends H{}class ut extends dt{}class pt extends dt{async _call(e){return new fc(await super._call(e))}}class _t extends dt{async _call(e){return new _c(await super._call(e))}}class mt extends dt{async _call(e){return new gc(await super._call(e))}}class ht extends H{}class ft extends ht{}class gt extends ht{async _call(e){return new _c(await super._call(e))}}class wt extends ht{async _call(e){return new gc(await super._call(e))}}class Mt extends ht{async _call(e){return new fc(await super._call(e))}}class bt extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class xt extends bt{}class yt extends bt{}class kt extends H{}class Tt extends kt{}class vt extends kt{}class Pt extends H{}class Ft extends Pt{}class Ct extends Pt{}class At extends H{}class St extends At{}class Et extends At{}class It extends At{async _call(e){return new _c(await super._call(e))}}class Lt extends H{}class zt extends Lt{}class jt extends Lt{}class Nt extends Lt{async _call(e){return new _c(await super._call(e))}}class Ot extends Lt{}class Bt extends H{}class Vt extends Bt{}class Dt extends Bt{}class Rt extends H{}class Gt extends Rt{}class $t extends Rt{}class qt extends H{}class Ut extends qt{}class Wt extends qt{async _call(e){return new fc(await super._call(e))}}class Xt extends qt{async _call(e){return new _c(await super._call(e))}}class Qt extends qt{async _call(e){return new hc(await super._call(e))}}class Ht extends qt{async _call(e){return new gc(await super._call(e))}}class Jt extends H{}class Yt extends Jt{}class Kt extends Jt{async _call(e){return new fc(await super._call(e))}}class Zt extends Jt{async _call(e){return new _c(await super._call(e))}}class es extends Jt{async _call(e){return new hc(await super._call(e))}}class ts extends Jt{async _call(e){return new gc(await super._call(e))}}class ss extends H{}class rs extends ss{}class ns extends ss{async _call(e){return new fc(await super._call(e))}}class os extends ss{async _call(e){return new _c(await super._call(e))}}class is extends ss{async _call(e){return new hc(await super._call(e))}}class as extends ss{async _call(e){return new gc(await super._call(e))}}class ls extends H{}class cs extends ls{}class ds extends ls{}class us extends H{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class ps extends us{}class _s extends us{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,w.WhisperGenerationConfig)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let s=e.language;const r=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");const n=`<|${(0,M.whisper_language_to_code)(s)}|>`;t.push(e.lang_to_id[n]),t.push(e.task_to_id[r??"transcribe"])}else if(s||r)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter((e=>null!=e))}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,...n}){t=this._prepare_generation_config(t,n);const o=n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(s??=new d.LogitsProcessorList,s.push(new d.WhisperTimeStampLogitsProcessor(t,o))),t.begin_suppress_tokens&&(s??=new d.LogitsProcessorList,s.push(new d.SuppressTokensAtBeginLogitsProcessor(t.begin_suppress_tokens,o.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");"translate"===t.task&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const i=await super.generate({inputs:e,generation_config:t,logits_processor:s,decoder_input_ids:o,...n});return t.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,t.alignment_heads,t.num_frames)),i}_extract_token_timestamps(e,t,s=null,r=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");null==s&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let n=this.config.median_filter_width;void 0===n&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),n=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},((e,t)=>(0,p.cat)(o.map((e=>e[t])),2))),l=(0,p.stack)(t.map((([e,t])=>{if(e>=i.length)throw new Error(`Layer index ${e} is out of bounds for cross attentions (length ${i.length}).`);return s?i[e].slice(null,t,null,[0,s]):i[e].slice(null,t)}))).transpose(1,0,2,3),[c,d]=(0,p.std_mean)(l,-2,0,!0),u=l.clone();for(let e=0;e<u.dims[0];++e){const t=u[e];for(let s=0;s<t.dims[0];++s){const r=t[s],o=c[e][s][0].data,i=d[e][s][0].data;for(let e=0;e<r.dims[0];++e){let t=r[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-i[e])/o[e];t.set((0,m.medianFilter)(t,n))}}}const _=[(0,p.mean)(u,1)],h=e.sequences.dims,f=new p.Tensor("float32",new Float32Array(h[0]*h[1]),h);for(let e=0;e<h[0];++e){const t=_[e].neg().squeeze_(0),[s,n]=(0,m.dynamic_time_warping)(t.tolist()),o=Array.from({length:s.length-1},((e,t)=>s[t+1]-s[t])),i=(0,a.mergeArrays)([1],o).map((e=>!!e)),l=[];for(let e=0;e<i.length;++e)i[e]&&l.push(n[e]*r);f[e].data.set(l,1)}return f}}class ms extends H{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]}class hs extends ms{}class fs extends ms{}class gs extends H{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]}class ws extends H{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]}class Ms extends ws{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:r}){const n=this.config.image_token_index,o=s.tolist().map((e=>e.findIndex((e=>e==n)))),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:r};const l=[],c=[];for(let s=0;s<o.length;++s){const n=o[s],i=e[s],a=t[s],d=r[s];l.push((0,p.cat)([i.slice([0,n]),a,i.slice([n+1,i.dims[0]])],0)),c.push((0,p.cat)([d.slice([0,n]),(0,p.ones)([a.dims[0]]),d.slice([n+1,d.dims[0]])],0))}return{inputs_embeds:(0,p.stack)(l,0),attention_mask:(0,p.stack)(c,0)}}}class bs extends Ms{}class xs extends Ms{}class ys extends H{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"}class ks extends ys{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:r}){return{inputs_embeds:(0,p.cat)([t,e],1),attention_mask:(0,p.cat)([(0,p.ones)(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:r}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,o;return e&&(n=await this.encode_text({input_ids:e})),t&&(o=await this.encode_image({pixel_values:t})),n&&o?({inputs_embeds:s,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:o,input_ids:e,attention_mask:r})):s=n||o,{inputs_embeds:s,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:s,decoder_input_ids:r,decoder_attention_mask:n,encoder_outputs:o,past_key_values:i,inputs_embeds:a,decoder_inputs_embeds:l}){if(a||({inputs_embeds:a,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:a,attention_mask:s})),!o){let{last_hidden_state:e}=await D(this,{inputs_embeds:a,attention_mask:s});o=e}if(!l){if(!r)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:r})}const c={inputs_embeds:l,attention_mask:n,encoder_attention_mask:s,encoder_hidden_states:o,past_key_values:i};return await R(this,c,!0)}}class Ts extends H{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]}class vs extends Ts{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return G({image_token_id:this.config.image_token_index,...e,image_features:s})}}class Ps extends H{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]}class Fs extends Ps{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await j(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:t})).image_features}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return G({image_token_id:this.config.image_token_id,...e,image_features:s})}}class Cs extends H{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]}class As extends Cs{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,image_sizes:r=null,position_ids:n=null,inputs_embeds:o=null,past_key_values:i=null,generation_config:a=null,logits_processor:l=null,...c}){if(!o){let t;if(s&&1!==e.dims[1]){if(!r)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await j(this.sessions.vision_encoder,{pixel_values:s,image_sizes:r}))}else{const e=this.config.normalized_config.hidden_size;t=new p.Tensor("float32",[],[0,e])}({inputs_embeds:o}=await j(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await R(this,{inputs_embeds:o,past_key_values:i,attention_mask:t,position_ids:n,generation_config:a,logits_processor:l},!1)}}class Ss extends H{}class Es extends Ss{}class Is extends Ss{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"text_model",...t})}}class Ls extends Ss{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"text_model",...t})}}class zs extends Ss{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"vision_model",...t})}}class js extends Ss{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"vision_model",...t})}}class Ns extends H{}class Os extends Ns{}class Bs extends Ns{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"text_model",...t})}}class Vs extends Ss{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"vision_model",...t})}}class Ds extends H{}class Rs extends Ds{}class Gs extends H{}class $s extends Gs{async forward(e){const t=!e.input_ids,s=!e.pixel_values;if(t&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=(0,p.ones)([e.pixel_values.dims[0],1])),s){const{image_size:t}=this.config.vision_config;e.pixel_values=(0,p.full)([0,3,t,t],0)}const{text_embeddings:r,image_embeddings:n,l2norm_text_embeddings:o,l2norm_image_embeddings:i}=await super.forward(e),a={};return t||(a.text_embeddings=r,a.l2norm_text_embeddings=o),s||(a.image_embeddings=n,a.l2norm_image_embeddings=i),a}}class qs extends Gs{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"text_model",...t})}}class Us extends Gs{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"vision_model",...t})}}class Ws extends H{}class Xs extends Ws{}class Qs extends Ws{}class Hs extends H{}class Js extends Hs{}class Ys extends Hs{}class Ks extends H{}class Zs extends Ks{}class er extends Ks{}class tr extends H{}class sr extends tr{}class rr extends tr{}class nr extends H{}class or extends nr{}class ir extends nr{}class ar extends H{}class lr extends ar{}class cr extends ar{}class dr extends H{}class ur extends dr{}class pr extends dr{}class _r extends H{}class mr extends _r{}class hr extends _r{}class fr extends H{}class gr extends fr{}class wr extends fr{}class Mr extends H{}class br extends Mr{}class xr extends Mr{}class yr extends H{}class kr extends yr{}class Tr extends yr{}class vr extends H{}class Pr extends vr{}class Fr extends vr{}class Cr extends H{}class Ar extends Cr{}class Sr extends Cr{}class Er extends H{}class Ir extends Er{}class Lr extends Er{}class zr extends H{}class jr extends zr{}class Nr extends zr{}class Or extends H{}class Br extends Or{}class Vr extends Or{}class Dr extends H{}class Rr extends Dr{}class Gr extends Dr{}class $r extends H{}class qr extends $r{}class Ur extends $r{}class Wr extends H{}class Xr extends Wr{}class Qr extends Wr{}class Hr extends H{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]}class Jr extends Hr{get_rope_index(e,t,s,r){const{vision_config:n,image_token_id:o,video_token_id:i,vision_start_token_id:a}=this.config,l=n.spatial_merge_size??2,c=[];if(t||s){let n=e.tolist();r||(r=(0,p.ones_like)(e));const d=r.tolist(),u=Array.from({length:3},(t=>Array.from({length:e.dims[0]},(t=>Array.from({length:e.dims[1]},(e=>1)))))),_=t?t.tolist():[],h=s?s.tolist():[];let f=0,g=0;for(let e=0;e<n.length;++e){const t=n[e].filter(((t,s)=>1==d[e][s])),s=t.reduce(((e,t,s)=>(t==a&&e.push(s),e)),[]).map((e=>t[e+1])),r=s.filter((e=>e==o)).length,p=s.filter((e=>e==i)).length;let w=[],M=0,b=r,x=p;for(let e=0;e<s.length;++e){const e=t.findIndex(((e,t)=>t>M&&e==o)),s=t.findIndex(((e,t)=>t>M&&e==i)),r=b>0&&-1!==e?e:t.length+1,n=x>0&&-1!==s?s:t.length+1;let a,c,d,u;r<n?([c,d,u]=_[f],++f,--b,a=r):([c,d,u]=h[g],++g,--x,a=n);const[p,y,k]=[Number(c),Math.floor(Number(d)/l),Math.floor(Number(u)/l)],T=a-M,v=w.length>0?(0,m.max)(w.at(-1))[0]+1:0;w.push(Array.from({length:3*T},((e,t)=>v+t%T)));const P=T+v,F=p*y*k,C=Array.from({length:F},((e,t)=>P+Math.floor(t/(y*k)))),A=Array.from({length:F},((e,t)=>P+Math.floor(t/k)%y)),S=Array.from({length:F},((e,t)=>P+t%k));w.push([C,A,S].flat()),M=a+F}if(M<t.length){const e=w.length>0?(0,m.max)(w.at(-1))[0]+1:0,s=t.length-M;w.push(Array.from({length:3*s},((t,r)=>e+r%s)))}const y=w.reduce(((e,t)=>e+t.length),0),k=new Array(y);let T=0;for(let e=0;e<3;++e)for(let t=0;t<w.length;++t){const s=w[t],r=s.length/3;for(let t=e*r;t<(e+1)*r;++t)k[T++]=s[t]}let v=0;const P=d[e];for(let t=0;t<P.length;++t)if(1==P[t]){for(let s=0;s<3;++s)u[s][e][t]=k[s*y/3+v];++v}const F=(0,m.max)(k)[0];c.push(F+1-n[e].length)}return[new p.Tensor("int64",u.flat(1/0),[3,e.dims[0],e.dims[1]]),new p.Tensor("int64",c,[c.length,1])]}if(r){const{data:e,dims:t}=q(r),s=BigInt64Array.from({length:3*e.length},((t,s)=>e[s%e.length])),n=Array.from({length:t[0]},((s,r)=>(0,m.max)(e.subarray(t[1]*r,t[1]*(r+1)))[0]+1+t[1]));return[new p.Tensor("int64",s,[3,...t]),new p.Tensor("int64",n,[n.length,1])]}{const[t,s]=e.dims,r=BigInt64Array.from({length:3*t*s},((e,r)=>BigInt(Math.floor(r%s/t))));return[new p.Tensor("int64",r,[3,...e.dims]),(0,p.zeros)([t,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await j(this.sessions.vision_encoder,{pixel_values:e,grid_thw:t})).image_features}_merge_input_ids_with_image_features(e){return G({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,s){if(t.attention_mask&&!t.position_ids)if(t.past_key_values){t.pixel_values=null;const e=BigInt(Object.values(t.past_key_values)[0].dims.at(-2)),s=t.rope_deltas.map((t=>e+t));t.position_ids=(0,p.stack)([s,s,s],0)}else[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);return t}}class Yr extends H{}class Kr extends Yr{}class Zr extends Yr{}class en extends H{}class tn extends en{}class sn extends en{}class rn extends H{}class nn extends rn{}class on extends rn{}class an extends H{}class ln extends an{}class cn extends an{}class dn extends H{}class un extends dn{}class pn extends dn{}class _n extends H{}class mn extends _n{}class hn extends _n{async _call(e){return new _c(await super._call(e))}}class fn extends H{}class gn extends fn{}class wn extends fn{async _call(e){return new _c(await super._call(e))}}class Mn extends H{}class bn extends Mn{}class xn extends H{}class yn extends xn{}class kn extends xn{async _call(e){return new _c(await super._call(e))}}class Tn extends H{}class vn extends Tn{}class Pn extends H{}class Fn extends Pn{}class Cn extends Pn{async _call(e){return new _c(await super._call(e))}}class An extends H{}class Sn extends An{}class En extends H{}class In extends En{}class Ln extends En{async _call(e){return new _c(await super._call(e))}}class zn extends H{}class jn extends zn{async _call(e){return new bc(await super._call(e))}}class Nn extends H{}class On extends Nn{}class Bn extends Nn{async _call(e){return new _c(await super._call(e))}}class Vn extends H{}class Dn extends Vn{}class Rn extends Vn{async _call(e){return new _c(await super._call(e))}}class Gn extends H{}class $n extends Gn{}class qn extends Gn{}class Un extends H{}class Wn extends Un{}class Xn extends Un{}class Qn extends H{}class Hn extends Qn{}class Jn extends Qn{async _call(e){return new _c(await super._call(e))}}class Yn extends H{}class Kn extends Yn{}class Zn extends Yn{async _call(e){return new to(await super._call(e))}}class eo extends Yn{async _call(e){return new so(await super._call(e))}}class to extends J{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class so extends J{constructor({logits:e,pred_boxes:t,pred_masks:s}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=s}}class ro extends H{}class no extends ro{}class oo extends ro{async _call(e){return new io(await super._call(e))}}class io extends J{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class ao extends H{}class lo extends ao{}class co extends ao{async _call(e){return new uo(await super._call(e))}}class uo extends to{}class po extends H{}class _o extends po{}class mo extends po{async _call(e){return new _c(await super._call(e))}}class ho extends H{}class fo extends ho{}class go extends ho{async _call(e){return new _c(await super._call(e))}}class wo extends H{}class Mo extends wo{}class bo extends wo{async _call(e){return new _c(await super._call(e))}}class xo extends H{}class yo extends xo{}class ko extends xo{async _call(e){return new _c(await super._call(e))}}class To extends H{}class vo extends To{}class Po extends To{}class Fo extends H{}class Co extends Fo{}class Ao extends Fo{}class So extends H{}class Eo extends So{}class Io extends H{}class Lo extends Io{}class zo extends Io{}class jo extends Io{}class No extends H{}class Oo extends No{}class Bo extends H{}class Vo extends Bo{}class Do extends Bo{}class Ro extends H{}class Go extends Ro{}class $o extends Ro{}class qo extends H{}class Uo extends qo{}class Wo extends H{}class Xo extends Wo{}class Qo extends Wo{async _call(e){return new _c(await super._call(e))}}class Ho extends H{}class Jo extends Ho{}class Yo extends Ho{async _call(e){return new _c(await super._call(e))}}class Ko extends H{}class Zo extends Ko{}class ei extends Ko{async _call(e){return new _c(await super._call(e))}}class ti extends H{}class si extends ti{}class ri extends ti{async _call(e){return new ni(await super._call(e))}}class ni extends J{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class oi extends H{}class ii extends oi{async get_image_embeddings({pixel_values:e}){return await D(this,{pixel_values:e})}async forward(e){if(e.image_embeddings&&e.image_positional_embeddings||(e={...e,...await this.get_image_embeddings(e)}),!e.input_labels&&e.input_points){const t=e.input_points.dims.slice(0,-1),s=t.reduce(((e,t)=>e*t),1);e.input_labels=new p.Tensor("int64",new BigInt64Array(s).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 j(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new ai(await super._call(e))}}class ai extends J{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class li extends H{}class ci extends li{}class di extends li{}class ui extends H{}class pi extends ui{}class _i extends ui{}class mi extends H{}class hi extends mi{}class fi extends mi{async _call(e){return new wc(await super._call(e))}}class gi extends mi{async _call(e){return new _c(await super._call(e))}}class wi extends mi{async _call(e){return new hc(await super._call(e))}}class Mi extends H{}class bi extends Mi{}class xi extends Mi{async _call(e){return new hc(await super._call(e))}}class yi extends H{}class ki extends yi{}class Ti extends H{}class vi extends Ti{}class Pi extends Ti{async _call(e){return new wc(await super._call(e))}}class Fi extends Ti{async _call(e){return new _c(await super._call(e))}}class Ci extends H{}class Ai extends Ci{}class Si extends Ci{async _call(e){return new wc(await super._call(e))}}class Ei extends Ci{async _call(e){return new _c(await super._call(e))}}class Ii extends Ci{async _call(e){return new hc(await super._call(e))}}class Li extends H{}class zi extends Li{}class ji extends Li{async _call(e){return new wc(await super._call(e))}}class Ni extends Li{async _call(e){return new _c(await super._call(e))}}class Oi extends H{}class Bi extends mi{}class Vi extends mi{async _call(e){return new wc(await super._call(e))}}class Di extends mi{async _call(e){return new _c(await super._call(e))}}class Ri extends H{}class Gi extends Ri{}class $i extends Ri{async _call(e){return new wc(await super._call(e))}}class qi extends Ri{async _call(e){return new _c(await super._call(e))}}class Ui extends Ri{async _call(e){return new mc(await super._call(e))}}class Wi extends Ri{async _call(e){return new hc(await super._call(e))}}class Xi extends H{}class Qi extends Xi{}class Hi extends Xi{}class Ji extends Xi{async generate_speech(e,t,{threshold:s=.5,minlenratio:r=0,maxlenratio:n=20,vocoder:o=null}={}){const i={input_ids:e},{encoder_outputs:a,encoder_attention_mask:l}=await D(this,i),c=a.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),u=Math.floor(c*r),_=this.config.num_mel_bins;let m=[],h=null,f=null,g=0;for(;;){++g;const e=B(!!f);let r;r=f?f.output_sequence_out:new p.Tensor("float32",new Float32Array(_),[1,1,_]);let n={use_cache_branch:e,output_sequence:r,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:a};this.addPastKeyValues(n,h),f=await j(this.sessions.decoder_model_merged,n),h=this.getPastKeyValues(f,h);const{prob:o,spectrum:i}=f;if(m.push(i),g>=u&&(Array.from(o.data).filter((e=>e>=s)).length>0||g>=d))break}const w=(0,p.cat)(m),{waveform:M}=await j(o.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:M}}}class Yi extends H{main_input_name="spectrogram"}class Ki extends H{}class Zi extends Ki{}class ea extends H{}class ta extends ea{}class sa extends ea{}class ra extends H{}class na extends ra{}class oa extends ra{}class ia extends H{}class aa extends ia{}class la extends ia{}class ca extends H{}class da extends ca{}class ua extends ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"text_model",...t})}}class pa extends ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{model_file_name:"audio_model",...t})}}class _a extends H{}class ma extends _a{async _call(e){return new xc(await super._call(e))}}class ha extends H{}class fa extends ha{}class ga extends ha{}class wa extends ha{}class Ma extends H{}class ba extends Ma{}class xa extends Ma{}class ya extends H{}class ka extends ya{}class Ta extends ya{async _call(e){return new _c(await super._call(e))}}class va extends H{}class Pa extends va{}class Fa extends va{}class Ca extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,s]=e.dims,r=this.config.decoder.num_codebooks,n=s-r;let o=0;for(let t=0;t<e.size;++t){if(e.data[t]===this.config.decoder.pad_token_id)continue;const i=t%s-Math.floor(t/s)%r;i>0&&i<=n&&(e.data[o++]=e.data[t])}const i=Math.floor(t/r),a=o/(i*r);return new p.Tensor(e.type,e.data.slice(0,o),[i,r,a])}prepare_inputs_for_generation(e,t,s){let r=structuredClone(e);for(let e=0;e<r.length;++e)for(let t=0;t<r[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(r[e][t]=BigInt(this.config.decoder.pad_token_id));null!==s.guidance_scale&&s.guidance_scale>1&&(r=r.concat(r));return super.prepare_inputs_for_generation(r,t,s)}async generate(e){const t=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await j(this.sessions.encodec_decode,{audio_codes:s});return r}}class Aa extends H{}class Sa extends Aa{}class Ea extends Aa{async _call(e){return new _c(await super._call(e))}}class Ia extends H{}class La extends Ia{}class za extends Ia{async _call(e){return new _c(await super._call(e))}}class ja extends H{}class Na extends ja{}class Oa extends ja{async _call(e){return new _c(await super._call(e))}}class Ba extends H{}class Va extends Ba{}class Da extends Ba{async _call(e){return new _c(await super._call(e))}}class Ra extends H{}class Ga extends Ra{}class $a extends H{}class qa extends $a{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let s;if("text"!==t&&e.past_key_values){const t=this.sessions.gen_img_embeds,r=(0,a.pick)({image_ids:e.input_ids},t.inputNames);s=await j(t,r)}else{const t=this.sessions.prepare_inputs_embeds,r=(0,a.pick)(e,t.inputNames);s=await j(t,r)}const r={...e,...s},n=await R(this,r),o=this.sessions["text"===t?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await j(o,(0,a.pick)(n,o.inputNames));return{...s,...n,...i}}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:n}=await j(r,{generated_tokens:s}),o=n.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),i=[];for(const e of o){const t=_.RawImage.fromTensor(e);i.push(t)}return i}}class Ua extends J{constructor({char_logits:e,bpe_logits:t,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Wa extends H{}class Xa extends Wa{async _call(e){return new Ua(await super._call(e))}}class Qa extends H{}class Ha extends Qa{}class Ja extends Qa{}class Ya extends H{}class Ka extends Ya{}class Za extends Ya{}class el{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",model_file_name:a=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:u=null,session_options:p={}}={}){const _={progress_callback:t,config:s,cache_dir:n,local_files_only:o,revision:i,model_file_name:a,subfolder:l,device:c,dtype:d,use_external_data_format:u,session_options:p};if(_.config=await r.AutoConfig.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const t of this.MODEL_CLASS_MAPPINGS){const s=t.get(_.config.model_type);if(s)return await s[1].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_.config.model_type}", attempting to construct from base class.`),await H.from_pretrained(e,_);throw Error(`Unsupported model type: ${_.config.model_type}`)}}const tl=new Map([["bert",["BertModel",Z]],["nomic_bert",["NomicBertModel",oe]],["roformer",["RoFormerModel",ae]],["electra",["ElectraModel",Me]],["esm",["EsmModel",He]],["convbert",["ConvBertModel",_e]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",Ee]],["deberta-v2",["DebertaV2Model",Oe]],["mpnet",["MPNetModel",ot]],["albert",["AlbertModel",ft]],["distilbert",["DistilBertModel",$e]],["roberta",["RobertaModel",Ut]],["xlm",["XLMModel",Yt]],["xlm-roberta",["XLMRobertaModel",rs]],["clap",["ClapModel",da]],["clip",["CLIPModel",Es]],["clipseg",["CLIPSegModel",Xs]],["chinese_clip",["ChineseCLIPModel",Rs]],["siglip",["SiglipModel",Os]],["jina_clip",["JinaCLIPModel",$s]],["mobilebert",["MobileBertModel",et]],["squeezebert",["SqueezeBertModel",ut]],["wav2vec2",["Wav2Vec2Model",hi]],["wav2vec2-bert",["Wav2Vec2BertModel",zi]],["unispeech",["UniSpeechModel",vi]],["unispeech-sat",["UniSpeechSatModel",Ai]],["hubert",["HubertModel",Bi]],["wavlm",["WavLMModel",Gi]],["audio-spectrogram-transformer",["ASTModel",cs]],["vits",["VitsModel",ma]],["pyannote",["PyAnnoteModel",bi]],["wespeaker-resnet",["WeSpeakerResNetModel",ki]],["detr",["DetrModel",Kn]],["rt_detr",["RTDetrModel",no]],["table-transformer",["TableTransformerModel",lo]],["vit",["ViTModel",mn]],["ijepa",["IJepaModel",gn]],["pvt",["PvtModel",yn]],["vit_msn",["ViTMSNModel",Fn]],["vit_mae",["ViTMAEModel",vn]],["groupvit",["GroupViTModel",Sn]],["fastvit",["FastViTModel",In]],["mobilevit",["MobileViTModel",On]],["mobilevitv2",["MobileViTV2Model",Dn]],["owlvit",["OwlViTModel",$n]],["owlv2",["Owlv2Model",Wn]],["beit",["BeitModel",Hn]],["deit",["DeiTModel",_o]],["hiera",["HieraModel",fo]],["convnext",["ConvNextModel",Xo]],["convnextv2",["ConvNextV2Model",Jo]],["dinov2",["Dinov2Model",Zo]],["resnet",["ResNetModel",Mo]],["swin",["SwinModel",yo]],["swin2sr",["Swin2SRModel",vo]],["donut-swin",["DonutSwinModel",Uo]],["yolos",["YolosModel",si]],["dpt",["DPTModel",Co]],["glpn",["GLPNModel",Go]],["hifigan",["SpeechT5HifiGan",Yi]],["efficientnet",["EfficientNetModel",ka]],["decision_transformer",["DecisionTransformerModel",Ga]],["patchtst",["PatchTSTForPrediction",Ha]],["patchtsmixer",["PatchTSMixerForPrediction",Ka]],["mobilenet_v1",["MobileNetV1Model",Sa]],["mobilenet_v2",["MobileNetV2Model",La]],["mobilenet_v3",["MobileNetV3Model",Na]],["mobilenet_v4",["MobileNetV4Model",Va]],["maskformer",["MaskFormerModel",Vo]],["mgp-str",["MgpstrForSceneTextRecognition",Xa]]]),sl=new Map([["t5",["T5Model",xt]],["longt5",["LongT5Model",Tt]],["mt5",["MT5Model",Ft]],["bart",["BartModel",St]],["mbart",["MBartModel",zt]],["marian",["MarianModel",ci]],["whisper",["WhisperModel",ps]],["m2m_100",["M2M100Model",pi]],["blenderbot",["BlenderbotModel",Vt]],["blenderbot-small",["BlenderbotSmallModel",Gt]]]),rl=new Map([["bloom",["BloomModel",nn]],["jais",["JAISModel",Zs]],["gpt2",["GPT2Model",Js]],["gptj",["GPTJModel",lr]],["gpt_bigcode",["GPTBigCodeModel",ur]],["gpt_neo",["GPTNeoModel",sr]],["gpt_neox",["GPTNeoXModel",or]],["codegen",["CodeGenModel",mr]],["llama",["LlamaModel",gr]],["exaone",["ExaoneModel",br]],["olmo",["OlmoModel",Pr]],["olmo2",["Olmo2Model",Ar]],["mobilellm",["MobileLLMModel",kr]],["granite",["GraniteModel",Ir]],["cohere",["CohereModel",jr]],["gemma",["GemmaModel",Br]],["gemma2",["Gemma2Model",Rr]],["openelm",["OpenELMModel",qr]],["qwen2",["Qwen2Model",Xr]],["phi",["PhiModel",Kr]],["phi3",["Phi3Model",tn]],["mpt",["MptModel",ln]],["opt",["OPTModel",un]],["mistral",["MistralModel",ta]],["starcoder2",["Starcoder2Model",na]],["falcon",["FalconModel",aa]],["stablelm",["StableLmModel",ba]]]),nl=new Map([["speecht5",["SpeechT5ForSpeechToText",Hi]],["whisper",["WhisperForConditionalGeneration",_s]],["moonshine",["MoonshineForConditionalGeneration",fs]]]),ol=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ji]]]),il=new Map([["vits",["VitsModel",ma]],["musicgen",["MusicgenForConditionalGeneration",Ca]]]),al=new Map([["bert",["BertForSequenceClassification",te]],["roformer",["RoFormerForSequenceClassification",ce]],["electra",["ElectraForSequenceClassification",xe]],["esm",["EsmForSequenceClassification",Ye]],["convbert",["ConvBertForSequenceClassification",he]],["camembert",["CamembertForSequenceClassification",Fe]],["deberta",["DebertaForSequenceClassification",Le]],["deberta-v2",["DebertaV2ForSequenceClassification",Ve]],["mpnet",["MPNetForSequenceClassification",at]],["albert",["AlbertForSequenceClassification",gt]],["distilbert",["DistilBertForSequenceClassification",qe]],["roberta",["RobertaForSequenceClassification",Xt]],["xlm",["XLMForSequenceClassification",Zt]],["xlm-roberta",["XLMRobertaForSequenceClassification",os]],["bart",["BartForSequenceClassification",It]],["mbart",["MBartForSequenceClassification",Nt]],["mobilebert",["MobileBertForSequenceClassification",st]],["squeezebert",["SqueezeBertForSequenceClassification",_t]]]),ll=new Map([["bert",["BertForTokenClassification",se]],["roformer",["RoFormerForTokenClassification",de]],["electra",["ElectraForTokenClassification",ye]],["esm",["EsmForTokenClassification",Ke]],["convbert",["ConvBertForTokenClassification",fe]],["camembert",["CamembertForTokenClassification",Ce]],["deberta",["DebertaForTokenClassification",ze]],["deberta-v2",["DebertaV2ForTokenClassification",De]],["mpnet",["MPNetForTokenClassification",lt]],["distilbert",["DistilBertForTokenClassification",Ue]],["roberta",["RobertaForTokenClassification",Qt]],["xlm",["XLMForTokenClassification",es]],["xlm-roberta",["XLMRobertaForTokenClassification",is]]]),cl=new Map([["t5",["T5ForConditionalGeneration",yt]],["longt5",["LongT5ForConditionalGeneration",vt]],["mt5",["MT5ForConditionalGeneration",Ct]],["bart",["BartForConditionalGeneration",Et]],["mbart",["MBartForConditionalGeneration",jt]],["marian",["MarianMTModel",di]],["m2m_100",["M2M100ForConditionalGeneration",_i]],["blenderbot",["BlenderbotForConditionalGeneration",Dt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",$t]]]),dl=new Map([["bloom",["BloomForCausalLM",on]],["gpt2",["GPT2LMHeadModel",Ys]],["jais",["JAISLMHeadModel",er]],["gptj",["GPTJForCausalLM",cr]],["gpt_bigcode",["GPTBigCodeForCausalLM",pr]],["gpt_neo",["GPTNeoForCausalLM",rr]],["gpt_neox",["GPTNeoXForCausalLM",ir]],["codegen",["CodeGenForCausalLM",hr]],["llama",["LlamaForCausalLM",wr]],["exaone",["ExaoneForCausalLM",xr]],["olmo",["OlmoForCausalLM",Fr]],["olmo2",["Olmo2ForCausalLM",Sr]],["mobilellm",["MobileLLMForCausalLM",Tr]],["granite",["GraniteForCausalLM",Lr]],["cohere",["CohereForCausalLM",Nr]],["gemma",["GemmaForCausalLM",Vr]],["gemma2",["Gemma2ForCausalLM",Gr]],["openelm",["OpenELMForCausalLM",Ur]],["qwen2",["Qwen2ForCausalLM",Qr]],["phi",["PhiForCausalLM",Zr]],["phi3",["Phi3ForCausalLM",sn]],["mpt",["MptForCausalLM",cn]],["opt",["OPTForCausalLM",pn]],["mbart",["MBartForCausalLM",Ot]],["mistral",["MistralForCausalLM",sa]],["starcoder2",["Starcoder2ForCausalLM",oa]],["falcon",["FalconForCausalLM",la]],["trocr",["TrOCRForCausalLM",Zi]],["stablelm",["StableLmForCausalLM",xa]],["phi3_v",["Phi3VForCausalLM",As]]]),ul=new Map([["multi_modality",["MultiModalityCausalLM",qa]]]),pl=new Map([["bert",["BertForMaskedLM",ee]],["roformer",["RoFormerForMaskedLM",le]],["electra",["ElectraForMaskedLM",be]],["esm",["EsmForMaskedLM",Je]],["convbert",["ConvBertForMaskedLM",me]],["camembert",["CamembertForMaskedLM",Pe]],["deberta",["DebertaForMaskedLM",Ie]],["deberta-v2",["DebertaV2ForMaskedLM",Be]],["mpnet",["MPNetForMaskedLM",it]],["albert",["AlbertForMaskedLM",Mt]],["distilbert",["DistilBertForMaskedLM",Xe]],["roberta",["RobertaForMaskedLM",Wt]],["xlm",["XLMWithLMHeadModel",Kt]],["xlm-roberta",["XLMRobertaForMaskedLM",ns]],["mobilebert",["MobileBertForMaskedLM",tt]],["squeezebert",["SqueezeBertForMaskedLM",pt]]]),_l=new Map([["bert",["BertForQuestionAnswering",re]],["roformer",["RoFormerForQuestionAnswering",ue]],["electra",["ElectraForQuestionAnswering",ke]],["convbert",["ConvBertForQuestionAnswering",ge]],["camembert",["CamembertForQuestionAnswering",Ae]],["deberta",["DebertaForQuestionAnswering",je]],["deberta-v2",["DebertaV2ForQuestionAnswering",Re]],["mpnet",["MPNetForQuestionAnswering",ct]],["albert",["AlbertForQuestionAnswering",wt]],["distilbert",["DistilBertForQuestionAnswering",We]],["roberta",["RobertaForQuestionAnswering",Ht]],["xlm",["XLMForQuestionAnswering",ts]],["xlm-roberta",["XLMRobertaForQuestionAnswering",as]],["mobilebert",["MobileBertForQuestionAnswering",rt]],["squeezebert",["SqueezeBertForQuestionAnswering",mt]]]),ml=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",gs]],["idefics3",["Idefics3ForConditionalGeneration",Fs]]]),hl=new Map([["llava",["LlavaForConditionalGeneration",Ms]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",bs]],["moondream1",["Moondream1ForConditionalGeneration",xs]],["florence2",["Florence2ForConditionalGeneration",ks]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Jr]],["idefics3",["Idefics3ForConditionalGeneration",Fs]],["paligemma",["PaliGemmaForConditionalGeneration",vs]]]),fl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",gs]]]),gl=new Map([["vit",["ViTForImageClassification",hn]],["ijepa",["IJepaForImageClassification",wn]],["pvt",["PvtForImageClassification",kn]],["vit_msn",["ViTMSNForImageClassification",Cn]],["fastvit",["FastViTForImageClassification",Ln]],["mobilevit",["MobileViTForImageClassification",Bn]],["mobilevitv2",["MobileViTV2ForImageClassification",Rn]],["beit",["BeitForImageClassification",Jn]],["deit",["DeiTForImageClassification",mo]],["hiera",["HieraForImageClassification",go]],["convnext",["ConvNextForImageClassification",Qo]],["convnextv2",["ConvNextV2ForImageClassification",Yo]],["dinov2",["Dinov2ForImageClassification",ei]],["resnet",["ResNetForImageClassification",bo]],["swin",["SwinForImageClassification",ko]],["segformer",["SegformerForImageClassification",ga]],["efficientnet",["EfficientNetForImageClassification",Ta]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ea]],["mobilenet_v2",["MobileNetV2ForImageClassification",za]],["mobilenet_v3",["MobileNetV3ForImageClassification",Oa]],["mobilenet_v4",["MobileNetV4ForImageClassification",Da]]]),wl=new Map([["detr",["DetrForObjectDetection",Zn]],["rt_detr",["RTDetrForObjectDetection",oo]],["table-transformer",["TableTransformerForObjectDetection",co]],["yolos",["YolosForObjectDetection",ri]]]),Ml=new Map([["owlvit",["OwlViTForObjectDetection",qn]],["owlv2",["Owlv2ForObjectDetection",Xn]]]),bl=new Map([["detr",["DetrForSegmentation",eo]],["clipseg",["CLIPSegForImageSegmentation",Qs]]]),xl=new Map([["segformer",["SegformerForSemanticSegmentation",wa]],["sapiens",["SapiensForSemanticSegmentation",Lo]]]),yl=new Map([["detr",["DetrForSegmentation",eo]],["maskformer",["MaskFormerForInstanceSegmentation",Do]]]),kl=new Map([["sam",["SamModel",ii]]]),Tl=new Map([["wav2vec2",["Wav2Vec2ForCTC",fi]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ji]],["unispeech",["UniSpeechForCTC",Pi]],["unispeech-sat",["UniSpeechSatForCTC",Si]],["wavlm",["WavLMForCTC",$i]],["hubert",["HubertForCTC",Vi]]]),vl=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",gi]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ni]],["unispeech",["UniSpeechForSequenceClassification",Fi]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ei]],["wavlm",["WavLMForSequenceClassification",qi]],["hubert",["HubertForSequenceClassification",Di]],["audio-spectrogram-transformer",["ASTForAudioClassification",ds]]]),Pl=new Map([["wavlm",["WavLMForXVector",Ui]]]),Fl=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ii]],["wavlm",["WavLMForAudioFrameClassification",Wi]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",wi]],["pyannote",["PyAnnoteForAudioFrameClassification",xi]]]),Cl=new Map([["vitmatte",["VitMatteForImageMatting",jn]]]),Al=new Map([["patchtst",["PatchTSTForPrediction",Ja]],["patchtsmixer",["PatchTSMixerForPrediction",Za]]]),Sl=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Po]]]),El=new Map([["dpt",["DPTForDepthEstimation",Ao]],["depth_anything",["DepthAnythingForDepthEstimation",Eo]],["glpn",["GLPNForDepthEstimation",$o]],["sapiens",["SapiensForDepthEstimation",zo]],["depth_pro",["DepthProForDepthEstimation",Oo]]]),Il=new Map([["sapiens",["SapiensForNormalEstimation",jo]]]),Ll=new Map([["vitpose",["VitPoseForPoseEstimation",bn]]]),zl=new Map([["clip",["CLIPVisionModelWithProjection",js]],["siglip",["SiglipVisionModel",Vs]],["jina_clip",["JinaCLIPVisionModel",Us]]]),jl=[[tl,b],[sl,x],[rl,T],[al,b],[ll,b],[cl,y],[nl,y],[dl,T],[ul,C],[pl,b],[_l,b],[ml,k],[hl,P],[gl,b],[bl,b],[yl,b],[xl,b],[Cl,b],[Al,b],[Sl,b],[El,b],[Il,b],[Ll,b],[wl,b],[Ml,b],[kl,v],[Tl,b],[vl,b],[ol,y],[il,b],[Pl,b],[Fl,b],[zl,b]];for(const[e,t]of jl)for(const[s,r]of e.values())S.set(s,t),I.set(r,s),E.set(s,r);const Nl=[["MusicgenForConditionalGeneration",Ca,F],["Phi3VForCausalLM",As,A],["CLIPTextModelWithProjection",Ls,b],["SiglipTextModel",Bs,b],["JinaCLIPTextModel",qs,b],["ClapTextModelWithProjection",ua,b],["ClapAudioModelWithProjection",pa,b]];for(const[e,t,s]of Nl)S.set(e,s),I.set(t,e),E.set(e,t);class Ol extends el{static MODEL_CLASS_MAPPINGS=jl.map((e=>e[0]));static BASE_IF_FAIL=!0}class Bl extends el{static MODEL_CLASS_MAPPINGS=[al]}class Vl extends el{static MODEL_CLASS_MAPPINGS=[ll]}class Dl extends el{static MODEL_CLASS_MAPPINGS=[cl]}class Rl extends el{static MODEL_CLASS_MAPPINGS=[nl]}class Gl extends el{static MODEL_CLASS_MAPPINGS=[ol]}class $l extends el{static MODEL_CLASS_MAPPINGS=[il]}class ql extends el{static MODEL_CLASS_MAPPINGS=[dl]}class Ul extends el{static MODEL_CLASS_MAPPINGS=[pl]}class Wl extends el{static MODEL_CLASS_MAPPINGS=[_l]}class Xl extends el{static MODEL_CLASS_MAPPINGS=[ml]}class Ql extends el{static MODEL_CLASS_MAPPINGS=[gl]}class Hl extends el{static MODEL_CLASS_MAPPINGS=[bl]}class Jl extends el{static MODEL_CLASS_MAPPINGS=[xl]}class Yl extends el{static MODEL_CLASS_MAPPINGS=[yl]}class Kl extends el{static MODEL_CLASS_MAPPINGS=[wl]}class Zl extends el{static MODEL_CLASS_MAPPINGS=[Ml]}class ec extends el{static MODEL_CLASS_MAPPINGS=[kl]}class tc extends el{static MODEL_CLASS_MAPPINGS=[Tl]}class sc extends el{static MODEL_CLASS_MAPPINGS=[vl]}class rc extends el{static MODEL_CLASS_MAPPINGS=[Pl]}class nc extends el{static MODEL_CLASS_MAPPINGS=[Fl]}class oc extends el{static MODEL_CLASS_MAPPINGS=[fl]}class ic extends el{static MODEL_CLASS_MAPPINGS=[Cl]}class ac extends el{static MODEL_CLASS_MAPPINGS=[Sl]}class lc extends el{static MODEL_CLASS_MAPPINGS=[El]}class cc extends el{static MODEL_CLASS_MAPPINGS=[Il]}class dc extends el{static MODEL_CLASS_MAPPINGS=[Ll]}class uc extends el{static MODEL_CLASS_MAPPINGS=[zl]}class pc extends J{constructor({logits:e,past_key_values:t,encoder_outputs:s,decoder_attentions:r=null,cross_attentions:n=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=s,this.decoder_attentions=r,this.cross_attentions=n}}class _c extends J{constructor({logits:e}){super(),this.logits=e}}class mc extends J{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class hc extends J{constructor({logits:e}){super(),this.logits=e}}class fc extends J{constructor({logits:e}){super(),this.logits=e}}class gc extends J{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class wc extends J{constructor({logits:e}){super(),this.logits=e}}class Mc extends J{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class bc extends J{constructor({alphas:e}){super(),this.alphas=e}}class xc extends J{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTFeatureExtractor:()=>o});var r=s("./src/base/feature_extraction_utils.js"),n=(s("./src/utils/tensor.js"),s("./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return(0,n.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){(0,r.validate_audio_inputs)(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const e=2*this.std,s=t.data;for(let t=0;t<s.length;++t)s[t]=(s[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}}},"./src/models/auto/feature_extraction_auto.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoFeatureExtractor:()=>i});var r=s("./src/utils/constants.js"),n=s("./src/utils/hub.js"),o=(s("./src/base/feature_extraction_utils.js"),s("./src/models/feature_extractors.js"));class i{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.FEATURE_EXTRACTOR_NAME,!0,t),i=s.feature_extractor_type,a=o[i];if(!a)throw new Error(`Unknown feature_extractor_type: '${i}'. Please report this at ${r.GITHUB_ISSUE_URL}.`);return new a(s)}}},"./src/models/auto/image_processing_auto.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoImageProcessor:()=>a});var r=s("./src/utils/constants.js"),n=s("./src/utils/hub.js"),o=s("./src/base/image_processors_utils.js"),i=s("./src/models/image_processors.js");class a{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.IMAGE_PROCESSOR_NAME,!0,t),a=s.image_processor_type??s.feature_extractor_type;let l=i[a];return l||(void 0!==a&&console.warn(`Image processor type '${a}' not found, assuming base ImageProcessor. Please report this at ${r.GITHUB_ISSUE_URL}.`),l=o.ImageProcessor),new l(s)}}},"./src/models/auto/processing_auto.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AutoProcessor:()=>c});var r=s("./src/utils/constants.js"),n=s("./src/utils/hub.js"),o=s("./src/base/processing_utils.js"),i=s("./src/models/processors.js"),a=s("./src/models/image_processors.js"),l=s("./src/models/feature_extractors.js");class c{static async from_pretrained(e,t={}){const s=await(0,n.getModelJSON)(e,r.IMAGE_PROCESSOR_NAME,!0,t),{image_processor_type:c,feature_extractor_type:d,processor_class:u}=s;if(u&&i[u])return i[u].from_pretrained(e,t);if(!c&&!d)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const p={};if(c){const e=a[c];if(!e)throw new Error(`Unknown image_processor_type: '${c}'.`);p.image_processor=new e(s)}if(d){const e=a[d];if(e)p.image_processor=new e(s);else{const e=l[d];if(!e)throw new Error(`Unknown feature_extractor_type: '${d}'.`);p.feature_extractor=new e(s)}}return new o.Processor({},p)}}},"./src/models/beit/image_processing_beit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{BeitFeatureExtractor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{BitImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ChineseCLIPFeatureExtractor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ClapFeatureExtractor:()=>o});var r=s("./src/base/feature_extraction_utils.js"),n=(s("./src/utils/tensor.js"),s("./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e),this.mel_filters=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,s,r){let n,o=!1;const i=e.length-t;if(i>0){if("rand_trunc"!==s)throw new Error(`Truncation strategy "${s}" not implemented`);{o=!0;const s=Math.floor(Math.random()*(i+1));e=e.subarray(s,s+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}}else{if(i<0){let s=new Float64Array(t);if(s.set(e),"repeat"===r)for(let r=e.length;r<t;r+=e.length)s.set(e.subarray(0,Math.min(e.length,t-r)),r);else if("repeatpad"===r)for(let t=e.length;t<-i;t+=e.length)s.set(e,t);e=s}if("fusion"===s)throw new Error(`Truncation strategy "${s}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,s=null){return(0,n.spectrogram)(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){(0,r.validate_audio_inputs)(e,"ClapFeatureExtractor");return{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}},"./src/models/clip/image_processing_clip.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/convnext/image_processing_convnext.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{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 s=Math.floor(t/this.crop_pct),[r,n]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(r,n,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class o extends n{}},"./src/models/deit/image_processing_deit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/detr/image_processing_detr.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e){const t=await super._call(e),s=[t.pixel_values.dims[0],64,64],r=(0,n.full)(s,1n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}post_process_panoptic_segmentation(...e){return(0,r.post_process_panoptic_segmentation)(...e)}post_process_instance_segmentation(...e){return(0,r.post_process_instance_segmentation)(...e)}}class i extends o{}},"./src/models/donut/image_processing_donut.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{pad_image(e,t,s,r={}){const[n,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,s,{center:!0,constant_values:c,...r})}}class o extends n{}},"./src/models/dpt/image_processing_dpt.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{EfficientNetImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{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)))}}},"./src/models/feature_extractors.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ASTFeatureExtractor:()=>r.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,ImageFeatureExtractor:()=>p.ImageProcessor,MoonshineFeatureExtractor:()=>o.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>i.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>a.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>l.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>u.WhisperFeatureExtractor});var r=s("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=s("./src/models/clap/feature_extraction_clap.js"),o=s("./src/models/moonshine/feature_extraction_moonshine.js"),i=s("./src/models/pyannote/feature_extraction_pyannote.js"),a=s("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),l=s("./src/models/speecht5/feature_extraction_speecht5.js"),c=s("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),d=s("./src/models/wespeaker/feature_extraction_wespeaker.js"),u=s("./src/models/whisper/feature_extraction_whisper.js"),p=s("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Florence2Processor:()=>i});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(e,t){super(e,t);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:r,task_prompts_with_input:n}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(r??{})),this.task_prompts_with_input=new Map(Object.entries(n??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){"string"==typeof e&&(e=[e]);const t=[];for(const s of e)if(this.task_prompts_without_inputs.has(s))t.push(this.task_prompts_without_inputs.get(s));else{for(const[e,r]of this.task_prompts_with_input)if(s.includes(e)){t.push(r.replaceAll("{input}",s).replaceAll(e,""));break}t.length!==e.length&&t.push(s)}return t}post_process_generation(e,t,s){const r=this.tasks_answer_post_processing_type.get(t)??"pure_text";let n;switch(e=e.replaceAll("<s>","").replaceAll("</s>",""),r){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const o="ocr"===r?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[o]),a=[],l=[];for(const[e,t,...r]of i)a.push(t?t.trim():a.at(-1)??""),l.push(r.map(((e,t)=>(Number(e)+.5)/this.size_per_bin*s[t%2])));n={labels:a,[o]:l};break;default:throw new Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...await this.image_processor(e,s),...t?this.tokenizer(t,s):{}}}}},"./src/models/glpn/image_processing_glpn.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{GLPNFeatureExtractor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Idefics3ImageProcessor:()=>o});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/tensor.js");class o extends r.ImageProcessor{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[s,r]=e.dims.slice(-2);const n=r/s;return r>=s?(r=Math.ceil(r/t)*t,s=Math.floor(r/n),s=Math.ceil(s/t)*t):(s=Math.ceil(s/t)*t,r=Math.floor(s*n),r=Math.ceil(r/t)*t),{height:s,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:s=!1}={}){let r;if(Array.isArray(e)){if(0===e.length||!e[0])throw new Error("No images provided.");r=Array.isArray(e[0])?e:[e]}else r=[[e]];let o=[],i=[],a=[];const l=[],c=[];for(const e of r){let s=await Promise.all(e.map((e=>this.preprocess(e))));l.push(...s.map((e=>e.original_size))),c.push(...s.map((e=>e.reshaped_input_size))),s.forEach((e=>e.pixel_values.unsqueeze_(0)));const{longest_edge:r}=this.max_image_size;let d;if(t??this.do_image_splitting){let e=new Array(s.length),t=new Array(s.length);d=await Promise.all(s.map((async(s,o)=>{const i=this.get_resize_for_vision_encoder(s.pixel_values,r),a=await(0,n.interpolate_4d)(s.pixel_values,{size:[i.height,i.width]}),{frames:l,num_splits_h:c,num_splits_w:d}=await this.split_image(a,this.max_image_size);return e[o]=c,t[o]=d,(0,n.cat)(l,0)}))),i.push(e),a.push(t)}else{const e=[r,r];d=await Promise.all(s.map((t=>(0,n.interpolate_4d)(t.pixel_values,{size:e})))),i.push(new Array(s.length).fill(0)),a.push(new Array(s.length).fill(0))}o.push((0,n.cat)(d,0))}const d=o.length,[u,p,_,m]=o[0].dims;let h,f;if(1===d)h=o[0].unsqueeze_(0),f=(0,n.full)([d,u,_,m],!0);else{const e=Math.max(...o.map((e=>e.dims.at(0))));f=(0,n.full)([d,e,_,m],!0);const t=f.data,s=e*_*m;for(let r=0;r<d;++r){const i=o[r].dims[0];if(i<e){o[r]=(0,n.cat)([o[r],(0,n.full)([e-i,p,_,m],0)],0);const a=r*s+i*_*m,l=(r+1)*s;t.fill(!1,a,l)}}h=(0,n.stack)(o,0)}return{pixel_values:h,pixel_attention_mask:f,original_sizes:l,reshaped_input_sizes:c,...s?{rows:i,cols:a}:{}}}async split_image(e,{longest_edge:t}){const s=t,r=t,o=[],[i,a]=e.dims.slice(-2);let l=0,c=0;if(i>s||a>r){l=Math.ceil(i/s),c=Math.ceil(a/r);const t=Math.ceil(i/l),d=Math.ceil(a/c);for(let s=0;s<l;++s)for(let r=0;r<c;++r){let u,p,_,m;s===l-1?(p=i-t,m=i):(p=s*t,m=(s+1)*t),r===c-1?(u=a-d,_=a):(u=r*d,_=(r+1)*d);const h=[p,u],f=[m,_],g=await(0,n.slice)(e,h,f,[2,3]);o.push(g)}const u=s,p=r;i===u&&a===p||(e=await(0,n.interpolate_4d)(e,{size:[u,p]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}}},"./src/models/idefics3/processing_idefics3.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Idefics3Processor:()=>l});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js"),i=(s("./src/utils/image.js"),s("./src/utils/core.js"));function a(e,t,s,r,n,o){return 0===e&&0===t?function(e,t,s,r){return`${t}${r}`+s.repeat(e)+`${t}`}(s,r,n,o):function(e,t,s,r,n,o){let i="";for(let o=0;o<t;++o){for(let t=0;t<s;++t)i+=r+`<row_${o+1}_col_${t+1}>`+n.repeat(e);i+="\n"}return i+=`\n${r}${o}`+n.repeat(e)+`${r}`,i}(s,e,t,r,n,o)}class l extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,s={}){let r;s.return_row_col_info??=!0,t&&(r=await this.image_processor(t,s)),Array.isArray(e)||(e=[e]);const n=r.rows??[new Array(e.length).fill(0)],o=r.cols??[new Array(e.length).fill(0)],l=this.config.image_seq_len,c=[],d=[];for(let t=0;t<e.length;++t){const s=e[t],r=n[t],u=o[t];c.push((0,i.count)(s,this.image_token));const p=r.map(((e,t)=>a(e,u[t],l,this.fake_image_token,this.image_token,this.global_img_token))),_=s.split(this.image_token);if(0===_.length)throw new Error("The image token should be present in the text.");let m=_[0];for(let e=0;e<p.length;++e)m+=p[e]+_[e+1];d.push(m)}return{...this.tokenizer(d),...r}}}},"./src/models/image_processors.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{BeitFeatureExtractor:()=>r.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>p.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>m.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>w.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>M.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>M.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>b.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>b.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>y.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>y.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>v.NougatImageProcessor,OwlViTFeatureExtractor:()=>F.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>F.OwlViTImageProcessor,Owlv2ImageProcessor:()=>P.Owlv2ImageProcessor,Phi3VImageProcessor:()=>C.Phi3VImageProcessor,PvtImageProcessor:()=>A.PvtImageProcessor,Qwen2VLImageProcessor:()=>S.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>E.RTDetrImageProcessor,SamImageProcessor:()=>I.SamImageProcessor,SegformerFeatureExtractor:()=>L.SegformerFeatureExtractor,SegformerImageProcessor:()=>L.SegformerImageProcessor,SiglipImageProcessor:()=>z.SiglipImageProcessor,Swin2SRImageProcessor:()=>j.Swin2SRImageProcessor,VLMImageProcessor:()=>h.VLMImageProcessor,ViTFeatureExtractor:()=>N.ViTFeatureExtractor,ViTImageProcessor:()=>N.ViTImageProcessor,VitMatteImageProcessor:()=>O.VitMatteImageProcessor,VitPoseImageProcessor:()=>B.VitPoseImageProcessor,YolosFeatureExtractor:()=>V.YolosFeatureExtractor,YolosImageProcessor:()=>V.YolosImageProcessor});var r=s("./src/models/beit/image_processing_beit.js"),n=s("./src/models/bit/image_processing_bit.js"),o=s("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=s("./src/models/clip/image_processing_clip.js"),a=s("./src/models/convnext/image_processing_convnext.js"),l=s("./src/models/deit/image_processing_deit.js"),c=s("./src/models/detr/image_processing_detr.js"),d=s("./src/models/donut/image_processing_donut.js"),u=s("./src/models/dpt/image_processing_dpt.js"),p=s("./src/models/efficientnet/image_processing_efficientnet.js"),_=s("./src/models/glpn/image_processing_glpn.js"),m=s("./src/models/idefics3/image_processing_idefics3.js"),h=s("./src/models/janus/image_processing_janus.js"),f=s("./src/models/jina_clip/image_processing_jina_clip.js"),g=s("./src/models/llava_onevision/image_processing_llava_onevision.js"),w=s("./src/models/mask2former/image_processing_mask2former.js"),M=s("./src/models/maskformer/image_processing_maskformer.js"),b=s("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=s("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),y=s("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=s("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=s("./src/models/mobilevit/image_processing_mobilevit.js"),v=s("./src/models/nougat/image_processing_nougat.js"),P=s("./src/models/owlv2/image_processing_owlv2.js"),F=s("./src/models/owlvit/image_processing_owlvit.js"),C=s("./src/models/phi3_v/image_processing_phi3_v.js"),A=s("./src/models/pvt/image_processing_pvt.js"),S=s("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),E=s("./src/models/rt_detr/image_processing_rt_detr.js"),I=s("./src/models/sam/image_processing_sam.js"),L=s("./src/models/segformer/image_processing_segformer.js"),z=s("./src/models/siglip/image_processing_siglip.js"),j=s("./src/models/swin2sr/image_processing_swin2sr.js"),N=s("./src/models/vit/image_processing_vit.js"),O=s("./src/models/vitmatte/image_processing_vitmatte.js"),B=s("./src/models/vitpose/image_processing_vitpose.js"),V=s("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{VLMImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map((e=>e*this.rescale_factor))}pad_image(e,t,s,r){return super.pad_image(e,t,s,{constant_values:this.constant_values,center:!0,...r})}}},"./src/models/janus/processing_janus.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{VLChatProcessor:()=>c});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js"),i=s("./src/utils/core.js"),a=s("./src/utils/tensor.js"),l=s("./src/utils/image.js");class c extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(e,t){super(e,t),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:s="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter((e=>e.images)).flatMap((e=>e.images)).map((e=>l.RawImage.read(e))));const r=this.tokenizer,n=e=>r.encode(e,{add_special_tokens:!1}),o=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}).split(this.image_tag),c=o.length-1;if(t.length!==c)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${c})`);const[d,u,p]=r.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let _=n(o[0]),m=new Array(_.length).fill(!1);for(let e=1;e<o.length;++e){const t=new Array(this.num_image_tokens).fill(d),s=n(o[e]);_=(0,i.mergeArrays)(_,[u],t,[p],s);const r=new Array(this.num_image_tokens).fill(!0);m=(0,i.mergeArrays)(m,[!1],r,[!1],new Array(s.length).fill(!1))}const h=[1,_.length],f={input_ids:new a.Tensor("int64",_,h),attention_mask:new a.Tensor("int64",new Array(_.length).fill(1),h),images_seq_mask:new a.Tensor("bool",m,h),images_emb_mask:new a.Tensor("bool",new Array(c*this.num_image_tokens).fill(!0),[1,c,this.num_image_tokens])};if(t&&t.length>0){const e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...f,...e}}return f}}},"./src/models/jina_clip/image_processing_jina_clip.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{JinaCLIPImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{constructor(e){const{resize_mode:t,fill_color:s,interpolation:r,size:n,...o}=e;super({...o,size:"squash"===t?{width:n,height:n}:"shortest"===t?{shortest_edge:n}:{longest_edge:n},resample:"bicubic"===r?3:2,do_center_crop:!0,crop_size:n,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{JinaCLIPProcessor:()=>i});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(e=null,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...e?this.tokenizer(e,s):{},...t?await this.image_processor(t,s):{}}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{LlavaOnevisionImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Mask2FormerImageProcessor:()=>n});var r=s("./src/models/maskformer/image_processing_maskformer.js");class n extends r.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_panoptic_segmentation(...e){return(0,r.post_process_panoptic_segmentation)(...e)}post_process_instance_segmentation(...e){return(0,r.post_process_instance_segmentation)(...e)}}class o extends n{}},"./src/models/mgp_str/processing_mgp_str.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MgpstrProcessor:()=>l});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js"),i=s("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!a.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[s,r]=a[t],n=this[s].bind(this),[o,l]=e.dims,c=[],d=[],u=e.tolist();for(let e=0;e<o;++e){const t=u[e],s=[],n=[];for(let e=1;e<l;++e){const[o,a]=(0,i.max)((0,i.softmax)(t[e]));if(n.push(o),a==r)break;s.push(a)}const o=n.length>0?n.reduce(((e,t)=>e*t),1):0;d.push(s),c.push(o)}return[n(d),c]}char_decode(e){return this.char_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}batch_decode([e,t,s]){const[r,n]=this._decode_helper(e,"char"),[o,a]=this._decode_helper(t,"bpe"),[l,c]=this._decode_helper(s,"wp"),d=[],u=[];for(let e=0;e<r.length;++e){const[t,s]=(0,i.max)([n[e],a[e],c[e]]);d.push([r[e],o[e],l[e]][s]),u.push(t)}return{generated_text:d,scores:u,char_preds:r,bpe_preds:o,wp_preds:l}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),s=await o.AutoTokenizer.from_pretrained("Xenova/gpt2"),r=await o.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:s,wp_tokenizer:r},t}async _call(e,t=null){const s=await this.image_processor(e);return t&&(s.labels=this.tokenizer(t).input_ids),s}}},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MoonshineFeatureExtractor:()=>o});var r=s("./src/base/feature_extraction_utils.js"),n=s("./src/utils/tensor.js");class o extends r.FeatureExtractor{async _call(e){(0,r.validate_audio_inputs)(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new n.Tensor("float32",e,t)}}}},"./src/models/moonshine/processing_moonshine.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{MoonshineProcessor:()=>i});var r=s("./src/models/auto/feature_extraction_auto.js"),n=s("./src/tokenizers.js"),o=s("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=r.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/nougat/image_processing_nougat.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{NougatImageProcessor:()=>n});var r=s("./src/models/donut/image_processing_donut.js");class n extends r.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Owlv2ImageProcessor:()=>n});var r=s("./src/models/owlvit/image_processing_owlvit.js");class n extends r.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}class o extends n{}},"./src/models/owlvit/processing_owlvit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{OwlViTProcessor:()=>i});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");class i extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor}},"./src/models/paligemma/processing_paligemma.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{PaliGemmaProcessor:()=>a});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");const i="<image>";class a extends r.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!1;async _call(e,t=null,s={}){t||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length;let o;t.some((e=>e.includes(i)))?o=t.map((e=>{const t=e.replaceAll(i,i.repeat(n)),s=t.lastIndexOf(i),o=-1===s?0:s+7;return t.slice(0,o)+r+t.slice(o)+"\n"})):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),o=t.map((t=>function(e,t,s,r,n){return`${r.repeat(s*n)}${t}${e}\n`}(t,r,n,i,e.length))));const a=this.tokenizer(o,s);return{...await this.image_processor(e,s),...a}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Phi3VImageProcessor:()=>d});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/tensor.js");const o=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class d extends r.ImageProcessor{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){const{num_img_tokens:s}=this.config;return l((l(t/o)*l(e/o)+1)*s+1+(l(t/o)+1)*c(s))}get_resize_output_image_size(e,t){const s=this._num_crops,[r,n]=e.size;let o=r/n,i=1;for(;i*Math.ceil(i/o)<=s;)i+=1;i-=1;const a=Math.floor(336*i);return[a,Math.floor(a/o)]}pad_image(e,t,s,r={}){const[n,i]=t,l=o*a(n/o),c=o*a(i/o),d=[1,1,1].map(((e,t)=>(e-this.image_mean[t])/this.image_std[t]));return super.pad_image(e,t,{width:c,height:l},{center:!0,constant_values:d,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||c(t)%1!=0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const s=e.length,r=await Promise.all(e.map((e=>this.preprocess(e)))),d=r.map((e=>e.original_size)),u=r.map((e=>e.reshaped_input_size)),p=[];for(const{pixel_values:e}of r){e.unsqueeze_(0);const[s,r]=e.dims.slice(-2),a=await(0,n.interpolate_4d)(e,{size:[o,o],mode:"bicubic"});if(t>0){const d=[],u=c(t),_=l(r/u),m=l(s/u);for(let t=0;t<u;++t)for(let o=0;o<u;++o){let a,l,c,p;t===u-1?(l=s-m,p=s):(l=t*m,p=(t+1)*m),o===u-1?(a=r-_,c=r):(a=o*_,c=(o+1)*_);const h=[l,a],f=[p,c],g=await(0,n.slice)(e,h,f,i);d.push(g)}const h=await(0,n.interpolate_4d)((0,n.cat)(d,0),{size:[o,o],mode:"bicubic"});p.push((0,n.cat)([a,h],0))}else p.push(a)}const _=(0,n.stack)(p,0),m=u.map((e=>e.map((e=>o*a(e/o)))));return{pixel_values:_,original_sizes:d,reshaped_input_sizes:u,image_sizes:new n.Tensor("int64",m.flat(),[s,2]),num_img_tokens:m.map((([e,t])=>this.calc_num_image_tokens_from_image_size(t,e)))}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Phi3VProcessor:()=>l});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");s("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(e,t=null,{padding:s=!0,truncation:r=!0,num_crops:n=null}={}){let o,l;if(Array.isArray(e)||(e=[e]),t){l=await this.image_processor(t,{num_crops:n});const{num_img_tokens:c}=l,d=e.map(((e,t)=>e.split(a).join(i.repeat(c[t]))));o=this.tokenizer(d,{padding:s,truncation:r});const u=this.tokenizer.model.convert_tokens_to_ids([i])[0];o.input_ids.map_((e=>e==u?-e:e))}else o=this.tokenizer(e);return{...o,...l}}}},"./src/models/processors.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Florence2Processor:()=>r.Florence2Processor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,MgpstrProcessor:()=>n.MgpstrProcessor,MoonshineProcessor:()=>o.MoonshineProcessor,OwlViTProcessor:()=>c.OwlViTProcessor,PaliGemmaProcessor:()=>u.PaliGemmaProcessor,Phi3VProcessor:()=>d.Phi3VProcessor,PyAnnoteProcessor:()=>p.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>m.SamProcessor,SpeechT5Processor:()=>h.SpeechT5Processor,VLChatProcessor:()=>a.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>f.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>g.WhisperProcessor});var r=s("./src/models/florence2/processing_florence2.js"),n=s("./src/models/mgp_str/processing_mgp_str.js"),o=s("./src/models/moonshine/processing_moonshine.js"),i=s("./src/models/idefics3/processing_idefics3.js"),a=s("./src/models/janus/processing_janus.js"),l=s("./src/models/jina_clip/processing_jina_clip.js"),c=s("./src/models/owlvit/processing_owlvit.js"),d=s("./src/models/phi3_v/processing_phi3_v.js"),u=s("./src/models/paligemma/processing_paligemma.js"),p=s("./src/models/pyannote/processing_pyannote.js"),_=s("./src/models/qwen2_vl/processing_qwen2_vl.js"),m=s("./src/models/sam/processing_sam.js"),h=s("./src/models/speecht5/processing_speecht5.js"),f=s("./src/models/wav2vec2/processing_wav2vec2.js"),g=s("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{PvtImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{PyAnnoteFeatureExtractor:()=>i});var r=s("./src/base/feature_extraction_utils.js"),n=s("./src/utils/tensor.js"),o=s("./src/utils/maths.js");class i extends r.FeatureExtractor{async _call(e){(0,r.validate_audio_inputs)(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new n.Tensor("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const s=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(const t of e.tolist()){const e=[];let n=-1;for(let s=0;s<t.length;++s){const r=(0,o.softmax)(t[s]),[i,a]=(0,o.max)(r),[l,c]=[s,s+1];a!==n?(n=a,e.push({id:a,start:l,end:c,score:i})):(e.at(-1).end=c,e.at(-1).score+=i)}r.push(e.map((({id:e,start:t,end:r,score:n})=>({id:e,start:t*s,end:r*s,confidence:n/(r-t)}))))}return r}}},"./src/models/pyannote/processing_pyannote.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{PyAnnoteProcessor:()=>o});var r=s("./src/base/processing_utils.js"),n=s("./src/models/pyannote/feature_extraction_pyannote.js");class o extends r.Processor{static feature_extractor_class=n.PyAnnoteFeatureExtractor;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Qwen2VLImageProcessor:()=>o});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e,...t){const{pixel_values:s,original_sizes:r,reshaped_input_sizes:o}=await super._call(e,...t);let i=s;const{temporal_patch_size:a,merge_size:l,patch_size:c}=this.config;1===i.dims[0]&&(i=(0,n.cat)(Array.from({length:a},(()=>i)),0));const d=i.dims[0]/a,u=i.dims[1],p=Math.floor(i.dims[2]/c),_=Math.floor(i.dims[3]/c);return{pixel_values:i.view(d,a,u,Math.floor(p/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(d*p*_,u*a*c*c),image_grid_thw:new n.Tensor("int64",[d,p,_],[1,3]),original_sizes:r,reshaped_input_sizes:o}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Qwen2VLProcessor:()=>i});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js"),o=s("./src/tokenizers.js");s("./src/utils/image.js");class i extends r.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(e,t=null,...s){let r,n;if(Array.isArray(e)||(e=[e]),t&&(r=await this.image_processor(t),n=r.image_grid_thw),n){let t=this.image_processor.config.merge_size**2,s=0;const r=n.tolist();e=e.map((e=>{for(;e.includes("<|image_pad|>");){const n=Number(r[s++].reduce(((e,t)=>e*t),1n));e=e.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(n/t)))}return e.replaceAll("<|placeholder|>","<|image_pad|>")}))}return{...this.tokenizer(e),...r}}}},"./src/models/rt_detr/image_processing_rt_detr.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{RTDetrImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}},"./src/models/sam/image_processing_sam.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SamImageProcessor:()=>i});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/core.js"),o=s("./src/utils/tensor.js");class i extends r.ImageProcessor{reshape_input_points(e,t,s,r=!1){e=structuredClone(e);let i=(0,n.calculateDimensions)(e);if(3===i.length)r||(i=[1,...i]),e=[e];else if(4!==i.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;r<e.length;++r){let n=t[r],o=s[r],i=[o[0]/n[0],o[1]/n[1]];for(let t=0;t<e[r].length;++t)for(let s=0;s<e[r][t].length;++s)for(let n=0;n<e[r][t][s].length;++n)e[r][t][s][n]*=i[n%2]}return new o.Tensor("float32",Float32Array.from(e.flat(1/0)),i)}add_input_labels(e,t){let s=(0,n.calculateDimensions)(e);if(2===s.length)s=[1,...s],e=[e];else if(3!==s.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some(((e,s)=>e!==t.dims[s])))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:t=null,input_labels:s=null,input_boxes:r=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),s){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(s,n.input_points)}return r&&(n.input_boxes=this.reshape_input_points(r,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,s,{mask_threshold:r=0,binarize:n=!0,pad_size:i=null}={}){const a=[],l=[(i=i??this.pad_size).height,i.width];for(let i=0;i<t.length;++i){const c=t[i],d=s[i];let u=await(0,o.interpolate_4d)(e[i],{mode:"bilinear",size:l});if(u=u.slice(null,null,[0,d[0]],[0,d[1]]),u=await(0,o.interpolate_4d)(u,{mode:"bilinear",size:c}),n){const e=u.data,t=new Uint8Array(e.length);for(let s=0;s<e.length;++s)e[s]>r&&(t[s]=1);u=new o.Tensor("bool",t,u.dims)}a.push(u)}return a}generate_crop_boxes(e,t,{crop_n_layers:s=0,overlap_ratio:r=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:o=1}={}){}}},"./src/models/sam/processing_sam.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SamProcessor:()=>o});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/image_processing_auto.js");class o extends r.Processor{static image_processor_class=n.AutoImageProcessor;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SeamlessM4TFeatureExtractor:()=>i});var r=s("./src/base/feature_extraction_utils.js"),n=s("./src/utils/tensor.js"),o=s("./src/utils/audio.js");class i extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,o.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map((e=>32768*e)),(0,o.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:s=2,do_normalize_per_mel_bins:o=!0,return_attention_mask:i=!0}={}){(0,r.validate_audio_inputs)(e,"SeamlessM4TFeatureExtractor");let a,l=await this._extract_fbank_features(e,this.config.max_length);if(o){const[e,t]=l.dims,s=l.data;for(let r=0;r<t;++r){let n=0;for(let o=0;o<e;++o)n+=s[o*t+r];const o=n/e;let i=0;for(let n=0;n<e;++n)i+=(s[n*t+r]-o)**2;i/=e-1;const a=Math.sqrt(i+1e-7);for(let n=0;n<e;++n){const e=n*t+r;s[e]=(s[e]-o)/a}}}if(t){const[e,t]=l.dims,r=l.data,o=e%s;if(o>0){const s=new Float32Array(t*(e+o));s.set(r),s.fill(this.config.padding_value,r.length);const c=e+o;l=new n.Tensor(l.type,s,[c,t]),i&&(a=new n.Tensor("int64",new BigInt64Array(c),[1,c]),a.data.fill(1n,0,e))}}const[c,d]=l.dims,u=this.config.stride;if(0!==c%u)throw new Error(`The number of frames (${c}) must be a multiple of the stride (${u}).`);const p=l.view(1,Math.floor(c/u),d*u),_={input_features:p};if(i){const e=p.dims[1],t=new BigInt64Array(e);if(a){const e=a.data;for(let s=1,r=0;s<c;s+=u,++r)t[r]=e[s]}else t.fill(1n);_.attention_mask=new n.Tensor("int64",t,[1,e])}return _}}},"./src/models/segformer/image_processing_segformer.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_semantic_segmentation(...e){return(0,r.post_process_semantic_segmentation)(...e)}}class o extends n{}},"./src/models/siglip/image_processing_siglip.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SiglipImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SpeechT5FeatureExtractor:()=>n});var r=s("./src/base/feature_extraction_utils.js");class n extends r.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{SpeechT5Processor:()=>i});var r=s("./src/base/processing_utils.js"),n=s("./src/tokenizers.js"),o=s("./src/models/auto/feature_extraction_auto.js");class i extends r.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/swin2sr/image_processing_swin2sr.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Swin2SRImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{pad_image(e,t,s,r={}){const[n,o,i]=t;return super.pad_image(e,t,{width:o+(s-o%s)%s,height:n+(s-n%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...r})}}},"./src/models/vit/image_processing_vit.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{}class o extends n{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{VitMatteImageProcessor:()=>o});var r=s("./src/base/image_processors_utils.js"),n=s("./src/utils/tensor.js");class o extends r.ImageProcessor{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=await Promise.all(e.map((e=>this.preprocess(e)))),r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))));return{pixel_values:(0,n.stack)(s.map(((e,t)=>(0,n.cat)([e.pixel_values,r[t].pixel_values],0))),0),original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{VitPoseImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_pose_estimation(e,t,{threshold:s=null}={}){const r=e.tolist(),[n,o,i,a]=e.dims,l=[];for(let e=0;e<n;++e){const n=r[e],o=t[e],c=[];for(let e=0;e<o.length;++e){const t=o[e],r=[],l=[],d=[],u=t.at(-2)/a,p=t.at(-1)/i;for(let e=0;e<n.length;++e){let[t,o]=[0,0],i=0,a=-1/0;const c=n[e];for(let e=0;e<c.length;++e){const s=c[e];for(let r=0;r<s.length;++r){const n=s[r];i+=n,a=Math.max(a,n),t+=(r+.5)*n,o+=e*n}}if(null!=s&&a<s)continue;const _=[u*t/i,p*o/i];r.push(_),d.push(e),l.push(a)}c.push({bbox:t,scores:l,labels:d,keypoints:r})}l.push(c)}return l}}},"./src/models/wav2vec2/feature_extraction_wav2vec2.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Wav2Vec2FeatureExtractor:()=>o});var r=s("./src/base/feature_extraction_utils.js"),n=s("./src/utils/tensor.js");class o extends r.FeatureExtractor{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,s=e.reduce(((e,s)=>e+(s-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(s+1e-7)))}async _call(e){(0,r.validate_audio_inputs)(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const s=[1,t.length];return{input_values:new n.Tensor("float32",t,s),attention_mask:new n.Tensor("int64",new BigInt64Array(t.length).fill(1n),s)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Wav2Vec2ProcessorWithLM:()=>o});var r=s("./src/base/processing_utils.js"),n=s("./src/models/auto/feature_extraction_auto.js");class o extends r.Processor{static feature_extractor_class=n.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{WeSpeakerFeatureExtractor:()=>o});var r=s("./src/base/feature_extraction_utils.js"),n=(s("./src/utils/tensor.js"),s("./src/utils/audio.js"));class o extends r.FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate,s=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e<s.length;++e)s[e].push(0);this.mel_filters=s,this.window=(0,n.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map((e=>32768*e)),(0,n.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,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){(0,r.validate_audio_inputs)(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){const e=t.mean(1).data,s=t.data,[r,n,o]=t.dims;for(let t=0;t<r;++t){const r=t*n*o,i=t*o;for(let t=0;t<n;++t){const n=r+t*o;for(let t=0;t<o;++t)s[n+t]-=e[i+t]}}}return{input_features:t}}}},"./src/models/whisper/common_whisper.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{WHISPER_LANGUAGE_MAPPING:()=>n,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>i});const r=[["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"]],n=new Map(r),o=new Map([...r.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"]]);function i(e){e=e.toLowerCase();let t=o.get(e);if(void 0===t){if(!n.has(e)){const t=2===e.length?n.keys():n.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(t)}`)}t=e}return t}},"./src/models/whisper/feature_extraction_whisper.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperFeatureExtractor:()=>i});var r=s("./src/base/feature_extraction_utils.js"),n=(s("./src/utils/tensor.js"),s("./src/utils/audio.js")),o=s("./src/utils/maths.js");class i extends r.FeatureExtractor{constructor(e){super(e),this.config.mel_filters??=(0,n.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,n.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await(0,n.spectrogram)(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),s=t.data,r=(0,o.max)(s)[0];for(let e=0;e<s.length;++e)s[e]=(Math.max(s[e],r-8)+4)/4;return t}async _call(e){let t;(0,r.validate_audio_inputs)(e,"WhisperFeatureExtractor"),e.length>this.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));return{input_features:(await this._extract_fbank_features(t)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperGenerationConfig:()=>n});var r=s("./src/generation/configuration_utils.js");class n extends r.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}},"./src/models/whisper/processing_whisper.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{WhisperProcessor:()=>i});var r=s("./src/models/auto/feature_extraction_auto.js"),n=s("./src/tokenizers.js"),o=s("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=r.AutoFeatureExtractor;async _call(e){return await this.feature_extractor(e)}}},"./src/models/yolos/image_processing_yolos.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>n});var r=s("./src/base/image_processors_utils.js");class n extends r.ImageProcessor{post_process_object_detection(...e){return(0,r.post_process_object_detection)(...e)}}class o extends n{}},"./src/ops/registry.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{TensorOpRegistry:()=>i});var r=s("./src/backends/onnx.js"),n=s("./src/utils/tensor.js");const o=async(e,t,s)=>{const o=await(0,r.createInferenceSession)(new Uint8Array(e),t);return async e=>{const t=Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.ort_tensor]))),r=await o.run(t);return Array.isArray(s)?s.map((e=>new n.Tensor(r[e]))):new n.Tensor(r[s])}};class i{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o([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([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}static get matmul(){return this._matmul||(this._matmul=o([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=o([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=o([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=o([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=o([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}},"./src/pipelines.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AudioClassificationPipeline:()=>C,AutomaticSpeechRecognitionPipeline:()=>S,DepthEstimationPipeline:()=>D,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>P,FillMaskPipeline:()=>M,ImageClassificationPipeline:()=>I,ImageFeatureExtractionPipeline:()=>F,ImageSegmentationPipeline:()=>L,ImageToImagePipeline:()=>V,ImageToTextPipeline:()=>E,ObjectDetectionPipeline:()=>j,Pipeline:()=>h,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>b,TextClassificationPipeline:()=>f,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>B,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>y,ZeroShotAudioClassificationPipeline:()=>A,ZeroShotClassificationPipeline:()=>v,ZeroShotImageClassificationPipeline:()=>z,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>$});var r=s("./src/tokenizers.js"),n=s("./src/models.js"),o=s("./src/models/auto/processing_auto.js"),i=(s("./src/base/processing_utils.js"),s("./src/utils/generic.js")),a=s("./src/utils/core.js"),l=s("./src/utils/maths.js"),c=s("./src/utils/audio.js"),d=s("./src/utils/tensor.js"),u=s("./src/utils/image.js");async function p(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>u.RawImage.read(e))))}async function _(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 m(e,t){t&&(e=e.map((e=>0|e)));const[s,r,n,o]=e;return{xmin:s,ymin:r,xmax:n,ymax:o}}class h extends i.Callable{constructor({task:e,model:t,tokenizer:s=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=s,this.processor=r}async dispose(){await this.model.dispose()}}class f extends h{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(s),n="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid():e=>new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),o=this.model.config.id2label,i=[];for(const e of r.logits){const s=n(e),r=await(0,d.topk)(s,t),a=r[0].tolist(),l=r[1].tolist().map(((e,t)=>({label:o?o[e]:`LABEL_${e}`,score:a[t]})));1===t?i.push(...l):i.push(l)}return Array.isArray(e)||1===t?i:i[0]}}class g extends h{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const s=Array.isArray(e),r=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),n=(await this.model(r)).logits,o=this.model.config.id2label,i=[];for(let e=0;e<n.dims[0];++e){const s=r.input_ids[e],a=n[e],c=[];for(let e=0;e<a.dims[0];++e){const r=a[e],n=(0,l.max)(r.data)[1],i=o?o[n]:`LABEL_${n}`;if(t.includes(i))continue;const d=this.tokenizer.decode([s[e].item()],{skip_special_tokens:!0});if(""===d)continue;const u=(0,l.softmax)(r.data);c.push({entity:i,score:u[n],index:e,word:d})}i.push(c)}return s?i:i[0]}}class w extends h{constructor(e){super(e)}async _call(e,t,{top_k:s=1}={}){const r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),{start_logits:n,end_logits:o}=await this.model(r),i=r.input_ids.tolist(),c=r.attention_mask.tolist(),d=this.tokenizer.all_special_ids,u=[];for(let e=0;e<n.dims[0];++e){const t=i[e],r=t.findIndex((e=>e==this.tokenizer.sep_token_id)),p=(c[e].map(((e,s)=>1==e&&(0===s||s>r&&-1===d.findIndex((e=>e==t[s]))))),n[e].tolist()),_=o[e].tolist();for(let s=1;s<p.length;++s)(0==c[e]||s<=r||-1!==d.findIndex((e=>e==t[s])))&&(p[s]=-1/0,_[s]=-1/0);const m=(0,l.softmax)(p).map(((e,t)=>[e,t])),h=(0,l.softmax)(_).map(((e,t)=>[e,t]));m[0][0]=0,h[0][0]=0;const f=(0,a.product)(m,h).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<Math.min(f.length,s);++e){const[s,r,n]=f[e],o=t.slice(s,r+1),i=this.tokenizer.decode(o,{skip_special_tokens:!0});u.push({answer:i,score:n})}}return 1===s?u[0]:u}}class M extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:r}=await this.model(s),n=[],o=s.input_ids.tolist();for(let e=0;e<o.length;++e){const s=o[e],i=s.findIndex((e=>e==this.tokenizer.mask_token_id));if(-1===i)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const a=r[e][i],c=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(a.data),a.dims),t),u=c[0].tolist(),p=c[1].tolist();n.push(p.map(((e,t)=>{const r=s.slice();return r[i]=e,{score:u[t],token:Number(e),token_str:this.tokenizer.model.vocab[e],sequence:this.tokenizer.decode(r,{skip_special_tokens:!0})}})))}return Array.isArray(e)?n:n[0]}}class b extends h{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map((e=>this.model.config.prefix+e)));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map((e=>s[this.task].prefix+e)));const r=this.tokenizer,n={padding:!0,truncation:!0};let o;o=this instanceof y&&"_build_translation_inputs"in r?r._build_translation_inputs(e,n,t):r(e,n);const i=await this.model.generate({...o,...t});return r.batch_decode(i,{skip_special_tokens:!0}).map((e=>({[this._key]:e})))}}class x extends b{_key="summary_text";constructor(e){super(e)}}class y extends b{_key="translation_text";constructor(e){super(e)}}function k(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class T extends h{constructor(e){super(e)}async _call(e,t={}){let s,r=!1,n=!1;if("string"==typeof e)s=e=[e];else if(Array.isArray(e)&&e.every((e=>"string"==typeof e)))r=!0,s=e;else{if(k(e))e=[e];else{if(!Array.isArray(e)||!e.every(k))throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");r=!0}n=!0,s=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0})))}const o=t.add_special_tokens??!1,i=!n&&(t.return_full_text??!0);this.tokenizer.padding_side="left";const a=this.tokenizer(s,{add_special_tokens:o,padding:!0,truncation:!0}),l=await this.model.generate({...a,...t}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0});let d;!i&&a.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(a.input_ids,{skip_special_tokens:!0}).map((e=>e.length)));const u=Array.from({length:e.length},(e=>[]));for(let t=0;t<c.length;++t){const s=Math.floor(t/l.dims[0]*e.length);d&&(c[t]=c[t].slice(d[s])),u[s].push({generated_text:n?[...e[s],{role:"assistant",content:c[t]}]:c[t]})}return r||1!==u.length?u:u[0]}}class v extends h{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:s="This example is {}.",multi_label:r=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const o=t.map((e=>s.replace("{}",e))),i=r||1===t.length,a=[];for(const s of e){const e=[];for(const t of o){const r=this.tokenizer(s,{text_pair:t,padding:!0,truncation:!0}),n=await this.model(r);i?e.push([n.logits.data[this.contradiction_id],n.logits.data[this.entailment_id]]):e.push(n.logits.data[this.entailment_id])}const r=(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:s,labels:r.map((e=>t[e[1]])),scores:r.map((e=>e[0]))})}return n?a:a[0]}}class P extends h{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:s=!1,quantize:r=!1,precision:n="binary"}={}){const o=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(o);let a=i.last_hidden_state??i.logits??i.token_embeddings;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 s&&(a=a.normalize(2,-1)),r&&(a=(0,d.quantize_embeddings)(a,n)),a}}class F extends h{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const s=await p(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r});let o;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");o=n.pooler_output}else o=n.last_hidden_state??n.logits??n.image_embeds;return o}}class C extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.processor.feature_extractor.config.sampling_rate,r=await _(e,s),n=this.model.config.id2label,o=[];for(const e of r){const s=await this.processor(e),r=(await this.model(s)).logits[0],i=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(r.data),r.dims),t),a=i[0].tolist(),c=i[1].tolist().map(((e,t)=>({label:n?n[e]:`LABEL_${e}`,score:a[t]})));o.push(c)}return Array.isArray(e)?o:o[0]}}class A extends h{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const n=t.map((e=>s.replace("{}",e))),o=this.tokenizer(n,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,a=await _(e,i),c=[];for(const e of a){const s=await this.processor(e),r=await this.model({...o,...s}),n=(0,l.softmax)(r.logits_per_audio.data);c.push([...n].map(((e,s)=>({score:e,label:t[s]}))))}return r?c[0]:c}}class S extends h{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(e);s&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,n=await _(e,r),o=[];for(const e of n){const t=await this.processor(e),s=(await this.model(t)).logits[0],r=[];for(const e of s)r.push((0,l.max)(e.data)[1]);const n=this.tokenizer.decode(r);o.push({text:n})}return s?o[0]:o}async _call_whisper(e,t){const s=t.return_timestamps??!1,r=t.chunk_length_s??0,n=t.force_full_sequences??!1;let o=t.stride_length_s??null;const i={...t};"word"===s&&(i.return_token_timestamps=!0,i.return_timestamps=!1);const a=!Array.isArray(e);a&&(e=[e]);const c=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,d=this.processor.feature_extractor.config.hop_length,u=this.processor.feature_extractor.config.sampling_rate,p=await _(e,u),m=[];for(const e of p){let t=[];if(r>0){if(null===o)o=r/6;else if(r<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const s=u*r,n=u*o,i=s-2*n;let a=0;for(;;){const r=a+s,o=e.subarray(a,r),l=await this.processor(o),c=0===a,d=r>=e.length;if(t.push({stride:[o.length,c?0:n,d?0:n],input_features:l.input_features,is_last:d}),d)break;a+=i}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of t){i.num_frames=Math.floor(e.stride[0]/d);const t=await this.model.generate({inputs:e.input_features,...i});"word"===s?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=t[0].tolist(),e.stride=e.stride.map((e=>e/u))}const[a,p]=this.tokenizer._decode_asr(t,{time_precision:c,return_timestamps:s,force_full_sequences:n});m.push({text:a,...p})}return a?m[0]:m}async _call_moonshine(e,t){const s=!Array.isArray(e);s&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,n=await _(e,r),o=[];for(const e of n){const s=await this.processor(e),n=6*Math.floor(e.length/r),i=await this.model.generate({max_new_tokens:n,...t,...s}),a=this.processor.batch_decode(i,{skip_special_tokens:!0})[0];o.push({text:a})}return s?o[0]:o}}class E extends h{constructor(e){super(e)}async _call(e,t={}){const s=Array.isArray(e),r=await p(e),{pixel_values:n}=await this.processor(r),o=[];for(const e of n){e.dims=[1,...e.dims];const s=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(s,{skip_special_tokens:!0}).map((e=>({generated_text:e.trim()})));o.push(r)}return s?o:o[0]}}class I extends h{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=await p(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r}),o=this.model.config.id2label,i=[];for(const e of n.logits){const s=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),t),r=s[0].tolist(),n=s[1].tolist().map(((e,t)=>({label:o?o[e]:`LABEL_${e}`,score:r[t]})));i.push(n)}return Array.isArray(e)?i:i[0]}}class L extends h{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:s=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:n=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 p(e),l=a.map((e=>[e.height,e.width])),{pixel_values:c,pixel_mask:d}=await this.processor(a),_=await this.model({pixel_values:c,pixel_mask:d});let m=null;if(null!==i)m=this.subtasks_mapping[i];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.image_processor){m=this.processor.image_processor[t].bind(this.processor.image_processor),i=e;break}const h=this.model.config.id2label,f=[];if("panoptic"===i||"instance"===i){const e=m(_,t,s,r,n,o??l)[0],i=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(i.data.length);for(let s=0;s<i.data.length;++s)i.data[s]===t.id&&(e[s]=255);const s=new u.RawImage(e,i.dims[1],i.dims[0],1);f.push({score:t.score,label:h[t.label_id],mask:s})}}else{if("semantic"!==i)throw Error(`Subtask ${i} not supported.`);{const{segmentation:e,labels:t}=m(_,o??l)[0];for(const s of t){const t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r)e.data[r]===s&&(t[r]=255);const r=new u.RawImage(t,e.dims[1],e.dims[0],1);f.push({score:null,label:h[s],mask:r})}}}return f}}class z extends h{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a photo of {}"}={}){const r=Array.isArray(e),n=await p(e),o=t.map((e=>s.replace("{}",e))),i=this.tokenizer(o,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:a}=await this.processor(n),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 s=[...d(e)].map(((e,s)=>({score:e,label:t[s]})));s.sort(((e,t)=>t.score-e.score)),u.push(s)}return r?u:u[0]}}class j extends h{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:s=!1}={}){const r=Array.isArray(e);if(r&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await p(e),o=s?null:n.map((e=>[e.height,e.width])),{pixel_values:i,pixel_mask:a}=await this.processor(n),l=await this.model({pixel_values:i,pixel_mask:a}),c=this.processor.image_processor.post_process_object_detection(l,t,o),d=this.model.config.id2label,u=c.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:d[e.classes[r]],box:m(t,!s)})))));return r?u:u[0]}}class N extends h{constructor(e){super(e)}async _call(e,t,{threshold:s=.1,top_k:r=null,percentage:n=!1}={}){const o=Array.isArray(e),i=await p(e),a=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(i),c=[];for(let e=0;e<i.length;++e){const o=i[e],d=n?null:[[o.height,o.width]],u=l.pixel_values[e].unsqueeze_(0),p=await this.model({...a,pixel_values:u}),_=this.processor.image_processor.post_process_object_detection(p,s,d,!0)[0];let h=_.boxes.map(((e,s)=>({score:_.scores[s],label:t[_.classes[s]],box:m(e,!n)}))).sort(((e,t)=>t.score-e.score));null!==r&&(h=h.slice(0,r)),c.push(h)}return o?c:c[0]}}class O extends h{constructor(e){super(e)}async _call(e,t,s={}){const r=(await p(e))[0],{pixel_values:n}=await this.processor(r),o=`<s_docvqa><s_question>${t}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,a=await this.model.generate({inputs:n,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),l=this.tokenizer.batch_decode(a)[0].match(/<s_answer>(.*?)<\/s_answer>/);let c=null;return l&&l.length>=2&&(c=l[1].trim()),[{answer:c}]}}class B extends h{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(t),r=this.model.config.sampling_rate;return{audio:s.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.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:s}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model.generate_speech(s,t,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:o}}}class V extends h{constructor(e){super(e)}async _call(e){const t=await p(e),s=await this.processor(t),r=await this.model(s),n=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(u.RawImage.fromTensor(t))}return n.length>1?n:n[0]}}class D extends h{constructor(e){super(e)}async _call(e){const t=await p(e),s=await this.processor(t),{predicted_depth:r}=await this.model(s),n=[];for(let e=0;e<t.length;++e){const s=(0,d.interpolate)(r[e],t[e].size.reverse(),"bilinear",!1),o=s.mul_(255/(0,l.max)(s.data)[0]).to("uint8");n.push({predicted_depth:r[e],depth:u.RawImage.fromTensor(o)})}return n.length>1?n:n[0]}}const R=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:f,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:g,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:w,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:M,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:x,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:y,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:b,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:T,model:n.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:v,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:C,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:A,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:S,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:B,model:[n.AutoModelForTextToWaveform,n.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:E,model:n.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:I,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:L,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:z,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:j,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:N,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:O,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:V,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:D,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:P,model:n.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:F,model:[n.AutoModelForImageFeatureExtraction,n.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),G=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $(e,t=null,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main",device:l=null,dtype:c=null,model_file_name:d=null,session_options:u={}}={}){e=G[e]??e;const p=R[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(R)}]`);t||(t=p.default.model,console.log(`No model specified. Using default model: "${t}".`));const _={progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i,device:l,dtype:c,model_file_name:d,session_options:u},m=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),h=await async function(e,t,s){const r=Object.create(null),n=[];for(const[o,i]of e.entries()){if(!i)continue;let e;e=Array.isArray(i)?new Promise((async(e,r)=>{let n;for(const o of i){if(null===o)return void e(null);try{return void e(await o.from_pretrained(t,s))}catch(e){if(e.message?.includes("Unsupported model type"))n=e;else{if(!e.message?.includes("Could not locate file"))return void r(e);n=e}}}r(n)})):i.from_pretrained(t,s),r[o]=e,n.push(e)}await Promise.all(n);for(const[e,t]of Object.entries(r))r[e]=await t;return r}(m,t,_);h.task=e,(0,a.dispatchCallback)(s,{status:"ready",task:e,model:t});return new(0,p.pipeline)(h)}},"./src/tokenizers.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{AlbertTokenizer:()=>ye,AutoTokenizer:()=>mt,BartTokenizer:()=>Ne,BertTokenizer:()=>xe,BlenderbotSmallTokenizer:()=>lt,BlenderbotTokenizer:()=>at,BloomTokenizer:()=>De,CLIPTokenizer:()=>rt,CamembertTokenizer:()=>Ee,CodeGenTokenizer:()=>st,CodeLlamaTokenizer:()=>$e,CohereTokenizer:()=>pt,ConvBertTokenizer:()=>Ce,DebertaTokenizer:()=>ve,DebertaV2Tokenizer:()=>Pe,DistilBertTokenizer:()=>Se,ElectraTokenizer:()=>Le,EsmTokenizer:()=>Qe,FalconTokenizer:()=>We,GPT2Tokenizer:()=>je,GPTNeoXTokenizer:()=>Xe,GemmaTokenizer:()=>Je,Grok1Tokenizer:()=>Ye,HerbertTokenizer:()=>Fe,LlamaTokenizer:()=>Ge,M2M100Tokenizer:()=>et,MBart50Tokenizer:()=>Be,MBartTokenizer:()=>Oe,MPNetTokenizer:()=>Ue,MarianTokenizer:()=>ot,MgpstrTokenizer:()=>_t,MobileBertTokenizer:()=>ke,NllbTokenizer:()=>Ze,NougatTokenizer:()=>dt,PreTrainedTokenizer:()=>be,Qwen2Tokenizer:()=>He,RoFormerTokenizer:()=>Ae,RobertaTokenizer:()=>Ve,SiglipTokenizer:()=>nt,SpeechT5Tokenizer:()=>ct,SqueezeBertTokenizer:()=>Te,T5Tokenizer:()=>ze,TokenizerModel:()=>k,VitsTokenizer:()=>ut,Wav2Vec2CTCTokenizer:()=>it,WhisperTokenizer:()=>tt,XLMRobertaTokenizer:()=>qe,XLMTokenizer:()=>Ie,is_chinese_char:()=>g});var r=s("./src/utils/generic.js"),n=s("./src/utils/core.js"),o=s("./src/utils/hub.js"),i=s("./src/utils/maths.js"),a=s("./src/utils/tensor.js"),l=s("./src/utils/data-structures.js"),c=s("./node_modules/@huggingface/jinja/dist/index.js"),d=s("./src/models/whisper/common_whisper.js");s("./src/utils/constants.js");async function u(e,t){const s=await Promise.all([(0,o.getModelJSON)(e,"tokenizer.json",!0,t),(0,o.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(s[1].legacy=t.legacy),s}function p(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,s]of x)t=t.replaceAll(e,s);return new RegExp(t,"gu")}if(void 0!==e.String){const s=(0,n.escapeRegExp)(e.String);return new RegExp(t?s:`(${s})`,"gu")}return console.warn("Unknown pattern type:",e),null}function _(e){return new Map(Object.entries(e))}function m(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 h(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 f(e){return e.replace(/\p{M}/gu,"")}function g(e){return e>=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}const w="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",M=new RegExp(`^[${w}]+$`,"gu"),b=".,!?…。,、।۔،",x=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],[` ?[^(\\s|[${b}])]+`,` ?[^\\s${b}]+`]]);class y{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 k extends r.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 T(e);case"Unigram":return new v(e,...t);case"BPE":return new C(e);default:if(e.vocab)return Array.isArray(e.vocab)?new v(e,...t):new A(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return e=this.encode(e),this.fuse_unk&&(e=function(e,t,s){const r=[];let n=0;for(;n<e.length;)if(r.push(e[n]),(t.get(e[n])??s)===s)for(;++n<e.length&&(t.get(e[n])??s)===s;)t.get(r.at(-1))!==s&&(r[r.length-1]+=e[n]);else++n;return r}(e,this.tokens_to_ids,this.unk_token_id)),e}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){return e.map((e=>this.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 T extends k{constructor(e){super(e),this.tokens_to_ids=_(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.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 s of e){const e=[...s];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,n=0;const o=[];for(;n<e.length;){let t=e.length,s=null;for(;n<t;){let r=e.slice(n,t).join("");if(n>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){s=r;break}--t}if(null===s){r=!0;break}o.push(s),n=t}r?t.push(this.unk_token):t.push(...o)}return t}}class v extends k{constructor(e,t){super(e);const s=e.vocab.length;this.vocab=new Array(s),this.scores=new Array(s);for(let t=0;t<s;++t){const s=e.vocab[t];this.vocab[t]=s[0],this.scores[t]=s[1]}this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map(((e,t)=>[e,t]))),this.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.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.chars;let s=0;for(;s<t.length;){let r=!1;const o=[],i=t.slice(s).join(""),a=this.trie.commonPrefixSearch(i);for(const t of a){o.push(t);const i=this.tokens_to_ids.get(t),a=this.scores[i],l=(0,n.len)(t);e.insert(s,l,a,i),r||1!==l||(r=!0)}r||e.insert(s,1,this.unk_score,this.unk_token_id),s+=1}}tokenize(e){const t=new l.TokenLattice(e,this.bos_token_id,this.eos_token_id);return this.populateNodes(t),t.tokens()}encode(e){const t=[];for(const s of e){const e=this.tokenize(s);t.push(...e)}return t}}const P=(()=>{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 s=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+s),s+=1);const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})(),F=(0,n.reverseDictionary)(P);class C extends k{constructor(e){super(e),this.tokens_to_ids=_(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map((e=>e.split(" ",2))),this.bpe_ranks=new Map(this.merges.map(((e,t)=>[JSON.stringify(e),t]))),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.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const s=Array.from(e);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let r=[];if(s.length>1){const e=new l.PriorityQueue(((e,t)=>e.score<t.score));let t={token:s[0],bias:0,prev:null,next:null},n=t;for(let t=1;t<s.length;++t){const r={bias:t/s.length,token:s[t],prev:n,next:null};n.next=r,this._add_node(e,n),n=r}for(;!e.isEmpty();){const s=e.pop();if(s.deleted||!s.next||s.next.deleted)continue;if(s.deleted=!0,s.next.deleted=!0,s.prev){const e={...s.prev};s.prev.deleted=!0,s.prev=e,e.prev?e.prev.next=e:t=e}const r={token:s.token+s.next.token,bias:s.bias,prev:s.prev,next:s.next.next};r.prev?(r.prev.next=r,this._add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this._add_node(e,r))}for(let e=t;null!==e;e=e.next)r.push(e.token)}else r=s;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return this.cache.set(e,r),r}_add_node(e,t){const s=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));void 0!==s&&(t.score=s+t.bias,e.push(t))}encode(e){const t=[];for(const s of e){if(this.ignore_merges&&this.tokens_to_ids.has(s)){t.push(s);continue}const e=this.bpe(s);for(const s of e)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const e=Array.from(this.text_encoder.encode(s)).map((e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`));e.every((e=>this.tokens_to_ids.has(e)))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}}class A extends k{constructor(e,t){super(e),this.tokens_to_ids=_(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 S extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new D(e);case"Precompiled":return new pe(e);case"Sequence":return new V(e);case"Replace":return new E(e);case"NFC":return new I(e);case"NFKC":return new L(e);case"NFKD":return new z(e);case"Strip":return new j(e);case"StripAccents":return new N(e);case"Lowercase":return new O(e);case"Prepend":return new B(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 E extends S{normalize(e){const t=p(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class I extends S{normalize(e){return e=e.normalize("NFC")}}class L extends S{normalize(e){return e=e.normalize("NFKC")}}class z extends S{normalize(e){return e=e.normalize("NFKD")}}class j extends S{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 N extends S{normalize(e){return e=f(e)}}class O extends S{normalize(e){return e=e.toLowerCase()}}class B extends S{normalize(e){return e=this.config.prepend+e}}class V extends S{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>S.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class D extends S{_tokenize_chinese_chars(e){const t=[];for(let s=0;s<e.length;++s){const r=e[s];g(r.charCodeAt(0))?(t.push(" "),t.push(r),t.push(" ")):t.push(r)}return t.join("")}stripAccents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}_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 s of e){const e=s.charCodeAt(0);0===e||65533===e||this._is_control(s)||(/^\s$/.test(s)?t.push(" "):t.push(s))}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 R extends r.Callable{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new G(e);case"Sequence":return new _e(e);case"Whitespace":return new me(e);case"WhitespaceSplit":return new he(e);case"Metaspace":return new de(e);case"ByteLevel":return new $(e);case"Split":return new q(e);case"Punctuation":return new U(e);case"Digits":return new W(e);case"Replace":return new fe(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 G extends R{constructor(e){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class $ extends R{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=P,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 q extends R{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:"removed"===this.config.behavior?.toLowerCase()?e.split(this.pattern).filter((e=>e)):function(e,t){const s=[];let r=0;for(const n of e.matchAll(t)){const t=n[0];r<n.index&&s.push(e.slice(r,n.index)),t.length>0&&s.push(t),r=n.index+t.length}return r<e.length&&s.push(e.slice(r)),s}(e,this.pattern)}}class U extends R{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class W extends R{constructor(e){super(),this.config=e;const t="[^\\d]+|\\d"+(this.config.individual_digits?"":"+");this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class X extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new J(e);case"ByteLevel":return new Y(e);case"RobertaProcessing":return new H(e);case"BertProcessing":return new Q(e);case"Sequence":return new K(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class Q extends X{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null,{add_special_tokens:s=!0}={}){s&&(e=(0,n.mergeArrays)([this.cls],e,[this.sep]));let r=new Array(e.length).fill(0);if(null!==t){const o=s&&this instanceof H?[this.sep]:[],i=s?[this.sep]:[];e=(0,n.mergeArrays)(e,o,t,i),r=(0,n.mergeArrays)(r,new Array(t.length+o.length+i.length).fill(1))}return{tokens:e,token_type_ids:r}}}class H extends Q{}class J extends X{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null,{add_special_tokens:s=!0}={}){const r=null===t?this.single:this.pair;let o=[],i=[];for(const a of r)"SpecialToken"in a?s&&(o.push(a.SpecialToken.id),i.push(a.SpecialToken.type_id)):"Sequence"in a&&("A"===a.Sequence.id?(o=(0,n.mergeArrays)(o,e),i=(0,n.mergeArrays)(i,new Array(e.length).fill(a.Sequence.type_id))):"B"===a.Sequence.id&&(o=(0,n.mergeArrays)(o,t),i=(0,n.mergeArrays)(i,new Array(t.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:i}}}class Y extends X{post_process(e,t=null){return t&&(e=(0,n.mergeArrays)(e,t)),{tokens:e}}}class K extends X{constructor(e){super(e),this.processors=e.processors.map((e=>X.fromConfig(e)))}post_process(e,t=null,s={}){let r;for(const n of this.processors)if(n instanceof Y){if(e=n.post_process(e).tokens,t){t=n.post_process(t).tokens}}else{const o=n.post_process(e,t,s);e=o.tokens,r=o.token_type_ids}return{tokens:e,token_type_ids:r}}}class Z extends r.Callable{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(null===e)return null;switch(e.type){case"WordPiece":return new ne(e);case"Metaspace":return new ue(e);case"ByteLevel":return new oe(e);case"Replace":return new ee(e);case"ByteFallback":return new te(e);case"Fuse":return new se(e);case"Strip":return new re(e);case"Sequence":return new ae(e);case"CTC":return new ie(e);case"BPEDecoder":return new le(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends Z{decode_chain(e){const t=p(this.config.pattern);return null===t?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class te extends Z{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let s=[];for(const r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)s.push(e);else{if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}t.push(r)}}if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}return t}}class se extends Z{decode_chain(e){return[e.join("")]}}class re extends Z{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 s=0;s<this.start&&e[s]===this.content;++s)t=s+1;let s=e.length;for(let t=0;t<this.stop;++t){const r=e.length-t-1;if(e[r]!==this.content)break;s=r}return e.slice(t,s)}))}}class ne extends Z{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map(((e,t)=>(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=h(e)),e)))}}class oe extends Z{constructor(e){super(e),this.byte_decoder=F,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(""),s=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(s)}decode_chain(e){const t=[];let s=[];for(const r of e)void 0!==this.added_tokens.find((e=>e.content===r))?(s.length>0&&(t.push(this.convert_tokens_to_string(s)),s=[]),t.push(r)):s.push(r);return s.length>0&&t.push(this.convert_tokens_to_string(s)),t}}class ie extends Z{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 s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let s=t.filter((e=>e!==this.pad_token)).join("");return this.cleanup&&(s=h(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class ae extends Z{constructor(e){super(e),this.decoders=e.decoders.map((e=>Z.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class le extends Z{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,s)=>t.replaceAll(this.suffix,s===e.length-1?"":" ")))}}class ce extends Z{decode_chain(e){let t="";for(let s=1;s<e.length;s+=2)t+=e[s];return[t]}}class de extends R{constructor(e){super(),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement,this.strRep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,{section_index:t}={}){let s=e.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!s.startsWith(this.replacement)&&("always"===this.prepend_scheme||"first"===this.prepend_scheme&&0===t)&&(s=this.strRep+s),[s]}}class ue extends Z{constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){const t=[];for(let s=0;s<e.length;++s){let r=e[s].replaceAll(this.replacement," ");this.addPrefixSpace&&0==s&&r.startsWith(" ")&&(r=r.substring(1)),t.push(r)}return t}}class pe extends S{constructor(e){super(e),this.charsmap=e.precompiled_charsmap}normalize(e){if((e=(e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"")).replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," ")).includes("~")){const t=e.split("~");e=t.map((e=>e.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class _e extends R{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>R.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,s)=>s.pre_tokenize(e,t)),[e])}}class me extends R{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class he extends R{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class fe extends R{constructor(e){super(),this.config=e,this.pattern=p(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 ge=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function we(e,t,s,r){for(const o of Object.keys(e)){const i=t-e[o].length,a=s(o),l=new Array(i).fill(a);e[o]="right"===r?(0,n.mergeArrays)(e[o],l):(0,n.mergeArrays)(l,e[o])}}function Me(e,t){for(const s of Object.keys(e))e[s].length=t}class be extends r.Callable{return_token_type_ids=!1;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=S.fromConfig(e.normalizer),this.pre_tokenizer=R.fromConfig(e.pre_tokenizer),this.model=k.fromConfig(e.model,t),this.post_processor=X.fromConfig(e.post_processor),this.decoder=Z.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new y(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.slice().sort(((e,t)=>t.content.length-e.content.length)).map((e=>`${e.lstrip?"\\s*":""}(${(0,n.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.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_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:s}of this.chat_template){if("string"!=typeof t||"string"!=typeof s)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=s}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:s=null,cache_dir:r=null,local_files_only:n=!1,revision:o="main",legacy:i=null}={}){return new this(...await u(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:o,legacy:i}))}_call(e,{text_pair:t=null,add_special_tokens:s=!0,padding:r=!1,truncation:n=null,max_length:o=null,return_tensor:l=!0,return_token_type_ids:c=null}={}){const d=Array.isArray(e);let u;if(d){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");u=e.map(((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:s,return_token_type_ids:c})))}else u=e.map((e=>this._encode_plus(e,{add_special_tokens:s,return_token_type_ids:c})))}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).");u=[this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:c})]}if(null===o?o="max_length"===r?this.model_max_length:(0,i.max)(u.map((e=>e.input_ids.length)))[0]:n||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??1/0),r||n)for(let e=0;e<u.length;++e)u[e].input_ids.length!==o&&(u[e].input_ids.length>o?n&&Me(u[e],o):r&&we(u[e],o,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const p={};if(l){if((!r||!n)&&u.some((e=>{for(const t of Object.keys(e))if(e[t].length!==u[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=[u.length,u[0].input_ids.length];for(const t of Object.keys(u[0]))p[t]=new a.Tensor("int64",BigInt64Array.from(u.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(u[0]))p[e]=u.map((t=>t[e]));if(!d)for(const e of Object.keys(p))p[e]=p[e][0]}return p}_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 f(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const s=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(s)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){const{tokens:n,token_type_ids:o}=this._tokenize_helper(e,{pair:t,add_special_tokens:s}),i=this.model.convert_tokens_to_ids(n),a={input_ids:i,attention_mask:new Array(i.length).fill(1)};return(r??this.return_token_type_ids)&&o&&(a.token_type_ids=o),a}_tokenize_helper(e,{pair:t=null,add_special_tokens:s=!1}={}){const r=this._encode_text(e),o=this._encode_text(t);return this.post_processor?this.post_processor(r,o,{add_special_tokens:s}):{tokens:(0,n.mergeArrays)(r??[],o??[])}}tokenize(e,{pair:t=null,add_special_tokens:s=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:s}).tokens}encode(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:r}).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=m(e)),!Array.isArray(e)||0===e.length||!(0,n.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:s=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter((e=>!this.special_tokens.includes(e))));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t&&(n=n.trim())),(s??this.clean_up_tokenization_spaces)&&(n=h(n)),n}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){const s=this.chat_template;if(null!==e&&Object.hasOwn(s,e))e=s[e];else if(null===e)if(null!==t&&"tool_use"in s)e=s.tool_use;else{if(!("default"in s))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(s).sort()}.`);e=s.default}}else if(null===e){if(!this.chat_template)throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");e=this.chat_template}return e}apply_chat_template(e,{tools:t=null,documents:s=null,chat_template:r=null,add_generation_prompt:n=!1,tokenize:o=!0,padding:i=!1,truncation:a=!1,max_length:l=null,return_tensor:d=!0,return_dict:u=!1,tokenizer_kwargs:p={},..._}={}){if("string"!=typeof(r=this.get_chat_template({chat_template:r,tools:t})))throw Error("chat_template must be a string, but got "+typeof r);let m=this._compiled_template_cache.get(r);void 0===m&&(m=new c.Template(r),this._compiled_template_cache.set(r,m));const h=Object.create(null);for(const e of ge){const t=this.getToken(e);t&&(h[e]=t)}const f=m.render({messages:e,add_generation_prompt:n,tools:t,documents:s,...h,..._});if(o){const e=this._call(f,{add_special_tokens:!1,padding:i,truncation:a,max_length:l,return_tensor:d,...p});return u?e:e.input_ids}return f}}class xe extends be{return_token_type_ids=!0}class ye extends be{return_token_type_ids=!0}class ke extends be{return_token_type_ids=!0}class Te extends be{return_token_type_ids=!0}class ve extends be{return_token_type_ids=!0}class Pe extends be{return_token_type_ids=!0}class Fe extends be{return_token_type_ids=!0}class Ce extends be{return_token_type_ids=!0}class Ae extends be{return_token_type_ids=!0}class Se extends be{}class Ee extends be{}class Ie extends be{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 Le extends be{return_token_type_ids=!0}class ze extends be{}class je extends be{}class Ne extends be{}class Oe extends be{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,s){return Ke(this,e,t,s)}}class Be extends Oe{}class Ve extends be{}class De extends be{}const Re="▁";class Ge extends be{padding_side="left";constructor(e,t){super(e,t),this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new de({replacement:Re,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(Re+e.replaceAll(Re," "));return t.length>1&&t[0]===Re&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}}class $e extends be{}class qe extends be{}class Ue extends be{}class We extends be{}class Xe extends be{}class Qe extends be{}class He extends be{}class Je extends be{}class Ye extends be{}function Ke(e,t,s,r){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 n=r.src_lang,o=r.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!==n){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" 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(n);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(o)])[0],e._call(t,s)}class Ze extends be{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,s){return Ke(this,e,t,s)}}class et extends be{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,s){return Ke(this,e,t,s)}}class tt extends be{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:s=!1,time_precision:r=null,force_full_sequences:n=!0}={}){if(null===r)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 u=l(),p=0;const _=this.timestamp_begin,m=_+1500;let h=[],f=[],g=!1,w=null;const b=new Set(this.all_special_ids);for(const s of e){const e=s.tokens,n=a?s.token_timestamps:null;let x=null,y=_;if("stride"in s){const[t,n,o]=s.stride;if(p-=n,w=t-o,n&&(y=n/r+_),o)for(let t=e.length-1;t>=0;--t){const s=Number(e[t]);if(s>=_){if(null!==x&&(s-_)*r<w)break;x=s}}}let k=[],T=[];for(let s=0;s<e.length;++s){const w=Number(e[s]);if(b.has(w)){const e=this.decode([w]),s=d.WHISPER_LANGUAGE_MAPPING.get(e.slice(2,-2));if(void 0!==s){if(null!==o&&s!==o&&!t){h.push(k);const e=this.findLongestCommonSequence(h)[0],t=this.decode(e);u.text=t,c.push(u),h=[],k=[],u=l()}o=u.language=s}}else if(w>=_&&w<=m){const e=(w-_)*r+p,t=(0,i.round)(e,2);if(null!==x&&w>=x)g=!0;else if(g||h.length>0&&w<y)g=!1;else if(null===u.timestamp[0])u.timestamp[0]=t;else if(t===u.timestamp[0]);else{u.timestamp[1]=t,h.push(k),a&&f.push(T);const[e,s]=this.findLongestCommonSequence(h,f),r=this.decode(e);u.text=r,a&&(u.words=this.collateWordTimestamps(e,s,o)),c.push(u),h=[],k=[],f=[],T=[],u=l()}}else if(k.push(w),a){let e,t=(0,i.round)(n[s]+p,2);if(s+1<n.length){e=(0,i.round)(n[s+1]+p,2);const o=this.decode([w]);M.test(o)&&(e=(0,i.round)(Math.min(t+r,e),2))}else e=null;T.push([t,e])}}if("stride"in s){const[e,t,r]=s.stride;p+=e-r}k.length>0?(h.push(k),a&&f.push(T)):h.every((e=>0===e.length))&&(u=l(),h=[],k=[],f=[],T=[])}if(h.length>0){if(n&&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,s]=this.findLongestCommonSequence(h,f),r=this.decode(e);u.text=r,a&&(u.words=this.collateWordTimestamps(e,s,o)),c.push(u)}let x=Object.create(null);const y=c.map((e=>e.text)).join("");if(t||s){for(let e=0;e<c.length;++e){const r=c[e];t||delete r.timestamp,s||delete r.language}if(a){const e=[];for(const t of c)for(const s of t.words)e.push(s);x={chunks:e}}else x={chunks:c}}return[y,x]}findLongestCommonSequence(e,t=null){let s=e[0],r=s.length,n=[];const o=Array.isArray(t)&&t.length>0;let i=o?[]:null,a=o?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,u=[r,r,0,0];const p=c.length;for(let e=1;e<r+p;++e){const n=Math.max(0,r-e),i=Math.min(r,r+p-e),_=s.slice(n,i),m=Math.max(0,e-r),h=Math.min(p,e),f=c.slice(m,h);if(_.length!==f.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let g;g=o?_.filter(((e,s)=>e===f[s]&&a[n+s]<=t[l][m+s])).length:_.filter(((e,t)=>e===f[t])).length;const w=g/e+e/1e4;g>1&&w>d&&(d=w,u=[n,i,m,h])}const[_,m,h,f]=u,g=Math.floor((m+_)/2),w=Math.floor((f+h)/2);n.push(...s.slice(0,g)),s=c.slice(w),r=s.length,o&&(i.push(...a.slice(0,g)),a=t[l].slice(w))}return n.push(...s),o?(i.push(...a),[n,i]):[n,[]]}collateWordTimestamps(e,t,s){const[r,n,o]=this.combineTokensIntoWords(e,s),i=[];for(let e=0;e<r.length;++e){const s=o[e];i.push({text:r[e],timestamp:[t[s.at(0)][0],t[s.at(-1)][1]]})}return i}combineTokensIntoWords(e,t,s="\"'“¡¿([{-",r="\"'.。,,!!??::”)]}、"){let n,o,i;return["chinese","japanese","thai","lao","myanmar"].includes(t=t??"english")?[n,o,i]=this.splitTokensOnUnicode(e):[n,o,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,o,i,s,r)}decode(e,t){let s;return t?.decode_with_timestamps?(e instanceof a.Tensor&&(e=m(e)),s=this.decodeWithTimestamps(e,t)):s=super.decode(e,t),s}decodeWithTimestamps(e,t){const s=t?.time_precision??.02,r=Array.from(this.all_special_ids).at(-1)+1;let n=[[]];for(let t of e)if(t=Number(t),t>=r){const e=((t-r)*s).toFixed(2);n.push(`<|${e}|>`),n.push([])}else n[n.length-1].push(t);return n=n.map((e=>"string"==typeof e?e:super.decode(e,t))),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),s=[],r=[],n=[];let o=[],i=[],a=0;for(let l=0;l<e.length;++l){const c=e[l];o.push(c),i.push(l);const d=this.decode(o,{decode_with_timestamps:!0});d.includes("�")&&"�"!==t[a+d.indexOf("�")]||(s.push(d),r.push(o),n.push(i),o=[],i=[],a+=d.length)}return[s,r,n]}splitTokensOnSpaces(e){const[t,s,r]=this.splitTokensOnUnicode(e),n=[],o=[],i=[],a=new RegExp(`^[${w}]$`,"gu");for(let e=0;e<t.length;++e){const l=t[e],c=s[e],d=r[e],u=c[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),p=l.startsWith(" "),_=l.trim(),m=a.test(_);if(u||p||m||0===n.length)n.push(l),o.push(c),i.push(d);else{const e=n.length-1;n[e]+=l,o[e].push(...c),i[e].push(...d)}}return[n,o,i]}mergePunctuations(e,t,s,r,o){const i=structuredClone(e),a=structuredClone(t),l=structuredClone(s);let c=i.length-2,d=i.length-1;for(;c>=0;)i[c].startsWith(" ")&&r.includes(i[c].trim())?(i[d]=i[c]+i[d],a[d]=(0,n.mergeArrays)(a[c],a[d]),l[d]=(0,n.mergeArrays)(l[c],l[d]),i[c]="",a[c]=[],l[c]=[]):d=c,--c;for(c=0,d=1;d<i.length;)!i[c].endsWith(" ")&&o.includes(i[d])?(i[c]+=i[d],a[c]=(0,n.mergeArrays)(a[c],a[d]),l[c]=(0,n.mergeArrays)(l[c],l[d]),i[d]="",a[d]=[],l[d]=[]):c=d,++d;return[i.filter((e=>e)),a.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}}class st extends be{}class rt extends be{}class nt extends be{}class ot extends be{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,...s]=e.trim().split(this.languageRegex);if(0===s.length)return super._encode_text(t);if(2===s.length){const[e,t]=s;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,n.mergeArrays)([e],super._encode_text(t))}}}class it extends be{}class at extends be{}class lt extends be{}class ct extends be{}class dt extends be{}class ut extends be{constructor(e,t){super(e,t),this.decoder=new ce({})}}class pt extends be{}class _t extends be{}class mt{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:ze,DistilBertTokenizer:Se,CamembertTokenizer:Ee,DebertaTokenizer:ve,DebertaV2Tokenizer:Pe,BertTokenizer:xe,HerbertTokenizer:Fe,ConvBertTokenizer:Ce,RoFormerTokenizer:Ae,XLMTokenizer:Ie,ElectraTokenizer:Le,MobileBertTokenizer:ke,SqueezeBertTokenizer:Te,AlbertTokenizer:ye,GPT2Tokenizer:je,BartTokenizer:Ne,MBartTokenizer:Oe,MBart50Tokenizer:Be,RobertaTokenizer:Ve,WhisperTokenizer:tt,CodeGenTokenizer:st,CLIPTokenizer:rt,SiglipTokenizer:nt,MarianTokenizer:ot,BloomTokenizer:De,NllbTokenizer:Ze,M2M100Tokenizer:et,LlamaTokenizer:Ge,CodeLlamaTokenizer:$e,XLMRobertaTokenizer:qe,MPNetTokenizer:Ue,FalconTokenizer:We,GPTNeoXTokenizer:Xe,EsmTokenizer:Qe,Wav2Vec2CTCTokenizer:it,BlenderbotTokenizer:at,BlenderbotSmallTokenizer:lt,SpeechT5Tokenizer:ct,NougatTokenizer:dt,VitsTokenizer:ut,Qwen2Tokenizer:He,GemmaTokenizer:Je,Grok1Tokenizer:Ye,CohereTokenizer:pt,MgpstrTokenizer:_t,PreTrainedTokenizer:be};static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:o="main",legacy:i=null}={}){const[a,l]=await u(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:o,legacy:i}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let d=this.TOKENIZER_CLASS_MAPPING[c];return d||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),d=be),new d(a,l)}}},"./src/utils/audio.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{hamming:()=>d,hanning:()=>c,mel_filter_bank:()=>h,read_audio:()=>a,spectrogram:()=>g,window_function:()=>w});var r=s("./src/utils/hub.js"),n=s("./src/utils/maths.js"),o=s("./src/utils/core.js"),i=s("./src/utils/tensor.js");async function a(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 s=await(await(0,r.getFile)(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const o=await n.decodeAudioData(s);let i;if(2===o.numberOfChannels){const e=Math.sqrt(2),t=o.getChannelData(0),s=o.getChannelData(1);i=new Float32Array(t.length);for(let r=0;r<o.length;++r)i[r]=e*(t[r]+s[r])/2}else i=o.getChannelData(0);return i}function l(e,t){if(e<1)return new Float64Array;if(1===e)return new Float64Array([1]);const s=1-t,r=2*Math.PI/(e-1),n=new Float64Array(e);for(let o=0;o<e;++o)n[o]=t-s*Math.cos(o*r);return n}function c(e){return l(e,.5)}function d(e){return l(e,.54)}const u={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,s=15,r=27/Math.log(6.4))=>e>=t?s+Math.log(e/t)*r:3*e/200};function p(e,t="htk"){const s=u[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}const _={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,s=15,r=Math.log(6.4)/27)=>e>=s?t*Math.exp(r*(e-s)):200*e/3};function m(e,t,s){const r=(t-e)/(s-1);return Float64Array.from({length:s},((t,s)=>e+r*s))}function h(e,t,s,r,n,o=null,i="htk",a=!1){if(null!==o&&"slaney"!==o)throw new Error('norm must be one of null or "slaney"');const l=m(p(s,i),p(r,i),t+2);let c,d=function(e,t="htk"){const s=_[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}(l,i);if(a){const t=n/(2*e);c=p(Float64Array.from({length:e},((e,s)=>s*t)),i),d=l}else c=m(0,Math.floor(n/2),e);const u=function(e,t){const s=Float64Array.from({length:t.length-1},((e,s)=>t[s+1]-t[s])),r=Array.from({length:e.length},(()=>new Array(t.length)));for(let s=0;s<e.length;++s){const n=r[s];for(let r=0;r<t.length;++r)n[r]=t[r]-e[s]}const n=t.length-2,o=Array.from({length:n},(()=>new Array(e.length)));for(let t=0;t<e.length;++t){const e=r[t];for(let r=0;r<n;++r){const n=-e[r]/s[r],i=e[r+2]/s[r+1];o[r][t]=Math.max(0,Math.min(n,i))}}return o}(c,d);if(null!==o&&"slaney"===o)for(let s=0;s<t;++s){const t=u[s],r=2/(d[s+2]-d[s]);for(let s=0;s<e;++s)t[s]*=r}return u}function f(e,t,s,r,o){if(s<=0)throw new Error("reference must be greater than zero");if(r<=0)throw new Error("min_value must be greater than zero");s=Math.max(r,s);const i=Math.log10(s);for(let s=0;s<e.length;++s)e[s]=t*Math.log10(Math.max(r,e[s])-i);if(null!==o){if(o<=0)throw new Error("db_range must be greater than zero");const t=(0,n.max)(e)[0]-o;for(let s=0;s<e.length;++s)e[s]=Math.max(e[s],t)}return e}async function g(e,t,s,r,{fft_length:a=null,power:l=1,center:c=!0,pad_mode:d="reflect",onesided:u=!0,preemphasis:p=null,mel_filters:_=null,mel_floor:m=1e-10,log_mel:h=null,reference:g=1,min_value:w=1e-10,db_range:M=null,remove_dc_offset:b=null,min_num_frames:x=null,max_num_frames:y=null,do_pad:k=!0,transpose:T=!1}={}){const v=t.length;if(null===a&&(a=s),s>a)throw Error(`frame_length (${s}) may not be larger than fft_length (${a})`);if(v!==s)throw new Error(`Length of the window (${v}) must equal frame_length (${s})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(null===l&&null!==_)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(c){if("reflect"!==d)throw new Error(`pad_mode="${d}" not implemented yet.`);const t=Math.floor((a-1)/2)+1;e=function(e,t,s){const r=new e.constructor(e.length+t+s),n=e.length-1;for(let s=0;s<e.length;++s)r[t+s]=e[s];for(let s=1;s<=t;++s)r[t-s]=e[(0,o.calculateReflectOffset)(s,n)];for(let i=1;i<=s;++i)r[n+t+i]=e[(0,o.calculateReflectOffset)(n-i,n)];return r}(e,t,t)}let P=Math.floor(1+Math.floor((e.length-s)/r));null!==x&&P<x&&(P=x);const F=u?Math.floor(a/2)+1:a;let C=P,A=P;null!==y&&(y>P?k&&(A=y):A=C=y);const S=new n.FFT(a),E=new Float64Array(a),I=new Float64Array(S.outputBufferSize),L=new Float32Array(F*A);for(let n=0;n<C;++n){const o=n*r,i=Math.min(e.length-o,s);i!==s&&E.fill(0,0,s);for(let t=0;t<i;++t)E[t]=e[o+t];if(b){let e=0;for(let t=0;t<i;++t)e+=E[t];const t=e/i;for(let e=0;e<i;++e)E[e]-=t}if(null!==p){for(let e=i-1;e>=1;--e)E[e]-=p*E[e-1];E[0]*=1-p}for(let e=0;e<t.length;++e)E[e]*=t[e];S.realTransform(I,E);for(let e=0;e<F;++e){const t=e<<1;L[e*A+n]=I[t]**2+I[t+1]**2}}if(null!==l&&2!==l){const e=2/l;for(let t=0;t<L.length;++t)L[t]**=e}const z=_.length;let j=await(0,i.matmul)(new i.Tensor("float32",_.flat(),[z,F]),new i.Tensor("float32",L,[F,A]));T&&(j=j.transpose(1,0));const N=j.data;for(let e=0;e<N.length;++e)N[e]=Math.max(m,N[e]);if(null!==l&&null!==h){const e=Math.min(N.length,C*z);switch(h){case"log":for(let t=0;t<e;++t)N[t]=Math.log(N[t]);break;case"log10":for(let t=0;t<e;++t)N[t]=Math.log10(N[t]);break;case"dB":if(1===l)!function(e,t=1,s=1e-5,r=null){f(e,20,t,s,r)}(N,g,w,M);else{if(2!==l)throw new Error(`Cannot use log_mel option '${h}' with power ${l}`);!function(e,t=1,s=1e-10,r=null){f(e,10,t,s,r)}(N,g,w,M)}break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return j}function w(e,t,{periodic:s=!0,frame_length:r=null,center:n=!0}={}){const o=s?e+1:e;let i;switch(t){case"boxcar":i=new Float64Array(o).fill(1);break;case"hann":case"hann_window":i=c(o);break;case"hamming":i=d(o);break;case"povey":i=c(o).map((e=>Math.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(s&&(i=i.subarray(0,e)),null===r)return i;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return i}},"./src/utils/constants.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>r,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const r="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.json",c="generation_config.json"},"./src/utils/core.js":(e,t,s)=>{"use strict";function r(e,t){e&&e(t)}function n(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){return null==e||-1===e}function c(e){const t=[];let s=e;for(;Array.isArray(s);)t.push(s.length),s=s[0];return t}function d(e,t,s=void 0){const r=e[t];if(void 0!==r)return delete e[t],r;if(void 0===s)throw Error(`Key ${t} does not exist in object.`);return s}function u(...e){return Array.prototype.concat.apply([],e)}function p(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function _(e,t){return Math.abs((e+t)%(2*t)-t)}function m(e,t){return Object.assign({},...t.map((t=>{if(void 0!==e[t])return{[t]:e[t]}})))}function h(e){let t=0;for(const s of e)++t;return t}function f(e,t){let s=0;for(const r of e)r===t&&++s;return s}s.r(t),s.d(t,{calculateDimensions:()=>c,calculateReflectOffset:()=>_,count:()=>f,dispatchCallback:()=>r,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>h,mergeArrays:()=>u,pick:()=>m,pop:()=>d,product:()=>p,reverseDictionary:()=>n})},"./src/utils/data-structures.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{CharTrie:()=>n,PriorityQueue:()=>r,TokenLattice:()=>i});class r{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._maxSize=t}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)if(this.size<this._maxSize)this._heap.push(t),this._siftUp();else{const e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._siftUpFrom(e))}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 s=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=s}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(e){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.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}}class n{constructor(){this.root=o.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const s of e){let e=t.children.get(s);void 0===e&&(e=o.default(),t.children.set(s,e)),t=e}t.isLeaf=!0}*commonPrefixSearch(e){let t=this.root;if(void 0===t)return;let s="";for(const r of e){if(s+=r,t=t.children.get(r),void 0===t)return;t.isLeaf&&(yield s)}}}class o{constructor(e,t){this.isLeaf=e,this.children=t}static default(){return new o(!1,new Map)}}class i{constructor(e,t,s){this.chars=Array.from(e),this.len=this.chars.length,this.bosTokenId=t,this.eosTokenId=s,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},(()=>[])),this.endNodes=Array.from({length:this.len+1},(()=>[]));const r=new a(this.bosTokenId,0,0,0,0),n=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(n.clone()),this.beginNodes[this.len].push(n),this.endNodes[0].push(r)}insert(e,t,s,r){const n=this.nodes.length,o=new a(r,n,e,t,s);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 s=0,r=null;for(let n of this.endNodes[t]){const t=n.backtraceScore+e.score;(null===r||t>s)&&(r=n.clone(),s=t)}if(null===r)return[];e.prev=r,e.backtraceScore=s}++t}const s=[],r=this.beginNodes[e][0].prev;if(null===r)return[];let n=r.clone();for(;null!==n.prev;){s.push(n.clone());const e=n.clone();n=e.prev.clone()}return s.reverse(),s}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map((e=>this.piece(e)))}tokenIds(){return this.viterbi().map((e=>e.tokenId))}}class a{constructor(e,t,s,r,n){this.tokenId=e,this.nodeId=t,this.pos=s,this.length=r,this.score=n,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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DEVICE_TYPES:()=>r});const r=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var r=s("./src/env.js"),n=s("./src/utils/devices.js");const o=function(){let e;return async function(){if(void 0===e)if(r.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({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Callable:()=>r});const r=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":(e,t,s)=>{"use strict";s.r(t),s.d(t,{getFile:()=>d,getModelFile:()=>_,getModelJSON:()=>m});var r=s("fs"),n=s("path"),o=s("./src/env.js"),i=s("./src/utils/core.js");const a={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"};class l{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=r.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let s=this;this.body=new ReadableStream({start(e){s.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",a[e]??"application/octet-stream")}clone(){let e=new l(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 r.promises.readFile(this.filePath)).buffer}async blob(){const e=await r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function c(e,t=null,s=null){let r;try{r=new URL(e)}catch(e){return!1}return!(t&&!t.includes(r.protocol))&&!(s&&!s.includes(r.hostname))}async function d(e){if(o.env.useFS&&!c(e,["http:","https:","blob:"]))return new l(e);if("undefined"!=typeof process&&"node"===process?.release?.name){const t=!!process.env?.TESTING_REMOTELY,s=o.env.version,r=new Headers;r.set("User-Agent",`transformers.js/${s}; is_ci/${t};`);if(c(e,["http:","https:"],["huggingface.co","hf.co"])){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&r.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:r})}return fetch(e)}const u={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 p{constructor(e){this.path=e}async match(e){let t=n.join(this.path,e),s=new l(t);return s.exists?s:void 0}async put(e,t){const s=Buffer.from(await t.arrayBuffer());let o=n.join(this.path,e);try{await r.promises.mkdir(n.dirname(o),{recursive:!0}),await r.promises.writeFile(o,s)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function _(e,t,s=!0,r={}){if(!o.env.allowLocalModels){if(r.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 n;if((0,i.dispatchCallback)(r.progress_callback,{status:"initiate",name:e,file:t}),!n&&o.env.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{n=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!n&&o.env.useFSCache&&(n=new p(r.cache_dir??o.env.cacheDir)),!n&&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");n=o.env.customCache}const a=r.revision??"main";let l,_,m=h(e,t),f=h(o.env.localModelPath,m),g=h(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(a)),t),w="main"===a?m:h(e,a,t),M=n instanceof p?w:g,b=!1;n&&(_=await async function(e,...t){for(let s of t)try{let t=await e.match(s);if(t)return t}catch(e){continue}}(n,f,M));const x=void 0!==_;if(void 0===_){if(o.env.allowLocalModels){if(c(m,["http:","https:"])){if(r.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{_=await d(f),l=f}catch(e){console.warn(`Unable to load from local path "${f}": "${e}"`)}}if(void 0===_||404===_.status){if(r.local_files_only||!o.env.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${f}".`);return null}if(_=await d(g),200!==_.status)return function(e,t,s){if(!s)return null;const r=u[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}(_.status,g,s);l=M}b=n&&"undefined"!=typeof Response&&_ instanceof Response&&200===_.status}let y;return(0,i.dispatchCallback)(r.progress_callback,{status:"download",name:e,file:t}),r.progress_callback?x&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(y=new Uint8Array(await _.arrayBuffer()),(0,i.dispatchCallback)(r.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:y.length,total:y.length})):y=await async function(e,t){const s=e.headers.get("Content-Length");null===s&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(s??"0"),n=new Uint8Array(r),o=0;const i=e.body.getReader();async function a(){const{done:e,value:s}=await i.read();if(e)return;let l=o+s.length;if(l>r){r=l;let e=new Uint8Array(r);e.set(n),n=e}n.set(s,o),o=l;return t({progress:o/r*100,loaded:o,total:r}),a()}return await a(),n}(_,(s=>{(0,i.dispatchCallback)(r.progress_callback,{status:"progress",name:e,file:t,...s})})):y=new Uint8Array(await _.arrayBuffer()),b&&l&&void 0===await n.match(l)&&await n.put(l,new Response(y,{headers:_.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)})),(0,i.dispatchCallback)(r.progress_callback,{status:"done",name:e,file:t}),y}async function m(e,t,s=!0,r={}){let n=await _(e,t,s,r);if(null===n)return{};let o=new TextDecoder("utf-8").decode(n);return JSON.parse(o)}function h(...e){return(e=e.map(((t,s)=>(s&&(t=t.replace(new RegExp("^/"),"")),s!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)))).join("/")}},"./src/utils/image.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{RawImage:()=>m,load_image:()=>h});var r=s("./src/utils/core.js"),n=s("./src/utils/hub.js"),o=s("./src/env.js"),i=s("./src/utils/tensor.js"),a=s("sharp");let l,c,d;const u=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(u)l=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},d=self.createImageBitmap,c=self.ImageData;else{if(!a)throw new Error("Unable to load image processing library.");d=async e=>{const t=(await e.metadata()).channels,{data:s,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),n=new m(new Uint8ClampedArray(s),r.width,r.height,r.channels);return void 0!==t&&t!==r.channels&&n.convert(t),n}}const p={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class m{constructor(e,t,s,r){this.data=e,this.width=t,this.height=s,this.channels=r}get size(){return[this.width,this.height]}static async read(e){if(e instanceof m)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(!u)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 m(t,e.width,e.height,4)}static async fromURL(e){const t=await(0,n.getFile)(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const s=await t.blob();return this.fromBlob(s)}static async fromBlob(e){if(u){const t=await d(e),s=l(t.width,t.height).getContext("2d");return s.drawImage(t,0,0),new this(s.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=a(await e.arrayBuffer());return await d(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 m(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,s=0;t<this.data.length;t+=this.channels){const r=this.data[t],n=this.data[t+1],o=this.data[t+2];e[s++]=Math.round(.2989*r+.587*n+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(3===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t];break;case 4:for(let t=0,s=0;t<this.data.length;t+=4)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(4===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=255;break;case 3:for(let t=0,s=0;t<this.data.length;t+=3)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(1!==e.channels)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);const t=this.data,s=e.data,r=this.width*this.height;if(3===this.channels){const e=new Uint8ClampedArray(4*r);for(let n=0,o=0,i=0;n<r;++n)e[i++]=t[o++],e[i++]=t[o++],e[i++]=t[o++],e[i++]=s[n];return this._update(e,this.width,this.height,4)}if(4===this.channels){for(let e=0;e<r;++e)t[4*e+3]=s[e];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,t,{resample:s=2}={}){if(this.width===e&&this.height===t)return this;let n=p[s]??s;const o=(0,r.isNullishDimension)(e),i=(0,r.isNullishDimension)(t);if(o&&i)return this;if(o?e=t/this.height*this.width:i&&(t=e/this.width*this.height),u){const s=this.channels,r=this.toCanvas(),n=l(e,t).getContext("2d");n.drawImage(r,0,0,e,t);return new m(n.getImageData(0,0,e,t).data,e,t,4).convert(s)}{let s=this.toSharp();switch(n){case"box":case"hamming":"box"!==n&&"hamming"!==n||(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":s=s.affine([e/this.width,0,0,t/this.height],{interpolator:n});break;case"lanczos":s=s.resize({width:e,height:t,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await d(s)}}async pad([e,t,s,r]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.max(s,0),r=Math.max(r,0),0===e&&0===t&&0===s&&0===r)return this;if(u){const n=this.channels,o=this.toCanvas(),i=this.width+e+t,a=this.height+s+r,c=l(i,a).getContext("2d");c.drawImage(o,0,0,this.width,this.height,e,s,this.width,this.height);return new m(c.getImageData(0,0,i,a).data,i,a,4).convert(n)}{const n=this.toSharp().extend({left:e,right:t,top:s,bottom:r});return await d(n)}}async crop([e,t,s,r]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.min(s,this.width-1),r=Math.min(r,this.height-1),0===e&&0===t&&s===this.width-1&&r===this.height-1)return this;const n=s-e+1,o=r-t+1;if(u){const s=this.channels,r=this.toCanvas(),i=l(n,o).getContext("2d");i.drawImage(r,e,t,n,o,0,0,n,o);return new m(i.getImageData(0,0,n,o).data,n,o,4).convert(s)}{const s=this.toSharp().extract({left:e,top:t,width:n,height:o});return await d(s)}}async center_crop(e,t){if(this.width===e&&this.height===t)return this;const s=(this.width-e)/2,r=(this.height-t)/2;if(u){const n=this.channels,o=this.toCanvas(),i=l(e,t).getContext("2d");let a=0,c=0,d=0,u=0;s>=0?a=s:d=-s,r>=0?c=r:u=-r,i.drawImage(o,a,c,e,t,d,u,e,t);return new m(i.getImageData(0,0,e,t).data,e,t,4).convert(n)}{let n=this.toSharp();if(s>=0&&r>=0)n=n.extract({left:Math.floor(s),top:Math.floor(r),width:e,height:t});else if(s<=0&&r<=0){const o=Math.floor(-r),i=Math.floor(-s);n=n.extend({top:o,left:i,right:e-this.width-i,bottom:t-this.height-o})}else{let o=[0,0],i=0;r<0?(o[0]=Math.floor(-r),o[1]=t-this.height-o[0]):i=Math.floor(r);let a=[0,0],l=0;s<0?(a[0]=Math.floor(-s),a[1]=e-this.width-a[0]):l=Math.floor(s),n=n.extend({top:o[0],bottom:o[1],left:a[0],right:a[1]}).extract({left:l,top:i,width:e,height:t})}return await d(n)}}async toBlob(e="image/png",t=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");const s=this.toCanvas();return await s.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new i.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(!u)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=l(e.width,e.height),s=new c(e.data,e.width,e.height);return t.getContext("2d").putImageData(s,0,0),t}split(){const{data:e,width:t,height:s,channels:r}=this,n=e.constructor,o=e.length/r,i=Array.from({length:r},(()=>new n(o)));for(let t=0;t<o;++t){const s=r*t;for(let n=0;n<r;++n)i[n][t]=e[s+n]}return i.map((e=>new m(e,t,s,1)))}_update(e,t,s,r=null){return this.data=e,this.width=t,this.height=s,null!==r&&(this.channels=r),this}clone(){return new m(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(!u){if(o.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(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),s=_.get(t)??"image/png",r=await this.toBlob(s),n=URL.createObjectURL(r),i=document.createElement("a");i.href=n,i.download=e,i.click(),i.remove()}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const h=m.read.bind(m)},"./src/utils/maths.js":(e,t,s)=>{"use strict";function r(e,[t,s,r],[n,o],i="bilinear",a=!1){const l=o/r,c=n/s,d=new e.constructor(n*o*t),u=s*r,p=n*o;for(let i=0;i<n;++i)for(let n=0;n<o;++n){const a=i*o+n,_=(n+.5)/l-.5,m=(i+.5)/c-.5;let h=Math.floor(_),f=Math.floor(m);const g=Math.min(h+1,r-1),w=Math.min(f+1,s-1);h=Math.max(h,0),f=Math.max(f,0);const M=_-h,b=m-f,x=(1-M)*(1-b),y=M*(1-b),k=(1-M)*b,T=M*b,v=f*r,P=w*r,F=v+h,C=v+g,A=P+h,S=P+g;for(let s=0;s<t;++s){const t=s*u;d[s*p+a]=x*e[t+F]+y*e[t+C]+k*e[t+A]+T*e[t+S]}}return d}function n(e,t,s){const r=new Array(s.length),n=new Array(s.length);for(let e=s.length-1,o=1;e>=0;--e)n[e]=o,r[e]=t[s[e]],o*=r[e];const o=s.map(((e,t)=>n[s.indexOf(t)])),i=new e.constructor(e.length);for(let s=0;s<e.length;++s){let r=0;for(let e=t.length-1,n=s;e>=0;--e)r+=n%t[e]*o[e],n=Math.floor(n/t[e]);i[r]=e[s]}return[i,r]}function o(e){const t=u(e)[0],s=e.map((e=>Math.exp(e-t))),r=s.reduce(((e,t)=>e+t),0);return s.map((e=>e/r))}function i(e){const t=u(e)[0];let s=0;for(let r=0;r<e.length;++r)s+=Math.exp(e[r]-t);const r=Math.log(s);return e.map((e=>e-t-r))}function a(e,t){let s=0;for(let r=0;r<e.length;++r)s+=e[r]*t[r];return s}function l(e,t){return a(e,t)/(c(e)*c(t))}function c(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}function d(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],s=r);return[t,s]}function u(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],s=r);return[Number(t),s]}function p(e){return e>0&&!(e&e-1)}s.r(t),s.d(t,{FFT:()=>h,bankers_round:()=>w,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>M,interpolate_data:()=>r,log_softmax:()=>i,magnitude:()=>c,max:()=>u,medianFilter:()=>f,min:()=>d,permute_data:()=>n,round:()=>g,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;e<this.table.length;e+=2){const t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){const s=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const s=t||new Array(e.length>>>1);for(let t=0;t<e.length;t+=2)s[t>>>1]=e[t];return s}toComplexArray(e,t){const s=t||this.createComplexArray();for(let t=0;t<s.length;t+=2)s[t]=e[t>>>1],s[t+1]=0;return s}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,s){const r=this._csize;let n,o,i=1<<this._width,a=r/i<<1;const l=this._bitrev;if(4===a)for(n=0,o=0;n<r;n+=a,++o){const s=l[o];this._singleTransform2(t,e,n,s,i)}else for(n=0,o=0;n<r;n+=a,++o){const r=l[o];this._singleTransform4(t,e,n,r,i,s)}const c=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;const t=a>>>2;for(n=0;n<r;n+=a){const r=n+t-1;for(let o=n,a=0;o<r;o+=2,a+=i){const r=o,n=r+t,i=n+t,l=i+t,d=e[r],u=e[r+1],p=e[n],_=e[n+1],m=e[i],h=e[i+1],f=e[l],g=e[l+1],w=c[a],M=s*c[a+1],b=p*w-_*M,x=p*M+_*w,y=c[2*a],k=s*c[2*a+1],T=m*y-h*k,v=m*k+h*y,P=c[3*a],F=s*c[3*a+1],C=f*P-g*F,A=f*F+g*P,S=d+T,E=u+v,I=d-T,L=u-v,z=b+C,j=x+A,N=s*(b-C),O=s*(x-A);e[r]=S+z,e[r+1]=E+j,e[n]=I+O,e[n+1]=L-N,e[i]=S-z,e[i+1]=E-j,e[l]=I-O,e[l+1]=L+N}}}}_singleTransform2(e,t,s,r,n){const o=e[r],i=e[r+1],a=e[r+n],l=e[r+n+1];t[s]=o+a,t[s+1]=i+l,t[s+2]=o-a,t[s+3]=i-l}_singleTransform4(e,t,s,r,n,o){const i=2*n,a=3*n,l=e[r],c=e[r+1],d=e[r+n],u=e[r+n+1],p=e[r+i],_=e[r+i+1],m=e[r+a],h=e[r+a+1],f=l+p,g=c+_,w=l-p,M=c-_,b=d+m,x=u+h,y=o*(d-m),k=o*(u-h);t[s]=f+b,t[s+1]=g+x,t[s+2]=w+k,t[s+3]=M-y,t[s+4]=f-b,t[s+5]=g-x,t[s+6]=w-k,t[s+7]=M+y}_realTransform4(e,t,s){const r=this._csize;let n,o,i=1<<this._width,a=r/i<<1;const l=this._bitrev;if(4===a)for(n=0,o=0;n<r;n+=a,++o){const s=l[o];this._singleRealTransform2(t,e,n,s>>>1,i>>>1)}else for(n=0,o=0;n<r;n+=a,++o){const r=l[o];this._singleRealTransform4(t,e,n,r>>>1,i>>>1,s)}const c=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;const t=a>>>1,o=t>>>1,l=o>>>1;for(n=0;n<r;n+=a)for(let r=0,a=0;r<=l;r+=2,a+=i){const i=n+r,d=i+o,u=d+o,p=u+o,_=e[i],m=e[i+1],h=e[d],f=e[d+1],g=e[u],w=e[u+1],M=e[p],b=e[p+1],x=_,y=m,k=c[a],T=s*c[a+1],v=h*k-f*T,P=h*T+f*k,F=c[2*a],C=s*c[2*a+1],A=g*F-w*C,S=g*C+w*F,E=c[3*a],I=s*c[3*a+1],L=M*E-b*I,z=M*I+b*E,j=x+A,N=y+S,O=x-A,B=y-S,V=v+L,D=P+z,R=s*(v-L),G=s*(P-z);if(e[i]=j+V,e[i+1]=N+D,e[d]=O+G,e[d+1]=B-R,0===r){e[u]=j-V,e[u+1]=N-D;continue}if(r===l)continue;const $=n+o-r,q=n+t-r;e[$]=O-s*G,e[$+1]=-B-s*R,e[q]=j-s*V,e[q+1]=s*D-N}}const d=r>>>1;for(let t=2;t<d;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,s,r,n){const o=e[r],i=e[r+n];t[s]=o+i,t[s+1]=0,t[s+2]=o-i,t[s+3]=0}_singleRealTransform4(e,t,s,r,n,o){const i=2*n,a=3*n,l=e[r],c=e[r+n],d=e[r+i],u=e[r+a],p=l+d,_=l-d,m=c+u,h=o*(c-u);t[s]=p+m,t[s+1]=0,t[s+2]=_,t[s+3]=-h,t[s+4]=p-m,t[s+5]=0,t[s+6]=_,t[s+7]=h}}class m{constructor(e){const t=2*(e-1),s=2*(2*e-1),r=2**Math.ceil(Math.log2(s));this.bufferSize=r,this._a=t;const n=new Float64Array(s),o=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);const i=-2*Math.PI/e,a=Math.cos(i),l=Math.sin(i);for(let t=0;t<s>>1;++t){const s=(t+1-e)**2/2,r=Math.sqrt(a**2+l**2)**s,i=s*Math.atan2(l,a),c=2*t;n[c]=r*Math.cos(i),n[c+1]=r*Math.sin(i),o[c]=n[c],o[c+1]=-n[c+1]}this._slicedChirpBuffer=n.subarray(t,s),this._f=new _(r>>1),this._f.transform(this._chirpBuffer,o)}_transform(e,t,s){const r=this._buffer1,n=this._buffer2,o=this._outBuffer1,i=this._outBuffer2,a=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(s)for(let e=0;e<l.length;e+=2){const s=e+1,n=t[e>>1];r[e]=n*l[e],r[s]=n*l[s]}else for(let e=0;e<l.length;e+=2){const s=e+1;r[e]=t[e]*l[e]-t[s]*l[s],r[s]=t[e]*l[s]+t[s]*l[e]}this._f.transform(o,r);for(let e=0;e<a.length;e+=2){const t=e+1;n[e]=o[e]*a[e]-o[t]*a[t],n[t]=o[e]*a[t]+o[t]*a[e]}this._f.inverseTransform(i,n);for(let t=0;t<i.length;t+=2){const s=i[t+c],r=i[t+c+1],n=l[t],o=l[t+1];e[t]=s*n-r*o,e[t+1]=s*o+r*n}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}}class h{constructor(e){this.fft_length=e,this.isPowerOfTwo=p(e),this.isPowerOfTwo?(this.fft=new _(e),this.outputBufferSize=2*e):(this.fft=new m(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}}function f(e,t){if(t%2==0||t<=0)throw new Error("Window size must be a positive odd number");const s=new e.constructor(e.length),r=new e.constructor(t),n=Math.floor(t/2);for(let t=0;t<e.length;++t){let o=0;for(let s=-n;s<=n;++s){let n=t+s;n<0?n=Math.abs(n):n>=e.length&&(n=2*(e.length-1)-n),r[o++]=e[n]}r.sort(),s[t]=r[n]}return s}function g(e,t){const s=Math.pow(10,t);return Math.round(e*s)/s}function w(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function M(e){const t=e.length,s=e[0].length,r=[t+1,s+1],n=Array.from({length:r[0]},(()=>Array(r[1]).fill(1/0)));n[0][0]=0;const o=Array.from({length:r[0]},(()=>Array(r[1]).fill(-1)));for(let t=1;t<r[1];++t)for(let s=1;s<r[0];++s){const r=n[s-1][t-1],i=n[s-1][t],a=n[s][t-1];let l,c;r<i&&r<a?(l=r,c=0):i<r&&i<a?(l=i,c=1):(l=a,c=2),n[s][t]=e[s-1][t-1]+l,o[s][t]=c}for(let e=0;e<r[1];++e)o[0][e]=2;for(let e=0;e<r[0];++e)o[e][0]=1;let i=t,a=s,l=[],c=[];for(;i>0||a>0;)switch(l.push(i-1),c.push(a-1),o[i][a]){case 0:--i,--a;break;case 1:--i;break;case 2:--a;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${a}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}},"./src/utils/tensor.js":(e,t,s)=>{"use strict";s.r(t),s.d(t,{Tensor:()=>a,cat:()=>x,full:()=>P,full_like:()=>F,interpolate:()=>c,interpolate_4d:()=>d,layer_norm:()=>g,matmul:()=>u,mean:()=>T,mean_pooling:()=>f,ones:()=>C,ones_like:()=>A,permute:()=>l,quantize_embeddings:()=>L,rand:()=>I,rfft:()=>p,slice:()=>h,stack:()=>y,std_mean:()=>k,topk:()=>_,zeros:()=>S,zeros_like:()=>E});var r=s("./src/utils/maths.js"),n=s("./src/backends/onnx.js"),o=s("./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,uint4:Uint8Array,int4:Int8Array});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}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return(0,n.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new n.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let s=Number(t);if(Number.isInteger(s))return e._getitem(s)}return e[t]},set:(e,t,s)=>e[t]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const s=t.reduce(((e,t)=>e*t));for(let r=0;r<e;++r)yield this._subarray(r,s,t)}else yield*this.data}_getitem(e){const[t,...s]=this.dims;if(e=b(e,t),s.length>0){const t=s.reduce(((e,t)=>e*t));return this._subarray(e,t,s)}return new a(this.type,[this.data[e]],s)}indexOf(e){const t=this.data;for(let s=0;s<t.length;++s)if(t[s]==e)return s;return-1}_subarray(e,t,s){const r=e*t,n=(e+1)*t,o="subarray"in this.data?this.data.subarray(r,n):this.data.slice(r,n);return new a(this.type,o,s)}item(){const e=this.data;if(1!==e.length)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return function(e,t){const s=e.length,r=t.reduce(((e,t)=>e*t));if(s!==r)throw Error(`cannot reshape array of size ${s} into shape (${t})`);let n=e;for(let e=t.length-1;e>=0;e--)n=n.reduce(((s,r)=>{let n=s[s.length-1];return n.length<t[e]?n.push(r):s.push([r]),s}),[[]]);return n[0]}(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]=e(t[s],s,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]-=e;return this}clone(){return new a(this.type,this.data.slice(),this.dims.slice())}slice(...e){const t=[],s=[];for(let r=0;r<this.dims.length;++r){let n=e[r];if(null==n)s.push([0,this.dims[r]]),t.push(this.dims[r]);else if("number"==typeof n)n=b(n,this.dims[r],r),s.push([n,n+1]);else{if(!Array.isArray(n)||2!==n.length)throw new Error(`Invalid slice: ${n}`);{let[e,o]=n;if(e=null===e?0:b(e,this.dims[r],r,!1),o=null===o?this.dims[r]:b(o,this.dims[r],r,!1),e>o)throw new Error(`Invalid slice: ${n}`);const i=[Math.max(e,0),Math.min(o,this.dims[r])];s.push(i),t.push(i[1]-i[0])}}}const r=s.map((([e,t])=>t-e)),n=r.reduce(((e,t)=>e*t)),o=this.data,i=new o.constructor(n),l=this.stride();for(let e=0;e<n;++e){let t=0;for(let n=r.length-1,o=e;n>=0;--n){const e=r[n];t+=(o%e+s[n][0])*l[n],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,s=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const r=this.data;if(null===t){let t=r.reduce(((t,s)=>t+s**e),0)**(1/e);return new a(this.type,[t],[])}t=b(t,this.dims.length);const n=this.dims.slice();n[t]=1;const o=new r.constructor(r.length/this.dims[t]);for(let s=0;s<r.length;++s){let i=0;for(let e=this.dims.length-1,r=s,o=1;e>=0;--e){const s=this.dims[e];if(e!==t){i+=r%s*o,o*=n[e]}r=Math.floor(r/s)}o[i]+=r[s]**e}if(1!==e)for(let t=0;t<o.length;++t)o[t]=o[t]**(1/e);return s||n.splice(t,1),new a(this.type,o,n)}normalize_(e=2,t=1){t=b(t,this.dims.length);const s=this.norm(e,t,!0),r=this.data,n=s.data;for(let e=0;e<r.length;++e){let s=0;for(let r=this.dims.length-1,n=e,o=1;r>=0;--r){const e=this.dims[r];if(r!==t){s+=n%e*o,o*=this.dims[r]}n=Math.floor(n/e)}r[e]/=n[s]}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 s=e.length-1,r=1;s>=0;--s)t[s]=r,r*=e[s];return t}(this.dims)}squeeze(e=null){return new a(this.type,this.data,w(this.dims,e))}squeeze_(e=null){return this.dims=w(this.dims,e),this}unsqueeze(e=null){return new a(this.type,this.data,M(this.dims,e))}unsqueeze_(e=null){return this.dims=M(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),r=this.dims.slice(e,t+1),n=this.dims.slice(t+1);return this.dims=[...s,r.reduce(((e,t)=>e*t),1),...n],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let s=0;s<e.length;++s)if(-1===e[s]){if(-1!==t)throw new Error("Only one dimension can be inferred");t=s}const s=this.data;if(-1!==t){const r=e.reduce(((e,s,r)=>r!==t?e*s:e),1);e[t]=s.length/r}return new a(this.type,s,e)}neg_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}clamp_(e,t){const s=this.data;for(let r=0;r<s.length;++r)s[r]=Math.min(Math.max(s[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return T(this,e,t)}to(e){if(this.type===e)return this;if(!i.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let t;const s=["int64","uint64"].includes(this.type),r=["int64","uint64"].includes(e);return s&&!r?t=Number:!s&&r&&(t=BigInt),new a(e,i[e].from(this.data,t),this.dims)}}function l(e,t){const[s,n]=(0,r.permute_data)(e.data,e.dims,t);return new a(e.type,s,n)}function c(e,[t,s],n="bilinear",o=!1){const i=e.dims.at(-3)??1,l=e.dims.at(-2),c=e.dims.at(-1);let d=(0,r.interpolate_data)(e.data,[i,l,c],[t,s],n,o);return new a(e.type,d,[i,t,s])}async function d(e,{size:t=null,mode:s="bilinear"}={}){if(4!==e.dims.length)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let r,n;if(2===t.length)r=[...e.dims.slice(0,2),...t];else if(3===t.length)r=[e.dims[0],...t];else{if(4!==t.length)throw new Error("`size` must be of length 2, 3, or 4.");r=t}if("bilinear"===s)n=await o.TensorOpRegistry.bilinear_interpolate_4d;else{if("bicubic"!==s)throw new Error(`Unsupported mode: ${s}`);n=await o.TensorOpRegistry.bicubic_interpolate_4d}const i=new a("int64",new BigInt64Array(r.map(BigInt)),[r.length]);return await n({x:e,s:i})}async function u(e,t){const s=await o.TensorOpRegistry.matmul;return await s({a:e,b:t})}async function p(e,t){const s=await o.TensorOpRegistry.rfft;return await s({x:e,a:t})}async function _(e,t){const s=await o.TensorOpRegistry.top_k;return t=null===t?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await s({x:e,k:new a("int64",[BigInt(t)],[1])})}const m=e=>new a("int64",e,[e.length]);async function h(e,t,s,r,n){const i=await o.TensorOpRegistry.slice;return await i({x:e,s:m(t),e:m(s),a:m(r),t:m(n??new Array(r.length).fill(1))})}function f(e,t){const s=e.data,r=t.data,n=[e.dims[0],e.dims[2]],o=new s.constructor(n[0]*n[1]),[i,l,c]=e.dims;let d=0;for(let e=0;e<i;++e){const t=e*c*l;for(let n=0;n<c;++n){let i=0,a=0;const u=e*l,p=t+n;for(let e=0;e<l;++e){const t=Number(r[u+e]);a+=t,i+=s[p+e*c]*t}const _=i/a;o[d++]=_}}return new a(e.type,o,n)}function g(e,t,{eps:s=1e-5}={}){if(2!==e.dims.length)throw new Error("`layer_norm` currently only supports 2D input.");const[r,n]=e.dims;if(1!==t.length&&t[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[o,i]=k(e,1,0,!0),l=o.data,c=i.data,d=e.data,u=new d.constructor(d.length);for(let e=0;e<r;++e){const t=e*n;for(let r=0;r<n;++r){const n=t+r;u[n]=(d[n]-c[e])/(l[e]+s)}}return new a(e.type,u,e.dims)}function w(e,t){return e=e.slice(),null===t?e=e.filter((e=>1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,s)=>1!==e||!t.includes(s)))),e}function M(e,t){return t=b(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function b(e,t,s=null,r=!0){if(r&&(e<-t||e>=t))throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===s?"":" "+s} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function x(e,t=0){t=b(t,e[0].dims.length);const s=e[0].dims.slice();s[t]=e.reduce(((e,s)=>e+s.dims[t]),0);const r=s.reduce(((e,t)=>e*t),1),n=new e[0].data.constructor(r),o=e[0].type;if(0===t){let t=0;for(const s of e){const e=s.data;n.set(e,t),t+=e.length}}else{let r=0;for(let o=0;o<e.length;++o){const{data:i,dims:a}=e[o];for(let e=0;e<i.length;++e){let o=0;for(let n=a.length-1,i=e,l=1;n>=0;--n){const e=a[n];let c=i%e;n===t&&(c+=r),o+=c*l,l*=s[n],i=Math.floor(i/e)}n[o]=i[e]}r+=a[t]}}return new a(o,n,s)}function y(e,t=0){return x(e.map((e=>e.unsqueeze(t))),t)}function k(e,t=null,s=1,r=!1){const n=e.data,o=e.dims;if(null===t){const t=n.reduce(((e,t)=>e+t),0)/n.length,r=Math.sqrt(n.reduce(((e,s)=>e+(s-t)**2),0)/(n.length-s)),o=new a(e.type,[t],[]);return[new a(e.type,[r],[]),o]}const i=T(e,t=b(t,o.length),r),l=i.data,c=o.slice();c[t]=1;const d=new n.constructor(n.length/o[t]);for(let e=0;e<n.length;++e){let s=0;for(let r=o.length-1,n=e,i=1;r>=0;--r){const e=o[r];if(r!==t){s+=n%e*i,i*=c[r]}n=Math.floor(n/e)}d[s]+=(n[e]-l[s])**2}for(let e=0;e<d.length;++e)d[e]=Math.sqrt(d[e]/(o[t]-s));r||c.splice(t,1);return[new a(e.type,d,c),i]}function T(e,t=null,s=!1){const r=e.data;if(null===t){const t=r.reduce(((e,t)=>e+t),0);return new a(e.type,[t/r.length],[])}const n=e.dims;t=b(t,n.length);const o=n.slice();o[t]=1;const i=new r.constructor(r.length/n[t]);for(let e=0;e<r.length;++e){let s=0;for(let r=n.length-1,i=e,a=1;r>=0;--r){const e=n[r];if(r!==t){s+=i%e*a,a*=o[r]}i=Math.floor(i/e)}i[s]+=r[e]}if(1!==n[t])for(let e=0;e<i.length;++e)i[e]=i[e]/n[t];return s||o.splice(t,1),new a(e.type,i,o)}function v(e,t,s,r){const n=e.reduce(((e,t)=>e*t),1);return new a(s,new r(n).fill(t),e)}function P(e,t){let s,r;if("number"==typeof t)s="float32",r=Float32Array;else if("bigint"==typeof t)s="int64",r=BigInt64Array;else{if("boolean"!=typeof t)throw new Error("Unsupported data type: "+typeof t);s="bool",r=Uint8Array}return v(e,t,s,r)}function F(e,t){return P(e.dims,t)}function C(e){return v(e,1n,"int64",BigInt64Array)}function A(e){return C(e.dims)}function S(e){return v(e,0n,"int64",BigInt64Array)}function E(e){return S(e.dims)}function I(e){const t=e.reduce(((e,t)=>e*t),1);return new a("float32",Float32Array.from({length:t},(()=>Math.random())),e)}function L(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 s="binary"===t,r=s?"int8":"uint8",n=s?Int8Array:Uint8Array,o=e.data,i=new n(o.length/8);for(let e=0;e<o.length;++e){const t=o[e]>0?1:0,r=Math.floor(e/8),n=e%8;i[r]|=t<<7-n,s&&0===n&&(i[r]-=128)}return new a(r,i,[e.dims[0],e.dims[1]/8])}}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var o=r[e]={exports:{}};return s[e](o,o.exports,n),o.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(s,r){if(1&r&&(s=this(s)),8&r)return s;if("object"==typeof s&&s){if(4&r&&s.__esModule)return s;if(16&r&&"function"==typeof s.then)return s}var o=Object.create(null);n.r(o);var i={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&s;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>i[e]=()=>s[e]));return i.default=()=>s,n.d(o,i),o},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";n.r(o),n.d(o,{ASTFeatureExtractor:()=>p.ASTFeatureExtractor,ASTForAudioClassification:()=>s.ASTForAudioClassification,ASTModel:()=>s.ASTModel,ASTPreTrainedModel:()=>s.ASTPreTrainedModel,AlbertForMaskedLM:()=>s.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>s.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>s.AlbertForSequenceClassification,AlbertModel:()=>s.AlbertModel,AlbertPreTrainedModel:()=>s.AlbertPreTrainedModel,AlbertTokenizer:()=>r.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>i.AutoConfig,AutoFeatureExtractor:()=>_.AutoFeatureExtractor,AutoImageProcessor:()=>f.AutoImageProcessor,AutoModel:()=>s.AutoModel,AutoModelForAudioClassification:()=>s.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>s.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>s.AutoModelForCTC,AutoModelForCausalLM:()=>s.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>s.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>s.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>s.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>s.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>s.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>s.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>s.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>s.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>s.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>s.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>s.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>s.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>s.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>s.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>s.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>s.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>s.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>s.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>s.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>s.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>s.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>s.AutoModelForVision2Seq,AutoModelForXVector:()=>s.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>s.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>M.AutoProcessor,AutoTokenizer:()=>r.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>s.BartForConditionalGeneration,BartForSequenceClassification:()=>s.BartForSequenceClassification,BartModel:()=>s.BartModel,BartPretrainedModel:()=>s.BartPretrainedModel,BartTokenizer:()=>r.BartTokenizer,BaseModelOutput:()=>s.BaseModelOutput,BaseStreamer:()=>b.BaseStreamer,BeitFeatureExtractor:()=>h.BeitFeatureExtractor,BeitForImageClassification:()=>s.BeitForImageClassification,BeitModel:()=>s.BeitModel,BeitPreTrainedModel:()=>s.BeitPreTrainedModel,BertForMaskedLM:()=>s.BertForMaskedLM,BertForQuestionAnswering:()=>s.BertForQuestionAnswering,BertForSequenceClassification:()=>s.BertForSequenceClassification,BertForTokenClassification:()=>s.BertForTokenClassification,BertModel:()=>s.BertModel,BertPreTrainedModel:()=>s.BertPreTrainedModel,BertTokenizer:()=>r.BertTokenizer,BitImageProcessor:()=>h.BitImageProcessor,BlenderbotForConditionalGeneration:()=>s.BlenderbotForConditionalGeneration,BlenderbotModel:()=>s.BlenderbotModel,BlenderbotPreTrainedModel:()=>s.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>s.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>s.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>s.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>r.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>r.BlenderbotTokenizer,BloomForCausalLM:()=>s.BloomForCausalLM,BloomModel:()=>s.BloomModel,BloomPreTrainedModel:()=>s.BloomPreTrainedModel,BloomTokenizer:()=>r.BloomTokenizer,CLIPFeatureExtractor:()=>h.CLIPFeatureExtractor,CLIPImageProcessor:()=>h.CLIPImageProcessor,CLIPModel:()=>s.CLIPModel,CLIPPreTrainedModel:()=>s.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>s.CLIPSegForImageSegmentation,CLIPSegModel:()=>s.CLIPSegModel,CLIPSegPreTrainedModel:()=>s.CLIPSegPreTrainedModel,CLIPTextModel:()=>s.CLIPTextModel,CLIPTextModelWithProjection:()=>s.CLIPTextModelWithProjection,CLIPTokenizer:()=>r.CLIPTokenizer,CLIPVisionModel:()=>s.CLIPVisionModel,CLIPVisionModelWithProjection:()=>s.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>s.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>s.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>s.CamembertForSequenceClassification,CamembertForTokenClassification:()=>s.CamembertForTokenClassification,CamembertModel:()=>s.CamembertModel,CamembertPreTrainedModel:()=>s.CamembertPreTrainedModel,CamembertTokenizer:()=>r.CamembertTokenizer,CausalLMOutput:()=>s.CausalLMOutput,CausalLMOutputWithPast:()=>s.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>h.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>s.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>s.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>s.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>p.ClapFeatureExtractor,ClapModel:()=>s.ClapModel,ClapPreTrainedModel:()=>s.ClapPreTrainedModel,ClapTextModelWithProjection:()=>s.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>s.CodeGenForCausalLM,CodeGenModel:()=>s.CodeGenModel,CodeGenPreTrainedModel:()=>s.CodeGenPreTrainedModel,CodeGenTokenizer:()=>r.CodeGenTokenizer,CodeLlamaTokenizer:()=>r.CodeLlamaTokenizer,CohereForCausalLM:()=>s.CohereForCausalLM,CohereModel:()=>s.CohereModel,CoherePreTrainedModel:()=>s.CoherePreTrainedModel,CohereTokenizer:()=>r.CohereTokenizer,ConvBertForMaskedLM:()=>s.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>s.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>s.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>s.ConvBertForTokenClassification,ConvBertModel:()=>s.ConvBertModel,ConvBertPreTrainedModel:()=>s.ConvBertPreTrainedModel,ConvBertTokenizer:()=>r.ConvBertTokenizer,ConvNextFeatureExtractor:()=>h.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>s.ConvNextForImageClassification,ConvNextImageProcessor:()=>h.ConvNextImageProcessor,ConvNextModel:()=>s.ConvNextModel,ConvNextPreTrainedModel:()=>s.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>s.ConvNextV2ForImageClassification,ConvNextV2Model:()=>s.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>s.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>h.DPTFeatureExtractor,DPTForDepthEstimation:()=>s.DPTForDepthEstimation,DPTImageProcessor:()=>h.DPTImageProcessor,DPTModel:()=>s.DPTModel,DPTPreTrainedModel:()=>s.DPTPreTrainedModel,DebertaForMaskedLM:()=>s.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>s.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>s.DebertaForSequenceClassification,DebertaForTokenClassification:()=>s.DebertaForTokenClassification,DebertaModel:()=>s.DebertaModel,DebertaPreTrainedModel:()=>s.DebertaPreTrainedModel,DebertaTokenizer:()=>r.DebertaTokenizer,DebertaV2ForMaskedLM:()=>s.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>s.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>s.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>s.DebertaV2ForTokenClassification,DebertaV2Model:()=>s.DebertaV2Model,DebertaV2PreTrainedModel:()=>s.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>r.DebertaV2Tokenizer,DecisionTransformerModel:()=>s.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>s.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>h.DeiTFeatureExtractor,DeiTForImageClassification:()=>s.DeiTForImageClassification,DeiTImageProcessor:()=>h.DeiTImageProcessor,DeiTModel:()=>s.DeiTModel,DeiTPreTrainedModel:()=>s.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>s.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>s.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DepthProForDepthEstimation:()=>s.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>s.DepthProPreTrainedModel,DetrFeatureExtractor:()=>h.DetrFeatureExtractor,DetrForObjectDetection:()=>s.DetrForObjectDetection,DetrForSegmentation:()=>s.DetrForSegmentation,DetrImageProcessor:()=>h.DetrImageProcessor,DetrModel:()=>s.DetrModel,DetrObjectDetectionOutput:()=>s.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>s.DetrPreTrainedModel,DetrSegmentationOutput:()=>s.DetrSegmentationOutput,Dinov2ForImageClassification:()=>s.Dinov2ForImageClassification,Dinov2Model:()=>s.Dinov2Model,Dinov2PreTrainedModel:()=>s.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>s.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>s.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>s.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>s.DistilBertForTokenClassification,DistilBertModel:()=>s.DistilBertModel,DistilBertPreTrainedModel:()=>s.DistilBertPreTrainedModel,DistilBertTokenizer:()=>r.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>h.DonutFeatureExtractor,DonutImageProcessor:()=>h.DonutImageProcessor,DonutSwinModel:()=>s.DonutSwinModel,DonutSwinPreTrainedModel:()=>s.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>s.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,EfficientNetModel:()=>s.EfficientNetModel,EfficientNetPreTrainedModel:()=>s.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>s.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>s.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>s.ElectraForSequenceClassification,ElectraForTokenClassification:()=>s.ElectraForTokenClassification,ElectraModel:()=>s.ElectraModel,ElectraPreTrainedModel:()=>s.ElectraPreTrainedModel,ElectraTokenizer:()=>r.ElectraTokenizer,EosTokenCriteria:()=>x.EosTokenCriteria,EsmForMaskedLM:()=>s.EsmForMaskedLM,EsmForSequenceClassification:()=>s.EsmForSequenceClassification,EsmForTokenClassification:()=>s.EsmForTokenClassification,EsmModel:()=>s.EsmModel,EsmPreTrainedModel:()=>s.EsmPreTrainedModel,EsmTokenizer:()=>r.EsmTokenizer,ExaoneForCausalLM:()=>s.ExaoneForCausalLM,ExaoneModel:()=>s.ExaoneModel,ExaonePreTrainedModel:()=>s.ExaonePreTrainedModel,FFT:()=>d.FFT,FalconForCausalLM:()=>s.FalconForCausalLM,FalconModel:()=>s.FalconModel,FalconPreTrainedModel:()=>s.FalconPreTrainedModel,FalconTokenizer:()=>r.FalconTokenizer,FastViTForImageClassification:()=>s.FastViTForImageClassification,FastViTModel:()=>s.FastViTModel,FastViTPreTrainedModel:()=>s.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>u.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>s.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>s.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>h.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>s.GLPNForDepthEstimation,GLPNModel:()=>s.GLPNModel,GLPNPreTrainedModel:()=>s.GLPNPreTrainedModel,GPT2LMHeadModel:()=>s.GPT2LMHeadModel,GPT2Model:()=>s.GPT2Model,GPT2PreTrainedModel:()=>s.GPT2PreTrainedModel,GPT2Tokenizer:()=>r.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>s.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>s.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>s.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>s.GPTJForCausalLM,GPTJModel:()=>s.GPTJModel,GPTJPreTrainedModel:()=>s.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>s.GPTNeoForCausalLM,GPTNeoModel:()=>s.GPTNeoModel,GPTNeoPreTrainedModel:()=>s.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>s.GPTNeoXForCausalLM,GPTNeoXModel:()=>s.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>s.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>r.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>s.Gemma2ForCausalLM,Gemma2Model:()=>s.Gemma2Model,Gemma2PreTrainedModel:()=>s.Gemma2PreTrainedModel,GemmaForCausalLM:()=>s.GemmaForCausalLM,GemmaModel:()=>s.GemmaModel,GemmaPreTrainedModel:()=>s.GemmaPreTrainedModel,GemmaTokenizer:()=>r.GemmaTokenizer,GraniteForCausalLM:()=>s.GraniteForCausalLM,GraniteModel:()=>s.GraniteModel,GranitePreTrainedModel:()=>s.GranitePreTrainedModel,Grok1Tokenizer:()=>r.Grok1Tokenizer,GroupViTModel:()=>s.GroupViTModel,GroupViTPreTrainedModel:()=>s.GroupViTPreTrainedModel,HerbertTokenizer:()=>r.HerbertTokenizer,HieraForImageClassification:()=>s.HieraForImageClassification,HieraModel:()=>s.HieraModel,HieraPreTrainedModel:()=>s.HieraPreTrainedModel,HubertForCTC:()=>s.HubertForCTC,HubertForSequenceClassification:()=>s.HubertForSequenceClassification,HubertModel:()=>s.HubertModel,HubertPreTrainedModel:()=>s.HubertPreTrainedModel,IJepaForImageClassification:()=>s.IJepaForImageClassification,IJepaModel:()=>s.IJepaModel,IJepaPreTrainedModel:()=>s.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>s.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>h.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>s.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>p.ImageFeatureExtractor,ImageMattingOutput:()=>s.ImageMattingOutput,ImageProcessor:()=>m.ImageProcessor,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>x.InterruptableStoppingCriteria,JAISLMHeadModel:()=>s.JAISLMHeadModel,JAISModel:()=>s.JAISModel,JAISPreTrainedModel:()=>s.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>h.JinaCLIPImageProcessor,JinaCLIPModel:()=>s.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>s.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>s.JinaCLIPTextModel,JinaCLIPVisionModel:()=>s.JinaCLIPVisionModel,LlamaForCausalLM:()=>s.LlamaForCausalLM,LlamaModel:()=>s.LlamaModel,LlamaPreTrainedModel:()=>s.LlamaPreTrainedModel,LlamaTokenizer:()=>r.LlamaTokenizer,LlavaForConditionalGeneration:()=>s.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>s.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>h.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>s.LlavaPreTrainedModel,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>s.LongT5ForConditionalGeneration,LongT5Model:()=>s.LongT5Model,LongT5PreTrainedModel:()=>s.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>s.M2M100ForConditionalGeneration,M2M100Model:()=>s.M2M100Model,M2M100PreTrainedModel:()=>s.M2M100PreTrainedModel,M2M100Tokenizer:()=>r.M2M100Tokenizer,MBart50Tokenizer:()=>r.MBart50Tokenizer,MBartForCausalLM:()=>s.MBartForCausalLM,MBartForConditionalGeneration:()=>s.MBartForConditionalGeneration,MBartForSequenceClassification:()=>s.MBartForSequenceClassification,MBartModel:()=>s.MBartModel,MBartPreTrainedModel:()=>s.MBartPreTrainedModel,MBartTokenizer:()=>r.MBartTokenizer,MPNetForMaskedLM:()=>s.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>s.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>s.MPNetForSequenceClassification,MPNetForTokenClassification:()=>s.MPNetForTokenClassification,MPNetModel:()=>s.MPNetModel,MPNetPreTrainedModel:()=>s.MPNetPreTrainedModel,MPNetTokenizer:()=>r.MPNetTokenizer,MT5ForConditionalGeneration:()=>s.MT5ForConditionalGeneration,MT5Model:()=>s.MT5Model,MT5PreTrainedModel:()=>s.MT5PreTrainedModel,MarianMTModel:()=>s.MarianMTModel,MarianModel:()=>s.MarianModel,MarianPreTrainedModel:()=>s.MarianPreTrainedModel,MarianTokenizer:()=>r.MarianTokenizer,Mask2FormerImageProcessor:()=>h.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>h.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>s.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>h.MaskFormerImageProcessor,MaskFormerModel:()=>s.MaskFormerModel,MaskFormerPreTrainedModel:()=>s.MaskFormerPreTrainedModel,MaskedLMOutput:()=>s.MaskedLMOutput,MaxLengthCriteria:()=>x.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>s.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>s.MgpstrModelOutput,MgpstrPreTrainedModel:()=>s.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>r.MgpstrTokenizer,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>s.MistralForCausalLM,MistralModel:()=>s.MistralModel,MistralPreTrainedModel:()=>s.MistralPreTrainedModel,MobileBertForMaskedLM:()=>s.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>s.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>s.MobileBertForSequenceClassification,MobileBertModel:()=>s.MobileBertModel,MobileBertPreTrainedModel:()=>s.MobileBertPreTrainedModel,MobileBertTokenizer:()=>r.MobileBertTokenizer,MobileLLMForCausalLM:()=>s.MobileLLMForCausalLM,MobileLLMModel:()=>s.MobileLLMModel,MobileLLMPreTrainedModel:()=>s.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>h.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>s.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>h.MobileNetV1ImageProcessor,MobileNetV1Model:()=>s.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>s.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>h.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>s.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>h.MobileNetV2ImageProcessor,MobileNetV2Model:()=>s.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>s.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>h.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>s.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>h.MobileNetV3ImageProcessor,MobileNetV3Model:()=>s.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>s.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>h.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>s.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>h.MobileNetV4ImageProcessor,MobileNetV4Model:()=>s.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>s.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>h.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>s.MobileViTForImageClassification,MobileViTImageProcessor:()=>h.MobileViTImageProcessor,MobileViTModel:()=>s.MobileViTModel,MobileViTPreTrainedModel:()=>s.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>s.MobileViTV2ForImageClassification,MobileViTV2Model:()=>s.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>s.MobileViTV2PreTrainedModel,ModelOutput:()=>s.ModelOutput,Moondream1ForConditionalGeneration:()=>s.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>p.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>s.MoonshineForConditionalGeneration,MoonshineModel:()=>s.MoonshineModel,MoonshinePreTrainedModel:()=>s.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>s.MptForCausalLM,MptModel:()=>s.MptModel,MptPreTrainedModel:()=>s.MptPreTrainedModel,MultiModalityCausalLM:()=>s.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>s.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>s.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>s.MusicgenForConditionalGeneration,MusicgenModel:()=>s.MusicgenModel,MusicgenPreTrainedModel:()=>s.MusicgenPreTrainedModel,NllbTokenizer:()=>r.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>s.NomicBertModel,NomicBertPreTrainedModel:()=>s.NomicBertPreTrainedModel,NougatImageProcessor:()=>h.NougatImageProcessor,NougatTokenizer:()=>r.NougatTokenizer,OPTForCausalLM:()=>s.OPTForCausalLM,OPTModel:()=>s.OPTModel,OPTPreTrainedModel:()=>s.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>s.Olmo2ForCausalLM,Olmo2Model:()=>s.Olmo2Model,Olmo2PreTrainedModel:()=>s.Olmo2PreTrainedModel,OlmoForCausalLM:()=>s.OlmoForCausalLM,OlmoModel:()=>s.OlmoModel,OlmoPreTrainedModel:()=>s.OlmoPreTrainedModel,OpenELMForCausalLM:()=>s.OpenELMForCausalLM,OpenELMModel:()=>s.OpenELMModel,OpenELMPreTrainedModel:()=>s.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>h.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>s.OwlViTForObjectDetection,OwlViTImageProcessor:()=>h.OwlViTImageProcessor,OwlViTModel:()=>s.OwlViTModel,OwlViTPreTrainedModel:()=>s.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>s.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>h.Owlv2ImageProcessor,Owlv2Model:()=>s.Owlv2Model,Owlv2PreTrainedModel:()=>s.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>s.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>s.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>s.PatchTSMixerForPrediction,PatchTSMixerModel:()=>s.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>s.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>s.PatchTSTForPrediction,PatchTSTModel:()=>s.PatchTSTModel,PatchTSTPreTrainedModel:()=>s.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>s.Phi3ForCausalLM,Phi3Model:()=>s.Phi3Model,Phi3PreTrainedModel:()=>s.Phi3PreTrainedModel,Phi3VForCausalLM:()=>s.Phi3VForCausalLM,Phi3VImageProcessor:()=>h.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>s.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>s.PhiForCausalLM,PhiModel:()=>s.PhiModel,PhiPreTrainedModel:()=>s.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>s.PreTrainedModel,PreTrainedTokenizer:()=>r.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>s.PretrainedMixin,Processor:()=>g.Processor,PvtForImageClassification:()=>s.PvtForImageClassification,PvtImageProcessor:()=>h.PvtImageProcessor,PvtModel:()=>s.PvtModel,PvtPreTrainedModel:()=>s.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>s.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>s.PyAnnoteModel,PyAnnotePreTrainedModel:()=>s.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>s.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>s.Qwen2ForCausalLM,Qwen2Model:()=>s.Qwen2Model,Qwen2PreTrainedModel:()=>s.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>r.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>s.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>h.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>s.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,RTDetrForObjectDetection:()=>s.RTDetrForObjectDetection,RTDetrImageProcessor:()=>h.RTDetrImageProcessor,RTDetrModel:()=>s.RTDetrModel,RTDetrObjectDetectionOutput:()=>s.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>s.RTDetrPreTrainedModel,RawImage:()=>l.RawImage,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>s.ResNetForImageClassification,ResNetModel:()=>s.ResNetModel,ResNetPreTrainedModel:()=>s.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>s.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>s.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>s.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>s.RoFormerForTokenClassification,RoFormerModel:()=>s.RoFormerModel,RoFormerPreTrainedModel:()=>s.RoFormerPreTrainedModel,RoFormerTokenizer:()=>r.RoFormerTokenizer,RobertaForMaskedLM:()=>s.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>s.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>s.RobertaForSequenceClassification,RobertaForTokenClassification:()=>s.RobertaForTokenClassification,RobertaModel:()=>s.RobertaModel,RobertaPreTrainedModel:()=>s.RobertaPreTrainedModel,RobertaTokenizer:()=>r.RobertaTokenizer,SamImageProcessor:()=>h.SamImageProcessor,SamImageSegmentationOutput:()=>s.SamImageSegmentationOutput,SamModel:()=>s.SamModel,SamPreTrainedModel:()=>s.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>s.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>s.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>s.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>s.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>p.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>h.SegformerFeatureExtractor,SegformerForImageClassification:()=>s.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>s.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>h.SegformerImageProcessor,SegformerModel:()=>s.SegformerModel,SegformerPreTrainedModel:()=>s.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>s.Seq2SeqLMOutput,SequenceClassifierOutput:()=>s.SequenceClassifierOutput,SiglipImageProcessor:()=>h.SiglipImageProcessor,SiglipModel:()=>s.SiglipModel,SiglipPreTrainedModel:()=>s.SiglipPreTrainedModel,SiglipTextModel:()=>s.SiglipTextModel,SiglipTokenizer:()=>r.SiglipTokenizer,SiglipVisionModel:()=>s.SiglipVisionModel,SpeechT5FeatureExtractor:()=>p.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>s.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>s.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>s.SpeechT5HifiGan,SpeechT5Model:()=>s.SpeechT5Model,SpeechT5PreTrainedModel:()=>s.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>r.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>s.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>s.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>s.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>s.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>s.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>r.SqueezeBertTokenizer,StableLmForCausalLM:()=>s.StableLmForCausalLM,StableLmModel:()=>s.StableLmModel,StableLmPreTrainedModel:()=>s.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>s.Starcoder2ForCausalLM,Starcoder2Model:()=>s.Starcoder2Model,Starcoder2PreTrainedModel:()=>s.Starcoder2PreTrainedModel,StoppingCriteria:()=>x.StoppingCriteria,StoppingCriteriaList:()=>x.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>s.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>h.Swin2SRImageProcessor,Swin2SRModel:()=>s.Swin2SRModel,Swin2SRPreTrainedModel:()=>s.Swin2SRPreTrainedModel,SwinForImageClassification:()=>s.SwinForImageClassification,SwinModel:()=>s.SwinModel,SwinPreTrainedModel:()=>s.SwinPreTrainedModel,T5ForConditionalGeneration:()=>s.T5ForConditionalGeneration,T5Model:()=>s.T5Model,T5PreTrainedModel:()=>s.T5PreTrainedModel,T5Tokenizer:()=>r.T5Tokenizer,TableTransformerForObjectDetection:()=>s.TableTransformerForObjectDetection,TableTransformerModel:()=>s.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>s.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>s.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>c.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>b.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>s.TokenClassifierOutput,TokenizerModel:()=>r.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>s.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>s.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>s.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>s.UniSpeechForSequenceClassification,UniSpeechModel:()=>s.UniSpeechModel,UniSpeechPreTrainedModel:()=>s.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>s.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>s.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>s.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>s.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>s.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>h.VLMImageProcessor,ViTFeatureExtractor:()=>h.ViTFeatureExtractor,ViTForImageClassification:()=>s.ViTForImageClassification,ViTImageProcessor:()=>h.ViTImageProcessor,ViTMAEModel:()=>s.ViTMAEModel,ViTMAEPreTrainedModel:()=>s.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>s.ViTMSNForImageClassification,ViTMSNModel:()=>s.ViTMSNModel,ViTMSNPreTrainedModel:()=>s.ViTMSNPreTrainedModel,ViTModel:()=>s.ViTModel,ViTPreTrainedModel:()=>s.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>s.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>s.VitMatteForImageMatting,VitMatteImageProcessor:()=>h.VitMatteImageProcessor,VitMattePreTrainedModel:()=>s.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>s.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>h.VitPoseImageProcessor,VitPosePreTrainedModel:()=>s.VitPosePreTrainedModel,VitsModel:()=>s.VitsModel,VitsModelOutput:()=>s.VitsModelOutput,VitsPreTrainedModel:()=>s.VitsPreTrainedModel,VitsTokenizer:()=>r.VitsTokenizer,Wav2Vec2BertForCTC:()=>s.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>s.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>s.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>s.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>r.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>p.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>s.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>s.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>s.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>s.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>s.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>s.WavLMForAudioFrameClassification,WavLMForCTC:()=>s.WavLMForCTC,WavLMForSequenceClassification:()=>s.WavLMForSequenceClassification,WavLMForXVector:()=>s.WavLMForXVector,WavLMModel:()=>s.WavLMModel,WavLMPreTrainedModel:()=>s.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>p.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>s.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>s.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>p.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>s.WhisperForConditionalGeneration,WhisperModel:()=>s.WhisperModel,WhisperPreTrainedModel:()=>s.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>b.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>r.WhisperTokenizer,XLMForQuestionAnswering:()=>s.XLMForQuestionAnswering,XLMForSequenceClassification:()=>s.XLMForSequenceClassification,XLMForTokenClassification:()=>s.XLMForTokenClassification,XLMModel:()=>s.XLMModel,XLMPreTrainedModel:()=>s.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>s.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>s.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>s.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>s.XLMRobertaForTokenClassification,XLMRobertaModel:()=>s.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>s.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>r.XLMRobertaTokenizer,XLMTokenizer:()=>r.XLMTokenizer,XLMWithLMHeadModel:()=>s.XLMWithLMHeadModel,XVectorOutput:()=>s.XVectorOutput,YolosFeatureExtractor:()=>h.YolosFeatureExtractor,YolosForObjectDetection:()=>s.YolosForObjectDetection,YolosImageProcessor:()=>h.YolosImageProcessor,YolosModel:()=>s.YolosModel,YolosObjectDetectionOutput:()=>s.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>s.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>d.bankers_round,cat:()=>c.cat,cos_sim:()=>d.cos_sim,dot:()=>d.dot,dynamic_time_warping:()=>d.dynamic_time_warping,env:()=>e.env,full:()=>c.full,full_like:()=>c.full_like,getKeyValueShapes:()=>i.getKeyValueShapes,hamming:()=>a.hamming,hanning:()=>a.hanning,interpolate:()=>c.interpolate,interpolate_4d:()=>c.interpolate_4d,interpolate_data:()=>d.interpolate_data,is_chinese_char:()=>r.is_chinese_char,layer_norm:()=>c.layer_norm,load_image:()=>l.load_image,log_softmax:()=>d.log_softmax,magnitude:()=>d.magnitude,matmul:()=>c.matmul,max:()=>d.max,mean:()=>c.mean,mean_pooling:()=>c.mean_pooling,medianFilter:()=>d.medianFilter,mel_filter_bank:()=>a.mel_filter_bank,min:()=>d.min,ones:()=>c.ones,ones_like:()=>c.ones_like,permute:()=>c.permute,permute_data:()=>d.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>c.quantize_embeddings,rand:()=>c.rand,read_audio:()=>a.read_audio,rfft:()=>c.rfft,round:()=>d.round,slice:()=>c.slice,softmax:()=>d.softmax,spectrogram:()=>a.spectrogram,stack:()=>c.stack,std_mean:()=>c.std_mean,topk:()=>c.topk,window_function:()=>a.window_function,zeros:()=>c.zeros,zeros_like:()=>c.zeros_like});var e=n("./src/env.js"),t=n("./src/pipelines.js"),s=n("./src/models.js"),r=n("./src/tokenizers.js"),i=n("./src/configs.js"),a=n("./src/utils/audio.js"),l=n("./src/utils/image.js"),c=n("./src/utils/tensor.js"),d=n("./src/utils/maths.js"),u=n("./src/base/feature_extraction_utils.js"),p=n("./src/models/feature_extractors.js"),_=n("./src/models/auto/feature_extraction_auto.js"),m=n("./src/base/image_processors_utils.js"),h=n("./src/models/image_processors.js"),f=n("./src/models/auto/image_processing_auto.js"),g=n("./src/base/processing_utils.js"),w=n("./src/models/processors.js"),M=n("./src/models/auto/processing_auto.js"),b=n("./src/generation/streamers.js"),x=n("./src/generation/stopping_criteria.js"),y=n("./src/generation/logits_process.js")})();var i=exports;for(var a in o)i[a]=o[a];o.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
359
2
|
//# sourceMappingURL=transformers.min.cjs.map
|