diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 09cc8c331..b6ef08f83 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -203,7 +203,7 @@ function lineToBeIgnored(line: string, isFirstLine: boolean = false): boolean { const EditSlashCommand: SlashCommand = { name: "edit", - description: "Edit highlighted code", + description: "Edit selected code", run: async function* ({ ide, llm, input, history, contextItems, params }) { const contextItemToEdit = contextItems.find( (item: ContextItemWithId) => @@ -211,7 +211,7 @@ const EditSlashCommand: SlashCommand = { ); if (!contextItemToEdit) { - yield "Highlight (select and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first"; + yield "Select (highlight and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first"; return; } diff --git a/core/commands/slash/verticalEdit.ts b/core/commands/slash/verticalEdit.ts index 1013ceb8e..3bc20a058 100644 --- a/core/commands/slash/verticalEdit.ts +++ b/core/commands/slash/verticalEdit.ts @@ -213,7 +213,7 @@ export async function* streamDiffLines( const VerticalEditSlashCommand: SlashCommand = { name: "verticalEdit", - description: "Edit highlighted code with vertical diff", + description: "Edit selected code with vertical diff", run: async function* ({ ide, llm, input, contextItems }) { const contextItemToEdit = contextItems.find( (item: ContextItemWithId) => diff --git a/core/config/default.ts b/core/config/default.ts index 69b11ce01..5c43f6383 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -26,11 +26,11 @@ const defaultConfig: SerializedContinueConfig = { slashCommands: [ { name: "edit", - description: "Edit highlighted code", + description: "Edit selected code", }, { name: "comment", - description: "Write comments for the highlighted code", + description: "Write comments for the selected code", }, { name: "share", diff --git a/core/config/load.ts b/core/config/load.ts index 4e8795b10..36429c5e1 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -17,7 +17,7 @@ import { import { contextProviderClassFromName } from "../context/providers"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; -import { AllEmbeddingsProviders } from "../index/embeddings"; +import { AllEmbeddingsProviders } from "../indexing/embeddings"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 2e30a4b31..29562c57a 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -1,131 +1,10 @@ import { BaseContextProvider } from ".."; import { - Chunk, ContextItem, ContextProviderDescription, ContextProviderExtras, - ILLM, - ModelProvider, } from "../.."; -import { ExtensionIde } from "../../ide"; -import { getBasename } from "../../util"; - -const RERANK_PROMPT = ( - query: string, - documentId: string, - document: string -) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. - -Query: Where is the FastAPI server? -Snippet: -\`\`\`/Users/andrew/Desktop/server/main.py -from fastapi import FastAPI -app = FastAPI() -@app.get("/") -def read_root(): - return {{"Hello": "World"}} -\`\`\` -Relevant: Yes - -Query: Where in the documentation does it talk about the UI? -Snippet: -\`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs -fn bubble_sort(arr: &mut [T]) {{ - for i in 0..arr.len() {{ - for j in 1..arr.len() - i {{ - if arr[j - 1] > arr[j] {{ - arr.swap(j - 1, j); - }} - }} - }} -}} -\`\`\` -Relevant: No - -Query: ${query} -Snippet: -\`\`\`${documentId} -${document} -\`\`\` -Relevant: -`; - -const PARALLEL_PROVIDERS: ModelProvider[] = [ - "anthropic", - "bedrock", - "deepinfra", - "gemini", - "google-palm", - "huggingface-inference-api", - "huggingface-tgi", - "mistral", - "free-trial", - "replicate", - "together", -]; - -function llmCanGenerateInParallel(llm: ILLM): boolean { - if (llm.providerName === "openai") { - return llm.model.includes("gpt"); - } - - return PARALLEL_PROVIDERS.includes(llm.providerName); -} - -async function scoreChunk( - chunk: Chunk, - llm: ILLM, - query: string -): Promise { - const completion = await llm.complete( - RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), - { - maxTokens: 1, - model: - llm.providerName.startsWith("openai") && llm.model.startsWith("gpt-4") - ? "gpt-3.5-turbo" - : llm.model, - } - ); - - if (!completion) { - // TODO: Why is this happening? - return 0.0; - } - - let answer = completion - .trim() - .toLowerCase() - .replace(/"/g, "") - .replace(/'/g, ""); - - if (answer === "yes") { - return 1.0; - } else if (answer === "no") { - return 0.0; - } else { - console.warn( - `Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".` - ); - return 0.0; - } -} - -async function rerank( - chunks: Chunk[], - llm: ILLM, - query: string, - nFinal: number -): Promise { - const scores = await Promise.all( - chunks.map((chunk) => scoreChunk(chunk, llm, query)) - ); - const sorted = chunks - .map((chunk, i) => ({ chunk, score: scores[i] })) - .sort((a, b) => b.score - a.score); - - return sorted.map((s) => s.chunk).slice(0, nFinal); -} +import { retrieveContextItemsFromEmbeddings } from "../retrieval"; class CodebaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -140,49 +19,7 @@ class CodebaseContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras ): Promise { - if (!extras.embeddingsProvider) { - return []; - } - - const nRetrieve = this.options.nRetrieve || 20; - const nFinal = this.options.nFinal || 10; - const useReranking = - llmCanGenerateInParallel(extras.llm) && - (this.options.useReranking === undefined - ? false - : this.options.useReranking); - - // Similarity search - const [v] = await extras.embeddingsProvider.embed([extras.fullInput]); - let results = await new ExtensionIde().retrieveChunks( - v, - useReranking === false ? nFinal : nRetrieve, - [], - extras.embeddingsProvider.id - ); - - // Re-ranking - if (useReranking) { - results = await rerank(results, extras.llm, query, nFinal); - } - - return [ - ...results.map((r) => { - const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; - const description = `${r.filepath} (${r.startLine}-${r.endLine})`; - return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, - }; - }), - { - name: "Instructions", - description: "Instructions", - content: - "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", - }, - ]; + return retrieveContextItemsFromEmbeddings(extras, this.options, undefined); } async load(): Promise {} } diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts new file mode 100644 index 000000000..806b469b9 --- /dev/null +++ b/core/context/providers/FolderContextProvider.ts @@ -0,0 +1,27 @@ +import { BaseContextProvider } from ".."; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, +} from "../.."; +import { retrieveContextItemsFromEmbeddings } from "../retrieval"; + +class FolderContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "folder", + displayTitle: "Folder", + description: "Type to search", + dynamic: false, + requiresQuery: false, + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras + ): Promise { + return retrieveContextItemsFromEmbeddings(extras, this.options, query); + } + async load(): Promise {} +} + +export default FolderContextProvider; diff --git a/core/context/providers/context_provider_server.py b/core/context/providers/context_provider_server.py index 47f61c440..df423e571 100644 --- a/core/context/providers/context_provider_server.py +++ b/core/context/providers/context_provider_server.py @@ -1,3 +1,8 @@ +""" +This is an example of a server that can be used with the "http" context provider. +This can be useful if you want to write custom logic in another language, or on a server. +""" + import asyncio from fastapi import FastAPI diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 59666b679..fc3c6aee4 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -3,6 +3,7 @@ import { ContextProviderName } from "../.."; import CodebaseContextProvider from "./CodebaseContextProvider"; import DiffContextProvider from "./DiffContextProvider"; import FileTreeContextProvider from "./FileTreeContextProvider"; +import FolderContextProvider from "./FolderContextProvider"; import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider"; import GoogleContextProvider from "./GoogleContextProvider"; import HttpContextProvider from "./HttpContextProvider"; @@ -24,6 +25,7 @@ const Providers: (typeof BaseContextProvider)[] = [ SearchContextProvider, CodebaseContextProvider, ProblemsContextProvider, + FolderContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/context/retrieval.ts b/core/context/retrieval.ts new file mode 100644 index 000000000..d9a929d88 --- /dev/null +++ b/core/context/retrieval.ts @@ -0,0 +1,172 @@ +import { + Chunk, + ContextItem, + ContextProviderExtras, + ILLM, + ModelProvider, +} from ".."; +import { ExtensionIde } from "../ide"; +import { getBasename } from "../util"; + +const RERANK_PROMPT = ( + query: string, + documentId: string, + document: string +) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. + +Query: Where is the FastAPI server? +Snippet: +\`\`\`/Users/andrew/Desktop/server/main.py +from fastapi import FastAPI +app = FastAPI() +@app.get("/") +def read_root(): + return {{"Hello": "World"}} +\`\`\` +Relevant: Yes + +Query: Where in the documentation does it talk about the UI? +Snippet: +\`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs +fn bubble_sort(arr: &mut [T]) {{ + for i in 0..arr.len() {{ + for j in 1..arr.len() - i {{ + if arr[j - 1] > arr[j] {{ + arr.swap(j - 1, j); + }} + }} + }} +}} +\`\`\` +Relevant: No + +Query: ${query} +Snippet: +\`\`\`${documentId} +${document} +\`\`\` +Relevant: +`; + +const PARALLEL_PROVIDERS: ModelProvider[] = [ + "anthropic", + "bedrock", + "deepinfra", + "gemini", + "google-palm", + "huggingface-inference-api", + "huggingface-tgi", + "mistral", + "free-trial", + "replicate", + "together", +]; + +function llmCanGenerateInParallel(llm: ILLM): boolean { + if (llm.providerName === "openai") { + return llm.model.includes("gpt"); + } + + return PARALLEL_PROVIDERS.includes(llm.providerName); +} + +async function scoreChunk( + chunk: Chunk, + llm: ILLM, + query: string +): Promise { + const completion = await llm.complete( + RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), + { + maxTokens: 1, + model: + llm.providerName.startsWith("openai") && llm.model.startsWith("gpt-4") + ? "gpt-3.5-turbo" + : llm.model, + } + ); + + if (!completion) { + // TODO: Why is this happening? + return 0.0; + } + + let answer = completion + .trim() + .toLowerCase() + .replace(/"/g, "") + .replace(/'/g, ""); + + if (answer === "yes") { + return 1.0; + } else if (answer === "no") { + return 0.0; + } else { + console.warn( + `Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".` + ); + return 0.0; + } +} + +async function rerank( + chunks: Chunk[], + llm: ILLM, + query: string, + nFinal: number +): Promise { + const scores = await Promise.all( + chunks.map((chunk) => scoreChunk(chunk, llm, query)) + ); + const sorted = chunks + .map((chunk, i) => ({ chunk, score: scores[i] })) + .sort((a, b) => b.score - a.score); + + return sorted.map((s) => s.chunk).slice(0, nFinal); +} + +export async function retrieveContextItemsFromEmbeddings( + extras: ContextProviderExtras, + options: any | undefined, + filterDirectory: string | undefined +): Promise { + if (!extras.embeddingsProvider) { + return []; + } + + const nRetrieve = options?.nRetrieve || 20; + const nFinal = options?.nFinal || 8; + const useReranking = + llmCanGenerateInParallel(extras.llm) && + (options?.useReranking === undefined ? false : options?.useReranking); + + // Similarity search + let results = await new ExtensionIde().retrieveChunks( + extras.fullInput, + useReranking === false ? nFinal : nRetrieve, + filterDirectory + ); + + // Re-ranking + if (useReranking) { + results = await rerank(results, extras.llm, extras.fullInput, nFinal); + } + + return [ + ...results.map((r) => { + const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; + const description = `${r.filepath} (${r.startLine}-${r.endLine})`; + return { + name, + description, + content: `\`\`\`${name}\n${r.content}\n\`\`\``, + }; + }), + { + name: "Instructions", + description: "Instructions", + content: + "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", + }, + ]; +} diff --git a/core/ide/filesystem.ts b/core/ide/filesystem.ts index 5104c09b8..54771c9f2 100644 --- a/core/ide/filesystem.ts +++ b/core/ide/filesystem.ts @@ -48,6 +48,9 @@ class FileSystemIde implements IDE { }); }); } + listFolders(): Promise { + return Promise.resolve([]); + } writeFile(path: string, contents: string): Promise { return new Promise((resolve, reject) => { fs.writeFile(path, contents, (err) => { @@ -123,10 +126,9 @@ class FileSystemIde implements IDE { sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {} retrieveChunks( - v: number[], + text: string, n: number, - tags: string[], - providerId: string + directory: string | undefined ): Promise { return Promise.resolve([]); } diff --git a/core/ide/index.ts b/core/ide/index.ts index 706111847..e6d6f4a2e 100644 --- a/core/ide/index.ts +++ b/core/ide/index.ts @@ -30,6 +30,10 @@ export class ExtensionIde implements IDE { return await r("getWorkspaceDirs"); } + async listFolders(): Promise { + return await r("listFolders"); + } + _continueDir: string | null = null; async getContinueDir(): Promise { @@ -105,11 +109,10 @@ export class ExtensionIde implements IDE { } retrieveChunks( - v: number[], + text: string, n: number, - tags: string[], - providerId: string + directory: string | undefined ): Promise { - return r("retrieveChunks", { v, n, tags, providerId }); + return r("retrieveChunks", { text, n, directory }); } } diff --git a/core/index.d.ts b/core/index.d.ts index ad8e45da1..ee16aaec2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -275,6 +275,7 @@ export interface IDE { getDiff(): Promise; getTerminalContents(): Promise; listWorkspaceContents(directory?: string): Promise; + listFolders(): Promise; getWorkspaceDirs(): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; @@ -310,10 +311,9 @@ export interface IDE { tags: string[] ): void; retrieveChunks( - v: number[], + text: string, n: number, - tags: string[], - providerId: string + directory: string | undefined ): Promise; } @@ -365,7 +365,8 @@ type ContextProviderName = | "tree" | "http" | "codebase" - | "problems"; + | "problems" + | "folders"; type TemplateType = | "llama2" diff --git a/core/index/embeddings/TransformersJsEmbeddingsProvider.ts b/core/index/embeddings/TransformersJsEmbeddingsProvider.ts deleted file mode 100644 index a1500bf2a..000000000 --- a/core/index/embeddings/TransformersJsEmbeddingsProvider.ts +++ /dev/null @@ -1,23 +0,0 @@ -import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; - -class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { - providerName: string = "transformers.js"; - - get id(): string { - return "transformers.js"; - } - - constructor() { - super({ model: "all-MiniLM-L2-v6" }); - } - - embed(chunks: string[]) { - throw new Error( - "TransformersJsEmbeddingsProvider is only available in the browser" - ); - - return Promise.resolve([]); - } -} - -export default TransformersJsEmbeddingsProvider; diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts new file mode 100644 index 000000000..a883cca8e --- /dev/null +++ b/core/indexing/LanceDbIndex.ts @@ -0,0 +1,300 @@ +// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error +import { v4 as uuidv4 } from "uuid"; +import * as lancedb from "vectordb"; +import { Chunk, EmbeddingsProvider } from ".."; +import { getLanceDbPath } from "../util/paths"; +import { chunkDocument } from "./chunk/chunk"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { + CodebaseIndex, + IndexResultType, + IndexTag, + PathAndCacheKey, + RefreshIndexResults, +} from "./types"; + +export function tagToString(tag: IndexTag): string { + return `${tag.directory}::${tag.branch}::${tag.artifactId}`; +} + +// LanceDB converts to lowercase, so names must all be lowercase +interface LanceDbRow { + uuid: string; + path: string; + cachekey: string; + vector: number[]; + [key: string]: any; +} + +export class LanceDbIndex implements CodebaseIndex { + get artifactId(): string { + return "vectordb::" + this.embeddingsProvider.id; + } + + static MAX_CHUNK_SIZE = 512; + + embeddingsProvider: EmbeddingsProvider; + readFile: (filepath: string) => Promise; + + constructor( + embeddingsProvider: EmbeddingsProvider, + readFile: (filepath: string) => Promise + ) { + this.embeddingsProvider = embeddingsProvider; + this.readFile = readFile; + } + + private tableNameForTag(tag: IndexTag) { + return tagToString(tag).replace(/\//g, "").replace(/\\/g, ""); + } + + private async createSqliteCacheTable(db: DatabaseConnection) { + await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache ( + uuid TEXT PRIMARY KEY, + cacheKey TEXT NOT NULL, + path TEXT NOT NULL, + vector TEXT NOT NULL, + startLine INTEGER NOT NULL, + endLine INTEGER NOT NULL, + contents TEXT NOT NULL + )`); + } + + private async *computeChunks( + items: PathAndCacheKey[] + ): AsyncGenerator< + | [ + number, + LanceDbRow, + { startLine: number; endLine: number; contents: string }, + ] + | PathAndCacheKey + > { + const contents = await Promise.all( + items.map(({ path }) => this.readFile(path)) + ); + + for (let i = 0; i < items.length; i++) { + // Break into chunks + const content = contents[i]; + const chunks: Chunk[] = []; + + for await (let chunk of chunkDocument( + items[i].path, + content, + LanceDbIndex.MAX_CHUNK_SIZE, + items[i].cacheKey + )) { + chunks.push(chunk); + } + + if (chunks.length > 20) { + // Too many chunks to index, probably a larger file than we want to include + continue; + } + + // Calculate embeddings + const embeddings = await this.embeddingsProvider.embed( + chunks.map((c) => c.content) + ); + + // Create row format + for (let j = 0; j < chunks.length; j++) { + const progress = (i + j / chunks.length) / items.length; + const row = { + vector: embeddings[j], + path: items[i].path, + cachekey: items[i].cacheKey, + uuid: uuidv4(), + }; + const chunk = chunks[j]; + yield [ + progress, + row, + { + contents: chunk.content, + startLine: chunk.startLine, + endLine: chunk.endLine, + }, + ]; + } + + yield items[i]; + } + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: ( + items: PathAndCacheKey[], + resultType: IndexResultType + ) => void + ): AsyncGenerator { + const tableName = this.tableNameForTag(tag); + const db = await lancedb.connect(getLanceDbPath()); + + const sqlite = await SqliteDb.get(); + await this.createSqliteCacheTable(sqlite); + + // Compute + let table: lancedb.Table | undefined = undefined; + let needToCreateTable = true; + const existingTables = await db.tableNames(); + let computedRows: LanceDbRow[] = []; + + for await (const update of this.computeChunks(results.compute)) { + if (Array.isArray(update)) { + const [progress, row, data] = update; + computedRows.push(row); + + // Add the computed row to the cache + await sqlite.run( + "INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)", + row.uuid, + row.cachekey, + row.path, + JSON.stringify(row.vector), + data.startLine, + data.endLine, + data.contents + ); + + yield progress; + } else { + // Create table if needed, add computed rows + if (table) { + if (computedRows.length > 0) { + await table.add(computedRows); + } + } else if (existingTables.includes(tableName)) { + table = await db.openTable(tableName); + needToCreateTable = false; + if (computedRows.length > 0) { + await table.add(computedRows); + } + } else if (computedRows.length > 0) { + table = await db.createTable(tableName, computedRows); + needToCreateTable = false; + } + + computedRows = []; + + // Mark item complete + markComplete([update], IndexResultType.Compute); + } + } + + // Add tag - retrieve the computed info from lance sqlite cache + for (let { path, cacheKey } of results.addTag) { + const stmt = await sqlite.prepare( + "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ?", + cacheKey, + path + ); + const cachedItems = await stmt.all(); + + const lanceRows: LanceDbRow[] = cachedItems.map((item) => { + return { + path, + cachekey: cacheKey, + uuid: item.uuid, + vector: JSON.parse(item.vector), + }; + }); + + if (needToCreateTable && lanceRows.length > 0) { + table = await db.createTable(tableName, lanceRows); + needToCreateTable = false; + } else if (lanceRows.length > 0) { + await table!.add(lanceRows); + } + + markComplete([{ path, cacheKey }], IndexResultType.AddTag); + } + + // Delete or remove tag - remove from lance table) + if (!needToCreateTable) { + for (let { path, cacheKey } of [...results.removeTag, ...results.del]) { + // This is where the aforementioned lowercase conversion problem shows + await table!.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); + } + } + markComplete(results.removeTag, IndexResultType.RemoveTag); + + // Delete - also remove from sqlite cache + for (let { path, cacheKey } of results.del) { + await sqlite.run( + "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ?", + cacheKey, + path + ); + } + + markComplete(results.del, IndexResultType.Delete); + yield 1; + } + + private async _retrieveForTag( + tag: IndexTag, + n: number, + directory: string | undefined, + vector: number[], + db: lancedb.Connection + ): Promise { + const tableName = this.tableNameForTag(tag); + const tableNames = await db.tableNames(); + if (!tableNames.includes(tableName)) { + return []; + } + + const table = await db.openTable(tableName); + let query = table.search(vector); + if (directory) { + // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after + query = query.where(`path LIKE '${directory}%'`).limit(300); + } else { + query = query.limit(n); + } + const results = await query.execute(); + return results.slice(0, n) as any; + } + + async retrieve( + tags: IndexTag[], + text: string, + n: number, + directory: string | undefined + ): Promise { + const [vector] = await this.embeddingsProvider.embed([text]); + const db = await lancedb.connect(getLanceDbPath()); + + let allResults = []; + for (const tag of tags) { + const results = await this._retrieveForTag(tag, n, directory, vector, db); + allResults.push(...results); + } + + allResults = allResults + .sort((a, b) => b._distance - a._distance) + .slice(0, n); + + const sqliteDb = await SqliteDb.get(); + const data = await sqliteDb.all( + `SELECT * FROM lance_db_cache WHERE uuid in (${allResults + .map((r) => `'${r.uuid}'`) + .join(",")})` + ); + + return data.map((d) => { + return { + digest: d.cacheKey, + filepath: d.path, + startLine: d.startLine, + endLine: d.endLine, + index: 0, + content: d.contents, + }; + }); + } +} diff --git a/core/index/chunk/basic.ts b/core/indexing/chunk/basic.ts similarity index 100% rename from core/index/chunk/basic.ts rename to core/indexing/chunk/basic.ts diff --git a/core/index/chunk/chunk.ts b/core/indexing/chunk/chunk.ts similarity index 90% rename from core/index/chunk/chunk.ts rename to core/indexing/chunk/chunk.ts index a2fc13fab..425dd377d 100644 --- a/core/index/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -1,6 +1,6 @@ import { Chunk, ChunkWithoutID } from "../.."; import { basicChunker } from "./basic"; -import { codeChunker, fileExtensionToLanguage } from "./code"; +import { codeChunker, supportedLanguages } from "./code"; async function* chunkDocumentWithoutId( filepath: string, @@ -13,7 +13,7 @@ async function* chunkDocumentWithoutId( const segs = filepath.split("."); const ext = segs[segs.length - 1]; - if (ext in fileExtensionToLanguage) { + if (ext in supportedLanguages) { try { for await (const chunk of codeChunker(filepath, contents, maxChunkSize)) { yield chunk; diff --git a/core/index/chunk/code.ts b/core/indexing/chunk/code.ts similarity index 58% rename from core/index/chunk/code.ts rename to core/indexing/chunk/code.ts index 3dfe3a824..7cc10edb1 100644 --- a/core/index/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -1,36 +1,92 @@ +// import treeSitterBash from "tree-sitter-wasms/out/tree-sitter-bash.wasm"; +// import treeSitterC from "tree-sitter-wasms/out/tree-sitter-c.wasm"; +// import treeSitterCSharp from "tree-sitter-wasms/out/tree-sitter-c_sharp.wasm"; +// import treeSitterCpp from "tree-sitter-wasms/out/tree-sitter-cpp.wasm"; +// import treeSitterCss from "tree-sitter-wasms/out/tree-sitter-css.wasm"; +// // import treeSitterElisp from "tree-sitter-wasms/out/tree-sitter-elisp.wasm" +// // import treeSitterElixir from "tree-sitter-wasms/out/tree-sitter-elixir.wasm" +// import treeSitterElm from "tree-sitter-wasms/out/tree-sitter-elm.wasm"; +// // import treeSitterEmbeddedTemplate from "tree-sitter-wasms/out/tree-sitter-embedded_template.wasm" +// import treeSitterGo from "tree-sitter-wasms/out/tree-sitter-go.wasm"; +// import treeSitterHtml from "tree-sitter-wasms/out/tree-sitter-html.wasm"; +// import treeSitterJava from "tree-sitter-wasms/out/tree-sitter-java.wasm"; +// import treeSitterJavascript from "tree-sitter-wasms/out/tree-sitter-javascript.wasm"; +// import treeSitterJson from "tree-sitter-wasms/out/tree-sitter-json.wasm"; +// // import treeSitterLua from "tree-sitter-wasms/out/tree-sitter-lua.wasm" +// import treeSitterOcaml from "tree-sitter-wasms/out/tree-sitter-ocaml.wasm"; +// import treeSitterPhp from "tree-sitter-wasms/out/tree-sitter-php.wasm"; +// import treeSitterPython from "tree-sitter-wasms/out/tree-sitter-python.wasm"; +// // import treeSitterQl from "tree-sitter-wasms/out/tree-sitter-ql.wasm" +// // import treeSitterRescript from "tree-sitter-wasms/out/tree-sitter-rescript.wasm" +// import treeSitterRuby from "tree-sitter-wasms/out/tree-sitter-ruby.wasm"; +// import treeSitterRust from "tree-sitter-wasms/out/tree-sitter-rust.wasm"; +// // import treeSitterSystemRdl from "tree-sitter-wasms/out/tree-sitter-systemrdl.wasm" +// import treeSitterToml from "tree-sitter-wasms/out/tree-sitter-toml.wasm"; +// import treeSitterTsx from "tree-sitter-wasms/out/tree-sitter-tsx.wasm"; +// import treeSitterTypescript from "tree-sitter-wasms/out/tree-sitter-typescript.wasm"; +// import treeSitterVue from "tree-sitter-wasms/out/tree-sitter-vue.wasm"; +// import treeSitterYaml from "tree-sitter-wasms/out/tree-sitter-yaml.wasm"; + import Parser, { SyntaxNode } from "web-tree-sitter"; import { ChunkWithoutID } from "../.."; import { countTokens } from "../../llm/countTokens"; -export const fileExtensionToLanguage: { [key: string]: string } = { - py: "python", - js: "javascript", - html: "html", - java: "java", - go: "go", - rb: "ruby", - rs: "rust", - c: "c", +// export const fileExtensionToWasm: { [key: string]: string } = { +// py: treeSitterPython, +// js: treeSitterJavascript, +// html: treeSitterHtml, +// java: treeSitterJava, +// go: treeSitterGo, +// rb: treeSitterRuby, +// rs: treeSitterRust, +// c: treeSitterC, +// cpp: treeSitterCpp, +// cs: treeSitterCSharp, +// php: treeSitterPhp, +// css: treeSitterCss, +// bash: treeSitterBash, +// json: treeSitterJson, +// ts: treeSitterTypescript, +// tsx: treeSitterTsx, +// vue: treeSitterVue, +// yaml: treeSitterYaml, +// toml: treeSitterToml, +// ocaml: treeSitterOcaml, +// elm: treeSitterElm, +// // jl: treeSitterJulia, +// // swift: "swift", +// // kt: "kotlin", +// // scala: treeSitterScala, +// }; + +export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", - cs: "c_sharp", + cs: "csharp", php: "php", css: "css", bash: "bash", json: "json", - jl: "julia", - scala: "scala", ts: "typescript", tsx: "tsx", + vue: "vue", + yaml: "yaml", + toml: "toml", + ocaml: "ocaml", + elm: "elm", + rb: "ruby", + js: "javascript", + // jl: "julia", // swift: "swift", // kt: "kotlin", + // scala: "scala", }; async function getParserForFile(filepath: string) { await Parser.init(); const parser = new Parser(); const segs = filepath.split("."); - const wasmPath = `/tree-sitter/tree-sitter-${ - fileExtensionToLanguage[segs[segs.length - 1]] + const wasmPath = `${__dirname}/tree-sitter-wasms/tree-sitter-${ + supportedLanguages[segs[segs.length - 1]] }.wasm`; const Language = await Parser.Language.load(wasmPath); parser.setLanguage(Language); diff --git a/core/index/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts similarity index 100% rename from core/index/embeddings/BaseEmbeddingsProvider.ts rename to core/indexing/embeddings/BaseEmbeddingsProvider.ts diff --git a/core/index/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts similarity index 100% rename from core/index/embeddings/OllamaEmbeddingsProvider.ts rename to core/indexing/embeddings/OllamaEmbeddingsProvider.ts diff --git a/core/index/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts similarity index 100% rename from core/index/embeddings/OpenAIEmbeddingsProvider.ts rename to core/indexing/embeddings/OpenAIEmbeddingsProvider.ts diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts new file mode 100644 index 000000000..4773e6f0b --- /dev/null +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -0,0 +1,72 @@ +import { + PipelineType, + env, + pipeline, +} from "../../vendor/node_modules/@xenova/transformers"; + +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; + +env.allowLocalModels = true; +env.allowRemoteModels = false; +if (typeof window === "undefined") { + // The embeddings provider should just never be called in the browser + env.localModelPath = `${__dirname}/../models`; +} + +class EmbeddingsPipeline { + static task: PipelineType = "feature-extraction"; + static model = "all-MiniLM-L6-v2"; + static instance: any | null = null; + + static async getInstance() { + if (this.instance === null) { + this.instance = await pipeline(this.task, this.model); + } + + return this.instance; + } +} + +class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { + static MaxGroupSize: number = 4; + + constructor() { + super({ model: "all-MiniLM-L2-v6" }); + } + + get id(): string { + return "transformers-js"; + } + + async embed(chunks: string[]) { + let extractor = await EmbeddingsPipeline.getInstance(); + + if (!extractor) { + throw new Error("TransformerJS embeddings pipeline is not initialized"); + } + + if (chunks.length === 0) { + return []; + } + + let outputs = []; + for ( + let i = 0; + i < chunks.length; + i += TransformersJsEmbeddingsProvider.MaxGroupSize + ) { + let chunkGroup = chunks.slice( + i, + i + TransformersJsEmbeddingsProvider.MaxGroupSize + ); + let output = await extractor(chunkGroup, { + pooling: "mean", + normalize: true, + }); + outputs.push(...output.tolist()); + } + return outputs; + } +} + +export default TransformersJsEmbeddingsProvider; diff --git a/core/index/embeddings/index.ts b/core/indexing/embeddings/index.ts similarity index 100% rename from core/index/embeddings/index.ts rename to core/indexing/embeddings/index.ts diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts new file mode 100644 index 000000000..43a3c7f84 --- /dev/null +++ b/core/indexing/refreshIndex.ts @@ -0,0 +1,364 @@ +import crypto from "crypto"; +import { Database, open } from "sqlite"; +import sqlite3 from "sqlite3"; +import { getIndexSqlitePath } from "../util/paths"; +import { + CodebaseIndex, + IndexResultType, + IndexTag, + LastModifiedMap, + MarkCompleteCallback, + PathAndCacheKey, + RefreshIndexResults, +} from "./types"; + +export type DatabaseConnection = Database; + +export class SqliteDb { + static db: DatabaseConnection | null = null; + + private static async createTables(db: DatabaseConnection) { + await db.exec( + `CREATE TABLE IF NOT EXISTS tag_catalog ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + dir STRING NOT NULL, + branch STRING NOT NULL, + artifactId STRING NOT NULL, + path STRING NOT NULL, + cacheKey STRING NOT NULL, + lastUpdated INTEGER NOT NULL + )` + ); + + await db.exec( + `CREATE TABLE IF NOT EXISTS global_cache ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cacheKey STRING NOT NULL, + dir STRING NOT NULL, + branch STRING NOT NULL, + artifactId STRING NOT NULL + )` + ); + } + + static async get() { + if (SqliteDb.db) { + return SqliteDb.db; + } + + SqliteDb.db = await open({ + filename: getIndexSqlitePath(), + driver: sqlite3.Database, + }); + + await SqliteDb.createTables(SqliteDb.db); + + return SqliteDb.db; + } +} + +async function getSavedItemsForTag( + tag: IndexTag +): Promise<{ path: string; cacheKey: string; lastUpdated: number }[]> { + const db = await SqliteDb.get(); + const stmt = await db.prepare( + `SELECT path, cacheKey, lastUpdated FROM tag_catalog + WHERE dir = ? AND branch = ? AND artifactId = ?`, + tag.directory, + tag.branch, + tag.artifactId + ); + const rows = await stmt.all(); + return rows; +} + +interface PathAndOptionalCacheKey { + path: string; + cacheKey?: string; +} + +enum AddRemoveResultType { + Add = "add", + Remove = "remove", + UpdateNewVersion = "updateNewVersion", + UpdateOldVersion = "updateOldVersion", +} + +async function getAddRemoveForTag( + tag: IndexTag, + currentFiles: LastModifiedMap, + readFile: (path: string) => Promise +): Promise<[PathAndCacheKey[], PathAndCacheKey[], MarkCompleteCallback]> { + const newLastUpdatedTimestamp = Date.now(); + + const saved = await getSavedItemsForTag(tag); + + const add: PathAndCacheKey[] = []; + const updateNewVersion: PathAndCacheKey[] = []; + const updateOldVersion: PathAndCacheKey[] = []; + const remove: PathAndCacheKey[] = []; + + for (let item of saved) { + const { lastUpdated, ...pathAndCacheKey } = item; + + if (currentFiles[item.path] === undefined) { + // Was indexed, but no longer exists. Remove + remove.push(pathAndCacheKey); + } else { + // Exists in old and new, so determine whether it was updated + if (lastUpdated < currentFiles[item.path]) { + // Change was made after last update + updateNewVersion.push({ + path: pathAndCacheKey.path, + cacheKey: calculateHash(await readFile(pathAndCacheKey.path)), + }); + updateOldVersion.push(pathAndCacheKey); + } else { + // Already updated, do nothing + } + + // Remove so we can check leftovers afterward + delete currentFiles[item.path]; + } + } + + // Any leftover in current files need to be added + add.push( + ...(await Promise.all( + Object.keys(currentFiles).map(async (path) => { + const fileContents = await readFile(path); + return { path, cacheKey: calculateHash(fileContents) }; + }) + )) + ); + + // Create the markComplete callback function + const db = await SqliteDb.get(); + const itemToAction: { + [key: string]: [PathAndCacheKey, AddRemoveResultType]; + } = {}; + + async function markComplete(items: PathAndCacheKey[], _: IndexResultType) { + const actions = items.map((item) => itemToAction[JSON.stringify(item)]); + for (const [{ path, cacheKey }, resultType] of actions) { + switch (resultType) { + case AddRemoveResultType.Add: + await db.run( + `INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)`, + path, + cacheKey, + newLastUpdatedTimestamp, + tag.directory, + tag.branch, + tag.artifactId + ); + break; + case AddRemoveResultType.Remove: + await db.run( + `DELETE FROM tag_catalog WHERE + path IN (?) AND + dir = ? AND + branch = ? AND + artifactId = ? + `, + remove.map((r) => `'${r.path}'`).join(", "), + tag.directory, + tag.branch, + tag.artifactId + ); + break; + case AddRemoveResultType.UpdateNewVersion: + await db.run( + `UPDATE tag_catalog SET + cacheKey = ?, + lastUpdated = ? + WHERE + path = ? AND + dir = ? AND + branch = ? AND + artifactId = ? + `, + cacheKey, + newLastUpdatedTimestamp, + path, + tag.directory, + tag.branch, + tag.artifactId + ); + break; + case AddRemoveResultType.UpdateOldVersion: + break; + } + } + } + + for (let item of updateNewVersion) { + itemToAction[JSON.stringify(item)] = [ + item, + AddRemoveResultType.UpdateNewVersion, + ]; + } + for (let item of add) { + itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Add]; + } + for (let item of updateOldVersion) { + itemToAction[JSON.stringify(item)] = [ + item, + AddRemoveResultType.UpdateOldVersion, + ]; + } + for (let item of remove) { + itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Remove]; + } + + return [ + [...add, ...updateNewVersion], + [...remove, ...updateOldVersion], + markComplete, + ]; +} + +/** + * Check the global cache for items with this cacheKey for the given artifactId. + * Return all of the tags that it exists under, which could be an empty array + */ +async function getTagsFromGlobalCache( + cacheKey: string, + artifactId: string +): Promise { + const db = await SqliteDb.get(); + const stmt = await db.prepare( + `SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?` + ); + const rows = await stmt.all(cacheKey, artifactId); + return rows; +} + +function calculateHash(fileContents: string): string { + const hash = crypto.createHash("sha256"); + hash.update(fileContents); + return hash.digest("hex"); +} + +export async function getComputeDeleteAddRemove( + tag: IndexTag, + currentFiles: LastModifiedMap, + readFile: (path: string) => Promise +): Promise<[RefreshIndexResults, MarkCompleteCallback]> { + const [add, remove, markComplete] = await getAddRemoveForTag( + tag, + currentFiles, + readFile + ); + + const compute: PathAndCacheKey[] = []; + const del: PathAndCacheKey[] = []; + const addTag: PathAndCacheKey[] = []; + const removeTag: PathAndCacheKey[] = []; + + for (let { path, cacheKey } of add) { + const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId); + if (existingTags.length > 0) { + addTag.push({ path, cacheKey }); + } else { + compute.push({ path, cacheKey }); + } + } + + for (let { path, cacheKey } of remove) { + const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId); + if (existingTags.length > 1) { + removeTag.push({ path, cacheKey }); + } else { + if (existingTags.length === 0) { + console.warn("Existing tags should not be empty when trying to remove"); + } + + del.push({ path, cacheKey }); + } + } + + const results = { + compute, + del, + addTag, + removeTag, + }; + + const globalCacheIndex = await GlobalCacheCodeBaseIndex.create(); + + return [ + results, + async (items, resultType) => { + // Update tag catalog + markComplete(items, resultType); + + // Update the global cache + let results: any = { + compute: [], + del: [], + addTag: [], + removeTag: [], + }; + results[resultType] = items; + for await (let _ of globalCacheIndex.update(tag, results, () => {})) { + } + }, + ]; +} + +export class GlobalCacheCodeBaseIndex implements CodebaseIndex { + private db: DatabaseConnection; + + constructor(db: DatabaseConnection) { + this.db = db; + } + artifactId: string = "globalCache"; + + static async create(): Promise { + return new GlobalCacheCodeBaseIndex(await SqliteDb.get()); + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + _: MarkCompleteCallback + ): AsyncGenerator { + const add = [...results.compute, ...results.addTag]; + const remove = [...results.del, ...results.removeTag]; + await Promise.all([ + ...add.map(({ cacheKey }) => { + return this.computeOrAddTag(cacheKey, tag); + }), + ...remove.map(({ cacheKey }) => { + return this.deleteOrRemoveTag(cacheKey, tag); + }), + ]); + yield 1; + } + + private async computeOrAddTag( + cacheKey: string, + tag: IndexTag + ): Promise { + await this.db.run( + "INSERT INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)", + cacheKey, + tag.directory, + tag.branch, + tag.artifactId + ); + } + private async deleteOrRemoveTag( + cacheKey: string, + tag: IndexTag + ): Promise { + await this.db.run( + "DELETE FROM global_cache WHERE cacheKey = ? AND dir = ? AND branch = ? AND artifactId = ?", + cacheKey, + tag.directory, + tag.branch, + tag.artifactId + ); + } +} diff --git a/core/indexing/types.ts b/core/indexing/types.ts new file mode 100644 index 000000000..c63908a0e --- /dev/null +++ b/core/indexing/types.ts @@ -0,0 +1,44 @@ +export enum IndexResultType { + Compute = "compute", + Delete = "del", + AddTag = "addTag", + RemoveTag = "removeTag", +} + +export type MarkCompleteCallback = ( + items: PathAndCacheKey[], + resultType: IndexResultType +) => void; + +export interface CodebaseIndex { + artifactId: string; + update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: MarkCompleteCallback + ): AsyncGenerator; +} + +export type PathAndCacheKey = { + path: string; + cacheKey: string; +}; + +export interface IndexTag { + directory: string; + branch: string; + artifactId: string; +} + +export type RefreshIndexResults = { + compute: PathAndCacheKey[]; + del: PathAndCacheKey[]; + addTag: PathAndCacheKey[]; + removeTag: PathAndCacheKey[]; +}; + +export type LastModifiedMap = { + [path: string]: number; +}; + +export type RefreshIndex = (tag: IndexTag) => Promise; diff --git a/core/package-lock.json b/core/package-lock.json index 0da629464..e98dd51b3 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -9,13 +9,18 @@ "version": "1.0.0", "license": "Apache-2.0", "dependencies": { + "@xenova/transformers": "^2.14.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", + "vectordb": "^0.4.3", "web-tree-sitter": "^0.20.8" }, "devDependencies": { @@ -27,6 +32,26 @@ "ts-jest": "^29.1.1" } }, + "node_modules/@75lb/deep-merge": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz", + "integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==", + "dependencies": { + "lodash.assignwith": "^4.2.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@75lb/deep-merge/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/@ampproject/remapping": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", @@ -40,6 +65,33 @@ "node": ">=6.0.0" } }, + "node_modules/@apache-arrow/ts": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", + "integrity": "sha512-CtwAvLkK0CZv7xsYeCo91ml6PvlfzAmAJZkRYuz2GNBwfYufj5SVi0iuSMwIMkcU/szVwvLdzORSLa5PlF/2ug==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + } + }, + "node_modules/@apache-arrow/ts/node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/@apache-arrow/ts/node_modules/flatbuffers": { + "version": "23.5.26", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", + "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==" + }, "node_modules/@babel/code-frame": { "version": "7.23.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", @@ -134,21 +186,21 @@ } }, "node_modules/@babel/core": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.5.tgz", - "integrity": "sha512-Cwc2XjUrG4ilcfOw4wBAK+enbdgwAcAJCfGUItPBKR7Mjw4aEfAFYrLxeRp4jWgtNIKn3n2AlBOfwwafl+42/g==", + "version": "7.23.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.7.tgz", + "integrity": "sha512-+UpDgowcmqe36d4NwqvKsyPMlOLNGMsfMmQ5WGCu+siCe3t3dfe9njrzGfdN4qq+bcNUt0+Vw6haRxBOycs4dw==", "dev": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.5", - "@babel/helper-compilation-targets": "^7.22.15", + "@babel/generator": "^7.23.6", + "@babel/helper-compilation-targets": "^7.23.6", "@babel/helper-module-transforms": "^7.23.3", - "@babel/helpers": "^7.23.5", - "@babel/parser": "^7.23.5", + "@babel/helpers": "^7.23.7", + "@babel/parser": "^7.23.6", "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.5", - "@babel/types": "^7.23.5", + "@babel/traverse": "^7.23.7", + "@babel/types": "^7.23.6", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -164,12 +216,12 @@ } }, "node_modules/@babel/generator": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.5.tgz", - "integrity": "sha512-BPssCHrBD+0YrxviOa3QzpqwhNIXKEtOa2jQrm4FlmkC2apYgRnQcmPWiGZDlGxiNtltnUFolMe8497Esry+jA==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", "dev": true, "dependencies": { - "@babel/types": "^7.23.5", + "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" @@ -179,14 +231,14 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.15.tgz", - "integrity": "sha512-y6EEzULok0Qvz8yyLkCvVX+02ic+By2UdOhylwUOvOn9dvYc9mKICJuuU1n1XBI02YWsNsnrY1kc6DVbjcXbtw==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", + "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.22.9", - "@babel/helper-validator-option": "^7.22.15", - "browserslist": "^4.21.9", + "@babel/compat-data": "^7.23.5", + "@babel/helper-validator-option": "^7.23.5", + "browserslist": "^4.22.2", "lru-cache": "^5.1.1", "semver": "^6.3.1" }, @@ -320,14 +372,14 @@ } }, "node_modules/@babel/helpers": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.5.tgz", - "integrity": "sha512-oO7us8FzTEsG3U6ag9MfdF1iA/7Z6dz+MtFhifZk8C8o453rGJFFWUP1t+ULM9TUIAzC9uxXEiXjOiVMyd7QPg==", + "version": "7.23.8", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.8.tgz", + "integrity": "sha512-KDqYz4PiOWvDFrdHLPhKtCThtIcKVy6avWD2oG4GEvyQ+XDZwHD4YQd+H2vNMnq2rkdxsDkU82T+Vk8U/WXHRQ==", "dev": true, "dependencies": { "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.5", - "@babel/types": "^7.23.5" + "@babel/traverse": "^7.23.7", + "@babel/types": "^7.23.6" }, "engines": { "node": ">=6.9.0" @@ -419,9 +471,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.5.tgz", - "integrity": "sha512-hOOqoiNXrmGdFbhgCzu6GiURxUgM27Xwd/aPuu8RfHEZPBzL1Z54okAHAQjXfcQNwvrlkAmAp4SlRTZ45vlthQ==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", + "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", "dev": true, "bin": { "parser": "bin/babel-parser.js" @@ -622,20 +674,20 @@ } }, "node_modules/@babel/traverse": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.5.tgz", - "integrity": "sha512-czx7Xy5a6sapWWRx61m1Ke1Ra4vczu1mCTtJam5zRTBOonfdJ+S/B6HYmGYu3fJtr8GGET3si6IhgWVBhJ/m8w==", + "version": "7.23.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz", + "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==", "dev": true, "dependencies": { "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.5", + "@babel/generator": "^7.23.6", "@babel/helper-environment-visitor": "^7.22.20", "@babel/helper-function-name": "^7.23.0", "@babel/helper-hoist-variables": "^7.22.5", "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.23.5", - "@babel/types": "^7.23.5", - "debug": "^4.1.0", + "@babel/parser": "^7.23.6", + "@babel/types": "^7.23.6", + "debug": "^4.3.1", "globals": "^11.1.0" }, "engines": { @@ -643,9 +695,9 @@ } }, "node_modules/@babel/types": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.5.tgz", - "integrity": "sha512-ON5kSOJwVO6xXVRTvOI0eOnWe7VdUcIpsovGo9U/Br4Ie4UVFQTboO2cYnDhAGU6Fp+UxSiT+pMft0SMHfuq6w==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz", + "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==", "dev": true, "dependencies": { "@babel/helper-string-parser": "^7.23.4", @@ -662,30 +714,18 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "optional": true, - "peer": true, - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } + "node_modules/@gar/promisify": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz", + "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", + "optional": true }, - "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "optional": true, - "peer": true, - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" + "node_modules/@huggingface/jinja": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.1.2.tgz", + "integrity": "sha512-x5mpbfJt1nKmVep5WNP5VjNsjWApWNj8pPYI+uYMkBWH9bWUJmQmHt2lbf0VCoQd54Oq3XuFEh/UyoVh7rPxmg==", + "engines": { + "node": ">=18" } }, "node_modules/@istanbuljs/load-nyc-config": { @@ -1030,15 +1070,191 @@ "dev": true }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.20", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", - "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "version": "0.3.21", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz", + "integrity": "sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g==", "dev": true, "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.3.tgz", + "integrity": "sha512-47CvvSaV1EdUsFEpXUJApTk+hMzAhCxVizipCFUlXCgcmzpCDL86wNgJij/X9a+j6zADhIX//Lsu0qd/an/Bpw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-darwin-x64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.3.tgz", + "integrity": "sha512-UlZZv8CmJIuRJNJG+Y1VmFsGyPR8W/72Q5EwgMMsSES6zpMQ9pNdBDWhL3UGX6nMRgnbprkwYiWJ3xHhJvtqtw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.3.tgz", + "integrity": "sha512-L6NVJr/lKEd8+904FzZNpT8BGQMs2cHNYbGJMIaVvGnMiIJgKAFKtOyGtdDjoe1xRZoEw21yjRGksGbnRO5wHQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.3.tgz", + "integrity": "sha512-OBx3WF3pK0xNfFJeErmuD9R2QWLa3XdeZspyTsIrQmBDeKj3HKh8y7Scpx4NH5Y09+9JNqRRKRZN7OqWTYhITg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.3.tgz", + "integrity": "sha512-n9IvR81NXZKnSN91mrgeXbEyCiGM+YLJpOgbdHoEtMP04VDnS+iSU4jGOtQBKErvWeCJQaGFQ9qzdcVchpRGyw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@neon-rs/load": { + "version": "0.0.74", + "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", + "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" + }, + "node_modules/@npmcli/fs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz", + "integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==", + "optional": true, + "dependencies": { + "@gar/promisify": "^1.0.1", + "semver": "^7.3.5" + } + }, + "node_modules/@npmcli/fs/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/fs/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "optional": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/fs/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "optional": true + }, + "node_modules/@npmcli/move-file": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz", + "integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==", + "deprecated": "This functionality has been moved to @npmcli/fs", + "optional": true, + "dependencies": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -1063,37 +1279,14 @@ "@sinonjs/commons": "^3.0.0" } }, - "node_modules/@tsconfig/node10": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", - "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", - "dev": true, + "node_modules/@tootallnate/once": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", "optional": true, - "peer": true - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true, - "optional": true, - "peer": true - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true, - "optional": true, - "peer": true - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true, - "optional": true, - "peer": true + "engines": { + "node": ">= 6" + } }, "node_modules/@types/babel__core": { "version": "7.20.5", @@ -1109,9 +1302,9 @@ } }, "node_modules/@types/babel__generator": { - "version": "7.6.7", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.7.tgz", - "integrity": "sha512-6Sfsq+EaaLrw4RmdFWE9Onp63TOUue71AWb4Gpa6JxzgTYtimbM086WnYTy2U67AofR++QKCo08ZP6pwx8YFHQ==", + "version": "7.6.8", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", + "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", "dev": true, "dependencies": { "@babel/types": "^7.0.0" @@ -1128,14 +1321,24 @@ } }, "node_modules/@types/babel__traverse": { - "version": "7.20.4", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.4.tgz", - "integrity": "sha512-mSM/iKUk5fDDrEV/e83qY+Cr3I1+Q3qqTuEn++HAWYjEa1+NxZr6CNrcJGf2ZTnq4HoFGC3zaTPZTobCzCFukA==", + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.5.tgz", + "integrity": "sha512-WXCyOcRtH37HAUkpXhUduaxdm82b4GSlyTqajXviN4EfiuPgNYR109xMCKvpl6zPIpua0DGlMEDCq+g8EdoheQ==", "dev": true, "dependencies": { "@babel/types": "^7.20.7" } }, + "node_modules/@types/command-line-args": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.0.tgz", + "integrity": "sha512-UuKzKpJJ/Ief6ufIaIzr3A/0XnluX7RvFgwkV89Yzvm77wCh1kFaFmqN8XEnGcN62EuHdedQjEMb8mYxFLGPyA==" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", + "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -1189,6 +1392,11 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==" + }, "node_modules/@types/mustache": { "version": "4.2.5", "resolved": "https://registry.npmjs.org/@types/mustache/-/mustache-4.2.5.tgz", @@ -1196,22 +1404,27 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.10.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.3.tgz", - "integrity": "sha512-XJavIpZqiXID5Yxnxv3RUDKTN5b81ddNC3ecsA0SoFXz/QU8OGBwZGMomiq0zw+uuqbL/krztv/DINAQ/EV4gg==", + "version": "20.11.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.3.tgz", + "integrity": "sha512-nrlmbvGPNGaj84IJZXMPhQuCMEVTT/hXZMJJG/aIqVL9fKxqk814sGGtJA4GI6hpJSLQjpi6cn0Qx9eOf9SDVg==", "dependencies": { "undici-types": "~5.26.4" } }, "node_modules/@types/node-fetch": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.9.tgz", - "integrity": "sha512-bQVlnMLFJ2d35DkPNjEPmd9ueO/rh5EiaZt2bhqiSarPjZIuIV6bPQVqcrEyvNo+AfTrRGVazle1tl597w3gfA==", + "version": "2.6.10", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.10.tgz", + "integrity": "sha512-PPpPK6F9ALFTn59Ka3BaL+qGuipRfxNE8qVgkp0bVixeiR2c2/L+IVOiBdu9JhhT22sWnQEp6YyHGI2b2+CMcA==", "dependencies": { "@types/node": "*", "form-data": "^4.0.0" } }, + "node_modules/@types/pad-left": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@types/pad-left/-/pad-left-2.1.1.tgz", + "integrity": "sha512-Xd22WCRBydkGSApl5Bw0PhAOHKSVjNL3E3AwzKaps96IMraPqy5BvZIsBVK6JLwdybUzjHnuWVwpDd0JjTfHXA==" + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -1239,6 +1452,25 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "dev": true }, + "node_modules/@xenova/transformers": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.14.0.tgz", + "integrity": "sha512-rQ3O7SW5EM64b6XFZGx3XQ2cfiroefxUwU9ShfSpEZyhd082GvwNJJKndxgaukse1hZP1JUDoT0DfjDiq4IZiw==", + "dependencies": { + "@huggingface/jinja": "^0.1.0", + "onnxruntime-web": "1.14.0", + "sharp": "^0.32.0" + }, + "optionalDependencies": { + "onnxruntime-node": "1.14.0" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "optional": true + }, "node_modules/abort-controller": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", @@ -1250,29 +1482,16 @@ "node": ">=6.5" } }, - "node_modules/acorn": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", - "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", - "dev": true, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "optional": true, - "peer": true, - "bin": { - "acorn": "bin/acorn" + "dependencies": { + "debug": "4" }, "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.3.1", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.1.tgz", - "integrity": "sha512-TgUZgYvqZprrl7YldZNoa9OciCAyZR+Ejm9eXzKCmjsF5IKp/wgQ7Z/ZpjpGTIUPwrHQIcYeI8qDh4PsEwxMbw==", - "dev": true, - "optional": true, - "peer": true, - "engines": { - "node": ">=0.4.0" + "node": ">= 6.0.0" } }, "node_modules/agentkeepalive": { @@ -1286,6 +1505,19 @@ "node": ">= 8.0.0" } }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "optional": true, + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -1305,7 +1537,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, + "devOptional": true, "engines": { "node": ">=8" } @@ -1314,7 +1546,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "dependencies": { "color-convert": "^2.0.1" }, @@ -1338,13 +1569,54 @@ "node": ">= 8" } }, - "node_modules/arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true, + "node_modules/apache-arrow": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-14.0.2.tgz", + "integrity": "sha512-EBO2xJN36/XoY81nhLcwCJgFwkboDZeyNQ+OPsG7bCoQjc2BT0aTyH/MR6SrL+LirSNz+cYqjGRlupMMlP1aEg==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/apache-arrow/node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/apache-arrow/node_modules/flatbuffers": { + "version": "23.5.26", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", + "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==" + }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "optional": true + }, + "node_modules/are-we-there-yet": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-3.0.1.tgz", + "integrity": "sha512-QZW4EDmGwlYur0Yyf/b2uGucHQMa8aFUP7eu9ddR73vvhFyt4V0Vl3QHPcTNJ8l6qYOBdxgXdnBXQrHilfRQBg==", "optional": true, - "peer": true + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } }, "node_modules/argparse": { "version": "1.0.10", @@ -1355,11 +1627,34 @@ "sprintf-js": "~1.0.2" } }, + "node_modules/array-back": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", + "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", + "engines": { + "node": ">=6" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, + "node_modules/axios": { + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", + "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/b4a": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", + "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" + }, "node_modules/babel-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", @@ -1471,7 +1766,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "devOptional": true }, "node_modules/base-64": { "version": "0.1.0", @@ -1497,11 +1792,29 @@ } ] }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, + "devOptional": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1572,12 +1885,82 @@ "node-int64": "^0.4.0" } }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/cacache": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", + "integrity": "sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==", + "optional": true, + "dependencies": { + "@npmcli/fs": "^1.0.0", + "@npmcli/move-file": "^1.0.1", + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "glob": "^7.1.4", + "infer-owner": "^1.0.4", + "lru-cache": "^6.0.0", + "minipass": "^3.1.1", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.2", + "mkdirp": "^1.0.3", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.0.2", + "unique-filename": "^1.1.1" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/cacache/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cacache/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "optional": true + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -1597,9 +1980,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001566", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001566.tgz", - "integrity": "sha512-ggIhCsTxmITBAMmK8yZjEhCO5/47jKXPu6Dha/wuCS4JePVL+3uiDEBuhu2aIoT+bqTOR8L76Ip1ARL9xYsEJA==", + "version": "1.0.30001576", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001576.tgz", + "integrity": "sha512-ff5BdakGe2P3SQsMsiqmt1Lc8221NR1VzHj5jXN5vBny9A6fpze94HiVV/n7XRosOlsShJcvMv5mdnpjOGCEgg==", "dev": true, "funding": [ { @@ -1620,7 +2003,6 @@ "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -1632,6 +2014,20 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, "node_modules/char-regex": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", @@ -1649,6 +2045,14 @@ "node": "*" } }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, "node_modules/ci-info": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", @@ -1670,6 +2074,15 @@ "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", "dev": true }, + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "optional": true, + "engines": { + "node": ">=6" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -1700,11 +2113,22 @@ "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", "dev": true }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "dependencies": { "color-name": "~1.1.4" }, @@ -1715,8 +2139,25 @@ "node_modules/color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "optional": true, + "bin": { + "color-support": "bin.js" + } }, "node_modules/combined-stream": { "version": "1.0.8", @@ -1729,11 +2170,61 @@ "node": ">= 0.8" } }, + "node_modules/command-line-args": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", + "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==", + "dependencies": { + "array-back": "^3.1.0", + "find-replace": "^3.0.0", + "lodash.camelcase": "^4.3.0", + "typical": "^4.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/command-line-usage": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.1.tgz", + "integrity": "sha512-NCyznE//MuTjwi3y84QVUGEOT+P5oto1e1Pk/jFPVdPPfsG03qpTIl3yw6etR+v73d0lXsoojRpvbru2sqePxQ==", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^3.0.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/command-line-usage/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/command-line-usage/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true + "devOptional": true + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "optional": true }, "node_modules/convert-source-map": { "version": "2.0.0", @@ -1762,14 +2253,6 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, - "node_modules/create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true, - "optional": true, - "peer": true - }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -1796,7 +2279,7 @@ "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, + "devOptional": true, "dependencies": { "ms": "2.1.2" }, @@ -1809,6 +2292,20 @@ } } }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/dedent": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", @@ -1823,6 +2320,14 @@ } } }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -1840,6 +2345,20 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "optional": true + }, + "node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "engines": { + "node": ">=8" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -1849,17 +2368,6 @@ "node": ">=8" } }, - "node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true, - "optional": true, - "peer": true, - "engines": { - "node": ">=0.3.1" - } - }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -1890,9 +2398,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.4.606", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.606.tgz", - "integrity": "sha512-Zdv0XuhfyWZUsQ5Uq59d43ZmZOdoGZNWjeN4WCxxlQaP8crAWdnWcTxfHKcaJl6PW2SWpHx6DsxSx7v6KcGCuw==", + "version": "1.4.632", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.632.tgz", + "integrity": "sha512-JGmudTwg7yxMYvR/gWbalqqQiyu7WTFv2Xu3vw4cJHXPFxNgAk0oy8UHaer8nLF4lZJa+rNoj6GsrKIVJTV6Tw==", "dev": true }, "node_modules/emittery": { @@ -1911,7 +2419,39 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true + "devOptional": true + }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/err-code": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", + "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", + "optional": true }, "node_modules/error-ex": { "version": "1.3.2", @@ -1993,6 +2533,14 @@ "node": ">= 0.8.0" } }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "engines": { + "node": ">=6" + } + }, "node_modules/expect": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", @@ -2009,6 +2557,11 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", + "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==" + }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -2032,6 +2585,11 @@ "bser": "2.1.1" } }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==" + }, "node_modules/fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", @@ -2044,6 +2602,17 @@ "node": ">=8" } }, + "node_modules/find-replace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", + "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", + "dependencies": { + "array-back": "^3.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/find-up": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", @@ -2057,6 +2626,30 @@ "node": ">=8" } }, + "node_modules/flatbuffers": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", + "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==" + }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/form-data": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", @@ -2095,11 +2688,27 @@ "node": ">= 14" } }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true + "devOptional": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -2124,6 +2733,25 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/gauge": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz", + "integrity": "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==", + "optional": true, + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^3.0.7", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -2163,11 +2791,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==" + }, "node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, + "devOptional": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -2196,7 +2829,12 @@ "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true + "devOptional": true + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==" }, "node_modules/handlebars": { "version": "4.7.8", @@ -2222,11 +2860,16 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, "engines": { "node": ">=8" } }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "optional": true + }, "node_modules/hasown": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", @@ -2245,6 +2888,39 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", + "optional": true + }, + "node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "optional": true, + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -2262,6 +2938,37 @@ "ms": "^2.0.0" } }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/import-local": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", @@ -2285,16 +2992,31 @@ "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.8.19" } }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", + "optional": true + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, + "devOptional": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -2303,8 +3025,18 @@ "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "node_modules/ip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==", + "optional": true }, "node_modules/is-arrayish": { "version": "0.2.1", @@ -2333,7 +3065,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, + "devOptional": true, "engines": { "node": ">=8" } @@ -2347,6 +3079,12 @@ "node": ">=6" } }, + "node_modules/is-lambda": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", + "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==", + "optional": true + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -2372,7 +3110,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true + "devOptional": true }, "node_modules/istanbul-lib-coverage": { "version": "3.2.2", @@ -3100,6 +3838,14 @@ "node": ">=4" } }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -3154,12 +3900,27 @@ "node": ">=8" } }, + "node_modules/lodash.assignwith": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz", + "integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", "dev": true }, + "node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -3223,6 +3984,51 @@ "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true }, + "node_modules/make-fetch-happen": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz", + "integrity": "sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==", + "optional": true, + "dependencies": { + "agentkeepalive": "^4.1.3", + "cacache": "^15.2.0", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^6.0.0", + "minipass": "^3.1.3", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^1.3.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.2", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.0.0", + "ssri": "^8.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/make-fetch-happen/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-fetch-happen/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "optional": true + }, "node_modules/makeerror": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", @@ -3289,11 +4095,22 @@ "node": ">=6" } }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, + "devOptional": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -3309,22 +4126,196 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-collect": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz", + "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-fetch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz", + "integrity": "sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==", + "optional": true, + "dependencies": { + "minipass": "^3.1.0", + "minipass-sized": "^1.0.3", + "minizlib": "^2.0.0" + }, + "engines": { + "node": ">=8" + }, + "optionalDependencies": { + "encoding": "^0.1.12" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", + "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", + "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", + "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==" + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, + "node_modules/node-abi": { + "version": "3.54.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.54.0.tgz", + "integrity": "sha512-p7eGEiQil0YUV3ItH4/tBb781L5impVmmx2E9FRKF7d18XXzp4PGT2tdYMFY6wQqgxD0IwNZOiSJ0/K0fSi/OA==", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-abi/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-abi/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-abi/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/node-addon-api": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", + "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==" + }, "node_modules/node-domexception": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", @@ -3362,6 +4353,63 @@ } } }, + "node_modules/node-gyp": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-8.4.1.tgz", + "integrity": "sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==", + "optional": true, + "dependencies": { + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^9.1.0", + "nopt": "^5.0.0", + "npmlog": "^6.0.0", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.2", + "which": "^2.0.2" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": ">= 10.12.0" + } + }, + "node_modules/node-gyp/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-gyp/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "optional": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-gyp/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "optional": true + }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -3374,6 +4422,21 @@ "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", "dev": true }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "optional": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -3395,11 +4458,25 @@ "node": ">=8" } }, + "node_modules/npmlog": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-6.0.2.tgz", + "integrity": "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==", + "optional": true, + "dependencies": { + "are-we-there-yet": "^3.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^4.0.3", + "set-blocking": "^2.0.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "dependencies": { "wrappy": "1" } @@ -3419,10 +4496,50 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/onnx-proto": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", + "integrity": "sha512-aldMOB3HRoo6q/phyB6QRQxSt895HNNw82BNyZ2CMh4bjeKv7g/c+VpAFtJuEMVfYLMbRx61hbuqnKceLeDcDA==", + "dependencies": { + "protobufjs": "^6.8.8" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.14.0.tgz", + "integrity": "sha512-3LJpegM2iMNRX2wUmtYfeX/ytfOzNwAWKSq1HbRrKc9+uqG/FsEA0bbKZl1btQeZaXhC26l44NWpNUeXPII7Ew==" + }, + "node_modules/onnxruntime-node": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz", + "integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==", + "optional": true, + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "onnxruntime-common": "~1.14.0" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.14.0.tgz", + "integrity": "sha512-Kcqf43UMfW8mCydVGcX9OMXI2VN17c0p6XvR7IPSZzBf/6lteBzXHvcEVWDPmCKuGombl997HgLqj91F11DzXw==", + "dependencies": { + "flatbuffers": "^1.12.0", + "guid-typescript": "^1.0.9", + "long": "^4.0.0", + "onnx-proto": "^4.0.4", + "onnxruntime-common": "~1.14.0", + "platform": "^1.3.6" + } + }, "node_modules/openai": { - "version": "4.20.1", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.20.1.tgz", - "integrity": "sha512-Dd3q8EvINfganZFtg6V36HjrMaihqRgIcKiHua4Nq9aw/PxOP48dhbsk8x5klrxajt5Lpnc1KTOG5i1S6BKAJA==", + "version": "4.24.7", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.24.7.tgz", + "integrity": "sha512-JUesECWPtsDHO0TlZGb6q73hnAmXUdzj9NrwgZeL4lqlRt/kR1sWrXoy8LocxN/6uOtitywvcJqe0O1PLkG45g==", "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", @@ -3439,9 +4556,9 @@ } }, "node_modules/openai/node_modules/@types/node": { - "version": "18.19.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.3.tgz", - "integrity": "sha512-k5fggr14DwAytoA/t8rPrIz++lXK7/DqckthCmoZOKNsEbJkId4Z//BqgApXBUGrGddrigYa1oqheo/7YmW4rg==", + "version": "18.19.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.7.tgz", + "integrity": "sha512-IGRJfoNX10N/PfrReRZ1br/7SQ+2vF/tK3KXNwzXz82D32z5dMQEoOlFew18nLSN+vMNcLY4GrKfzwi/yWI8/w==", "dependencies": { "undici-types": "~5.26.4" } @@ -3488,6 +4605,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "optional": true, + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", @@ -3497,6 +4629,17 @@ "node": ">=6" } }, + "node_modules/pad-left": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", + "integrity": "sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA==", + "dependencies": { + "repeat-string": "^1.5.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -3528,7 +4671,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -3587,6 +4730,67 @@ "node": ">=8" } }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==" + }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", + "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" + }, + "node_modules/prebuild-install/node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/prebuild-install/node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/pretty-format": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", @@ -3613,6 +4817,25 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==", + "optional": true + }, + "node_modules/promise-retry": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", + "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", + "optional": true, + "dependencies": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/prompts": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", @@ -3626,6 +4849,45 @@ "node": ">= 6" } }, + "node_modules/protobufjs": { + "version": "6.11.4", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.4.tgz", + "integrity": "sha512-5kQWPaJHi1WoCpjTGszzQ32PG2F4+wRY6BmAT4Vfw56Q2FZ4YZzK20xUYQH4YkfehY1e6QSICrJquM6xXZNcrw==", + "hasInstallScript": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/long": "^4.0.1", + "@types/node": ">=13.7.0", + "long": "^4.0.0" + }, + "bin": { + "pbjs": "bin/pbjs", + "pbts": "bin/pbts" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, "node_modules/pure-rand": { "version": "6.0.4", "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz", @@ -3642,12 +4904,60 @@ } ] }, + "node_modules/queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==" + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/rc/node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/react-is": { "version": "18.2.0", "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", "dev": true }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "engines": { + "node": ">=0.10" + } + }, "node_modules/replicate": { "version": "0.23.0", "resolved": "https://registry.npmjs.org/replicate/-/replicate-0.23.0.tgz", @@ -3715,6 +5025,55 @@ "node": ">=10" } }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "optional": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "optional": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "optional": true + }, "node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -3724,6 +5083,64 @@ "semver": "bin/semver.js" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "optional": true + }, + "node_modules/sharp": { + "version": "0.32.6", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", + "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==", + "hasInstallScript": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.2", + "node-addon-api": "^6.1.0", + "prebuild-install": "^7.1.1", + "semver": "^7.5.4", + "simple-get": "^4.0.1", + "tar-fs": "^3.0.4", + "tunnel-agent": "^0.6.0" + }, + "engines": { + "node": ">=14.15.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/sharp/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -3749,7 +5166,63 @@ "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true + "devOptional": true + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/simple-swizzle/node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" }, "node_modules/sisteransi": { "version": "1.0.5", @@ -3766,6 +5239,44 @@ "node": ">=8" } }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "optional": true, + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", + "optional": true, + "dependencies": { + "ip": "^2.0.0", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.13.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-6.2.1.tgz", + "integrity": "sha512-a6KW9G+6B3nWZ1yB8G7pJwL3ggLy1uTzKAgCb7ttblwqdz9fMGJUuTy3uFzEP48FAs9FLILlmzDlE2JJhVQaXQ==", + "optional": true, + "dependencies": { + "agent-base": "^6.0.2", + "debug": "^4.3.3", + "socks": "^2.6.2" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -3790,6 +5301,51 @@ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "dev": true }, + "node_modules/sqlite": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/sqlite/-/sqlite-5.1.1.tgz", + "integrity": "sha512-oBkezXa2hnkfuJwUo44Hl9hS3er+YFtueifoajrgidvqsJRQFpc5fKoAkAor1O5ZnLoa28GBScfHXs8j0K358Q==" + }, + "node_modules/sqlite3": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-5.1.7.tgz", + "integrity": "sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==", + "hasInstallScript": true, + "dependencies": { + "bindings": "^1.5.0", + "node-addon-api": "^7.0.0", + "prebuild-install": "^7.1.1", + "tar": "^6.1.11" + }, + "optionalDependencies": { + "node-gyp": "8.x" + }, + "peerDependencies": { + "node-gyp": "8.x" + }, + "peerDependenciesMeta": { + "node-gyp": { + "optional": true + } + } + }, + "node_modules/sqlite3/node_modules/node-addon-api": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.0.0.tgz", + "integrity": "sha512-vgbBJTS4m5/KkE16t5Ly0WW9hz46swAstv0hYYwMtbG7AznRhNyfLRe8HZAiWIpcHzoO7HxhLuBQj9rJ/Ho0ZA==" + }, + "node_modules/ssri": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz", + "integrity": "sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==", + "optional": true, + "dependencies": { + "minipass": "^3.1.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -3802,6 +5358,31 @@ "node": ">=10" } }, + "node_modules/stream-read-all": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz", + "integrity": "sha512-EWZT9XOceBPlVJRrYcykW8jyRSZYbkb/0ZK36uLEmoWVO5gxBOnntNTseNzfREsqxqdfEGQrD8SXQ3QWbBmq8A==", + "engines": { + "node": ">=10" + } + }, + "node_modules/streamx": { + "version": "2.15.6", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz", + "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==", + "dependencies": { + "fast-fifo": "^1.1.0", + "queue-tick": "^1.0.1" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", @@ -3819,7 +5400,7 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, + "devOptional": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -3833,7 +5414,7 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, + "devOptional": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -3875,7 +5456,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -3895,6 +5475,91 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/table-layout": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz", + "integrity": "sha512-rpyNZYRw+/C+dYkcQ3Pr+rLxW4CfHpXjPDnG7lYhdRoUcZTUt+KEsX+94RGp/aVp/MQU35JCITv2T/beY4m+hw==", + "dependencies": { + "@75lb/deep-merge": "^1.1.1", + "array-back": "^6.2.2", + "command-line-args": "^5.2.1", + "command-line-usage": "^7.0.0", + "stream-read-all": "^3.0.1", + "typical": "^7.1.1", + "wordwrapjs": "^5.1.0" + }, + "bin": { + "table-layout": "bin/cli.js" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/tar": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.0.tgz", + "integrity": "sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar-fs": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz", + "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==", + "dependencies": { + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^3.1.5" + } + }, + "node_modules/tar-stream": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.6.tgz", + "integrity": "sha512-B/UyjYwPpMBv+PaFSWAmtYjwdrlEaZQEhMIBFNC5oEG8lpiW8XjcSdmEaClj28ArfKScKHs2nshz3k2le6crsg==", + "dependencies": { + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" + } + }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/test-exclude": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", @@ -3941,6 +5606,11 @@ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" }, + "node_modules/tree-sitter-wasms": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.6.tgz", + "integrity": "sha512-Q7XG/tNYc/rJrUzCELB2t6Y9Ivk8tzCqQFpJNXWdLmycNE68yTMpS8atr2PGtskiIbg4ai13cZ6Y3hNMDmWJZA==" + }, "node_modules/ts-jest": { "version": "29.1.1", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.1.tgz", @@ -4017,49 +5687,20 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "node_modules/ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", - "dev": true, - "optional": true, - "peer": true, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" + "safe-buffer": "^5.0.1" }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } + "engines": { + "node": "*" } }, "node_modules/type-detect": { @@ -4097,6 +5738,14 @@ "node": ">=14.17" } }, + "node_modules/typical": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", + "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", + "engines": { + "node": ">=8" + } + }, "node_modules/uglify-js": { "version": "3.17.4", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", @@ -4114,6 +5763,24 @@ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" }, + "node_modules/unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "optional": true, + "dependencies": { + "unique-slug": "^2.0.0" + } + }, + "node_modules/unique-slug": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", + "optional": true, + "dependencies": { + "imurmurhash": "^0.1.4" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", @@ -4144,6 +5811,11 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, "node_modules/uuid": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", @@ -4156,14 +5828,6 @@ "uuid": "dist/bin/uuid" } }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true, - "optional": true, - "peer": true - }, "node_modules/v8-to-istanbul": { "version": "9.2.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.2.0.tgz", @@ -4178,6 +5842,33 @@ "node": ">=10.12.0" } }, + "node_modules/vectordb": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.3.tgz", + "integrity": "sha512-7ToixoZgAB/hn44EE4ftcdE74SGRX+wmGejatTQodFBiYD9RQLW8LIuGo8MmT+AkYEDAuOR98jTEFUwnEU5sqA==", + "cpu": [ + "x64", + "arm64" + ], + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@apache-arrow/ts": "^14.0.2", + "@neon-rs/load": "^0.0.74", + "apache-arrow": "^14.0.2", + "axios": "^1.4.0" + }, + "optionalDependencies": { + "@lancedb/vectordb-darwin-arm64": "0.4.3", + "@lancedb/vectordb-darwin-x64": "0.4.3", + "@lancedb/vectordb-linux-arm64-gnu": "0.4.3", + "@lancedb/vectordb-linux-x64-gnu": "0.4.3", + "@lancedb/vectordb-win32-x64-msvc": "0.4.3" + } + }, "node_modules/walker": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", @@ -4188,9 +5879,9 @@ } }, "node_modules/web-streams-polyfill": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", - "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.2.tgz", + "integrity": "sha512-3pRGuxRF5gpuZc0W+EpwQRmCD7gRqcDOMt688KmdlDAgAyaB1XlN0zq2njfDNm44XVdIouE7pZ6GzbdyH47uIQ==", "engines": { "node": ">= 8" } @@ -4218,7 +5909,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, + "devOptional": true, "dependencies": { "isexe": "^2.0.0" }, @@ -4229,11 +5920,28 @@ "node": ">= 8" } }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "optional": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==" }, + "node_modules/wordwrapjs": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.0.tgz", + "integrity": "sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -4254,8 +5962,7 @@ "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/write-file-atomic": { "version": "4.0.2", @@ -4312,17 +6019,6 @@ "node": ">=12" } }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, - "optional": true, - "peer": true, - "engines": { - "node": ">=6" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/core/package.json b/core/package.json index b86030faa..8b966f847 100644 --- a/core/package.json +++ b/core/package.json @@ -16,13 +16,18 @@ "ts-jest": "^29.1.1" }, "dependencies": { + "@xenova/transformers": "^2.14.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", + "vectordb": "^0.4.3", "web-tree-sitter": "^0.20.8" } } diff --git a/core/util/paths.ts b/core/util/paths.ts index fedeb504f..82dbbcc23 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -22,6 +22,14 @@ export function getSessionsFolderPath(): string { return sessionsPath; } +export function getIndexFolderPath(): string { + const indexPath = path.join(getContinueGlobalPath(), "index"); + if (!fs.existsSync(indexPath)) { + fs.mkdirSync(indexPath); + } + return indexPath; +} + export function getSessionFilePath(sessionId: string): string { return path.join(getSessionsFolderPath(), `${sessionId}.json`); } @@ -159,3 +167,11 @@ export function migrate(id: string, callback: () => void) { callback(); } } + +export function getIndexSqlitePath(): string { + return path.join(getIndexFolderPath(), "index.sqlite"); +} + +export function getLanceDbPath(): string { + return path.join(getIndexFolderPath(), "lancedb"); +} diff --git a/core/vendor/.gitignore b/core/vendor/.gitignore new file mode 100644 index 000000000..736e8ae58 --- /dev/null +++ b/core/vendor/.gitignore @@ -0,0 +1 @@ +!node_modules \ No newline at end of file diff --git a/core/vendor/README.md b/core/vendor/README.md new file mode 100644 index 000000000..dc534eb76 --- /dev/null +++ b/core/vendor/README.md @@ -0,0 +1,3 @@ +# Vendored node_modules + +- transformers.js: to avoid the sharp dependency, which isn't used and has native dependencies diff --git a/core/vendor/node_modules/.package-lock.json b/core/vendor/node_modules/.package-lock.json new file mode 100644 index 000000000..75d2e2367 --- /dev/null +++ b/core/vendor/node_modules/.package-lock.json @@ -0,0 +1,713 @@ +{ + "name": "vendor", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@huggingface/jinja": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.1.2.tgz", + "integrity": "sha512-x5mpbfJt1nKmVep5WNP5VjNsjWApWNj8pPYI+uYMkBWH9bWUJmQmHt2lbf0VCoQd54Oq3XuFEh/UyoVh7rPxmg==", + "engines": { + "node": ">=18" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" + }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==" + }, + "node_modules/@types/node": { + "version": "20.11.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.3.tgz", + "integrity": "sha512-nrlmbvGPNGaj84IJZXMPhQuCMEVTT/hXZMJJG/aIqVL9fKxqk814sGGtJA4GI6hpJSLQjpi6cn0Qx9eOf9SDVg==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@xenova/transformers": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.14.0.tgz", + "integrity": "sha512-rQ3O7SW5EM64b6XFZGx3XQ2cfiroefxUwU9ShfSpEZyhd082GvwNJJKndxgaukse1hZP1JUDoT0DfjDiq4IZiw==", + "dependencies": { + "@huggingface/jinja": "^0.1.0", + "onnxruntime-web": "1.14.0", + "sharp": "^0.32.0" + }, + "optionalDependencies": { + "onnxruntime-node": "1.14.0" + } + }, + "node_modules/b4a": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", + "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" + }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", + "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==" + }, + "node_modules/flatbuffers": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", + "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==" + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, + "node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" + }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", + "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==" + }, + "node_modules/node-abi": { + "version": "3.54.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.54.0.tgz", + "integrity": "sha512-p7eGEiQil0YUV3ItH4/tBb781L5impVmmx2E9FRKF7d18XXzp4PGT2tdYMFY6wQqgxD0IwNZOiSJ0/K0fSi/OA==", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", + "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==" + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onnx-proto": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", + "integrity": "sha512-aldMOB3HRoo6q/phyB6QRQxSt895HNNw82BNyZ2CMh4bjeKv7g/c+VpAFtJuEMVfYLMbRx61hbuqnKceLeDcDA==", + "dependencies": { + "protobufjs": "^6.8.8" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.14.0.tgz", + "integrity": "sha512-3LJpegM2iMNRX2wUmtYfeX/ytfOzNwAWKSq1HbRrKc9+uqG/FsEA0bbKZl1btQeZaXhC26l44NWpNUeXPII7Ew==" + }, + "node_modules/onnxruntime-node": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz", + "integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==", + "optional": true, + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "onnxruntime-common": "~1.14.0" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.14.0.tgz", + "integrity": "sha512-Kcqf43UMfW8mCydVGcX9OMXI2VN17c0p6XvR7IPSZzBf/6lteBzXHvcEVWDPmCKuGombl997HgLqj91F11DzXw==", + "dependencies": { + "flatbuffers": "^1.12.0", + "guid-typescript": "^1.0.9", + "long": "^4.0.0", + "onnx-proto": "^4.0.4", + "onnxruntime-common": "~1.14.0", + "platform": "^1.3.6" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==" + }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", + "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/prebuild-install/node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/protobufjs": { + "version": "6.11.4", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.4.tgz", + "integrity": "sha512-5kQWPaJHi1WoCpjTGszzQ32PG2F4+wRY6BmAT4Vfw56Q2FZ4YZzK20xUYQH4YkfehY1e6QSICrJquM6xXZNcrw==", + "hasInstallScript": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/long": "^4.0.1", + "@types/node": ">=13.7.0", + "long": "^4.0.0" + }, + "bin": { + "pbjs": "bin/pbjs", + "pbts": "bin/pbts" + } + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==" + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.32.6", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", + "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==", + "hasInstallScript": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.2", + "node-addon-api": "^6.1.0", + "prebuild-install": "^7.1.1", + "semver": "^7.5.4", + "simple-get": "^4.0.1", + "tar-fs": "^3.0.4", + "tunnel-agent": "^0.6.0" + }, + "engines": { + "node": ">=14.15.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/streamx": { + "version": "2.15.6", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz", + "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==", + "dependencies": { + "fast-fifo": "^1.1.0", + "queue-tick": "^1.0.1" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz", + "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==", + "dependencies": { + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^3.1.5" + } + }, + "node_modules/tar-stream": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.6.tgz", + "integrity": "sha512-B/UyjYwPpMBv+PaFSWAmtYjwdrlEaZQEhMIBFNC5oEG8lpiW8XjcSdmEaClj28ArfKScKHs2nshz3k2le6crsg==", + "dependencies": { + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/LICENSE b/core/vendor/node_modules/@xenova/transformers/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/core/vendor/node_modules/@xenova/transformers/README.md b/core/vendor/node_modules/@xenova/transformers/README.md new file mode 100644 index 000000000..d0f9bec49 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/README.md @@ -0,0 +1,351 @@ + + +

+
+ + + + transformers.js javascript library logo + +
+

+ +

+ + NPM + + + NPM Downloads + + + jsDelivr Hits + + + License + + + Documentation + +

+ + +State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server! + +Transformers.js is designed to be functionally equivalent to Hugging Face's [transformers](https://github.com/huggingface/transformers) python library, meaning you can run the same pretrained models using a very similar API. These models support common tasks in different modalities, such as: + - 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation. + - 🖼️ **Computer Vision**: image classification, object detection, and segmentation. + - 🗣️ **Audio**: automatic speech recognition and audio classification. + - 🐙 **Multimodal**: zero-shot image classification. + +Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime). + +For more information, check out the full [documentation](https://huggingface.co/docs/transformers.js). + + +## Quick tour + + +It's super simple to translate from existing code! Just like the python library, we support the `pipeline` API. Pipelines group together a pretrained model with preprocessing of inputs and postprocessing of outputs, making it the easiest way to run models with the library. + + + + + + + + + + +
Python (original)Javascript (ours)
+ +```python +from transformers import pipeline + +# Allocate a pipeline for sentiment-analysis +pipe = pipeline('sentiment-analysis') + +out = pipe('I love transformers!') +# [{'label': 'POSITIVE', 'score': 0.999806941}] +``` + + + +```javascript +import { pipeline } from '@xenova/transformers'; + +// Allocate a pipeline for sentiment-analysis +let pipe = await pipeline('sentiment-analysis'); + +let out = await pipe('I love transformers!'); +// [{'label': 'POSITIVE', 'score': 0.999817686}] +``` + +
+ + +You can also use a different model by specifying the model id or path as the second argument to the `pipeline` function. For example: +```javascript +// Use a different model for sentiment-analysis +let pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment'); +``` + + +## Installation + + +To install via [NPM](https://www.npmjs.com/package/@xenova/transformers), run: +```bash +npm i @xenova/transformers +``` + +Alternatively, you can use it in vanilla JS, without any bundler, by using a CDN or static hosting. For example, using [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), you can import the library with: +```html + +``` + + +## Examples + +Want to jump straight in? Get started with one of our sample applications/templates: + +| Name | Description | Links | +|-------------------|----------------------------------|-------------------------------| +| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) | +| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) | +| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) | +| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) | +| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) | +| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) | +| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) | +| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) | +| Browser extension | Text classification extension | [code](./examples/extension/) | +| Electron | Text classification application | [code](./examples/electron/) | +| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) | +| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) | +| Node.js | Sentiment analysis API | [code](./examples/node/) | +| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) | + +Check out the Transformers.js [template](https://huggingface.co/new-space?template=static-templates%2Ftransformers.js) on Hugging Face to get started in one click! + + +## Custom usage + + + +By default, Transformers.js uses [hosted pretrained models](https://huggingface.co/models?library=transformers.js) and [precompiled WASM binaries](https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0/dist/), which should work out-of-the-box. You can customize this as follows: + + +### Settings + +```javascript +import { env } from '@xenova/transformers'; + +// Specify a custom location for models (defaults to '/models/'). +env.localModelPath = '/path/to/models/'; + +// Disable the loading of remote models from the Hugging Face Hub: +env.allowRemoteModels = false; + +// Set location of .wasm files. Defaults to use a CDN. +env.backends.onnx.wasm.wasmPaths = '/path/to/files/'; +``` + +For a full list of available settings, check out the [API Reference](https://huggingface.co/docs/transformers.js/api/env). + +### Convert your models to ONNX + +We recommend using our [conversion script](https://github.com/xenova/transformers.js/blob/main/scripts/convert.py) to convert your PyTorch, TensorFlow, or JAX models to ONNX in a single command. Behind the scenes, it uses [🤗 Optimum](https://huggingface.co/docs/optimum) to perform conversion and quantization of your model. + +```bash +python -m scripts.convert --quantize --model_id +``` + +For example, convert and quantize [bert-base-uncased](https://huggingface.co/bert-base-uncased) using: +```bash +python -m scripts.convert --quantize --model_id bert-base-uncased +``` + +This will save the following files to `./models/`: + +``` +bert-base-uncased/ +├── config.json +├── tokenizer.json +├── tokenizer_config.json +└── onnx/ + ├── model.onnx + └── model_quantized.onnx +``` + +For the full list of supported architectures, see the [Optimum documentation](https://huggingface.co/docs/optimum/main/en/exporters/onnx/overview). + + +## Supported tasks/models + +Here is the list of all tasks and architectures currently supported by Transformers.js. +If you don't see your task/model listed here or it is not yet supported, feel free +to open up a feature request [here](https://github.com/xenova/transformers.js/issues/new/choose). + +To find compatible models on the Hub, select the "transformers.js" library tag in the filter menu (or visit [this link](https://huggingface.co/models?library=transformers.js)). +You can refine your search by selecting the task you're interested in (e.g., [text-classification](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js)). + + +### Tasks + +#### Natural Language Processing + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ | +| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) | +| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) | +| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) | +| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) | +| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ | +| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) | +| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) | +| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) | +| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) | +| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) | +| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) | + +#### Vision + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) | +| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) | +| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) | +| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)
[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) | +| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ | +| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) | +| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ | +| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ | + +#### Audio + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) | +| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ | +| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) | +| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) | + + +#### Tabular + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ | +| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ | + + +#### Multimodal + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) | +| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) | +| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) | +| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ | +| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ | +| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)
[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) | +| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)
[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) | +| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)
[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) | + + +#### Reinforcement Learning + +| Task | ID | Description | Supported? | +|--------------------------|----|-------------|------------| +| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ | + + + +### Models + +1. **[ALBERT](https://huggingface.co/docs/transformers/model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut. +1. **[Audio Spectrogram Transformer](https://huggingface.co/docs/transformers/model_doc/audio-spectrogram-transformer)** (from MIT) released with the paper [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778) by Yuan Gong, Yu-An Chung, James Glass. +1. **[BART](https://huggingface.co/docs/transformers/model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer. +1. **[BEiT](https://huggingface.co/docs/transformers/model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei. +1. **[BERT](https://huggingface.co/docs/transformers/model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. +1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/). +1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot. +1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou. +1. **[CLAP](https://huggingface.co/docs/transformers/model_doc/clap)** (from LAION-AI) released with the paper [Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation](https://arxiv.org/abs/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov. +1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever. +1. **[CLIPSeg](https://huggingface.co/docs/transformers/model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo Lüddecke and Alexander Ecker. +1. **[CodeGen](https://huggingface.co/docs/transformers/model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong. +1. **[CodeLlama](https://huggingface.co/docs/transformers/model_doc/llama_code)** (from MetaAI) released with the paper [Code Llama: Open Foundation Models for Code](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/) by Baptiste Rozière, Jonas Gehring, Fabian Gloeckle, Sten Sootla, Itai Gat, Xiaoqing Ellen Tan, Yossi Adi, Jingyu Liu, Tal Remez, Jérémy Rapin, Artyom Kozhevnikov, Ivan Evtimov, Joanna Bitton, Manish Bhatt, Cristian Canton Ferrer, Aaron Grattafiori, Wenhan Xiong, Alexandre Défossez, Jade Copet, Faisal Azhar, Hugo Touvron, Louis Martin, Nicolas Usunier, Thomas Scialom, Gabriel Synnaeve. +1. **[ConvBERT](https://huggingface.co/docs/transformers/model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan. +1. **[ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie. +1. **[ConvNeXTV2](https://huggingface.co/docs/transformers/model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie. +1. **[DeBERTa](https://huggingface.co/docs/transformers/model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[DeBERTa-v2](https://huggingface.co/docs/transformers/model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[DeiT](https://huggingface.co/docs/transformers/model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou. +1. **[DETR](https://huggingface.co/docs/transformers/model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko. +1. **[DINOv2](https://huggingface.co/docs/transformers/model_doc/dinov2)** (from Meta AI) released with the paper [DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/abs/2304.07193) by Maxime Oquab, Timothée Darcet, Théo Moutakanni, Huy Vo, Marc Szafraniec, Vasil Khalidov, Pierre Fernandez, Daniel Haziza, Francisco Massa, Alaaeldin El-Nouby, Mahmoud Assran, Nicolas Ballas, Wojciech Galuba, Russell Howes, Po-Yao Huang, Shang-Wen Li, Ishan Misra, Michael Rabbat, Vasu Sharma, Gabriel Synnaeve, Hu Xu, Hervé Jegou, Julien Mairal, Patrick Labatut, Armand Joulin, Piotr Bojanowski. +1. **[DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT. +1. **[DiT](https://huggingface.co/docs/transformers/model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei. +1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park. +1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun. +1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning. +1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives. +1. **[Falcon](https://huggingface.co/docs/transformers/model_doc/falcon)** (from Technology Innovation Institute) by Almazrouei, Ebtesam and Alobeidli, Hamza and Alshamsi, Abdulaziz and Cappelli, Alessandro and Cojocaru, Ruxandra and Debbah, Merouane and Goffinet, Etienne and Heslow, Daniel and Launay, Julien and Malartic, Quentin and Noune, Badreddine and Pannier, Baptiste and Penedo, Guilherme. +1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei +1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim. +1. **[GPT Neo](https://huggingface.co/docs/transformers/model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy. +1. **[GPT NeoX](https://huggingface.co/docs/transformers/model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745) by Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, Samuel Weinbach +1. **[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**. +1. **[GPT-J](https://huggingface.co/docs/transformers/model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki. +1. **[GPTBigCode](https://huggingface.co/docs/transformers/model_doc/gpt_bigcode)** (from BigCode) released with the paper [SantaCoder: don't reach for the stars!](https://arxiv.org/abs/2301.03988) by Loubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, Logesh Kumar Umapathi, Carolyn Jane Anderson, Yangtian Zi, Joel Lamy Poirier, Hailey Schoelkopf, Sergey Troshin, Dmitry Abulkhanov, Manuel Romero, Michael Lappert, Francesco De Toni, Bernardo García del Río, Qian Liu, Shamik Bose, Urvashi Bhattacharyya, Terry Yue Zhuo, Ian Yu, Paulo Villegas, Marco Zocca, Sourab Mangrulkar, David Lansky, Huu Nguyen, Danish Contractor, Luis Villa, Jia Li, Dzmitry Bahdanau, Yacine Jernite, Sean Hughes, Daniel Fried, Arjun Guha, Harm de Vries, Leandro von Werra. +1. **[HerBERT](https://huggingface.co/docs/transformers/model_doc/herbert)** (from Allegro.pl, AGH University of Science and Technology) released with the paper [KLEJ: Comprehensive Benchmark for Polish Language Understanding](https://www.aclweb.org/anthology/2020.acl-main.111.pdf) by Piotr Rybak, Robert Mroczkowski, Janusz Tracz, Ireneusz Gawlik. +1. **[Hubert](https://huggingface.co/docs/transformers/model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed. +1. **[LongT5](https://huggingface.co/docs/transformers/model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang. +1. **[LLaMA](https://huggingface.co/docs/transformers/model_doc/llama)** (from The FAIR team of Meta AI) released with the paper [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/abs/2302.13971) by Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, Aurelien Rodriguez, Armand Joulin, Edouard Grave, Guillaume Lample. +1. **[Llama2](https://huggingface.co/docs/transformers/model_doc/llama2)** (from The FAIR team of Meta AI) released with the paper [Llama2: Open Foundation and Fine-Tuned Chat Models](https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/XXX) by Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton Ferrer, Moya Chen, Guillem Cucurull, David Esiobu, Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller, Cynthia Gao, Vedanuj Goswami, Naman Goyal, Anthony Hartshorn, Saghar Hosseini, Rui Hou, Hakan Inan, Marcin Kardas, Viktor Kerkez Madian Khabsa, Isabel Kloumann, Artem Korenev, Punit Singh Koura, Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Diana Liskovich, Yinghai Lu, Yuning Mao, Xavier Martinet, Todor Mihaylov, Pushka rMishra, Igor Molybog, Yixin Nie, Andrew Poulton, Jeremy Reizenstein, Rashi Rungta, Kalyan Saladi, Alan Schelten, Ruan Silva, Eric Michael Smith, Ranjan Subramanian, Xiaoqing EllenTan, Binh Tang, Ross Taylor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, Melanie Kambadur, Sharan Narang, Aurelien Rodriguez, Robert Stojnic, Sergey Edunov, Thomas Scialom. +1. **[M2M100](https://huggingface.co/docs/transformers/model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin. +1. **[MarianMT](https://huggingface.co/docs/transformers/model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team. +1. **[mBART](https://huggingface.co/docs/transformers/model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. +1. **[mBART-50](https://huggingface.co/docs/transformers/model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan. +1. **[Mistral](https://huggingface.co/docs/transformers/model_doc/mistral)** (from Mistral AI) by The [Mistral AI](https://mistral.ai) team: Albert Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lélio Renard Lavaud, Lucile Saulnier, Marie-Anne Lachaux, Pierre Stock, Teven Le Scao, Thibaut Lavril, Thomas Wang, Timothée Lacroix, William El Sayed. +1. **[MMS](https://huggingface.co/docs/transformers/model_doc/mms)** (from Facebook) released with the paper [Scaling Speech Technology to 1,000+ Languages](https://arxiv.org/abs/2305.13516) by Vineel Pratap, Andros Tjandra, Bowen Shi, Paden Tomasello, Arun Babu, Sayani Kundu, Ali Elkahky, Zhaoheng Ni, Apoorv Vyas, Maryam Fazel-Zarandi, Alexei Baevski, Yossi Adi, Xiaohui Zhang, Wei-Ning Hsu, Alexis Conneau, Michael Auli. +1. **[MobileBERT](https://huggingface.co/docs/transformers/model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou. +1. **[MobileViT](https://huggingface.co/docs/transformers/model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari. +1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. +1. **[MPT](https://huggingface.co/docs/transformers/model_doc/mpt)** (from MosaiML) released with the repository [llm-foundry](https://github.com/mosaicml/llm-foundry/) by the MosaicML NLP Team. +1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. +1. **[NLLB](https://huggingface.co/docs/transformers/model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team. +1. **[Nougat](https://huggingface.co/docs/transformers/model_doc/nougat)** (from Meta AI) released with the paper [Nougat: Neural Optical Understanding for Academic Documents](https://arxiv.org/abs/2308.13418) by Lukas Blecher, Guillem Cucurull, Thomas Scialom, Robert Stojnic. +1. **[OPT](https://huggingface.co/docs/transformers/master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al. +1. **[OWL-ViT](https://huggingface.co/docs/transformers/model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby. +1. **[Phi](https://huggingface.co/docs/transformers/main/model_doc/phi)** (from Microsoft) released with the papers - [Textbooks Are All You Need](https://arxiv.org/abs/2306.11644) by Suriya Gunasekar, Yi Zhang, Jyoti Aneja, Caio César Teodoro Mendes, Allie Del Giorno, Sivakanth Gopi, Mojan Javaheripi, Piero Kauffmann, Gustavo de Rosa, Olli Saarikivi, Adil Salim, Shital Shah, Harkirat Singh Behl, Xin Wang, Sébastien Bubeck, Ronen Eldan, Adam Tauman Kalai, Yin Tat Lee and Yuanzhi Li, [Textbooks Are All You Need II: phi-1.5 technical report](https://arxiv.org/abs/2309.05463) by Yuanzhi Li, Sébastien Bubeck, Ronen Eldan, Allie Del Giorno, Suriya Gunasekar and Yin Tat Lee. +1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. +1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. +1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. +1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. +1. **[Segment Anything](https://huggingface.co/docs/transformers/model_doc/sam)** (from Meta AI) released with the paper [Segment Anything](https://arxiv.org/pdf/2304.02643v1.pdf) by Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alex Berg, Wan-Yen Lo, Piotr Dollar, Ross Girshick. +1. **[SigLIP](https://huggingface.co/docs/transformers/main/model_doc/siglip)** (from Google AI) released with the paper [Sigmoid Loss for Language Image Pre-Training](https://arxiv.org/abs/2303.15343) by Xiaohua Zhai, Basil Mustafa, Alexander Kolesnikov, Lucas Beyer. +1. **[SpeechT5](https://huggingface.co/docs/transformers/model_doc/speecht5)** (from Microsoft Research) released with the paper [SpeechT5: Unified-Modal Encoder-Decoder Pre-Training for Spoken Language Processing](https://arxiv.org/abs/2110.07205) by Junyi Ao, Rui Wang, Long Zhou, Chengyi Wang, Shuo Ren, Yu Wu, Shujie Liu, Tom Ko, Qing Li, Yu Zhang, Zhihua Wei, Yao Qian, Jinyu Li, Furu Wei. +1. **[SqueezeBERT](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. +1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. +1. **[Swin2SR](https://huggingface.co/docs/transformers/model_doc/swin2sr)** (from University of Würzburg) released with the paper [Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration](https://arxiv.org/abs/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte. +1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[Table Transformer](https://huggingface.co/docs/transformers/model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham. +1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei. +1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. +1. **[ViTMatte](https://huggingface.co/docs/transformers/model_doc/vitmatte)** (from HUST-VL) released with the paper [ViTMatte: Boosting Image Matting with Pretrained Plain Vision Transformers](https://arxiv.org/abs/2305.15272) by Jingfeng Yao, Xinggang Wang, Shusheng Yang, Baoyuan Wang. +1. **[VITS](https://huggingface.co/docs/transformers/model_doc/vits)** (from Kakao Enterprise) released with the paper [Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech](https://arxiv.org/abs/2106.06103) by Jaehyeon Kim, Jungil Kong, Juhee Son. +1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. +1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. +1. **[Whisper](https://huggingface.co/docs/transformers/model_doc/whisper)** (from OpenAI) released with the paper [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever. +1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau. +1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov. +1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu. + + diff --git a/core/vendor/node_modules/@xenova/transformers/package.json b/core/vendor/node_modules/@xenova/transformers/package.json new file mode 100644 index 000000000..cedc521b9 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/package.json @@ -0,0 +1,85 @@ +{ + "name": "@xenova/transformers", + "version": "2.14.0", + "description": "State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!", + "main": "./src/transformers.js", + "types": "./types/transformers.d.ts", + "type": "module", + "scripts": { + "typegen": "tsc ./src/transformers.js --allowJs --declaration --emitDeclarationOnly --declarationMap --outDir types", + "dev": "webpack serve --no-client-overlay", + "build": "webpack && npm run typegen", + "generate-tests": "python -m tests.generate_tests", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --verbose --maxConcurrency 1", + "readme": "python ./docs/scripts/build_readme.py", + "docs-api": "node ./docs/scripts/generate.js", + "docs-preview": "doc-builder preview transformers.js ./docs/source/ --not_python_module", + "docs-build": "doc-builder build transformers.js ./docs/source/ --not_python_module --build_dir ./docs/build/ --repo_owner xenova" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/xenova/transformers.js.git" + }, + "keywords": [ + "transformers", + "transformers.js", + "huggingface", + "hugging face", + "machine learning", + "deep learning", + "artificial intelligence", + "AI", + "ML" + ], + "author": "Xenova", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/xenova/transformers.js/issues" + }, + "homepage": "https://github.com/xenova/transformers.js#readme", + "dependencies": { + "onnxruntime-web": "1.14.0", + "sharp": "^0.32.0", + "@huggingface/jinja": "^0.1.0" + }, + "optionalDependencies": { + "onnxruntime-node": "1.14.0" + }, + "devDependencies": { + "@types/jest": "^29.5.1", + "catharsis": "github:xenova/catharsis", + "copy-webpack-plugin": "^11.0.0", + "jest": "^29.5.0", + "jest-environment-node": "^29.5.0", + "jsdoc-to-markdown": "^8.0.0", + "typescript": "^5.2.2", + "wavefile": "^11.0.0", + "webpack": "^5.80.0", + "webpack-cli": "^5.0.2", + "webpack-dev-server": "^4.13.3" + }, + "overrides": { + "semver": "^7.5.4", + "protobufjs": "^7.2.4" + }, + "files": [ + "src", + "dist", + "types", + "README.md", + "LICENSE" + ], + "browser": { + "fs": false, + "path": false, + "url": false, + "sharp": false, + "onnxruntime-node": false, + "stream/web": false + }, + "publishConfig": { + "access": "public" + }, + "jsdelivr": "./dist/transformers.min.js", + "unpkg": "./dist/transformers.min.js" +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/backends/onnx.js b/core/vendor/node_modules/@xenova/transformers/src/backends/onnx.js new file mode 100644 index 000000000..0bee3dce7 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/backends/onnx.js @@ -0,0 +1,50 @@ +/** + * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment. + * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed, + * but dynamic imports don't seem to work with the current webpack version and/or configuration. + * This is possibly due to the experimental nature of top-level await statements. + * So, we just import both packages, and use the appropriate one based on the environment: + * - When running in node, we use `onnxruntime-node`. + * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled). + * + * This module is not directly exported, but can be accessed through the environment variables: + * ```javascript + * import { env } from '@xenova/transformers'; + * console.log(env.backends.onnx); + * ``` + * + * @module backends/onnx + */ + +// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`. +// In either case, we select the default export if it exists, otherwise we use the named export. +import * as ONNX_NODE from 'onnxruntime-node'; +import * as ONNX_WEB from 'onnxruntime-web'; + +/** @type {import('onnxruntime-web')} The ONNX runtime module. */ +export let ONNX; + +export const executionProviders = [ + // 'webgpu', + 'wasm' +]; + +if (typeof process !== 'undefined' && process?.release?.name === 'node') { + // Running in a node-like environment. + ONNX = ONNX_NODE.default ?? ONNX_NODE; + + // Add `cpu` execution provider, with higher precedence that `wasm`. + executionProviders.unshift('cpu'); + +} else { + // Running in a browser-environment + ONNX = ONNX_WEB.default ?? ONNX_WEB; + + // SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x). + // As a temporary fix, we disable it for now. + // For more information, see: https://github.com/microsoft/onnxruntime/issues/15644 + const isIOS = typeof navigator !== 'undefined' && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent); + if (isIOS) { + ONNX.env.wasm.simd = false; + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/configs.js b/core/vendor/node_modules/@xenova/transformers/src/configs.js new file mode 100644 index 000000000..4506d2d9c --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/configs.js @@ -0,0 +1,107 @@ + +/** + * @file Helper module for using model configs. For more information, see the corresponding + * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig). + * + * **Example:** Load an `AutoConfig`. + * + * ```javascript + * import { AutoConfig } from '@xenova/transformers'; + * let config = await AutoConfig.from_pretrained('bert-base-uncased'); + * console.log(config); + * // PretrainedConfig { + * // "model_type": "bert", + * // "is_encoder_decoder": false, + * // "architectures": [ + * // "BertForMaskedLM" + * // ], + * // "vocab_size": 30522 + * // "num_attention_heads": 12, + * // "num_hidden_layers": 12, + * // "hidden_size": 768, + * // "max_position_embeddings": 512, + * // ... + * // } + * ``` + * + * @module configs + */ + +import { + getModelJSON, +} from './utils/hub.js'; + +/** + * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions + */ + + +/** + * Loads a config from the specified path. + * @param {string} pretrained_model_name_or_path The path to the config directory. + * @param {PretrainedOptions} options Additional options for loading the config. + * @returns {Promise} A promise that resolves with information about the loaded config. + */ +async function loadConfig(pretrained_model_name_or_path, options) { + let info = await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options); + return info; +} + +/** + * Base class for all configuration classes. For more information, see the corresponding + * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig). + */ +export class PretrainedConfig { + // NOTE: Typo in original + + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} configJSON The JSON of the config. + */ + constructor(configJSON) { + this.model_type = null; + this.is_encoder_decoder = false; + + Object.assign(this, configJSON); + } + + /** + * Loads a pre-trained config from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained config. + * @param {PretrainedOptions} options Additional options for loading the config. + * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. + * + * @returns {Promise} A new instance of the `PretrainedConfig` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + } = {}) { + + let data = config ?? await loadConfig(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + }) + return new this(data); + } +} + +/** + * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function. + * + * @example + * let config = await AutoConfig.from_pretrained('bert-base-uncased'); + */ +export class AutoConfig { + /** @type {PretrainedConfig.from_pretrained} */ + static async from_pretrained(...args) { + return PretrainedConfig.from_pretrained(...args); + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/env.js b/core/vendor/node_modules/@xenova/transformers/src/env.js new file mode 100644 index 000000000..8a02af538 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/env.js @@ -0,0 +1,127 @@ +/** + * @file Module used to configure Transformers.js. + * + * **Example:** Disable remote models. + * ```javascript + * import { env } from '@xenova/transformers'; + * env.allowRemoteModels = false; + * ``` + * + * **Example:** Set local model path. + * ```javascript + * import { env } from '@xenova/transformers'; + * env.localModelPath = '/path/to/local/models/'; + * ``` + * + * **Example:** Set cache directory. + * ```javascript + * import { env } from '@xenova/transformers'; + * env.cacheDir = '/path/to/cache/directory/'; + * ``` + * + * @module env + */ + +import fs from 'fs'; +import path from 'path'; +import url from 'url'; + +import { ONNX } from './backends/onnx.js'; +const { env: onnx_env } = ONNX; + +const VERSION = '2.14.0'; + +// Check if various APIs are available (depends on environment) +const WEB_CACHE_AVAILABLE = typeof self !== 'undefined' && 'caches' in self; +const FS_AVAILABLE = !isEmpty(fs); // check if file system is available +const PATH_AVAILABLE = !isEmpty(path); // check if path is available + +const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE; + +const __dirname = RUNNING_LOCALLY + ? path.dirname(path.dirname(url.fileURLToPath(import.meta.url))) + : './'; + +// Only used for environments with access to file system +const DEFAULT_CACHE_DIR = RUNNING_LOCALLY + ? path.join(__dirname, '/.cache/') + : null; + +// Set local model path, based on available APIs +const DEFAULT_LOCAL_MODEL_PATH = '/models/'; +const localModelPath = RUNNING_LOCALLY + ? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH) + : DEFAULT_LOCAL_MODEL_PATH; + +// Set path to wasm files. This is needed when running in a web worker. +// https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths +// We use remote wasm files by default to make it easier for newer users. +// In practice, users should probably self-host the necessary .wasm files. +onnx_env.wasm.wasmPaths = RUNNING_LOCALLY + ? path.join(__dirname, '/dist/') + : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`; + + +/** + * Global variable used to control execution. This provides users a simple way to configure Transformers.js. + * @property {Object} backends Expose environment variables of different backends, + * allowing users to set these variables if they want to. + * @property {string} __dirname Directory name of module. Useful for resolving local paths. + * @property {string} version This version of Transformers.js. + * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`. + * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc. + * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub. + * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models. + * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `true`. + * If set to `false`, it will skip the local file check and try to load the model from the remote host. + * @property {string} localModelPath Path to load local models from. Defaults to `/models/`. + * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available. + * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available. + * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available. + * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`. + * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`. + * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this 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 + */ +export const env = { + /////////////////// Backends settings /////////////////// + backends: { + // onnxruntime-web/onnxruntime-node + onnx: onnx_env, + + // TensorFlow.js + tfjs: {}, + }, + + __dirname, + version: VERSION, + + /////////////////// Model settings /////////////////// + allowRemoteModels: true, + remoteHost: 'https://huggingface.co/', + remotePathTemplate: '{model}/resolve/{revision}/', + + allowLocalModels: true, + localModelPath: localModelPath, + useFS: FS_AVAILABLE, + + /////////////////// Cache settings /////////////////// + useBrowserCache: WEB_CACHE_AVAILABLE, + + useFSCache: FS_AVAILABLE, + cacheDir: DEFAULT_CACHE_DIR, + + useCustomCache: false, + customCache: null, + ////////////////////////////////////////////////////// +} + + +/** + * @param {Object} obj + * @private + */ +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} + diff --git a/core/vendor/node_modules/@xenova/transformers/src/models.js b/core/vendor/node_modules/@xenova/transformers/src/models.js new file mode 100644 index 000000000..1c48030a4 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/models.js @@ -0,0 +1,5794 @@ + +/** + * @file Definitions of all models available in Transformers.js. + * + * **Example:** Load and run an `AutoModel`. + * + * ```javascript + * import { AutoModel, AutoTokenizer } from '@xenova/transformers'; + * + * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); + * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased'); + * + * let inputs = await tokenizer('I love transformers!'); + * let { logits } = await model(inputs); + * // Tensor { + * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...] + * // dims: (3) [1, 6, 30522], + * // type: "float32", + * // size: 183132, + * // } + * ``` + * + * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example: + * + * **Example:** Load and run an `AutoModelForSeq2SeqLM`. + * ```javascript + * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@xenova/transformers'; + * + * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small'); + * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small'); + * + * let { input_ids } = await tokenizer('translate English to German: I love transformers!'); + * let outputs = await model.generate(input_ids); + * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true }); + * // 'Ich liebe Transformatoren!' + * ``` + * + * @module models + */ + +import { + AutoConfig, +} from './configs.js'; + +import { + Callable, + isIntegralNumber, + isTypedArray, + mergeArrays, +} from './utils/core.js'; + +import { + getModelFile, + getModelJSON, +} from './utils/hub.js'; + +import { + ForcedBOSTokenLogitsProcessor, + ForcedEOSTokenLogitsProcessor, + ForceTokensLogitsProcessor, + GenerationConfig, + LogitsProcessorList, + MinLengthLogitsProcessor, + MinNewTokensLengthLogitsProcessor, + NoBadWordsLogitsProcessor, + NoRepeatNGramLogitsProcessor, + RepetitionPenaltyLogitsProcessor, + Sampler, + SuppressTokensAtBeginLogitsProcessor, + WhisperTimeStampLogitsProcessor, +} from './utils/generation.js'; + +import { + cat, + dynamicTimeWarping, + mean, + ones_like, + stack, + std_mean, + Tensor, +} from './utils/tensor.js'; + +import { executionProviders, ONNX } from './backends/onnx.js'; +// import { medianFilter } from './transformers.js'; +const { InferenceSession, Tensor: ONNXTensor, env } = ONNX; + +/** @typedef {import('onnxruntime-web').InferenceSession} InferenceSession */ + +////////////////////////////////////////////////// +// Model types: used internally +const MODEL_TYPES = { + EncoderOnly: 0, + EncoderDecoder: 1, + Seq2Seq: 2, + Vision2Seq: 3, + DecoderOnly: 4, + MaskGeneration: 5, +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Helper functions + +// NOTE: These will be populated fully later +const MODEL_TYPE_MAPPING = new Map(); +const MODEL_NAME_TO_CLASS_MAPPING = new Map(); +const MODEL_CLASS_TO_NAME_MAPPING = new Map(); + + +/** + * Constructs an InferenceSession using a model file located at the specified path. + * @param {string} pretrained_model_name_or_path The path to the directory containing the model file. + * @param {string} fileName The name of the model file. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. + * @returns {Promise} A Promise that resolves to an InferenceSession object. + * @private + */ +async function constructSession(pretrained_model_name_or_path, fileName, options) { + // TODO add option for user to force specify their desired execution provider + let modelFileName = `onnx/${fileName}${options.quantized ? '_quantized' : ''}.onnx`; + let buffer = await getModelFile(pretrained_model_name_or_path, modelFileName, true, options); + + try { + return await InferenceSession.create(buffer, { + executionProviders, + }); + } catch (err) { + // If the execution provided was only wasm, throw the error + if (executionProviders.length === 1 && executionProviders[0] === 'wasm') { + throw err; + } + + console.warn(err); + console.warn( + 'Something went wrong during model construction (most likely a missing operation). ' + + 'Using `wasm` as a fallback. ' + ) + return await InferenceSession.create(buffer, { + executionProviders: ['wasm'] + }); + } +} + +/** + * Validate model inputs + * @param {InferenceSession} session The InferenceSession object that will be run. + * @param {Record} inputs The inputs to check. + * @returns {Record} The checked inputs. + * @throws {Error} If any inputs are missing. + * @private + */ +function validateInputs(session, inputs) { + /** + * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy` + * @type {Record} + */ + const checkedInputs = Object.create(null); + const missingInputs = []; + for (const inputName of session.inputNames) { + const tensor = inputs[inputName]; + // Rare case where one of the model's input names corresponds to a built-in + // object name (e.g., toString), which would cause a simple (!tensor) check to fail, + // because it's not undefined but a function. + if (!(tensor instanceof Tensor)) { + missingInputs.push(inputName); + continue; + } + // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker + // boundary, transferring ownership to the worker and invalidating the tensor. + // So, in this case, we simply sacrifice a clone for it. + checkedInputs[inputName] = env.wasm.proxy ? tensor.clone() : tensor; + } + if (missingInputs.length > 0) { + throw new Error( + `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(', ')}.`); + } + + const numInputsProvided = Object.keys(inputs).length; + const numInputsNeeded = session.inputNames.length; + if (numInputsProvided > numInputsNeeded) { + // No missing inputs, but too many inputs were provided. + // Warn the user and ignore the extra inputs. + let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName)); + console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(', ')}".`); + } + + return checkedInputs; +} + +/** + * Executes an InferenceSession using the specified inputs. + * NOTE: `inputs` must contain at least the input names of the model. + * - If additional inputs are passed, they will be ignored. + * - If inputs are missing, an error will be thrown. + * + * @param {InferenceSession} session The InferenceSession object to run. + * @param {Object} inputs An object that maps input names to input tensors. + * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors. + * @private + */ +async function sessionRun(session, inputs) { + const checkedInputs = validateInputs(session, inputs); + try { + // @ts-ignore + let output = await session.run(checkedInputs); + output = replaceTensors(output); + return output; + } catch (e) { + // This usually occurs when the inputs are of the wrong type. + console.error(`An error occurred during model execution: "${e}".`); + console.error('Inputs given to model:', checkedInputs); + throw e; + } +} + +/** + * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions. + * @param {Object} obj The object to replace tensor objects in. + * @returns {Object} The object with tensor objects replaced by custom Tensor objects. + * @private + */ +function replaceTensors(obj) { + for (let prop in obj) { + if (obj[prop] instanceof ONNXTensor) { + obj[prop] = new Tensor(obj[prop]); + } else if (typeof obj[prop] === 'object') { + replaceTensors(obj[prop]); + } + } + return obj; +} + + +/** + * Converts an array or Tensor of integers to an int64 Tensor. + * @param {Array|Tensor} items The input integers to be converted. + * @returns {Tensor} The int64 Tensor with the converted values. + * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length. + * @private + */ +function toI64Tensor(items) { + if (items instanceof Tensor) { + return items; + } + // items is an array + if (items.length === 0) { + throw Error("items must be non-empty"); + } + + if (Array.isArray(items[0])) { + // batched + if (items.some(x => x.length !== items[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 Tensor('int64', + BigInt64Array.from(items.flat().map(x => BigInt(x))), + [items.length, items[0].length] + ); + } else { + //flat + return new Tensor('int64', + BigInt64Array.from(items.map(x => BigInt(x))), + [1, items.length] + ); + } +} + +/** + * Prepares an attention mask for a sequence of tokens based on configuration options. + * @param {Object} self The calling object instance. + * @param {Tensor} tokens The input tokens. + * @returns {Tensor} The attention mask tensor. + * @private + */ +function prepareAttentionMask(self, tokens) { + + // Prepare attention mask + let pad_token_id = self.config.pad_token_id ?? null; + let eos_token_id = self.config.eos_token_id ?? null; + if (isIntegralNumber(eos_token_id)) { + eos_token_id = [eos_token_id]; + } + + let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1; + let is_pad_token_not_equal_to_eos_token_id = (eos_token_id === null) || !eos_token_id.includes(pad_token_id) + + if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) { + let data = BigInt64Array.from( + // Note: != so that int matches bigint + // @ts-ignore + tokens.data.map(x => x != pad_token_id) + ) + return new Tensor('int64', data, tokens.dims) + } else { + return ones_like(tokens); + } +} + +/** + * Add position IDs to the feeds object. + * @param {Object} session The inference session. + * @param {Object} feeds The input to the model. + * @param {boolean} use_cache_branch Whether to use the cache branch of the model. + * @returns {void} + * @private + */ +function preparePositionIds(session, feeds, use_cache_branch) { + if (!session.inputNames.includes('position_ids')) return; + + const data = new BigInt64Array(feeds.attention_mask.data.length); + + // Compute cumulative sum of the attention mask along the sequence length dimension + for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) { + let start = i * feeds.attention_mask.dims[1]; + let sum = BigInt(0); + for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) { + const index = start + j; + if (feeds.attention_mask.data[index] === 0n) { + data[index] = BigInt(1); + } else { // === 1n + data[index] = sum; + sum += feeds.attention_mask.data[index]; + } + } + } + + feeds.position_ids = new Tensor('int64', data, feeds.attention_mask.dims); + + if (use_cache_branch) { + feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1); + } +} + +/** + * Creates a boolean tensor with a single value. + * @param {boolean} value The value of the tensor. + * @returns {Tensor} The boolean tensor. + * @private + */ +function boolTensor(value) { + return new Tensor('bool', [value], [1]); +} + +// JS doesn't support mixins, so we define some reused functions here, and allow "this" to be passed in +/** + * Perform forward pass on the seq2seq model (both encoder and decoder). + * @param {Object} self The seq2seq model object. + * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs. + * @returns {Promise} Promise that resolves with the output of the seq2seq model. + * @private + */ +async function seq2seqForward(self, model_inputs) { + + let { encoder_outputs, past_key_values } = model_inputs; + + if (!encoder_outputs) { + // Encoder outputs are not given, so we must compute them. + encoder_outputs = (await encoderForward(self, model_inputs)).last_hidden_state; + } + let decoderFeeds = { + input_ids: model_inputs.decoder_input_ids, + encoder_hidden_states: encoder_outputs, + }; + const use_cache_branch = !!past_key_values; + + if (self.decoder_merged_session.inputNames.includes('use_cache_branch')) { + decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); + } + + if (self.decoder_merged_session.inputNames.includes('encoder_attention_mask')) { + decoderFeeds.encoder_attention_mask = model_inputs.attention_mask + } + + preparePositionIds(self.decoder_merged_session, decoderFeeds, use_cache_branch); + self.addPastKeyValues(decoderFeeds, past_key_values); + + const decoderResults = await sessionRun(self.decoder_merged_session, decoderFeeds); + let logits = decoderResults.logits; + past_key_values = self.getPastKeyValues(decoderResults, past_key_values); + + // Get cross attention and/or decoder attentions if they are present + const attns = self.getAttentions(decoderResults); + + return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns }); +} + +/** + * Start the beam search process for the seq2seq model. + * @param {PreTrainedModel} self The seq2seq model object. + * @param {Tensor} inputTokenIds Array of input token ids for each input sequence. + * @param {Object} generation_config The generation config. + * @param {number} numOutputTokens The maximum number of output tokens for the model. + * @returns {Object[]} Array of beam search objects. + * @private + */ +function seq2seqStartBeams(self, inputTokenIds, generation_config, numOutputTokens) { + let beams = []; + let beamId = 0; + + // @ts-ignore + const requires_attention_mask = self.requires_attention_mask ?? true; + + // decoder_input_ids == output_token_ids + let decoder_input_ids = + generation_config.decoder_input_ids + ?? generation_config.decoder_start_token_id + ?? generation_config.bos_token_id + ?? generation_config.eos_token_id; + + // Support input as tensor or list + // TODO support batched decoder_input_ids + if (decoder_input_ids instanceof Tensor) { + decoder_input_ids = decoder_input_ids.tolist().flat(); + } else if (!Array.isArray(decoder_input_ids)) { + decoder_input_ids = [decoder_input_ids]; + } + + for (let tokens of inputTokenIds) { + // TODO: Improve + // Currently, just add back batch dimension. + // In future, allow for true parallel execution + tokens.dims = [1, ...tokens.dims] + + // Create beam + let start = { + inputs: tokens, + encoder_outputs: null, + prev_model_outputs: null, + + output_token_ids: decoder_input_ids, + done: false, + score: 0, + id: beamId++ // assign unique id to beams + } + + if (requires_attention_mask) { + start.attention_mask = prepareAttentionMask(self, tokens); + } + + beams.push(start); + } + + return beams; +} + +/** + * Run beam search on the seq2seq model for a single beam. + * @param {PreTrainedModel} self The seq2seq model object. + * @param {Object} beam The beam search object for which to run the model. + * @param {Object} options options + * @param {string} [options.input_name='input_ids'] The name of the input tensor for the encoder. + * @returns {Promise} Promise that resolves with the output of the seq2seq model for the given beam. + * @private + */ +async function seq2seqRunBeam(self, beam) { + const input_name = self.main_input_name; + + let decoder_input_ids = beam.output_token_ids; + if (beam.prev_model_outputs) { + // After the first step, `prev_model_outputs` won't be null. + // So, we cut decoder_input_ids if past is used + decoder_input_ids = decoder_input_ids.slice(-1); + } + + // 1. Prepare + let model_inputs = { + [input_name]: beam.inputs, + decoder_input_ids: toI64Tensor(decoder_input_ids), + encoder_outputs: beam.encoder_outputs, + past_key_values: beam.prev_model_outputs?.past_key_values, + } + if (beam.attention_mask) { + model_inputs.attention_mask = beam.attention_mask + } + + // 2. Run + let output = await self.forward(model_inputs); + + // 3. Update + beam.prev_model_outputs = output; + beam.encoder_outputs = output.encoder_outputs; + + return output; +} + +/** + * Update a beam with a new token ID. + * @param {Object} beam The beam to update. + * @param {number} newTokenId The new token ID to add to the beam's output. + * @private + */ +function seq2seqUpdatebeam(beam, newTokenId) { + beam.output_token_ids = [...beam.output_token_ids, newTokenId]; +} + +/** + * Forward pass of an encoder model. + * @param {Object} self The encoder model. + * @param {Object} model_inputs The input data to be used for the forward pass. + * @returns {Promise} Promise that resolves with an object containing the model's outputs. + * @private + */ +async function encoderForward(self, model_inputs) { + const encoderFeeds = Object.create(null); + for (const key of self.session.inputNames) { + encoderFeeds[key] = model_inputs[key]; + } + if (self.session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) { + // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it, + // but they weren't created by the tokenizer. + encoderFeeds.token_type_ids = new Tensor( + 'int64', + new BigInt64Array(encoderFeeds.input_ids.data.length), + encoderFeeds.input_ids.dims + ) + } + return await sessionRun(self.session, encoderFeeds); +} + + +/** + * Forward pass of a decoder model. + * @param {Object} self The decoder model. + * @param {Object} model_inputs The input data to be used for the forward pass. + * @returns {Promise} Promise that resolves with an object containing the logits and past key values. + * @private + */ +async function decoderForward(self, model_inputs) { + let { input_ids, past_key_values, attention_mask } = model_inputs; + let decoderFeeds = { + input_ids: input_ids, + attention_mask: attention_mask ?? prepareAttentionMask(self, input_ids), + } + const use_cache_branch = !!past_key_values; + + if (self.session.inputNames.includes('use_cache_branch')) { + decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); + } + + preparePositionIds(self.session, decoderFeeds, use_cache_branch); + + self.addPastKeyValues(decoderFeeds, past_key_values); + + let decoderResults = await sessionRun(self.session, decoderFeeds); + + let logits = decoderResults.logits; + + past_key_values = self.getPastKeyValues(decoderResults, past_key_values); + return { logits, past_key_values }; +} + +/** + * Starts the generation of text by initializing the beams for the given input token IDs. + * @param {Object} self The text generation model object. + * @param {Tensor} inputTokenIds An tensor of input token IDs to generate text from. + * @param {Object} generation_config The generation config. + * @param {number} numOutputTokens The maximum number of tokens to generate for each beam. + * @param {Tensor} [inputs_attention_mask] The attention mask tensor for the input token IDs. + * @returns {Object[]} An array of beams initialized with the given inputs and parameters. + * @private + */ +function decoderStartBeams(self, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { + let beams = []; + + let beamId = 0; + for (let tokens of inputTokenIds) { + let output_token_ids = tokens.tolist().map(Number); + + // TODO: Improve + // Currently, just add back batch dimension. + // In future, allow for true parallel execution + tokens.dims = [1, ...tokens.dims] + + let attn_mask; + if (inputs_attention_mask) { + attn_mask = inputs_attention_mask[beamId]; + attn_mask.dims = [1, ...attn_mask.dims] + + } else { + attn_mask = prepareAttentionMask(self, tokens) + } + + let start = { + input: tokens, + model_input_ids: tokens, + attention_mask: attn_mask, + prev_model_outputs: null, + + output_token_ids: output_token_ids, + num_output_tokens: numOutputTokens, + + done: false, + score: 0, + id: beamId++ // assign unique id to beams + } + + beams.push(start); + } + return beams; +} + +/** + * Runs a single step of the text generation process for a given beam. + * + * @param {Object} self The decoder object. + * @param {Object} beam The beam to run. + * @param {Tensor} beam.input The input tensor. + * @param {Tensor} beam.model_input_ids The input ids to the model. + * @param {Tensor} beam.attention_mask The attention mask. + * @param {Object} beam.prev_model_outputs The past key values. + * @param {number[]} beam.output_token_ids The output token ids. + * @returns {Promise} The output of the generation step. + * @private + */ +async function decoderRunBeam(self, beam) { + let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n) + + // 1. Prepare + let model_inputs = { + input_ids: beam.model_input_ids, + attention_mask: new Tensor( + 'int64', + attnMaskData, + [1, attnMaskData.length] + ), + past_key_values: beam.prev_model_outputs?.past_key_values, + } + + // 2. Run + let output = await self.forward(model_inputs); + + // 3. Update + beam.prev_model_outputs = output; + + return output; +} + +/** + * Update a beam with a new token ID. + * @param {Object} beam The beam to update. + * @param {number} newTokenId The new token ID to add to the beam's output. + * @private + */ +function decoderUpdatebeam(beam, newTokenId) { + beam.output_token_ids = [...beam.output_token_ids, newTokenId]; + beam.model_input_ids = new Tensor('int64', [BigInt(newTokenId)], [1, 1]); +} + +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +/** + * A base class for pre-trained models that provides the model configuration and an ONNX session. + */ +export class PreTrainedModel extends Callable { + main_input_name = 'input_ids'; + + /** + * Creates a new instance of the `PreTrainedModel` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + */ + constructor(config, session) { + super(); + + this.config = config; + this.session = session; + + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + const modelType = MODEL_TYPE_MAPPING.get(modelName); + + this.can_generate = false; + this._runBeam = null; + this._getStartBeams = null; + this._updateBeam = null; + this._forward = null; + if (modelType === MODEL_TYPES.DecoderOnly) { + this.can_generate = true; + + this._runBeam = decoderRunBeam; + this._getStartBeams = decoderStartBeams; + this._updateBeam = decoderUpdatebeam; + this._forward = decoderForward; + + } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { + this.can_generate = true; + + this._runBeam = seq2seqRunBeam; + this._getStartBeams = seq2seqStartBeams; + this._updateBeam = seq2seqUpdatebeam; + this._forward = seq2seqForward; + + } else if (modelType === MODEL_TYPES.EncoderDecoder) { + this._forward = encoderForward; + + } else { // should be MODEL_TYPES.EncoderOnly + this._forward = encoderForward; + } + } + + /** + * Disposes of all the ONNX sessions that were created during inference. + * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. + * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ + async dispose() { + const promises = []; + for (let key of Object.keys(this)) { + const item = this[key]; + // @ts-ignore + if (item instanceof InferenceSession) { + promises.push(item.handler.dispose()) + } + } + return await Promise.all(promises); + } + + /** + * Instantiate one of the model classes of the library from a pretrained model. + * + * The model class to instantiate is selected based on the `model_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. + * + * @returns {Promise} A new instance of the `PreTrainedModel` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + quantized = true, + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + model_file_name = null, + } = {}) { + + let options = { + quantized, + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + } + + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); + const modelType = MODEL_TYPE_MAPPING.get(modelName); + + let info; + if (modelType === MODEL_TYPES.DecoderOnly) { + info = await Promise.all([ + AutoConfig.from_pretrained(pretrained_model_name_or_path, options), + constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'decoder_model_merged', options), + getModelJSON(pretrained_model_name_or_path, 'generation_config.json', false, options), + ]); + + } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { + info = await Promise.all([ + AutoConfig.from_pretrained(pretrained_model_name_or_path, options), + constructSession(pretrained_model_name_or_path, 'encoder_model', options), + constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options), + getModelJSON(pretrained_model_name_or_path, 'generation_config.json', false, options), + ]); + + } else if (modelType === MODEL_TYPES.MaskGeneration) { + info = await Promise.all([ + AutoConfig.from_pretrained(pretrained_model_name_or_path, options), + constructSession(pretrained_model_name_or_path, 'vision_encoder', options), + constructSession(pretrained_model_name_or_path, 'prompt_encoder_mask_decoder', options), + ]); + + } else if (modelType === MODEL_TYPES.EncoderDecoder) { + info = await Promise.all([ + AutoConfig.from_pretrained(pretrained_model_name_or_path, options), + constructSession(pretrained_model_name_or_path, 'encoder_model', options), + constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options), + ]); + + } else { // should be MODEL_TYPES.EncoderOnly + if (modelType !== MODEL_TYPES.EncoderOnly) { + console.warn(`Model type for '${modelName}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`) + } + info = await Promise.all([ + AutoConfig.from_pretrained(pretrained_model_name_or_path, options), + constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'model', options) + ]); + } + + // @ts-ignore + return new this(...info); + } + + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Object containing input tensors + * @returns {Promise} Object containing output tensors + */ + async _call(model_inputs) { + return await this.forward(model_inputs); + } + + /** + * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method + * will be chosen based on the model type. + * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. + * @returns {Promise} The output data from the model in the format specified in the ONNX model. + * @throws {Error} This method must be implemented in subclasses. + */ + async forward(model_inputs) { + return await this._forward(this, model_inputs); + } + + /** + * @param {import('./utils/generation.js').GenerationConfigType} generation_config + * @param {number} input_ids_seq_length The starting sequence length for the input ids. + * @returns {LogitsProcessorList} + * @private + */ + _get_logits_processor( + generation_config, + input_ids_seq_length, + // encoder_input_ids, TODO + // prefix_allowed_tokens_fn, TODO + logits_processor = null + ) { + const processors = new LogitsProcessorList(); + + // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) { + // processors.push(new HammingDiversityLogitsProcessor( + // generation_config.diversity_penalty, + // generation_config.num_beams, + // generation_config.num_beam_groups + // )); + // } + + // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) { + // processors.push(new EncoderRepetitionPenaltyLogitsProcessor( + // generation_config.encoder_repetition_penalty, + // encoder_input_ids + // )); + // } + + if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) { + processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); + } + + if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { + processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); + } + + // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) { + // if (this.config.is_encoder_decoder) { + // processors.push(new EncoderNoRepeatNGramLogitsProcessor( + // generation_config.encoder_no_repeat_ngram_size, + // encoder_input_ids + // )); + // } else { + // throw new Error("It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture"); + // } + // } + + if (generation_config.bad_words_ids !== null) { + processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)); + } + + if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { + processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); + } + + if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { + processors.push(new MinNewTokensLengthLogitsProcessor( + input_ids_seq_length, + generation_config.min_new_tokens, + generation_config.eos_token_id + )); + } + + // if (prefix_allowed_tokens_fn !== null) { + // processors.push(new PrefixConstrainedLogitsProcessor( + // prefix_allowed_tokens_fn, + // generation_config.num_beams / generation_config.num_beam_groups + // )); + // } + + + if (generation_config.forced_bos_token_id !== null) { + processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); + } + + if (generation_config.forced_eos_token_id !== null) { + processors.push(new ForcedEOSTokenLogitsProcessor( + generation_config.max_length, + generation_config.forced_eos_token_id + )); + } + + // if (generation_config.remove_invalid_values === true) { + // processors.push(new InfNanRemoveLogitsProcessor()); + // } + + // if (generation_config.exponential_decay_length_penalty !== null) { + // processors.push(new ExponentialDecayLengthPenalty( + // generation_config.exponential_decay_length_penalty, + // generation_config.eos_token_id, + // input_ids_seq_length + // )); + // } + + // if (generation_config.suppress_tokens !== null) { + // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens)); + // } + + if (generation_config.begin_suppress_tokens !== null) { + let begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null) + ? input_ids_seq_length + : input_ids_seq_length + 1; + + if (generation_config.forced_decoder_ids !== null) { + // generation starts after the last token that is forced + begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0]; + } + processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)); + } + + if (generation_config.forced_decoder_ids !== null) { + processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids)); + } + + if (logits_processor !== null) { + processors.extend(logits_processor) + } + + // `LogitNormalization` should always be the last logit processor, when present + // if (generation_config.renormalize_logits === true) { + // processors.push(new LogitNormalization()); + // } + + return processors; + } + + /** + * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. + * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. + * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters. + * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation. + */ + _get_generation_config(generation_config) { + // Create empty generation config (contains defaults) + // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them + let gen_config = new GenerationConfig(this.config); + + // Apply model's generation config, if it exists + if ('generation_config' in this) { + Object.assign(gen_config, this.generation_config); + } + + // Finally, use any generation config specified by the user + // when calling `generate` + if (generation_config !== null) { + Object.assign(gen_config, generation_config); + } + return gen_config; + } + + /** + * @typedef {import('./utils/maths.js').TypedArray} TypedArray + */ + + /** + * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput + * @typedef {Object} DecoderOutput + * + * Generates text based on the given inputs and generation configuration using the model. + * @param {Tensor|Array|TypedArray} inputs An array of input token IDs. + * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used. + * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created. + * @param {Object} options options + * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs. + * @returns {Promise} An array of generated output sequences, where each sequence is an array of token IDs. + * @throws {Error} Throws an error if the inputs array is empty. + */ + async generate( + inputs, + generation_config = null, + logits_processor = null, + { + inputs_attention_mask = null + } = {}, + ) { + if (!this.can_generate) { + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.` + + const modelType = this.config.model_type; + const possibleInfo = + MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType) + ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType) + ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType) + // ?? MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES.get(modelType) // TODO + ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType); + + if (possibleInfo) { + // TODO: support multiple possible classes + errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`; + } + throw Error(errorMessage); + } + + if (!(inputs instanceof Tensor) && !isTypedArray(inputs) && !Array.isArray(inputs)) { + throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`); + } + + let input_ids_seq_length; + + // Prepare `input_ids` which will be used for auto-regressive generation + // TODO: Update to align with HF transformers' implementation + if (this.config.is_encoder_decoder) { + // Generating from the encoder outputs + input_ids_seq_length = 0; + + } else { + input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length; + + // decoder-only + if (input_ids_seq_length === 0) { + throw Error("Must supply a non-empty array of input token ids.") + } + } + + // Update generation config with defaults + generation_config = this._get_generation_config(generation_config); + + logits_processor = logits_processor ?? new LogitsProcessorList() + + // Update logits processor + logits_processor = this._get_logits_processor( + generation_config, + input_ids_seq_length, + logits_processor + ) + + /** @type {number[]} */ + let eos_token_ids = generation_config.eos_token_id; + if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) { + eos_token_ids = [eos_token_ids]; + } + + // TODO implement early_stopping + // https://huggingface.co/blog/how-to-generate + + let numOutputTokens = 1; + const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity); + + // Only use max length if max_new_tokens is not provided + const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null; + let sampler = Sampler.getSampler(generation_config); + + // @ts-ignore + let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask); + + while (beams.some(x => !x.done) && numOutputTokens < maxOutputTokens) { + let newest_beams = []; + for (let beam of beams) { + if (beam.done) { + // Add this beam back into the pool + newest_beams.push(beam); + continue + } + if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) { + // Set this beam to done and add it back into the pool + beam.done = true; + newest_beams.push(beam); + continue + } + + // @ts-ignore + let output = await this.runBeam(beam); + + // add attentions/scores to beam only if user requested + if (generation_config.output_attentions) { + this.addAttentionsToBeam(beam, output); + } + if (generation_config.output_scores) { + // TODO add + } + + // Logits are of the form [batch_size, out_seq_length, vocab_size] + // In most cases, this will be [batch_size, 1, vocab_size] + // So, we select the last token's logits: + // (equivalent to `logits = outputs.logits[:, -1, :]`) + let logits = output.logits.slice(null, -1, null); + + // Apply logits processor + logits_processor(beam.output_token_ids, logits); + + let sampledTokens = sampler(logits); + for (let [newTokenId, logProb] of sampledTokens) { + // use previous beam as a starting point + let newBeam = { ...beam }; + + // update new beam + // @ts-ignore + this.updateBeam(newBeam, newTokenId); + + newBeam.score += logProb; + + if (eos_token_ids && eos_token_ids.includes(newTokenId)) { + newBeam.done = true; + } + + newest_beams.push(newBeam); + } + } + ++numOutputTokens; + + // Next, we get the best beams, per ID + newest_beams = this.groupBeams(newest_beams).map( + group => group + .sort((a, b) => b.score - a.score) // sort by score + .slice(0, generation_config.num_beams) // remove outside beam width + ); + + // Flatten beams + beams = newest_beams.flat(); + + // Run callback + if (generation_config.callback_function) { + generation_config.callback_function(beams); + } + } + + // TODO: Ensure that we can return non-batched outputs + + const groupedBeams = this.groupBeams(beams); + + const getFlattened = (key) => groupedBeams.map( + batch => { + if (generation_config.num_return_sequences > 1) { + return batch.slice(0, generation_config.num_return_sequences).map(x => x[key]); + } else { + return [batch[0][key]]; + } + } + ).flat(); // Flatten across batches (depth=1) + + const sequences = getFlattened('output_token_ids'); // [1, seqLength] + + if (generation_config.return_dict_in_generate) { + // NOTE: `decoder_attentions` and `cross_attentions` should be: + // list (one element for each generated token) + // of list (one element for each layer of the decoder) + // of torch.FloatTensor of shape (batch_size, num_heads, generated_length, sequence_length) + // However, since we are only generating one batch at a time, they are of the form: + // list (batches) + // of list (one element for each generated token) + // of list (one element for each layer of the decoder) + // of torch.FloatTensor of shape (1, num_heads, generated_length, sequence_length) + // + // TODO: In future (when true parallelism, we should be able to return the correct shape) + + const decoder_attentions = getFlattened('decoder_attentions'); + const cross_attentions = getFlattened('cross_attentions'); + + return { + sequences, + + decoder_attentions, + cross_attentions, + } + } else { + return sequences; + } + } + + /** + * Helper function to add attentions to beam + * @param {Object} beam + * @param {Object} output + * @private + */ + addAttentionsToBeam(beam, output) { + if (this.config.is_encoder_decoder) { + if (!output.cross_attentions || output.cross_attentions.length === 0) { + throw Error( + "`output_attentions` is true, but the model did not produce cross-attentions. " + + "This is most likely because the model was not exported with `output_attentions=True`." + ) + } + if (!beam.cross_attentions) { + beam.cross_attentions = []; + } + beam.cross_attentions.push(output.cross_attentions); + } + + if (!output.decoder_attentions || output.decoder_attentions.length === 0) { + throw Error( + "`output_attentions` is true, but the model did not produce decoder-attentions. " + + "This is most likely because the model was not exported with `output_attentions=True`." + ) + } + if (!beam.decoder_attentions) { + beam.decoder_attentions = []; + } + beam.decoder_attentions.push(output.decoder_attentions); + } + + /** + * Groups an array of beam objects by their ids. + * + * @param {Array} beams The array of beam objects to group. + * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id. + */ + groupBeams(beams) { + // Group beams by their ids + const groups = Object.create(null); + for (const obj of beams) { + if (groups[obj.id] === undefined) { + groups[obj.id] = [obj]; + } else { + groups[obj.id].push(obj); + } + } + + return Object.values(groups); + } + + /** + * Returns an object containing past key values from the given decoder results object. + * + * @param {Object} decoderResults The decoder results object. + * @param {Object} pastKeyValues The previous past key values. + * @returns {Object} An object containing past key values. + */ + getPastKeyValues(decoderResults, pastKeyValues) { + + const pkvs = Object.create(null); + + for (const name in decoderResults) { + if (name.startsWith('present')) { + let newName = name.replace('present', 'past_key_values'); + + if (pastKeyValues && name.includes('encoder')) { + // Optimization introduced by optimum to reuse past key values. So, we just replace the constant + // outputs with the previous past key values. + // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704 + pkvs[newName] = pastKeyValues[newName]; + } else { + pkvs[newName] = decoderResults[name]; + } + } + } + return pkvs; + } + + /** + * Returns an object containing attentions from the given decoder results object. + * + * @param {Object} decoderResults The decoder results object. + * @returns {Object} An object containing attentions. + */ + getAttentions(decoderResults) { + const attns = Object.create(null); + + for (const attnName of ['cross_attentions', 'decoder_attentions']) { + const result = []; + for (const name in decoderResults) { + if (name.startsWith(attnName)) { + const index = name.split('.').pop() + result[index] = decoderResults[name]; + } + } + attns[attnName] = result; + } + return attns; + } + + /** + * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. + * + * @param {Object} decoderFeeds The decoder feeds object to add past key values to. + * @param {Object} pastKeyValues An object containing past key values. + */ + addPastKeyValues(decoderFeeds, pastKeyValues) { + if (pastKeyValues) { + Object.assign(decoderFeeds, pastKeyValues) + } else { + // TODO support batches (i.e., batch_size > 1) + const batch_size = 1; + + // @ts-ignore + if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) { + // @ts-ignore + let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv]; + // @ts-ignore + let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv]; + // @ts-ignore + for (let i = 0; i < this.num_decoder_layers; ++i) { + decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor('float32', [], encoder_dims) + decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor('float32', [], encoder_dims) + decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor('float32', [], decoder_dims) + decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor('float32', [], decoder_dims) + } + } else if (this.config.model_type === 'falcon') { + // NOTE: Custom implementation for Falcon + // @ts-ignore + let dims = [batch_size * this.num_heads, 0, this.dim_kv] + // @ts-ignore + for (let i = 0; i < this.num_layers; ++i) { + decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], dims) + decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], dims) + } + } else if (this.config.multi_query) { // e.g., for `gpt_bigcode` + // @ts-ignore + let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv] + // @ts-ignore + for (let i = 0; i < this.num_layers; ++i) { + decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor('float32', [], dims) + } + } else if (this.config.model_type === 'bloom') { + // NOTE: Custom implementation for Bloom + + // @ts-ignore + let keyDims = [batch_size * this.num_heads, this.dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length] + // @ts-ignore + let valueDims = [batch_size * this.num_heads, 0, this.dim_kv] // [batch_size x num_heads,past_sequence_length,64] + // @ts-ignore + for (let i = 0; i < this.num_layers; ++i) { + decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], keyDims) + decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], valueDims) + } + } else { // Decoder-only + // @ts-ignore + let dims = [batch_size, this.num_heads, 0, this.dim_kv] + // @ts-ignore + for (let i = 0; i < this.num_layers; ++i) { + decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], dims) + decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], dims) + } + } + } + } + + /** + * Initializes and returns the beam for text generation task + * @param {Tensor} inputTokenIds The input token ids. + * @param {Object} generation_config The generation config. + * @param {number} numOutputTokens The number of tokens to be generated. + * @param {Tensor} inputs_attention_mask Optional input attention mask. + * @returns {any} A Beam object representing the initialized beam. + * @private + */ + getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { + return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) + } + + /** + * Runs a single step of the beam search generation algorithm. + * @param {any} beam The current beam being generated. + * @returns {Promise} The updated beam after a single generation step. + * @private + */ + async runBeam(beam) { + return await this._runBeam(this, beam); + } + + /** + * Update a beam with a new token ID. + * @param {Object} beam The beam to update. + * @param {number} newTokenId The new token ID to add to the beam's output. + * @private + */ + updateBeam(beam, newTokenId) { + return this._updateBeam(beam, newTokenId); + } +} + +////////////////////////////////////////////////// +// Base model output class +export class ModelOutput { } + +/** + * Base class for model's outputs, with potential hidden states and attentions. + */ +export class BaseModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. + * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ last_hidden_state, hidden_states = null, attentions = null }) { + super(); + this.last_hidden_state = last_hidden_state; + this.hidden_states = hidden_states; + this.attentions = attentions; + } +} +////////////////////////////////////////////////// +// Bert models +export class BertPreTrainedModel extends PreTrainedModel { } +export class BertModel extends BertPreTrainedModel { } + +/** + * BertForMaskedLM is a class representing a BERT model for masked language modeling. + */ +export class BertForMaskedLM extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * BertForSequenceClassification is a class representing a BERT model for sequence classification. + */ +export class BertForSequenceClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * BertForTokenClassification is a class representing a BERT model for token classification. + */ +export class BertForTokenClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * BertForQuestionAnswering is a class representing a BERT model for question answering. + */ +export class BertForQuestionAnswering extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// RoFormer models +export class RoFormerPreTrainedModel extends PreTrainedModel { } + +/** + * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top. + */ +export class RoFormerModel extends RoFormerPreTrainedModel { } + +/** + * RoFormer Model with a `language modeling` head on top. + */ +export class RoFormerForMaskedLM extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class RoFormerForSequenceClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class RoFormerForTokenClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// ConvBert models +export class ConvBertPreTrainedModel extends PreTrainedModel { } + +/** + * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class ConvBertModel extends ConvBertPreTrainedModel { } + +/** + * ConvBERT Model with a language modeling head on top. + */ +export class ConvBertForMaskedLM extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class ConvBertForSequenceClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class ConvBertForTokenClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`) + */ +export class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Electra models +export class ElectraPreTrainedModel extends PreTrainedModel { } + +/** + * The bare Electra Model transformer outputting raw hidden-states without any specific head on top. + * Identical to the BERT model except that it uses an additional linear layer between the embedding + * layer and the encoder if the hidden size and embedding size are different. + */ +export class ElectraModel extends ElectraPreTrainedModel { } +// TODO add ElectraForPreTraining +/** + * Electra model with a language modeling head on top. + */ +export class ElectraForMaskedLM extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class ElectraForSequenceClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * Electra model with a token classification head on top. + */ +export class ElectraForTokenClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class ElectraForQuestionAnswering extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// CamemBERT models +export class CamembertPreTrainedModel extends PreTrainedModel { } + +/** + * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class CamembertModel extends CamembertPreTrainedModel { } + +/** + * CamemBERT Model with a `language modeling` head on top. + */ +export class CamembertForMaskedLM extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. + */ +export class CamembertForSequenceClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class CamembertForTokenClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * CamemBERT Model with a span classification head on top for extractive question-answering tasks + */ +export class CamembertForQuestionAnswering extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// DeBERTa models +export class DebertaPreTrainedModel extends PreTrainedModel { } + +/** + * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DebertaModel extends DebertaPreTrainedModel { } + +/** + * DeBERTa Model with a `language modeling` head on top. + */ +export class DebertaForMaskedLM extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class DebertaForSequenceClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class DebertaForTokenClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class DebertaForQuestionAnswering extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// DeBERTa-v2 models +export class DebertaV2PreTrainedModel extends PreTrainedModel { } + +/** + * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DebertaV2Model extends DebertaV2PreTrainedModel { } + +/** + * DeBERTa-V2 Model with a `language modeling` head on top. + */ +export class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// DistilBert models +export class DistilBertPreTrainedModel extends PreTrainedModel { } +export class DistilBertModel extends DistilBertPreTrainedModel { } + +/** + * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification. + */ +export class DistilBertForSequenceClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification. + */ +export class DistilBertForTokenClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + + +/** + * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering. + */ +export class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} + +/** + * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task. + */ +export class DistilBertForMaskedLM extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// ESM models +export class EsmPreTrainedModel extends PreTrainedModel { } + +/** + * The bare ESM Model transformer outputting raw hidden-states without any specific head on top. + */ +export class EsmModel extends EsmPreTrainedModel { } + +/** + * ESM Model with a `language modeling` head on top. + */ +export class EsmForMaskedLM extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class EsmForSequenceClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class EsmForTokenClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// MobileBert models +export class MobileBertPreTrainedModel extends PreTrainedModel { } +export class MobileBertModel extends MobileBertPreTrainedModel { } + +/** + * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task. + */ +export class MobileBertForMaskedLM extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class MobileBertForSequenceClassification extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * MobileBert Model with a span classification head on top for extractive question-answering tasks + */ +export class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// MPNet models +export class MPNetPreTrainedModel extends PreTrainedModel { } + +/** + * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top. + */ +export class MPNetModel extends MPNetPreTrainedModel { } + +/** + * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling. + */ +export class MPNetForMaskedLM extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification. + */ +export class MPNetForSequenceClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * MPNetForTokenClassification is a class representing a MPNet model for token classification. + */ +export class MPNetForTokenClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * MPNetForQuestionAnswering is a class representing a MPNet model for question answering. + */ +export class MPNetForQuestionAnswering extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// SqueezeBert models +export class SqueezeBertPreTrainedModel extends PreTrainedModel { } +export class SqueezeBertModel extends SqueezeBertPreTrainedModel { } +export class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} +export class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +export class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Albert models +export class AlbertPreTrainedModel extends PreTrainedModel { } +export class AlbertModel extends AlbertPreTrainedModel { } +export class AlbertForSequenceClassification extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +export class AlbertForQuestionAnswering extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +export class AlbertForMaskedLM extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// T5 models +export class T5PreTrainedModel extends PreTrainedModel { }; + +export class T5Model extends T5PreTrainedModel { } + +/** + * T5Model is a class representing a T5 model for conditional generation. + */ +export class T5ForConditionalGeneration extends T5PreTrainedModel { + + /** + * Creates a new instance of the `T5ForConditionalGeneration` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.num_decoder_layers; + this.num_decoder_heads = this.config.num_heads; + this.decoder_dim_kv = this.config.d_kv; + + this.num_encoder_layers = this.config.num_layers; + this.num_encoder_heads = this.config.num_heads; + this.encoder_dim_kv = this.config.d_kv; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// LONGT5 models +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class LongT5PreTrainedModel extends PreTrainedModel { }; + +/** + * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class LongT5Model extends LongT5PreTrainedModel { } + +/** + * LONGT5 Model with a `language modeling` head on top. + */ +export class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { + /** + * Creates a new instance of the `LongT5ForConditionalGeneration` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.num_decoder_layers; + this.num_decoder_heads = this.config.num_heads; + this.decoder_dim_kv = this.config.d_kv; + + this.num_encoder_layers = this.config.num_layers; + this.num_encoder_heads = this.config.num_heads; + this.encoder_dim_kv = this.config.d_kv; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// MT5 models +export class MT5PreTrainedModel extends PreTrainedModel { }; + +export class MT5Model extends MT5PreTrainedModel { } + +/** + * A class representing a conditional sequence-to-sequence model based on the MT5 architecture. + */ +export class MT5ForConditionalGeneration extends MT5PreTrainedModel { + + /** + * Creates a new instance of the `MT5ForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.num_decoder_layers; + this.num_decoder_heads = this.config.num_heads; + this.decoder_dim_kv = this.config.d_kv; + + this.num_encoder_layers = this.config.num_layers; + this.num_encoder_heads = this.config.num_heads; + this.encoder_dim_kv = this.config.d_kv; + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Bart models +export class BartPretrainedModel extends PreTrainedModel { }; + +/** + * The bare BART Model outputting raw hidden-states without any specific head on top. + */ +export class BartModel extends BartPretrainedModel { } + +/** + * The BART Model with a language modeling head. Can be used for summarization. + */ +export class BartForConditionalGeneration extends BartPretrainedModel { + + /** + * Creates a new instance of the `BartForConditionalGeneration` class. + * @param {Object} config The configuration object for the Bart model. + * @param {Object} session The ONNX session used to execute the model. + * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. + * @param {Object} generation_config The generation configuration object. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } + +} + +/** + * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) + */ +export class BartForSequenceClassification extends BartPretrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// MBart models +export class MBartPreTrainedModel extends PreTrainedModel { }; + +/** + * The bare MBART Model outputting raw hidden-states without any specific head on top. + */ +export class MBartModel extends MBartPreTrainedModel { } + +/** + * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models. + */ +export class MBartForConditionalGeneration extends MBartPreTrainedModel { + + /** + * Creates a new instance of the `MBartForConditionalGeneration` class. + * @param {Object} config The configuration object for the Bart model. + * @param {Object} session The ONNX session used to execute the model. + * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. + * @param {Object} generation_config The generation configuration object. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } + +} + +/** + * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output). + */ +export class MBartForSequenceClassification extends MBartPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + + +export class MBartForCausalLM extends MBartPreTrainedModel { + /** + * Creates a new instance of the `MBartForCausalLM` class. + * @param {Object} config Configuration object for the model. + * @param {Object} decoder_merged_session ONNX Session object for the decoder. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config, decoder_merged_session, generation_config) { + super(config, decoder_merged_session); + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Blenderbot models +export class BlenderbotPreTrainedModel extends PreTrainedModel { }; + +/** + * The bare Blenderbot Model outputting raw hidden-states without any specific head on top. + */ +export class BlenderbotModel extends BlenderbotPreTrainedModel { } + +/** + * The Blenderbot Model with a language modeling head. Can be used for summarization. + */ +export class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { + + /** + * Creates a new instance of the `BlenderbotForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Blenderbot models +export class BlenderbotSmallPreTrainedModel extends PreTrainedModel { }; + +/** + * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top. + */ +export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { } + +/** + * The BlenderbotSmall Model with a language modeling head. Can be used for summarization. + */ +export class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { + + /** + * Creates a new instance of the `BlenderbotForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Roberta models +export class RobertaPreTrainedModel extends PreTrainedModel { } +export class RobertaModel extends RobertaPreTrainedModel { } + +/** + * RobertaForMaskedLM class for performing masked language modeling on Roberta models. + */ +export class RobertaForMaskedLM extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * RobertaForSequenceClassification class for performing sequence classification on Roberta models. + */ +export class RobertaForSequenceClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * RobertaForTokenClassification class for performing token classification on Roberta models. + */ +export class RobertaForTokenClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * RobertaForQuestionAnswering class for performing question answering on Roberta models. + */ +export class RobertaForQuestionAnswering extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// XLM models +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class XLMPreTrainedModel extends PreTrainedModel { } + +/** + * The bare XLM Model transformer outputting raw hidden-states without any specific head on top. + */ +export class XLMModel extends XLMPreTrainedModel { } + +/** + * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class XLMWithLMHeadModel extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class XLMForSequenceClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) + */ +export class XLMForTokenClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * XLM Model with a span classification head on top for extractive question-answering tasks + */ +export class XLMForQuestionAnswering extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// XLMRoberta models +export class XLMRobertaPreTrainedModel extends PreTrainedModel { } +export class XLMRobertaModel extends XLMRobertaPreTrainedModel { } + +/** + * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models. + */ +export class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +} + +/** + * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models. + */ +export class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models. + */ +export class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +} + +/** + * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models. + */ +export class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Audio Spectrogram Transformer (AST) models +export class ASTPreTrainedModel extends PreTrainedModel { }; + +/** + * The bare AST Model transformer outputting raw hidden-states without any specific head on top. + */ +export class ASTModel extends ASTPreTrainedModel { } + +/** + * Audio Spectrogram Transformer model with an audio classification head on top + * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2. + */ +export class ASTForAudioClassification extends ASTPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Whisper models +export class WhisperPreTrainedModel extends PreTrainedModel { }; + +/** + * WhisperModel class for training Whisper models without a language model head. + */ +export class WhisperModel extends WhisperPreTrainedModel { } + +/** + * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models. + */ +export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { + + requires_attention_mask = false; + main_input_name = 'input_features'; + + /** + * Creates a new instance of the `WhisperForConditionalGeneration` class. + * @param {Object} config Configuration object for the model. + * @param {Object} session ONNX Session object for the model. + * @param {Object} decoder_merged_session ONNX Session object for the decoder. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } + + /** + * @typedef {Object} WhisperGenerationConfig + * @extends GenerationConfig + * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. + * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps + * with the text. This can be used with or without the `return_timestamps` option. To get word-level + * timestamps, use the tokenizer to group the tokens into words. + * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps. + */ + + /** + * Generates outputs based on input and generation configuration. + * @param {Object} inputs Input data for the model. + * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process. + * @param {Object} logits_processor Optional logits processor object. + * @returns {Promise} Promise object represents the generated outputs. + */ + async generate( + inputs, + generation_config = null, + logits_processor = null, + // { + // return_timestamps = null, + // return_token_timestamps = null, + // language = null, + // task = null, + // } = {}, + ) { + // Create generation config object + generation_config = this._get_generation_config(generation_config); + + + // Whisper has additional options for returning timestamps + generation_config.return_timestamps ??= false; + + // TODO add language and task + + if (generation_config.return_timestamps) { + logits_processor = [new WhisperTimeStampLogitsProcessor(generation_config)] + } + + if (generation_config.return_token_timestamps) { + generation_config.output_attentions = true; + generation_config.return_dict_in_generate = true; + + if (generation_config.task === 'translate') { + console.warn("Token-level timestamps may not be reliable for task 'translate'.") + } + + if (!generation_config.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." + ) + } + } + + const outputs = await super.generate(inputs, generation_config, logits_processor); + + if (generation_config.return_token_timestamps && generation_config.alignment_heads) { + outputs["token_timestamps"] = this._extract_token_timestamps( + outputs, + generation_config.alignment_heads, + generation_config.num_frames, + ) + } + + return outputs + } + + /** + * Calculates token-level timestamps using the encoder-decoder cross-attentions and + * dynamic time-warping (DTW) to map each output token to a position in the input audio. + * @param {Object} generate_outputs Outputs generated by the model + * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model + * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model + * @param {number[][]} generate_outputs.sequences The sequences output by the model + * @param {number[][]} alignment_heads Alignment heads of the model + * @param {number} [num_frames=null] Number of frames in the input audio. + * @param {number} [time_precision=0.02] Precision of the timestamps in seconds + * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token + */ + _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) { + if (!generate_outputs.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`." + ) + } + + let median_filter_width = this.config.median_filter_width; + if (median_filter_width === undefined) { + console.warn("Model config has no `median_filter_width`, using default value of 7.") + median_filter_width = 7; + } + + const batchedMatrices = generate_outputs.cross_attentions.map(batch => { + // Create a list with `decoder_layers` elements, each a tensor of shape + // (batch size, attention_heads, output length, input length). + let cross_attentions = Array.from({ length: this.config.decoder_layers }, + (_, i) => cat(batch.map(x => x[i]), 2) + ); + + let weights = stack(alignment_heads.map(([l, h]) => { + return num_frames + ? cross_attentions[l].slice(null, h, null, [0, num_frames]) + : cross_attentions[l].slice(null, h); + })); + weights = weights.transpose(1, 0, 2, 3) + + let [std, calculatedMean] = std_mean(weights, -2, 0, true); + + // Normalize and smoothen the weights. + let smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500] + + for (let a = 0; a < smoothedWeights.dims[0]; ++a) { + let aTensor = smoothedWeights[a]; // [8, seqLength, 1500] + + for (let b = 0; b < aTensor.dims[0]; ++b) { + let bTensor = aTensor[b]; // [seqLength, 1500] + + const stdTensor = std[a][b][0]; // [1500] + const meanTensor = calculatedMean[a][b][0]; // [1500] + + for (let c = 0; c < bTensor.dims[0]; ++c) { + + let cTensor = bTensor[c]; // [1500] + for (let d = 0; d < cTensor.data.length; ++d) { + cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d] + } + + // Apply median filter. + // cTensor.data.set(medianFilter(cTensor.data, median_filter_width)) + } + } + } + + // Average the different cross-attention heads. + const matrix = mean(smoothedWeights, 1); + return matrix; + }); + + const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length]; + + const timestamps = new Tensor( + 'float32', + new Float32Array(timestampsShape[0] * timestampsShape[1]), + timestampsShape + ); + + // Perform dynamic time warping on each element of the batch. + for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { + // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions + // as the python implementation + const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); + let [text_indices, time_indices] = dynamicTimeWarping(matrix); + + let diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]); + let jumps = mergeArrays([1], diffs).map(x => !!x); // convert to boolean + + let jump_times = []; + for (let i = 0; i < jumps.length; ++i) { + if (jumps[i]) { + jump_times.push(time_indices[i] * time_precision); + // NOTE: No point in rounding here, since we set to Float32Array later + } + } + timestamps[batch_idx].data.set(jump_times, 1) + } + + return timestamps; + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +/** + * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks + */ +export class VisionEncoderDecoderModel extends PreTrainedModel { + main_input_name = 'pixel_values'; + + /** + * Creates a new instance of the `VisionEncoderDecoderModel` class. + * @param {Object} config The configuration object specifying the hyperparameters and other model settings. + * @param {Object} session The ONNX session containing the encoder model. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder model. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + // Extract configs + const encoderConfig = this.config.encoder; + const decoderConfig = this.config.decoder; + + // Validate encoder + const encoderModelType = encoderConfig.model_type; + const encoderModel = + MODEL_MAPPING_NAMES_ENCODER_ONLY.get(encoderModelType) + ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(encoderModelType); + if (!encoderModel) { + console.warn(`Model type for encoder '${encoderModelType}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`); + } + + // Validate decoder + const decoderModel = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(decoderConfig.model_type); + if (!decoderModel) { + throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`); + } + + // @ts-ignore + const decoderModelClass = decoderModel[1]; + // @ts-ignore + const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config); + + this.add_encoder_pkv = 'num_decoder_layers' in decoder; + if (this.add_encoder_pkv) { + // Decoder is part of an encoder-decoder model + this.num_decoder_layers = decoder.num_decoder_layers; + this.num_decoder_heads = decoder.num_decoder_heads; + this.decoder_dim_kv = decoder.decoder_dim_kv; + + this.num_encoder_layers = decoder.num_encoder_layers; + this.num_encoder_heads = decoder.num_encoder_heads; + this.encoder_dim_kv = decoder.encoder_dim_kv; + + } else { + // Decoder is a decoder-only model + this.num_layers = decoder.num_layers; + this.num_heads = decoder.num_heads; + this.dim_kv = decoder.dim_kv; + } + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// CLIP models +export class CLIPPreTrainedModel extends PreTrainedModel { } + +/** + * CLIP Text and Vision Model with a projection layers on top + * + * **Example:** Perform zero-shot image classification with a `CLIPModel`. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); + * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Run tokenization + * let texts = ['a photo of a car', 'a photo of a football match'] + * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Read image and run processor + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * let output = await model({ ...text_inputs, ...image_inputs }); + * // { + * // logits_per_image: Tensor { + * // dims: [ 1, 2 ], + * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], + * // }, + * // logits_per_text: Tensor { + * // dims: [ 2, 1 ], + * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], + * // }, + * // text_embeds: Tensor { + * // dims: [ 2, 512 ], + * // data: Float32Array(1024) [ ... ], + * // }, + * // image_embeds: Tensor { + * // dims: [ 1, 512 ], + * // data: Float32Array(512) [ ... ], + * // } + * // } + * ``` + */ +export class CLIPModel extends CLIPPreTrainedModel { } + +/** + * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output) + * + * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`. + * + * ```javascript + * import { AutoTokenizer, CLIPTextModelWithProjection } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); + * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Run tokenization + * let texts = ['a photo of a car', 'a photo of a football match']; + * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Compute embeddings + * const { text_embeds } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 512 ], + * // type: 'float32', + * // data: Float32Array(1024) [ ... ], + * // size: 1024 + * // } + * ``` + */ +export class CLIPTextModelWithProjection extends CLIPPreTrainedModel { + + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'text_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} + +/** + * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output) + * + * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`. + * + * ```javascript + * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@xenova/transformers'; + * + * // Load processor and vision model + * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Read image and run processor + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * + * // Compute embeddings + * const { image_embeds } = await vision_model(image_inputs); + * // Tensor { + * // dims: [ 1, 512 ], + * // type: 'float32', + * // data: Float32Array(512) [ ... ], + * // size: 512 + * // } + * ``` + */ +export class CLIPVisionModelWithProjection extends CLIPPreTrainedModel { + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'vision_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// SigLIP models +export class SiglipPreTrainedModel extends PreTrainedModel { } + +/** + * SigLIP Text and Vision Model with a projection layers on top + * + * **Example:** Perform zero-shot image classification with a `SiglipModel`. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); + * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); + * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Run tokenization + * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; + * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); + * + * // Read image and run processor + * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg'); + * const image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * const output = await model({ ...text_inputs, ...image_inputs }); + * // { + * // logits_per_image: Tensor { + * // dims: [ 1, 2 ], + * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], + * // }, + * // logits_per_text: Tensor { + * // dims: [ 2, 1 ], + * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], + * // }, + * // text_embeds: Tensor { + * // dims: [ 2, 768 ], + * // data: Float32Array(1536) [ ... ], + * // }, + * // image_embeds: Tensor { + * // dims: [ 1, 768 ], + * // data: Float32Array(768) [ ... ], + * // } + * // } + * ``` + */ +export class SiglipModel extends SiglipPreTrainedModel { } + +/** + * The text model from SigLIP without any head or projection on top. + * + * **Example:** Compute text embeddings with `SiglipTextModel`. + * + * ```javascript + * import { AutoTokenizer, SiglipTextModel } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); + * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Run tokenization + * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; + * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); + * + * // Compute embeddings + * const { pooler_output } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 768 ], + * // type: 'float32', + * // data: Float32Array(1536) [ ... ], + * // size: 1536 + * // } + * ``` + */ +export class SiglipTextModel extends SiglipPreTrainedModel { + + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'text_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} + +/** + * The vision model from SigLIP without any head or projection on top. + * + * **Example:** Compute vision embeddings with `SiglipVisionModel`. + * + * ```javascript + * import { AutoProcessor, SiglipVisionModel, RawImage} from '@xenova/transformers'; + * + * // Load processor and vision model + * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); + * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Read image and run processor + * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * const image_inputs = await processor(image); + * + * // Compute embeddings + * const { pooler_output } = await vision_model(image_inputs); + * // Tensor { + * // dims: [ 1, 768 ], + * // type: 'float32', + * // data: Float32Array(768) [ ... ], + * // size: 768 + * // } + * ``` + */ +export class SiglipVisionModel extends CLIPPreTrainedModel { + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'vision_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} +////////////////////////////////////////////////// +// ChineseCLIP models +export class ChineseCLIPPreTrainedModel extends PreTrainedModel { } + +export class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// CLIPSeg models +export class CLIPSegPreTrainedModel extends PreTrainedModel { } + +export class CLIPSegModel extends CLIPSegPreTrainedModel { } + +/** + * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation. + * + * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined'); + * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined'); + * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined'); + * + * // Run tokenization + * const texts = ['a glass', 'something to fill', 'wood', 'a jar']; + * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Read image and run processor + * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true'); + * const image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * const { logits } = await model({ ...text_inputs, ...image_inputs }); + * // logits: Tensor { + * // dims: [4, 352, 352], + * // type: 'float32', + * // data: Float32Array(495616) [ ... ], + * // size: 495616 + * // } + * ``` + * + * You can visualize the predictions as follows: + * ```javascript + * const preds = logits + * .unsqueeze_(1) + * .sigmoid_() + * .mul_(255) + * .round_() + * .to('uint8'); + * + * for (let i = 0; i < preds.dims[0]; ++i) { + * const img = RawImage.fromTensor(preds[i]); + * img.save(`prediction_${i}.png`); + * } + * ``` + */ +export class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// GPT2 models +export class GPT2PreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPT2PreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_head + this.num_layers = this.config.n_layer + this.dim_kv = this.config.n_embd / this.num_heads; + } +} + +export class GPT2Model extends GPT2PreTrainedModel { } + +/** + * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks. + */ +export class GPT2LMHeadModel extends GPT2PreTrainedModel { } +// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel { +// TODO +// } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// GPTNeo models +export class GPTNeoPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTNeoPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_heads; + this.num_layers = this.config.num_layers; + this.dim_kv = this.config.hidden_size / this.num_heads; + } +} +export class GPTNeoModel extends GPTNeoPreTrainedModel { } + +export class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// GPTNeoX models +export class GPTNeoXPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTNeoXPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_attention_heads; + this.num_layers = this.config.num_hidden_layers; + this.dim_kv = this.config.hidden_size / this.num_heads; + } +} +export class GPTNeoXModel extends GPTNeoXPreTrainedModel { } + +export class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// GPT-J models +export class GPTJPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTJPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_head + this.num_layers = this.config.n_layer + this.dim_kv = this.config.n_embd / this.num_heads; + } +} + +export class GPTJModel extends GPTJPreTrainedModel { } + +export class GPTJForCausalLM extends GPTJPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// GPTBigCode models +export class GPTBigCodePreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTBigCodePreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_head + this.num_layers = this.config.n_layer + this.dim_kv = this.config.n_embd / this.num_heads; + } +} + +export class GPTBigCodeModel extends GPTBigCodePreTrainedModel { } + +export class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// CodeGen models +export class CodeGenPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `CodeGenPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_head + this.num_layers = this.config.n_layer + this.dim_kv = this.config.n_embd / this.num_heads; + } +} +/** + * CodeGenModel is a class representing a code generation model without a language model head. + */ +export class CodeGenModel extends CodeGenPreTrainedModel { } + +/** + * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class. + */ +export class CodeGenForCausalLM extends CodeGenPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// LLama models + +/** + * The bare LLama Model outputting raw hidden-states without any specific head on top. + */ +export class LlamaPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `LlamaPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads + this.num_layers = this.config.num_hidden_layers + this.dim_kv = this.config.hidden_size / this.config.num_attention_heads + } +} +/** + * The bare LLaMA Model outputting raw hidden-states without any specific head on top. + */ +export class LlamaModel extends LlamaPreTrainedModel { } + +export class LlamaForCausalLM extends LlamaPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Phi models + +export class PhiPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `PhiPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id; + + this.num_heads = this.config.num_attention_heads; + this.num_layers = this.config.num_hidden_layers; + this.dim_kv = this.config.hidden_size / this.num_heads; + } +} +/** + * The bare Phi Model outputting raw hidden-states without any specific head on top. + */ +export class PhiModel extends PhiPreTrainedModel { } + +export class PhiForCausalLM extends PhiPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Bloom models +/** + * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class BloomPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `BloomPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_head + this.num_layers = this.config.n_layer + this.dim_kv = this.config.hidden_size / this.num_heads; + } +} + +/** + * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top. + */ +export class BloomModel extends BloomPreTrainedModel { } + +/** + * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class BloomForCausalLM extends BloomPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// MPT models +export class MptPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `MptPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.n_heads + this.num_layers = this.config.n_layers + this.dim_kv = this.config.d_model / this.num_heads; + } +} + +/** + * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top. + */ +export class MptModel extends MptPreTrainedModel { } + +/** + * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class MptForCausalLM extends MptPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// OPT models +export class OPTPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `OPTPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_attention_heads; + this.num_layers = this.config.num_hidden_layers; + this.dim_kv = this.config.hidden_size / this.num_heads; + } +} + +/** + * The bare OPT Model outputting raw hidden-states without any specific head on top. + */ +export class OPTModel extends OPTPreTrainedModel { } + +/** + * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class OPTForCausalLM extends OPTPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class ViTPreTrainedModel extends PreTrainedModel { } +export class ViTModel extends ViTPreTrainedModel { } +export class ViTForImageClassification extends ViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class VitMattePreTrainedModel extends PreTrainedModel { } + +/** + * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes. + * + * **Example:** Perform image matting with a `VitMatteForImageMatting` model. + * ```javascript + * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@xenova/transformers'; + * + * // Load processor and model + * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646'); + * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646'); + * + * // Load image and trimap + * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png'); + * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png'); + * + * // Prepare image + trimap for the model + * const inputs = await processor(image, trimap); + * + * // Predict alpha matte + * const { alphas } = await model(inputs); + * // Tensor { + * // dims: [ 1, 1, 640, 960 ], + * // type: 'float32', + * // size: 614400, + * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ] + * // } + * ``` + * + * You can visualize the alpha matte as follows: + * ```javascript + * import { Tensor, cat } from '@xenova/transformers'; + * + * // Visualize predicted alpha matte + * const imageTensor = new Tensor( + * 'uint8', + * new Uint8Array(image.data), + * [image.height, image.width, image.channels] + * ).transpose(2, 0, 1); + * + * // Convert float (0-1) alpha matte to uint8 (0-255) + * const alphaChannel = alphas + * .squeeze(0) + * .mul_(255) + * .clamp_(0, 255) + * .round_() + * .to('uint8'); + * + * // Concatenate original image with predicted alpha + * const imageData = cat([imageTensor, alphaChannel], 0); + * + * // Save output image + * const outputImage = RawImage.fromTensor(imageData); + * outputImage.save('output.png'); + * ``` + */ +export class VitMatteForImageMatting extends VitMattePreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new ImageMattingOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class MobileViTPreTrainedModel extends PreTrainedModel { } +export class MobileViTModel extends MobileViTPreTrainedModel { } +export class MobileViTForImageClassification extends MobileViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +// TODO: MobileViTForSemanticSegmentation + +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class OwlViTPreTrainedModel extends PreTrainedModel { } +export class OwlViTModel extends OwlViTPreTrainedModel { } +export class OwlViTForObjectDetection extends OwlViTPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Beit Models +export class BeitPreTrainedModel extends PreTrainedModel { } +export class BeitModel extends BeitPreTrainedModel { } +export class BeitForImageClassification extends BeitPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class DetrPreTrainedModel extends PreTrainedModel { } +export class DetrModel extends DetrPreTrainedModel { } +export class DetrForObjectDetection extends DetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new DetrObjectDetectionOutput(await super._call(model_inputs)); + } +} + +export class DetrForSegmentation extends DetrPreTrainedModel { + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new DetrSegmentationOutput(await super._call(model_inputs)); + } +} + +export class DetrObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } +} + +export class DetrSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.pred_boxes Predicted boxes. + * @param {Tensor} output.pred_masks Predicted masks. + */ + constructor({ logits, pred_boxes, pred_masks }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + this.pred_masks = pred_masks; + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class TableTransformerPreTrainedModel extends PreTrainedModel { } + +/** + * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) + * outputting raw hidden-states without any specific head on top. + */ +export class TableTransformerModel extends TableTransformerPreTrainedModel { } + +/** + * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) + * with object detection heads on top, for tasks such as COCO detection. + */ +export class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); + } +} +export class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class DeiTPreTrainedModel extends PreTrainedModel { } +export class DeiTModel extends DeiTPreTrainedModel { } +export class DeiTForImageClassification extends DeiTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class ResNetPreTrainedModel extends PreTrainedModel { } + +/** + * The bare ResNet model outputting raw features without any specific head on top. + */ +export class ResNetModel extends ResNetPreTrainedModel { } + +/** + * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ResNetForImageClassification extends ResNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class SwinPreTrainedModel extends PreTrainedModel { } +export class SwinModel extends SwinPreTrainedModel { } +export class SwinForImageClassification extends SwinPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class Swin2SRPreTrainedModel extends PreTrainedModel { } + +/** + * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top. + */ +export class Swin2SRModel extends Swin2SRPreTrainedModel { } + +/** + * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration. + * + * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`. + * + * ```javascript + * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@xenova/transformers'; + * + * // Load processor and model + * const model_id = 'Xenova/swin2SR-classical-sr-x2-64'; + * const processor = await AutoProcessor.from_pretrained(model_id); + * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id); + * + * // Prepare model inputs + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; + * const image = await RawImage.fromURL(url); + * const inputs = await processor(image); + * + * // Run model + * const outputs = await model(inputs); + * + * // Convert Tensor to RawImage + * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8'); + * const outputImage = RawImage.fromTensor(output); + * // RawImage { + * // data: Uint8Array(786432) [ 41, 31, 24, ... ], + * // width: 512, + * // height: 512, + * // channels: 3 + * // } + * ``` + */ +export class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class DPTPreTrainedModel extends PreTrainedModel { } + +/** + * The bare DPT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DPTModel extends DPTPreTrainedModel { } + +/** + * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2. + * + * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`. + * ```javascript + * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers'; + * + * // Load model and processor + * const model_id = 'Xenova/dpt-hybrid-midas'; + * const model = await DPTForDepthEstimation.from_pretrained(model_id); + * const processor = await AutoProcessor.from_pretrained(model_id); + * + * // Load image from URL + * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; + * const image = await RawImage.fromURL(url); + * + * // Prepare image for the model + * const inputs = await processor(image); + * + * // Run model + * const { predicted_depth } = await model(inputs); + * + * // Interpolate to original size + * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false); + * + * // Visualize the prediction + * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8'); + * const depth = RawImage.fromTensor(formatted); + * // RawImage { + * // data: Uint8Array(307200) [ 85, 85, 84, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * ``` + */ +export class DPTForDepthEstimation extends DPTPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class GLPNPreTrainedModel extends PreTrainedModel { } + +/** + * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. + */ +export class GLPNModel extends GLPNPreTrainedModel { } + +/** + * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2. + * + * **Example:** Depth estimation w/ `Xenova/glpn-kitti`. + * ```javascript + * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers'; + * + * // Load model and processor + * const model_id = 'Xenova/glpn-kitti'; + * const model = await GLPNForDepthEstimation.from_pretrained(model_id); + * const processor = await AutoProcessor.from_pretrained(model_id); + * + * // Load image from URL + * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; + * const image = await RawImage.fromURL(url); + * + * // Prepare image for the model + * const inputs = await processor(image); + * + * // Run model + * const { predicted_depth } = await model(inputs); + * + * // Interpolate to original size + * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false); + * + * // Visualize the prediction + * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8'); + * const depth = RawImage.fromTensor(formatted); + * // RawImage { + * // data: Uint8Array(307200) [ 207, 169, 154, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * ``` + */ +export class GLPNForDepthEstimation extends GLPNPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class DonutSwinPreTrainedModel extends PreTrainedModel { } + +/** + * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Step-by-step Document Parsing. + * + * ```javascript + * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers'; + * + * // Choose model to use + * const model_id = 'Xenova/donut-base-finetuned-cord-v2'; + * + * // Prepare image inputs + * const processor = await AutoProcessor.from_pretrained(model_id); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png'; + * const image = await RawImage.read(url); + * const image_inputs = await processor(image); + * + * // Prepare decoder inputs + * const tokenizer = await AutoTokenizer.from_pretrained(model_id); + * const task_prompt = ''; + * const decoder_input_ids = tokenizer(task_prompt, { + * add_special_tokens: false, + * }).input_ids; + * + * // Create the model + * const model = await AutoModelForVision2Seq.from_pretrained(model_id); + * + * // Run inference + * const output = await model.generate(image_inputs.pixel_values, { + * decoder_input_ids, + * max_length: model.config.decoder.max_position_embeddings, + * }); + * + * // Decode output + * const decoded = tokenizer.batch_decode(output)[0]; + * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000 + * ``` + * + * **Example:** Step-by-step Document Visual Question Answering (DocVQA) + * + * ```javascript + * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers'; + * + * // Choose model to use + * const model_id = 'Xenova/donut-base-finetuned-docvqa'; + * + * // Prepare image inputs + * const processor = await AutoProcessor.from_pretrained(model_id); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; + * const image = await RawImage.read(url); + * const image_inputs = await processor(image); + * + * // Prepare decoder inputs + * const tokenizer = await AutoTokenizer.from_pretrained(model_id); + * const question = 'What is the invoice number?'; + * const task_prompt = `${question}`; + * const decoder_input_ids = tokenizer(task_prompt, { + * add_special_tokens: false, + * }).input_ids; + * + * // Create the model + * const model = await AutoModelForVision2Seq.from_pretrained(model_id); + * + * // Run inference + * const output = await model.generate(image_inputs.pixel_values, { + * decoder_input_ids, + * max_length: model.config.decoder.max_position_embeddings, + * }); + * + * // Decode output + * const decoded = tokenizer.batch_decode(output)[0]; + * // What is the invoice number? us-001 + * ``` + */ +export class DonutSwinModel extends DonutSwinPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class ConvNextPreTrainedModel extends PreTrainedModel { } + +/** + * The bare ConvNext model outputting raw features without any specific head on top. + */ +export class ConvNextModel extends ConvNextPreTrainedModel { } + +/** + * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ConvNextForImageClassification extends ConvNextPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class ConvNextV2PreTrainedModel extends PreTrainedModel { } + +/** + * The bare ConvNextV2 model outputting raw features without any specific head on top. + */ +export class ConvNextV2Model extends ConvNextV2PreTrainedModel { } + +/** + * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class Dinov2PreTrainedModel extends PreTrainedModel { } + +/** + * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class Dinov2Model extends Dinov2PreTrainedModel { } + +/** + * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. + */ +export class Dinov2ForImageClassification extends Dinov2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class YolosPreTrainedModel extends PreTrainedModel { } +export class YolosModel extends YolosPreTrainedModel { } +export class YolosForObjectDetection extends YolosPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new YolosObjectDetectionOutput(await super._call(model_inputs)); + } +} + +export class YolosObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +export class SamPreTrainedModel extends PreTrainedModel { } + +/** + * Segment Anything Model (SAM) for generating segmentation masks, given an input image + * and optional 2D location and bounding boxes. + * + * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`. + * ```javascript + * import { SamModel, AutoProcessor, RawImage } from '@xenova/transformers'; + * + * const model = await SamModel.from_pretrained('Xenova/sam-vit-base'); + * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base'); + * + * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'; + * const raw_image = await RawImage.read(img_url); + * const input_points = [[[450, 600]]] // 2D localization of a window + * + * const inputs = await processor(raw_image, input_points); + * const outputs = await model(inputs); + * + * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes); + * // [ + * // Tensor { + * // dims: [ 1, 3, 1764, 2646 ], + * // type: 'bool', + * // data: Uint8Array(14002632) [ ... ], + * // size: 14002632 + * // } + * // ] + * const scores = outputs.iou_scores; + * // Tensor { + * // dims: [ 1, 1, 3 ], + * // type: 'float32', + * // data: Float32Array(3) [ + * // 0.8892380595207214, + * // 0.9311248064041138, + * // 0.983696699142456 + * // ], + * // size: 3 + * // } + * ``` + */ +export class SamModel extends SamPreTrainedModel { + /** + * Creates a new instance of the `SamModel` class. + * @param {Object} config The configuration object specifying the hyperparameters and other model settings. + * @param {Object} vision_encoder The ONNX session containing the vision encoder model. + * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model. + */ + constructor(config, vision_encoder, prompt_encoder_mask_decoder) { + super(config, vision_encoder); + this.prompt_encoder_mask_decoder = prompt_encoder_mask_decoder; + } + + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. + * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. + */ + async get_image_embeddings({ pixel_values }) { + // in: + // - pixel_values: tensor.float32[batch_size,3,1024,1024] + // + // out: + // - image_embeddings: tensor.float32[batch_size,256,64,64] + // - image_positional_embeddings: tensor.float32[batch_size,256,64,64] + return await encoderForward(this, { pixel_values }) + } + + /** + * @typedef {Object} SamModelInputs Object containing the model inputs. + * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. + * These can be obtained using a `SamProcessor`. + * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`. + * This is used by the prompt encoder to encode the prompt. + * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. + * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: + * - `1`: the point is a point that contains the object of interest + * - `0`: the point is a point that does not contain the object of interest + * - `-1`: the point corresponds to the background + * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder + * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. + * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. + */ + + /** + * @param {SamModelInputs} model_inputs Object containing the model inputs. + * @returns {Promise} The output of the model. + */ + async forward(model_inputs) { + if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) { + // Compute the image embeddings if they are missing + model_inputs = { + ...model_inputs, + ...(await this.get_image_embeddings(model_inputs)) + } + } + + if (!model_inputs.input_labels) { + // Set default input labels if they are missing + const shape = model_inputs.input_points.dims.slice(0, -1); + const numElements = shape.reduce((a, b) => a * b, 1); + model_inputs.input_labels = new Tensor( + 'int64', + new BigInt64Array(numElements).fill(1n), + shape + ); + } + + // Returns: + // - iou_scores: tensor.float32[batch_size,point_batch_size,3] + // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256] + return await sessionRun(this.prompt_encoder_mask_decoder, { + input_points: model_inputs.input_points, + input_labels: model_inputs.input_labels, + image_embeddings: model_inputs.image_embeddings, + image_positional_embeddings: model_inputs.image_positional_embeddings, + }); + } + + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new SamImageSegmentationOutput(await super._call(model_inputs)); + } +} + + +/** + * Base class for Segment-Anything model's output. + */ +export class SamImageSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + */ + constructor({ iou_scores, pred_masks }) { + super(); + this.iou_scores = iou_scores; + this.pred_masks = pred_masks; + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// MarianMT models +export class MarianPreTrainedModel extends PreTrainedModel { }; + +export class MarianModel extends MarianPreTrainedModel { } + +export class MarianMTModel extends MarianPreTrainedModel { + + /** + * Creates a new instance of the `MarianMTModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {any} decoder_merged_session + * @param {any} generation_config + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// M2M100 models +export class M2M100PreTrainedModel extends PreTrainedModel { }; + +export class M2M100Model extends M2M100PreTrainedModel { } + +export class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { + + /** + * Creates a new instance of the `M2M100ForConditionalGeneration` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {any} decoder_merged_session + * @param {any} generation_config + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; + } + +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Wav2Vec2 models +export class Wav2Vec2PreTrainedModel extends PreTrainedModel { }; + +/** + * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `Wav2Vec2Model` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m'); + * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000); + * const inputs = await processor(audio); + * + * // Run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/mms-300m'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 1144, 1024 ], + * // type: 'float32', + * // data: Float32Array(1171456) [ ... ], + * // size: 1171456 + * // } + * // } + * ``` + */ +export class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { } + +export class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +} + +export class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Hubert models +export class HubertPreTrainedModel extends PreTrainedModel { } + +/** + * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `HubertModel` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960'); + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); + * const inputs = await processor(audio); + * + * // Load and run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 549, 768 ], + * // type: 'float32', + * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...], + * // size: 421632 + * // } + * // } + * ``` + */ +export class HubertModel extends Wav2Vec2PreTrainedModel { } + +/** + * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). + */ +export class HubertForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +} + +/** + * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. + */ +export class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// WavLM models +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class WavLMPreTrainedModel extends PreTrainedModel { }; + +/** + * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `WavLMModel` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base'); + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); + * const inputs = await processor(audio); + * + * // Run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/wavlm-base'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 549, 768 ], + * // type: 'float32', + * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...], + * // size: 421632 + * // } + * // } + * ``` + */ +export class WavLMModel extends WavLMPreTrainedModel { } + +/** + * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). + */ +export class WavLMForCTC extends WavLMPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +} + +/** + * WavLM Model with a sequence classification head on top (a linear layer over the pooled output). + */ +export class WavLMForSequenceClassification extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +} + +////////////////////////////////////////////////// +// SpeechT5 models +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class SpeechT5PreTrainedModel extends PreTrainedModel { }; + +/** + * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets. + */ +export class SpeechT5Model extends SpeechT5PreTrainedModel { }; + +/** + * SpeechT5 Model with a speech encoder and a text decoder. + * + * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`. + * ```javascript + * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@xenova/transformers'; + * + * // Load the tokenizer and processor + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts'); + * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts'); + * + * // Load the models + * // NOTE: We use the unquantized versions as they are more accurate + * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { quantized: false }); + * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { quantized: false }); + * + * // Load speaker embeddings from URL + * const speaker_embeddings_data = new Float32Array( + * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer() + * ); + * const speaker_embeddings = new Tensor( + * 'float32', + * speaker_embeddings_data, + * [1, speaker_embeddings_data.length] + * ) + * + * // Run tokenization + * const { input_ids } = tokenizer('Hello, my dog is cute'); + * + * // Generate waveform + * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder }); + * console.log(waveform) + * // Tensor { + * // dims: [ 26112 ], + * // type: 'float32', + * // size: 26112, + * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ], + * // } + * ``` + */ +export class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { } + +/** + * SpeechT5 Model with a text encoder and a speech decoder. + */ +export class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel { + + /** + * Creates a new instance of the `SpeechT5ForTextToSpeech` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, decoder_merged_session, generation_config) { + super(config, session); + this.decoder_merged_session = decoder_merged_session; + this.generation_config = generation_config; + + this.num_decoder_layers = this.config.decoder_layers; + this.num_decoder_heads = this.config.decoder_attention_heads; + this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads; + + this.num_encoder_layers = this.config.encoder_layers; + this.num_encoder_heads = this.config.encoder_attention_heads; + this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads; + } + + /** + * @typedef {Object} SpeechOutput + * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape + * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided + * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. + * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape + * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. + */ + + /** + * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. + * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. + * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. + * @param {Object} options Optional parameters for generating speech. + * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. + * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. + * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. + * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. + * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. + * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. + */ + async generate_speech(input_values, speaker_embeddings, { + threshold = 0.5, + minlenratio = 0.0, + maxlenratio = 20.0, + vocoder = null, + // output_cross_attentions = false, // TODO add + } = {}) { + + const model_inputs = { + input_ids: input_values + } + + const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs); + + const r = encoder_outputs.dims[1] / this.config.reduction_factor; + const maxlen = Math.floor(r * maxlenratio); + const minlen = Math.floor(r * minlenratio); + + const num_mel_bins = this.config.num_mel_bins; + + let spectrogramParts = []; + let past_key_values = null; + let decoder_outputs = null; + let idx = 0; + + while (true) { + ++idx; + + const use_cache_branch = boolTensor(!!decoder_outputs); + let output_sequence; + if (decoder_outputs) { + output_sequence = decoder_outputs.output_sequence_out; + } else { + output_sequence = new Tensor( + 'float32', + new Float32Array(num_mel_bins), + [1, 1, num_mel_bins], + ) + } + let decoderFeeds = { + use_cache_branch, + output_sequence, + encoder_attention_mask: encoder_attention_mask, + speaker_embeddings: speaker_embeddings, + encoder_hidden_states: encoder_outputs, + }; + + this.addPastKeyValues(decoderFeeds, past_key_values); + decoder_outputs = await sessionRun(this.decoder_merged_session, decoderFeeds); + past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values); + + const { prob, spectrum } = decoder_outputs; + spectrogramParts.push(spectrum); + + if (idx >= minlen && ( + // Finished when stop token or maximum length is reached. + Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen + )) { + break; + } + } + + const spectrogram = cat(spectrogramParts); + const { waveform } = await sessionRun(vocoder.session, { spectrogram }); + + return { + spectrogram, + waveform, + // cross_attentions: null, // TODO add + } + } +} + +/** + * HiFi-GAN vocoder. + * + * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage. + */ +export class SpeechT5HifiGan extends PreTrainedModel { + main_input_name = 'spectrogram'; +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// TrOCR models +export class TrOCRPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `TrOCRPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id; + + this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers; + this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads; + this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; + } +} + +/** + * The TrOCR Decoder with a language modeling head. + */ +export class TrOCRForCausalLM extends TrOCRPreTrainedModel { } + +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// Mistral models +/** + * The bare Mistral Model outputting raw hidden-states without any specific head on top. + */ +export class MistralPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `MistralPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_key_value_heads; + this.num_layers = this.config.num_hidden_layers; + this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; + } +} + +export class MistralModel extends MistralPreTrainedModel { } + +export class MistralForCausalLM extends MistralPreTrainedModel { } +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Falcon models +/** + * The bare Falcon Model outputting raw hidden-states without any specific head on top. + */ +export class FalconPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `FalconPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config, session, generation_config) { + super(config, session); + this.generation_config = generation_config; + + // config doesn't contain pad_token_id, so we assume it is the eos_token_id + this.config.pad_token_id = this.config.eos_token_id + + this.num_heads = this.config.num_attention_heads; + this.num_layers = this.config.num_hidden_layers; + this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; + } +} + +export class FalconModel extends FalconPreTrainedModel { } + +export class FalconForCausalLM extends FalconPreTrainedModel { } +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// CLAP models +export class ClapPreTrainedModel extends PreTrainedModel { } + +export class ClapModel extends ClapPreTrainedModel { } + +/** + * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output). + * + * **Example:** Compute text embeddings with `ClapTextModelWithProjection`. + * + * ```javascript + * import { AutoTokenizer, ClapTextModelWithProjection } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused'); + * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); + * + * // Run tokenization + * const texts = ['a sound of a cat', 'a sound of a dog']; + * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Compute embeddings + * const { text_embeds } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 512 ], + * // type: 'float32', + * // data: Float32Array(1024) [ ... ], + * // size: 1024 + * // } + * ``` + */ +export class ClapTextModelWithProjection extends ClapPreTrainedModel { + + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'text_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} + +/** + * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output). + * + * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`. + * + * ```javascript + * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@xenova/transformers'; + * + * // Load processor and audio model + * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused'); + * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); + * + * // Read audio and run processor + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'); + * const audio_inputs = await processor(audio); + * + * // Compute embeddings + * const { audio_embeds } = await audio_model(audio_inputs); + * // Tensor { + * // dims: [ 1, 512 ], + * // type: 'float32', + * // data: Float32Array(512) [ ... ], + * // size: 512 + * // } + * ``` + */ +export class ClapAudioModelWithProjection extends ClapPreTrainedModel { + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + // Update default model file name if not provided + options.model_file_name ??= 'audio_model'; + return super.from_pretrained(pretrained_model_name_or_path, options); + } +} +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// VITS models +export class VitsPreTrainedModel extends PreTrainedModel { } + +/** + * The complete VITS model, for text-to-speech synthesis. + * + * **Example:** Generate speech from text with `VitsModel`. + * ```javascript + * import { AutoTokenizer, VitsModel } from '@xenova/transformers'; + * + * // Load the tokenizer and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng'); + * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng'); + * + * // Run tokenization + * const inputs = tokenizer('I love transformers'); + * + * // Generate waveform + * const { waveform } = await model(inputs); + * // Tensor { + * // dims: [ 1, 35328 ], + * // type: 'float32', + * // data: Float32Array(35328) [ ... ], + * // size: 35328, + * // } + * ``` + */ +export class VitsModel extends VitsPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} The outputs for the VITS model. + */ + async _call(model_inputs) { + return new VitsModelOutput(await super._call(model_inputs)); + } +} +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +// Segformer models +export class SegformerPreTrainedModel extends PreTrainedModel { } + +/** + * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. + */ +export class SegformerModel extends SegformerPreTrainedModel { } + +/** + * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet. + */ +export class SegformerForImageClassification extends SegformerPreTrainedModel { } + +/** + * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes. + */ +export class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { } + +////////////////////////////////////////////////// + + +////////////////////////////////////////////////// +// AutoModels, used to simplify construction of PreTrainedModels +// (uses config to instantiate correct class) + +/** + * Base class of all AutoModels. Contains the `from_pretrained` function + * which is used to instantiate pretrained models. + */ +export class PretrainedMixin { + /** + * Mapping from model type to model class. + * @type {Map[]} + */ + static MODEL_CLASS_MAPPINGS = null; + + /** + * Whether to attempt to instantiate the base class (`PretrainedModel`) if + * the model type is not found in the mapping. + */ + static BASE_IF_FAIL = false; + + + /** @type {PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, { + quantized = true, + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + model_file_name = null, + } = {}) { + + let options = { + quantized, + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + } + config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options); + if (!options.config) { + // If no config was passed, reuse this config for future processing + options.config = config; + } + + if (!this.MODEL_CLASS_MAPPINGS) { + throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); + } + + for (let MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { + const modelInfo = MODEL_CLASS_MAPPING.get(config.model_type); + if (!modelInfo) { + continue; // Item not found in this mapping + } + return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options); + } + + if (this.BASE_IF_FAIL) { + console.warn(`Unknown model class "${config.model_type}", attempting to construct from base class.`); + return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); + } else { + throw Error(`Unsupported model type: ${config.model_type}`) + } + } +} + +const MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([ + ['bert', ['BertModel', BertModel]], + ['roformer', ['RoFormerModel', RoFormerModel]], + ['electra', ['ElectraModel', ElectraModel]], + ['esm', ['EsmModel', EsmModel]], + ['convbert', ['ConvBertModel', ConvBertModel]], + ['camembert', ['CamembertModel', CamembertModel]], + ['deberta', ['DebertaModel', DebertaModel]], + ['deberta-v2', ['DebertaV2Model', DebertaV2Model]], + ['mpnet', ['MPNetModel', MPNetModel]], + ['albert', ['AlbertModel', AlbertModel]], + ['distilbert', ['DistilBertModel', DistilBertModel]], + ['roberta', ['RobertaModel', RobertaModel]], + ['xlm', ['XLMModel', XLMModel]], + ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]], + ['clap', ['ClapModel', ClapModel]], + ['clip', ['CLIPModel', CLIPModel]], + ['clipseg', ['CLIPSegModel', CLIPSegModel]], + ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]], + ['siglip', ['SiglipModel', SiglipModel]], + ['mobilebert', ['MobileBertModel', MobileBertModel]], + ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]], + ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]], + ['hubert', ['HubertModel', HubertModel]], + ['wavlm', ['WavLMModel', WavLMModel]], + ['audio-spectrogram-transformer', ['ASTModel', ASTModel]], + ['vits', ['VitsModel', VitsModel]], + + ['detr', ['DetrModel', DetrModel]], + ['table-transformer', ['TableTransformerModel', TableTransformerModel]], + ['vit', ['ViTModel', ViTModel]], + ['mobilevit', ['MobileViTModel', MobileViTModel]], + ['owlvit', ['OwlViTModel', OwlViTModel]], + ['beit', ['BeitModel', BeitModel]], + ['deit', ['DeiTModel', DeiTModel]], + ['convnext', ['ConvNextModel', ConvNextModel]], + ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]], + ['dinov2', ['Dinov2Model', Dinov2Model]], + ['resnet', ['ResNetModel', ResNetModel]], + ['swin', ['SwinModel', SwinModel]], + ['swin2sr', ['Swin2SRModel', Swin2SRModel]], + ['donut-swin', ['DonutSwinModel', DonutSwinModel]], + ['yolos', ['YolosModel', YolosModel]], + ['dpt', ['DPTModel', DPTModel]], + ['glpn', ['GLPNModel', GLPNModel]], + + ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]], + +]); + +const MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([ + ['t5', ['T5Model', T5Model]], + ['longt5', ['LongT5Model', LongT5Model]], + ['mt5', ['MT5Model', MT5Model]], + ['bart', ['BartModel', BartModel]], + ['mbart', ['MBartModel', MBartModel]], + ['marian', ['MarianModel', MarianModel]], + ['whisper', ['WhisperModel', WhisperModel]], + ['m2m_100', ['M2M100Model', M2M100Model]], + ['blenderbot', ['BlenderbotModel', BlenderbotModel]], + ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]], +]); + + +const MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([ + ['bloom', ['BloomModel', BloomModel]], + ['gpt2', ['GPT2Model', GPT2Model]], + ['gptj', ['GPTJModel', GPTJModel]], + ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]], + ['gpt_neo', ['GPTNeoModel', GPTNeoModel]], + ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]], + ['codegen', ['CodeGenModel', CodeGenModel]], + ['llama', ['LlamaModel', LlamaModel]], + ['phi', ['PhiModel', PhiModel]], + ['mpt', ['MptModel', MptModel]], + ['opt', ['OPTModel', OPTModel]], + ['mistral', ['MistralModel', MistralModel]], + ['falcon', ['FalconModel', FalconModel]], +]); + +const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([ + ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]], + ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]], +]); + +const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([ + ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]], +]); + +const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([ + ['vits', ['VitsModel', VitsModel]], +]); + +const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([ + ['bert', ['BertForSequenceClassification', BertForSequenceClassification]], + ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]], + ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]], + ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]], + ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]], + ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]], + ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]], + ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]], + ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]], + ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]], + ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]], + ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]], + ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]], + ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]], + ['bart', ['BartForSequenceClassification', BartForSequenceClassification]], + ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]], + ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]], + ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]], +]); + +const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([ + ['bert', ['BertForTokenClassification', BertForTokenClassification]], + ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]], + ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]], + ['esm', ['EsmForTokenClassification', EsmForTokenClassification]], + ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]], + ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]], + ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]], + ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]], + ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]], + ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]], + ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]], + ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]], + ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]], +]); + +const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([ + ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]], + ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]], + ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]], + ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]], + ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]], + ['marian', ['MarianMTModel', MarianMTModel]], + ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]], + ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]], + ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]], +]); + +const MODEL_WITH_LM_HEAD_MAPPING_NAMES = new Map([ + ['bloom', ['BloomForCausalLM', BloomForCausalLM]], + ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]], + ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]], + ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]], + ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]], + ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]], + ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]], + ['llama', ['LlamaForCausalLM', LlamaForCausalLM]], + ['phi', ['PhiForCausalLM', PhiForCausalLM]], + ['mpt', ['MptForCausalLM', MptForCausalLM]], + ['opt', ['OPTForCausalLM', OPTForCausalLM]], + ['mbart', ['MBartForCausalLM', MBartForCausalLM]], + ['mistral', ['MistralForCausalLM', MistralForCausalLM]], + ['falcon', ['FalconForCausalLM', FalconForCausalLM]], + ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]], +]); + +const MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([ + ['bert', ['BertForMaskedLM', BertForMaskedLM]], + ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]], + ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]], + ['esm', ['EsmForMaskedLM', EsmForMaskedLM]], + ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]], + ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]], + ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]], + ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]], + ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]], + ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]], + ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]], + ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]], + ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]], + ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]], + ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]], + ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]], +]); + +const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([ + ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]], + ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]], + ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]], + ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]], + ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]], + ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]], + ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]], + ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]], + ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]], + ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]], + ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]], + ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]], + ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]], + ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]], + ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]], +]); + +const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([ + ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]], +]); + +const MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([ + ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]], +]); + +const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([ + ['vit', ['ViTForImageClassification', ViTForImageClassification]], + ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]], + ['beit', ['BeitForImageClassification', BeitForImageClassification]], + ['deit', ['DeiTForImageClassification', DeiTForImageClassification]], + ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]], + ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]], + ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]], + ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]], + ['swin', ['SwinForImageClassification', SwinForImageClassification]], + ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]], +]); + +const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([ + ['detr', ['DetrForObjectDetection', DetrForObjectDetection]], + ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]], + ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]], +]); + +const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([ + ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]], +]); + +const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([ + ['detr', ['DetrForSegmentation', DetrForSegmentation]], + ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]], +]); + +const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([ + ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]], +]); + +const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([ + ['sam', ['SamModel', SamModel]], +]); + +const MODEL_FOR_CTC_MAPPING_NAMES = new Map([ + ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]], + ['wavlm', ['WavLMForCTC', WavLMForCTC]], + ['hubert', ['HubertForCTC', HubertForCTC]], +]); + +const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([ + ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]], + ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]], + ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]], + ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]], +]); + +const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([ + ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]], +]); + +const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([ + ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]], +]) + +const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([ + ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]], + ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]], +]) + + +const MODEL_CLASS_TYPE_MAPPING = [ + [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], + [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], + [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly], + [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], + [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], + [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration], + [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], +]; + +for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { + // @ts-ignore + for (const [name, model] of mappings.values()) { + MODEL_TYPE_MAPPING.set(name, type); + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); + } +} + +const CUSTOM_MAPPING = [ + ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection, MODEL_TYPES.EncoderOnly], + ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly], + ['SiglipVisionModel', SiglipVisionModel, MODEL_TYPES.EncoderOnly], + ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly], +] +for (const [name, model, type] of CUSTOM_MAPPING) { + MODEL_TYPE_MAPPING.set(name, type); + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); +} + + +/** + * Helper class which is used to instantiate pretrained models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModel.from_pretrained('bert-base-uncased'); + */ +export class AutoModel extends PretrainedMixin { + /** @type {Map[]} */ + // @ts-ignore + static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]); + static BASE_IF_FAIL = true; +} + +/** + * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased-finetuned-sst-2-english'); + */ +export class AutoModelForSequenceClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTokenClassification.from_pretrained('Davlan/distilbert-base-multilingual-cased-ner-hrl'); + */ +export class AutoModelForTokenClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSeq2SeqLM.from_pretrained('t5-small'); + */ +export class AutoModelForSeq2SeqLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en'); + */ +export class AutoModelForSpeechSeq2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts'); + */ +export class AutoModelForTextToSpectrogram extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng'); + */ +export class AutoModelForTextToWaveform extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForCausalLM.from_pretrained('gpt2'); + */ +export class AutoModelForCausalLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_WITH_LM_HEAD_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForMaskedLM.from_pretrained('bert-base-uncased'); + */ +export class AutoModelForMaskedLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForQuestionAnswering.from_pretrained('distilbert-base-cased-distilled-squad'); + */ +export class AutoModelForQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForVision2Seq.from_pretrained('nlpconnect/vit-gpt2-image-captioning'); + */ +export class AutoModelForVision2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForImageClassification.from_pretrained('google/vit-base-patch16-224'); + */ +export class AutoModelForImageClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForImageSegmentation.from_pretrained('facebook/detr-resnet-50-panoptic'); + */ +export class AutoModelForImageSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024'); + */ +export class AutoModelForSemanticSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; +} + +/** + * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForObjectDetection.from_pretrained('facebook/detr-resnet-50'); + */ +export class AutoModelForObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; +} + +export class AutoModelForZeroShotObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; +} + + +/** + * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base'); + */ +export class AutoModelForMaskGeneration extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]; +} + +export class AutoModelForCTC extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES]; +} + +export class AutoModelForAudioClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; +} + +export class AutoModelForDocumentQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; +} + +export class AutoModelForImageMatting extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]; +} + +export class AutoModelForImageToImage extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; +} + +export class AutoModelForDepthEstimation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; +} + +////////////////////////////////////////////////// + +////////////////////////////////////////////////// +export class Seq2SeqLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. + * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. + * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + */ + constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + this.encoder_outputs = encoder_outputs; + this.decoder_attentions = decoder_attentions; + this.cross_attentions = cross_attentions; + } +} + +/** + * Base class for outputs of sentence classification models. + */ +export class SequenceClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +} + +/** + * Base class for outputs of token classification models. + */ +export class TokenClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification scores (before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +} + +/** + * Base class for masked language models outputs. + */ +export class MaskedLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +} + +/** + * Base class for outputs of question answering models. + */ +export class QuestionAnsweringModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.start_logits Span-start scores (before SoftMax). + * @param {Tensor} output.end_logits Span-end scores (before SoftMax). + */ + constructor({ start_logits, end_logits }) { + super(); + this.start_logits = start_logits; + this.end_logits = end_logits; + } +} + + +/** + * Base class for causal language model (or autoregressive) outputs. + */ +export class CausalLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +} + +/** + * Base class for causal language model (or autoregressive) outputs. + */ +export class CausalLMOutputWithPast extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) + * that can be used (see `past_key_values` input) to speed up sequential decoding. + */ + constructor({ logits, past_key_values }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + } +} + +export class ImageMattingOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. + */ + constructor({ alphas }) { + super(); + this.alphas = alphas; + } +} + +/** + * Describes the outputs for the VITS model. + */ +export class VitsModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. + * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. + * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. + */ + constructor({ waveform, spectrogram }) { + super(); + this.waveform = waveform; + this.spectrogram = spectrogram; + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/pipelines.js b/core/vendor/node_modules/@xenova/transformers/src/pipelines.js new file mode 100644 index 000000000..0c388e282 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/pipelines.js @@ -0,0 +1,3124 @@ +/** + * @file Pipelines provide a high-level, easy to use, API for running machine learning models. + * + * **Example:** Instantiate pipeline using the `pipeline` function. + * ```javascript + * import { pipeline } from '@xenova/transformers'; + * + * const classifier = await pipeline('sentiment-analysis'); + * const output = await classifier('I love transformers!'); + * // [{'label': 'POSITIVE', 'score': 0.999817686}] + * ``` + * + * @module pipelines + */ + +import { + AutoModel, + AutoModelForAudioClassification, + AutoModelForCTC, + AutoModelForCausalLM, + AutoModelForDepthEstimation, + AutoModelForDocumentQuestionAnswering, + AutoModelForImageClassification, + AutoModelForImageSegmentation, + AutoModelForImageToImage, + AutoModelForMaskedLM, + AutoModelForObjectDetection, + AutoModelForQuestionAnswering, + AutoModelForSemanticSegmentation, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForSpeechSeq2Seq, + AutoModelForTextToSpectrogram, + AutoModelForTextToWaveform, + AutoModelForTokenClassification, + AutoModelForVision2Seq, + AutoModelForZeroShotObjectDetection, + PreTrainedModel, +} from './models.js'; +import { + AutoProcessor, + Processor +} from './processors.js'; +import { + AutoTokenizer, + PreTrainedTokenizer, +} from './tokenizers.js'; + + +import { + read_audio +} from './utils/audio.js'; +import { + Callable, + dispatchCallback, + pop, + product, +} from './utils/core.js'; +import { + getTopItems, + max, + round, + softmax, +} from './utils/maths.js'; +import { + Tensor, + interpolate, + mean_pooling, +} from './utils/tensor.js'; +// import { RawImage } from './utils/image.js'; + + +/** + * @typedef {string | RawImage | URL} ImageInput + * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs + */ + +/** + * Prepare images for further tasks. + * @param {ImagePipelineInputs} images images to prepare. + * @returns {Promise} returns processed images. + * @private + */ +async function prepareImages(images) { + if (!Array.isArray(images)) { + images = [images]; + } + + // Possibly convert any non-images to images + // return await Promise.all(images.map(x => RawImage.read(x))); + return Promise.resolve([]); +} + +/** + * @typedef {string | URL | Float32Array | Float64Array} AudioInput + * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs + */ + +/** + * Prepare audios for further tasks. + * @param {AudioPipelineInputs} audios audios to prepare. + * @param {number} sampling_rate sampling rate of the audios. + * @returns {Promise} The preprocessed audio data. + * @private + */ +async function prepareAudios(audios, sampling_rate) { + if (!Array.isArray(audios)) { + audios = [audios]; + } + + return await Promise.all(audios.map(x => { + if (typeof x === 'string' || x instanceof URL) { + return read_audio(x, sampling_rate); + } else if (x instanceof Float64Array) { + return new Float32Array(x); + } + return x; + })); +} + +/** + * @typedef {Object} BoundingBox + * @property {number} xmin The minimum x coordinate of the bounding box. + * @property {number} ymin The minimum y coordinate of the bounding box. + * @property {number} xmax The maximum x coordinate of the bounding box. + * @property {number} ymax The maximum y coordinate of the bounding box. + */ + +/** + * Helper function to convert list [xmin, xmax, ymin, ymax] into object { "xmin": xmin, ... } + * @param {number[]} box The bounding box as a list. + * @param {boolean} asInteger Whether to cast to integers. + * @returns {BoundingBox} The bounding box as an object. + * @private + */ +function get_bounding_box(box, asInteger) { + if (asInteger) { + box = box.map(x => x | 0); + } + const [xmin, ymin, xmax, ymax] = box; + + return { xmin, ymin, xmax, ymax }; +} + + +/** + * @callback DisposeType Disposes the item. + * @returns {Promise} A promise that resolves when the item has been disposed. + * + * @typedef {Object} Disposable + * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed. + */ + +/** + * The Pipeline class is the class from which all pipelines inherit. + * Refer to this class for methods shared across different pipelines. + * @extends Callable + */ +export class Pipeline extends Callable { + /** + * Create a new Pipeline. + * @param {Object} options An object containing the following properties: + * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. + * @param {PreTrainedModel} [options.model] The model used by the pipeline. + * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). + * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). + */ + constructor({ task, model, tokenizer = null, processor = null }) { + super(); + this.task = task; + this.model = model; + this.tokenizer = tokenizer; + this.processor = processor; + } + + /** @type {DisposeType} */ + async dispose() { + await this.model.dispose(); + } +} + +/** + * @typedef {Object} ModelTokenizerConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. + * + * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline. + */ + +/** + * @typedef {Object} ModelProcessorConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {Processor} processor The processor used by the pipeline. + * + * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline. + * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline. + */ + + +/** + * @typedef {Object} ModelTokenizerProcessorConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. + * @property {Processor} processor The processor used by the pipeline. + * + * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline. + * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline. + */ + +/** + * @typedef {Object} TextClassificationSingle + * @property {string} label The label predicted. + * @property {number} score The corresponding probability. + * @typedef {TextClassificationSingle[]} TextClassificationOutput + * + * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines. + * @property {number} [topk=1] The number of top predictions to be returned. + * + * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs. + * @param {string|string[]} texts The input text(s) to be classified. + * @param {TextClassificationPipelineOptions} [options] The options to use for text classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType + */ + +/** + * Text classification pipeline using any `ModelForSequenceClassification`. + * + * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`. + * ```javascript + * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english'); + * const output = await classifier('I love transformers!'); + * // [{ label: 'POSITIVE', score: 0.999788761138916 }] + * ``` + * + * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes). + * ```javascript + * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment'); + * const output = await classifier('Le meilleur film de tous les temps.', { topk: 5 }); + * // [ + * // { label: '5 stars', score: 0.9610759615898132 }, + * // { label: '4 stars', score: 0.03323351591825485 }, + * // { label: '3 stars', score: 0.0036155181005597115 }, + * // { label: '1 star', score: 0.0011325967498123646 }, + * // { label: '2 stars', score: 0.0009423971059732139 } + * // ] + * ``` + * + * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes). + * ```javascript + * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert'); + * const output = await classifier('I hate you!', { topk: null }); + * // [ + * // { label: 'toxic', score: 0.9593140482902527 }, + * // { label: 'insult', score: 0.16187334060668945 }, + * // { label: 'obscene', score: 0.03452680632472038 }, + * // { label: 'identity_hate', score: 0.0223250575363636 }, + * // { label: 'threat', score: 0.019197041168808937 }, + * // { label: 'severe_toxic', score: 0.005651099607348442 } + * // ] + * ``` + */ +export class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) { + + /** + * Create a new TextClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {TextClassificationPipelineCallback} */ + async _call(texts, { + topk = 1 + } = {}) { + + // Run tokenization + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true, + }); + + // Run model + const outputs = await this.model(model_inputs) + + // TODO: Use softmax tensor function + const function_to_apply = + this.model.config.problem_type === 'multi_label_classification' + ? batch => batch.sigmoid().data + : batch => softmax(batch.data); // single_label_classification (default) + + const id2label = this.model.config.id2label; + + const toReturn = []; + for (const batch of outputs.logits) { + const output = function_to_apply(batch); + const scores = getTopItems(output, topk); + + const vals = scores.map(x => ({ + label: id2label[x[0]], + score: x[1], + })); + if (topk === 1) { + toReturn.push(...vals); + } else { + toReturn.push(vals); + } + } + + return Array.isArray(texts) || topk === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0]; + } +} + +/** + * @typedef {Object} TokenClassificationSingle + * @property {string} word The token/word classified. This is obtained by decoding the selected tokens. + * @property {number} score The corresponding probability for `entity`. + * @property {string} entity The entity predicted for that token/word. + * @property {number} index The index of the corresponding token in the sentence. + * @property {number} [start] The index of the start of the corresponding entity in the sentence. + * @property {number} [end] The index of the end of the corresponding entity in the sentence. + * @typedef {TokenClassificationSingle[]} TokenClassificationOutput + * + * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines. + * @property {string[]} [ignore_labels] A list of labels to ignore. + * + * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs. + * @param {string|string[]} texts One or several texts (or one list of texts) for token classification. + * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification. + * @returns {Promise} The result. + * + * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType + */ + +/** + * Named Entity Recognition pipeline using any `ModelForTokenClassification`. + * + * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`. + * ```javascript + * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); + * const output = await classifier('My name is Sarah and I live in London'); + * // [ + * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' }, + * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' } + * // ] + * ``` + * + * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels). + * ```javascript + * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); + * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] }); + * // [ + * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' }, + * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' }, + * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' }, + * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' }, + * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' }, + * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' }, + * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' }, + * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' } + * // ] + * ``` + */ +export class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) { + + /** + * Create a new TokenClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {TokenClassificationPipelineCallback} */ + async _call(texts, { + ignore_labels = ['O'], + } = {}) { + + const isBatched = Array.isArray(texts); + + // Run tokenization + const model_inputs = this.tokenizer(isBatched ? texts : [texts], { + padding: true, + truncation: true, + }); + + // Run model + const outputs = await this.model(model_inputs) + + const logits = outputs.logits; + const id2label = this.model.config.id2label; + + const toReturn = []; + for (let i = 0; i < logits.dims[0]; ++i) { + const ids = model_inputs.input_ids[i]; + const batch = logits[i]; + + // List of tokens that aren't ignored + const tokens = []; + for (let j = 0; j < batch.dims[0]; ++j) { + const tokenData = batch[j]; + const topScoreIndex = max(tokenData.data)[1]; + + const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; + if (ignore_labels.includes(entity)) { + // We predicted a token that should be ignored. So, we skip it. + continue; + } + + // TODO add option to keep special tokens? + const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true }); + if (word === '') { + // Was a special token. So, we skip it. + continue; + } + + const scores = softmax(tokenData.data); + + tokens.push({ + entity: entity, + score: scores[topScoreIndex], + index: j, + word: word, + + // TODO: null for now, but will add + start: null, + end: null, + }); + } + toReturn.push(tokens); + } + return isBatched ? toReturn : toReturn[0]; + } +} + +/** + * @typedef {Object} QuestionAnsweringOutput + * @property {number} score The probability associated to the answer. + * @property {number} [start] The character start index of the answer (in the tokenized version of the input). + * @property {number} [end] The character end index of the answer (in the tokenized version of the input). + * @property {string} answer The answer to the question. + * + * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines. + * @property {number} [topk=1] The number of top answer predictions to be returned. + * + * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s). + * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument). + * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument). + * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering. + * @returns {Promise} An array or object containing the predicted answers and scores. + * + * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType + */ + +/** + * Question Answering pipeline using any `ModelForQuestionAnswering`. + * + * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`. + * ```javascript + * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad'); + * const question = 'Who was Jim Henson?'; + * const context = 'Jim Henson was a nice puppet.'; + * const output = await answerer(question, context); + * // { + * // answer: "a nice puppet", + * // score: 0.5768911502526741 + * // } + * ``` + */ +export class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) { + + /** + * Create a new QuestionAnsweringPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {QuestionAnsweringPipelineCallback} */ + async _call(question, context, { + topk = 1 + } = {}) { + + // Run tokenization + const inputs = this.tokenizer(question, { + text_pair: context, + padding: true, + truncation: true, + }); + + const output = await this.model(inputs); + + /** @type {QuestionAnsweringOutput[]} */ + const toReturn = []; + for (let j = 0; j < output.start_logits.dims[0]; ++j) { + const ids = inputs.input_ids[j]; + const sepIndex = ids.indexOf(this.tokenizer.sep_token_id); + + const s1 = Array.from(softmax(output.start_logits[j].data)) + .map((x, i) => [x, i]) + .filter(x => x[1] > sepIndex); + const e1 = Array.from(softmax(output.end_logits[j].data)) + .map((x, i) => [x, i]) + .filter(x => x[1] > sepIndex); + + const options = product(s1, e1) + .filter(x => x[0][1] <= x[1][1]) + .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]]) + .sort((a, b) => b[2] - a[2]); + + for (let k = 0; k < Math.min(options.length, topk); ++k) { + const [start, end, score] = options[k]; + + const answer_tokens = [...ids].slice(start, end + 1) + + const answer = this.tokenizer.decode(answer_tokens, { + skip_special_tokens: true, + }); + + // TODO add start and end? + // NOTE: HF returns character index + toReturn.push({ + answer, score + }); + } + } + + // Mimic HF's return type based on topk + return (topk === 1) ? toReturn[0] : toReturn; + } +} + + +/** + * @typedef {Object} FillMaskSingle + * @property {string} sequence The corresponding input with the mask token prediction. + * @property {number} score The corresponding probability. + * @property {number} token The predicted token id (to replace the masked one). + * @property {string} token_str The predicted token (to replace the masked one). + * @typedef {FillMaskSingle[]} FillMaskOutput + * + * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines. + * @property {number} [topk=5] When passed, overrides the number of predictions to return. + * + * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs. + * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens. + * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling. + * @returns {Promise} An array of objects containing the score, predicted token, predicted token string, + * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text). + * If only one input text is given, the output will be an array of objects. + * @throws {Error} When the mask token is not found in the input text. + * + * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType + */ + +/** + * Masked language modeling prediction pipeline using any `ModelWithLMHead`. + * + * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`. + * ```javascript + * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); + * const output = await unmasker('The goal of life is [MASK].'); + * // [ + * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' }, + * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' }, + * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' }, + * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' }, + * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' } + * // ] + * ``` + * + * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result). + * ```javascript + * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); + * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { topk: 1 }); + * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }] + * ``` + */ +export class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) { + + /** + * Create a new FillMaskPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {FillMaskPipelineCallback} */ + async _call(texts, { + topk = 5 + } = {}) { + + // Run tokenization + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true, + }); + + // Run model + const outputs = await this.model(model_inputs) + + const toReturn = []; + + for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) { + const ids = model_inputs.input_ids[i]; + const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id) + + if (mask_token_index === -1) { + throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`) + } + const logits = outputs.logits[i]; + const itemLogits = logits[mask_token_index]; + + const scores = getTopItems(softmax(itemLogits.data), topk); + + toReturn.push(scores.map(x => { + const sequence = [...ids]; + sequence[mask_token_index] = x[0]; + + return { + score: x[1], + token: x[0], + token_str: this.tokenizer.model.vocab[x[0]], + sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }), + } + })); + } + return Array.isArray(texts) ? toReturn : toReturn[0]; + } +} + + +/** + * @typedef {Object} Text2TextGenerationSingle + * @property {string} generated_text The generated text. + * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput + * + * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs. + * @param {string|string[]} texts Input text for the encoder. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType + */ + +/** + * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks. + * + * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`. + * ```javascript + * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M'); + * const output = await generator('how can I become more healthy?', { + * max_new_tokens: 100, + * }); + * // [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }] + * ``` + */ +export class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) { + /** @type {'generated_text'} */ + _key = 'generated_text'; + + /** + * Create a new Text2TextGenerationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {Text2TextGenerationPipelineCallback} */ + async _call(texts, generate_kwargs = {}) { + if (!Array.isArray(texts)) { + texts = [texts]; + } + + + // Add global prefix, if present + if (this.model.config.prefix) { + texts = texts.map(x => this.model.config.prefix + x) + } + + // Handle task specific params: + const task_specific_params = this.model.config.task_specific_params + if (task_specific_params && task_specific_params[this.task]) { + // Add prefixes, if present + if (task_specific_params[this.task].prefix) { + texts = texts.map(x => task_specific_params[this.task].prefix + x) + } + + // TODO update generation config + } + + const tokenizer = this.tokenizer; + const tokenizer_options = { + padding: true, + truncation: true, + } + let input_ids; + if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) { + // TODO: move to Translation pipeline? + // Currently put here to avoid code duplication + // @ts-ignore + input_ids = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs).input_ids; + + } else { + input_ids = tokenizer(texts, tokenizer_options).input_ids; + } + + const outputTokenIds = await this.model.generate(input_ids, generate_kwargs); + + return tokenizer.batch_decode(outputTokenIds, { + skip_special_tokens: true, + }).map(text => ({ [this._key]: text })); + } +} + + +/** + * @typedef {Object} SummarizationSingle + * @property {string} summary_text The summary text. + * @typedef {SummarizationSingle[]} SummarizationOutput + * + * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs. + * @param {string|string[]} texts One or several articles (or one list of articles) to summarize. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType + */ + +/** + * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline. + * + * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`. + * ```javascript + * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6'); + * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' + + * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' + + * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' + + * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' + + * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' + + * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' + + * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' + + * 'tallest free-standing structure in France after the Millau Viaduct.'; + * const output = await generator(text, { + * max_new_tokens: 100, + * }); + * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }] + * ``` + */ +export class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) { + /** @type {'summary_text'} */ + _key = 'summary_text'; + + /** + * Create a new SummarizationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } +} + + +/** + * @typedef {Object} TranslationSingle + * @property {string} translation_text The translated text. + * @typedef {TranslationSingle[]} TranslationOutput + * + * @callback TranslationPipelineCallback Translate the text(s) given as inputs. + * @param {string|string[]} texts Texts to be translated. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType + */ + +/** + * Translates text from one language to another. + * + * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`. + * + * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M'); + * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', { + * src_lang: 'hin_Deva', // Hindi + * tgt_lang: 'fra_Latn', // French + * }); + * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }] + * ``` + * + * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`. + * + * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/m2m100_418M'); + * const output = await translator('生活就像一盒巧克力。', { + * src_lang: 'zh', // Chinese + * tgt_lang: 'en', // English + * }); + * // [{ translation_text: 'Life is like a box of chocolate.' }] + * ``` + * + * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`. + * + * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt'); + * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', { + * src_lang: 'hi_IN', // Hindi + * tgt_lang: 'fr_XX', // French + * }); + * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }] + * ``` + */ +export class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) { + /** @type {'translation_text'} */ + _key = 'translation_text'; + + /** + * Create a new TranslationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } +} + + +/** + * @typedef {Object} TextGenerationSingle + * @property {string} generated_text The generated text. + * @typedef {TextGenerationSingle[]} TextGenerationOutput + * + * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines. + * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences. + * @typedef {import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams} TextGenerationConfig + * + * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs. + * @param {string|string[]} texts One or several prompts (or one list of prompts) to complete. + * @param {TextGenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An array or object containing the generated texts. + * + * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType + */ + +/** + * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. + * This pipeline predicts the words that will follow a specified text prompt. + * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig). + * + * **Example:** Text generation with `Xenova/distilgpt2` (default settings). + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); + * const text = 'I enjoy walking with my cute dog,'; + * const output = await generator(text); + * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }] + * ``` + * + * **Example:** Text generation with `Xenova/distilgpt2` (custom settings). + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); + * const text = 'Once upon a time, there was'; + * const output = await generator(text, { + * temperature: 2, + * max_new_tokens: 10, + * repetition_penalty: 1.5, + * no_repeat_ngram_size: 2, + * num_beams: 2, + * num_return_sequences: 2, + * }); + * // [{ + * // "generated_text": "Once upon a time, there was an abundance of information about the history and activities that" + * // }, { + * // "generated_text": "Once upon a time, there was an abundance of information about the most important and influential" + * // }] + * ``` + * + * **Example:** Run code generation with `Xenova/codegen-350M-mono`. + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono'); + * const text = 'def fib(n):'; + * const output = await generator(text, { + * max_new_tokens: 44, + * }); + * // [{ + * // generated_text: 'def fib(n):\n' + + * // ' if n == 0:\n' + + * // ' return 0\n' + + * // ' elif n == 1:\n' + + * // ' return 1\n' + + * // ' else:\n' + + * // ' return fib(n-1) + fib(n-2)\n' + * // }] + * ``` + */ +export class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) { + + /** + * Create a new TextGenerationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {TextGenerationPipelineCallback} */ + async _call(texts, generate_kwargs = {}) { + + const isBatched = Array.isArray(texts); + if (!isBatched) { + texts = [/** @type {string}*/ (texts)]; + } + + // By default, do not add special tokens + const add_special_tokens = generate_kwargs.add_special_tokens ?? false; + + this.tokenizer.padding_side = 'left'; + const { input_ids, attention_mask } = this.tokenizer(texts, { + add_special_tokens, + padding: true, + truncation: true, + }); + + const outputTokenIds = await this.model.generate(input_ids, generate_kwargs, null, { + inputs_attention_mask: attention_mask + }); + + const decoded = this.tokenizer.batch_decode(outputTokenIds, { + skip_special_tokens: true, + }); + + /** @type {TextGenerationOutput[]} */ + const toReturn = Array.from({ length: texts.length }, _ => []); + for (let i = 0; i < decoded.length; ++i) { + const textIndex = Math.floor(i / outputTokenIds.length * texts.length); + + toReturn[textIndex].push({ + generated_text: decoded[i] + }); + } + return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn; + } +} + +/** + * @typedef {Object} ZeroShotClassificationOutput + * @property {string} sequence The sequence for which this is the output. + * @property {string[]} labels The labels sorted by order of likelihood. + * @property {number[]} scores The probabilities for each of the labels. + * + * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines. + * @property {string} [hypothesis_template="This example is {}."] The template used to turn each + * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder. + * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true. + * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence + * is 1. If `true`, the labels are considered independent and probabilities are normalized for each + * candidate by doing a softmax of the entailment score vs. the contradiction score. + * + * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large. + * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into. + * Can be a single label, a string of comma-separated labels, or a list of labels. + * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType + */ + +/** + * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` + * trained on NLI (natural language inference) tasks. Equivalent of `text-classification` + * pipelines, but these models don't require a hardcoded number of potential classes, they + * can be chosen at runtime. It usually means it's slower but it is **much** more flexible. + * + * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`. + * ```javascript + * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli'); + * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.'; + * const labels = [ 'mobile', 'billing', 'website', 'account access' ]; + * const output = await classifier(text, labels); + * // { + * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.', + * // labels: [ 'mobile', 'website', 'billing', 'account access' ], + * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ] + * // } + * ``` + * + * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label). + * ```javascript + * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall'); + * const text = 'I have a problem with my iphone that needs to be resolved asap!'; + * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ]; + * const output = await classifier(text, labels, { multi_label: true }); + * // { + * // sequence: 'I have a problem with my iphone that needs to be resolved asap!', + * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ], + * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ] + * // } + * ``` + */ +export class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) { + /** + * Create a new ZeroShotClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + + // Use model config to get label2id mapping + this.label2id = Object.fromEntries( + Object.entries((/** @type {any} */(this).model).config.label2id).map( + ([k, v]) => [k.toLowerCase(), v] + ) + ); + + this.entailment_id = this.label2id['entailment']; + if (this.entailment_id === undefined) { + 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']; + if (this.contradiction_id === undefined) { + console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); + this.contradiction_id = 0; + } + } + + /** @type {ZeroShotClassificationPipelineCallback} */ + async _call(texts, candidate_labels, { + hypothesis_template = "This example is {}.", + multi_label = false, + } = {}) { + + const isBatched = Array.isArray(texts); + if (!isBatched) { + texts = [/** @type {string} */ (texts)]; + } + if (!Array.isArray(candidate_labels)) { + candidate_labels = [candidate_labels]; + } + + // Insert labels into hypothesis template + const hypotheses = candidate_labels.map( + x => hypothesis_template.replace('{}', x) + ); + + // How to perform the softmax over the logits: + // - true: softmax over the entailment vs. contradiction dim for each label independently + // - false: softmax the "entailment" logits over all candidate labels + const softmaxEach = multi_label || candidate_labels.length === 1; + + /** @type {ZeroShotClassificationOutput[]} */ + const toReturn = []; + for (const premise of texts) { + const entails_logits = []; + + for (const hypothesis of hypotheses) { + const inputs = this.tokenizer(premise, { + text_pair: hypothesis, + padding: true, + truncation: true, + }) + const outputs = await this.model(inputs) + + if (softmaxEach) { + entails_logits.push([ + outputs.logits.data[this.contradiction_id], + outputs.logits.data[this.entailment_id] + ]) + } else { + entails_logits.push(outputs.logits.data[this.entailment_id]) + } + } + + /** @type {number[]} */ + const scores = softmaxEach + ? entails_logits.map(x => softmax(x)[1]) + : softmax(entails_logits); + + // Sort by scores (desc) and return scores with indices + const scores_sorted = scores + .map((x, i) => [x, i]) + .sort((a, b) => (b[0] - a[0])); + + toReturn.push({ + sequence: premise, + labels: scores_sorted.map(x => candidate_labels[x[1]]), + scores: scores_sorted.map(x => x[0]), + }); + } + return isBatched ? toReturn : toReturn[0]; + } +} + +/** + * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines. + * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use. + * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension. + * + * @callback FeatureExtractionPipelineCallback Extract the features of the input(s). + * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of. + * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction. + * @returns {Promise} The features computed by the model. + * + * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType + */ + +/** + * Feature extraction pipeline using no model head. This pipeline extracts the hidden + * states from the base transformer, which can be used as features in downstream tasks. + * + * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization). + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); + * const output = await extractor('This is a simple test.'); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...], + * // dims: [1, 8, 768] + * // } + * ``` + * + * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization). + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); + * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...], + * // dims: [1, 768] + * // } + * ``` + * + * **Example:** Calculating embeddings with `sentence-transformers` models. + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2'); + * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...], + * // dims: [1, 384] + * // } + * ``` + */ +export class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) { + /** + * Create a new FeatureExtractionPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {FeatureExtractionPipelineCallback} */ + async _call(texts, { + pooling = /** @type {'none'} */('none'), + normalize = false, + } = {}) { + + // Run tokenization + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true, + }); + + // Run model + const outputs = await this.model(model_inputs) + + // TODO: Provide warning to the user that they might be using model which was not exported + // specifically for feature extraction + // console.log(this.model.config) + // console.log(outputs) + + /** @type {Tensor} */ + let result = outputs.last_hidden_state ?? outputs.logits; + if (pooling === 'none') { + // Skip pooling + } else if (pooling === 'mean') { + result = mean_pooling(result, model_inputs.attention_mask); + } else if (pooling === 'cls') { + result = result.slice(null, 0); + } else { + throw Error(`Pooling method '${pooling}' not supported.`); + } + + if (normalize) { + result = result.normalize(2, -1); + } + + return result; + } +} + +// TODO +// export class SentenceSimilarityPipeline extends Pipeline { +// } + +/** + * @typedef {Object} AudioClassificationSingle + * @property {string} label The label predicted. + * @property {number} score The corresponding probability. + * @typedef {AudioClassificationSingle[]} AudioClassificationOutput + * + * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines. + * @property {number} [topk=null] The number of top labels that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of labels available in the model configuration, + * it will default to the number of labels. + * + * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType + */ + +/** + * Audio classification pipeline using any `AutoModelForAudioClassification`. + * This pipeline predicts the class of a raw waveform or an audio file. + * + * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`. + * ```javascript + * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await classifier(url); + * // [ + * // { label: 'male', score: 0.9981542229652405 }, + * // { label: 'female', score: 0.001845747814513743 } + * // ] + * ``` + * + * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results. + * ```javascript + * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'; + * const output = await classifier(url, { topk: 4 }); + * // [ + * // { label: 'Meow', score: 0.5617874264717102 }, + * // { label: 'Cat', score: 0.22365376353263855 }, + * // { label: 'Domestic animals, pets', score: 0.1141069084405899 }, + * // { label: 'Animal', score: 0.08985692262649536 }, + * // ] + * ``` + */ +export class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) { + + /** + * Create a new AudioClassificationPipeline. + * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {AudioClassificationPipelineCallback} */ + async _call(audio, { + topk = null + } = {}) { + + const single = !Array.isArray(audio); + + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + + const id2label = this.model.config.id2label; + + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + + const scores = getTopItems(softmax(logits.data), topk); + + const vals = scores.map(x => ({ + label: /** @type {string} */ (id2label[x[0]]), + score: /** @type {number} */ (x[1]), + })); + + if (topk === 1) { + toReturn.push(...vals); + } else { + toReturn.push(vals); + } + } + return !single || topk === 1 ? /** @type {AudioClassificationOutput} */ (toReturn) : /** @type {AudioClassificationOutput[]} */ (toReturn)[0]; + } +} + +/** + * @typedef {Object} ZeroShotAudioClassificationOutput + * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. + * @property {number} score The score attributed by the model for that label (between 0 and 1). + * + * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines. + * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels` + * to attempt the audio classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_audio`. + * + * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {string[]} candidate_labels The candidate labels for this audio. + * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification. + * @returns {Promise} An array of objects containing the predicted labels and scores. + * + * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType + */ + +/** + * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you + * provide an audio and a set of `candidate_labels`. + * + * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`. + * ```javascript + * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused'); + * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav'; + * const candidate_labels = ['dog', 'vaccum cleaner']; + * const scores = await classifier(audio, candidate_labels); + * // [ + * // { score: 0.9993992447853088, label: 'dog' }, + * // { score: 0.0006007603369653225, label: 'vaccum cleaner' } + * // ] + * ``` + */ +export class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) { + + /** + * Create a new ZeroShotAudioClassificationPipeline. + * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ZeroShotAudioClassificationPipelineCallback} */ + async _call(audio, candidate_labels, { + hypothesis_template = "This is a sound of {}." + } = {}) { + + const single = !Array.isArray(audio); + if (single) { + audio = [/** @type {AudioInput} */ (audio)]; + } + + // Insert label into hypothesis template + const texts = candidate_labels.map( + x => hypothesis_template.replace('{}', x) + ); + + // Run tokenization + const text_inputs = this.tokenizer(texts, { + padding: true, + truncation: true, + }); + + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + + const toReturn = []; + for (const aud of preparedAudios) { + const audio_inputs = await this.processor(aud); + + // Run model with both text and audio inputs + const output = await this.model({ ...text_inputs, ...audio_inputs }); + + // Compute softmax per audio + const probs = softmax(output.logits_per_audio.data); + + toReturn.push([...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + }))); + } + return single ? toReturn[0] : toReturn; + } +} + +/** + * @typedef {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: number[], token_timestamps?: number[]}} ChunkCallbackItem + * @callback ChunkCallback + * @param {ChunkCallbackItem} chunk The chunk to process. + */ + +/** + * @typedef {Object} Chunk + * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds. + * @property {string} text The recognized text. + */ + +/** + * @typedef {Object} AutomaticSpeechRecognitionOutput + * @property {string} text The recognized text. + * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list + * containing all the various text chunks identified by the model. + * + * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines. + * @property {boolean|'word'} [kwargs.return_timestamps] Whether to return timestamps or not. Default is `false`. + * @property {number} [kwargs.chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking). + * @property {number} [kwargs.stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`. + * @property {ChunkCallback} [kwargs.chunk_callback] Callback function to be called with each chunk processed. + * @property {boolean} [kwargs.force_full_sequences] Whether to force outputting full sequences or not. Default is `false`. + * @property {string} [kwargs.language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known. + * @property {string} [kwargs.task] The task to perform. Default is `null`, meaning it should be auto-detected. + * @property {number[][]} [kwargs.forced_decoder_ids] A list of pairs of integers which indicates a mapping from generation indices to token indices + * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123. + * @property {number} [num_frames] The number of frames in the input audio. + * @typedef {import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig + * + * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text. + * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {AutomaticSpeechRecognitionConfig} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`. + * + * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType + */ + +/** + * Pipeline that aims at extracting spoken text contained within some audio. + * + * **Example:** Transcribe English. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url); + * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." } + * ``` + * + * **Example:** Transcribe English w/ timestamps. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url, { return_timestamps: true }); + * // { + * // text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." + * // chunks: [ + * // { timestamp: [0, 8], text: " And so my fellow Americans ask not what your country can do for you" } + * // { timestamp: [8, 11], text: " ask what you can do for your country." } + * // ] + * // } + * ``` + * + * **Example:** Transcribe English w/ word-level timestamps. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url, { return_timestamps: 'word' }); + * // { + * // "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.", + * // "chunks": [ + * // { "text": " And", "timestamp": [0, 0.78] }, + * // { "text": " so", "timestamp": [0.78, 1.06] }, + * // { "text": " my", "timestamp": [1.06, 1.46] }, + * // ... + * // { "text": " for", "timestamp": [9.72, 9.92] }, + * // { "text": " your", "timestamp": [9.92, 10.22] }, + * // { "text": " country.", "timestamp": [10.22, 13.5] } + * // ] + * // } + * ``` + * + * **Example:** Transcribe French. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; + * const output = await transcriber(url, { language: 'french', task: 'transcribe' }); + * // { text: " J'adore, j'aime, je n'aime pas, je déteste." } + * ``` + * + * **Example:** Translate French to English. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; + * const output = await transcriber(url, { language: 'french', task: 'translate' }); + * // { text: " I love, I like, I don't like, I hate." } + * ``` + * + * **Example:** Transcribe/translate audio longer than 30 seconds. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav'; + * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 }); + * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" } + * ``` + */ +export class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) { + + /** + * Create a new AutomaticSpeechRecognitionPipeline. + * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {AutomaticSpeechRecognitionPipelineCallback} */ + async _call(audio, kwargs = {}) { + switch (this.model.config.model_type) { + case 'whisper': + return this._call_whisper(audio, kwargs) + case 'wav2vec2': + case 'hubert': + return this._call_wav2vec2(audio, kwargs) + default: + throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`) + } + } + + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + async _call_wav2vec2(audio, kwargs = {}) { + // TODO use kwargs + + if (kwargs.language) { + console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); + } + if (kwargs.task) { + console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); + } + + const single = !Array.isArray(audio); + if (single) { + audio = [/** @type {AudioInput} */ (audio)]; + } + + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + + const predicted_ids = []; + for (const item of logits) { + predicted_ids.push(max(item.data)[1]) + } + const predicted_sentences = this.tokenizer.decode(predicted_ids) + toReturn.push({ text: predicted_sentences }) + } + return single ? toReturn[0] : toReturn; + } + + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + async _call_whisper(audio, kwargs = {}) { + + const return_timestamps = kwargs.return_timestamps ?? false; + const chunk_length_s = kwargs.chunk_length_s ?? 0; + const chunk_callback = kwargs.chunk_callback ?? null; + const force_full_sequences = kwargs.force_full_sequences ?? false; + let stride_length_s = kwargs.stride_length_s ?? null; + + if (return_timestamps === 'word') { + kwargs['return_token_timestamps'] = true; + } + + const language = pop(kwargs, 'language', null); + const task = pop(kwargs, 'task', null); + + if (language || task || return_timestamps) { + if (kwargs.forced_decoder_ids) { + throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.") + } + // @ts-ignore + const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({ language, task, no_timestamps: !return_timestamps }) + if (decoder_prompt_ids.length > 0) { + kwargs.forced_decoder_ids = decoder_prompt_ids; + } + } + + const single = !Array.isArray(audio); + if (single) { + audio = [/** @type {AudioInput} */ (audio)]; + } + + const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions; + const hop_length = this.processor.feature_extractor.config.hop_length; + + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + + const toReturn = []; + for (const aud of preparedAudios) { + /** @type {ChunkCallbackItem[]} */ + let chunks = []; + if (chunk_length_s > 0) { + if (stride_length_s === null) { + stride_length_s = chunk_length_s / 6; + } else if (chunk_length_s <= stride_length_s) { + throw Error("`chunk_length_s` must be larger than `stride_length_s`.") + } + + // TODO support different stride_length_s (for left and right) + + const window = sampling_rate * chunk_length_s; + const stride = sampling_rate * stride_length_s; + const jump = window - 2 * stride; + let offset = 0; + + // Create subarrays of audio with overlaps + + while (offset < aud.length) { + const subarr = aud.subarray(offset, offset + window); + const feature = await this.processor(subarr); + + const isFirst = offset === 0; + const isLast = offset + jump >= aud.length; + chunks.push({ + stride: [ + subarr.length, + isFirst ? 0 : stride, + isLast ? 0 : stride + ], + input_features: feature.input_features, + is_last: isLast + }) + offset += jump; + } + + } else { + chunks = [{ + stride: [aud.length, 0, 0], + input_features: (await this.processor(aud)).input_features, + is_last: true + }] + } + + // Generate for each set of input features + for (const chunk of chunks) { + kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length); + + // NOTE: doing sequentially for now + const data = await this.model.generate(chunk.input_features, kwargs); + + // TODO: Right now we only get top beam + if (return_timestamps === 'word') { + chunk.tokens = data.sequences[0]; + chunk.token_timestamps = data.token_timestamps.tolist()[0].map( + (/** @type {number} */ x) => round(x, 2) + ); + + } else { + chunk.tokens = data[0]; + } + + // convert stride to seconds + chunk.stride = chunk.stride.map(x => x / sampling_rate); + + if (chunk_callback !== null) { + chunk_callback(chunk) + } + } + + // Merge text chunks + // @ts-ignore + const [full_text, optional] = this.tokenizer._decode_asr(chunks, { + time_precision, return_timestamps, force_full_sequences + }); + + toReturn.push({ text: full_text, ...optional }) + } + return single ? toReturn[0] : toReturn; + } +} + +/** + * @typedef {Object} ImageToTextSingle + * @property {string} generated_text The generated text. + * @typedef {ImageToTextSingle[]} ImageToTextOutput + * + * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} texts The images to be captioned. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object (or array of objects) containing the generated text(s). + * + * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType + */ + +/** + * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image. + * + * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`. + * ```javascript + * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await captioner(url); + * // [{ generated_text: 'a cat laying on a couch with another cat' }] + * ``` + * + * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`. + * ```javascript + * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg'; + * const output = await captioner(url); + * // [{ generated_text: 'Mr. Brown commented icily.' }] + * ``` + */ +export class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) { + + /** + * Create a new ImageToTextPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ImageToTextPipelineCallback} */ + async _call(images, generate_kwargs = {}) { + + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + + const { pixel_values } = await this.processor(preparedImages); + + const toReturn = []; + for (const batch of pixel_values) { + batch.dims = [1, ...batch.dims] + const output = await this.model.generate(batch, generate_kwargs); + const decoded = this.tokenizer.batch_decode(output, { + skip_special_tokens: true, + }).map(x => ({ generated_text: x.trim() })) + toReturn.push(decoded); + } + + return isBatched ? toReturn : toReturn[0]; + } +} + +/** + * @typedef {Object} ImageClassificationSingle + * @property {string} label The label identified by the model. + * @property {number} score The score attributed by the model for that label. + * @typedef {ImageClassificationSingle[]} ImageClassificationOutput + * + * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines. + * @property {number} [topk=1] The number of top labels that will be returned by the pipeline. + * + * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images(s) to be classified. + * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType + */ + +/** + * Image classification pipeline using any `AutoModelForImageClassification`. + * This pipeline predicts the class of an image. + * + * **Example:** Classify an image. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // ] + * ``` + * + * **Example:** Classify an image and return top `n` classes. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, { topk: 3 }); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // { label: 'tiger cat', score: 0.3634825646877289 }, + * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, + * // ] + * ``` + * + * **Example:** Classify an image and return all classes. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, { topk: 0 }); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // { label: 'tiger cat', score: 0.3634825646877289 }, + * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, + * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 }, + * // ... + * // ] + * ``` + */ +export class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) { + + /** + * Create a new ImageClassificationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ImageClassificationPipelineCallback} */ + async _call(images, { + topk = 1 + } = {}) { + + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + + const { pixel_values } = await this.processor(preparedImages); + const output = await this.model({ pixel_values }); + + const id2label = this.model.config.id2label; + const toReturn = []; + for (const batch of output.logits) { + const scores = getTopItems(softmax(batch.data), topk); + + const vals = scores.map(x => ({ + label: id2label[x[0]], + score: x[1], + })); + if (topk === 1) { + toReturn.push(...vals); + } else { + toReturn.push(vals); + } + } + + return isBatched || topk === 1 ? /** @type {ImageClassificationOutput} */ (toReturn) : /** @type {ImageClassificationOutput[]} */ (toReturn)[0]; + } + +} + +/** + * @typedef {Object} ImageSegmentationPipelineOutput + * @property {string} label The label of the segment. + * @property {number|null} score The score of the segment. + * @property {RawImage} mask The mask of the segment. + * + * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines. + * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks. + * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. + * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments. + * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`], + * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order). + * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels. + * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes. + * + * @callback ImageSegmentationPipelineCallback Segment the input images. + * @param {ImagePipelineInputs} images The input images. + * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation. + * @returns {Promise} The annotated segments. + * + * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType + */ + +/** + * Image segmentation pipeline using any `AutoModelForXXXSegmentation`. + * This pipeline predicts masks of objects and their classes. + * + * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`. + * ```javascript + * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await segmenter(url); + * // [ + * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } }, + * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } } + * // ] + * ``` + */ +export class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) { + /** + * Create a new ImageSegmentationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + + this.subtasks_mapping = { + // Mapping of subtasks to their corresponding post-processing function names. + panoptic: 'post_process_panoptic_segmentation', + instance: 'post_process_instance_segmentation', + semantic: 'post_process_semantic_segmentation' + } + } + + /** @type {ImageSegmentationPipelineCallback} */ + async _call(images, { + threshold = 0.5, + mask_threshold = 0.5, + overlap_mask_area_threshold = 0.8, + label_ids_to_fuse = null, + target_sizes = null, + subtask = null, + } = {}) { + const isBatched = Array.isArray(images); + + if (isBatched && images.length !== 1) { + throw Error("Image segmentation pipeline currently only supports a batch size of 1."); + } + + const preparedImages = await prepareImages(images); + const imageSizes = preparedImages.map(x => [x.height, x.width]); + + const { pixel_values, pixel_mask } = await this.processor(preparedImages); + const output = await this.model({ pixel_values, pixel_mask }); + + let fn = null; + if (subtask !== null) { + fn = this.subtasks_mapping[subtask]; + } else { + for (let [task, func] of Object.entries(this.subtasks_mapping)) { + if (func in this.processor.feature_extractor) { + fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor); + subtask = task; + break; + } + } + } + + const id2label = this.model.config.id2label; + + /** @type {ImageSegmentationPipelineOutput[]} */ + const annotation = []; + if (subtask === 'panoptic' || subtask === 'instance') { + const processed = fn( + output, + threshold, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_sizes ?? imageSizes, // TODO FIX? + )[0]; + + const segmentation = processed.segmentation; + + for (const segment of processed.segments_info) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === segment.id) { + maskData[i] = 255; + } + } + + // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1) + + annotation.push({ + score: segment.score, + label: id2label[segment.label_id], + // mask: mask + }) + } + + } else if (subtask === 'semantic') { + const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0]; + + for (const label of labels) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === label) { + maskData[i] = 255; + } + } + + // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); + + annotation.push({ + score: null, + label: id2label[label], + // mask: mask + }); + } + } else { + throw Error(`Subtask ${subtask} not supported.`); + } + + return annotation; + } +} + +/** + * @typedef {Object} ZeroShotImageClassificationOutput + * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. + * @property {number} score The score attributed by the model for that label (between 0 and 1). + * + * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines. + * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels` + * to attempt the image classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_image`. + * + * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {string[]} candidate_labels The candidate labels for this image. + * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification. + * @returns {Promise} An array of objects containing the predicted labels and scores. + * + * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType + */ + +/** + * Zero shot image classification pipeline. This pipeline predicts the class of + * an image when you provide an image and a set of `candidate_labels`. + * + * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`. + * ```javascript + * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, ['tiger', 'horse', 'dog']); + * // [ + * // { score: 0.9993917942047119, label: 'tiger' }, + * // { score: 0.0003519294841680676, label: 'horse' }, + * // { score: 0.0002562698791734874, label: 'dog' } + * // ] + * ``` + */ +export class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) { + /** + * Create a new ZeroShotImageClassificationPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ZeroShotImageClassificationPipelineCallback} */ + async _call(images, candidate_labels, { + hypothesis_template = "This is a photo of {}" + } = {}) { + + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + + // Insert label into hypothesis template + const texts = candidate_labels.map( + x => hypothesis_template.replace('{}', x) + ); + + // Run tokenization + const text_inputs = this.tokenizer(texts, { + padding: this.model.config.model_type === 'siglip' ? 'max_length' : true, + truncation: true, + }); + + // Run processor + const { pixel_values } = await this.processor(preparedImages); + + // Run model with both text and pixel inputs + const output = await this.model({ ...text_inputs, pixel_values }); + + const function_to_apply = + this.model.config.model_type === 'siglip' + ? batch => batch.sigmoid().data + : batch => softmax(batch.data); + + // Compare each image with each candidate label + const toReturn = []; + for (const batch of output.logits_per_image) { + // Compute softmax per image + const probs = function_to_apply(batch); + + const result = [...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + })); + result.sort((a, b) => b.score - a.score); // sort by score in descending order + toReturn.push(result); + } + + return isBatched ? toReturn : toReturn[0]; + } +} + + +/** + * @typedef {Object} ObjectDetectionPipelineSingle + * @property {string} label The class label identified by the model. + * @property {number} score The score attributed by the model for that label. + * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true. + * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput + * + * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines. + * @property {number} [threshold=0.9] The threshold used to filter boxes by score. + * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). + * + * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection. + * @returns {Promise} A list of objects or a list of list of objects. + * + * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType + */ + +/** + * Object detection pipeline using any `AutoModelForObjectDetection`. + * This pipeline predicts bounding boxes of objects and their classes. + * + * **Example:** Run object-detection with `Xenova/detr-resnet-50`. + * ```javascript + * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50'); + * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await detector(img, { threshold: 0.9 }); + * // [{ + * // score: 0.9976370930671692, + * // label: "remote", + * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 } + * // }, + * // ... + * // { + * // score: 0.9984092116355896, + * // label: "cat", + * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 } + * // }] + * ``` + */ +export class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) { + + /** + * Create a new ObjectDetectionPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ObjectDetectionPipelineCallback} */ + async _call(images, { + threshold = 0.9, + percentage = false, + } = {}) { + + const isBatched = Array.isArray(images); + + if (isBatched && images.length !== 1) { + throw Error("Object detection pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + + const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]); + + const { pixel_values, pixel_mask } = await this.processor(preparedImages); + const output = await this.model({ pixel_values, pixel_mask }); + + // @ts-ignore + const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes); + + // Add labels + const id2label = this.model.config.id2label; + + // Format output + /** @type {ObjectDetectionPipelineOutput[]} */ + const result = processed.map(batch => ( + batch.boxes.map((box, i) => ({ + score: batch.scores[i], + label: id2label[batch.classes[i]], + box: get_bounding_box(box, !percentage), + })) + )) + + return isBatched ? result : result[0]; + } +} + + +/** + * @typedef {Object} ZeroShotObjectDetectionOutput + * @property {string} label Text query corresponding to the found object. + * @property {number} score Score corresponding to the object (between 0 and 1). + * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true. + * + * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines. + * @property {number} [threshold=0.1] The probability necessary to make a prediction. + * @property {number} [topk=null] The number of top predictions that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of predictions available, it will default + * to the number of predictions. + * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). + * + * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {string[]} candidate_labels What the model should recognize in the image. + * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection. + * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes. + * + * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType + */ + +/** + * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of + * objects when you provide an image and a set of `candidate_labels`. + * + * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`. + * ```javascript + * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png'; + * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag']; + * const output = await detector(url, candidate_labels); + * // [ + * // { + * // score: 0.24392342567443848, + * // label: 'human face', + * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 } + * // }, + * // { + * // score: 0.15129457414150238, + * // label: 'american flag', + * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 } + * // }, + * // { + * // score: 0.13649864494800568, + * // label: 'helmet', + * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 } + * // }, + * // { + * // score: 0.10262022167444229, + * // label: 'rocket', + * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 } + * // } + * // ] + * ``` + * + * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold). + * ```javascript + * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png'; + * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera']; + * const output = await detector(url, candidate_labels, { topk: 4, threshold: 0.05 }); + * // [ + * // { + * // score: 0.1606510728597641, + * // label: 'sunglasses', + * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 } + * // }, + * // { + * // score: 0.08935828506946564, + * // label: 'hat', + * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 } + * // }, + * // { + * // score: 0.08530698716640472, + * // label: 'camera', + * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 } + * // }, + * // { + * // score: 0.08349756896495819, + * // label: 'book', + * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 } + * // } + * // ] + * ``` + */ +export class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) { + + /** + * Create a new ZeroShotObjectDetectionPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ZeroShotObjectDetectionPipelineCallback} */ + async _call(images, candidate_labels, { + threshold = 0.1, + topk = null, + percentage = false, + } = {}) { + + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + + // Run tokenization + const text_inputs = this.tokenizer(candidate_labels, { + padding: true, + truncation: true, + }); + + // Run processor + const model_inputs = await this.processor(preparedImages); + + // Since non-maximum suppression is performed for exporting, we need to + // process each image separately. For more information, see: + // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032 + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const image = preparedImages[i]; + const imageSize = percentage ? null : [[image.height, image.width]]; + const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); + + // Run model with both text and pixel inputs + const output = await this.model({ ...text_inputs, pixel_values }); + + // @ts-ignore + const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0]; + let result = processed.boxes.map((box, i) => ({ + score: processed.scores[i], + label: candidate_labels[processed.classes[i]], + box: get_bounding_box(box, !percentage), + })).sort((a, b) => b.score - a.score); + if (topk !== null) { + result = result.slice(0, topk); + } + toReturn.push(result) + } + + return isBatched ? toReturn : toReturn[0]; + } +} + +/** + * @typedef {Object} DocumentQuestionAnsweringSingle + * @property {string} answer The generated text. + * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput + * + * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document. + * @param {ImageInput} image The image of the document to use. + * @param {string} question A question to ask of the document. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object (or array of objects) containing the answer(s). + * + * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType + */ + +/** + * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. + * The inputs/outputs are similar to the (extractive) question answering pipeline; however, + * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context. + * + * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`. + * ```javascript + * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa'); + * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; + * const question = 'What is the invoice number?'; + * const output = await qa_pipeline(image, question); + * // [{ answer: 'us-001' }] + * ``` + */ +export class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) { + + /** + * Create a new DocumentQuestionAnsweringPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {DocumentQuestionAnsweringPipelineCallback} */ + async _call(image, question, generate_kwargs = {}) { + + // NOTE: For now, we only support a batch size of 1 + + // Preprocess image + const preparedImage = (await prepareImages(image))[0]; + const { pixel_values } = await this.processor(preparedImage); + + // Run tokenization + const task_prompt = `${question}`; + const decoder_input_ids = this.tokenizer(task_prompt, { + add_special_tokens: false, + padding: true, + truncation: true, + }).input_ids; + + // Run model + const output = await this.model.generate( + pixel_values, + { + ...generate_kwargs, + decoder_input_ids, + max_length: this.model.config.decoder.max_position_embeddings, + } + ); + + // Decode output + const decoded = this.tokenizer.batch_decode(output)[0]; + + // Parse answer + const match = decoded.match(/(.*?)<\/s_answer>/); + let answer = null; + if (match && match.length >= 2) { + answer = match[1].trim(); + } + return [{ answer }]; + } +} + + +/** + * @typedef {Object} VocoderOptions + * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder. + * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs + */ + +/** + * @typedef {Object} TextToAudioOutput + * @property {Float32Array} audio The generated audio waveform. + * @property {number} sampling_rate The sampling rate of the generated audio waveform. + * + * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines. + * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it). + * + * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs. + * @param {string|string[]} texts The text(s) to generate. + * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method. + * @returns {Promise} An object containing the generated audio and sampling rate. + * + * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType + */ + +/** + * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. + * This pipeline generates an audio file from an input text and optional other conditional inputs. + * + * **Example:** Generate audio from text with `Xenova/speecht5_tts`. + * ```javascript + * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false }); + * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin'; + * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings }); + * // { + * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...], + * // sampling_rate: 16000 + * // } + * ``` + * + * You can then save the audio to a .wav file with the `wavefile` package: + * ```javascript + * import wavefile from 'wavefile'; + * import fs from 'fs'; + * + * const wav = new wavefile.WaveFile(); + * wav.fromScratch(1, out.sampling_rate, '32f', out.audio); + * fs.writeFileSync('out.wav', wav.toBuffer()); + * ``` + * + * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107). + * ```javascript + * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra'); + * const out = await synthesizer('Bonjour'); + * // { + * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...], + * // sampling_rate: 16000 + * // } + * ``` + */ +export class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) { + DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan" + + /** + * Create a new TextToAudioPipeline. + * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + + // TODO: Find a better way for `pipeline` to set the default vocoder + this.vocoder = options.vocoder ?? null; + } + + + /** @type {TextToAudioPipelineCallback} */ + async _call(text_inputs, { + speaker_embeddings = null, + } = {}) { + + // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model + if (this.processor) { + return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings }); + } else { + return this._call_text_to_waveform(text_inputs); + } + } + + async _call_text_to_waveform(text_inputs) { + + // Run tokenization + const inputs = this.tokenizer(text_inputs, { + padding: true, + truncation: true, + }); + + // Generate waveform + const { waveform } = await this.model(inputs); + + const sampling_rate = this.model.config.sampling_rate; + return { + audio: waveform.data, + sampling_rate, + } + } + + async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { + + // Load vocoder, if not provided + if (!this.vocoder) { + console.log('No vocoder specified, using default HifiGan vocoder.'); + this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false }); + } + + // Load speaker embeddings as Float32Array from path/URL + if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) { + // Load from URL with fetch + speaker_embeddings = new Float32Array( + await (await fetch(speaker_embeddings)).arrayBuffer() + ); + } + + if (speaker_embeddings instanceof Float32Array) { + speaker_embeddings = new Tensor( + 'float32', + speaker_embeddings, + [1, speaker_embeddings.length] + ) + } else if (!(speaker_embeddings instanceof Tensor)) { + throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.") + } + + // Run tokenization + const { input_ids } = this.tokenizer(text_inputs, { + padding: true, + truncation: true, + }); + + // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor` + // @ts-ignore + const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); + + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + return { + audio: waveform.data, + sampling_rate, + } + } +} + +/** + * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The images to transform. + * @returns {Promise} The transformed image or list of images. + * + * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType + */ + +/** + * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input. + * + * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64` + * ```javascript + * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; + * const output = await upscaler(url); + * // RawImage { + * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ], + * // width: 512, + * // height: 512, + * // channels: 3 + * // } + * ``` + */ +export class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) { + /** + * Create a new ImageToImagePipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {ImageToImagePipelineCallback} */ + async _call(images) { + + const preparedImages = await prepareImages(images); + const inputs = await this.processor(preparedImages); + const outputs = await this.model(inputs); + + /** @type {RawImage[]} */ + const toReturn = []; + for (const batch of outputs.reconstruction) { + const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8'); + // toReturn.push(RawImage.fromTensor(output)); + } + + return toReturn.length > 1 ? toReturn : toReturn[0]; + } +} + +/** + * @typedef {Object} DepthEstimationPipelineOutput + * @property {Tensor} predicted_depth The raw depth map predicted by the model. + * @property {RawImage} depth The processed depth map as an image (with the same size as the input image). + * + * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The images to compute depth for. + * @returns {Promise} An image or a list of images containing result(s). + * + * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType + */ + +/** + * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image. + * + * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas` + * ```javascript + * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const out = await depth_estimator(url); + * // { + * // predicted_depth: Tensor { + * // dims: [ 384, 384 ], + * // type: 'float32', + * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ], + * // size: 147456 + * // }, + * // depth: RawImage { + * // data: Uint8Array(307200) [ 86, 86, 86, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * // } + * ``` + */ +export class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) { + /** + * Create a new DepthEstimationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + + /** @type {DepthEstimationPipelineCallback} */ + async _call(images) { + + const preparedImages = await prepareImages(images); + + const inputs = await this.processor(preparedImages); + const { predicted_depth } = await this.model(inputs); + + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false); + const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8'); + toReturn.push({ + predicted_depth: predicted_depth[i], + // depth: RawImage.fromTensor(formatted), + }); + } + + return toReturn.length > 1 ? toReturn : toReturn[0]; + } +} + +const SUPPORTED_TASKS = Object.freeze({ + "text-classification": { + "tokenizer": AutoTokenizer, + "pipeline": TextClassificationPipeline, + "model": AutoModelForSequenceClassification, + "default": { + // TODO: replace with original + // "model": "distilbert-base-uncased-finetuned-sst-2-english", + "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english", + }, + "type": "text", + }, + "token-classification": { + "tokenizer": AutoTokenizer, + "pipeline": TokenClassificationPipeline, + "model": AutoModelForTokenClassification, + "default": { + // TODO: replace with original + // "model": "Davlan/bert-base-multilingual-cased-ner-hrl", + "model": "Xenova/bert-base-multilingual-cased-ner-hrl", + }, + "type": "text", + }, + "question-answering": { + "tokenizer": AutoTokenizer, + "pipeline": QuestionAnsweringPipeline, + "model": AutoModelForQuestionAnswering, + "default": { + // TODO: replace with original + // "model": "distilbert-base-cased-distilled-squad", + "model": "Xenova/distilbert-base-cased-distilled-squad", + }, + "type": "text", + }, + + "fill-mask": { + "tokenizer": AutoTokenizer, + "pipeline": FillMaskPipeline, + "model": AutoModelForMaskedLM, + "default": { + // TODO: replace with original + // "model": "bert-base-uncased", + "model": "Xenova/bert-base-uncased", + }, + "type": "text", + }, + "summarization": { + "tokenizer": AutoTokenizer, + "pipeline": SummarizationPipeline, + "model": AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "sshleifer/distilbart-cnn-6-6", + "model": "Xenova/distilbart-cnn-6-6", + }, + "type": "text", + }, + "translation": { + "tokenizer": AutoTokenizer, + "pipeline": TranslationPipeline, + "model": AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "t5-small", + "model": "Xenova/t5-small", + }, + "type": "text", + }, + "text2text-generation": { + "tokenizer": AutoTokenizer, + "pipeline": Text2TextGenerationPipeline, + "model": AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "google/flan-t5-small", + "model": "Xenova/flan-t5-small", + }, + "type": "text", + }, + "text-generation": { + "tokenizer": AutoTokenizer, + "pipeline": TextGenerationPipeline, + "model": AutoModelForCausalLM, + "default": { + // TODO: replace with original + // "model": "gpt2", + "model": "Xenova/gpt2", + }, + "type": "text", + }, + "zero-shot-classification": { + "tokenizer": AutoTokenizer, + "pipeline": ZeroShotClassificationPipeline, + "model": AutoModelForSequenceClassification, + "default": { + // TODO: replace with original + // "model": "typeform/distilbert-base-uncased-mnli", + "model": "Xenova/distilbert-base-uncased-mnli", + }, + "type": "text", + }, + "audio-classification": { + "pipeline": AudioClassificationPipeline, + "model": AutoModelForAudioClassification, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "superb/wav2vec2-base-superb-ks", + "model": "Xenova/wav2vec2-base-superb-ks", + }, + "type": "audio", + }, + "zero-shot-audio-classification": { + "tokenizer": AutoTokenizer, + "pipeline": ZeroShotAudioClassificationPipeline, + "model": AutoModel, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "laion/clap-htsat-fused", + "model": "Xenova/clap-htsat-unfused", + }, + "type": "multimodal", + }, + "automatic-speech-recognition": { + "tokenizer": AutoTokenizer, + "pipeline": AutomaticSpeechRecognitionPipeline, + "model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC], + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "openai/whisper-tiny.en", + "model": "Xenova/whisper-tiny.en", + }, + "type": "multimodal", + }, + "text-to-audio": { + "tokenizer": AutoTokenizer, + "pipeline": TextToAudioPipeline, + "model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram], + "processor": [AutoProcessor, /* Some don't use a processor */ null], + "default": { + // TODO: replace with original + // "model": "microsoft/speecht5_tts", + "model": "Xenova/speecht5_tts", + }, + "type": "text", + }, + "image-to-text": { + "tokenizer": AutoTokenizer, + "pipeline": ImageToTextPipeline, + "model": AutoModelForVision2Seq, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "nlpconnect/vit-gpt2-image-captioning", + "model": "Xenova/vit-gpt2-image-captioning", + }, + "type": "multimodal", + }, + + "image-classification": { + // no tokenizer + "pipeline": ImageClassificationPipeline, + "model": AutoModelForImageClassification, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "google/vit-base-patch16-224", + "model": "Xenova/vit-base-patch16-224", + }, + "type": "multimodal", + }, + + "image-segmentation": { + // no tokenizer + "pipeline": ImageSegmentationPipeline, + "model": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation], + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "facebook/detr-resnet-50-panoptic", + "model": "Xenova/detr-resnet-50-panoptic", + }, + "type": "multimodal", + }, + + "zero-shot-image-classification": { + "tokenizer": AutoTokenizer, + "pipeline": ZeroShotImageClassificationPipeline, + "model": AutoModel, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "openai/clip-vit-base-patch32", + "model": "Xenova/clip-vit-base-patch32", + }, + "type": "multimodal", + }, + + "object-detection": { + // no tokenizer + "pipeline": ObjectDetectionPipeline, + "model": AutoModelForObjectDetection, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "facebook/detr-resnet-50", + "model": "Xenova/detr-resnet-50", + }, + "type": "multimodal", + }, + "zero-shot-object-detection": { + "tokenizer": AutoTokenizer, + "pipeline": ZeroShotObjectDetectionPipeline, + "model": AutoModelForZeroShotObjectDetection, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "google/owlvit-base-patch32", + "model": "Xenova/owlvit-base-patch32", + }, + "type": "multimodal", + }, + "document-question-answering": { + "tokenizer": AutoTokenizer, + "pipeline": DocumentQuestionAnsweringPipeline, + "model": AutoModelForDocumentQuestionAnswering, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "naver-clova-ix/donut-base-finetuned-docvqa", + "model": "Xenova/donut-base-finetuned-docvqa", + }, + "type": "multimodal", + }, + "image-to-image": { + // no tokenizer + "pipeline": ImageToImagePipeline, + "model": AutoModelForImageToImage, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "caidas/swin2SR-classical-sr-x2-64", + "model": "Xenova/swin2SR-classical-sr-x2-64", + }, + "type": "image", + }, + "depth-estimation": { + // no tokenizer + "pipeline": DepthEstimationPipeline, + "model": AutoModelForDepthEstimation, + "processor": AutoProcessor, + "default": { + // TODO: replace with original + // "model": "Intel/dpt-large", + "model": "Xenova/dpt-large", + }, + "type": "image", + }, + + // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers). + "feature-extraction": { + "tokenizer": AutoTokenizer, + "pipeline": FeatureExtractionPipeline, + "model": AutoModel, + "default": { + // TODO: replace with original + // "model": "sentence-transformers/all-MiniLM-L6-v2", + "model": "Xenova/all-MiniLM-L6-v2", + }, + "type": "text", + }, +}) + + +// TODO: Add types for TASK_ALIASES +const TASK_ALIASES = Object.freeze({ + "sentiment-analysis": "text-classification", + "ner": "token-classification", + // "vqa": "visual-question-answering", // TODO: Add + "asr": "automatic-speech-recognition", + "text-to-speech": "text-to-audio", + + // Add for backwards compatibility + "embeddings": "feature-extraction", +}); + +/** + * @typedef {keyof typeof SUPPORTED_TASKS} TaskType + * @typedef {keyof typeof TASK_ALIASES} AliasType + * @typedef {TaskType | AliasType} PipelineType All possible pipeline types. + * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes. + * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes. + * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes. + */ + +/** + * Utility factory method to build a `Pipeline` object. + * + * @template {PipelineType} T The type of pipeline to return. + * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are: + * - `"audio-classification"`: will return a `AudioClassificationPipeline`. + * - `"automatic-speech-recognition"`: will return a `AutomaticSpeechRecognitionPipeline`. + * - `"depth-estimation"`: will return a `DepthEstimationPipeline`. + * - `"document-question-answering"`: will return a `DocumentQuestionAnsweringPipeline`. + * - `"feature-extraction"`: will return a `FeatureExtractionPipeline`. + * - `"fill-mask"`: will return a `FillMaskPipeline`. + * - `"image-classification"`: will return a `ImageClassificationPipeline`. + * - `"image-segmentation"`: will return a `ImageSegmentationPipeline`. + * - `"image-to-text"`: will return a `ImageToTextPipeline`. + * - `"object-detection"`: will return a `ObjectDetectionPipeline`. + * - `"question-answering"`: will return a `QuestionAnsweringPipeline`. + * - `"summarization"`: will return a `SummarizationPipeline`. + * - `"text2text-generation"`: will return a `Text2TextGenerationPipeline`. + * - `"text-classification"` (alias "sentiment-analysis" available): will return a `TextClassificationPipeline`. + * - `"text-generation"`: will return a `TextGenerationPipeline`. + * - `"token-classification"` (alias "ner" available): will return a `TokenClassificationPipeline`. + * - `"translation"`: will return a `TranslationPipeline`. + * - `"translation_xx_to_yy"`: will return a `TranslationPipeline`. + * - `"zero-shot-classification"`: will return a `ZeroShotClassificationPipeline`. + * - `"zero-shot-audio-classification"`: will return a `ZeroShotAudioClassificationPipeline`. + * - `"zero-shot-image-classification"`: will return a `ZeroShotImageClassificationPipeline`. + * - `"zero-shot-object-detection"`: will return a `ZeroShotObjectDetectionPipeline`. + * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used. + * @param {import('./utils/hub.js').PretrainedOptions} [options] Optional parameters for the pipeline. + * @returns {Promise} A Pipeline object for the specified task. + * @throws {Error} If an unsupported pipeline is requested. + */ +export async function pipeline( + task, + model = null, + { + quantized = true, + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + } = {} +) { + // Helper method to construct pipeline + + // Apply aliases + // @ts-ignore + task = TASK_ALIASES[task] ?? task; + + // Get pipeline info + const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]]; + if (!pipelineInfo) { + throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`) + } + + // Use model if specified, otherwise, use default + if (!model) { + model = pipelineInfo.default.model + console.log(`No model specified. Using default model: "${model}".`); + } + + const pretrainedOptions = { + quantized, + progress_callback, + config, + cache_dir, + local_files_only, + revision, + } + + const classes = new Map([ + ['tokenizer', pipelineInfo.tokenizer], + ['model', pipelineInfo.model], + ['processor', pipelineInfo.processor], + ]); + + // Load model, tokenizer, and processor (if they exist) + const results = await loadItems(classes, model, pretrainedOptions); + results.task = task; + + dispatchCallback(progress_callback, { + 'status': 'ready', + 'task': task, + 'model': model, + }); + + const pipelineClass = pipelineInfo.pipeline; + return new pipelineClass(results); +} + + +/** + * Helper function to get applicable model, tokenizer, or processor classes for a given model. + * @param {Map} mapping The mapping of names to classes, arrays of classes, or null. + * @param {string} model The name of the model to load. + * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method. + * @private + */ +async function loadItems(mapping, model, pretrainedOptions) { + + const result = Object.create(null); + + /**@type {Promise[]} */ + const promises = []; + for (let [name, cls] of mapping.entries()) { + if (!cls) continue; + + /**@type {Promise} */ + let promise; + if (Array.isArray(cls)) { + promise = new Promise(async (resolve, reject) => { + let e; + for (let c of cls) { + if (c === null) { + // If null, we resolve it immediately, meaning the relevant + // class was not found, but it is optional. + resolve(null); + return; + } + try { + resolve(await c.from_pretrained(model, pretrainedOptions)); + return; + } catch (err) { + e = err; + } + } + reject(e); + }) + } else { + promise = cls.from_pretrained(model, pretrainedOptions); + } + + result[name] = promise; + promises.push(promise); + } + + // Wait for all promises to resolve (in parallel) + await Promise.all(promises); + + // Then assign to result + for (let [name, promise] of Object.entries(result)) { + result[name] = await promise; + } + + return result; +} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/src/processors.js b/core/vendor/node_modules/@xenova/transformers/src/processors.js new file mode 100644 index 000000000..37e70c197 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/processors.js @@ -0,0 +1,1966 @@ + +/** + * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model. + * + * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model. + * ```javascript + * import { AutoProcessor, read_audio } from '@xenova/transformers'; + * + * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en'); + * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000); + * let { input_features } = await processor(audio); + * // Tensor { + * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...], + * // dims: [1, 80, 3000], + * // type: 'float32', + * // size: 240000, + * // } + * ``` + * + * @module processors + */ +import { + Callable, + calculateDimensions, + calculateReflectOffset, +} from './utils/core.js'; + +import { + getModelJSON, +} from './utils/hub.js'; + +import { + max, + min, + softmax, +} from './utils/maths.js'; + + +import { Tensor, cat, interpolate, stack, transpose } from './utils/tensor.js'; + +// import { RawImage } from './utils/image.js'; +import { + mel_filter_bank, + spectrogram, + window_function, +} from './utils/audio.js'; + + +// Helper functions + +/** + * Converts bounding boxes from center format to corners format. + * + * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height) + * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) + */ +function center_to_corners_format([centerX, centerY, width, height]) { + return [ + centerX - width / 2, + centerY - height / 2, + centerX + width / 2, + centerY + height / 2 + ]; +} + +/** + * Post-processes the outputs of the model (for object detection). + * @param {Object} outputs The outputs of the model that must be post-processed + * @param {Tensor} outputs.logits The logits + * @param {Tensor} outputs.pred_boxes The predicted boxes. + * @param {number} [threshold=0.5] The threshold to use for the scores. + * @param {number[][]} [target_sizes=null] The sizes of the original images. + * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed. + * @return {Object[]} An array of objects containing the post-processed outputs. + * @private + */ +function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { + const out_logits = outputs.logits; + const out_bbox = outputs.pred_boxes; + const [batch_size, num_boxes, num_classes] = out_logits.dims; + + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") + } + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + let info = { + boxes: [], + classes: [], + scores: [] + } + let logits = out_logits[i]; + let bbox = out_bbox[i]; + + for (let j = 0; j < num_boxes; ++j) { + let logit = logits[j]; + + let indices = []; + let probs; + if (is_zero_shot) { + // Get indices of classes with high enough probability + probs = logit.sigmoid().data; + for (let k = 0; k < probs.length; ++k) { + if (probs[k] > threshold) { + indices.push(k); + } + } + + } else { + // Get most probable class + let maxIndex = max(logit.data)[1]; + + if (maxIndex === num_classes - 1) { + // This is the background class, skip it + continue; + } + indices.push(maxIndex); + + // Compute softmax over classes + probs = softmax(logit.data); + } + + for (const index of indices) { + + // Some class has a high enough probability + /** @type {number[]} */ + let box = bbox[j].data; + + // convert to [x0, y0, x1, y1] format + box = center_to_corners_format(box) + if (target_size !== null) { + box = box.map((x, i) => x * target_size[(i + 1) % 2]) + } + + info.boxes.push(box); + info.classes.push(index); + info.scores.push(probs[index]); + } + } + toReturn.push(info); + } + return toReturn; +} + +/** + * Named tuple to indicate the order we are using is (height x width), even though + * the Graphics’ industry standard is (width x height). + * @typedef {[height: number, width: number]} HeightWidth + */ + +/** + * Helper function to validate audio inputs. + * @param {any} audio The audio data. + * @param {string} feature_extractor The name of the feature extractor. + * @private + */ +function validate_audio_inputs(audio, feature_extractor) { + if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { + throw new Error( + `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} 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.` + ) + } +} + +/** + * Base class for feature extractors. + * + * @extends Callable + */ +export class FeatureExtractor extends Callable { + /** + * Constructs a new FeatureExtractor instance. + * + * @param {Object} config The configuration for the feature extractor. + */ + constructor(config) { + super(); + this.config = config + } +} + +/** + * @typedef {object} ImageFeatureExtractorResult + * @property {Tensor} pixel_values The pixel values of the batched preprocessed images. + * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]]. + * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]]. + */ + +/** + * Feature extractor for image models. + * + * @extends FeatureExtractor + */ +export class ImageFeatureExtractor extends FeatureExtractor { + + /** + * Constructs a new ImageFeatureExtractor instance. + * + * @param {Object} config The configuration for the feature extractor. + * @param {number[]} config.image_mean The mean values for image normalization. + * @param {number[]} config.image_std The standard deviation values for image normalization. + * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range. + * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values. + * @param {boolean} config.do_normalize Whether to normalize the image pixel values. + * @param {boolean} config.do_resize Whether to resize the image. + * @param {number} config.resample What method to use for resampling. + * @param {number} config.size The size to resize the image to. + */ + constructor(config) { + super(config); + + this.image_mean = this.config.image_mean ?? this.config.mean; + this.image_std = this.config.image_std ?? this.config.std; + + this.resample = this.config.resample ?? 2; // 2 => bilinear + this.do_rescale = this.config.do_rescale ?? true; + this.rescale_factor = this.config.rescale_factor ?? (1 / 255); + this.do_normalize = this.config.do_normalize; + + this.do_resize = this.config.do_resize; + this.do_thumbnail = this.config.do_thumbnail; + this.size = this.config.size; + this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor; + + this.do_center_crop = this.config.do_center_crop; + this.crop_size = this.config.crop_size; + this.do_convert_rgb = this.config.do_convert_rgb ?? true; + this.do_crop_margin = this.config.do_crop_margin; + + this.pad_size = this.config.pad_size; + this.do_pad = this.config.do_pad; + + if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) { + // Should pad, but no pad size specified + // We infer the pad size from the resize size + this.pad_size = this.size + } + } + + /** + * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any + * corresponding dimension of the specified size. + * @param {RawImage} image The image to be resized. + * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. + * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. + * @returns {Promise} The resized image. + */ + async thumbnail(image, size, resample = 2) { + const input_height = image.height; + const input_width = image.width; + + const output_height = size.height; + const output_width = size.width; + + // We always resize to the smallest of either the input or output size. + let height = Math.min(input_height, output_height) + let width = Math.min(input_width, output_width) + + if (height === input_height && width === input_width) { + return image; + } + if (input_height > input_width) { + width = Math.floor(input_width * height / input_height); + } else if (input_width > input_height) { + height = Math.floor(input_height * width / input_width); + } + return await image.resize(width, height, { resample }); + } + + + /** + * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). + * @param {RawImage} image The image to be cropped. + * @param {number} gray_threshold Value below which pixels are considered to be gray. + * @returns {Promise} The cropped image. + */ + async crop_margin(image, gray_threshold = 200) { + + const gray_image = image.clone().grayscale(); + + const minValue = min(gray_image.data)[0]; + const maxValue = max(gray_image.data)[0]; + const diff = maxValue - minValue; + + if (diff === 0) { + return image; + } + + const threshold = gray_threshold / 255; + + let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; + for (let j = 0; j < gray_image.height; ++j) { + const row = j * gray_image.width; + for (let i = 0; i < gray_image.width; ++i) { + if ((gray_image.data[row + i] - minValue) / diff < threshold) { + // We have a non-zero pixel, so we update the min/max values accordingly + x_min = Math.min(x_min, i); + y_min = Math.min(y_min, j); + x_max = Math.max(x_max, i); + y_max = Math.max(y_max, j); + } + } + } + + image = await image.crop([x_min, y_min, x_max, y_max]); + return image; + } + + /** + * Pad the image by a certain amount. + * @param {Float32Array} pixelData The pixel data to pad. + * @param {number[]} imgDims The dimensions of the image. + * @param {{width:number; height:number}|number} padSize The dimensions of the padded image. + * @param {Object} options The options for padding. + * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. + * @param {boolean} [options.center=false] Whether to center the image. + * @param {number} [options.constant_values=0] The constant value to use for padding. + * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. + */ + pad_image(pixelData, imgDims, padSize, { + mode = 'constant', + center = false, + constant_values = 0, + } = {}) { + const [imageWidth, imageHeight, imageChannels] = imgDims; + + let paddedImageWidth, paddedImageHeight; + if (typeof padSize === 'number') { + paddedImageWidth = padSize; + paddedImageHeight = padSize; + } else { + paddedImageWidth = padSize.width; + paddedImageHeight = padSize.height; + } + + // Only add padding if there is a difference in size + if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { + const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); + if (Array.isArray(constant_values)) { + // Fill with constant values, cycling through the array + for (let i = 0; i < paddedPixelData.length; ++i) { + paddedPixelData[i] = constant_values[i % imageChannels]; + } + } else if (constant_values !== 0) { + paddedPixelData.fill(constant_values); + } + + const [left, top] = center + ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] + : [0, 0]; + + // Copy the original image into the padded image + for (let i = 0; i < imageHeight; ++i) { + const a = (i + top) * paddedImageWidth; + const b = i * imageWidth; + for (let j = 0; j < imageWidth; ++j) { + const c = (a + j + left) * imageChannels; + const d = (b + j) * imageChannels; + for (let k = 0; k < imageChannels; ++k) { + paddedPixelData[c + k] = pixelData[d + k]; + } + } + } + + if (mode === 'symmetric') { + if (center) { + throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.'); + // TODO: Implement this + } + const h1 = imageHeight - 1; + const w1 = imageWidth - 1; + for (let i = 0; i < paddedImageHeight; ++i) { + const a = i * paddedImageWidth; + const b = calculateReflectOffset(i, h1) * imageWidth; + + for (let j = 0; j < paddedImageWidth; ++j) { + if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image + const c = (a + j) * imageChannels; + const d = (b + calculateReflectOffset(j, w1)) * imageChannels; + + // Copy channel-wise + for (let k = 0; k < imageChannels; ++k) { + paddedPixelData[c + k] = pixelData[d + k]; + } + } + } + } + + + // Update pixel data and image dimensions + pixelData = paddedPixelData; + imgDims = [paddedImageHeight, paddedImageWidth, imageChannels] + } + return [pixelData, imgDims]; + } + + /** + * Rescale the image' pixel values by `this.rescale_factor`. + * @param {Float32Array} pixelData The pixel data to rescale. + * @returns {void} + */ + rescale(pixelData) { + for (let i = 0; i < pixelData.length; ++i) { + pixelData[i] = this.rescale_factor * pixelData[i]; + } + } + + /** + * Find the target (width, height) dimension of the output image after + * resizing given the input image and the desired size. + * @param {RawImage} image The image to resize. + * @param {any} size The size to use for resizing the image. + * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. + */ + get_resize_output_image_size(image, size) { + // `size` comes in many forms, so we need to handle them all here: + // 1. `size` is an integer, in which case we resize the image to be a square + + const [srcWidth, srcHeight] = image.size; + + let shortest_edge; + let longest_edge; + + if (this.do_thumbnail) { + // NOTE: custom logic for `Donut` models + const { height, width } = size; + shortest_edge = Math.min(height, width) + } + // Support both formats for backwards compatibility + else if (Number.isInteger(size)) { + shortest_edge = size; + longest_edge = this.config.max_size ?? shortest_edge; + + } else if (size !== undefined) { + // Extract known properties from `size` + shortest_edge = size.shortest_edge; + longest_edge = size.longest_edge; + } + + // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge` + // while keeping the largest dimension <= `longest_edge` + if (shortest_edge !== undefined || longest_edge !== undefined) { + // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/ + // Try resize so that shortest edge is `shortest_edge` (target) + const shortResizeFactor = shortest_edge === undefined + ? 1 // If `shortest_edge` is not set, don't upscale + : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); + + const newWidth = srcWidth * shortResizeFactor; + const newHeight = srcHeight * shortResizeFactor; + + // The new width and height might be greater than `longest_edge`, so + // we downscale again to ensure the largest dimension is `longest_edge` + const longResizeFactor = longest_edge === undefined + ? 1 // If `longest_edge` is not set, don't downscale + : Math.min(longest_edge / newWidth, longest_edge / newHeight); + + // To avoid certain floating point precision issues, we round to 2 decimal places + const finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); + const finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); + + return [finalWidth, finalHeight]; + + } else if (size !== undefined && size.width !== undefined && size.height !== undefined) { + // If `width` and `height` are set, resize to those dimensions + return [size.width, size.height]; + + } else if (this.size_divisibility !== undefined) { + // Rounds the height and width down to the closest multiple of size_divisibility + const newWidth = Math.floor(srcWidth / this.size_divisibility) * this.size_divisibility; + const newHeight = Math.floor(srcHeight / this.size_divisibility) * this.size_divisibility; + return [newWidth, newHeight]; + } else { + throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`); + } + } + + /** + * Resizes the image. + * @param {RawImage} image The image to resize. + * @returns {Promise} The resized image. + */ + async resize(image) { + const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size); + return await image.resize(newWidth, newHeight, { + resample: this.resample, + }); + } + + /** + * @typedef {object} PreprocessedImage + * @property {HeightWidth} original_size The original size of the image. + * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. + * @property {Tensor} pixel_values The pixel values of the preprocessed image. + */ + + /** + * Preprocesses the given image. + * + * @param {RawImage} image The image to preprocess. + * @param {Object} overrides The overrides for the preprocessing options. + * @returns {Promise} The preprocessed image. + */ + async preprocess(image, { + do_normalize = null, + do_pad = null, + do_convert_rgb = null, + do_convert_grayscale = null, + } = {}) { + if (this.do_crop_margin) { + // NOTE: Specific to nougat processors. This is done before resizing, + // and can be interpreted as a pre-preprocessing step. + image = await this.crop_margin(image); + } + + const [srcWidth, srcHeight] = image.size; // original image size + + // Convert image to RGB if specified in config. + if (do_convert_rgb ?? this.do_convert_rgb) { + image = image.rgb(); + } else if (do_convert_grayscale) { + image = image.grayscale(); + } + + // TODO: + // For efficiency reasons, it might be best to merge the resize and center crop operations into one. + + // Resize all images + if (this.do_resize) { + image = await this.resize(image); + } + + // Resize the image using thumbnail method. + if (this.do_thumbnail) { + image = await this.thumbnail(image, this.size, this.resample); + } + + if (this.do_center_crop) { + + let crop_width; + let crop_height; + if (Number.isInteger(this.crop_size)) { + crop_width = this.crop_size; + crop_height = this.crop_size; + } else { + crop_width = this.crop_size.width; + crop_height = this.crop_size.height; + } + + image = await image.center_crop(crop_width, crop_height); + } + + /** @type {HeightWidth} */ + const reshaped_input_size = [image.height, image.width]; + + let pixelData = Float32Array.from(image.data); + let imgDims = [image.height, image.width, image.channels]; + + if (this.do_rescale) { + this.rescale(pixelData); + } + + if (do_normalize ?? this.do_normalize) { + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(image.channels).fill(image_mean); + } + + let image_std = this.image_std; + if (!Array.isArray(this.image_std)) { + image_std = new Array(image.channels).fill(image_mean); + } + + if (image_mean.length !== image.channels || image_std.length !== image.channels) { + throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`); + } + + for (let i = 0; i < pixelData.length; i += image.channels) { + for (let j = 0; j < image.channels; ++j) { + pixelData[i + j] = (pixelData[i + j] - this.image_mean[j]) / this.image_std[j]; + } + } + } + + // do padding after rescaling/normalizing + if (do_pad ?? (this.do_pad && this.pad_size)) { + const padded = this.pad_image(pixelData, [image.width, image.height, image.channels], this.pad_size); + [pixelData, imgDims] = padded; // Update pixel data and image dimensions + } + + // Create HWC tensor + const img = new Tensor('float32', pixelData, imgDims); + + // convert to channel dimension format: + const transposed = transpose(img, [2, 0, 1]); // hwc -> chw + + return { + original_size: [srcHeight, srcWidth], + reshaped_input_size: reshaped_input_size, + pixel_values: transposed, + } + } + + /** + * Calls the feature extraction process on an array of images, + * preprocesses each image, and concatenates the resulting + * features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. + */ + async _call(images, ...args) { + if (!Array.isArray(images)) { + images = [images]; + } + /** @type {PreprocessedImage[]} */ + const imageData = await Promise.all(images.map(x => this.preprocess(x))); + + // Stack pixel values + const pixel_values = stack(imageData.map(x => x.pixel_values), 0); + + return { + pixel_values: pixel_values, + + // Original sizes of images + original_sizes: imageData.map(x => x.original_size), + + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map(x => x.reshaped_input_size), + } + } + +} + +export class SegformerFeatureExtractor extends ImageFeatureExtractor { + + /** + * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps. + * @param {*} outputs Raw outputs of the model. + * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size + * (height, width) of each prediction. If unset, predictions will not be resized. + * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps. + */ + post_process_semantic_segmentation(outputs, target_sizes = null) { + + const logits = outputs.logits; + const batch_size = logits.dims[0]; + + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") + } + + const toReturn = []; + for (let i = 0; i < batch_size; ++i) { + const target_size = target_sizes !== null ? target_sizes[i] : null; + + let data = logits[i]; + + // 1. If target_size is not null, we need to resize the masks to the target size + if (target_size !== null) { + // resize the masks to the target size + data = interpolate(data, target_size, 'bilinear', false); + } + const [height, width] = target_size ?? data.dims.slice(-2); + + const segmentation = new Tensor( + 'int32', + new Int32Array(height * width), + [height, width] + ); + + // Buffer to store current largest value + const buffer = data[0].data; + for (let j = 1; j < data.dims[0]; ++j) { + const row = data[j].data; + for (let k = 0; k < row.length; ++k) { + if (row[k] > buffer[k]) { + buffer[k] = row[k]; + segmentation.data[k] = j; + } + } + } + + // Store which objects have labels + // This is much more efficient that creating a set of the final values + const hasLabel = new Array(data.dims[0]); + const out = segmentation.data; + for (let j = 0; j < out.length; ++j) { + const index = out[j]; + hasLabel[index] = index; + } + /** @type {number[]} The unique list of labels that were detected */ + const labels = hasLabel.filter(x => x !== undefined); + + toReturn.push({ segmentation, labels }); + } + return toReturn; + } +} +export class BitImageProcessor extends ImageFeatureExtractor { } +export class DPTFeatureExtractor extends ImageFeatureExtractor { } +export class GLPNFeatureExtractor extends ImageFeatureExtractor { } +export class CLIPFeatureExtractor extends ImageFeatureExtractor { } +export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { } +export class SiglipImageProcessor extends ImageFeatureExtractor { } +export class ConvNextFeatureExtractor extends ImageFeatureExtractor { + constructor(config) { + super(config); + + /** + * Percentage of the image to crop. Only has an effect if this.size < 384. + */ + this.crop_pct = this.config.crop_pct ?? (224 / 256); + } + + async resize(image) { + const shortest_edge = this.size?.shortest_edge; + if (shortest_edge === undefined) { + throw new Error(`Size dictionary must contain 'shortest_edge' key.`); + } + + if (shortest_edge < 384) { + // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct + const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct); + + const [newWidth, newHeight] = this.get_resize_output_image_size(image, { + shortest_edge: resize_shortest_edge, + }); + + image = await image.resize(newWidth, newHeight, { + resample: this.resample, + }); + + // then crop to (shortest_edge, shortest_edge) + image = await image.center_crop(shortest_edge, shortest_edge); + } else { + // warping (no cropping) when evaluated at 384 or larger + image = await image.resize(shortest_edge, shortest_edge, { + resample: this.resample, + }); + } + + return image; + } +} +export class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor +export class ViTFeatureExtractor extends ImageFeatureExtractor { } +export class ViTImageProcessor extends ImageFeatureExtractor { } + +export class MobileViTFeatureExtractor extends ImageFeatureExtractor { } +export class OwlViTFeatureExtractor extends ImageFeatureExtractor { + /** @type {post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } +} +export class DeiTFeatureExtractor extends ImageFeatureExtractor { } +export class BeitFeatureExtractor extends ImageFeatureExtractor { } +export class DonutFeatureExtractor extends ImageFeatureExtractor { + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageWidth, imageHeight, imageChannels] = imgDims; + + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(imageChannels).fill(image_mean); + } + + let image_std = this.image_std; + if (!Array.isArray(image_std)) { + image_std = new Array(imageChannels).fill(image_mean); + } + + const constant_values = image_mean.map((x, i) => - x / this.image_std[i]); + + return super.pad_image(pixelData, imgDims, padSize, { + center: true, + + // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. + // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 + constant_values: constant_values, + ...options, + }); + } +} +export class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor + +/** + * @typedef {object} DetrFeatureExtractorResultProps + * @property {Tensor} pixel_mask + * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult + */ + +/** + * Detr Feature Extractor. + * + * @extends ImageFeatureExtractor + */ +export class DetrFeatureExtractor extends ImageFeatureExtractor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images) { + const result = await super._call(images); + + // TODO support differently-sized images, for now assume all images are the same size. + // TODO support different mask sizes (not just 64x64) + // Currently, just fill pixel mask with 1s + const maskSize = [result.pixel_values.dims[0], 64, 64]; + const pixel_mask = new Tensor( + 'int64', + new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n), + maskSize + ); + + return { ...result, pixel_mask }; + } + + /** + * Post-processes the outputs of the model (for object detection). + * @param {Object} outputs The outputs of the model that must be post-processed + * @param {Tensor} outputs.logits The logits + * @param {Tensor} outputs.pred_boxes The predicted boxes. + * @return {Object[]} An array of objects containing the post-processed outputs. + */ + + /** @type {post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } + + /** + * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. + * @param {Tensor} class_logits The class logits. + * @param {Tensor} mask_logits The mask logits. + * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks. + * @param {number} num_labels The number of labels. + * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels. + */ + remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { + + let mask_probs_item = []; + let pred_scores_item = []; + let pred_labels_item = []; + + for (let j = 0; j < class_logits.dims[0]; ++j) { + let cls = class_logits[j]; + let mask = mask_logits[j]; + + let pred_label = max(cls.data)[1]; + if (pred_label === num_labels) { + // Is the background, so we ignore it + continue; + } + + let scores = softmax(cls.data); + let pred_score = scores[pred_label]; + if (pred_score > object_mask_threshold) { + mask_probs_item.push(mask); + pred_scores_item.push(pred_score); + pred_labels_item.push(pred_label); + } + } + + return [mask_probs_item, pred_scores_item, pred_labels_item]; + + } + + /** + * Checks whether the segment is valid or not. + * @param {Int32Array} mask_labels Labels for each pixel in the mask. + * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks. + * @param {number} k The class id of the segment. + * @param {number} mask_threshold The mask threshold. + * @param {number} overlap_mask_area_threshold The overlap mask area threshold. + * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels. + */ + check_segment_validity( + mask_labels, + mask_probs, + k, + mask_threshold = 0.5, + overlap_mask_area_threshold = 0.8 + ) { + // mask_k is a 1D array of indices, indicating where the mask is equal to k + let mask_k = []; + let mask_k_area = 0; + let original_area = 0; + + // Compute the area of all the stuff in query k + for (let i = 0; i < mask_labels.length; ++i) { + if (mask_labels[i] === k) { + mask_k.push(i); + ++mask_k_area; + } + + if (mask_probs[k].data[i] >= mask_threshold) { + ++original_area; + } + } + let mask_exists = mask_k_area > 0 && original_area > 0; + + // Eliminate disconnected tiny segments + if (mask_exists) { + // Perform additional check + let area_ratio = mask_k_area / original_area; + mask_exists = area_ratio > overlap_mask_area_threshold; + } + + return [mask_exists, mask_k] + } + + /** + * Computes the segments. + * @param {Tensor[]} mask_probs The mask probabilities. + * @param {number[]} pred_scores The predicted scores. + * @param {number[]} pred_labels The predicted labels. + * @param {number} mask_threshold The mask threshold. + * @param {number} overlap_mask_area_threshold The overlap mask area threshold. + * @param {Set} label_ids_to_fuse The label ids to fuse. + * @param {number[]} target_size The target size of the image. + * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments. + */ + compute_segments( + mask_probs, + pred_scores, + pred_labels, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse = null, + target_size = null, + ) { + let [height, width] = target_size ?? mask_probs[0].dims; + + let segmentation = new Tensor( + 'int32', + new Int32Array(height * width), + [height, width] + ); + let segments = []; + + // 1. If target_size is not null, we need to resize the masks to the target size + if (target_size !== null) { + // resize the masks to the target size + for (let i = 0; i < mask_probs.length; ++i) { + mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false); + } + } + + // 2. Weigh each mask by its prediction score + // NOTE: `mask_probs` is updated in-place + // + // Temporary storage for the best label/scores for each pixel ([height, width]): + let mask_labels = new Int32Array(mask_probs[0].data.length); + let bestScores = new Float32Array(mask_probs[0].data.length); + + for (let i = 0; i < mask_probs.length; ++i) { + let score = pred_scores[i]; + + for (let j = 0; j < mask_probs[i].data.length; ++j) { + mask_probs[i].data[j] *= score + if (mask_probs[i].data[j] > bestScores[j]) { + mask_labels[j] = i; + bestScores[j] = mask_probs[i].data[j]; + } + } + } + + let current_segment_id = 0; + + // let stuff_memory_list = {} + for (let k = 0; k < pred_labels.length; ++k) { + let pred_class = pred_labels[k]; + + // TODO add `should_fuse` + // let should_fuse = pred_class in label_ids_to_fuse + + // Check if mask exists and large enough to be a segment + let [mask_exists, mask_k] = this.check_segment_validity( + mask_labels, + mask_probs, + k, + mask_threshold, + overlap_mask_area_threshold + ) + + if (!mask_exists) { + // Nothing to see here + continue; + } + + // TODO + // if (pred_class in stuff_memory_list) { + // current_segment_id = stuff_memory_list[pred_class] + // } else { + // current_segment_id += 1; + // } + ++current_segment_id; + + + // Add current object segment to final segmentation map + for (let index of mask_k) { + segmentation.data[index] = current_segment_id; + } + + segments.push({ + id: current_segment_id, + label_id: pred_class, + // was_fused: should_fuse, TODO + score: pred_scores[k], + }) + + // TODO + // if(should_fuse){ + // stuff_memory_list[pred_class] = current_segment_id + // } + } + + return [segmentation, segments]; + } + + /** + * Post-process the model output to generate the final panoptic segmentation. + * @param {*} outputs The model output to post process + * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. + * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. + * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask. + * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together. + * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to. + * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} + */ + post_process_panoptic_segmentation( + outputs, + threshold = 0.5, + mask_threshold = 0.5, + overlap_mask_area_threshold = 0.8, + label_ids_to_fuse = null, + target_sizes = null, + ) { + if (label_ids_to_fuse === null) { + console.warn("`label_ids_to_fuse` unset. No instance will be fused.") + label_ids_to_fuse = new Set(); + } + + const class_queries_logits = outputs.logits; // [batch_size, num_queries, num_classes+1] + const masks_queries_logits = outputs.pred_masks; // [batch_size, num_queries, height, width] + + const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width] + + let [batch_size, num_queries, num_labels] = class_queries_logits.dims; + num_labels -= 1; // Remove last class (background) + + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") + } + + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + + let class_logits = class_queries_logits[i]; + let mask_logits = mask_probs[i]; + + let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels); + + if (pred_labels_item.length === 0) { + // No mask found + let [height, width] = target_size ?? mask_logits.dims.slice(-2); + + let segmentation = new Tensor( + 'int32', + new Int32Array(height * width).fill(-1), + [height, width] + ) + toReturn.push({ + segmentation: segmentation, + segments_info: [] + }); + continue; + } + + + // Get segmentation map and segment information of batch item + let [segmentation, segments] = this.compute_segments( + mask_probs_item, + pred_scores_item, + pred_labels_item, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_size, + ) + + toReturn.push({ + segmentation: segmentation, + segments_info: segments + }) + } + + return toReturn; + } + + post_process_instance_segmentation() { + // TODO + throw Error("Not implemented yet"); + } +} + +export class YolosFeatureExtractor extends ImageFeatureExtractor { + /** @type {post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } +} + +/** + * @typedef {object} SamImageProcessorResult + * @property {Tensor} pixel_values + * @property {HeightWidth[]} original_sizes + * @property {HeightWidth[]} reshaped_input_sizes + * @property {Tensor} [input_points] + * @property {Tensor} [input_labels] + */ + +export class SamImageProcessor extends ImageFeatureExtractor { + + /** + * + * @param {any} input_points + * @param {HeightWidth[]} original_sizes + * @param {HeightWidth[]} reshaped_input_sizes + * @returns {Tensor} + */ + reshape_input_points(input_points, original_sizes, reshaped_input_sizes) { + + // Make deep copy to avoid altering user's input + input_points = structuredClone(input_points); + let shape = calculateDimensions(input_points); + + // TODO: add support for 2D input_points + if (shape.length === 3) { + // Correct user's input + shape = [1, ...shape]; + input_points = [input_points]; + } else if (shape.length !== 4) { + throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") + } + + // Reshape input points + for (let i = 0; i < input_points.length; ++i) { // batch_size + let originalImageSize = original_sizes[i]; + let reshapedImageSize = reshaped_input_sizes[i]; + + let resizeFactors = [ + reshapedImageSize[0] / originalImageSize[0], + reshapedImageSize[1] / originalImageSize[1] + ] + + for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size + for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image + for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 + input_points[i][j][k][w] *= resizeFactors[w]; + } + } + } + } + + return new Tensor( + 'float32', + Float32Array.from(input_points.flat(Infinity)), + shape + ) + + } + + /** + * + * @param {any} input_labels + * @param {Tensor} input_points + * @returns {Tensor} + */ + add_input_labels(input_labels, input_points) { + let shape = calculateDimensions(input_labels); + if (shape.length === 2) { + // Correct user's input + shape = [1, ...shape]; + input_labels = [input_labels]; + } else if (shape.length !== 3) { + throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") + } + + if (shape.some((x, i) => x !== input_points.dims[i])) { + throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`) + } + return new Tensor( + 'int64', + input_labels.flat(Infinity).map(BigInt), + shape, + ) + } + /** + * @param {any[]} images The URL(s) of the image(s) to extract features from. + * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user. + * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. + * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. + * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. + * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. + * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. + * @returns {Promise} + */ + async _call(images, input_points = null, input_labels = null) { + // TODO allow user to use preprocessed images + /** @type {SamImageProcessorResult} */ + const processed = await super._call(images); + + if (input_points) { + processed.input_points = this.reshape_input_points( + input_points, processed.original_sizes, processed.reshaped_input_sizes + ); + } + + if (input_labels) { + if (!processed.input_points) { + throw Error("`input_points` must be provided if `input_labels` are provided.") + } + processed.input_labels = this.add_input_labels(input_labels, processed.input_points); + } + + return processed; + } + + /** + * Remove padding and upscale masks to the original image size. + * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. + * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. + * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. + * @param {Object} options Optional parameters for post-processing. + * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. + * @param {boolean} [options.binarize] Whether to binarize the masks. + * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. + * @param {number} [options.pad_size.height] The height the images were padded to. + * @param {number} [options.pad_size.width] The width the images were padded to. + * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. + */ + post_process_masks(masks, original_sizes, reshaped_input_sizes, { + mask_threshold = 0.0, + binarize = true, + pad_size = null, + } = {}) { + // masks: [1, 1, 3, 256, 256] + + const output_masks = []; + + pad_size = pad_size ?? this.pad_size; + + const target_image_size = [pad_size.height, pad_size.width]; + + for (let i = 0; i < original_sizes.length; ++i) { + const original_size = original_sizes[i]; + const reshaped_input_size = reshaped_input_sizes[i]; + + const mask = masks[i]; // [b, c, h, w] + + // TODO: improve + const interpolated_masks = []; + for (let j = 0; j < mask.dims[0]; ++j) { + const m = mask[j]; // 3d tensor + + // Upscale mask to padded size + let interpolated_mask = interpolate(m, target_image_size, 'bilinear', false); + + // Crop mask + interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); + + // Downscale mask + interpolated_mask = interpolate(interpolated_mask, original_size, 'bilinear', false); + + if (binarize) { + const binarizedMaskData = new Uint8Array(interpolated_mask.data.length); + for (let i = 0; i < interpolated_mask.data.length; ++i) { + if (interpolated_mask.data[i] > mask_threshold) { + binarizedMaskData[i] = 1; + } + } + interpolated_mask = new Tensor( + 'bool', + binarizedMaskData, + interpolated_mask.dims + ) + } + + interpolated_masks.push(interpolated_mask); + } + + output_masks.push(stack(interpolated_masks)); + } + + return output_masks; + } +} + +export class Swin2SRImageProcessor extends ImageFeatureExtractor { + pad_image(pixelData, imgDims, padSize, options = {}) { + // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention. + // In other words, the image is padded so that its width and height are multiples of `padSize`. + const [imageWidth, imageHeight, imageChannels] = imgDims; + + return super.pad_image(pixelData, imgDims, { + // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already + // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). + // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. + width: imageWidth + (padSize - imageWidth % padSize) % padSize, + height: imageHeight + (padSize - imageHeight % padSize) % padSize, + }, { + mode: 'symmetric', + center: false, + constant_values: -1, + ...options, + }) + } +} + +export class VitMatteImageProcessor extends ImageFeatureExtractor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @param {RawImage[]} trimaps The trimaps(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images, trimaps) { + if (!Array.isArray(images)) { + images = [images]; + } + if (!Array.isArray(trimaps)) { + trimaps = [trimaps]; + } + + const imageData = await Promise.all(images.map(x => this.preprocess(x))); + const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, { + do_normalize: false, + do_convert_rgb: false, + do_convert_grayscale: true, + }))); + + + // Stack pixel values + const pixel_values = stack(imageData.map( + // Concatenate images and trimaps + (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0) + ), 0); + + return { + pixel_values: pixel_values, + + // Original sizes of images + original_sizes: imageData.map(x => x.original_size), + + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map(x => x.reshaped_input_size), + } + } +} + +export class WhisperFeatureExtractor extends FeatureExtractor { + + constructor(config) { + super(config); + + // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist. + this.config.mel_filters ??= mel_filter_bank( + Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins + this.config.feature_size, // num_mel_filters + 0.0, // min_frequency + 8000.0, // max_frequency + this.config.sampling_rate, // sampling_rate + "slaney", // norm + "slaney", // mel_scale + ); + + this.window = window_function(this.config.n_fft, 'hann'); + } + + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform) { + const { data, dims } = spectrogram( + waveform, + this.window, // window + this.config.n_fft, // frame_length + this.config.hop_length, // hop_length + { + power: 2.0, + mel_filters: this.config.mel_filters, + log_mel: 'log10', + + // Custom + max_num_frames: this.config.nb_max_frames, // 3000 + } + ) + + const maxValue = max(data)[0]; + + for (let i = 0; i < data.length; ++i) { + data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0; + } + + return { data, dims }; + } + + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + validate_audio_inputs(audio, 'WhisperFeatureExtractor'); + + let waveform; + if (audio.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`." + ); + waveform = audio.slice(0, this.config.n_samples); + } else { + // pad with zeros + waveform = new Float32Array(this.config.n_samples); + waveform.set(audio); + } + + const { data, dims } = this._extract_fbank_features(waveform); + + return { + input_features: new Tensor('float32', + data, + [1, ...dims] + ) + }; + } +} + +export class Wav2Vec2FeatureExtractor extends FeatureExtractor { + + /** + * @param {Float32Array} input_values + * @returns {Float32Array} + */ + _zero_mean_unit_var_norm(input_values) { + // TODO support batch? + const sum = input_values.reduce((a, b) => a + b, 0); + const mean = sum / input_values.length; + const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length; + return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7)); + } + + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. + */ + async _call(audio) { + validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor'); + + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + + let input_values = audio; + + // zero-mean and unit-variance normalization + if (this.config.do_normalize) { + input_values = this._zero_mean_unit_var_norm(input_values); + } + + // TODO: allow user to pass in attention mask + const shape = [1, input_values.length]; + return { + input_values: new Tensor('float32', input_values, shape), + attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape) + }; + } +} + +export class ASTFeatureExtractor extends FeatureExtractor { + + + constructor(config) { + super(config); + + const sampling_rate = this.config.sampling_rate; + const mel_filters = mel_filter_bank( + 256, // num_frequency_bins + this.config.num_mel_bins, // num_mel_filters + 20, // min_frequency + Math.floor(sampling_rate / 2), // max_frequency + sampling_rate, // sampling_rate + null, // norm + "kaldi", // mel_scale + true, // triangularize_in_mel_space + ); + + // Do padding: + for (let i = 0; i < mel_filters.length; ++i) { + mel_filters[i].push(0); + } + this.mel_filters = mel_filters; + + this.window = window_function(400, 'hann', { + periodic: false, + }) + + this.mean = this.config.mean; + this.std = this.config.std; + } + + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform, max_length) { + // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` + return spectrogram( + waveform, + this.window, // window + 400, // frame_length + 160, // hop_length + { + fft_length: 512, + power: 2.0, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: 'log', + mel_floor: 1.192092955078125e-07, + remove_dc_offset: true, + + // Custom + max_num_frames: max_length, + transpose: true, + } + ) + } + + + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + validate_audio_inputs(audio, 'ASTFeatureExtractor'); + + const features = this._extract_fbank_features(audio, this.config.max_length); + if (this.config.do_normalize) { + // Normalize the input audio spectrogram to have mean=0, std=0.5 + const denom = this.std * 2; + for (let i = 0; i < features.data.length; ++i) { + features.data[i] = (features.data[i] - this.mean) / denom; + } + } + + return { + input_values: new Tensor('float32', + features.data, + [1, ...features.dims] + ) + }; + } +} + +export class ClapFeatureExtractor extends FeatureExtractor { + + constructor(config) { + super(config); + + this.mel_filters = mel_filter_bank( + this.config.nb_frequency_bins, // num_frequency_bins + this.config.feature_size, // num_mel_filters + this.config.frequency_min, // min_frequency + this.config.frequency_max, // max_frequency + this.config.sampling_rate, // sampling_rate + null, // norm + "htk", // mel_scale + ); + + this.mel_filters_slaney = mel_filter_bank( + this.config.nb_frequency_bins, // num_frequency_bins + this.config.feature_size, // num_mel_filters + this.config.frequency_min, // min_frequency + this.config.frequency_max, // max_frequency + this.config.sampling_rate, // sampling_rate + "slaney", // norm + "slaney", // mel_scale + ); + + this.window = window_function(this.config.fft_window_size, 'hann') + + } + + + /** + * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. + * + * Four different path are possible: + * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram + * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram + * are then stacked together. They will later be used for `feature_fusion`. + * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is + * padded based on `padding`. + * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded + * based on `padding`, and is repeated `4` times. + * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel + * spectrogram will be computed on a random crop of the waveform. + * + * @param {Float32Array|Float64Array} waveform The input waveform. + * @param {number} max_length The maximum length of the waveform. + * @param {string} truncation The truncation strategy to use. + * @param {string} padding The padding strategy to use. + * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. + */ + _get_input_mel(waveform, max_length, truncation, padding) { + + /** @type {{ data: Float32Array; dims: number[]}} */ + let input_mel; + let longer = false; + const diff = waveform.length - max_length; + if (diff > 0) { + if (truncation === 'rand_trunc') { + longer = true; + const idx = Math.floor(Math.random() * (diff + 1)); + waveform = waveform.subarray(idx, idx + max_length); + + input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); + input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze" + } else { + // TODO implement fusion strategy + throw new Error(`Truncation strategy "${truncation}" not implemented`) + } + } else { + if (diff < 0) { + let padded = new Float64Array(max_length); // already padded with zeros + padded.set(waveform); + + if (padding === 'repeat') { + for (let i = waveform.length; i < max_length; i += waveform.length) { + padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); + } + } else if (padding === 'repeatpad') { + for (let i = waveform.length; i < -diff; i += waveform.length) { + padded.set(waveform, i); + } + } + waveform = padded; + } + + if (truncation === 'fusion') { + throw new Error(`Truncation strategy "${truncation}" not implemented`) + } + + input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); + input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze" + } + + return { + ...input_mel, + longer, + } + } + + /** + * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. + * In CLAP, two different filter banks are used depending on the truncation pattern: + * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from + * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` + * is set to `"fusion"`. + * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used + * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original + * implementation when the truncation mode is not `"fusion"`. + * + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number[][]} mel_filters The mel filters to use. + * @param {number} [max_length=null] The maximum number of frames to return. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform, mel_filters, max_length = null) { + // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` + return spectrogram( + waveform, + this.window, // window + this.config.fft_window_size, // frame_length + this.config.hop_length, // hop_length + { + power: 2.0, + mel_filters, + log_mel: 'dB', + + // Custom + max_num_frames: max_length, + do_pad: false, + transpose: true, + } + ) + } + + + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio, { + max_length = null, + } = {}) { + validate_audio_inputs(audio, 'ClapFeatureExtractor'); + + // convert to mel spectrogram, truncate and pad if needed. + const padded_inputs = this._get_input_mel( + audio, + max_length ?? this.config.nb_max_samples, + this.config.truncation, + this.config.padding, + ); + + + return { + input_features: new Tensor('float32', + padded_inputs.data, + [1, ...padded_inputs.dims] + ) + }; + } +} + + + +export class SpeechT5FeatureExtractor extends FeatureExtractor { } + +/** + * Represents a Processor that extracts features from an input. + * @extends Callable + */ +export class Processor extends Callable { + /** + * Creates a new Processor with the given feature extractor. + * @param {FeatureExtractor} feature_extractor The function used to extract features from the input. + */ + constructor(feature_extractor) { + super(); + this.feature_extractor = feature_extractor; + // TODO use tokenizer here? + } + + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input, ...args) { + return await this.feature_extractor(input, ...args); + } +} + +export class SamProcessor extends Processor { + /** + * @borrows SamImageProcessor#_call as _call + */ + async _call(...args) { + return await this.feature_extractor(...args); + } + + /** + * @borrows SamImageProcessor#post_process_masks as post_process_masks + */ + post_process_masks(...args) { + // @ts-ignore + return this.feature_extractor.post_process_masks(...args); + } + /** + * @borrows SamImageProcessor#reshape_input_points as reshape_input_points + */ + reshape_input_points(...args) { + // @ts-ignore + return this.feature_extractor.reshape_input_points(...args); + } +} + +/** + * Represents a WhisperProcessor that extracts features from an audio input. + * @extends Processor + */ +export class WhisperProcessor extends Processor { + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio) + } +} + + +export class Wav2Vec2ProcessorWithLM extends Processor { + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio) + } +} + +export class SpeechT5Processor extends Processor { + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input) { + return await this.feature_extractor(input) + } +} + +export class OwlViTProcessor extends Processor { } + + +////////////////////////////////////////////////// +/** + * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function. + * The chosen processor class is determined by the type specified in the processor config. + * + * **Example:** Load a processor using `from_pretrained`. + * ```javascript + * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en'); + * ``` + * + * **Example:** Run an image through a processor. + * ```javascript + * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * // { + * // "pixel_values": { + * // "dims": [ 1, 3, 224, 224 ], + * // "type": "float32", + * // "data": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ], + * // "size": 150528 + * // }, + * // "original_sizes": [ + * // [ 533, 800 ] + * // ], + * // "reshaped_input_sizes": [ + * // [ 224, 224 ] + * // ] + * // } + * ``` + */ +export class AutoProcessor { + static FEATURE_EXTRACTOR_CLASS_MAPPING = { + WhisperFeatureExtractor, + ViTFeatureExtractor, + MobileViTFeatureExtractor, + OwlViTFeatureExtractor, + CLIPFeatureExtractor, + ChineseCLIPFeatureExtractor, + SiglipImageProcessor, + ConvNextFeatureExtractor, + ConvNextImageProcessor, + SegformerFeatureExtractor, + BitImageProcessor, + DPTFeatureExtractor, + GLPNFeatureExtractor, + BeitFeatureExtractor, + DeiTFeatureExtractor, + DetrFeatureExtractor, + YolosFeatureExtractor, + DonutFeatureExtractor, + NougatImageProcessor, + + ViTImageProcessor, + VitMatteImageProcessor, + SamImageProcessor, + Swin2SRImageProcessor, + Wav2Vec2FeatureExtractor, + SpeechT5FeatureExtractor, + ASTFeatureExtractor, + ClapFeatureExtractor, + } + + static PROCESSOR_CLASS_MAPPING = { + WhisperProcessor, + Wav2Vec2ProcessorWithLM, + SamProcessor, + SpeechT5Processor, + OwlViTProcessor, + } + + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new instance of the Processor class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + } = {}) { + + let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + }) + + // Determine feature extractor class + // TODO: Ensure backwards compatibility with old configs + let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type; + let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key]; + + if (!feature_extractor_class) { + if (preprocessorConfig.size !== undefined) { + // Assume ImageFeatureExtractor + console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`); + feature_extractor_class = ImageFeatureExtractor; + } else { + throw new Error(`Unknown Feature Extractor type: ${key}`); + } + } + + // If no associated processor class, use default + let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor; + + // Instantiate processor and feature extractor + let feature_extractor = new feature_extractor_class(preprocessorConfig); + return new processor_class(feature_extractor); + } +} +////////////////////////////////////////////////// + diff --git a/core/vendor/node_modules/@xenova/transformers/src/tokenizers.js b/core/vendor/node_modules/@xenova/transformers/src/tokenizers.js new file mode 100644 index 000000000..a786cd1ed --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/tokenizers.js @@ -0,0 +1,4316 @@ + +/** + * @file Tokenizers are used to prepare textual inputs for a model. + * + * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence. + * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`. + * ```javascript + * import { AutoTokenizer } from '@xenova/transformers'; + * + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); + * const { input_ids } = await tokenizer('I love transformers!'); + * // Tensor { + * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n], + * // dims: [1, 6], + * // type: 'int64', + * // size: 6, + * // } + * ``` + * + * @module tokenizers + */ + +import { + Callable, + reverseDictionary, + escapeRegExp, + isIntegralNumber, + mergeArrays, +} from './utils/core.js'; + +import { + getModelJSON, +} from './utils/hub.js'; + +import { max, min, round } from './utils/maths.js'; +import { Tensor } from './utils/tensor.js'; + +import { + PriorityQueue, + TokenLattice, + CharTrie, +} from './utils/data-structures.js'; + +import { Template } from '@huggingface/jinja'; + + +/** + * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties. + * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used. + * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions + */ + +/** + * Loads a tokenizer from the specified path. + * @param {string} pretrained_model_name_or_path The path to the tokenizer directory. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * @returns {Promise} A promise that resolves with information about the loaded tokenizer. + */ +async function loadTokenizer(pretrained_model_name_or_path, options) { + + const info = await Promise.all([ + getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options), + getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options), + ]) + + // Override legacy option if `options.legacy` is not null + if (options.legacy !== null) { + info[1].legacy = options.legacy; + } + return info; +} + + +/** + * Helper function to split a string on a regex, but keep the delimiters. + * This is required, because the JavaScript `.split()` method does not keep the delimiters, + * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting). + * @param {string} text The text to split. + * @param {RegExp} regex The regex to split on. + * @returns {string[]} The split string. + */ +function regexSplit(text, regex) { + const result = []; + let prev = 0; + for (const match of text.matchAll(regex)) { + const fullMatch = match[0]; + if (prev < match.index) { + result.push(text.slice(prev, match.index)); + } + if (fullMatch.length > 0) { + result.push(fullMatch); + } + prev = match.index + fullMatch.length; + } + if (prev < text.length) { + result.push(text.slice(prev)); + } + return result; +} + + +/** + * Helper method to construct a pattern from a config object. + * @param {Object} pattern The pattern object. + * @param {boolean} invert Whether to invert the pattern. + * @returns {RegExp|null} The compiled pattern. + */ +function createPattern(pattern, invert = true) { + + if (pattern.Regex !== undefined) { + // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~). + // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed). + // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used. + // For this reason, it is necessary to remove these backslashes before creating the regex. + // See https://stackoverflow.com/a/63007777/13989043 for more information + const regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary + return new RegExp(regex, 'gu'); + + } else if (pattern.String !== undefined) { + const escaped = escapeRegExp(pattern.String); + // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split() + return new RegExp(invert ? escaped : `(${escaped})`, 'gu'); + + } else { + console.warn('Unknown pattern type:', pattern) + return null; + } +} + +/** + * Helper function to convert an Object to a Map + * @param {Object} obj The object to convert. + * @returns {Map} The map. + */ +function objectToMap(obj) { + return new Map(Object.entries(obj)); +} + +/** + * Helper function to convert a tensor to a list before decoding. + * @param {Tensor} tensor The tensor to convert. + * @returns {number[]} The tensor as a list. + */ +function prepareTensorForDecode(tensor) { + const dims = tensor.dims; + switch (dims.length) { + case 1: + return tensor.tolist(); + case 2: + if (dims[0] !== 1) { + throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.'); + } + return tensor.tolist()[0]; + default: + throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`) + } +} + +/** + * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms + * @param {string} text The text to clean up. + * @returns {string} The cleaned up text. + */ +function clean_up_tokenization(text) { + // Clean up a list of simple English tokenization artifacts + // like spaces before punctuations and abbreviated forms + return text.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"); +} + +/** + * Helper function to remove accents from a string. + * @param {string} text The text to remove accents from. + * @returns {string} The text with accents removed. + */ +function remove_accents(text) { + return text.replace(/[\u0300-\u036f]/g, ''); +} + +/** + * Helper function to lowercase a string and remove accents. + * @param {string} text The text to lowercase and remove accents from. + * @returns {string} The lowercased text with accents removed. + */ +function lowercase_and_remove_accent(text) { + return remove_accents(text.toLowerCase()); +} + +/** + * Helper function to fuse consecutive values in an array equal to the specified value. + * @param {string[]} arr The input array + * @param {any} value The value to fuse on. + * @param {Map} mapping The mapping from input domain to value. + */ +function fuse(arr, value, mapping) { + const fused = []; + let i = 0; + while (i < arr.length) { + fused.push(arr[i]) + if ((mapping.get(arr[i]) ?? value) !== value) { + ++i; + continue; + } + + while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) { + ++i; + } + } + + return fused; +} + +/** + * Split a string on whitespace. + * @param {string} text The text to split. + * @returns {string[]} The split string. + */ +function whitespace_split(text) { + return text.match(/\S+/g) || []; +} + +const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E'; + +/** + * Represent a token added by the user on top of the existing Model vocabulary. + * AddedToken can be configured to specify the behavior they should have in various situations like: + * - Whether they should only match single words + * - Whether to include any whitespace on its left or right + */ +class AddedToken { + /** + * Creates a new instance of AddedToken. + * @param {Object} config Added token configuration object. + * @param {string} config.content The content of the added token. + * @param {number} config.id The id of the added token. + * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. + * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. + * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. + * @param {boolean} [config.normalized=false] Whether this token should be normalized. + * @param {boolean} [config.special=false] Whether this token is special. + */ + constructor(config) { + this.content = config.content; + this.id = config.id; + this.single_word = config.single_word ?? false; + this.lstrip = config.lstrip ?? false; + this.rstrip = config.rstrip ?? false; + this.special = config.special ?? false; + this.normalized = config.normalized ?? null; + } +} + +/** + * Abstract base class for tokenizer models. + * + * @extends Callable + */ +export class TokenizerModel extends Callable { + /** + * Creates a new instance of TokenizerModel. + * @param {Object} config The configuration object for the TokenizerModel. + */ + constructor(config) { + super(); + this.config = config; + + /** @type {string[]} */ + this.vocab = []; + + /** + * A mapping of tokens to ids. + * @type {Map} + */ + this.tokens_to_ids = new Map(); + + this.unk_token_id = undefined; + this.unk_token = undefined; + this.end_of_word_suffix = undefined; + + /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */ + this.fuse_unk = this.config.fuse_unk ?? false; + } + + /** + * Instantiates a new TokenizerModel instance based on the configuration object provided. + * @param {Object} config The configuration object for the TokenizerModel. + * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. + * @returns {TokenizerModel} A new instance of a TokenizerModel. + * @throws Will throw an error if the TokenizerModel type in the config is not recognized. + */ + static fromConfig(config, ...args) { + switch (config.type) { + case 'WordPiece': + return new WordPieceTokenizer(config); + case 'Unigram': + // @ts-ignore + return new Unigram(config, ...args); + + case 'BPE': + return new BPE(config); + + default: + if (config.vocab) { + // @ts-ignore + return new LegacyTokenizerModel(config, ...args); + } + throw new Error(`Unknown TokenizerModel type: ${config.type}`); + } + } + + /** + * Internal function to call the TokenizerModel instance. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded token IDs. + */ + _call(tokens) { + let ids = this.encode(tokens); + if (this.fuse_unk) { + // Fuse unknown tokens + ids = fuse(ids, this.unk_token_id, this.tokens_to_ids); + } + return ids; + } + + /** + * Encodes a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded tokens. + * @throws Will throw an error if not implemented in a subclass. + */ + encode(tokens) { + throw Error("encode should be implemented in subclass.") + } + + /** + * Converts a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to convert. + * @returns {number[]} The converted token IDs. + */ + convert_tokens_to_ids(tokens) { + return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id); + } + + /** + * Converts a list of token IDs into a list of tokens. + * @param {number[]} ids The token IDs to convert. + * @returns {string[]} The converted tokens. + */ + convert_ids_to_tokens(ids) { + return ids.map(i => this.vocab[i] ?? this.unk_token); + } +} + +/** + * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens. + * @extends TokenizerModel + */ +class WordPieceTokenizer extends TokenizerModel { + /** + * @param {Object} config The configuration object. + * @param {Object} config.vocab A mapping of tokens to ids. + * @param {string} config.unk_token The unknown token string. + * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords. + * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word. + */ + constructor(config) { + super(config); + /** + * A mapping of tokens to ids. + * @type {Map} + */ + this.tokens_to_ids = objectToMap(config.vocab); + + /** + * The id of the unknown token. + * @type {number} + */ + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + + /** + * The unknown token string. + * @type {string} + */ + this.unk_token = config.unk_token; + + /** + * The maximum number of characters allowed per word. + * @type {number} + */ + this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; + + /** + * An array of tokens. + * @type {string[]} + */ + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + } + + /** + * Encodes an array of tokens using WordPiece encoding. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} An array of encoded tokens. + */ + encode(tokens) { + const outputTokens = []; + for (const token of tokens) { + const chars = [...token]; + if (chars.length > this.max_input_chars_per_word) { + outputTokens.push(this.unk_token); + continue; + } + + let isUnknown = false; + let start = 0; + const subTokens = []; + + while (start < chars.length) { + let end = chars.length; + let currentSubstring = null; + while (start < end) { + let substr = chars.slice(start, end).join(''); + + if (start > 0) { + substr = this.config.continuing_subword_prefix + substr; + } + if (this.tokens_to_ids.has(substr)) { + currentSubstring = substr; + break; + } + + --end; + } + if (currentSubstring === null) { + isUnknown = true; + break; + } + subTokens.push(currentSubstring); + start = end; + } + if (isUnknown) { + outputTokens.push(this.unk_token); + } else { + outputTokens.push(...subTokens); + } + } + + return outputTokens; + } + +} + +/** + * Class representing a Unigram tokenizer model. + * @extends TokenizerModel + */ +class Unigram extends TokenizerModel { + /** + * Create a new Unigram tokenizer model. + * @param {Object} config The configuration object for the Unigram model. + * @param {number} config.unk_id The ID of the unknown token + * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores. + * @param {Object} moreConfig Additional configuration object for the Unigram model. + */ + constructor(config, moreConfig) { + super(config); + + const vocabSize = config.vocab.length; + this.vocab = new Array(vocabSize); + this.scores = new Array(vocabSize); + for (let i = 0; i < vocabSize; ++i) { + const piece = config.vocab[i]; + this.vocab[i] = piece[0]; + this.scores[i] = piece[1]; + } + + this.unk_token_id = config.unk_id; + this.unk_token = this.vocab[config.unk_id]; + + this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i])); + this.bosToken = ' '; // beginning of a sentence token + + this.bosTokenId = this.tokens_to_ids.get(this.bosToken); // NOTE: may be undefined + this.eosToken = moreConfig.eos_token; + + this.eosTokenId = this.tokens_to_ids.get(this.eosToken); + this.unkToken = this.vocab[this.unk_token_id]; + + this.minScore = min(this.scores)[0]; + + this.unkScore = this.minScore - 10.0; + this.scores[this.unk_token_id] = this.unkScore; + + this.trie = new CharTrie(); + this.trie.extend(this.vocab); + + // NOTE: `fuse_unk` is hardcoded to true for Unigram models + // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119 + this.fuse_unk = true; + } + + /** + * Populates lattice nodes. + * @param {TokenLattice} lattice The token lattice to populate with nodes. + */ + populateNodes(lattice) { + const sentence = lattice.sentence; + const len = sentence.length; + let beginPos = 0; + while (beginPos < len) { + const mblen = 1; + let hasSingleNode = false; + const tokens = []; + + for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) { + tokens.push(token); + const tokenId = this.tokens_to_ids.get(token); + const tokenScore = this.scores[tokenId]; + const n = token.length; + lattice.insert(beginPos, n, tokenScore, tokenId); + if (!hasSingleNode && n === mblen) { + hasSingleNode = true; + } + } + if (!hasSingleNode) { + lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id); + } + beginPos += mblen; + } + } + + /** + * Encodes an array of tokens into an array of subtokens using the unigram model. + * + * @param {string} normalized The normalized string. + * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model. + */ + tokenize(normalized) { + const lattice = new TokenLattice(normalized, this.bosTokenId, this.eosTokenId); + this.populateNodes(lattice); + return lattice.tokens(); + } + + /** + * Encodes an array of tokens using Unigram encoding. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} An array of encoded tokens. + */ + encode(tokens) { + const toReturn = []; + for (const token of tokens) { + const tokenized = this.tokenize(token); + toReturn.push(...tokenized); + } + return toReturn; + } + +} + +/** + * Returns list of utf-8 byte and a mapping to unicode strings. + * Specifically avoids mapping to whitespace/control characters the BPE code barfs on. + * @returns {Object} Object with utf-8 byte keys and unicode string values. + */ +const BYTES_TO_UNICODE = (() => { + // Returns list of utf-8 byte and a mapping to unicode strings. + // We specifically avoids mapping to whitespace/control characters + // the bpe code barfs on. + + const bs = [ + ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)), + ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)), + ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)), + ]; + const cs = bs.slice(); + let n = 0; + for (let b = 0; b < 256; ++b) { + if (!bs.includes(b)) { + bs.push(b); + cs.push(256 + n); + n += 1; + } + } + const ccs = cs.map(n => String.fromCharCode(n)); + return Object.fromEntries(bs.map((b, i) => [b, ccs[i]])); +})(); + +const UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE); + + +/** + * @typedef {Object} BPENode + * @property {string} token The token associated with the node + * @property {number} bias A positional bias for the node. + * @property {number} [score] The score of the node. + * @property {BPENode} [prev] The previous node in the linked list. + * @property {BPENode} [next] The next node in the linked list. + */ + +/** + * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens. + * @extends TokenizerModel + */ +class BPE extends TokenizerModel { + /** + * Create a BPE instance. + * @param {Object} config The configuration object for BPE. + * @param {Object} config.vocab A mapping of tokens to ids. + * @param {string} config.unk_token The unknown token used for out of vocabulary words. + * @param {string} config.end_of_word_suffix The suffix to place at the end of each word. + * @param {string} [config.continuing_subword_suffix] The suffix to insert between words. + * @param {Array} config.merges An array of BPE merges as strings. + */ + constructor(config) { + super(config); + + this.BPE_SPLIT_TOKEN = ' '; + + /** @type {Map} */ + this.tokens_to_ids = objectToMap(config.vocab); + + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + this.unk_token = config.unk_token; + + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + + this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i])); + this.merges = config.merges.map(x => x.split(this.BPE_SPLIT_TOKEN)); + + this.end_of_word_suffix = config.end_of_word_suffix; + + // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`) + this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; + + this.byte_fallback = this.config.byte_fallback ?? false; + + if (this.byte_fallback) { + this.text_encoder = new TextEncoder(); + } + + /** @type {Map} */ + this.cache = new Map(); + } + + /** + * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority + * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. + * @param {string} token The token to encode. + * @returns {string[]} The BPE encoded tokens. + */ + bpe(token) { + if (token.length === 0) { + return []; + } + + const cached = this.cache.get(token); + if (cached !== undefined) { + return cached; + } + + const word = Array.from(token); + if (this.end_of_word_suffix) { + word[word.length - 1] += this.end_of_word_suffix; + } + + let result = []; + if (word.length > 1) { + // Create a priority queue to store the nodes that will be merged. + // The comparator function compares the scores of the nodes. + const queue = new PriorityQueue((a, b) => a.score < b.score); + + // Construct a doubly-linked list of nodes that will be inserted into the priority queue, + // starting with the individual characters. We also populate each node with a positional + // bias to break ties in the priority queue. + let startingNode = { + token: word[0], + bias: 0, + prev: null, + next: null, + } + + let previousNode = startingNode + for (let i = 1; i < word.length; ++i) { + const currentNode = { + bias: i / word.length, // Add fractional component to break ties + token: word[i], + prev: previousNode, + next: null, + } + previousNode.next = currentNode + this._add_node(queue, previousNode) + previousNode = currentNode + } + + while (!queue.isEmpty()) { + // Get the next node with the highest priority + const node = queue.pop(); + + // Check that this merge is still possible + if (node.deleted || !node.next || node.next.deleted) continue; + + // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted. + // This is because they will both be replaced by a new node representing the merge result. + node.deleted = true; + node.next.deleted = true; + + // Next, we fix the node that comes before the current node (i.e., left side of the merge). + if (node.prev) { + + // Make a shallow copy of the previous node + const newPreviousNode = { ...node.prev }; + + // Mark the old previous node as deleted. This avoids erroneous merges later, + // because there may still be references to this node in the priority queue. + node.prev.deleted = true; + node.prev = newPreviousNode; + + // Update the reference of the previous node, by pointing its previous node to this new previous node. + if (newPreviousNode.prev) { + newPreviousNode.prev.next = newPreviousNode; + } else { + // If the previous of the previous node does not exist, it means that + // `newPreviousNode` must be the new `startingNode`. + startingNode = newPreviousNode; + } + } + + // Create a new node which represents the result of the merge. + const merged = { + token: node.token + node.next.token, + bias: node.bias, + prev: node.prev, + next: node.next.next, + } + + // We now consider where we can add the new merged node to the priority queue: + // 1. prev <-> merged + if (merged.prev) { + merged.prev.next = merged; + this._add_node(queue, merged.prev); + } else { + // If `merged.prev` does not exist, then `merged` must be the new `startingNode`. + startingNode = merged; + } + + // 2. merged <-> next + if (merged.next) { + merged.next.prev = merged; + this._add_node(queue, merged); + } + } + + // Traverse the linked list, starting from the `startingNode`, and collect the tokens. + for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) { + result.push(currentNode.token); + } + } else { + result = word; + } + + // Possibly append suffix + if (this.continuing_subword_suffix) { + // Do not append suffix to the last token + for (let i = 0; i < result.length - 1; ++i) { + result[i] += this.continuing_subword_suffix; + } + } + + // Save the result to the cache + this.cache.set(token, result); + + return result; + } + + + /** + * Helper function to add a node to the priority queue. + * @param {PriorityQueue} queue + * @param {BPENode} node + * @private + */ + _add_node(queue, node) { + // `score` is a measure of the merge priority: lower means higher priority + // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list) + // We also add a fractional component to the score to break ties (with the earlier character having higher priority) + const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token); + if (rank !== undefined) { + node.score = rank + node.bias; + queue.push(node); + } + } + + /** + * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. + * @param {string[]} tokens The input sequence of tokens to encode. + * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. + */ + encode(tokens) { + const outputTokens = []; + + for (const token of tokens) { + const bpe_token_list = this.bpe(token); + + for (const t of bpe_token_list) { + if (this.tokens_to_ids.has(t)) { + outputTokens.push(t); + } else { + if (this.byte_fallback) { + outputTokens.push( + ...Array.from(this.text_encoder.encode(t)) + .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`) + ); + } else { + outputTokens.push(this.unk_token); + } + } + } + } + + return outputTokens; + } + +} + +/** + * Legacy tokenizer class for tokenizers with only a vocabulary. + */ +class LegacyTokenizerModel extends TokenizerModel { + /** + * Create a LegacyTokenizerModel instance. + * @param {Object} config The configuration object for LegacyTokenizerModel. + * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids. + * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model. + */ + constructor(config, moreConfig) { + super(config); + + /**@type {Map} */ + this.tokens_to_ids = objectToMap( + moreConfig.target_lang + ? config.vocab[moreConfig.target_lang] + : config.vocab + ); + + this.bos_token = moreConfig.bos_token; + this.bos_token_id = this.tokens_to_ids.get(this.bos_token); + + this.eos_token = moreConfig.eos_token; + this.eos_token_id = this.tokens_to_ids.get(this.eos_token); + + this.pad_token = moreConfig.pad_token; + this.pad_token_id = this.tokens_to_ids.get(this.pad_token); + + this.unk_token = moreConfig.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 [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + } + + encode(tokens) { + return tokens; + } +} + + +/** + * A base class for text normalization. + * @abstract + */ +class Normalizer extends Callable { + /** + * @param {Object} config The configuration object for the normalizer. + */ + constructor(config) { + super(); + this.config = config; + } + + /** + * Factory method for creating normalizers from config objects. + * @static + * @param {Object} config The configuration object for the normalizer. + * @returns {Normalizer} A Normalizer object. + * @throws {Error} If an unknown Normalizer type is specified in the config. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case 'BertNormalizer': + return new BertNormalizer(config); + case 'Precompiled': + return new Precompiled(config); + case 'Sequence': + return new NormalizerSequence(config); + case 'Replace': + return new Replace(config); + case 'NFC': + return new NFC(config); + case 'NFKC': + return new NFKC(config); + case 'NFKD': + return new NFKD(config); + case 'Strip': + return new StripNormalizer(config); + case 'StripAccents': + return new StripAccents(config); + case 'Lowercase': + return new Lowercase(config); + case 'Prepend': + return new Prepend(config); + default: + throw new Error(`Unknown Normalizer type: ${config.type}`); + } + } + + /** + * Normalize the input text. + * @abstract + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + * @throws {Error} If this method is not implemented in a subclass. + */ + normalize(text) { + throw Error("normalize should be implemented in subclass.") + } + + /** + * Alias for {@link Normalizer#normalize}. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + _call(text) { + return this.normalize(text); + } + +} + +/** + * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression. + * @extends Normalizer + */ +class Replace extends Normalizer { + /** + * Normalize the input text by replacing the pattern with the content. + * @param {string} text The input text to be normalized. + * @returns {string} The normalized text after replacing the pattern with the content. + */ + normalize(text) { + const pattern = createPattern(this.config.pattern); + return pattern === null + ? text + : text.replaceAll(pattern, this.config.content); + } +} + +/** + * A normalizer that applies Unicode normalization form C (NFC) to the input text. + * @extends Normalizer + */ +class NFC extends Normalizer { + /** + * Normalize the input text by applying Unicode normalization form C (NFC). + * @param {string} text The input text to be normalized. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.normalize('NFC') + return text; + } +} + +/** + * NFKC Normalizer. + * @extends Normalizer + */ +class NFKC extends Normalizer { + /** + * Normalize text using NFKC normalization. + * @param {string} text The text to be normalized. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.normalize('NFKC') + return text; + } +} +/** + * NFKD Normalizer. + * @extends Normalizer + */ +class NFKD extends Normalizer { + /** + * Normalize text using NFKD normalization. + * @param {string} text The text to be normalized. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.normalize('NFKD') + return text; + } +} + +/** + * A normalizer that strips leading and/or trailing whitespace from the input text. + */ +class StripNormalizer extends Normalizer { + /** + * Strip leading and/or trailing whitespace from the input text. + * @param {string} text The input text. + * @returns {string} The normalized text. + */ + normalize(text) { + if (this.config.strip_left && this.config.strip_right) { + // Fast path to avoid an extra trim call + text = text.trim(); + } else { + if (this.config.strip_left) { + text = text.trimStart(); + } + if (this.config.strip_right) { + text = text.trimEnd(); + } + } + return text; + } +} + +/** + * StripAccents normalizer removes all accents from the text. + * @extends Normalizer + */ +class StripAccents extends Normalizer { + /** + * Remove all accents from the text. + * @param {string} text The input text. + * @returns {string} The normalized text without accents. + */ + normalize(text) { + text = remove_accents(text); + return text; + } +} + +/** + * A Normalizer that lowercases the input string. + * @extends Normalizer + */ +class Lowercase extends Normalizer { + /** + * Lowercases the input string. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.toLowerCase(); + return text; + } +} + +/** + * A Normalizer that prepends a string to the input string. + * @extends Normalizer + */ +class Prepend extends Normalizer { + /** + * Prepends the input string. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + text = this.config.prepend + text; + return text; + } +} + +/** + * A Normalizer that applies a sequence of Normalizers. + * @extends Normalizer + */ +class NormalizerSequence extends Normalizer { + /** + * Create a new instance of NormalizerSequence. + * @param {Object} config The configuration object. + * @param {Object[]} config.normalizers An array of Normalizer configuration objects. + */ + constructor(config) { + super(config); + this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x)); + } + /** + * Apply a sequence of Normalizers to the input text. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + return this.normalizers.reduce((t, normalizer) => { + return normalizer.normalize(t); + }, text); + } +} + +/** + * A class representing a normalizer used in BERT tokenization. + * @extends Normalizer + */ +class BertNormalizer extends Normalizer { + /** + * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. + * + * @param {string} text The input text to tokenize. + * @returns {string} The tokenized text with whitespace added around CJK characters. + */ + _tokenize_chinese_chars(text) { + /* Adds whitespace around any CJK character. */ + const output = []; + for (let i = 0; i < text.length; ++i) { + const char = text[i]; + const cp = char.charCodeAt(0); + if (this._is_chinese_char(cp)) { + output.push(" "); + output.push(char); + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + + /** + * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character. + * + * A "chinese character" is defined as anything in the CJK Unicode block: + * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) + * + * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name. + * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana. + * Those alphabets are used to write space-separated words, so they are not treated specially + * and are handled like all other languages. + * + * @param {number} cp The Unicode codepoint to check. + * @returns {boolean} True if the codepoint represents a CJK character, false otherwise. + */ + _is_chinese_char(cp) { + return ( + (cp >= 0x4E00 && cp <= 0x9FFF) + || (cp >= 0x3400 && cp <= 0x4DBF) + || (cp >= 0x20000 && cp <= 0x2A6DF) + || (cp >= 0x2A700 && cp <= 0x2B73F) + || (cp >= 0x2B740 && cp <= 0x2B81F) + || (cp >= 0x2B820 && cp <= 0x2CEAF) + || (cp >= 0xF900 && cp <= 0xFAFF) + || (cp >= 0x2F800 && cp <= 0x2FA1F) + ) + } + /** + * Strips accents from the given text. + * @param {string} text The text to strip accents from. + * @returns {string} The text with accents removed. + */ + stripAccents(text) { + return text.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); + } + + + /** + * Checks whether `char` is a control character. + * @param {string} char The character to check. + * @returns {boolean} Whether `char` is a control character. + * @private + */ + _is_control(char) { + switch (char) { + case '\t': + case '\n': + case '\r': + // These are technically control characters but we count them as whitespace characters. + return false; + + default: + // Check if unicode category starts with C: + // Cc - Control + // Cf - Format + // Co - Private Use + // Cs - Surrogate + return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); + } + } + + /** + * Performs invalid character removal and whitespace cleanup on text. + * @param {string} text The text to clean. + * @returns {string} The cleaned text. + * @private + */ + _clean_text(text) { + const output = []; + for (const char of text) { + const cp = char.charCodeAt(0); + if (cp === 0 || cp === 0xFFFD || this._is_control(char)) { + continue; + } + if (/^\s$/.test(char)) { // is whitespace + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + /** + * Normalizes the given text based on the configuration. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + if (this.config.clean_text) { + text = this._clean_text(text); + } + + if (this.config.handle_chinese_chars) { + text = this._tokenize_chinese_chars(text); + } + + if (this.config.lowercase) { + text = text.toLowerCase(); + + if (this.config.strip_accents !== false) { + text = this.stripAccents(text); + } + } else if (this.config.strip_accents) { + text = this.stripAccents(text); + } + + return text; + } +} + +/** + * A callable class representing a pre-tokenizer used in tokenization. Subclasses + * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic. + * @extends Callable + */ +class PreTokenizer extends Callable { + /** + * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. + * + * @static + * @param {Object} config A configuration object for the pre-tokenizer. + * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. + * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. + */ + static fromConfig(config) { + if (config === null) return null; + + switch (config.type) { + case 'BertPreTokenizer': + return new BertPreTokenizer(config); + case 'Sequence': + return new PreTokenizerSequence(config); + case 'WhitespaceSplit': + return new WhitespaceSplit(config); + case 'Metaspace': + return new MetaspacePreTokenizer(config); + + case 'ByteLevel': + return new ByteLevelPreTokenizer(config); + case 'Split': + return new SplitPreTokenizer(config); + case 'Punctuation': + return new PunctuationPreTokenizer(config); + case 'Digits': + return new DigitsPreTokenizer(config); + case 'Replace': + return new ReplacePreTokenizer(config); + default: + throw new Error(`Unknown PreTokenizer type: ${config.type}`); + } + } + + /** + * Method that should be implemented by subclasses to define the specific pre-tokenization logic. + * + * @abstract + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} The pre-tokenized text. + * @throws {Error} If the method is not implemented in the subclass. + */ + pre_tokenize_text(text, options) { + throw Error("pre_tokenize_text should be implemented in subclass.") + } + + /** + * Tokenizes the given text into pre-tokens. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + pre_tokenize(text, options) { + return (Array.isArray(text) + ? text.map(x => this.pre_tokenize_text(x, options)) + : this.pre_tokenize_text(text, options) + ).flat(); + } + + /** + * Alias for {@link PreTokenizer#pre_tokenize}. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + _call(text, options) { + return this.pre_tokenize(text, options); + } +} + +/** + * @extends PreTokenizer + */ +class BertPreTokenizer extends PreTokenizer { + /** + * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme + * similar to that used in the original implementation of BERT. + * + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + // Construct a pattern which matches the rust implementation: + // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11 + // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters) + this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu'); + } + /** + * Tokenizes a single text using the BERT pre-tokenization scheme. + * + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.trim().match(this.pattern) || []; + } +} + +/** + * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords. + * @extends PreTokenizer + */ +class ByteLevelPreTokenizer extends PreTokenizer { + /** + * Creates a new instance of the `ByteLevelPreTokenizer` class. + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + this.config = config; + + /** + * @type {boolean} Whether to add a leading space to the first word. + * This allows to treat the leading word just as any other word. + */ + this.add_prefix_space = this.config.add_prefix_space; + + /** + * @type {boolean} Whether the post processing step should trim offsets + * to avoid including whitespaces. + * @todo Use this in the pretokenization step. + */ + this.trim_offsets = this.config.trim_offsets; + + /** + * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting. + * Set it to False if you want to use your own splitting. Defaults to true. + */ + this.use_regex = this.config.use_regex ?? true; + 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 = BYTES_TO_UNICODE; + this.text_encoder = new TextEncoder(); + } + + /** + * Tokenizes a single piece of text using byte-level tokenization. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + // Add a leading space if the option is enabled + if (this.add_prefix_space && !text.startsWith(' ')) { + text = ' ' + text; + } + + // Split on whitespace and punctuation + const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text]; + + // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) + return tokens.map( + token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('') + ); + } +} + +/** + * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior + */ + +/** + * Splits text using a given pattern. + * @extends PreTokenizer + */ +class SplitPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. + * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string. + * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex. + * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. + * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern. + */ + constructor(config) { + super(); + this.config = config; + // TODO support all behaviours (config.behavior) + + this.pattern = createPattern(this.config.pattern, this.config.invert); + } + + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + if (this.pattern === null) { + return []; + } + + if (this.config.invert) { + return text.match(this.pattern) || []; + } else { + return regexSplit(text, this.pattern); + } + } +} + +/** + * Splits text based on punctuation. + * @extends PreTokenizer + */ +class PunctuationPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu'); + } + + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.match(this.pattern) || []; + } +} + + +/** + * Splits text based on digits. + * @extends PreTokenizer + */ +class DigitsPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {boolean} config.individual_digits Whether to split on individual digits. + */ + constructor(config) { + super(); + this.config = config; + + // Construct a pattern which matches the rust implementation: + const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`; + this.pattern = new RegExp(digit_pattern, 'gu'); + } + + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.match(this.pattern) || []; + } +} + +/** + * @typedef {Object} PostProcessedOutput + * @property {string[]} tokens List of token produced by the post-processor. + * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor. + */ + + +/** + * @typedef {Object} EncodingSingle + * @property {number[]} input_ids List of token ids to be fed to a model. + * @property {number[]} attention_mask List of token type ids to be fed to a model + * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model + */ + + +/** + * @extends Callable + */ +class PostProcessor extends Callable { + + /** + * @param {Object} config The configuration for the post-processor. + */ + constructor(config) { + super(); + this.config = config; + } + + /** + * Factory method to create a PostProcessor object from a configuration object. + * + * @param {Object} config Configuration object representing a PostProcessor. + * @returns {PostProcessor} A PostProcessor object created from the given configuration. + * @throws {Error} If an unknown PostProcessor type is encountered. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case 'TemplateProcessing': + return new TemplateProcessing(config); + + case 'ByteLevel': + return new ByteLevelPostProcessor(config); + + case 'RobertaProcessing': + return new RobertaProcessing(config); + case 'BertProcessing': + return new BertProcessing(config); + + default: + throw new Error(`Unknown PostProcessor type: ${config.type}`); + } + } + + /** + * Method to be implemented in subclass to apply post-processing on the given tokens. + * + * @param {Array} tokens The input tokens to be post-processed. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + * @throws {Error} If the method is not implemented in subclass. + */ + post_process(tokens, ...args) { + throw Error("post_process should be implemented in subclass.") + } + + /** + * Alias for {@link PostProcessor#post_process}. + * @param {Array} tokens The text or array of texts to post-process. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + */ + _call(tokens, ...args) { + return this.post_process(tokens, ...args); + } +} + +/** + * A post-processor that adds special tokens to the beginning and end of the input. + */ +class BertProcessing extends PostProcessor { + /** + * @param {Object} config The configuration for the post-processor. + * @param {string[]} config.cls The special tokens to add to the beginning of the input. + * @param {string[]} config.sep The special tokens to add to the end of the input. + */ + constructor(config) { + super(config); + // TODO use all of config: add_prefix_space, trim_offsets + + this.cls = config.cls[0]; + this.sep = config.sep[0]; + } + + /** + * Adds the special tokens to the beginning and end of the input. + * @param {string[]} tokens The input tokens. + * @param {string[]} [tokens_pair=null] An optional second set of input tokens. + * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end. + */ + post_process(tokens, tokens_pair = null, { + add_special_tokens = true, + } = {}) { + if (add_special_tokens) { + tokens = mergeArrays([this.cls], tokens, [this.sep]); + } + + let token_type_ids = new Array(tokens.length).fill(0); + if (tokens_pair !== null) { + // NOTE: It is intended to add 2 EOS tokens after the first set of tokens + // https://github.com/huggingface/tokenizers/issues/983 + const middle = (add_special_tokens && this instanceof RobertaProcessing) + ? [this.sep] + : []; + const after = add_special_tokens ? [this.sep] : []; + + tokens = mergeArrays(tokens, middle, tokens_pair, after); + token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1)); + } + return { tokens, token_type_ids }; + } +} +class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing + +/** + * Post processor that replaces special tokens in a template with actual tokens. + * @extends PostProcessor + */ +class TemplateProcessing extends PostProcessor { + /** + * Creates a new instance of `TemplateProcessing`. + * @param {Object} config The configuration options for the post processor. + * @param {Array} config.single The template for a single sequence of tokens. + * @param {Array} config.pair The template for a pair of sequences of tokens. + */ + constructor(config) { + super(config); + + this.single = config.single; + this.pair = config.pair; + } + + /** + * Replaces special tokens in the template with actual tokens. + * @param {string[]} tokens The list of tokens for the first sequence. + * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). + * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens. + */ + post_process(tokens, tokens_pair = null, { + add_special_tokens = true, + } = {}) { + const type = tokens_pair === null ? this.single : this.pair + + let processedTokens = []; + let types = []; + for (const item of type) { + if ('SpecialToken' in item) { + if (add_special_tokens) { + processedTokens.push(item.SpecialToken.id); + types.push(item.SpecialToken.type_id); + } + } else if ('Sequence' in item) { + if (item.Sequence.id === 'A') { + processedTokens = mergeArrays(processedTokens, tokens); + types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id)); + + } else if (item.Sequence.id === 'B') { + processedTokens = mergeArrays(processedTokens, tokens_pair); + types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id)); + } + } + } + return { tokens: processedTokens, token_type_ids: types }; + } +} + +/** + * A PostProcessor that returns the given tokens as is. + * @extends PostProcessor + */ +class ByteLevelPostProcessor extends PostProcessor { + /** + * Post process the given tokens. + * @param {string[]} tokens The list of tokens for the first sequence. + * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). + * @returns {PostProcessedOutput} An object containing the post-processed tokens. + */ + post_process(tokens, tokens_pair = null) { + if (tokens_pair) { + tokens = mergeArrays(tokens, tokens_pair); + } + return { tokens }; + } +} + +/** + * The base class for token decoders. + * @extends Callable + */ +class Decoder extends Callable { + + /** + * Creates an instance of `Decoder`. + * + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + this.config = config; + + /** @type {AddedToken[]} */ + this.added_tokens = []; + this.end_of_word_suffix = null; + this.trim_offsets = config.trim_offsets; + } + + /** + * Creates a decoder instance based on the provided configuration. + * + * @param {Object} config The configuration object. + * @returns {Decoder} A decoder instance. + * @throws {Error} If an unknown decoder type is provided. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case 'WordPiece': + return new WordPieceDecoder(config); + case 'Metaspace': + return new MetaspaceDecoder(config); + case 'ByteLevel': + return new ByteLevelDecoder(config); + + case 'Replace': + return new ReplaceDecoder(config); + case 'ByteFallback': + return new ByteFallback(config); + case 'Fuse': + return new FuseDecoder(config); + case 'Strip': + return new StripDecoder(config); + + case 'Sequence': + return new DecoderSequence(config); + + case 'CTC': + return new CTCDecoder(config); + case 'BPEDecoder': + return new BPEDecoder(config); + default: + throw new Error(`Unknown Decoder type: ${config.type}`); + } + } + + /** + * Calls the `decode` method. + * + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + _call(tokens) { + return this.decode(tokens); + } + + /** + * Decodes a list of tokens. + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + decode(tokens) { + return this.decode_chain(tokens).join(''); + } + + /** + * Apply the decoder to a list of tokens. + * + * @param {string[]} tokens The list of tokens. + * @returns {string[]} The decoded list of tokens. + * @throws {Error} If the `decode_chain` method is not implemented in the subclass. + */ + decode_chain(tokens) { + throw Error("`decode_chain` should be implemented in subclass.") + } + +} + +class ReplaceDecoder extends Decoder { + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const pattern = createPattern(this.config.pattern); + return pattern === null + ? tokens + : tokens.map(token => token.replaceAll(pattern, this.config.content)) + } +} + + +class ByteFallback extends Decoder { + constructor(config) { + super(config); + + this.text_decoder = new TextDecoder(); + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + + const new_tokens = []; + let previous_byte_tokens = []; + + for (const token of tokens) { + let bytes = null; + if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) { + const byte = parseInt(token.slice(3, 5), 16); + if (!isNaN(byte)) { + bytes = byte; + } + } + if (bytes !== null) { + previous_byte_tokens.push(bytes); + } else { + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); + new_tokens.push(string); + previous_byte_tokens = []; + } + new_tokens.push(token); + } + } + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); + new_tokens.push(string); + previous_byte_tokens = []; + } + + return new_tokens; + } +} + +/** + * Fuse simply fuses all tokens into one big string. + * It's usually the last decoding step anyway, but this decoder + * exists incase some decoders need to happen after that step + */ +class FuseDecoder extends Decoder { + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return [tokens.join('')]; + } +} + + +class StripDecoder extends Decoder { + constructor(config) { + super(config); + + this.content = this.config.content; + this.start = this.config.start; + this.stop = this.config.stop; + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map(token => { + let start_cut = 0; + for (let i = 0; i < this.start; ++i) { + if (token[i] === this.content) { + start_cut = i + 1; + continue; + } else { + break; + } + } + + let stop_cut = token.length; + for (let i = 0; i < this.stop; ++i) { + const index = token.length - i - 1; + if (token[index] === this.content) { + stop_cut = index; + continue; + } else { + break; + } + } + + return token.slice(start_cut, stop_cut) + }); + } +} + +/** + * A decoder that decodes a list of WordPiece tokens into a single string. + * @extends Decoder + */ +class WordPieceDecoder extends Decoder { + + /** + * Creates a new instance of WordPieceDecoder. + * @param {Object} config The configuration object. + * @param {string} config.prefix The prefix used for WordPiece encoding. + * @param {boolean} config.cleanup Whether to cleanup the decoded string. + */ + constructor(config) { + super(config); + this.cleanup = config.cleanup; + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map((token, i) => { + if (i !== 0) { + if (token.startsWith(this.config.prefix)) { + // NOTE: .replace() is intended; only replace first occurrence + token = token.replace(this.config.prefix, ''); + } else { + token = ' ' + token; + } + } + if (this.cleanup) { + token = clean_up_tokenization(token) + } + + return token; + }); + } +} + +/** + * Byte-level decoder for tokenization output. Inherits from the `Decoder` class. + * @extends Decoder + */ +class ByteLevelDecoder extends Decoder { + + /** + * Create a `ByteLevelDecoder` object. + * @param {Object} config Configuration object. + */ + constructor(config) { + super(config); + + this.byte_decoder = UNICODE_TO_BYTES; + this.text_decoder = new TextDecoder("utf-8", { + fatal: false, + ignoreBOM: true, + }); + + this.end_of_word_suffix = null; + } + + /** + * Convert an array of tokens to string by decoding each byte. + * @param {string[]} tokens Array of tokens to be decoded. + * @returns {string} The decoded string. + */ + convert_tokens_to_string(tokens) { + const text = tokens.join(''); + const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c])); + const decoded_text = this.text_decoder.decode(byteArray); + return decoded_text; + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + // TODO move to base class (like HF) + // tokens === filtered_tokens + + // To avoid mixing byte-level and unicode for byte-level BPT + // we need to build string separately for added tokens and byte-level tokens + // cf. https://github.com/huggingface/transformers/issues/1133 + const sub_texts = []; + let current_sub_text = []; + for (const token of tokens) { + // tokens sent here are already filtered, so we don't need to do this + // if (skip_special_tokens && this.all_special_ids.includes(token)) { + // continue; + // } + + if (this.added_tokens.find(x => x.content === token) !== undefined) { + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + current_sub_text = []; + } + sub_texts.push(token); + } else { + current_sub_text.push(token); + } + } + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + } + + // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options + + return sub_texts; + } +} + +/** + * The CTC (Connectionist Temporal Classification) decoder. + * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs + */ +class CTCDecoder extends Decoder { + + constructor(config) { + super(config); + + this.pad_token = this.config.pad_token; + this.word_delimiter_token = this.config.word_delimiter_token; + this.cleanup = this.config.cleanup; + } + /** + * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. + * @param {string[]} tokens Array of tokens to be decoded. + * @returns {string} The decoded string. + */ + convert_tokens_to_string(tokens) { + if (tokens.length === 0) return ''; + + // group same tokens into non-repeating tokens in CTC style decoding + const grouped_tokens = [tokens[0]]; + for (let i = 1; i < tokens.length; ++i) { + if (tokens[i] !== grouped_tokens.at(-1)) { + grouped_tokens.push(tokens[i]); + } + } + + // filter self.pad_token which is used as CTC-blank token + const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token); + + let text = filtered_tokens.join(''); + if (this.cleanup) { + // cleanup and replace delimiter token + text = clean_up_tokenization(text) + .replaceAll(this.word_delimiter_token, ' ') + .trim(); + } + return text; + } + + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return [this.convert_tokens_to_string(tokens)]; + } +} + +/** + * Apply a sequence of decoders. + * @extends Decoder + */ +class DecoderSequence extends Decoder { + + /** + * Creates a new instance of DecoderSequence. + * @param {Object} config The configuration object. + * @param {Decoder[]} config.decoders The list of decoders to apply. + */ + constructor(config) { + super(config); + this.decoders = config.decoders.map(x => Decoder.fromConfig(x)); + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + // Use reduce to apply each decoder to the tokens + return this.decoders.reduce((toks, decoder) => { + return decoder.decode_chain(toks); + }, tokens); + } + +} + +class BPEDecoder extends Decoder { + constructor(config) { + super(config); + + this.suffix = this.config.suffix; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map((token, i) => { + return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ') + }); + } +} + +// Custom decoder for VITS +class VitsDecoder extends Decoder { + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + let decoded = ''; + for (let i = 1; i < tokens.length; i += 2) { + decoded += tokens[i]; + } + return [decoded]; + } +} + + +/** + * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested, + * and returns a list of tokens. + * @extends PreTokenizer + */ +class MetaspacePreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration object for the MetaspacePreTokenizer. + * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token. + * @param {string} config.replacement The character to replace spaces with. + * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character. + * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme. + */ + constructor(config) { + super(); + + this.addPrefixSpace = config.add_prefix_space; + this.replacement = config.replacement; + this.strRep = config.str_rep || this.replacement; + this.prepend_scheme = config.prepend_scheme ?? 'always'; + } + + /** + * This method takes a string, replaces spaces with the replacement character, + * adds a prefix space if requested, and returns a new list of tokens. + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] The options for the pre-tokenization. + * @param {number} [options.section_index] The index of the section to pre-tokenize. + * @returns {string[]} A new list of pre-tokenized tokens. + */ + pre_tokenize_text(text, { + section_index = undefined, + } = {}) { + + let normalized = text.replaceAll(' ', this.strRep); + + if ( + // We add a prefix space if: + // (1) The addPrefixSpace option is enabled and the normalized + // token does not already start with the replacement character. + (this.addPrefixSpace && !normalized.startsWith(this.replacement)) + + // and (2) either: + // (a) prepend_scheme is 'always' + // (b) prepend_scheme is 'first' and this is the first section + && ( + this.prepend_scheme === 'always' || + (this.prepend_scheme === 'first' && section_index === 0) + ) + ) { + normalized = this.strRep + normalized; + } + return [normalized]; + } +} + +/** + * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization. + * @extends Decoder + */ +class MetaspaceDecoder extends Decoder { + /** + * Constructs a new MetaspaceDecoder object. + * @param {Object} config The configuration object for the MetaspaceDecoder. + * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string. + * @param {string} config.replacement The string to replace spaces with. + */ + constructor(config) { + super(config); + + this.addPrefixSpace = config.add_prefix_space; + this.replacement = config.replacement; + } + + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const result = []; + for (let i = 0; i < tokens.length; ++i) { + let normalized = tokens[i].replaceAll(this.replacement, ' '); + if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) { + normalized = normalized.substring(1); + } + result.push(normalized); + } + return result; + } +} + +/** + * A normalizer that applies a precompiled charsmap. + * This is useful for applying complex normalizations in C++ and exposing them to JavaScript. + * @extends Normalizer + * @param {Object} config The configuration object for the Precompiled normalizer. + * @param {Object} config.precompiled_charsmap The precompiled charsmap object. + */ +class Precompiled extends Normalizer { + /** + * Create a new instance of Precompiled normalizer. + * @param {Object} config The configuration object. + * @param {any} config.precompiled_charsmap Precompiled chars mapping. + */ + constructor(config) { + super(config); + this.charsmap = config.precompiled_charsmap; + } + + /** + * Normalizes the given text by applying the precompiled charsmap. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule), + // there are 5 pre-defined normalization rules: + // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default) + // 2. nfkc: original NFKC normalization. + // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing) + // 4. nfkc_cf: nfkc + Unicode case folding. + // 5. identity: no normalization + // + // For now, we only implement the default (nmt_nfkc). + // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules. + // TODO: detect when a different `this.charsmap` is used. + + text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters + text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space + + if (text.includes('\uFF5E')) { + // To match the sentencepiece implementation 100%, we must handle a very strange edge-case. + // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E). + // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character, + // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character. + const parts = text.split('\uFF5E'); + text = parts.map(part => part.normalize('NFKC')).join('\uFF5E'); + } else { + text = text.normalize('NFKC'); + } + + return text; + } +} + +/** + * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text. + * @extends PreTokenizer + */ +class PreTokenizerSequence extends PreTokenizer { + /** + * Creates an instance of PreTokenizerSequence. + * @param {Object} config The configuration object for the pre-tokenizer sequence. + * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations. + */ + constructor(config) { + super(); + this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x)); + } + + /** + * Applies each pre-tokenizer in the sequence to the input text in turn. + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} The pre-tokenized text. + */ + pre_tokenize_text(text, options) { + // Use reduce to apply each tokenizer to the text + return this.tokenizers.reduce((preTokenizedText, tokenizer) => { + return tokenizer.pre_tokenize(preTokenizedText, options); + }, [text]); + } +} + +/** + * Splits a string of text by whitespace characters into individual tokens. + * @extends PreTokenizer + */ +class WhitespaceSplit extends PreTokenizer { + /** + * Creates an instance of WhitespaceSplit. + * @param {Object} config The configuration object for the pre-tokenizer sequence. + */ + constructor(config) { + super(); + } + /** + * Pre-tokenizes the input text by splitting it on whitespace characters. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. + */ + pre_tokenize_text(text, options) { + return whitespace_split(text); + } +} + +// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`) +class ReplacePreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. + * @param {string} config.content What to replace the pattern with. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = createPattern(this.config.pattern); + this.content = this.config.content; + } + + /** + * Pre-tokenizes the input text by replacing certain characters. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by replacing certain characters. + */ + pre_tokenize_text(text, options) { + if (this.pattern === null) { + return [text]; + } + return [text.replaceAll(this.pattern, this.config.content)]; + } +} + +const SPECIAL_TOKEN_ATTRIBUTES = [ + 'bos_token', + 'eos_token', + 'unk_token', + 'sep_token', + 'pad_token', + 'cls_token', + 'mask_token', + // additional_special_tokens (TODO) +] + +/** + * + * Helper function for padding values of an object, which are each arrays. + * NOTE: No additional checks are made here for validity of arguments. + * @param {Record} item The input object. + * @param {number} length The length to pad to. + * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key. + * @param {'right'|'left'} side Which side to pad the array. + * @private + */ +function padHelper(item, length, value_fn, side) { + for (const key of Object.keys(item)) { + const diff = length - item[key].length; + const value = value_fn(key); + + const padData = new Array(diff).fill(value); + item[key] = side === 'right' + ? mergeArrays(item[key], padData) + : mergeArrays(padData, item[key]); + } +} + +/** + * Helper function for truncating values of an object, which are each arrays. + * NOTE: No additional checks are made here for validity of arguments. + * @param {Record} item The input object. + * @param {number} length The length to truncate to. + * @private + */ +function truncateHelper(item, length) { + // Setting .length to a lower value truncates the array in-place: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length + for (const key of Object.keys(item)) { + item[key].length = length; + } +} + + +export class PreTrainedTokenizer extends Callable { + return_token_type_ids = false; + + _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}`; + + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(); + + this._tokenizer_config = tokenizerConfig; + + // Construct parts of the tokenizer from the JSON + this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer); + this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer); + this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig); + this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor); + this.decoder = Decoder.fromConfig(tokenizerJSON.decoder); + + // Add added_tokens to model + this.special_tokens = []; + this.all_special_ids = []; + + /** @type {AddedToken[]} */ + this.added_tokens = []; + for (const addedToken of tokenizerJSON.added_tokens) { + const token = new AddedToken(addedToken); + this.added_tokens.push(token); + + this.model.tokens_to_ids.set(token.content, token.id); + this.model.vocab[token.id] = token.content; + + if (token.special) { + this.special_tokens.push(token.content); + this.all_special_ids.push(token.id); + } + } + + // Update additional_special_tokens + this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? []; + this.special_tokens.push(...this.additional_special_tokens); + this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates + + if (this.decoder) { + // Slight hack, but it prevents code duplication: + this.decoder.added_tokens = this.added_tokens; + + // Another slight hack to add `end_of_word_suffix` (if present) to the decoder + // This is needed for cases where BPE model and ByteLevel decoder are used + // For more information, see https://github.com/xenova/transformers.js/issues/74 + // TODO: save this to the decoder when exporting? + this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; + } + + + this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp( + this.added_tokens.map(x => `${x.lstrip ? '\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\s*' : ''}`).join('|') + ) : null; + + // Set mask token if present (otherwise will be undefined, which is fine) + 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(tokenizerConfig, 'unk_token'); + this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token); + + this.model_max_length = tokenizerConfig.model_max_length; + + /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */ + this.remove_space = tokenizerConfig.remove_space; + + this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true; + this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false; + + // TODO allow user to change this + /** @type {'right'|'left'} */ + this.padding_side = 'right'; + + this.legacy = false; + + this.chat_template = tokenizerConfig.chat_template ?? null; + this._compiled_template_cache = new Map(); + } + + /** + * Returns the value of the first matching key in the tokenizer config object. + * @param {...string} keys One or more keys to search for in the tokenizer config object. + * @returns {string|null} The value associated with the first matching key, or null if no match is found. + * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". + */ + getToken(...keys) { + for (const key of keys) { + const item = this._tokenizer_config[key]; + + if (!item) continue; + + if (typeof item === 'object') { + if (item.__type === 'AddedToken') { + return item.content; + } else { + throw Error(`Unknown token: ${item}`); + } + } else { + return item; + } + } + return null; + } + + /** + * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. + * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + legacy = null, + } = {}) { + + const info = await loadTokenizer(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + legacy, + }) + + // @ts-ignore + return new this(...info); + } + + /** + * @typedef {number[]|number[][]|Tensor} BatchEncodingItem + * + * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. + * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. + * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. + * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. + */ + + /** + * Encode/tokenize the given text(s). + * @param {string|string[]} text The text to tokenize. + * @param {Object} options An optional object containing the following properties: + * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. + * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. + * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. + * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. + * @returns {BatchEncoding} Object to be passed to the model. + */ + _call( + // Required positional arguments + text, + + // Optional keyword arguments + { + text_pair = null, + add_special_tokens = true, + padding = false, + truncation = null, + max_length = null, + return_tensor = true, // Different to HF + } = {}, + ) { + + const isBatched = Array.isArray(text); + + /** @type {EncodingSingle[]} */ + let encodedTokens; + + if (isBatched) { + if (text.length === 0) { + throw Error('text array must be non-empty') + } + + if (text_pair !== null) { + if (!Array.isArray(text_pair)) { + throw Error('text_pair must also be an array') + + } else if (text.length !== text_pair.length) { + throw Error('text and text_pair must have the same length') + } + + encodedTokens = text.map( + (t, i) => this._encode_plus(t, text_pair[i], { add_special_tokens }) + ) + + } else { + encodedTokens = text.map(x => this._encode_plus(x, null, { add_special_tokens })); + } + + } else { + if (text === null) { + throw Error('text may not be null') + } + + if (Array.isArray(text_pair)) { + throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).') + } + + // For single input, we just wrap in an array, and then unwrap later. + encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens })]; + } + // At this point, tokens is batched: [batch_size, tokens] + // However, array may be jagged. So, we pad to max_length + + if (max_length === null) { + if (padding === 'max_length') { + max_length = this.model_max_length; + } else { + // Calculate max length from sequences + max_length = max(encodedTokens.map(x => x.input_ids.length))[0]; + } + } else { + if (!truncation) { + 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.`) + } + } + + // Ensure it is less than model max length + max_length = Math.min(max_length, this.model_max_length) + + if (padding || truncation) { + + // Perform padding and/or truncation + for (let i = 0; i < encodedTokens.length; ++i) { + if (encodedTokens[i].input_ids.length === max_length) { + continue; + + } else if (encodedTokens[i].input_ids.length > max_length) { + // possibly truncate + if (truncation) { + truncateHelper(encodedTokens[i], max_length); + } + + } else { // t.length < max_length + // possibly pad + if (padding) { + padHelper( + encodedTokens[i], + max_length, + key => key === 'input_ids' ? this.pad_token_id : 0, + this.padding_side + ); + } + } + } + } + + const result = {}; + + if (return_tensor) { + if (!(padding && truncation)) { + // Not, guaranteed that all items have same length, so + // we perform additional check + + if ( + encodedTokens.some(x => { + for (const key of Object.keys(x)) { + if (x[key].length !== encodedTokens[0][key]?.length) { + return true; + } + } + return false; + }) + ) { + 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." + ) + } + } + + // Now we actually convert to tensor + // NOTE: In the same way as the python library, we return a batched tensor, regardless of + // whether we have a single input or multiple inputs. + const dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; + + for (const key of Object.keys(encodedTokens[0])) { + result[key] = new Tensor('int64', + BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)), + dims + ); + } + + } else { + for (const key of Object.keys(encodedTokens[0])) { + result[key] = encodedTokens.map(x => x[key]); + } + + // If not returning a tensor, we match the input type + if (!isBatched) { + // Input was not batched, so we unwrap + for (const key of Object.keys(result)) { + result[key] = result[key][0]; + } + } + } + + return /** @type {BatchEncoding} */(result); + } + + /** + * Encodes a single text using the preprocessor pipeline of the tokenizer. + * + * @param {string|null} text The text to encode. + * @returns {string[]|null} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + + // Actual function which does encoding, for a single text + // First, we take care of special tokens. Needed to avoid issues arising from + // normalization and/or pretokenization (which may not preserve special tokens) + const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text]; + + const tokens = sections.map((x, section_index) => { + const addedToken = this.added_tokens.find(t => t.content === x); + if (addedToken !== undefined) { + // Ignore added tokens + return x + } else { + if (this.remove_space === true) { + x = x.trim().split(/\s+/).join(' '); + } + if (this.do_lowercase_and_remove_accent) { + x = lowercase_and_remove_accent(x); + } + + if (this.normalizer !== null) { + x = this.normalizer(x); + } + + const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, { + section_index, + }) : [x]; + + const tokens = this.model(sectionTokens); + + return tokens; + } + }).flat(); + + return tokens; + } + + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {string|null} text_pair The optional second text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @returns {EncodingSingle} An object containing the encoded text. + * @private + */ + _encode_plus(text, text_pair = null, { + add_special_tokens = true, + } = {}) { + // Function called by users to encode possibly multiple texts + const tokens = this._encode_text(text); + const tokens2 = this._encode_text(text_pair); + + const combinedTokens = this.post_processor + ? this.post_processor(tokens, tokens2, { add_special_tokens }) + : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) }; + + const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens); + + const result = { + input_ids, + attention_mask: new Array(input_ids.length).fill(1), + } + if (this.return_token_type_ids && combinedTokens.token_type_ids) { + result.token_type_ids = combinedTokens.token_type_ids; + } + return result; + } + + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {string|null} text_pair The optional second text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @returns {number[]} An array of token IDs representing the encoded text(s). + */ + encode(text, text_pair = null, { + add_special_tokens = true, + } = {}) { + const { input_ids } = this._encode_plus(text, text_pair, { + add_special_tokens, + }); + return input_ids; + } + + /** + * Decode a batch of tokenized sequences. + * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. + * @param {Object} decode_args (Optional) Object with decoding arguments. + * @returns {string[]} List of decoded sequences. + */ + batch_decode(batch, decode_args = {}) { + if (batch instanceof Tensor) { + batch = batch.tolist(); + } + return batch.map(x => this.decode(x, decode_args)); + } + + /** + * Decodes a sequence of token IDs back to a string. + * + * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode. + * @param {Object} [decode_args={}] + * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. + * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. + * + * @returns {string} The decoded string. + * @throws {Error} If `token_ids` is not a non-empty array of integers. + */ + decode( + token_ids, + decode_args = {}, + ) { + if (token_ids instanceof Tensor) { + token_ids = prepareTensorForDecode(token_ids); + } + + if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) { + throw Error("token_ids must be a non-empty array of integers."); + } + + return this.decode_single(token_ids, decode_args) + } + + /** + * Decode a single list of token ids to a string. + * @param {number[]} token_ids List of token ids to decode + * @param {Object} decode_args Optional arguments for decoding + * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding + * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. + * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. + * @returns {string} The decoded string + */ + decode_single( + token_ids, + { + skip_special_tokens = false, + clean_up_tokenization_spaces = null, + } + ) { + let tokens = this.model.convert_ids_to_tokens(token_ids); + if (skip_special_tokens) { + tokens = tokens.filter(x => !this.special_tokens.includes(x)); + } + + // If `this.decoder` is null, we just join tokens with a space: + // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835 + /** @type {string} */ + let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' '); + + // Slight hack, but prevents having to pass `skip_special_tokens` to + // each call to `decode`, which would lead to code duplication. + if (this.decoder && this.decoder.end_of_word_suffix) { + decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' '); + if (skip_special_tokens) { + decoded = decoded.trim(); + } + } + + if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { + decoded = clean_up_tokenization(decoded); + } + + return decoded; + } + + get default_chat_template() { + if (!this._warned_about_chat_template) { + console.warn( + "No chat template is defined for this tokenizer - using a default chat template " + + "that implements the ChatML format. If the default is not appropriate for " + + "your model, please set `tokenizer.chat_template` to an appropriate template. " + + "See https://huggingface.co/docs/transformers/main/chat_templating for more information." + ) + this._warned_about_chat_template = true; // TODO move to logger.warning_once() + } + + return this._default_chat_template; + } + + /** + * @typedef {Object} Message + * @property {string} role The role of the message (e.g., "user" or "assistant" or "system"). + * @property {string} content The content of the message. + */ + + /** + * Converts a list of message objects with `"role"` and `"content"` keys to a list of token + * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to + * determine the format and control tokens to use when converting. When chat_template is None, it will fall back + * to the default_chat_template specified at the class level. + * + * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. + * + * **Example:** Applying a chat template to a conversation. + * + * ```javascript + * import { AutoTokenizer } from "@xenova/transformers"; + * + * const tokenizer = await AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1"); + * + * const chat = [ + * { "role": "user", "content": "Hello, how are you?" }, + * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, + * { "role": "user", "content": "I'd like to show off how chat templating works!" }, + * ] + * + * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); + * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" + * + * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); + * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] + * ``` + * + * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If + * this is not passed, the model's default chat template will be used instead. + * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate + * the start of an assistant message. This is useful when you want to generate a response from the model. + * Note that this argument will be passed to the chat template, and so it must be supported in the + * template for this argument to have any effect. + * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. + * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. + * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. + * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. + * If not specified, the tokenizer's `max_length` attribute will be used as a default. + * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. + * @returns {string | Tensor | number[]| number[][]} The tokenized output. + */ + apply_chat_template(conversation, { + chat_template = null, + add_generation_prompt = false, + tokenize = true, + padding = false, + truncation = false, + max_length = null, + return_tensor = true, + } = {}) { + + chat_template ??= this.chat_template ?? this.default_chat_template; + + // Compilation function uses a cache to avoid recompiling the same template + let compiledTemplate = this._compiled_template_cache.get(chat_template); + if (compiledTemplate === undefined) { + compiledTemplate = new Template(chat_template); + this._compiled_template_cache.set(chat_template, compiledTemplate); + } + + const special_tokens_map = Object.create(null); + for (const key of SPECIAL_TOKEN_ATTRIBUTES) { + const value = this.getToken(key); + if (value) { + special_tokens_map[key] = value; + } + } + + const rendered = compiledTemplate.render({ + messages: conversation, + add_generation_prompt: add_generation_prompt, + + ...special_tokens_map, + }); + + if (tokenize) { + return this._call(rendered, { + add_special_tokens: false, + padding, + truncation, + max_length, + return_tensor, + }).input_ids; + } + + return rendered; + } +} + +/** + * BertTokenizer is a class used to tokenize text for BERT models. + * @extends PreTrainedTokenizer + */ +export class BertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +/** + * Albert tokenizer + * @extends PreTrainedTokenizer + */ +export class AlbertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class MobileBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class SqueezeBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class DebertaTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class DebertaV2Tokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class HerbertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class ConvBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class RoFormerTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} +export class DistilBertTokenizer extends PreTrainedTokenizer { } +export class CamembertTokenizer extends PreTrainedTokenizer { } +export class XLMTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.') + } +} +export class ElectraTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; +} + +export class T5Tokenizer extends PreTrainedTokenizer { } +export class GPT2Tokenizer extends PreTrainedTokenizer { + _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}` +} +export class BartTokenizer extends PreTrainedTokenizer { } +export class MBartTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + + this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; + this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x)); + this.lang_to_token = x => x; // Identity function + } + + /** + * Helper function to build translation inputs for an `MBartTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +} +export class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer + +export class RobertaTokenizer extends PreTrainedTokenizer { } + +export class BloomTokenizer extends GPT2Tokenizer { // NOTE: `GPT2Tokenizer` to get the correct chat template + + constructor(tokenizerJSON, tokenizerConfig) { + // Override the default (invalid) regex of the pretokenizer. + // For more information, see https://github.com/xenova/transformers.js/issues/94 + const splitChars = '.,!?\u2026\u3002\uff0c\u3001\u0964\u06d4\u060c'; + const patternObject = tokenizerJSON.pre_tokenizer?.pretokenizers[0]?.pattern; + if (patternObject && patternObject.Regex === ` ?[^(\\s|[${splitChars}])]+`) { + patternObject.Regex = ` ?[^\\s${splitChars}]+`; + } + super(tokenizerJSON, tokenizerConfig); + } +} + +const SPIECE_UNDERLINE = "▁"; + +export class LlamaTokenizer extends PreTrainedTokenizer { + _default_chat_template = `{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<>\n' + system_message + '\n<>\n\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<>\n' + content.strip() + '\n<>\n\n' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}` + + DEFAULT_SYSTEM_PROMPT = + "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your " + + "answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure " + + "that your responses are socially unbiased and positive in nature.\n\n" + + "If a question does not make any sense, or is not factually coherent, explain why instead of answering something not " + + "correct. If you don't know the answer to a question, please don't share false information." + + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.use_default_system_prompt = tokenizerConfig.use_default_system_prompt ?? false; + + this.legacy = tokenizerConfig.legacy ?? true; + if (!this.legacy) { + // See https://github.com/huggingface/transformers/pull/24565 for more information + this.normalizer = null; + this.pre_tokenizer = new MetaspacePreTokenizer({ + replacement: SPIECE_UNDERLINE, + add_prefix_space: true, + prepend_scheme: "first", + }); + } + } + + /** + * Helper function to handle legacy encoding of SPM tokenizers. + * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387 + * @param {string} text The text to encode. + * @returns {string[]} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + + if (this.legacy || text.length === 0) { + return super._encode_text(text); + } + + let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " ")); + if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) { + tokens = tokens.slice(1); + } + return tokens; + } + + get default_chat_template() { + return super.default_chat_template + .replaceAll('USE_DEFAULT_PROMPT', this.use_default_system_prompt ? 'true' : 'false') + .replaceAll('DEFAULT_SYSTEM_MESSAGE', this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n", "\\n").replaceAll("'", "\\'")); + } +} +export class CodeLlamaTokenizer extends LlamaTokenizer { } // NOTE: `LlamaTokenizer` to get the correct chat template + +export class XLMRobertaTokenizer extends PreTrainedTokenizer { } +export class MPNetTokenizer extends PreTrainedTokenizer { } + +export class FalconTokenizer extends PreTrainedTokenizer { } + +export class GPTNeoXTokenizer extends PreTrainedTokenizer { } + +export class EsmTokenizer extends PreTrainedTokenizer { } + +/** + * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`. + * @param {PreTrainedTokenizer} self The tokenizer instance. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + * @private + */ +function _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) { + if (!('language_codes' in self) || !Array.isArray(self.language_codes)) { + throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.') + } + if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) { + throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.') + } + if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') { + throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.') + } + const src_lang_token = generate_kwargs.src_lang; + const tgt_lang_token = generate_kwargs.tgt_lang; + + // Check that the target language is valid: + if (!self.language_codes.includes(tgt_lang_token)) { + throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`); + } + + // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default. + if (src_lang_token !== undefined) { + // Check that the source language is valid: + if (!self.language_codes.includes(src_lang_token)) { + throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`); + } + + // In the same way as the Python library, we override the post-processor + // to force the source language to be first: + for (const item of self.post_processor.config.single) { + if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) { + item.SpecialToken.id = self.lang_to_token(src_lang_token); + break; + } + } + // TODO: Do the same for pair? + } + + // Override the `forced_bos_token_id` to force the correct language + generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0]; + + return self._call(raw_inputs, tokenizer_options); +} + +/** + * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models. + * + * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project + * that open-sources models capable of delivering high-quality translations directly + * between any pair of 200+ languages — including low-resource languages like Asturian, + * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere, + * regardless of their language preferences. For more information, check out their + * [paper](https://arxiv.org/abs/2207.04672). + * + * For a list of supported languages (along with their language codes), + * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200} + */ +export class NllbTokenizer extends PreTrainedTokenizer { + + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + + this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; + this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x)); + this.lang_to_token = x => x; // Identity function + } + + /** + * Helper function to build translation inputs for an `NllbTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +} + +/** + * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models. + * + * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many + * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125) + * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository. + * + * For a list of supported languages (along with their language codes), + * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered} + */ +export class M2M100Tokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + + this.languageRegex = /^__[a-z]{2,3}__$/; + this.language_codes = this.special_tokens + .filter(x => this.languageRegex.test(x)) + .map(x => x.slice(2, -2)); + this.lang_to_token = x => `__${x}__`; + } + + /** + * Helper function to build translation inputs for an `M2M100Tokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +} + + +const WHISPER_LANGUAGES = [ + ["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"], +] + +// @ts-ignore +const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); +// @ts-ignore +const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ + ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]), + ...[ + ["burmese", "my"], + ["valencian", "ca"], + ["flemish", "nl"], + ["haitian", "ht"], + ["letzeburgesch", "lb"], + ["pushto", "ps"], + ["panjabi", "pa"], + ["moldavian", "ro"], + ["moldovan", "ro"], + ["sinhalese", "si"], + ["castilian", "es"], + ] +]); + +/** + * WhisperTokenizer tokenizer + * @extends PreTrainedTokenizer + */ +export class WhisperTokenizer extends PreTrainedTokenizer { + _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`; + + /** + * Decodes automatic speech recognition (ASR) sequences. + * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. + * @param {Object} options The options to use for decoding. + * @returns {Array, text: string}>}>} The decoded sequences. + */ + _decode_asr(sequences, { + return_timestamps = false, + return_language = false, + time_precision = null, + force_full_sequences = true + } = {}) { + // Set force_full_sequences=false if you want streaming + // TODO add support for `return_language` + + // Internal method meant to only be used by asr pipeline. + // Handles all the little quirks specific to whisper to handle + // the various options not allowed in other seq2seq models + + // =========== Overview ============ + // - iterate over all outputs + // - all tokens within output + // - Each token can be + // - language token + // - special token + // - timestamp token + // - text token + // - We accumulate the text tokens. + // - We split on end timestamps + // - Lots of complexity comes from stride and timestamps + + if (time_precision === null) { + throw Error("Must specify time_precision") + } + let last_language = null; + + const returnWordTimestamps = return_timestamps === "word"; + + function new_chunk() { + return { "language": last_language, "timestamp": [null, null], "text": "" }; + } + + // Welcome to the state machine! + const chunks = []; + let chunk = new_chunk(); + let time_offset = 0.0; + const timestamp_begin = this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; + + let previous_tokens = []; + let previous_token_timestamps = []; + + let skip = false; + let right_stride_start = null; + + + const all_special_ids = new Set(this.all_special_ids); + + for (const output of sequences) { + // NOTE: python version has batches, so it uses [0] + const token_ids = output.tokens; + const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; + + // These keep track of timestamps within strides, which need + // to be skipped and resolve all tokens in a single chunk. + let last_timestamp = null; + let first_timestamp = timestamp_begin; + + if ("stride" in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + + // Offset the timings to account for the other `model_outputs`. + time_offset -= stride_left; + right_stride_start = chunk_len - stride_right; + + // Keeping track of timestamps within strides + // We're going to NOT split on those, and delay until we're + // out of BOTH stride. Otherwise lots of issues occur and + // corner cases + if (stride_left) { + first_timestamp = stride_left / time_precision + timestamp_begin; + } + + if (stride_right) { + for (let i = token_ids.length - 1; i >= 0; --i) { + const token = token_ids[i]; + if (token >= timestamp_begin) { + // There can be several token in the right stride + // But the last one is ALWAYS going to be skipped + if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { + break; + } + last_timestamp = token; + } + } + } + } + + let current_tokens = []; + let current_token_timestamps = []; + + // - all tokens within output + for (let i = 0; i < token_ids.length; ++i) { + const token = token_ids[i]; + // 4 possible states for each token + // - 1/ Language code + // - 2/ all other special tokens (which we ignore) + // - 3/ Timestamp + // - 4/ Regular text + + if (all_special_ids.has(token)) { + const text = this.decode([token]); + const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); + + if (language !== undefined) { + // 1/ Indeed some language + // TODO Handle when language is different from the previous + // one, and we cannot use timestamped tokens to create chunks + if (last_language !== null && language !== last_language && !return_timestamps) { + previous_tokens.push(current_tokens); + const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; + const resolved_text = this.decode(resolved_tokens); + chunk.text = resolved_text; + chunks.push(chunk); + + // Flush all our temporary context + previous_tokens = []; + current_tokens = []; + chunk = new_chunk(); + } + + last_language = chunk.language = language; + } else { + // 2/ This is a regular special token, ignoring it + } + } else if (token >= timestamp_begin) { + // 3/ Timestamp token + const time = (token - timestamp_begin) * time_precision + time_offset; + const rounded_time = round(time, 2); + + if (last_timestamp !== null && token >= last_timestamp) { + // Whisper outputted a timestamp token, but it falls within + // our stride, so we're going to skip it for the time being + // and resolve this later + // Skip is necessary because timestamp tokens always come + // by pair, so we need to skip the next one too (which would mark the start of another chunk). + skip = true; + } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) { + skip = false; + } else if (chunk.timestamp[0] === null) { + chunk.timestamp[0] = rounded_time; + } else { + // This is the end of the timestamp chunk + if (rounded_time === chunk.timestamp[0]) { + // This is a bug in timestamp token output + // where we're taking the duplicate token + // as a stop where it should be a start. + // This is an issue in the underlying model output + // Let's just skip it so it becomes de-factor a start agin + } else { + chunk.timestamp[1] = rounded_time; + + // Handling merges + previous_tokens.push(current_tokens) + + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( + previous_tokens, previous_token_timestamps + ) + + const resolved_text = this.decode(resolved_tokens) + chunk.text = resolved_text + + if (returnWordTimestamps) { + chunk.words = this.collateWordTimestamps( + resolved_tokens, resolved_token_timestamps, last_language, + ) + } + + chunks.push(chunk) + + // Flush all our temporary context + previous_tokens = [] + current_tokens = [] + previous_token_timestamps = [] + current_token_timestamps = [] + chunk = new_chunk() + } + } + + } else { + // 4/ Regular token + // We just append to the list of all tokens so we can handle + // merges later and decode into text. + current_tokens.push(token) + + if (returnWordTimestamps) { + let start_time = round(token_timestamps[i] + time_offset, 2); + + let end_time; + if (i + 1 < token_timestamps.length) { + end_time = round(token_timestamps[i + 1] + time_offset, 2); + } else { + // should never happen + end_time = null; + } + current_token_timestamps.push([start_time, end_time]); + } + + } + } + + if ('stride' in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + time_offset += chunk_len - stride_right + } + + // Leftover tokens + if (current_tokens.length > 0) { + previous_tokens.push(current_tokens) + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + } else if (previous_tokens.every(p => p.length === 0)) { + // Flushing previous tokens (END)" + chunk = new_chunk() + previous_tokens = [] + current_tokens = [] + previous_token_timestamps = []; + current_token_timestamps = []; + } + + } + + if (previous_tokens.length > 0) { + if (force_full_sequences && return_timestamps) { + // Last token should always be timestamps, so there shouldn't be + // leftover + 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." + ); + } + + // Happens when we don't use timestamps + const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps); + + // Flushing previous tokens (FINAL) + const resolved_text = this.decode(resolved_tokens); + chunk.text = resolved_text; + if (returnWordTimestamps) { + chunk.words = this.collateWordTimestamps( + resolved_tokens, resolved_token_timestamps, last_language, + ) + } + chunks.push(chunk); + } + + let optional = Object.create(null); + + // Preparing and cleaning up the pipeline output + const full_text = chunks.map(chunk => chunk.text).join(''); + if (return_timestamps || return_language) { + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i]; + if (!return_timestamps) { + delete chunk["timestamp"]; + } + + if (!return_language) { + delete chunk["language"]; + } + } + if (returnWordTimestamps) { + const new_chunks = []; + for (const chunk of chunks) { + for (const word of chunk.words) { + new_chunks.push(word); + } + } + optional = { "chunks": new_chunks }; + } else { + optional = { "chunks": chunks }; + } + } + return [full_text, optional]; + + } + + /** + * Finds the longest common sequence among the provided sequences. + * @param {number[][]} sequences An array of sequences of token ids to compare. + * @returns {number[][]} The longest common sequence found. + * @throws {Error} If there is a bug within the function. + * @private + */ + findLongestCommonSequence(sequences, token_timestamp_sequences = null) { + // It would be much harder to do O(n) because of fault tolerance. + // We actually have a really good property which is that the total sequence + // MUST be those subsequences in order. + // If token_timestamp_sequences is provided, will split those sequences in + // exactly the same way. + let leftSequence = sequences[0]; + let leftLength = leftSequence.length; + let totalSequence = []; + + const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; + let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; + let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; + for (let i = 1; i < sequences.length; ++i) { + const rightSequence = sequences[i]; + let max = 0.0; + let maxIndices = [leftLength, leftLength, 0, 0]; + // Here we're sliding matches + // [a, b, c, d] + // [c, d, f] + // = [c] == [d] + + // [a, b, c, d] + // [c, d, f] + // = [c, d] == [c, d] + + + // [a, b, c, d] + // [c, d, f] + + // = [b, c, d] == [c, d, f] + + // [a, b, c, d] + // [c, d, f] + + // [a, b, c] == [c, d, f] + + // [a, b, c, d] + // [d, f] + + // [a, b] == [d, f] + + // [a, b, c, d] + // [f] + + // [a] == [f] + + const rightLength = rightSequence.length; + for (let j = 1; j < leftLength + rightLength; ++j) { + const eps = j / 10000.0; + const leftStart = Math.max(0, leftLength - j); + const leftStop = Math.min(leftLength, leftLength + rightLength - j); + const left = leftSequence.slice(leftStart, leftStop); + const rightStart = Math.max(0, j - leftLength); + const rightStop = Math.min(rightLength, j); + const right = rightSequence.slice(rightStart, rightStop); + if (left.length !== right.length) { + throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); + } + const matches = left.filter((elem, idx) => elem === right[idx]).length; + const matching = matches / j + eps; + if (matches > 1 && matching > max) { + max = matching; + maxIndices = [leftStart, leftStop, rightStart, rightStop]; + } + } + const [leftStart, leftStop, rightStart, rightStop] = maxIndices; + const leftMid = Math.floor((leftStop + leftStart) / 2); + const rightMid = Math.floor((rightStop + rightStart) / 2); + totalSequence.push(...leftSequence.slice(0, leftMid)); + leftSequence = rightSequence.slice(rightMid); + leftLength = leftSequence.length; + + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); + left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); + } + } + totalSequence.push(...leftSequence); + + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence); + return [totalSequence, total_token_timestamp_sequence]; + } else { + return [totalSequence, []]; + } + } + + /** @private */ + collateWordTimestamps(tokens, token_timestamps, language) { + + const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); + + const timings = []; + for (let i = 0; i < words.length; ++i) { + const indices = token_indices[i]; + timings.push({ + text: words[i], + timestamp: [ + token_timestamps[indices.at(0)][0], + token_timestamps[indices.at(-1)][1], + ], + }); + } + return timings; + } + + /** + * Groups tokens by word. Returns a tuple containing a list of strings with the words, + * and a list of `token_id` sequences with the tokens making up each word. + * @param {number[]} tokens + * @param {string} [language] + * @param {string} prepend_punctionations + * @param {string} append_punctuations + * + * @private + */ + combineTokensIntoWords(tokens, language, prepend_punctionations = "\"'“¡¿([{-", append_punctuations = "\"'.。,,!!??::”)]}、") { + language = language ?? 'english'; + + let words, word_tokens, token_indices; + + if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { + // These languages don't typically use spaces. + [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens) + } else { + [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens) + } + + return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); + } + + /** @type {PreTrainedTokenizer['decode']} */ + decode( + token_ids, + decode_args, + ) { + let text; + // @ts-ignore + if (decode_args && decode_args.decode_with_timestamps) { + if (token_ids instanceof Tensor) { + token_ids = prepareTensorForDecode(token_ids); + } + text = this.decodeWithTimestamps(token_ids, decode_args); + } else { + text = super.decode(token_ids, decode_args); + } + // TODO: implement offsets + // if (decode_args.output_offsets) { + // let offsets = this.computeOffsets + // } + return text; + } + + /** + * @param {number[]} token_ids List of token IDs to decode. + * @param {Object} decode_args Optional arguments for decoding + * @private + */ + decodeWithTimestamps(token_ids, decode_args) { + const time_precision = decode_args?.time_precision ?? 0.02; + + const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1; + /**@type {Array} */ + let outputs = [[]]; + for (const token of token_ids) { + if (token >= timestamp_begin) { + const timestamp = round((token - timestamp_begin) * time_precision, 2); + outputs.push(`<|${timestamp}|>`); + outputs.push([]); + } else { + outputs[outputs.length - 1].push(token); + } + } + outputs = outputs.map( + s => { + if (typeof s === 'string') { + return s; + } else { + return super.decode(s, decode_args); + } + } + ) + + return outputs.join(''); + } + + /** + * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. + * @param {number[]} tokens + * @returns {*} + * @private + */ + splitTokensOnUnicode(tokens) { + const decoded_full = this.decode(tokens, { + // @ts-ignore + decode_with_timestamps: true, + }); + const replacement_char = '\uFFFD'; + + const words = [] + const word_tokens = [] + const token_indices = [] + let current_tokens = [] + let current_indices = [] + let unicode_offset = 0 + + for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { + const token = tokens[token_idx]; + + current_tokens.push(token); + current_indices.push(token_idx); + + const decoded = this.decode(current_tokens, { + // @ts-ignore + decode_with_timestamps: true, + }); + + if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { + words.push(decoded) + word_tokens.push(current_tokens) + token_indices.push(current_indices) + current_tokens = [] + current_indices = [] + unicode_offset += decoded.length; + } + + } + + return [words, word_tokens, token_indices] + } + + /** + * Combine tokens into words by splitting at whitespace and punctuation tokens. + * @param {number[]} tokens + * @private + */ + splitTokensOnSpaces(tokens) { + + const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); + + const words = [] + const word_tokens = [] + const token_indices = [] + + const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu'); + + for (let i = 0; i < subwords.length; ++i) { + + const subword = subwords[i]; + const subword_tokens = subword_tokens_list[i]; + const subword_indices = subword_indices_list[i]; + + // @ts-ignore + const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>'); + const with_space = subword.startsWith(' '); + const trimmed = subword.trim(); + const punctuation = punctuationRegex.test(trimmed); + + if (special || with_space || punctuation || words.length === 0) { + words.push(subword); + word_tokens.push(subword_tokens); + token_indices.push(subword_indices); + } else { + const ix = words.length - 1; + words[ix] += subword; + word_tokens[ix].push(...subword_tokens); + token_indices[ix].push(...subword_indices); + } + } + + return [words, word_tokens, token_indices]; + + } + + /** + * Merges punctuation tokens with neighboring words. + * @param {string[]} words + * @param {number[][]} tokens + * @param {number[][]} indices + * @param {string} prepended + * @param {string} appended + * @private + */ + mergePunctuations(words, tokens, indices, prepended, appended) { + + const newWords = structuredClone(words); + const newTokens = structuredClone(tokens); + const newIndices = structuredClone(indices); + + + // prepend punctuations + let i = newWords.length - 2; + let j = newWords.length - 1; + + while (i >= 0) { + if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) { + newWords[j] = newWords[i] + newWords[j]; + newTokens[j] = mergeArrays(newTokens[i], newTokens[j]); + newIndices[j] = mergeArrays(newIndices[i], newIndices[j]); + newWords[i] = ''; + newTokens[i] = []; + newIndices[i] = []; + } else { + j = i; + } + --i; + } + + // append punctuations + i = 0; + j = 1; + while (j < newWords.length) { + if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) { + newWords[i] += newWords[j]; + newTokens[i] = mergeArrays(newTokens[i], newTokens[j]); + newIndices[i] = mergeArrays(newIndices[i], newIndices[j]); + newWords[j] = ''; + newTokens[j] = []; + newIndices[j] = []; + } else { + i = j; + } + ++j; + } + + return [ + newWords.filter(x => x), + newTokens.filter(x => x.length > 0), + newIndices.filter(x => x.length > 0), + ] + } + + /** + * Helper function to build translation inputs for a `WhisperTokenizer`, + * depending on the language, task, and whether to predict timestamp tokens. + * + * Used to override the prefix tokens appended to the start of the label sequence. + * + * **Example: Get ids for a language** + * ```javascript + * // instantiate the tokenizer and set the prefix token to Spanish + * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny'); + * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' }); + * // [(1, 50262), (2, 50363)] + * ``` + * + * @param {Object} options Options to generate the decoder prompt. + * @param {string} [options.language] The language of the transcription text. + * The corresponding language id token is appended to the start of the sequence for multilingual + * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended + * to the start of sequence. + * @param {string} [options.task] Task identifier to append at the start of sequence (if any). + * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and + * "translate" for speech translation. + * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence. + * @returns {number[][]} The decoder prompt ids. + */ + get_decoder_prompt_ids({ + language = null, + task = null, + no_timestamps = true, + } = {}) { + + // <|lang_id|> <|task|> <|notimestamps|> + + const forced_decoder_ids = []; + + if (language) { + // User wishes to specify the language + language = language.toLowerCase(); + + // Map to code from user-friendly name (e.g., "english" -> "en") + let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); + + if (language_code === undefined) { + // User provided something that is not a language name + + if (WHISPER_LANGUAGE_MAPPING.has(language)) { + // User provided the language code directly (e.g., "en") + language_code = language; + + } else { + // User provided something that is not a language code or name + const is_language_code = language.length === 2; + const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); + + throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(langs)}`); + } + } + + const language_token_id = this.model.tokens_to_ids.get(`<|${language_code}|>`); + if (language_token_id === undefined) { + throw new Error(`Unable to find language "${language_code}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`) + } + + forced_decoder_ids.push(language_token_id); + } else { + // No token will be forced, which leaves the model to predict the language + forced_decoder_ids.push(null); + } + + if (task) { + task = task.toLowerCase(); + if (task !== 'transcribe' && task !== 'translate') { + throw new Error(`Task "${task}" is not supported. Must be one of: ["transcribe", "translate"]`); + } + + const task_token_id = this.model.tokens_to_ids.get(`<|${task}|>`); + if (task_token_id === undefined) { + throw new Error(`Unable to find task "${task}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`) + } + + forced_decoder_ids.push(task_token_id); + } else { + // No token will be forced, which leaves the model to predict the task + forced_decoder_ids.push(null); + } + + if (no_timestamps) { + const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`); + if (no_timestamps_id === undefined) { + throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.') + } + + forced_decoder_ids.push(no_timestamps_id); + } + + return forced_decoder_ids.map((x, i) => [i + 1, x]).filter(x => x[1] !== null); + + } +} +export class CodeGenTokenizer extends PreTrainedTokenizer { } +export class CLIPTokenizer extends PreTrainedTokenizer { } +export class SiglipTokenizer extends PreTrainedTokenizer { } + +/** + * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers). + * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results. + */ +export class MarianTokenizer extends PreTrainedTokenizer { + /** + * Create a new MarianTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + + this.languageRegex = /^(>>\w+<<)\s*/g; + + this.supported_language_codes = this.model.vocab.filter( + x => this.languageRegex.test(x) + ); + + console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.') + } + + /** + * Encodes a single text. Overriding this method is necessary since the language codes + * must be removed before encoding with sentencepiece model. + * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 + * + * @param {string|null} text The text to encode. + * @returns {Array} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + + // Check if text starts with language code: + const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); + + if (remainder.length === 0) { + // No language code, encode normally + return super._encode_text(matchInfo); + + } else if (remainder.length === 2) { + // Text starts with language code, so we do not encode it with sentencepiece. + const [language, text] = remainder; + + if (!this.supported_language_codes.includes(language)) { + console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`) + } + return mergeArrays([language], super._encode_text(text)); + } + } + +} + +export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { } + +export class BlenderbotTokenizer extends PreTrainedTokenizer { + _default_chat_template = `{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}`; +} +export class BlenderbotSmallTokenizer extends BlenderbotTokenizer { } // NOTE `BlenderbotTokenizer` to get the correct chat template + +export class SpeechT5Tokenizer extends PreTrainedTokenizer { } + +export class NougatTokenizer extends PreTrainedTokenizer { } + +export class VitsTokenizer extends PreTrainedTokenizer { + + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + + // Custom decoder function + this.decoder = new VitsDecoder({}); + } +} +/** + * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function. + * The chosen tokenizer class is determined by the type specified in the tokenizer config. + * + * @example + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); + */ +export class AutoTokenizer { + static TOKENIZER_CLASS_MAPPING = { + T5Tokenizer, + DistilBertTokenizer, + CamembertTokenizer, + DebertaTokenizer, + DebertaV2Tokenizer, + BertTokenizer, + HerbertTokenizer, + ConvBertTokenizer, + RoFormerTokenizer, + XLMTokenizer, + ElectraTokenizer, + MobileBertTokenizer, + SqueezeBertTokenizer, + AlbertTokenizer, + GPT2Tokenizer, + BartTokenizer, + MBartTokenizer, + MBart50Tokenizer, + RobertaTokenizer, + WhisperTokenizer, + CodeGenTokenizer, + CLIPTokenizer, + SiglipTokenizer, + MarianTokenizer, + BloomTokenizer, + NllbTokenizer, + M2M100Tokenizer, + LlamaTokenizer, + CodeLlamaTokenizer, + XLMRobertaTokenizer, + MPNetTokenizer, + FalconTokenizer, + GPTNeoXTokenizer, + EsmTokenizer, + Wav2Vec2CTCTokenizer, + BlenderbotTokenizer, + BlenderbotSmallTokenizer, + SpeechT5Tokenizer, + NougatTokenizer, + VitsTokenizer, + + // Base case: + PreTrainedTokenizer, + } + + + /** + * Instantiate one of the tokenizer classes of the library from a pretrained model. + * + * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @returns {Promise} A new instance of the PreTrainedTokenizer class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + quantized = true, + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = 'main', + legacy = null, + } = {}) { + + const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { + quantized, + progress_callback, + config, + cache_dir, + local_files_only, + revision, + legacy, + }) + + // Some tokenizers are saved with the "Fast" suffix, so we remove that if present. + const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer'; + + let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName]; + if (!cls) { + console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); + cls = PreTrainedTokenizer; + } + return new cls(tokenizerJSON, tokenizerConfig); + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/transformers.js b/core/vendor/node_modules/@xenova/transformers/src/transformers.js new file mode 100644 index 000000000..acce33784 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/transformers.js @@ -0,0 +1,24 @@ +/** + * @file Entry point for the Transformers.js library. Only the exports from this file + * are available to the end user, and are grouped as follows: + * + * 1. [Pipelines](./pipelines) + * 2. [Environment variables](./env) + * 3. [Models](./models) + * 4. [Tokenizers](./tokenizers) + * 5. [Processors](./processors) + * + * @module transformers + */ + +export * from './env.js'; +export * from './pipelines.js'; +// export * from './models.js'; +// export * from './tokenizers.js'; +// export * from './processors.js'; +// export * from './configs.js'; + +// export * from './utils/audio.js'; +// export * from './utils/image.js'; +// export * from './utils/tensor.js'; +// export * from './utils/maths.js'; diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/audio.js b/core/vendor/node_modules/@xenova/transformers/src/utils/audio.js new file mode 100644 index 000000000..082870de8 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/audio.js @@ -0,0 +1,664 @@ +/** + * @file Helper module for audio processing. + * + * These functions and classes are only used internally, + * meaning an end-user shouldn't need to access anything here. + * + * @module utils/audio + */ + +import { + getFile, +} from './hub.js'; +import { FFT, max } from './maths.js'; +import { + calculateReflectOffset, +} from './core.js'; + + +/** + * Helper function to read audio from a path/URL. + * @param {string|URL} url The path/URL to load the audio from. + * @param {number} sampling_rate The sampling rate to use when decoding the audio. + * @returns {Promise} The decoded audio as a `Float32Array`. + */ +export async function read_audio(url, sampling_rate) { + if (typeof AudioContext === 'undefined') { + // Running in node or an environment without 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 response = await (await getFile(url)).arrayBuffer(); + const audioCTX = new AudioContext({ sampleRate: sampling_rate }); + if (typeof sampling_rate === 'undefined') { + console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`) + } + const decoded = await audioCTX.decodeAudioData(response); + + /** @type {Float32Array} */ + let audio; + + // We now replicate HuggingFace's `ffmpeg_read` method: + if (decoded.numberOfChannels === 2) { + // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg, + // the audio signal is summed across both channels to create a single mono channel. + // However, if the audio is at full scale (i.e. the highest possible volume level), + // the summing of the two channels can cause the audio signal to clip or distort. + + // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707) + // to the audio signal before summing the two channels. This scaling factor ensures + // that the combined audio signal will not exceed the maximum possible level, even + // if both channels are at full scale. + + // After applying this scaling factor, the audio signal from both channels is summed + // to create a single mono channel. It's worth noting that this scaling factor is + // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg. + // If you're using a different downmixing method, or if you're not downmixing the + // audio at all, this scaling factor may not be needed. + const SCALING_FACTOR = Math.sqrt(2); + + const left = decoded.getChannelData(0); + const right = decoded.getChannelData(1); + + audio = new Float32Array(left.length); + for (let i = 0; i < decoded.length; ++i) { + audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; + } + + } else { + // If the audio is not stereo, we can just use the first channel: + audio = decoded.getChannelData(0); + } + + return audio; +} + +/** + * Generates a Hanning window of length M. + * + * @param {number} M The length of the Hanning window to generate. + * @returns {Float64Array} The generated Hanning window. + */ +export function hanning(M) { + if (M < 1) { + return new Float64Array(); + } + if (M === 1) { + return new Float64Array([1]); + } + const denom = M - 1; + const factor = Math.PI / denom; + const cos_vals = new Float64Array(M); + for (let i = 0; i < M; ++i) { + const n = 2 * i - denom; + cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n); + } + return cos_vals; +} + +const HERTZ_TO_MEL_MAPPING = { + "htk": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)), + "kaldi": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)), + "slaney": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) => + freq >= min_log_hertz + ? min_log_mel + Math.log(freq / min_log_hertz) * logstep + : 3.0 * freq / 200.0, +} + +/** + * @template {Float32Array|Float64Array|number} T + * @param {T} freq + * @param {string} [mel_scale] + * @returns {T} + */ +function hertz_to_mel(freq, mel_scale = "htk") { + const fn = HERTZ_TO_MEL_MAPPING[mel_scale]; + if (!fn) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + + return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x)); +} + +const MEL_TO_HERTZ_MAPPING = { + "htk": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0), + "kaldi": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0), + "slaney": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel + ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) + : 200.0 * mels / 3.0, +} + +/** + * @template {Float32Array|Float64Array|number} T + * @param {T} mels + * @param {string} [mel_scale] + * @returns {T} + */ +function mel_to_hertz(mels, mel_scale = "htk") { + const fn = MEL_TO_HERTZ_MAPPING[mel_scale]; + if (!fn) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + + return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x)); +} + +/** +* Creates a triangular filter bank. +* +* Adapted from torchaudio and librosa. +* +* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`. +* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`. +* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`. +*/ +function _create_triangular_filter_bank(fft_freqs, filter_freqs) { + const filter_diff = Float64Array.from( + { length: filter_freqs.length - 1 }, + (_, i) => filter_freqs[i + 1] - filter_freqs[i] + ); + + const slopes = Array.from({ + length: fft_freqs.length + }, () => new Array(filter_freqs.length)); + + for (let j = 0; j < fft_freqs.length; ++j) { + const slope = slopes[j]; + for (let i = 0; i < filter_freqs.length; ++i) { + slope[i] = filter_freqs[i] - fft_freqs[j]; + } + } + + const numFreqs = filter_freqs.length - 2; + const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); + + for (let j = 0; j < fft_freqs.length; ++j) { // 201 + const slope = slopes[j]; + for (let i = 0; i < numFreqs; ++i) { // 80 + const down = -slope[i] / filter_diff[i]; + const up = slope[i + 2] / filter_diff[i + 1]; + ret[i][j] = Math.max(0, Math.min(down, up)); + } + } + return ret; +} + +/** + * Return evenly spaced numbers over a specified interval. + * @param {number} start The starting value of the sequence. + * @param {number} end The end value of the sequence. + * @param {number} num Number of samples to generate. + * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`. + */ +function linspace(start, end, num) { + const step = (end - start) / (num - 1); + return Float64Array.from({ length: num }, (_, i) => start + step * i); +} + +/** + * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and + * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters + * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these + * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency. + * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`). + * @param {number} num_mel_filters Number of mel filters to generate. + * @param {number} min_frequency Lowest frequency of interest in Hz. + * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`. + * @param {number} sampling_rate Sample rate of the audio waveform. + * @param {string} [norm] If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization). + * @param {string} [mel_scale] The mel frequency scale to use, `"htk"` or `"slaney"`. + * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space. + * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters. + * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`). + * This is a projection matrix to go from a spectrogram to a mel spectrogram. + */ +export function mel_filter_bank( + num_frequency_bins, + num_mel_filters, + min_frequency, + max_frequency, + sampling_rate, + norm = null, + mel_scale = "htk", + triangularize_in_mel_space = false, +) { + if (norm !== null && norm !== "slaney") { + throw new Error('norm must be one of null or "slaney"'); + } + + const mel_min = hertz_to_mel(min_frequency, mel_scale); + const mel_max = hertz_to_mel(max_frequency, mel_scale); + const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); + + let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); + let fft_freqs; // frequencies of FFT bins in Hz + + if (triangularize_in_mel_space) { + const fft_bin_width = sampling_rate / (num_frequency_bins * 2); + fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale); + filter_freqs = mel_freqs; + } else { + fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); + } + + const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); + + if (norm !== null && norm === "slaney") { + // Slaney-style mel is scaled to be approx constant energy per channel + for (let i = 0; i < num_mel_filters; ++i) { + const filter = mel_filters[i]; + const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]); + for (let j = 0; j < num_frequency_bins; ++j) { + // Apply this enorm to all frequency bins + filter[j] *= enorm; + } + } + } + + // TODO warn if there is a zero row + + return mel_filters; + +} + +/** + * @template {Float32Array|Float64Array} T + * Pads an array with a reflected version of itself on both ends. + * @param {T} array The array to pad. + * @param {number} left The amount of padding to add to the left. + * @param {number} right The amount of padding to add to the right. + * @returns {T} The padded array. + */ +function padReflect(array, left, right) { + // @ts-ignore + const padded = new array.constructor(array.length + left + right); + const w = array.length - 1; + + for (let i = 0; i < array.length; ++i) { + padded[left + i] = array[i]; + } + + for (let i = 1; i <= left; ++i) { + padded[left - i] = array[calculateReflectOffset(i, w)]; + } + + for (let i = 1; i <= right; ++i) { + padded[w + left + i] = array[calculateReflectOffset(w - i, w)]; + } + + return padded; +} + +/** + * Helper function to compute `amplitude_to_db` and `power_to_db`. + * @template {Float32Array|Float64Array} T + * @param {T} spectrogram + * @param {number} factor + * @param {number} reference + * @param {number} min_value + * @param {number} db_range + * @returns {T} + */ +function _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) { + if (reference <= 0) { + throw new Error('reference must be greater than zero'); + } + + if (min_value <= 0) { + throw new Error('min_value must be greater than zero'); + } + + reference = Math.max(min_value, reference); + + const logReference = Math.log10(reference); + for (let i = 0; i < spectrogram.length; ++i) { + spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference) + } + + if (db_range !== null) { + if (db_range <= 0) { + throw new Error('db_range must be greater than zero'); + } + const maxValue = max(spectrogram)[0] - db_range; + for (let i = 0; i < spectrogram.length; ++i) { + spectrogram[i] = Math.max(spectrogram[i], maxValue); + } + } + + return spectrogram; +} + +/** + * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`, + * using basic logarithm properties for numerical stability. NOTE: Operates in-place. + * + * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a + * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it. + * This means that large variations in energy may not sound all that different if the sound is loud to begin with. + * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear. + * + * @template {Float32Array|Float64Array} T + * @param {T} spectrogram The input amplitude (mel) spectrogram. + * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. + * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero. + * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels, + * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero. + * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the + * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero. + * @returns {T} The modified spectrogram in decibels. + */ +function amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) { + return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range); +} + +/** + * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`, + * using basic logarithm properties for numerical stability. NOTE: Operates in-place. + * + * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a + * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it. + * This means that large variations in energy may not sound all that different if the sound is loud to begin with. + * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear. + * + * Based on the implementation of `librosa.power_to_db`. + * + * @template {Float32Array|Float64Array} T + * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared! + * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. + * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero. + * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, + * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero. + * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the + * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero. + * @returns {T} The modified spectrogram in decibels. + */ +function power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) { + return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range); +} + +/** + * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform. + * + * This function can create the following kinds of spectrograms: + * - amplitude spectrogram (`power = 1.0`) + * - power spectrogram (`power = 2.0`) + * - complex-valued spectrogram (`power = None`) + * - log spectrogram (use `log_mel` argument) + * - mel spectrogram (provide `mel_filters`) + * - log-mel spectrogram (provide `mel_filters` and `log_mel`) + * + * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. + * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, + * typically the next power of two. + * + * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform. + * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be + * shorter than `frame_length`, but we're assuming the array has already been zero-padded. + * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`). + * @param {number} hop_length The stride between successive analysis frames in samples. + * @param {Object} options + * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have. + * For optimal speed, this should be a power of two. If `null`, uses `frame_length`. + * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers. + * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame + * `t` will start at time `t * hop_length`. + * @param {string} [options.pad_mode="reflect"] Padding mode used when `center` is `true`. Possible values are: `"constant"` (pad with zeros), + * `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values). + * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1` + * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins. + * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT. + * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`. + * If supplied, applies this filter bank to create a mel spectrogram. + * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks. + * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are: + * `null` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). + * Can only be used when `power` is not `null`. + * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set + * the loudest part to 0 dB. Must be greater than zero. + * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`. + * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB. + * Must be greater than zero. + * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the + * peak value and the smallest value will never be more than 80 dB. Must be greater than zero. + * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in + * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters. + * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value. + * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames. + * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`. + * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram). + */ +export function spectrogram( + waveform, + window, + frame_length, + hop_length, + { + fft_length = null, + power = 1.0, + center = true, + pad_mode = "reflect", + onesided = true, + preemphasis = null, + mel_filters = null, + mel_floor = 1e-10, + log_mel = null, + reference = 1.0, + min_value = 1e-10, + db_range = null, + remove_dc_offset = null, + + // Custom parameters for efficiency reasons + max_num_frames = null, + do_pad = true, + transpose = false, + } = {} +) { + const window_length = window.length; + if (fft_length === null) { + fft_length = frame_length; + } + if (frame_length > fft_length) { + throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`) + } + + if (window_length !== frame_length) { + throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); + } + + if (hop_length <= 0) { + throw new Error("hop_length must be greater than zero"); + } + + if (center) { + if (pad_mode !== 'reflect') { + throw new Error(`pad_mode="${pad_mode}" not implemented yet.`) + } + const half_window = Math.floor((fft_length - 1) / 2) + 1; + waveform = padReflect(waveform, half_window, half_window); + } + + // split waveform into frames of frame_length size + const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)) + + const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length + + let d1 = num_frames; + let d1Max = num_frames; + + // If maximum number of frames is provided, we must either pad or truncate + if (max_num_frames !== null) { + if (max_num_frames > num_frames) { // input is too short, so we pad + if (do_pad) { + d1Max = max_num_frames; + } + } else { // input is too long, so we truncate + d1Max = d1 = max_num_frames; + } + } + + // Preallocate arrays to store output. + const fft = new FFT(fft_length); + const inputBuffer = new Float64Array(fft_length); + const outputBuffer = new Float64Array(fft.outputBufferSize); + const magnitudes = new Array(d1); + + for (let i = 0; i < d1; ++i) { + // Populate buffer with waveform data + const offset = i * hop_length; + for (let j = 0; j < frame_length; ++j) { + inputBuffer[j] = waveform[offset + j]; + } + + if (remove_dc_offset) { + let sum = 0; + for (let j = 0; j < frame_length; ++j) { + sum += inputBuffer[j]; + } + const mean = sum / frame_length; + for (let j = 0; j < frame_length; ++j) { + inputBuffer[j] -= mean; + } + } + + if (preemphasis !== null) { + // Done in reverse to avoid copies and distructive modification + for (let j = frame_length - 1; j >= 1; --j) { + inputBuffer[j] -= preemphasis * inputBuffer[j - 1]; + } + inputBuffer[0] *= 1 - preemphasis; + } + + for (let j = 0; j < window.length; ++j) { + inputBuffer[j] *= window[j]; + } + + fft.realTransform(outputBuffer, inputBuffer); + + // compute magnitudes + const row = new Array(num_frequency_bins); + for (let j = 0; j < row.length; ++j) { + const j2 = j << 1; + row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2; + } + magnitudes[i] = row; + } + + // TODO what should happen if power is None? + // https://github.com/huggingface/transformers/issues/27772 + if (power !== null && power !== 2) { + // slight optimization to not sqrt + const pow = 2 / power; // we use 2 since we already squared + for (let i = 0; i < magnitudes.length; ++i) { + const magnitude = magnitudes[i]; + for (let j = 0; j < magnitude.length; ++j) { + magnitude[j] **= pow; + } + } + } + + // TODO: What if `mel_filters` is null? + const num_mel_filters = mel_filters.length; + + // Only here do we create Float32Array + const mel_spec = new Float32Array(num_mel_filters * d1Max); + + // Perform matrix muliplication: + // mel_spec = mel_filters @ magnitudes.T + // - mel_filters.shape=(80, 201) + // - magnitudes.shape=(3000, 201) => - magnitudes.T.shape=(201, 3000) + // - mel_spec.shape=(80, 3000) + const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max]; + for (let i = 0; i < num_mel_filters; ++i) { // num melfilters (e.g., 80) + const filter = mel_filters[i]; + for (let j = 0; j < d1; ++j) { // num frames (e.g., 3000) + const magnitude = magnitudes[j]; + + let sum = 0; + for (let k = 0; k < num_frequency_bins; ++k) { // num frequency bins (e.g., 201) + sum += filter[k] * magnitude[k]; + } + + mel_spec[ + transpose + ? j * num_mel_filters + i + : i * d1 + j + ] = Math.max(mel_floor, sum); + } + } + + if (power !== null && log_mel !== null) { + const o = Math.min(mel_spec.length, d1 * num_mel_filters); + switch (log_mel) { + case 'log': + for (let i = 0; i < o; ++i) { + mel_spec[i] = Math.log(mel_spec[i]); + } + break; + case 'log10': + for (let i = 0; i < o; ++i) { + mel_spec[i] = Math.log10(mel_spec[i]); + } + break; + case 'dB': + if (power === 1.0) { + // NOTE: operates in-place + amplitude_to_db(mel_spec, reference, min_value, db_range); + } else if (power === 2.0) { + power_to_db(mel_spec, reference, min_value, db_range); + } else { + throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`) + } + break; + default: + throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`); + } + } + + return { data: mel_spec, dims }; +} + +/** + * Returns an array containing the specified window. + * @param {number} window_length The length of the window in samples. + * @param {string} name The name of the window function. + * @param {Object} options Additional options. + * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric. + * @param {number} [options.frame_length=null] The length of the analysis frames in samples. + * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded. + * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided. + * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`. + */ +export function window_function(window_length, name, { + periodic = true, + frame_length = null, + center = true, +} = {}) { + const length = periodic ? window_length + 1 : window_length; + let window; + switch (name) { + case 'boxcar': + window = new Float64Array(length).fill(1.0); + break; + case 'hann': + case 'hann_window': + window = hanning(length); + break; + default: + throw new Error(`Unknown window type ${name}.`); + } + if (periodic) { + window = window.subarray(0, window_length); + } + if (frame_length === null) { + return window; + } + if (window_length > frame_length) { + throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`); + } + + return window; +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/core.js b/core/vendor/node_modules/@xenova/transformers/src/utils/core.js new file mode 100644 index 000000000..4ed0f15ef --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/core.js @@ -0,0 +1,175 @@ + +/** + * @file Core utility functions/classes for Transformers.js. + * + * These are only used internally, meaning an end-user shouldn't + * need to access anything here. + * + * @module utils/core + */ + +/** + * Helper function to dispatch progress callbacks. + * + * @param {Function} progress_callback The progress callback function to dispatch. + * @param {any} data The data to pass to the progress callback function. + * @returns {void} + * @private + */ +export function dispatchCallback(progress_callback, data) { + if (progress_callback) progress_callback(data); +} + +/** + * Reverses the keys and values of an object. + * + * @param {Object} data The object to reverse. + * @returns {Object} The reversed object. + * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript + */ +export function reverseDictionary(data) { + // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript + return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); +} + +/** + * Escapes regular expression special characters from a string by replacing them with their escaped counterparts. + * + * @param {string} string The string to escape. + * @returns {string} The escaped string. + */ +export function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} + +/** + * A base class for creating callable objects. + * + * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}} + */ +export const Callable = /** @type {any} */ (class { + /** + * Creates a new instance of the Callable class. + */ + constructor() { + /** + * Creates a closure that delegates to a private method '_call' with the given arguments. + * @type {any} + * @param {...any} args Zero or more arguments to pass to the '_call' method. + * @returns {*} The result of calling the '_call' method. + */ + let closure = function (...args) { + return closure._call(...args) + } + return Object.setPrototypeOf(closure, new.target.prototype) + } + + /** + * This method should be implemented in subclasses to provide the + * functionality of the callable object. + * + * @param {any[]} args + * @throws {Error} If the subclass does not implement the `_call` method. + */ + _call(...args) { + throw Error('Must implement _call method in subclass') + } +}); + +/** + * Check if a value is a typed array. + * @param {*} val The value to check. + * @returns {boolean} True if the value is a `TypedArray`, false otherwise. + * + * Adapted from https://stackoverflow.com/a/71091338/13989043 + */ +export function isTypedArray(val) { + return val?.prototype?.__proto__?.constructor?.name === 'TypedArray'; +} + + +/** + * Check if a value is an integer. + * @param {*} x The value to check. + * @returns {boolean} True if the value is a string, false otherwise. + */ +export function isIntegralNumber(x) { + return Number.isInteger(x) || typeof x === 'bigint' +} + +/** + * Check if a value is exists. + * @param {*} x The value to check. + * @returns {boolean} True if the value exists, false otherwise. + */ +export function exists(x) { + return x !== undefined && x !== null; +} + +/** + * Calculates the dimensions of a nested array. + * + * @param {any[]} arr The nested array to calculate dimensions for. + * @returns {number[]} An array containing the dimensions of the input array. + */ +export function calculateDimensions(arr) { + const dimensions = []; + let current = arr; + while (Array.isArray(current)) { + dimensions.push(current.length); + current = current[0]; + } + return dimensions; +} + +/** + * Replicate python's .pop() method for objects. + * @param {Object} obj The object to pop from. + * @param {string} key The key to pop. + * @param {*} defaultValue The default value to return if the key does not exist. + * @returns {*} The value of the popped key. + * @throws {Error} If the key does not exist and no default value is provided. + */ +export function pop(obj, key, defaultValue = undefined) { + const value = obj[key]; + if (value !== undefined) { + delete obj[key]; + return value; + } + if (defaultValue === undefined) { + throw Error(`Key ${key} does not exist in object.`) + } + return defaultValue; +} + +/** + * Efficiently merge arrays, creating a new copy. + * Adapted from https://stackoverflow.com/a/6768642/13989043 + * @param {Array[]} arrs Arrays to merge. + * @returns {Array} The merged array. + */ +export function mergeArrays(...arrs) { + return Array.prototype.concat.apply([], arrs); +} + +/** + * Compute the Cartesian product of given arrays + * @param {...Array} a Arrays to compute the product + * @returns {Array} Returns the computed Cartesian product as an array + * @private + */ +export function product(...a) { + // Cartesian product of items + // Adapted from https://stackoverflow.com/a/43053803 + return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e]))); +} + +/** + * Calculates the index offset for a given index and window size. + * @param {number} i The index. + * @param {number} w The window size. + * @returns {number} The index offset. + */ +export function calculateReflectOffset(i, w) { + return Math.abs((i + w) % (2 * w) - w); +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/data-structures.js b/core/vendor/node_modules/@xenova/transformers/src/utils/data-structures.js new file mode 100644 index 000000000..dd8a78867 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/data-structures.js @@ -0,0 +1,415 @@ + +/** + * @file Custom data structures. + * + * These are only used internally, meaning an end-user shouldn't + * need to access anything here. + * + * @module utils/data-structures + */ + + +/** + * Efficient Heap-based Implementation of a Priority Queue. + * It uses an array-based binary heap, where the root is at index `0`, and the + * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively. + * + * Adapted from the following sources: + * - https://stackoverflow.com/a/42919752/13989043 (original) + * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements) + */ +export class PriorityQueue { + + /** + * Create a new PriorityQueue. + * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap. + */ + constructor(comparator = (a, b) => a > b) { + this._heap = []; + this._comparator = comparator; + } + + /** + * The size of the queue + */ + get size() { + return this._heap.length; + } + + /** + * Check if the queue is empty. + * @returns {boolean} `true` if the queue is empty, `false` otherwise. + */ + isEmpty() { + return this.size === 0; + } + + /** + * Return the element with the highest priority in the queue. + * @returns {any} The highest priority element in the queue. + */ + peek() { + return this._heap[0]; + } + + /** + * Add one or more elements to the queue. + * @param {...any} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + push(...values) { + return this.extend(values); + } + + /** + * Add multiple elements to the queue. + * @param {any[]} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + extend(values) { + for (const value of values) { + this._heap.push(value); + this._siftUp(); + } + return this.size; + } + + /** + * Remove and return the element with the highest priority in the queue. + * @returns {any} The element with the highest priority in the queue. + */ + pop() { + const poppedValue = this.peek(); + const bottom = this.size - 1; + if (bottom > 0) { + this._swap(0, bottom); + } + this._heap.pop(); + this._siftDown(); + return poppedValue; + } + + /** + * Replace the element with the highest priority in the queue with a new value. + * @param {*} value The new value. + * @returns {*} The replaced value. + */ + replace(value) { + const replacedValue = this.peek(); + this._heap[0] = value; + this._siftDown(); + return replacedValue; + } + + /** + * Compute the index for the parent of the node at index `i`. + * @param {number} i The index of the node to get the parent of. + * @returns {number} The index of the parent node. + * @private + */ + _parent(i) { + return ((i + 1) >>> 1) - 1; + } + + /** + * Compute the index for the left child of the node at index `i`. + * @param {number} i The index of the node to get the left child of. + * @returns {number} The index of the left child. + * @private + */ + _left(i) { + return (i << 1) + 1; + } + + /** + * Compute the index for the right child of the node at index `i`. + * @param {number} i The index of the node to get the right child of. + * @returns {number} The index of the right child. + * @private + */ + _right(i) { + return (i + 1) << 1; + } + + /** + * Check if the element at index `i` is greater than the element at index `j`. + * @param {number} i The index of the first element to compare. + * @param {number} j The index of the second element to compare. + * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. + * @private + */ + _greater(i, j) { + return this._comparator(this._heap[i], this._heap[j]); + } + + /** + * Swap the elements at indices `i` and `j`. + * @param {number} i The index of the first element to swap. + * @param {number} j The index of the second element to swap. + * @private + */ + _swap(i, j) { + const temp = this._heap[i]; + this._heap[i] = this._heap[j]; + this._heap[j] = temp; + } + + /** + * Maintain the heap property by updating positions in the heap, + * starting at the last element and moving up the heap. + * @private + */ + _siftUp() { + let node = this.size - 1; + while (node > 0 && this._greater(node, this._parent(node))) { + this._swap(node, this._parent(node)); + node = this._parent(node); + } + } + /** + * Maintain the heap property by updating positions in the heap, + * starting at the first element and moving down the heap. + * @private + */ + _siftDown() { + let node = 0; + while ( + (this._left(node) < this.size && this._greater(this._left(node), node)) || + (this._right(node) < this.size && this._greater(this._right(node), node)) + ) { + const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node))) + ? this._right(node) + : this._left(node); + this._swap(node, maxChild); + node = maxChild; + } + } +} + +/** + * A trie structure to efficiently store and search for strings. + */ +export class CharTrie { + constructor() { + this.root = CharTrieNode.default(); + } + + /** + * Adds one or more `texts` to the trie. + * @param {string[]} texts The strings to add to the trie. + */ + extend(texts) { + for (let text of texts) { + this.push(text); + } + } + + /** + * Adds text to the trie. + * @param {string} text The string to add to the trie. + */ + push(text) { + let node = this.root; + for (let ch of text) { + let child = node.children.get(ch); + if (child === undefined) { + child = CharTrieNode.default(); + node.children.set(ch, child); + } + node = child; + } + node.isLeaf = true; + } + + /** + * Searches the trie for all strings with a common prefix of `text`. + * @param {string} text The common prefix to search for. + * @yields {string} Each string in the trie that has `text` as a prefix. + */ + *commonPrefixSearch(text) { + let node = this.root; + let prefix = ""; + for (let i = 0; i < text.length && node !== undefined; ++i) { + const ch = text[i]; + prefix += ch; + node = node.children.get(ch); + if (node !== undefined && node.isLeaf) { + yield prefix; + } + } + } +} + +/** + * Represents a node in a character trie. + */ +class CharTrieNode { + /** + * Create a new CharTrieNode. + * @param {boolean} isLeaf Whether the node is a leaf node or not. + * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. + */ + constructor(isLeaf, children) { + this.isLeaf = isLeaf; + this.children = children; + } + + /** + * Returns a new `CharTrieNode` instance with default values. + * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. + */ + static default() { + return new CharTrieNode(false, new Map()); + } +} + +/** + * A lattice data structure to be used for tokenization. + */ +export class TokenLattice { + /** + * Creates a new TokenLattice instance. + * + * @param {string} sentence The input sentence to be tokenized. + * @param {number} bosTokenId The beginning-of-sequence token ID. + * @param {number} eosTokenId The end-of-sequence token ID. + */ + constructor(sentence, bosTokenId, eosTokenId) { + this.sentence = sentence; + this.len = sentence.length; + this.bosTokenId = bosTokenId; + this.eosTokenId = eosTokenId; + this.nodes = []; + this.beginNodes = Array.from({ length: this.len + 1 }, () => []); + this.endNodes = Array.from({ length: this.len + 1 }, () => []); + + const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0); + const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0); + this.nodes.push(bos.clone()); + this.nodes.push(eos.clone()); + this.beginNodes[this.len].push(eos); + this.endNodes[0].push(bos); + } + + /** + * Inserts a new token node into the token lattice. + * + * @param {number} pos The starting position of the token. + * @param {number} length The length of the token. + * @param {number} score The score of the token. + * @param {number} tokenId The token ID of the token. + */ + insert(pos, length, score, tokenId) { + const nodeId = this.nodes.length; + const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score); + this.beginNodes[pos].push(node); + this.endNodes[pos + length].push(node); + this.nodes.push(node); + } + + /** + * Implements the Viterbi algorithm to compute the most likely sequence of tokens. + * + * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens. + */ + viterbi() { + const len = this.len; + let pos = 0; + while (pos <= len) { + if (this.beginNodes[pos].length == 0) { + return []; + } + for (let rnode of this.beginNodes[pos]) { + rnode.prev = null; + let bestScore = 0.0; + let bestNode = null; + for (let lnode of this.endNodes[pos]) { + const score = lnode.backtraceScore + rnode.score; + if (bestNode === null || score > bestScore) { + bestNode = lnode.clone(); + bestScore = score; + } + } + + if (bestNode !== null) { + rnode.prev = bestNode; + rnode.backtraceScore = bestScore; + } else { + return []; + } + } + ++pos; + } + + const results = []; + const root = this.beginNodes[len][0]; + const prev = root.prev; + if (prev === null) { + return []; + } + + let node = prev.clone(); + while (node.prev !== null) { + results.push(node.clone()); + const n = node.clone(); + node = n.prev.clone(); + } + + results.reverse(); + return results; + } + + /** + * @param {TokenLatticeNode} node + * @returns {string} The array of nodes representing the most likely sequence of tokens. + */ + piece(node) { + return this.sentence.slice(node.pos, node.pos + node.length); + } + + /** + * @returns {Array} The array of nodes representing the most likely sequence of tokens. + */ + tokens() { + const nodes = this.viterbi(); + return nodes.map(x => this.piece(x)); + } + + /** + * @returns {Array} The array of nodes representing the most likely sequence of tokens. + */ + tokenIds() { + const nodes = this.viterbi(); + return nodes.map(x => x.tokenId); + } +} +class TokenLatticeNode { + /** + * Represents a node in a token lattice for a given sentence. + * @param {number} tokenId The ID of the token associated with this node. + * @param {number} nodeId The ID of this node. + * @param {number} pos The starting position of the token in the sentence. + * @param {number} length The length of the token. + * @param {number} score The score associated with the token. + */ + constructor(tokenId, nodeId, pos, length, score) { + this.tokenId = tokenId; + this.nodeId = nodeId; + this.pos = pos; + this.length = length; + this.score = score; + this.prev = null; + this.backtraceScore = 0.0; + } + + /** + * Returns a clone of this node. + * @returns {TokenLatticeNode} A clone of this node. + */ + clone() { + const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score); + n.prev = this.prev; + n.backtraceScore = this.backtraceScore; + return n; + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/generation.js b/core/vendor/node_modules/@xenova/transformers/src/utils/generation.js new file mode 100644 index 000000000..1f9dc898b --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/generation.js @@ -0,0 +1,873 @@ + +/** + * @file Classes, functions, and utilities for generation. + * + * @todo Describe how to create a custom `GenerationConfig`. + * + * @module utils/generation + */ +import { Tensor } from './tensor.js'; +import { + Callable, + exists, +} from './core.js'; +import { + max, + softmax, + log_softmax, + getTopItems, +} from './maths.js'; + +/** + * A class representing a list of logits processors. A logits processor is a function that modifies the logits + * output of a language model. This class provides methods for adding new processors and applying all processors to a + * batch of logits. + * + * @extends Callable + */ +export class LogitsProcessorList extends Callable { + /** + * Constructs a new instance of `LogitsProcessorList`. + */ + constructor() { + super(); + this.processors = []; + } + + /** + * Adds a new logits processor to the list. + * + * @param {LogitsProcessor} item The logits processor function to add. + */ + push(item) { + this.processors.push(item); + } + + /** + * Adds multiple logits processors to the list. + * + * @param {LogitsProcessor[]} items The logits processor functions to add. + */ + extend(items) { + this.processors.push(...items); + } + + /** + * Applies all logits processors in the list to a batch of logits, modifying them in-place. + * + * @param {number[]} input_ids The input IDs for the language model. + * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single + * input sequence in the batch. + */ + _call(input_ids, batchedLogits) { + // NOTE: This is different from the Python code, since vanilla JS does not support vectorized operations. + // As a result, we apply each processor to each item in the batch. + for (let logits of batchedLogits) { + // Modifies logits inplace + this.processors.forEach( + func => func(input_ids, logits) + ) + } + } + + [Symbol.iterator]() { + return this.processors.values(); + } +} + +/** + * Base class for processing logits. + * @extends Callable + */ +export class LogitsProcessor extends Callable { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {Array} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids, logits) { + throw Error("`_call` should be implemented in a subclass") + } +} + +/** + * A logits processor that forces a specific token to be generated by the decoder. + * + * @extends LogitsProcessor + */ +export class ForceTokensLogitsProcessor extends LogitsProcessor { + /** + * Constructs a new instance of `ForceTokensLogitsProcessor`. + * + * @param {Array} forced_decoder_ids The ids of tokens that should be forced. + */ + constructor(forced_decoder_ids) { + super(); + this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []); + } + + /** + * Apply the processor to the input logits. + * + * @param {Array} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + let map = this.force_token_map[input_ids.length]; + if (exists(map)) { // There exists a mapping + logits.data.fill(-Infinity) + logits.data[map] = 0; + } + return logits; + } +} + +/** + * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence. + * @extends LogitsProcessor + */ +export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedBOSTokenLogitsProcessor. + * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. + */ + constructor(bos_token_id) { + super(); + this.bos_token_id = bos_token_id; + } + + /** + * Apply the BOS token forcing to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + if (input_ids.length === 1) { + logits.data.fill(-Infinity) + logits.data[this.bos_token_id] = 0; + } + return logits; + } +} + +/** + * A logits processor that forces end-of-sequence token probability to 1. + * + * @extends LogitsProcessor + */ +export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedEOSTokenLogitsProcessor. + * @param {number} max_length Max length of the sequence. + * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced. + */ + constructor(max_length, forced_eos_token_id) { + super(); + this.max_length = max_length; + this.forced_eos_token_id = forced_eos_token_id; + } + + /** + * Apply the processor to input_ids and logits. + * + * @param {number[]} input_ids The input ids. + * @param {Tensor} logits The logits tensor. + */ + _call(input_ids, logits) { + // console.log('call ForcedEOSTokenLogitsProcessor') + // TODO + } +} + +/** + * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts + * generating using `begin_index` tokens. This should ensure that the tokens defined by + * `begin_suppress_tokens` at not sampled at the begining of the generation. + * @extends LogitsProcessor + */ +export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { + /** + * Create a SuppressTokensAtBeginLogitsProcessor. + * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. + * @param {number} begin_index The number of tokens to generate before suppressing tokens. + */ + constructor(begin_suppress_tokens, begin_index) { + super(); + this.begin_suppress_tokens = begin_suppress_tokens; + this.begin_index = begin_index; + } + + /** + * Apply the BOS token forcing to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + if (input_ids.length === this.begin_index) { + for (let token_id of this.begin_suppress_tokens) { + logits.data[token_id] = -Infinity; + } + } + return logits; + } +} + +/** + * A LogitsProcessor that handles adding timestamps to generated text. + * @extends LogitsProcessor + */ +export class WhisperTimeStampLogitsProcessor extends LogitsProcessor { + /** + * Constructs a new WhisperTimeStampLogitsProcessor. + * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model. + * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token. + * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp. + * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp. + * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear. + */ + constructor(generate_config) { + super(); + this.eos_token_id = generate_config.eos_token_id; + this.no_timestamps_token_id = generate_config.no_timestamps_token_id; + this.timestamp_begin = this.no_timestamps_token_id + 1; + + this.begin_index = (generate_config.forced_decoder_ids || []).length + 2; + if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) { + this.begin_index -= 1; + } + this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; + + } + + /** + * Modify the logits to handle timestamp tokens. + * @param {Array} input_ids The input sequence of tokens. + * @param {Tensor} logits The logits output by the model. + * @returns {Tensor} The modified logits. + */ + _call(input_ids, logits) { + const logitsData = /** @type {Float32Array} */(logits.data); + + // suppress <|notimestamps|> which is handled by without_timestamps + logitsData[this.no_timestamps_token_id] = -Infinity; + + if (input_ids.length === this.begin_index - 1) { + logitsData.fill(-Infinity); + logitsData[this.timestamp_begin] = 0; + return logits; + } + + // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly + const seq = input_ids.slice(this.begin_index); + const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; + const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; + + if (last_was_timestamp) { + if (penultimate_was_timestamp) { // has to be non-timestamp + logitsData.subarray(this.timestamp_begin).fill(-Infinity); + } else { // cannot be normal text tokens + logitsData.subarray(0, this.eos_token_id).fill(-Infinity); + } + } + + // apply the `max_initial_timestamp` option + if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) { + const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; + logitsData.subarray(last_allowed + 1).fill(-Infinity); + } + + // if sum of probability over timestamps is above any other token, sample timestamp + const logprobs = log_softmax(logitsData); + const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); + const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0]; + + if (timestamp_logprob > max_text_token_logprob) { + logitsData.subarray(0, this.timestamp_begin).fill(-Infinity); + } + + return logits; + } +} + +/** + * A logits processor that disallows ngrams of a certain size to be repeated. + * + * @extends LogitsProcessor + */ +export class NoRepeatNGramLogitsProcessor extends LogitsProcessor { + /** + * Create a NoRepeatNGramLogitsProcessor. + * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. + */ + constructor(no_repeat_ngram_size) { + super(); + this.no_repeat_ngram_size = no_repeat_ngram_size; + } + + /** + * Generate n-grams from a sequence of token ids. + * @param {number[]} prevInputIds List of previous input ids + * @returns {Map} Map of generated n-grams + */ + getNgrams(prevInputIds) { + const curLen = prevInputIds.length; + + /**@type {number[][]} */ + const ngrams = []; + for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) { + const ngram = []; + for (let k = 0; k < this.no_repeat_ngram_size; ++k) { + ngram.push(prevInputIds[j + k]); + } + ngrams.push(ngram); + } + + /** @type {Map} */ + const generatedNgram = new Map(); + for (const ngram of ngrams) { + const prevNgram = ngram.slice(0, ngram.length - 1); + const prevNgramKey = JSON.stringify(prevNgram); + const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; + prevNgramValue.push(ngram[ngram.length - 1]); + generatedNgram.set(prevNgramKey, prevNgramValue); + } + return generatedNgram; + } + + /** + * Generate n-grams from a sequence of token ids. + * @param {Map} bannedNgrams Map of banned n-grams + * @param {number[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + getGeneratedNgrams(bannedNgrams, prevInputIds) { + const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); + const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? []; + return banned; + } + + /** + * Calculate banned n-gram tokens + * @param {number[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + calcBannedNgramTokens(prevInputIds) { + const bannedTokens = []; + if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { + // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet + return bannedTokens; + + } else { + const generatedNgrams = this.getNgrams(prevInputIds); + const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds); + return bannedTokens; + } + } + + /** + * Apply the no-repeat-ngram processor to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with no-repeat-ngram processing. + */ + _call(input_ids, logits) { + const bannedTokens = this.calcBannedNgramTokens(input_ids); + + for (const token of bannedTokens) { + logits.data[token] = -Infinity; + } + return logits; + } +} + +/** + * A logits processor that penalises repeated output tokens. + * + * @extends LogitsProcessor + */ +export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { + /** + * Create a RepetitionPenaltyLogitsProcessor. + * @param {number} penalty The penalty to apply for repeated tokens. + */ + constructor(penalty) { + super(); + this.penalty = penalty; + } + + /** + * Apply the repetition penalty to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with repetition penalty processing. + */ + _call(input_ids, logits) { + // Modify the logits corresponding to each element in `input_ids`. + // As a consequence, the logits corresponding to tokens that appear + // many times in the output will be penalised more. + for (const input_id of input_ids) { + if (logits.data[input_id] < 0) { + logits.data[input_id] *= this.penalty; + } else { + logits.data[input_id] /= this.penalty; + } + } + return logits + } +} + +/** + * A logits processor that enforces a minimum number of tokens. + * + * @extends LogitsProcessor + */ +export class MinLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinLengthLogitsProcessor. + * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(min_length, eos_token_id) { + super(); + this.min_length = min_length; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids, logits) { + if (input_ids.length < this.min_length) { + for (const eos_token of this.eos_token_id) { + logits.data[eos_token] = -Infinity; + } + } + + return logits + } +} + +/** + * A logits processor that enforces a minimum number of new tokens. + * + * @extends LogitsProcessor + */ +export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinNewTokensLengthLogitsProcessor. + * @param {number} prompt_length_to_skip The input tokens length. + * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { + super(); + this.prompt_length_to_skip = prompt_length_to_skip; + this.min_new_tokens = min_new_tokens; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids, logits) { + const new_tokens_length = input_ids.length - this.prompt_length_to_skip; + if (new_tokens_length < this.min_new_tokens) { + for (const eos_token of this.eos_token_id) { + logits.data[eos_token] = -Infinity; + } + } + + return logits + } +} + +export class NoBadWordsLogitsProcessor extends LogitsProcessor { + /** + * Create a `NoBadWordsLogitsProcessor`. + * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. + * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(bad_words_ids, eos_token_id) { + super(); + this.bad_words_ids = bad_words_ids; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids, logits) { + + for (const bad_word_ids of this.bad_words_ids) { + // Whether to modify the logits of the last token in the bad word id sequence + let mark = true; + + // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last), + // then we set the logits of the last bad word id to -Infinity. + for (let i = 1; i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i) { + + if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) { + // We have found a mismatch + mark = false; + break; + } + } + if (mark) { + logits.data[bad_word_ids.at(-1)] = -Infinity; + } + } + + return logits + } +} + +/** + * @typedef {Object} GenerationConfigType The default configuration parameters. + * @property {number} [max_length=20] The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set. + * @property {number} [max_new_tokens=null] The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @property {number} [min_length=0] The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set. + * @property {number} [min_new_tokens=null] The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @property {boolean|"never"} [early_stopping=false] Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: + * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; + * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; + * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). + * @property {number} [max_time=null] The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed. + * + * @property {boolean} [do_sample=false] Whether or not to use sampling; use greedy decoding otherwise. + * @property {number} [num_beams=1] Number of beams for beam search. 1 means no beam search. + * @property {number} [num_beam_groups=1] Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details. + * @property {number} [penalty_alpha=null] The values balance the model confidence and the degeneration penalty in contrastive search decoding. + * @property {boolean} [use_cache=true] Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. + * + * @property {number} [temperature=1.0] The value used to modulate the next token probabilities. + * @property {number} [top_k=50] The number of highest probability vocabulary tokens to keep for top-k-filtering. + * @property {number} [top_p=1.0] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. + * @property {number} [typical_p=1.0] Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details. + * @property {number} [epsilon_cutoff=0.0] If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + * @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + * @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled. + * @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + * @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. + * @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. + * @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once. + * @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`. + * @property {number[][]|number[][][]} [force_words_ids=null] List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. + * @property {boolean} [renormalize_logits=false] Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. + * @property {Object[]} [constraints=null] Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. + * + * @property {number} [forced_bos_token_id=null] The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token. + * @property {number|number[]} [forced_eos_token_id=null] The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens. + * @property {boolean} [remove_invalid_values=false] Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. + * @property {number[]} [exponential_decay_length_penalty=null] This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. + * @property {number[]} [suppress_tokens=null] A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @property {number[]} [begin_suppress_tokens=null] A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @property {number[][]} [forced_decoder_ids=null] A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123. + * + * @property {number} [num_return_sequences=1] The number of independently computed returned sequences for each element in the batch. + * @property {boolean} [output_attentions=false] Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details. + * @property {boolean} [output_hidden_states=false] Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details. + * @property {boolean} [output_scores=false] Whether or not to return the prediction scores. See `scores` under returned tensors for more details. + * @property {boolean} [return_dict_in_generate=false] Whether or not to return a `ModelOutput` instead of a plain tuple. + * + * @property {number} [pad_token_id=null] The id of the *padding* token. + * @property {number} [bos_token_id=null] The id of the *beginning-of-sequence* token. + * @property {number|number[]} [eos_token_id=null] The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + * + * @property {number} [encoder_no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. + * @property {number} [decoder_start_token_id=null] If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. + * + * @property {Object} [generation_kwargs={}] Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass. + */ + +/** + * Class that holds a configuration for a generation task. + * @type {new (kwargs?: GenerationConfigType) => GenerationConfigType} + */ +export const GenerationConfig = /** @type {any} */ (class { + + /** + * Create a new GenerationConfig object. + * @param {GenerationConfigType} kwargs + */ + constructor(kwargs = {}) { + // Parameters that control the length of the output + this.max_length = kwargs.max_length ?? 20; + this.max_new_tokens = kwargs.max_new_tokens ?? null; + this.min_length = kwargs.min_length ?? 0; + this.min_new_tokens = kwargs.min_new_tokens ?? null; + this.early_stopping = kwargs.early_stopping ?? false; + this.max_time = kwargs.max_time ?? null; + + // Parameters that control the generation strategy used + this.do_sample = kwargs.do_sample ?? false; + this.num_beams = kwargs.num_beams ?? 1; + this.num_beam_groups = kwargs.num_beam_groups ?? 1; + this.penalty_alpha = kwargs.penalty_alpha ?? null; + this.use_cache = kwargs.use_cache ?? true; + + // Parameters for manipulation of the model output logits + this.temperature = kwargs.temperature ?? 1.0; + this.top_k = kwargs.top_k ?? 50; + this.top_p = kwargs.top_p ?? 1.0; + this.typical_p = kwargs.typical_p ?? 1.0; + this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0.0; + this.eta_cutoff = kwargs.eta_cutoff ?? 0.0; + this.diversity_penalty = kwargs.diversity_penalty ?? 0.0; + this.repetition_penalty = kwargs.repetition_penalty ?? 1.0; + this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1.0; + this.length_penalty = kwargs.length_penalty ?? 1.0; + this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0; + this.bad_words_ids = kwargs.bad_words_ids ?? null; + this.force_words_ids = kwargs.force_words_ids ?? null; + this.renormalize_logits = kwargs.renormalize_logits ?? false; + this.constraints = kwargs.constraints ?? null; + this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null; + this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null; + this.remove_invalid_values = kwargs.remove_invalid_values ?? false; + this.exponential_decay_length_penalty = kwargs.exponential_decay_length_penalty ?? null; + this.suppress_tokens = kwargs.suppress_tokens ?? null; + this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null; + this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null; + + // Parameters that define the output variables of `generate` + this.num_return_sequences = kwargs.num_return_sequences ?? 1; + this.output_attentions = kwargs.output_attentions ?? false; + this.output_hidden_states = kwargs.output_hidden_states ?? false; + this.output_scores = kwargs.output_scores ?? false; + this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false; + + // Special tokens that can be used at generation time + this.pad_token_id = kwargs.pad_token_id ?? null; + this.bos_token_id = kwargs.bos_token_id ?? null; + this.eos_token_id = kwargs.eos_token_id ?? null; + + // Generation parameters exclusive to encoder-decoder models + this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0; + this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null; + + // Wild card + this.generation_kwargs = kwargs.generation_kwargs ?? {}; + } +}); + +/** + * Sampler is a base class for all sampling methods used for text generation. + */ +export class Sampler extends Callable { + /** + * Creates a new Sampler object with the specified generation config. + * @param {GenerationConfigType} generation_config The generation config. + */ + constructor(generation_config) { + super(); + this.generation_config = generation_config; + } + + /** + * Executes the sampler, using the specified logits. + * @param {Tensor} logits + * @param {number} index + * @returns {void} + */ + _call(logits, index = -1) { + // Sample from logits, of dims [batch, sequence_length, vocab_size]. + // If index is specified, sample from [batch, index, vocab_size]. + return this.sample(logits, index); + } + + /** + * Abstract method for sampling the logits. + * @param {Tensor} logits + * @param {number} index + * @throws {Error} + */ + sample(logits, index) { + throw Error("sample should be implemented in subclasses.") + } + + /** + * Returns the specified logits as an array, with temperature applied. + * @param {Tensor} logits + * @param {number} index + * @returns {Float32Array} + */ + getLogits(logits, index) { + let vocabSize = logits.dims.at(-1); + + let logs = /** @type {Float32Array} */(logits.data); + + if (index === -1) { + logs = logs.slice(-vocabSize); + } else { + let startIndex = index * vocabSize; + logs = logs.slice(startIndex, startIndex + vocabSize); + } + + // add temperature + if (this.generation_config.temperature > 0) { + logs = logs.map(x => x / this.generation_config.temperature) + } + return logs; + } + + /** + * Selects an item randomly based on the specified probabilities. + * @param {Array} probabilities An array of probabilities to use for selection. + * @returns {number} The index of the selected item. + */ + randomSelect(probabilities) { + // Return index of chosen item + let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0); + + let r = Math.random() * sumProbabilities; + for (let i = 0; i < probabilities.length; ++i) { + r -= probabilities[i]; + if (r <= 0) { + return i; + } + } + return 0; // return first (most probable) as a fallback + } + + /** + * Returns a Sampler object based on the specified options. + * @param {GenerationConfigType} generation_config An object containing options for the sampler. + * @returns {Sampler} A Sampler object. + */ + static getSampler(generation_config) { + // - *greedy decoding*: `num_beams=1` and `do_sample=False` + // - *contrastive search*: `penalty_alpha>0` and `top_k>1` + // - *multinomial sampling*: `num_beams=1` and `do_sample=True` + // - *beam-search decoding*: `num_beams>1` and `do_sample=False` + // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True` + // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1` + // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None` + + // NOTE: beam search is implemented directly into the generation function + if (generation_config.do_sample) { + return new MultinomialSampler(generation_config); + + } else if (generation_config.num_beams > 1) { + return new BeamSearchSampler(generation_config); + + } else { + if (generation_config.num_return_sequences > 1) { + throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`) + } + return new GreedySampler(generation_config); + } + } +} + +/** + * Class representing a Greedy Sampler. + * @extends Sampler + */ +class GreedySampler extends Sampler { + /** + * Sample the maximum probability of a given logits tensor. + * @param {Tensor} logits + * @param {number} [index=-1] + * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). + */ + sample(logits, index = -1) { + // NOTE: no need to do log_softmax here since we only take the maximum + let logs = this.getLogits(logits, index); + let argmax = max(logs)[1]; + + // Note: score is meaningless in this context, since we are performing + // greedy search (p = 1 => log(p) = 0) + return [ + [argmax, 0] + ]; + } +} + +/** + * Class representing a MultinomialSampler. + * @extends Sampler + */ +class MultinomialSampler extends Sampler { + + /** + * Sample from the logits. + * @param {Tensor} logits + * @param {number} index + * @returns {Array} + */ + sample(logits, index = -1) { + let k = logits.dims.at(-1); // defaults to vocab size + if (this.generation_config.top_k > 0) { + k = Math.min(this.generation_config.top_k, k); + } + + // Get logits of nth token + const logs = this.getLogits(logits, index); + + // Get top k tokens + const topLogits = getTopItems(logs, k); + + // Compute softmax over logits + const probabilities = softmax(topLogits.map(x => x[1])); + + return Array.from({ length: this.generation_config.num_beams }, () => { + const sampledIndex = this.randomSelect(probabilities); + return [ + topLogits[sampledIndex][0], // token id + Math.log(probabilities[sampledIndex]), // score + ]; + }); + } +} + + +/** + * Class representing a BeamSearchSampler. + * @extends Sampler + */ +class BeamSearchSampler extends Sampler { + + /** + * Sample from the logits. + * @param {Tensor} logits + * @param {number} index + * @returns {Array} + */ + sample(logits, index = -1) { + let k = logits.dims.at(-1); // defaults to vocab size + if (this.generation_config.top_k > 0) { + k = Math.min(this.generation_config.top_k, k); + } + + // Get logits of nth token + const logs = this.getLogits(logits, index); + + // Get top k tokens + const topLogits = getTopItems(logs, k); + + // Compute softmax over logits + const probabilities = softmax(topLogits.map(x => x[1])); + + return Array.from({ length: this.generation_config.num_beams }, (_, i) => { + return [ + topLogits[i][0], // token id + Math.log(probabilities[i]), // score + ]; + }); + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/hub.js b/core/vendor/node_modules/@xenova/transformers/src/utils/hub.js new file mode 100644 index 000000000..93617674c --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/hub.js @@ -0,0 +1,661 @@ + +/** + * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models) + * + * @module utils/hub + */ + +import fs from 'fs'; +import path from 'path'; +import stream from 'stream/web'; + +import { env } from '../env.js'; +import { dispatchCallback } from './core.js'; + +if (!globalThis.ReadableStream) { + // @ts-ignore + globalThis.ReadableStream = stream.ReadableStream; // ReadableStream is not a global with Node 16 +} + +/** + * @typedef {Object} PretrainedOptions Options for loading a pretrained model. + * @property {boolean?} [quantized=true] Whether to load the 8-bit quantized version of the model (only applicable when loading model files). + * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates. + * @property {Object} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: + * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). + * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. + * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. + * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model). + * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id, + * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. + * NOTE: This setting is ignored for local requests. + * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models. + */ + +class FileResponse { + /** + * Mapping from file extensions to MIME types. + */ + _CONTENT_TYPE_MAP = { + 'txt': 'text/plain', + 'html': 'text/html', + 'css': 'text/css', + 'js': 'text/javascript', + 'json': 'application/json', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + } + /** + * Creates a new `FileResponse` object. + * @param {string|URL} filePath + */ + constructor(filePath) { + this.filePath = filePath; + this.headers = new Headers(); + + this.exists = fs.existsSync(filePath); + if (this.exists) { + this.status = 200; + this.statusText = 'OK'; + + let stats = fs.statSync(filePath); + this.headers.set('content-length', stats.size.toString()); + + this.updateContentType(); + + let self = this; + this.body = new ReadableStream({ + start(controller) { + self.arrayBuffer().then(buffer => { + controller.enqueue(new Uint8Array(buffer)); + controller.close(); + }) + } + }); + } else { + this.status = 404; + this.statusText = 'Not Found'; + this.body = null; + } + } + + /** + * Updates the 'content-type' header property of the response based on the extension of + * the file specified by the filePath property of the current object. + * @returns {void} + */ + updateContentType() { + // Set content-type header based on file extension + const extension = this.filePath.toString().split('.').pop().toLowerCase(); + this.headers.set('content-type', this._CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream'); + } + + /** + * Clone the current FileResponse object. + * @returns {FileResponse} A new FileResponse object with the same properties as the current object. + */ + clone() { + let response = new FileResponse(this.filePath); + response.exists = this.exists; + response.status = this.status; + response.statusText = this.statusText; + response.headers = new Headers(this.headers); + return response; + } + + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with an ArrayBuffer containing the file's contents. + * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async arrayBuffer() { + const data = await fs.promises.readFile(this.filePath); + return data.buffer; + } + + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a Blob containing the file's contents. + * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async blob() { + const data = await fs.promises.readFile(this.filePath); + return new Blob([data], { type: this.headers.get('content-type') }); + } + + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a string containing the file's contents. + * @returns {Promise} A Promise that resolves with a string containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async text() { + const data = await fs.promises.readFile(this.filePath, 'utf8'); + return data; + } + + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a parsed JavaScript object containing the file's contents. + * + * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async json() { + return JSON.parse(await this.text()); + } +} + +/** + * Determines whether the given string is a valid HTTP or HTTPS URL. + * @param {string|URL} string The string to test for validity as an HTTP or HTTPS URL. + * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list. + * @returns {boolean} True if the string is a valid HTTP or HTTPS URL, false otherwise. + */ +function isValidHttpUrl(string, validHosts = null) { + // https://stackoverflow.com/a/43467144 + let url; + try { + url = new URL(string); + } catch (_) { + return false; + } + if (validHosts && !validHosts.includes(url.hostname)) { + return false; + } + return url.protocol === "http:" || url.protocol === "https:"; +} + +/** + * Helper function to get a file, using either the Fetch API or FileSystem API. + * + * @param {URL|string} urlOrPath The URL/path of the file to get. + * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API). + */ +export async function getFile(urlOrPath) { + + if (env.useFS && !isValidHttpUrl(urlOrPath)) { + return new FileResponse(urlOrPath); + + } else if (typeof process !== 'undefined' && process?.release?.name === 'node') { + const IS_CI = !!process.env?.TESTING_REMOTELY; + const version = env.version; + + const headers = new Headers(); + headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`); + + // Check whether we are making a request to the Hugging Face Hub. + const isHFURL = isValidHttpUrl(urlOrPath, ['huggingface.co', 'hf.co']); + if (isHFURL) { + // If an access token is present in the environment variables, + // we add it to the request headers. + // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback). + const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; + if (token) { + headers.set('Authorization', `Bearer ${token}`); + } + } + return fetch(urlOrPath, { headers }); + } else { + // Running in a browser-environment, so we use default headers + // NOTE: We do not allow passing authorization headers in the browser, + // since this would require exposing the token to the client. + return fetch(urlOrPath); + } +} + +const ERROR_MAPPING = { + // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) + 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', + + // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) + 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', +} +/** + * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub. + * @param {number} status The HTTP status code of the error. + * @param {string} remoteURL The URL of the file that could not be loaded. + * @param {boolean} fatal Whether to raise an error if the file could not be loaded. + * @returns {null} Returns `null` if `fatal = true`. + * @throws {Error} If `fatal = false`. + */ +function handleError(status, remoteURL, fatal) { + if (!fatal) { + // File was not loaded correctly, but it is optional. + // TODO in future, cache the response? + return null; + } + + const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; + throw Error(`${message}: "${remoteURL}".`); +} + +class FileCache { + /** + * Instantiate a `FileCache` object. + * @param {string} path + */ + constructor(path) { + this.path = path; + } + + /** + * Checks whether the given request is in the cache. + * @param {string} request + * @returns {Promise} + */ + async match(request) { + + let filePath = path.join(this.path, request); + let file = new FileResponse(filePath); + + if (file.exists) { + return file; + } else { + return undefined; + } + } + + /** + * Adds the given response to the cache. + * @param {string} request + * @param {Response|FileResponse} response + * @returns {Promise} + */ + async put(request, response) { + const buffer = Buffer.from(await response.arrayBuffer()); + + let outputPath = path.join(this.path, request); + + try { + await fs.promises.mkdir(path.dirname(outputPath), { recursive: true }); + await fs.promises.writeFile(outputPath, buffer); + + } catch (err) { + console.warn('An error occurred while writing the file to cache:', err) + } + } + + // TODO add the rest? + // addAll(requests: RequestInfo[]): Promise; + // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; +} + +/** + * + * @param {FileCache|Cache} cache The cache to search + * @param {string[]} names The names of the item to search for + * @returns {Promise} The item from the cache, or undefined if not found. + */ +async function tryCache(cache, ...names) { + for (let name of names) { + try { + let result = await cache.match(name); + if (result) return result; + } catch (e) { + continue; + } + } + return undefined; +} + +/** + * + * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API. + * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached. + * + * @param {string} path_or_repo_id This can be either: + * - a string, the *model id* of a model repo on huggingface.co. + * - a path to a *directory* potentially containing the file. + * @param {string} filename The name of the file to locate in `path_or_repo`. + * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. + * @param {PretrainedOptions} [options] An object containing optional parameters. + * + * @throws Will throw an error if the file is not found and `fatal` is true. + * @returns {Promise} A Promise that resolves with the file content as a buffer. + */ +export async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) { + + if (!env.allowLocalModels) { + // User has disabled local models, so we just make sure other settings are correct. + + if (options.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`).") + } else if (!env.allowRemoteModels) { + throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.") + } + } + + // Initiate file retrieval + dispatchCallback(options.progress_callback, { + status: 'initiate', + name: path_or_repo_id, + file: filename + }) + + // First, check if the a caching backend is available + // If no caching mechanism available, will download the file every time + let cache; + if (!cache && env.useBrowserCache) { + if (typeof caches === 'undefined') { + throw Error('Browser cache is not available in this environment.') + } + try { + // In some cases, the browser cache may be visible, but not accessible due to security restrictions. + // For example, when running an application in an iframe, if a user attempts to load the page in + // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage': + // An attempt was made to break through the security policy of the user agent.` + // So, instead of crashing, we just ignore the error and continue without using the cache. + cache = await caches.open('transformers-cache'); + } catch (e) { + console.warn('An error occurred while opening the browser cache:', e); + } + } + + if (!cache && env.useFSCache) { + // TODO throw error if not available + + // If `cache_dir` is not specified, use the default cache directory + cache = new FileCache(options.cache_dir ?? env.cacheDir); + } + + if (!cache && env.useCustomCache) { + // Allow the user to specify a custom cache system. + if (!env.customCache) { + throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.') + } + + // Check that the required methods are defined: + if (!env.customCache.match || !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" + ) + } + cache = env.customCache; + } + + const revision = options.revision ?? 'main'; + + let requestURL = pathJoin(path_or_repo_id, filename); + let localPath = pathJoin(env.localModelPath, requestURL); + + let remoteURL = pathJoin( + env.remoteHost, + env.remotePathTemplate + .replaceAll('{model}', path_or_repo_id) + .replaceAll('{revision}', encodeURIComponent(revision)), + filename + ); + + // Choose cache key for filesystem cache + // When using the main revision (default), we use the request URL as the cache key. + // If a specific revision is requested, we account for this in the cache key. + let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename); + + /** @type {string} */ + let cacheKey; + let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL; + + // Whether to cache the final response in the end. + let toCacheResponse = false; + + /** @type {Response|FileResponse|undefined} */ + let response; + + if (cache) { + // A caching system is available, so we try to get the file from it. + // 1. We first try to get from cache using the local path. In some environments (like deno), + // non-URL cache keys are not allowed. In these cases, `response` will be undefined. + // 2. If no response is found, we try to get from cache using the remote URL or file system cache. + response = await tryCache(cache, localPath, proposedCacheKey); + } + + const cacheHit = response !== undefined; + + if (response === undefined) { + // Caching not available, or file is not cached, so we perform the request + + if (env.allowLocalModels) { + // Accessing local models is enabled, so we try to get the file locally. + // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally. + const isURL = isValidHttpUrl(requestURL); + if (!isURL) { + try { + response = await getFile(localPath); + cacheKey = localPath; // Update the cache key to be the local path + } catch (e) { + // Something went wrong while trying to get the file locally. + // NOTE: error handling is done in the next step (since `response` will be undefined) + console.warn(`Unable to load from local path "${localPath}": "${e}"`); + } + } else if (options.local_files_only) { + throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); + } else if (!env.allowRemoteModels) { + throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`); + } + } + + if (response === undefined || response.status === 404) { + // File not found locally. This means either: + // - The user has disabled local file access (`env.allowLocalModels=false`) + // - the path is a valid HTTP url (`response === undefined`) + // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`) + + if (options.local_files_only || !env.allowRemoteModels) { + // User requested local files only, but the file is not found locally. + if (fatal) { + throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`); + } else { + // File not found, but this file is optional. + // TODO in future, cache the response? + return null; + } + } + + // File not found locally, so we try to download it from the remote server + response = await getFile(remoteURL); + + if (response.status !== 200) { + return handleError(response.status, remoteURL, fatal); + } + + // Success! We use the proposed cache key from earlier + cacheKey = proposedCacheKey; + } + + // Only cache the response if: + toCacheResponse = + cache // 1. A caching system is available + && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment) + && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`) + && response.status === 200 // 4. request was successful (status code 200) + } + + // Start downloading + dispatchCallback(options.progress_callback, { + status: 'download', + name: path_or_repo_id, + file: filename + }) + + const progressInfo = { + status: 'progress', + name: path_or_repo_id, + file: filename + } + + /** @type {Uint8Array} */ + let buffer; + + if (!options.progress_callback) { + // If no progress callback is specified, we can use the `.arrayBuffer()` + // method to read the response. + buffer = new Uint8Array(await response.arrayBuffer()); + + } else if ( + cacheHit // The item is being read from the cache + && + typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox + ) { + // Due to bug in Firefox, we cannot display progress when loading from cache. + // Fortunately, since this should be instantaneous, this should not impact users too much. + buffer = new Uint8Array(await response.arrayBuffer()); + + // For completeness, we still fire the final progress callback + dispatchCallback(options.progress_callback, { + ...progressInfo, + progress: 100, + loaded: buffer.length, + total: buffer.length, + }) + } else { + buffer = await readResponse(response, data => { + dispatchCallback(options.progress_callback, { + ...progressInfo, + ...data, + }) + }) + } + + if ( + // Only cache web responses + // i.e., do not cache FileResponses (prevents duplication) + toCacheResponse && cacheKey + && + // Check again whether request is in cache. If not, we add the response to the cache + (await cache.match(cacheKey) === undefined) + ) { + // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files + await cache.put(cacheKey, new Response(buffer, { + headers: response.headers + })) + .catch(err => { + // Do not crash if unable to add to cache (e.g., QuotaExceededError). + // Rather, log a warning and proceed with execution. + console.warn(`Unable to add response to browser cache: ${err}.`); + }); + + } + + dispatchCallback(options.progress_callback, { + status: 'done', + name: path_or_repo_id, + file: filename + }); + + return buffer; +} + +/** + * Fetches a JSON file from a given path and file name. + * + * @param {string} modelPath The path to the directory containing the file. + * @param {string} fileName The name of the file to fetch. + * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. + * @param {PretrainedOptions} [options] An object containing optional parameters. + * @returns {Promise} The JSON data parsed into a JavaScript object. + * @throws Will throw an error if the file is not found and `fatal` is true. + */ +export async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { + let buffer = await getModelFile(modelPath, fileName, fatal, options); + if (buffer === null) { + // Return empty object + return {} + } + + let decoder = new TextDecoder('utf-8'); + let jsonData = decoder.decode(buffer); + + return JSON.parse(jsonData); +} + +/** + * Read and track progress when reading a Response object + * + * @param {any} response The Response object to read + * @param {function} progress_callback The function to call with progress updates + * @returns {Promise} A Promise that resolves with the Uint8Array buffer + */ +async function readResponse(response, progress_callback) { + + const contentLength = response.headers.get('Content-Length'); + if (contentLength === null) { + console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.') + } + let total = parseInt(contentLength ?? '0'); + let buffer = new Uint8Array(total); + let loaded = 0; + + const reader = response.body.getReader(); + async function read() { + const { done, value } = await reader.read(); + if (done) return; + + let newLoaded = loaded + value.length; + if (newLoaded > total) { + total = newLoaded; + + // Adding the new data will overflow buffer. + // In this case, we extend the buffer + let newBuffer = new Uint8Array(total); + + // copy contents + newBuffer.set(buffer); + + buffer = newBuffer; + } + buffer.set(value, loaded) + loaded = newLoaded; + + const progress = (loaded / total) * 100; + + // Call your function here + progress_callback({ + progress: progress, + loaded: loaded, + total: total, + }) + + return read(); + } + + // Actually read + await read(); + + return buffer; +} + +/** + * Joins multiple parts of a path into a single path, while handling leading and trailing slashes. + * + * @param {...string} parts Multiple parts of a path. + * @returns {string} A string representing the joined path. + */ +function pathJoin(...parts) { + // https://stackoverflow.com/a/55142565 + parts = parts.map((part, index) => { + if (index) { + part = part.replace(new RegExp('^/'), ''); + } + if (index !== parts.length - 1) { + part = part.replace(new RegExp('/$'), ''); + } + return part; + }) + return parts.join('/'); +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/image.js b/core/vendor/node_modules/@xenova/transformers/src/utils/image.js new file mode 100644 index 000000000..2d12cb876 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/image.js @@ -0,0 +1,713 @@ + +/** + * @file Helper module for image processing. + * + * These functions and classes are only used internally, + * meaning an end-user shouldn't need to access anything here. + * + * @module utils/image + */ + +import { getFile } from './hub.js'; +import { env } from '../env.js'; + +// Will be empty (or not used) if running in browser or web-worker +import sharp from 'sharp'; + +const BROWSER_ENV = typeof self !== 'undefined'; +const WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope'; + +let createCanvasFunction; +let ImageDataClass; +let loadImageFunction; +if (BROWSER_ENV) { + // Running in browser or web-worker + createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => { + if (!self.OffscreenCanvas) { + throw new Error('OffscreenCanvas not supported by this browser.'); + } + return new self.OffscreenCanvas(width, height) + }; + loadImageFunction = self.createImageBitmap; + ImageDataClass = self.ImageData; + +} else if (sharp) { + // Running in Node.js, electron, or other non-browser environment + + loadImageFunction = async (/**@type {sharp.Sharp}*/img) => { + const metadata = await img.metadata(); + const rawChannels = metadata.channels; + + let { data, info } = await img.raw().toBuffer({ resolveWithObject: true }); + + const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); + if (rawChannels !== undefined && rawChannels !== info.channels) { + // Make sure the new image has the same number of channels as the input image. + // This is necessary for grayscale images. + newImage.convert(rawChannels); + } + return newImage; + } + +} else { + throw new Error('Unable to load image processing library.'); +} + + +// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268 +const RESAMPLING_MAPPING = { + 0: 'nearest', + 1: 'lanczos', + 2: 'bilinear', + 3: 'bicubic', + 4: 'box', + 5: 'hamming', +} + +/** + * Mapping from file extensions to MIME types. + */ +const CONTENT_TYPE_MAP = new Map([ + ['png', 'image/png'], + ['jpg', 'image/jpeg'], + ['jpeg', 'image/jpeg'], + ['gif', 'image/gif'], +]); + +export class RawImage { + + /** + * Create a new `RawImage` object. + * @param {Uint8ClampedArray|Uint8Array} data The pixel data. + * @param {number} width The width of the image. + * @param {number} height The height of the image. + * @param {1|2|3|4} channels The number of channels. + */ + constructor(data, width, height, channels) { + this.data = data; + this.width = width; + this.height = height; + this.channels = channels; + } + + /** + * Returns the size of the image (width, height). + * @returns {[number, number]} The size of the image (width, height). + */ + get size() { + return [this.width, this.height]; + } + + /** + * Helper method for reading an image from a variety of input types. + * @param {RawImage|string|URL} input + * @returns The image object. + * + * **Example:** Read image from a URL. + * ```javascript + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * // RawImage { + * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], + * // "width": 800, + * // "height": 533, + * // "channels": 3 + * // } + * ``` + */ + static async read(input) { + if (input instanceof RawImage) { + return input; + } else if (typeof input === 'string' || input instanceof URL) { + return await this.fromURL(input); + } else { + throw new Error(`Unsupported input type: ${typeof input}`); + } + } + + + /** + * Read an image from a URL or file path. + * @param {string|URL} url The URL or file path to read the image from. + * @returns {Promise} The image object. + */ + static async fromURL(url) { + let response = await getFile(url); + if (response.status !== 200) { + throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`); + } + let blob = await response.blob(); + return this.fromBlob(blob); + } + + /** + * Helper method to create a new Image from a blob. + * @param {Blob} blob The blob to read the image from. + * @returns {Promise} The image object. + */ + static async fromBlob(blob) { + if (BROWSER_ENV) { + // Running in environment with canvas + let img = await loadImageFunction(blob); + + const ctx = createCanvasFunction(img.width, img.height).getContext('2d'); + + // Draw image to context + ctx.drawImage(img, 0, 0); + + return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); + + } else { + // Use sharp.js to read (and possible resize) the image. + let img = sharp(await blob.arrayBuffer()); + + return await loadImageFunction(img); + } + } + + /** + * Helper method to create a new Image from a tensor + * @param {import('./tensor.js').Tensor} tensor + */ + static fromTensor(tensor, channel_format = 'CHW') { + if (tensor.dims.length !== 3) { + throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`); + } + + if (channel_format === 'CHW') { + tensor = tensor.transpose(1, 2, 0); + } else if (channel_format === 'HWC') { + // Do nothing + } else { + throw new Error(`Unsupported channel format: ${channel_format}`); + } + if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { + throw new Error(`Unsupported tensor type: ${tensor.type}`); + } + switch (tensor.dims[2]) { + case 1: + case 2: + case 3: + case 4: + return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); + default: + throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); + } + } + + /** + * Convert the image to grayscale format. + * @returns {RawImage} `this` to support chaining. + */ + grayscale() { + if (this.channels === 1) { + return this; + } + + let newData = new Uint8ClampedArray(this.width * this.height * 1); + switch (this.channels) { + case 3: // rgb to grayscale + case 4: // rgba to grayscale + for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { + const red = this.data[i]; + const green = this.data[i + 1]; + const blue = this.data[i + 2]; + + newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue); + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this._update(newData, this.width, this.height, 1); + } + + /** + * Convert the image to RGB format. + * @returns {RawImage} `this` to support chaining. + */ + rgb() { + if (this.channels === 3) { + return this; + } + + let newData = new Uint8ClampedArray(this.width * this.height * 3); + + switch (this.channels) { + case 1: // grayscale to rgb + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + } + break; + case 4: // rgba to rgb + for (let i = 0, offset = 0; i < this.data.length; i += 4) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this._update(newData, this.width, this.height, 3); + + } + + /** + * Convert the image to RGBA format. + * @returns {RawImage} `this` to support chaining. + */ + rgba() { + if (this.channels === 4) { + return this; + } + + let newData = new Uint8ClampedArray(this.width * this.height * 4); + + switch (this.channels) { + case 1: // grayscale to rgba + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = 255; + } + break; + case 3: // rgb to rgba + for (let i = 0, offset = 0; i < this.data.length; i += 3) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; + newData[offset++] = 255; + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + + return this._update(newData, this.width, this.height, 4); + } + + /** + * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. + * @param {number} width The width of the new image. + * @param {number} height The height of the new image. + * @param {Object} options Additional options for resizing. + * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. + * @returns {Promise} `this` to support chaining. + */ + async resize(width, height, { + resample = 2, + } = {}) { + + // Ensure resample method is a string + let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; + + if (BROWSER_ENV) { + // TODO use `resample` in browser environment + + // Store number of channels before resizing + let numChannels = this.channels; + + // Create canvas object for this image + let canvas = this.toCanvas(); + + // Actually perform resizing using the canvas API + const ctx = createCanvasFunction(width, height).getContext('2d'); + + // Draw image to context, resizing in the process + ctx.drawImage(canvas, 0, 0, width, height); + + // Create image from the resized data + let resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); + + // Convert back so that image has the same number of channels as before + return resizedImage.convert(numChannels); + + } else { + // Create sharp image from raw data, and resize + let img = this.toSharp(); + + switch (resampleMethod) { + case 'box': + case 'hamming': + if (resampleMethod === 'box' || resampleMethod === 'hamming') { + console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`); + resampleMethod = 'bilinear'; + } + + case 'nearest': + case 'bilinear': + case 'bicubic': + // Perform resizing using affine transform. + // This matches how the python Pillow library does it. + img = img.affine([width / this.width, 0, 0, height / this.height], { + interpolator: resampleMethod + }); + break; + + case 'lanczos': + // https://github.com/python-pillow/Pillow/discussions/5519 + // https://github.com/lovell/sharp/blob/main/docs/api-resize.md + img = img.resize({ + width, height, + fit: 'fill', + kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 + }); + break; + + default: + throw new Error(`Resampling method ${resampleMethod} is not supported.`); + } + + return await loadImageFunction(img); + } + + } + + async pad([left, right, top, bottom]) { + left = Math.max(left, 0); + right = Math.max(right, 0); + top = Math.max(top, 0); + bottom = Math.max(bottom, 0); + + if (left === 0 && right === 0 && top === 0 && bottom === 0) { + // No padding needed + return this; + } + + if (BROWSER_ENV) { + // Store number of channels before padding + let numChannels = this.channels; + + // Create canvas object for this image + let canvas = this.toCanvas(); + + let newWidth = this.width + left + right; + let newHeight = this.height + top + bottom; + + // Create a new canvas of the desired size. + const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d'); + + // Draw image to context, padding in the process + ctx.drawImage(canvas, + 0, 0, this.width, this.height, + left, top, newWidth, newHeight + ); + + // Create image from the padded data + let paddedImage = new RawImage( + ctx.getImageData(0, 0, newWidth, newHeight).data, + newWidth, newHeight, 4); + + // Convert back so that image has the same number of channels as before + return paddedImage.convert(numChannels); + + } else { + let img = this.toSharp().extend({ left, right, top, bottom }); + return await loadImageFunction(img); + } + } + + async crop([x_min, y_min, x_max, y_max]) { + // Ensure crop bounds are within the image + x_min = Math.max(x_min, 0); + y_min = Math.max(y_min, 0); + x_max = Math.min(x_max, this.width - 1); + y_max = Math.min(y_max, this.height - 1); + + // Do nothing if the crop is the entire image + if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { + return this; + } + + const crop_width = x_max - x_min + 1; + const crop_height = y_max - y_min + 1; + + if (BROWSER_ENV) { + // Store number of channels before resizing + const numChannels = this.channels; + + // Create canvas object for this image + const canvas = this.toCanvas(); + + // Create a new canvas of the desired size. This is needed since if the + // image is too small, we need to pad it with black pixels. + const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d'); + + // Draw image to context, cropping in the process + ctx.drawImage(canvas, + x_min, y_min, crop_width, crop_height, + 0, 0, crop_width, crop_height + ); + + // Create image from the resized data + const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); + + // Convert back so that image has the same number of channels as before + return resizedImage.convert(numChannels); + + } else { + // Create sharp image from raw data + const img = this.toSharp().extract({ + left: x_min, + top: y_min, + width: crop_width, + height: crop_height, + }); + + return await loadImageFunction(img); + } + + } + + async center_crop(crop_width, crop_height) { + // If the image is already the desired size, return it + if (this.width === crop_width && this.height === crop_height) { + return this; + } + + // Determine bounds of the image in the new canvas + let width_offset = (this.width - crop_width) / 2; + let height_offset = (this.height - crop_height) / 2; + + + if (BROWSER_ENV) { + // Store number of channels before resizing + let numChannels = this.channels; + + // Create canvas object for this image + let canvas = this.toCanvas(); + + // Create a new canvas of the desired size. This is needed since if the + // image is too small, we need to pad it with black pixels. + const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d'); + + let sourceX = 0; + let sourceY = 0; + let destX = 0; + let destY = 0; + + if (width_offset >= 0) { + sourceX = width_offset; + } else { + destX = -width_offset; + } + + if (height_offset >= 0) { + sourceY = height_offset; + } else { + destY = -height_offset; + } + + // Draw image to context, cropping in the process + ctx.drawImage(canvas, + sourceX, sourceY, crop_width, crop_height, + destX, destY, crop_width, crop_height + ); + + // Create image from the resized data + let resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); + + // Convert back so that image has the same number of channels as before + return resizedImage.convert(numChannels); + + } else { + // Create sharp image from raw data + let img = this.toSharp(); + + if (width_offset >= 0 && height_offset >= 0) { + // Cropped image lies entirely within the original image + img = img.extract({ + left: Math.floor(width_offset), + top: Math.floor(height_offset), + width: crop_width, + height: crop_height, + }) + } else if (width_offset <= 0 && height_offset <= 0) { + // Cropped image lies entirely outside the original image, + // so we add padding + let top = Math.floor(-height_offset); + let left = Math.floor(-width_offset); + img = img.extend({ + top: top, + left: left, + + // Ensures the resulting image has the desired dimensions + right: crop_width - this.width - left, + bottom: crop_height - this.height - top, + }); + } else { + // Cropped image lies partially outside the original image. + // We first pad, then crop. + + let y_padding = [0, 0]; + let y_extract = 0; + if (height_offset < 0) { + y_padding[0] = Math.floor(-height_offset); + y_padding[1] = crop_height - this.height - y_padding[0]; + } else { + y_extract = Math.floor(height_offset); + } + + let x_padding = [0, 0]; + let x_extract = 0; + if (width_offset < 0) { + x_padding[0] = Math.floor(-width_offset); + x_padding[1] = crop_width - this.width - x_padding[0]; + } else { + x_extract = Math.floor(width_offset); + } + + img = img.extend({ + top: y_padding[0], + bottom: y_padding[1], + left: x_padding[0], + right: x_padding[1], + }).extract({ + left: x_extract, + top: y_extract, + width: crop_width, + height: crop_height, + }) + } + + return await loadImageFunction(img); + } + } + + async toBlob(type = 'image/png', quality = 1) { + if (!BROWSER_ENV) { + throw new Error('toBlob() is only supported in browser environments.') + } + + const canvas = this.toCanvas(); + return await canvas.convertToBlob({ type, quality }); + } + + toCanvas() { + if (!BROWSER_ENV) { + throw new Error('toCanvas() is only supported in browser environments.') + } + + // Clone, and convert data to RGBA before drawing to canvas. + // This is because the canvas API only supports RGBA + let cloned = this.clone().rgba(); + + // Create canvas object for the cloned image + let clonedCanvas = createCanvasFunction(cloned.width, cloned.height); + + // Draw image to context + let data = new ImageDataClass(cloned.data, cloned.width, cloned.height); + clonedCanvas.getContext('2d').putImageData(data, 0, 0); + + return clonedCanvas; + } + + /** + * Helper method to update the image data. + * @param {Uint8ClampedArray} data The new image data. + * @param {number} width The new width of the image. + * @param {number} height The new height of the image. + * @param {1|2|3|4|null} [channels] The new number of channels of the image. + * @private + */ + _update(data, width, height, channels = null) { + this.data = data; + this.width = width; + this.height = height; + if (channels !== null) { + this.channels = channels; + } + return this; + } + + /** + * Clone the image + * @returns {RawImage} The cloned image + */ + clone() { + return new RawImage(this.data.slice(), this.width, this.height, this.channels); + } + + /** + * Helper method for converting image to have a certain number of channels + * @param {number} numChannels The number of channels. Must be 1, 3, or 4. + * @returns {RawImage} `this` to support chaining. + */ + convert(numChannels) { + if (this.channels === numChannels) return this; // Already correct number of channels + + switch (numChannels) { + 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; + } + + /** + * Save the image to the given path. + * @param {string} path The path to save the image to. + */ + async save(path) { + + if (BROWSER_ENV) { + if (WEBWORKER_ENV) { + throw new Error('Unable to save an image from a Web Worker.') + } + + const extension = path.split('.').pop().toLowerCase(); + const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png'; + + // Convert image to Blob + const blob = await this.toBlob(mime); + + // Convert the canvas content to a data URL + const dataURL = URL.createObjectURL(blob); + + // Create an anchor element with the data URL as the href attribute + const downloadLink = document.createElement('a'); + downloadLink.href = dataURL; + + // Set the download attribute to specify the desired filename for the downloaded image + downloadLink.download = path; + + // Trigger the download + downloadLink.click(); + + // Clean up: remove the anchor element from the DOM + downloadLink.remove(); + + } else if (!env.useFS) { + throw new Error('Unable to save the image because filesystem is disabled in this environment.') + + } else { + const img = this.toSharp(); + return await img.toFile(path); + } + } + + toSharp() { + if (BROWSER_ENV) { + throw new Error('toSharp() is only supported in server-side environments.') + } + + return sharp(this.data, { + raw: { + width: this.width, + height: this.height, + channels: this.channels + } + }); + } +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/maths.js b/core/vendor/node_modules/@xenova/transformers/src/utils/maths.js new file mode 100644 index 000000000..216def07e --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/maths.js @@ -0,0 +1,954 @@ + +/** + * @file Helper module for mathematical processing. + * + * These functions and classes are only used internally, + * meaning an end-user shouldn't need to access anything here. + * + * @module utils/maths + */ + +/** + * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray + * @typedef {BigInt64Array | BigUint64Array} BigTypedArray + * @typedef {TypedArray | BigTypedArray} AnyTypedArray + */ + +/** + * @param {TypedArray} input + */ +export function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) { + // TODO use mode and align_corners + + // Output image dimensions + const x_scale = out_width / in_width; + const y_scale = out_height / in_height; + + // Output image + // @ts-ignore + const out_img = new input.constructor(out_height * out_width * in_channels); + + // Pre-calculate strides + const inStride = in_height * in_width; + const outStride = out_height * out_width; + + for (let i = 0; i < out_height; ++i) { + for (let j = 0; j < out_width; ++j) { + // Calculate output offset + const outOffset = i * out_width + j; + + // Calculate input pixel coordinates + const x = (j + 0.5) / x_scale - 0.5; + const y = (i + 0.5) / y_scale - 0.5; + + // Calculate the four nearest input pixels + // We also check if the input pixel coordinates are within the image bounds + let x1 = Math.floor(x); + let y1 = Math.floor(y); + const x2 = Math.min(x1 + 1, in_width - 1); + const y2 = Math.min(y1 + 1, in_height - 1); + + x1 = Math.max(x1, 0); + y1 = Math.max(y1, 0); + + + // Calculate the fractional distances between the input pixel and the four nearest pixels + const s = x - x1; + const t = y - y1; + + // Perform bilinear interpolation + const w1 = (1 - s) * (1 - t); + const w2 = s * (1 - t); + const w3 = (1 - s) * t; + const w4 = s * t; + + // Calculate the four nearest input pixel indices + const yStride = y1 * in_width; + const xStride = y2 * in_width; + const idx1 = yStride + x1; + const idx2 = yStride + x2; + const idx3 = xStride + x1; + const idx4 = xStride + x2; + + for (let k = 0; k < in_channels; ++k) { + // Calculate channel offset + const cOffset = k * inStride; + + out_img[k * outStride + outOffset] = + w1 * input[cOffset + idx1] + + w2 * input[cOffset + idx2] + + w3 * input[cOffset + idx3] + + w4 * input[cOffset + idx4]; + } + } + } + + return out_img; +} + + +/** + * Helper method to transpose a `AnyTypedArray` directly + * @template {AnyTypedArray} T + * @param {T} array + * @param {number[]} dims + * @param {number[]} axes + * @returns {[T, number[]]} The transposed array and the new shape. + */ +export function transpose_data(array, dims, axes) { + // Calculate the new shape of the transposed array + // and the stride of the original array + const shape = new Array(axes.length); + const stride = new Array(axes.length); + + for (let i = axes.length - 1, s = 1; i >= 0; --i) { + stride[i] = s; + shape[i] = dims[axes[i]]; + s *= shape[i]; + } + + // Precompute inverse mapping of stride + const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); + + // Create the transposed array with the new shape + // @ts-ignore + const transposedData = new array.constructor(array.length); + + // Transpose the original array to the new array + for (let i = 0; i < array.length; ++i) { + let newIndex = 0; + for (let j = dims.length - 1, k = i; j >= 0; --j) { + newIndex += (k % dims[j]) * invStride[j]; + k = Math.floor(k / dims[j]); + } + transposedData[newIndex] = array[i]; + } + + return [transposedData, shape]; +} + + +/** + * Compute the softmax of an array of numbers. + * @template {TypedArray|number[]} T + * @param {T} arr The array of numbers to compute the softmax of. + * @returns {T} The softmax array. + */ +export function softmax(arr) { + // Compute the maximum value in the array + const maxVal = max(arr)[0]; + + // Compute the exponentials of the array values + const exps = arr.map(x => Math.exp(x - maxVal)); + + // Compute the sum of the exponentials + // @ts-ignore + const sumExps = exps.reduce((acc, val) => acc + val, 0); + + // Compute the softmax values + const softmaxArr = exps.map(x => x / sumExps); + + return /** @type {T} */(softmaxArr); +} + +/** + * Calculates the logarithm of the softmax function for the input array. + * @template {TypedArray|number[]} T + * @param {T} arr The input array to calculate the log_softmax function for. + * @returns {T} The resulting log_softmax array. + */ +export function log_softmax(arr) { + // Compute the softmax values + const softmaxArr = softmax(arr); + + // Apply log formula to each element + const logSoftmaxArr = softmaxArr.map(x => Math.log(x)); + + return /** @type {T} */(logSoftmaxArr); +} + +/** + * Calculates the dot product of two arrays. + * @param {number[]} arr1 The first array. + * @param {number[]} arr2 The second array. + * @returns {number} The dot product of arr1 and arr2. + */ +export function dot(arr1, arr2) { + return arr1.reduce((acc, val, i) => acc + val * arr2[i], 0); +} + + +/** + * Get the top k items from an iterable, sorted by descending order + * @param {any[]|TypedArray} items The items to be sorted + * @param {number|null} [top_k=0] The number of top items to return (default: 0 = return all) + * @returns {[number, any][]} The top k items, sorted by descending order + */ +export function getTopItems(items, top_k = 0) { + // if top == 0, return all + + items = Array.from(items) + .map((x, i) => [i, x]) // Get indices ([index, score]) + .sort((a, b) => b[1] - a[1]) // Sort by log probabilities + + if (top_k !== null && top_k > 0) { + items = items.slice(0, top_k); // Get top k items + } + + return items +} + +/** + * Computes the cosine similarity between two arrays. + * + * @param {number[]} arr1 The first array. + * @param {number[]} arr2 The second array. + * @returns {number} The cosine similarity between the two arrays. + */ +export function cos_sim(arr1, arr2) { + // Calculate dot product of the two arrays + const dotProduct = dot(arr1, arr2); + + // Calculate the magnitude of the first array + const magnitudeA = magnitude(arr1); + + // Calculate the magnitude of the second array + const magnitudeB = magnitude(arr2); + + // Calculate the cosine similarity + const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB); + + return cosineSimilarity; +} + +/** + * Calculates the magnitude of a given array. + * @param {number[]} arr The array to calculate the magnitude of. + * @returns {number} The magnitude of the array. + */ +export function magnitude(arr) { + return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0)); +} + + +/** + * Returns the value and index of the minimum element in an array. + * @param {number[]|TypedArray} arr array of numbers. + * @returns {number[]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin] + * @throws {Error} If array is empty. + */ +export function min(arr) { + if (arr.length === 0) throw Error('Array must not be empty'); + let min = arr[0]; + let indexOfMin = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] < min) { + min = arr[i]; + indexOfMin = i; + } + } + return [min, indexOfMin]; +} + + +/** + * Returns the value and index of the maximum element in an array. + * @param {number[]|AnyTypedArray} arr array of numbers. + * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax] + * @throws {Error} If array is empty. + */ +export function max(arr) { + if (arr.length === 0) throw Error('Array must not be empty'); + let max = arr[0]; + let indexOfMax = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] > max) { + max = arr[i]; + indexOfMax = i; + } + } + return [Number(max), indexOfMax]; +} + +function isPowerOfTwo(number) { + // Check if the number is greater than 0 and has only one bit set to 1 + return (number > 0) && ((number & (number - 1)) === 0); +} + +/** + * Implementation of Radix-4 FFT. + * + * P2FFT class provides functionality for performing Fast Fourier Transform on arrays + * which are a power of two in length. + * Code adapted from https://www.npmjs.com/package/fft.js + */ +class P2FFT { + /** + * @param {number} size The size of the input array. Must be a power of two larger than 1. + * @throws {Error} FFT size must be a power of two larger than 1. + */ + constructor(size) { + this.size = size | 0; // convert to a 32-bit signed integer + if (this.size <= 1 || !isPowerOfTwo(this.size)) + throw new Error('FFT size must be a power of two larger than 1'); + + this._csize = size << 1; + + this.table = new Float64Array(this.size * 2); + for (let i = 0; i < this.table.length; i += 2) { + const angle = Math.PI * i / this.size; + this.table[i] = Math.cos(angle); + this.table[i + 1] = -Math.sin(angle); + } + + // Find size's power of two + let power = 0; + for (let t = 1; this.size > t; t <<= 1) + ++power; + + // Calculate initial step's width: + // * If we are full radix-4, it is 2x smaller to give inital len=8 + // * Otherwise it is the same as `power` to give len=4 + this._width = power % 2 === 0 ? power - 1 : power; + + // Pre-compute bit-reversal patterns + this._bitrev = new Int32Array(1 << this._width); + for (let j = 0; j < this._bitrev.length; ++j) { + this._bitrev[j] = 0; + for (let shift = 0; shift < this._width; shift += 2) { + const revShift = this._width - shift - 2; + this._bitrev[j] |= ((j >>> shift) & 3) << revShift; + } + } + } + + /** + * Create a complex number array with size `2 * size` + * + * @returns {Float64Array} A complex number array with size `2 * size` + */ + createComplexArray() { + return new Float64Array(this._csize); + } + + /** + * Converts a complex number representation stored in a Float64Array to an array of real numbers. + * + * @param {Float64Array} complex The complex number representation to be converted. + * @param {number[]} [storage] An optional array to store the result in. + * @returns {number[]} An array of real numbers representing the input complex number representation. + */ + fromComplexArray(complex, storage) { + const res = storage || new Array(complex.length >>> 1); + for (let i = 0; i < complex.length; i += 2) + res[i >>> 1] = complex[i]; + return res; + } + + /** + * Convert a real-valued input array to a complex-valued output array. + * @param {Float64Array} input The real-valued input array. + * @param {Float64Array} [storage] Optional buffer to store the output array. + * @returns {Float64Array} The complex-valued output array. + */ + toComplexArray(input, storage) { + const res = storage || this.createComplexArray(); + for (let i = 0; i < res.length; i += 2) { + res[i] = input[i >>> 1]; + res[i + 1] = 0; + } + return res; + } + + /** + * Completes the spectrum by adding its mirrored negative frequency components. + * @param {Float64Array} spectrum The input spectrum. + * @returns {void} + */ + completeSpectrum(spectrum) { + const size = this._csize; + const half = size >>> 1; + for (let i = 2; i < half; i += 2) { + spectrum[size - i] = spectrum[i]; + spectrum[size - i + 1] = -spectrum[i + 1]; + } + } + + /** + * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. + * + * @param {Float64Array} out The output buffer to store the result. + * @param {Float64Array} data The input data to transform. + * + * @throws {Error} Input and output buffers must be different. + * + * @returns {void} + */ + transform(out, data) { + if (out === data) + throw new Error('Input and output buffers must be different'); + + this._transform4(out, data, 1 /* DONE */); + } + + /** + * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. + * The input buffer must contain real values only, while the output buffer will contain complex values. The input and + * output buffers must be different. + * + * @param {Float64Array} out The output buffer. + * @param {Float64Array} data The input buffer containing real values. + * + * @throws {Error} If the input and output buffers are the same. + */ + realTransform(out, data) { + if (out === data) + throw new Error('Input and output buffers must be different'); + + this._realTransform4(out, data, 1 /* DONE */); + } + + /** + * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. + * The `out` array must be a different buffer than the `data` array. The `out` array will contain the + * result of the transformation. The `data` array will not be modified. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input data to transform. + * @throws {Error} If `out` and `data` refer to the same buffer. + * @returns {void} + */ + inverseTransform(out, data) { + if (out === data) + throw new Error('Input and output buffers must be different'); + + this._transform4(out, data, -1 /* DONE */); + for (let i = 0; i < out.length; ++i) + out[i] /= this.size; + } + + /** + * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {number} inv A scaling factor to apply to the transform. + * @returns {void} + */ + _transform4(out, data, inv) { + // radix-4 implementation + + const size = this._csize; + + // Initial step (permute and transform) + const width = this._width; + let step = 1 << width; + let len = (size / step) << 1; + + let outOff; + let t; + const bitrev = this._bitrev; + if (len === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleTransform2(data, out, outOff, off, step); + } + } else { + // len === 8 + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleTransform4(data, out, outOff, off, step, inv); + } + } + + // Loop through steps in decreasing order + for (step >>= 2; step >= 2; step >>= 2) { + len = (size / step) << 1; + const quarterLen = len >>> 2; + + // Loop through offsets in the data + for (outOff = 0; outOff < size; outOff += len) { + // Full case + const limit = outOff + quarterLen - 1; + for (let i = outOff, k = 0; i < limit; i += 2, k += step) { + const A = i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + + // Original values + const Ar = out[A]; + const Ai = out[A + 1]; + const Br = out[B]; + const Bi = out[B + 1]; + const Cr = out[C]; + const Ci = out[C + 1]; + const Dr = out[D]; + const Di = out[D + 1]; + + const tableBr = this.table[k]; + const tableBi = inv * this.table[k + 1]; + const MBr = Br * tableBr - Bi * tableBi; + const MBi = Br * tableBi + Bi * tableBr; + + const tableCr = this.table[2 * k]; + const tableCi = inv * this.table[2 * k + 1]; + const MCr = Cr * tableCr - Ci * tableCi; + const MCi = Cr * tableCi + Ci * tableCr; + + const tableDr = this.table[3 * k]; + const tableDi = inv * this.table[3 * k + 1]; + const MDr = Dr * tableDr - Di * tableDi; + const MDi = Dr * tableDi + Di * tableDr; + + // Pre-Final values + const T0r = Ar + MCr; + const T0i = Ai + MCi; + const T1r = Ar - MCr; + const T1i = Ai - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + + // Final values + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + out[D] = T1r - T3i; + out[D + 1] = T1i + T3r; + } + } + } + } + + /** + * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {Float64Array} out The output buffer for the transformed data. + * @param {number} outOff The offset at which to write the output data. + * @param {number} off The offset at which to begin reading the input data. + * @param {number} step The step size for indexing the input data. + * @returns {void} + */ + _singleTransform2(data, out, outOff, off, step) { + // radix-2 implementation + // NOTE: Only called for len=4 + + const evenR = data[off]; + const evenI = data[off + 1]; + const oddR = data[off + step]; + const oddI = data[off + step + 1]; + + out[outOff] = evenR + oddR; + out[outOff + 1] = evenI + oddI; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = evenI - oddI; + } + + /** + * Performs radix-4 transformation on input data of length 8 + * + * @param {Float64Array} data Input data array of length 8 + * @param {Float64Array} out Output data array of length 8 + * @param {number} outOff Index of output array to start writing from + * @param {number} off Index of input array to start reading from + * @param {number} step Step size between elements in input array + * @param {number} inv Scaling factor for inverse transform + * + * @returns {void} + */ + _singleTransform4(data, out, outOff, off, step, inv) { + // radix-4 + // NOTE: Only called for len=8 + const step2 = step * 2; + const step3 = step * 3; + + // Original values + const Ar = data[off]; + const Ai = data[off + 1]; + const Br = data[off + step]; + const Bi = data[off + step + 1]; + const Cr = data[off + step2]; + const Ci = data[off + step2 + 1]; + const Dr = data[off + step3]; + const Di = data[off + step3 + 1]; + + // Pre-Final values + const T0r = Ar + Cr; + const T0i = Ai + Ci; + const T1r = Ar - Cr; + const T1i = Ai - Ci; + const T2r = Br + Dr; + const T2i = Bi + Di; + const T3r = inv * (Br - Dr); + const T3i = inv * (Bi - Di); + + // Final values + out[outOff] = T0r + T2r; + out[outOff + 1] = T0i + T2i; + out[outOff + 2] = T1r + T3i; + out[outOff + 3] = T1i - T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = T0i - T2i; + out[outOff + 6] = T1r - T3i; + out[outOff + 7] = T1i + T3r; + } + + /** + * Real input radix-4 implementation + * @param {Float64Array} out Output array for the transformed data + * @param {Float64Array} data Input array of real data to be transformed + * @param {number} inv The scale factor used to normalize the inverse transform + */ + _realTransform4(out, data, inv) { + // Real input radix-4 implementation + const size = this._csize; + + // Initial step (permute and transform) + const width = this._width; + let step = 1 << width; + let len = (size / step) << 1; + + let outOff; + let t; + const bitrev = this._bitrev; + if (len === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); + } + } else { + // len === 8 + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); + } + } + + // TODO: Optimize once https://github.com/indutny/fft.js/issues/25 is fixed + // Loop through steps in decreasing order + for (step >>= 2; step >= 2; step >>= 2) { + len = (size / step) << 1; + const quarterLen = len >>> 2; + + // Loop through offsets in the data + for (outOff = 0; outOff < size; outOff += len) { + // Full case + const limit = outOff + quarterLen - 1; + for (let i = outOff, k = 0; i < limit; i += 2, k += step) { + const A = i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + + // Original values + const Ar = out[A]; + const Ai = out[A + 1]; + const Br = out[B]; + const Bi = out[B + 1]; + const Cr = out[C]; + const Ci = out[C + 1]; + const Dr = out[D]; + const Di = out[D + 1]; + + const tableBr = this.table[k]; + const tableBi = inv * this.table[k + 1]; + const MBr = Br * tableBr - Bi * tableBi; + const MBi = Br * tableBi + Bi * tableBr; + + const tableCr = this.table[2 * k]; + const tableCi = inv * this.table[2 * k + 1]; + const MCr = Cr * tableCr - Ci * tableCi; + const MCi = Cr * tableCi + Ci * tableCr; + + const tableDr = this.table[3 * k]; + const tableDi = inv * this.table[3 * k + 1]; + const MDr = Dr * tableDr - Di * tableDi; + const MDi = Dr * tableDi + Di * tableDr; + + // Pre-Final values + const T0r = Ar + MCr; + const T0i = Ai + MCi; + const T1r = Ar - MCr; + const T1i = Ai - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + + // Final values + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + out[D] = T1r - T3i; + out[D + 1] = T1i + T3r; + } + } + } + } + + /** + * Performs a single real input radix-2 transformation on the provided data + * + * @param {Float64Array} data The input data array + * @param {Float64Array} out The output data array + * @param {number} outOff The output offset + * @param {number} off The input offset + * @param {number} step The step + * + * @returns {void} + */ + _singleRealTransform2(data, out, outOff, off, step) { + // radix-2 implementation + // NOTE: Only called for len=4 + + const evenR = data[off]; + const oddR = data[off + step]; + + out[outOff] = evenR + oddR; + out[outOff + 1] = 0; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = 0; + } + + /** + * Computes a single real-valued transform using radix-4 algorithm. + * This method is only called for len=8. + * + * @param {Float64Array} data The input data array. + * @param {Float64Array} out The output data array. + * @param {number} outOff The offset into the output array. + * @param {number} off The offset into the input array. + * @param {number} step The step size for the input array. + * @param {number} inv The value of inverse. + */ + _singleRealTransform4(data, out, outOff, off, step, inv) { + // radix-4 + // NOTE: Only called for len=8 + const step2 = step * 2; + const step3 = step * 3; + + // Original values + const Ar = data[off]; + const Br = data[off + step]; + const Cr = data[off + step2]; + const Dr = data[off + step3]; + + // Pre-Final values + const T0r = Ar + Cr; + const T1r = Ar - Cr; + const T2r = Br + Dr; + const T3r = inv * (Br - Dr); + + // Final values + out[outOff] = T0r + T2r; + out[outOff + 1] = 0; + out[outOff + 2] = T1r; + out[outOff + 3] = -T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = 0; + out[outOff + 6] = T1r; + out[outOff + 7] = T3r; + } +} + +/** + * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays + * which are not a power of two in length. In such cases, the chirp-z transform is used. + * + * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156 + */ +class NP2FFT { + + /** + * Constructs a new NP2FFT object. + * @param {number} fft_length The length of the FFT + */ + constructor(fft_length) { + // Helper variables + const a = 2 * (fft_length - 1); + const b = 2 * (2 * fft_length - 1); + const nextP2 = 2 ** (Math.ceil(Math.log2(b))) + this.bufferSize = nextP2; + this._a = a; + + // Define buffers + // Compute chirp for transform + const chirp = new Float64Array(b); + const ichirp = new Float64Array(nextP2); + this._chirpBuffer = new Float64Array(nextP2); + this._buffer1 = new Float64Array(nextP2); + this._buffer2 = new Float64Array(nextP2); + this._outBuffer1 = new Float64Array(nextP2); + this._outBuffer2 = new Float64Array(nextP2); + + // Compute complex exponentiation + const theta = -2 * Math.PI / fft_length; + const baseR = Math.cos(theta); + const baseI = Math.sin(theta); + + // Precompute helper for chirp-z transform + for (let i = 0; i < b >> 1; ++i) { + // Compute complex power: + const e = (i + 1 - fft_length) ** 2 / 2.0; + + // Compute the modulus and argument of the result + const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; + const result_arg = e * Math.atan2(baseI, baseR); + + // Convert the result back to rectangular form + // and assign to chirp and ichirp + const i2 = 2 * i; + chirp[i2] = result_mod * Math.cos(result_arg); + chirp[i2 + 1] = result_mod * Math.sin(result_arg); + + // conjugate + ichirp[i2] = chirp[i2]; + ichirp[i2 + 1] = - chirp[i2 + 1]; + } + this._slicedChirpBuffer = chirp.subarray(a, b); + + // create object to perform Fast Fourier Transforms + // with `nextP2` complex numbers + this._f = new P2FFT(nextP2 >> 1); + this._f.transform(this._chirpBuffer, ichirp); + } + + _transform(output, input, real) { + const ib1 = this._buffer1; + const ib2 = this._buffer2; + const ob2 = this._outBuffer1; + const ob3 = this._outBuffer2; + const cb = this._chirpBuffer; + const sb = this._slicedChirpBuffer; + const a = this._a; + + if (real) { + // Real multiplication + for (let j = 0; j < sb.length; j += 2) { + const j2 = j + 1 + const j3 = j >> 1; + + const a_real = input[j3]; + ib1[j] = a_real * sb[j]; + ib1[j2] = a_real * sb[j2]; + } + } else { + // Complex multiplication + for (let j = 0; j < sb.length; j += 2) { + const j2 = j + 1 + ib1[j] = input[j] * sb[j] - input[j2] * sb[j2]; + ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j]; + } + } + this._f.transform(ob2, ib1); + + for (let j = 0; j < cb.length; j += 2) { + const j2 = j + 1; + + ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2]; + ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j]; + } + this._f.inverseTransform(ob3, ib2); + + for (let j = 0; j < ob3.length; j += 2) { + const a_real = ob3[j + a]; + const a_imag = ob3[j + a + 1]; + const b_real = sb[j]; + const b_imag = sb[j + 1]; + + output[j] = a_real * b_real - a_imag * b_imag; + output[j + 1] = a_real * b_imag + a_imag * b_real; + } + } + + transform(output, input) { + this._transform(output, input, false); + } + + realTransform(output, input) { + this._transform(output, input, true); + } +} + +export class FFT { + constructor(fft_length) { + this.fft_length = fft_length; + this.isPowerOfTwo = isPowerOfTwo(fft_length); + if (this.isPowerOfTwo) { + this.fft = new P2FFT(fft_length); + this.outputBufferSize = 2 * fft_length; + } else { + this.fft = new NP2FFT(fft_length); + this.outputBufferSize = this.fft.bufferSize; + } + } + + realTransform(out, input) { + this.fft.realTransform(out, input); + } + + transform(out, input) { + this.fft.transform(out, input); + } +} + + +/** + * Performs median filter on the provided data. Padding is done by mirroring the data. + * @param {AnyTypedArray} data The input array + * @param {number} windowSize The window size + */ +export function medianFilter(data, windowSize) { + + if (windowSize % 2 === 0 || windowSize <= 0) { + throw new Error('Window size must be a positive odd number'); + } + + // @ts-ignore + const outputArray = new data.constructor(data.length); + + // @ts-ignore + const buffer = new data.constructor(windowSize); // Reusable array for storing values + + const halfWindowSize = Math.floor(windowSize / 2); + + for (let i = 0; i < data.length; ++i) { + let valuesIndex = 0; + + for (let j = -halfWindowSize; j <= halfWindowSize; ++j) { + let index = i + j; + if (index < 0) { + index = Math.abs(index); + } else if (index >= data.length) { + index = 2 * (data.length - 1) - index; + } + + buffer[valuesIndex++] = data[index]; + } + + buffer.sort(); + outputArray[i] = buffer[halfWindowSize]; + } + + return outputArray; +} + +/** + * Helper function to round a number to a given number of decimals + * @param {number} num The number to round + * @param {number} decimals The number of decimals + * @returns {number} The rounded number + */ +export function round(num, decimals) { + const pow = Math.pow(10, decimals); + return Math.round(num * pow) / pow; +} diff --git a/core/vendor/node_modules/@xenova/transformers/src/utils/tensor.js b/core/vendor/node_modules/@xenova/transformers/src/utils/tensor.js new file mode 100644 index 000000000..74cb23880 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/src/utils/tensor.js @@ -0,0 +1,1157 @@ +/** + * @file Helper module for `Tensor` processing. + * + * These functions and classes are only used internally, + * meaning an end-user shouldn't need to access anything here. + * + * @module utils/tensor + */ + +import { ONNX } from '../backends/onnx.js'; + +import { + interpolate_data, + transpose_data +} from './maths.js'; + + +const DataTypeMap = Object.freeze({ + float32: Float32Array, + float64: Float64Array, + string: Array, // string[] + int8: Int8Array, + uint8: Uint8Array, + int16: Int16Array, + uint16: Uint16Array, + int32: Int32Array, + uint32: Uint32Array, + int64: BigInt64Array, + uint64: BigUint64Array, + bool: Uint8Array, +}); + +/** + * @typedef {keyof typeof DataTypeMap} DataType + * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray + */ + +const ONNXTensor = ONNX.Tensor; + +export class Tensor { + /** @type {number[]} Dimensions of the tensor. */ + dims; + + /** @type {DataType} Type of the tensor. */ + type; + + /** @type {DataArray} The data stored in the tensor. */ + data; + + /** @type {number} The number of elements in the tensor. */ + size; + + /** + * Create a new Tensor or copy an existing Tensor. + * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args + */ + constructor(...args) { + if (args[0] instanceof ONNXTensor) { + // Create shallow copy + Object.assign(this, args[0]); + + } else { + // Create new tensor + Object.assign(this, new ONNXTensor( + /** @type {DataType} */(args[0]), + /** @type {Exclude} */(args[1]), + args[2] + )); + } + + return new Proxy(this, { + get: (obj, key) => { + if (typeof key === 'string') { + let index = Number(key); + if (Number.isInteger(index)) { + // key is an integer (i.e., index) + return obj._getitem(index); + } + } + // @ts-ignore + return obj[key]; + }, + set: (obj, key, value) => { + // TODO allow setting of data + + // @ts-ignore + return obj[key] = value; + } + }); + } + + /** + * Returns an iterator object for iterating over the tensor data in row-major order. + * If the tensor has more than one dimension, the iterator will yield subarrays. + * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. + */ + *[Symbol.iterator]() { + const [iterLength, ...iterDims] = this.dims; + + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + for (let i = 0; i < iterLength; ++i) { + yield this._subarray(i, iterSize, iterDims); + } + } else { + yield* this.data + } + + } + + /** + * Index into a Tensor object. + * @param {number} index The index to access. + * @returns {Tensor} The data at the specified index. + */ + _getitem(index) { + const [iterLength, ...iterDims] = this.dims; + + index = safeIndex(index, iterLength); + + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + return this._subarray(index, iterSize, iterDims); + } else { + return new Tensor(this.type, [this.data[index]], iterDims); + } + } + + /** + * @param {number|bigint} item The item to search for in the tensor + * @returns {number} The index of the first occurrence of item in the tensor data. + */ + indexOf(item) { + for (let index = 0; index < this.data.length; ++index) { + // Note: == instead of === so we can match Ints with BigInts + if (this.data[index] == item) { + return index; + } + } + return -1; + } + + /** + * @param {number} index + * @param {number} iterSize + * @param {any} iterDims + * @returns {Tensor} + */ + _subarray(index, iterSize, iterDims) { + const o1 = index * iterSize; + const o2 = (index + 1) * iterSize; + + // We use subarray if available (typed array), otherwise we use slice (normal array) + const data = + ('subarray' in this.data) + ? this.data.subarray(o1, o2) + : this.data.slice(o1, o2); + return new Tensor(this.type, data, iterDims); + } + + /** + * Returns the value of this tensor as a standard JavaScript Number. This only works + * for tensors with one element. For other cases, see `Tensor.tolist()`. + * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. + * @throws {Error} If the tensor has more than one element. + */ + item() { + if (this.data.length !== 1) { + throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`); + } + return this.data[0]; + } + + /** + * Convert tensor data to a n-dimensional JS list + * @returns {Array} + */ + tolist() { + return reshape(this.data, this.dims) + } + + /** + * Return a new Tensor with the sigmoid function applied to each element. + * @returns {Tensor} The tensor with the sigmoid function applied. + */ + sigmoid() { + return this.clone().sigmoid_(); + } + + /** + * Applies the sigmoid function to the tensor in place. + * @returns {Tensor} Returns `this`. + */ + sigmoid_() { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] = 1 / (1 + Math.exp(-this.data[i])); + } + return this; + } + + /** + * Return a new Tensor with every element multiplied by a constant. + * @param {number} val The value to multiply by. + * @returns {Tensor} The new tensor. + */ + mul(val) { + return this.clone().mul_(val); + } + + /** + * Multiply the tensor by a constant in place. + * @param {number} val The value to multiply by. + * @returns {Tensor} Returns `this`. + */ + mul_(val) { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] *= val; + } + return this; + } + + + /** + * Return a new Tensor with every element added by a constant. + * @param {number} val The value to add by. + * @returns {Tensor} The new tensor. + */ + add(val) { + return this.clone().add_(val); + } + + /** + * Add the tensor by a constant in place. + * @param {number} val The value to add by. + * @returns {Tensor} Returns `this`. + */ + add_(val) { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] += val; + } + return this; + } + clone() { + return new Tensor(this.type, this.data.slice(), this.dims.slice()); + } + + slice(...slices) { + // This allows for slicing with ranges and numbers + let newTensorDims = []; + let newOffsets = []; + + // slices is an array of numbers or arrays of numbers + // e.g., slices = [0, [1, 3], null, [0, 3]] + for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { + let slice = slices[sliceIndex]; + + if (slice === null || slice === undefined) { + // null or undefined means take the whole dimension + newOffsets.push([0, this.dims[sliceIndex]]); + newTensorDims.push(this.dims[sliceIndex]); + + } else if (typeof slice === 'number') { + slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex); + + // A number means take a single element + newOffsets.push([slice, slice + 1]); + + } else if (Array.isArray(slice) && slice.length === 2) { + // An array of length 2 means take a range of elements + + if (slice[0] > slice[1]) { + throw new Error(`Invalid slice: ${slice}`); + } + + let offsets = [ + Math.max(slice[0], 0), + Math.min(slice[1], this.dims[sliceIndex]) + ]; + + newOffsets.push(offsets); + newTensorDims.push(offsets[1] - offsets[0]); + + } else { + throw new Error(`Invalid slice: ${slice}`); + } + } + + let newDims = newOffsets.map(([start, end]) => end - start); + let newBufferSize = newDims.reduce((a, b) => a * b); + + // Allocate memory + // @ts-ignore + let data = new this.data.constructor(newBufferSize); + + // Precompute strides + const stride = this.stride(); + + for (let i = 0; i < newBufferSize; ++i) { + let originalIndex = 0; + for (let j = newDims.length - 1, num = i; j >= 0; --j) { + const size = newDims[j]; + originalIndex += ((num % size) + newOffsets[j][0]) * stride[j]; + num = Math.floor(num / size); + } + data[i] = this.data[originalIndex]; + } + return new Tensor(this.type, data, newTensorDims); + + } + + /** + * Return a transposed version of this Tensor, according to the provided dimensions. + * @param {...number} dims Dimensions to transpose. + * @returns {Tensor} The transposed tensor. + */ + transpose(...dims) { + return transpose(this, dims); + } + + // TODO: rename transpose to permute + // TODO: implement transpose + + // TODO add .max() and .min() methods + + /** + * Returns the sum of each row of the input tensor in the given dimension dim. + * + * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. + * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. + * @returns The summed tensor + */ + sum(dim = null, keepdim = false) { + return this.norm(1, dim, keepdim); + } + + /** + * Returns the matrix norm or vector norm of a given tensor. + * @param {number|string} [p='fro'] The order of norm + * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. + * If dim is None, the norm will be calculated across all dimensions of input. + * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. + * @returns {Tensor} The norm of the tensor. + */ + norm(p = 'fro', dim = null, keepdim = false) { + if (p === 'fro') { + // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2. + p = 2; + } else if (typeof p === 'string') { + throw Error(`Unsupported norm: ${p}`); + } + + if (dim === null) { + // @ts-ignore + let val = this.data.reduce((a, b) => a + (b ** p), 0) ** (1 / p); + return new Tensor(this.type, [val], []); + } + + // Negative indexing + dim = safeIndex(dim, this.dims.length); + + // Calculate the shape of the resulting array after summation + const resultDims = this.dims.slice(); // Copy the original dimensions + resultDims[dim] = 1; // Remove the specified axis + + // Create a new array to store the accumulated values + // @ts-ignore + const result = new this.data.constructor(this.data.length / this.dims[dim]); + + // Iterate over the data array + for (let i = 0; i < this.data.length; ++i) { + + // Calculate the index in the resulting array + let resultIndex = 0; + + for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = this.dims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + } + num = Math.floor(num / size); + } + + // Accumulate the value at the current index + result[resultIndex] += (this.data[i]) ** p; + } + + if (p !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] = result[i] ** (1 / p); + } + } + + if (!keepdim) { + resultDims.splice(dim, 1); + } + + return new Tensor(this.type, result, resultDims); + } + + /** + * Performs `L_p` normalization of inputs over specified dimension. Operates in place. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} `this` for operation chaining. + */ + normalize_(p = 2.0, dim = 1) { + dim = safeIndex(dim, this.dims.length); + + const norm = this.norm(p, dim, true); + + for (let i = 0; i < this.data.length; ++i) { + + // Calculate the index in the resulting array + let resultIndex = 0; + + for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = this.dims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= this.dims[j]; + } + num = Math.floor(num / size); + } + + // Divide by normalized value + this.data[i] /= norm.data[resultIndex]; + } + + return this; + } + + /** + * Performs `L_p` normalization of inputs over specified dimension. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} The normalized tensor. + */ + normalize(p = 2.0, dim = 1) { + return this.clone().normalize_(p, dim); + } + + /** + * Compute and return the stride of this tensor. + * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. + * @returns {number[]} The stride of this tensor. + */ + stride() { + return dimsToStride(this.dims); + } + + /** + * Returns a tensor with all specified dimensions of input of size 1 removed. + * + * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. + * If you would like a copy, use `tensor.clone()` before squeezing. + * + * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions. + * @returns The squeezed tensor + */ + squeeze(dim = null) { + return new Tensor( + this.type, + this.data, + calc_squeeze_dims(this.dims, dim) + ) + } + + /** + * In-place version of @see {@link Tensor.squeeze} + */ + squeeze_(dim = null) { + this.dims = calc_squeeze_dims(this.dims, dim); + return this; + } + + /** + * Returns a new tensor with a dimension of size one inserted at the specified position. + * + * NOTE: The returned tensor shares the same underlying data with this tensor. + * + * @param {number} dim The index at which to insert the singleton dimension + * @returns The unsqueezed tensor + */ + unsqueeze(dim = null) { + return new Tensor( + this.type, + this.data, + calc_unsqueeze_dims(this.dims, dim) + ); + } + + /** + * In-place version of @see {@link Tensor.unsqueeze} + */ + unsqueeze_(dim = null) { + this.dims = calc_unsqueeze_dims(this.dims, dim); + return this; + } + + /** + * In-place version of @see {@link Tensor.flatten} + */ + flatten_(start_dim = 0, end_dim = -1) { + // TODO validate inputs + end_dim = (end_dim + this.dims.length) % this.dims.length; + + let dimsToKeepBefore = this.dims.slice(0, start_dim); + let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); + let dimsToKeepAfter = this.dims.slice(end_dim + 1); + + this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter] + return this; + } + + /** + * Flattens input by reshaping it into a one-dimensional tensor. + * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` + * and ending with `end_dim` are flattened. The order of elements in input is unchanged. + * @param {number} start_dim the first dim to flatten + * @param {number} end_dim the last dim to flatten + * @returns The flattened tensor. + */ + flatten(start_dim = 0, end_dim = -1) { + return this.clone().flatten_(start_dim, end_dim); + } + + /** + * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. + * @param {...number} dims the desired size + * @returns {Tensor} The tensor with the same data but different shape + */ + view(...dims) { + // TODO: validate dims + let inferredIndex = -1; + for (let i = 0; i < dims.length; ++i) { + if (dims[i] === -1) { + if (inferredIndex !== -1) { + throw new Error("Only one dimension can be inferred"); + } + inferredIndex = i; + } + } + + if (inferredIndex !== -1) { + // Some dimension must be inferred + const productOther = dims.reduce((product, curr, index) => { + return index !== inferredIndex ? product * curr : product + }, 1); + + dims[inferredIndex] = this.data.length / productOther; + } + return new Tensor(this.type, this.data, dims); // NOTE: uses same underlying storage + } + + neg_() { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] = -this.data[i]; + } + return this; + } + neg() { + return this.clone().neg_(); + } + + /** + * In-place version of @see {@link Tensor.clamp} + */ + clamp_(min, max) { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] = Math.min(Math.max(this.data[i], min), max); + } + return this; + } + + /** + * Clamps all elements in input into the range [ min, max ] + * @param {number} min lower-bound of the range to be clamped to + * @param {number} max upper-bound of the range to be clamped to + * @returns the output tensor. + */ + clamp(min, max) { + return this.clone().clamp_(min, max); + } + + /** + * In-place version of @see {@link Tensor.round} + */ + round_() { + for (let i = 0; i < this.data.length; ++i) { + this.data[i] = Math.round(this.data[i]); + } + return this; + } + + /** + * Rounds elements of input to the nearest integer. + * @returns the output tensor. + */ + round() { + return this.clone().round_(); + } + + /** + * Performs Tensor dtype conversion. + * @param {DataType} type The desired data type. + * @returns {Tensor} The converted tensor. + */ + to(type) { + // If the self Tensor already has the correct dtype, then self is returned. + if (this.type === type) return this; + + // Otherwise, the returned tensor is a copy of self with the desired dtype. + if (!DataTypeMap.hasOwnProperty(type)) { + throw new Error(`Unsupported type: ${type}`); + } + // @ts-ignore + return new Tensor(type, DataTypeMap[type].from(this.data), this.dims); + } +} + +/** + * This creates a nested array of a given type and depth (see examples). + * + * @example + * NestArray; // string[] + * @example + * NestArray; // number[][] + * @example + * NestArray; // string[][][] etc. + * @template T + * @template {number} Depth + * @template {never[]} [Acc=[]] + * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray + */ + +/** + * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions. + * + * @example + * reshape([10 ], [1 ]); // Type: number[] Value: [10] + * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]] + * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]] + * @param {T[]|DataArray} data The input array to reshape. + * @param {DIM} dimensions The target shape/dimensions. + * @template T + * @template {[number]|number[]} DIM + * @returns {NestArray} The reshaped array. + */ +function reshape(data, dimensions) { + + const totalElements = data.length; + const dimensionSize = dimensions.reduce((a, b) => a * b); + + if (totalElements !== dimensionSize) { + throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); + } + + /** @type {any} */ + let reshapedArray = data; + + for (let i = dimensions.length - 1; i >= 0; i--) { + reshapedArray = reshapedArray.reduce((acc, val) => { + let lastArray = acc[acc.length - 1]; + + if (lastArray.length < dimensions[i]) { + lastArray.push(val); + } else { + acc.push([val]); + } + + return acc; + }, [[]]); + } + + return reshapedArray[0]; +} + +/** + * Transposes a tensor according to the provided axes. + * @param {any} tensor The input tensor to transpose. + * @param {Array} axes The axes to transpose the tensor along. + * @returns {Tensor} The transposed tensor. + */ +export function transpose(tensor, axes) { + const [transposedData, shape] = transpose_data(tensor.data, tensor.dims, axes); + return new Tensor(tensor.type, transposedData, shape); +} + + +/** + * Interpolates an Tensor to the given size. + * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w]) + * @param {number[]} size The output size of the image + * @param {string} mode The interpolation mode + * @param {boolean} align_corners Whether to align corners. + * @returns {Tensor} The interpolated tensor. + */ +export function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) { + + // Input image dimensions + const in_channels = input.dims.at(-3) ?? 1; + const in_height = input.dims.at(-2); + const in_width = input.dims.at(-1); + + let output = interpolate_data( + /** @type {import('./maths.js').TypedArray}*/(input.data), + [in_channels, in_height, in_width], + [out_height, out_width], + mode, + align_corners + ); + return new Tensor(input.type, output, [in_channels, out_height, out_width]); +} + +/** + * Perform mean pooling of the last hidden state followed by a normalization step. + * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim] + * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength] + * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim]. + */ +export function mean_pooling(last_hidden_state, attention_mask) { + // last_hidden_state: [batchSize, seqLength, embedDim] + // attention_mask: [batchSize, seqLength] + + let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; + // @ts-ignore + let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]); + let [batchSize, seqLength, embedDim] = last_hidden_state.dims; + + let outIndex = 0; + for (let i = 0; i < batchSize; ++i) { + let offset = i * embedDim * seqLength; + + for (let k = 0; k < embedDim; ++k) { + let sum = 0; + let count = 0; + + let attnMaskOffset = i * seqLength; + let offset2 = offset + k; + // Pool over all words in sequence + for (let j = 0; j < seqLength; ++j) { + // index into attention mask + let attn = Number(attention_mask.data[attnMaskOffset + j]); + + count += attn; + sum += last_hidden_state.data[offset2 + j * embedDim] * attn; + } + + let avg = sum / count; + returnedData[outIndex++] = avg; + } + } + + return new Tensor( + last_hidden_state.type, + returnedData, + shape + ) +} + +/** + * Helper function to calculate new dimensions when performing a squeeze operation. + * @param {number[]} dims The dimensions of the tensor. + * @param {number|number[]|null} dim The dimension(s) to squeeze. + * @returns The new dimensions. + * @private + */ +function calc_squeeze_dims(dims, dim) { + dims = dims.slice(); + if (dim === null) { + dims = dims.filter((d) => d !== 1); + } else if (typeof dim === 'number') { + if (dims[dim] === 1) { + dims.splice(dim, 1); + } + } else if (Array.isArray(dim)) { + dims = dims.filter((x, i) => { + return x !== 1 || !dim.includes(i); + }); + } + return dims; +} + +/** + * Helper function to calculate new dimensions when performing an unsqueeze operation. + * @param {number[]} dims The dimensions of the tensor. + * @param {number} dim The dimension to unsqueeze. + * @returns The new dimensions. + * @private + */ +function calc_unsqueeze_dims(dims, dim) { + // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4") + // + 1 since we allow inserting at the end (i.e. dim = -1) + dim = safeIndex(dim, dims.length + 1); + dims = dims.slice(); + // Insert 1 into specified dimension + dims.splice(dim, 0, 1); + return dims; +} + +/** + * Safely calculate the index for an array of a given size, allowing negative indexing. + * @param {number} index The index that will be used. + * @param {number} size The size of the array. + * @param {number} [dimension=null] The dimension that the index is for (optional). + * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`. + * + * @throws {Error} If the index is out of range. + * @private + */ +function safeIndex(index, size, dimension = null) { + if (index < -size || index >= size) { + throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`); + } + + if (index < 0) { + // Negative indexing, ensuring positive index + index = ((index % size) + size) % size; + } + return index; +} + +/** + * Concatenates an array of tensors along a specified dimension. + * @param {Tensor[]} tensors The array of tensors to concatenate. + * @param {number} dim The dimension to concatenate along. + * @returns {Tensor} The concatenated tensor. + */ +export function cat(tensors, dim = 0) { + dim = safeIndex(dim, tensors[0].dims.length); + + // TODO do validation of shapes + + const resultDims = tensors[0].dims.slice(); + resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); + + // Create a new array to store the accumulated values + const resultSize = resultDims.reduce((a, b) => a * b, 1); + // @ts-ignore + const result = new tensors[0].data.constructor(resultSize); + + // Create output tensor of same type as first + const resultType = tensors[0].type; + + if (dim === 0) { + // Handle special case for performance reasons + + let offset = 0; + for (let t of tensors) { + result.set(t.data, offset); + offset += t.data.length; + } + + } else { + + let currentDim = 0; + + for (let t = 0; t < tensors.length; ++t) { + let tensor = tensors[t]; + + // Iterate over the data array + for (let i = 0; i < tensor.data.length; ++i) { + // Calculate the index in the resulting array + let resultIndex = 0; + + for (let j = tensor.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = tensor.dims[j]; + let index = num % size; + if (j === dim) { + index += currentDim; + } + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + num = Math.floor(num / size); + } + // Accumulate the value at the current index + result[resultIndex] = tensor.data[i]; + } + + currentDim += tensor.dims[dim]; + } + } + return new Tensor(resultType, result, resultDims); +} + +/** + * Stack an array of tensors along a specified dimension. + * @param {Tensor[]} tensors The array of tensors to stack. + * @param {number} dim The dimension to stack along. + * @returns {Tensor} The stacked tensor. + */ +export function stack(tensors, dim = 0) { + // TODO do validation of shapes + // NOTE: stack expects each tensor to be equal size + return cat(tensors.map(t => t.unsqueeze(dim)), dim); +} + + +/** + * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions. + * @param {Tensor} input the input tenso + * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced. + * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1. + * @param {boolean} keepdim whether the output tensor has dim retained or not. + * @returns {Tensor[]} A tuple of (std, mean) tensors. + */ +export function std_mean(input, dim = null, correction = 1, keepdim = false) { + + if (dim === null) { + // None to reduce over all dimensions. + // @ts-ignore + const sum = input.data.reduce((a, b) => a + b, 0); + const mean = sum / input.data.length; + // @ts-ignore + const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean) ** 2, 0) / (input.data.length - correction)); + + const meanTensor = new Tensor(input.type, [mean], [/* scalar */]); + const stdTensor = new Tensor(input.type, [std], [/* scalar */]); + + return [stdTensor, meanTensor]; + } + + // Negative indexing + dim = safeIndex(dim, input.dims.length); + + const meanTensor = mean(input, dim, keepdim); + + // Calculate the shape of the resulting array after summation + const resultDims = input.dims.slice(); // Copy the original dimensions + resultDims[dim] = 1; // Remove the specified axis + + // Create a new array to store the accumulated values + // @ts-ignore + const result = new input.data.constructor(input.data.length / input.dims[dim]); + + // Iterate over the data array + for (let i = 0; i < input.data.length; ++i) { + + // Calculate the index in the resulting array + let resultIndex = 0; + + for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = input.dims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + } + num = Math.floor(num / size); + } + + // Accumulate the value at the current index + result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2; + } + + for (let i = 0; i < result.length; ++i) { + result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction)); + } + + if (!keepdim) { + resultDims.splice(dim, 1); + } + + const stdTensor = new Tensor(input.type, result, resultDims); + + return [stdTensor, meanTensor]; +} + + +/** + * Returns the mean value of each row of the input tensor in the given dimension dim. + * @param {Tensor} input the input tensor. + * @param {number|null} dim the dimension to reduce. + * @param {boolean} keepdim whether the output tensor has dim retained or not. + * @returns A new tensor with means taken along the specified dimension. + */ +export function mean(input, dim = null, keepdim = false) { + + if (dim === null) { + // None to reduce over all dimensions. + // @ts-ignore + let val = input.data.reduce((a, b) => a + b, 0); + return new Tensor(input.type, [val / input.data.length], [/* scalar */]); + } + + // Negative indexing + dim = safeIndex(dim, input.dims.length); + + // Calculate the shape of the resulting array after summation + const resultDims = input.dims.slice(); // Copy the original dimensions + resultDims[dim] = 1; // Remove the specified axis + + // Create a new array to store the accumulated values + // @ts-ignore + const result = new input.data.constructor(input.data.length / input.dims[dim]); + + // Iterate over the data array + for (let i = 0; i < input.data.length; ++i) { + + // Calculate the index in the resulting array + let resultIndex = 0; + + for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = input.dims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + } + num = Math.floor(num / size); + } + + // Accumulate the value at the current index + result[resultIndex] += input.data[i]; + } + + if (input.dims[dim] !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] = result[i] / input.dims[dim]; + } + } + + if (!keepdim) { + resultDims.splice(dim, 1); + } + + return new Tensor(input.type, result, resultDims); +} + + +/** + * + * Measures similarity between two temporal sequences (e.g., input audio and output tokens + * to generate token-level timestamps). + * @param {Tensor} matrix + * @returns {number[][]} + */ +export function dynamicTimeWarping(matrix) { + const [output_length, input_length] = matrix.dims; + + const outputShape = [output_length + 1, input_length + 1]; + + const cost = new Tensor( + 'float32', + new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity), + outputShape + ); + + const trace = new Tensor( + 'float32', + new Float32Array(outputShape[0] * outputShape[1]).fill(-1), + outputShape + ) + + // same as `cost[0][0] = 0`; + cost[0].data[0] = 0; + + for (let j = 1; j < input_length + 1; ++j) { + for (let i = 1; i < output_length + 1; ++i) { + + const c0 = cost[i - 1][j - 1].item(); + const c1 = cost[i - 1][j].item(); + const c2 = cost[i][j - 1].item(); + + let c, t; + if (c0 < c1 && c0 < c2) { + c = c0; + t = 0; + } else if (c1 < c0 && c1 < c2) { + c = c1; + t = 1; + } else { + c = c2; + t = 2; + } + + cost[i].data[j] = matrix[i - 1][j - 1].item() + c; + trace[i].data[j] = t; + } + } + + // backtrace + let i = output_length; + let j = input_length; + + // @ts-ignore + trace.data.fill(2, 0, outputShape[1]) // trace[0, :] = 2 + for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1 + trace[i].data[0] = 1; + } + + let text_indices = []; + let time_indices = []; + + while (i > 0 || j > 0) { + text_indices.push(i - 1); + time_indices.push(j - 1); + + const t = trace[i][j].item(); + switch (t) { + case 0: + --i; --j; + break; + case 1: + --i; + break; + case 2: + --j; + break; + default: + throw new Error( + `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.` + ) + } + } + + text_indices.reverse(); + time_indices.reverse(); + + return [text_indices, time_indices]; + +} + +function dimsToStride(dims) { + const stride = new Array(dims.length); + for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { + stride[i] = s2; + s2 *= dims[i]; + } + return stride; +} + +/** + * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size. + * @param {number[]} size A sequence of integers defining the shape of the output tensor. + */ +export function ones(size) { + const numElements = size.reduce((a, b) => a * b, 1); + return new Tensor( + 'int64', + new BigInt64Array(numElements).fill(1n), + size + ) +} + +/** + * Returns a tensor filled with the scalar value 1, with the same size as input. + * @param {Tensor} tensor The size of input will determine size of the output tensor. + * @returns The ones tensor. + */ +export function ones_like(tensor) { + return ones(tensor.dims); +} diff --git a/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts b/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts new file mode 100644 index 000000000..a287ca200 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts @@ -0,0 +1,5 @@ +/** @type {import('onnxruntime-web')} The ONNX runtime module. */ +export let ONNX: typeof ONNX_WEB; +export const executionProviders: string[]; +import * as ONNX_WEB from 'onnxruntime-web'; +//# sourceMappingURL=onnx.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts.map new file mode 100644 index 000000000..dfa827f92 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/backends/onnx.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"onnx.d.ts","sourceRoot":"","sources":["../../src/backends/onnx.js"],"names":[],"mappings":"AAuBA,iEAAiE;AACjE,iCAAgB;AAEhB,0CAGE;0BARwB,iBAAiB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts b/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts new file mode 100644 index 000000000..fa3989912 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts @@ -0,0 +1,43 @@ +/** + * Base class for all configuration classes. For more information, see the corresponding + * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig). + */ +export class PretrainedConfig { + /** + * Loads a pre-trained config from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained config. + * @param {PretrainedOptions} options Additional options for loading the config. + * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. + * + * @returns {Promise} A new instance of the `PretrainedConfig` class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: PretrainedOptions): Promise; + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} configJSON The JSON of the config. + */ + constructor(configJSON: any); + model_type: any; + is_encoder_decoder: boolean; +} +/** + * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function. + * + * @example + * let config = await AutoConfig.from_pretrained('bert-base-uncased'); + */ +export class AutoConfig { + /** + * Loads a pre-trained config from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained config. + * @param {PretrainedOptions} options Additional options for loading the config. + * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. + * + * @returns {Promise} A new instance of the `PretrainedConfig` class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import("./utils/hub.js").PretrainedOptions): Promise; +} +export type PretrainedOptions = import('./utils/hub.js').PretrainedOptions; +//# sourceMappingURL=configs.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts.map new file mode 100644 index 000000000..66011d266 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/configs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"configs.d.ts","sourceRoot":"","sources":["../src/configs.js"],"names":[],"mappings":"AAiDA;;;GAGG;AACH;IAcI;;;;;;;;OAQG;IACH,sDANW,MAAM,0EACN,iBAAiB,GAGf,QAAQ,gBAAgB,CAAC,CAkBrC;IApCD;;;OAGG;IACH,6BAKC;IAJG,gBAAsB;IACtB,4BAA+B;CA+BtC;AAED;;;;;GAKG;AACH;IAlCI;;;;;;;;OAQG;IACH,6MAgBC;CAcJ;gCAxEY,OAAO,gBAAgB,EAAE,iBAAiB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/env.d.ts b/core/vendor/node_modules/@xenova/transformers/types/env.d.ts new file mode 100644 index 000000000..bfba7425b --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/env.d.ts @@ -0,0 +1,28 @@ +export namespace env { + export namespace backends { + export { onnx_env as onnx }; + export let tfjs: {}; + } + export { __dirname }; + export { VERSION as version }; + export let allowRemoteModels: boolean; + export let remoteHost: string; + export let remotePathTemplate: string; + export let allowLocalModels: boolean; + export { localModelPath }; + export { FS_AVAILABLE as useFS }; + export { WEB_CACHE_AVAILABLE as useBrowserCache }; + export { FS_AVAILABLE as useFSCache }; + export { DEFAULT_CACHE_DIR as cacheDir }; + export let useCustomCache: boolean; + export let customCache: any; +} +declare const onnx_env: import("onnxruntime-common").Env; +declare const __dirname: any; +declare const VERSION: "2.14.0"; +declare const localModelPath: any; +declare const FS_AVAILABLE: boolean; +declare const WEB_CACHE_AVAILABLE: boolean; +declare const DEFAULT_CACHE_DIR: any; +export {}; +//# sourceMappingURL=env.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/env.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/env.d.ts.map new file mode 100644 index 000000000..3952df4f4 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/env.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../src/env.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,6BAEW;AAXX,gCAAyB;AAoBzB,kCAE+B;AAlB/B,oCAAkC;AADlC,2CAA4E;AAW5E,qCAEW"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/models.d.ts b/core/vendor/node_modules/@xenova/transformers/types/models.d.ts new file mode 100644 index 000000000..380a4702b --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/models.d.ts @@ -0,0 +1,3318 @@ +declare const PreTrainedModel_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * A base class for pre-trained models that provides the model configuration and an ONNX session. + */ +export class PreTrainedModel extends PreTrainedModel_base { + /** + * Instantiate one of the model classes of the library from a pretrained model. + * + * The model class to instantiate is selected based on the `model_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. + * + * @returns {Promise} A new instance of the `PreTrainedModel` class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name, }?: import('./utils/hub.js').PretrainedOptions): Promise; + /** + * Creates a new instance of the `PreTrainedModel` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + */ + constructor(config: any, session: any); + main_input_name: string; + config: any; + session: any; + can_generate: boolean; + _runBeam: typeof decoderRunBeam; + _getStartBeams: typeof decoderStartBeams; + _updateBeam: typeof decoderUpdatebeam; + _forward: typeof encoderForward; + /** + * Disposes of all the ONNX sessions that were created during inference. + * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. + * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ + dispose(): Promise; + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Object containing input tensors + * @returns {Promise} Object containing output tensors + */ + _call(model_inputs: any): Promise; + /** + * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method + * will be chosen based on the model type. + * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. + * @returns {Promise} The output data from the model in the format specified in the ONNX model. + * @throws {Error} This method must be implemented in subclasses. + */ + forward(model_inputs: any): Promise; + /** + * @param {import('./utils/generation.js').GenerationConfigType} generation_config + * @param {number} input_ids_seq_length The starting sequence length for the input ids. + * @returns {LogitsProcessorList} + * @private + */ + private _get_logits_processor; + /** + * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. + * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. + * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters. + * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation. + */ + _get_generation_config(generation_config: import('./utils/generation.js').GenerationConfigType): import('./utils/generation.js').GenerationConfigType; + /** + * @typedef {import('./utils/maths.js').TypedArray} TypedArray + */ + /** + * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput + * @typedef {Object} DecoderOutput + * + * Generates text based on the given inputs and generation configuration using the model. + * @param {Tensor|Array|TypedArray} inputs An array of input token IDs. + * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used. + * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created. + * @param {Object} options options + * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs. + * @returns {Promise} An array of generated output sequences, where each sequence is an array of token IDs. + * @throws {Error} Throws an error if the inputs array is empty. + */ + generate(inputs: any[] | import("./transformers.js").TypedArray | Tensor, generation_config?: any | (new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType) | null, logits_processor?: any | null, { inputs_attention_mask }?: { + inputs_attention_mask?: any; + }): Promise; + /** + * Helper function to add attentions to beam + * @param {Object} beam + * @param {Object} output + * @private + */ + private addAttentionsToBeam; + /** + * Groups an array of beam objects by their ids. + * + * @param {Array} beams The array of beam objects to group. + * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id. + */ + groupBeams(beams: any[]): any[]; + /** + * Returns an object containing past key values from the given decoder results object. + * + * @param {Object} decoderResults The decoder results object. + * @param {Object} pastKeyValues The previous past key values. + * @returns {Object} An object containing past key values. + */ + getPastKeyValues(decoderResults: any, pastKeyValues: any): any; + /** + * Returns an object containing attentions from the given decoder results object. + * + * @param {Object} decoderResults The decoder results object. + * @returns {Object} An object containing attentions. + */ + getAttentions(decoderResults: any): any; + /** + * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. + * + * @param {Object} decoderFeeds The decoder feeds object to add past key values to. + * @param {Object} pastKeyValues An object containing past key values. + */ + addPastKeyValues(decoderFeeds: any, pastKeyValues: any): void; + /** + * Initializes and returns the beam for text generation task + * @param {Tensor} inputTokenIds The input token ids. + * @param {Object} generation_config The generation config. + * @param {number} numOutputTokens The number of tokens to be generated. + * @param {Tensor} inputs_attention_mask Optional input attention mask. + * @returns {any} A Beam object representing the initialized beam. + * @private + */ + private getStartBeams; + /** + * Runs a single step of the beam search generation algorithm. + * @param {any} beam The current beam being generated. + * @returns {Promise} The updated beam after a single generation step. + * @private + */ + private runBeam; + /** + * Update a beam with a new token ID. + * @param {Object} beam The beam to update. + * @param {number} newTokenId The new token ID to add to the beam's output. + * @private + */ + private updateBeam; +} +export class ModelOutput { +} +/** + * Base class for model's outputs, with potential hidden states and attentions. + */ +export class BaseModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. + * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ last_hidden_state, hidden_states, attentions }: { + last_hidden_state: Tensor; + hidden_states?: Tensor; + attentions?: Tensor; + }); + last_hidden_state: Tensor; + hidden_states: Tensor; + attentions: Tensor; +} +export class BertPreTrainedModel extends PreTrainedModel { +} +export class BertModel extends BertPreTrainedModel { +} +/** + * BertForMaskedLM is a class representing a BERT model for masked language modeling. + */ +export class BertForMaskedLM extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * BertForSequenceClassification is a class representing a BERT model for sequence classification. + */ +export class BertForSequenceClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * BertForTokenClassification is a class representing a BERT model for token classification. + */ +export class BertForTokenClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * BertForQuestionAnswering is a class representing a BERT model for question answering. + */ +export class BertForQuestionAnswering extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class RoFormerPreTrainedModel extends PreTrainedModel { +} +/** + * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top. + */ +export class RoFormerModel extends RoFormerPreTrainedModel { +} +/** + * RoFormer Model with a `language modeling` head on top. + */ +export class RoFormerForMaskedLM extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class RoFormerForSequenceClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class RoFormerForTokenClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class ConvBertPreTrainedModel extends PreTrainedModel { +} +/** + * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class ConvBertModel extends ConvBertPreTrainedModel { +} +/** + * ConvBERT Model with a language modeling head on top. + */ +export class ConvBertForMaskedLM extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class ConvBertForSequenceClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class ConvBertForTokenClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`) + */ +export class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class ElectraPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Electra Model transformer outputting raw hidden-states without any specific head on top. + * Identical to the BERT model except that it uses an additional linear layer between the embedding + * layer and the encoder if the hidden size and embedding size are different. + */ +export class ElectraModel extends ElectraPreTrainedModel { +} +/** + * Electra model with a language modeling head on top. + */ +export class ElectraForMaskedLM extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class ElectraForSequenceClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * Electra model with a token classification head on top. + */ +export class ElectraForTokenClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD + * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class ElectraForQuestionAnswering extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class CamembertPreTrainedModel extends PreTrainedModel { +} +/** + * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class CamembertModel extends CamembertPreTrainedModel { +} +/** + * CamemBERT Model with a `language modeling` head on top. + */ +export class CamembertForMaskedLM extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. + */ +export class CamembertForSequenceClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class CamembertForTokenClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * CamemBERT Model with a span classification head on top for extractive question-answering tasks + */ +export class CamembertForQuestionAnswering extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class DebertaPreTrainedModel extends PreTrainedModel { +} +/** + * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DebertaModel extends DebertaPreTrainedModel { +} +/** + * DeBERTa Model with a `language modeling` head on top. + */ +export class DebertaForMaskedLM extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class DebertaForSequenceClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class DebertaForTokenClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class DebertaForQuestionAnswering extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class DebertaV2PreTrainedModel extends PreTrainedModel { +} +/** + * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DebertaV2Model extends DebertaV2PreTrainedModel { +} +/** + * DeBERTa-V2 Model with a `language modeling` head on top. + */ +export class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + */ +export class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class DistilBertPreTrainedModel extends PreTrainedModel { +} +export class DistilBertModel extends DistilBertPreTrainedModel { +} +/** + * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification. + */ +export class DistilBertForSequenceClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification. + */ +export class DistilBertForTokenClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering. + */ +export class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +/** + * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task. + */ +export class DistilBertForMaskedLM extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class EsmPreTrainedModel extends PreTrainedModel { +} +/** + * The bare ESM Model transformer outputting raw hidden-states without any specific head on top. + */ +export class EsmModel extends EsmPreTrainedModel { +} +/** + * ESM Model with a `language modeling` head on top. + */ +export class EsmForMaskedLM extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class EsmForSequenceClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output) + * e.g. for Named-Entity-Recognition (NER) tasks. + */ +export class EsmForTokenClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +export class MobileBertPreTrainedModel extends PreTrainedModel { +} +export class MobileBertModel extends MobileBertPreTrainedModel { +} +/** + * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task. + */ +export class MobileBertForMaskedLM extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class MobileBertForSequenceClassification extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * MobileBert Model with a span classification head on top for extractive question-answering tasks + */ +export class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class MPNetPreTrainedModel extends PreTrainedModel { +} +/** + * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top. + */ +export class MPNetModel extends MPNetPreTrainedModel { +} +/** + * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling. + */ +export class MPNetForMaskedLM extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + _call(model_inputs: any): Promise; +} +/** + * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification. + */ +export class MPNetForSequenceClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * MPNetForTokenClassification is a class representing a MPNet model for token classification. + */ +export class MPNetForTokenClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * MPNetForQuestionAnswering is a class representing a MPNet model for question answering. + */ +export class MPNetForQuestionAnswering extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + _call(model_inputs: any): Promise; +} +export class SqueezeBertPreTrainedModel extends PreTrainedModel { +} +export class SqueezeBertModel extends SqueezeBertPreTrainedModel { +} +export class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class AlbertPreTrainedModel extends PreTrainedModel { +} +export class AlbertModel extends AlbertPreTrainedModel { +} +export class AlbertForSequenceClassification extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class AlbertForQuestionAnswering extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class AlbertForMaskedLM extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class T5PreTrainedModel extends PreTrainedModel { +} +export class T5Model extends T5PreTrainedModel { +} +/** + * T5Model is a class representing a T5 model for conditional generation. + */ +export class T5ForConditionalGeneration extends T5PreTrainedModel { + /** + * Creates a new instance of the `T5ForConditionalGeneration` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: any; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: any; +} +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class LongT5PreTrainedModel extends PreTrainedModel { +} +/** + * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class LongT5Model extends LongT5PreTrainedModel { +} +/** + * LONGT5 Model with a `language modeling` head on top. + */ +export class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { + /** + * Creates a new instance of the `LongT5ForConditionalGeneration` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: any; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: any; +} +export class MT5PreTrainedModel extends PreTrainedModel { +} +export class MT5Model extends MT5PreTrainedModel { +} +/** + * A class representing a conditional sequence-to-sequence model based on the MT5 architecture. + */ +export class MT5ForConditionalGeneration extends MT5PreTrainedModel { + /** + * Creates a new instance of the `MT5ForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: any; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: any; +} +export class BartPretrainedModel extends PreTrainedModel { +} +/** + * The bare BART Model outputting raw hidden-states without any specific head on top. + */ +export class BartModel extends BartPretrainedModel { +} +/** + * The BART Model with a language modeling head. Can be used for summarization. + */ +export class BartForConditionalGeneration extends BartPretrainedModel { + /** + * Creates a new instance of the `BartForConditionalGeneration` class. + * @param {Object} config The configuration object for the Bart model. + * @param {Object} session The ONNX session used to execute the model. + * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. + * @param {Object} generation_config The generation configuration object. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + decoder_merged_session: any; + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +/** + * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) + */ +export class BartForSequenceClassification extends BartPretrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +export class MBartPreTrainedModel extends PreTrainedModel { +} +/** + * The bare MBART Model outputting raw hidden-states without any specific head on top. + */ +export class MBartModel extends MBartPreTrainedModel { +} +/** + * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models. + */ +export class MBartForConditionalGeneration extends MBartPreTrainedModel { + /** + * Creates a new instance of the `MBartForConditionalGeneration` class. + * @param {Object} config The configuration object for the Bart model. + * @param {Object} session The ONNX session used to execute the model. + * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. + * @param {Object} generation_config The generation configuration object. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + decoder_merged_session: any; + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +/** + * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output). + */ +export class MBartForSequenceClassification extends MBartPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +export class MBartForCausalLM extends MBartPreTrainedModel { + /** + * Creates a new instance of the `MBartForCausalLM` class. + * @param {Object} config Configuration object for the model. + * @param {Object} decoder_merged_session ONNX Session object for the decoder. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config: any, decoder_merged_session: any, generation_config: any); + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +export class BlenderbotPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Blenderbot Model outputting raw hidden-states without any specific head on top. + */ +export class BlenderbotModel extends BlenderbotPreTrainedModel { +} +/** + * The Blenderbot Model with a language modeling head. Can be used for summarization. + */ +export class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { + /** + * Creates a new instance of the `BlenderbotForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +export class BlenderbotSmallPreTrainedModel extends PreTrainedModel { +} +/** + * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top. + */ +export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { +} +/** + * The BlenderbotSmall Model with a language modeling head. Can be used for summarization. + */ +export class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { + /** + * Creates a new instance of the `BlenderbotForConditionalGeneration` class. + * @param {any} config The model configuration. + * @param {any} session The ONNX session containing the encoder weights. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +export class RobertaPreTrainedModel extends PreTrainedModel { +} +export class RobertaModel extends RobertaPreTrainedModel { +} +/** + * RobertaForMaskedLM class for performing masked language modeling on Roberta models. + */ +export class RobertaForMaskedLM extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * RobertaForSequenceClassification class for performing sequence classification on Roberta models. + */ +export class RobertaForSequenceClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * RobertaForTokenClassification class for performing token classification on Roberta models. + */ +export class RobertaForTokenClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * RobertaForQuestionAnswering class for performing question answering on Roberta models. + */ +export class RobertaForQuestionAnswering extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class XLMPreTrainedModel extends PreTrainedModel { +} +/** + * The bare XLM Model transformer outputting raw hidden-states without any specific head on top. + */ +export class XLMModel extends XLMPreTrainedModel { +} +/** + * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class XLMWithLMHeadModel extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) + */ +export class XLMForSequenceClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) + */ +export class XLMForTokenClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * XLM Model with a span classification head on top for extractive question-answering tasks + */ +export class XLMForQuestionAnswering extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class XLMRobertaPreTrainedModel extends PreTrainedModel { +} +export class XLMRobertaModel extends XLMRobertaPreTrainedModel { +} +/** + * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models. + */ +export class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models. + */ +export class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +/** + * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models. + */ +export class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + _call(model_inputs: any): Promise; +} +/** + * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models. + */ +export class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + _call(model_inputs: any): Promise; +} +export class ASTPreTrainedModel extends PreTrainedModel { +} +/** + * The bare AST Model transformer outputting raw hidden-states without any specific head on top. + */ +export class ASTModel extends ASTPreTrainedModel { +} +/** + * Audio Spectrogram Transformer model with an audio classification head on top + * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2. + */ +export class ASTForAudioClassification extends ASTPreTrainedModel { +} +export class WhisperPreTrainedModel extends PreTrainedModel { +} +/** + * WhisperModel class for training Whisper models without a language model head. + */ +export class WhisperModel extends WhisperPreTrainedModel { +} +/** + * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models. + */ +export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { + /** + * Creates a new instance of the `WhisperForConditionalGeneration` class. + * @param {Object} config Configuration object for the model. + * @param {Object} session ONNX Session object for the model. + * @param {Object} decoder_merged_session ONNX Session object for the decoder. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + requires_attention_mask: boolean; + decoder_merged_session: any; + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; + /** + * @typedef {Object} WhisperGenerationConfig + * @extends GenerationConfig + * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. + * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps + * with the text. This can be used with or without the `return_timestamps` option. To get word-level + * timestamps, use the tokenizer to group the tokens into words. + * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps. + */ + /** + * Generates outputs based on input and generation configuration. + * @param {Object} inputs Input data for the model. + * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process. + * @param {Object} logits_processor Optional logits processor object. + * @returns {Promise} Promise object represents the generated outputs. + */ + generate(inputs: any, generation_config?: any, logits_processor?: any): Promise; + /** + * Calculates token-level timestamps using the encoder-decoder cross-attentions and + * dynamic time-warping (DTW) to map each output token to a position in the input audio. + * @param {Object} generate_outputs Outputs generated by the model + * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model + * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model + * @param {number[][]} generate_outputs.sequences The sequences output by the model + * @param {number[][]} alignment_heads Alignment heads of the model + * @param {number} [num_frames=null] Number of frames in the input audio. + * @param {number} [time_precision=0.02] Precision of the timestamps in seconds + * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token + */ + _extract_token_timestamps(generate_outputs: { + cross_attentions: Tensor[][][]; + decoder_attentions: Tensor[][][]; + sequences: number[][]; + }, alignment_heads: number[][], num_frames?: number, time_precision?: number): Tensor; +} +/** + * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks + */ +export class VisionEncoderDecoderModel extends PreTrainedModel { + /** + * Creates a new instance of the `VisionEncoderDecoderModel` class. + * @param {Object} config The configuration object specifying the hyperparameters and other model settings. + * @param {Object} session The ONNX session containing the encoder model. + * @param {any} decoder_merged_session The ONNX session containing the merged decoder model. + * @param {Object} generation_config Configuration object for the generation process. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + decoder_merged_session: any; + generation_config: any; + add_encoder_pkv: boolean; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: any; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: any; + num_layers: any; + num_heads: any; + dim_kv: any; +} +export class CLIPPreTrainedModel extends PreTrainedModel { +} +/** + * CLIP Text and Vision Model with a projection layers on top + * + * **Example:** Perform zero-shot image classification with a `CLIPModel`. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); + * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Run tokenization + * let texts = ['a photo of a car', 'a photo of a football match'] + * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Read image and run processor + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * let output = await model({ ...text_inputs, ...image_inputs }); + * // { + * // logits_per_image: Tensor { + * // dims: [ 1, 2 ], + * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], + * // }, + * // logits_per_text: Tensor { + * // dims: [ 2, 1 ], + * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], + * // }, + * // text_embeds: Tensor { + * // dims: [ 2, 512 ], + * // data: Float32Array(1024) [ ... ], + * // }, + * // image_embeds: Tensor { + * // dims: [ 1, 512 ], + * // data: Float32Array(512) [ ... ], + * // } + * // } + * ``` + */ +export class CLIPModel extends CLIPPreTrainedModel { +} +/** + * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output) + * + * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`. + * + * ```javascript + * import { AutoTokenizer, CLIPTextModelWithProjection } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); + * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Run tokenization + * let texts = ['a photo of a car', 'a photo of a football match']; + * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Compute embeddings + * const { text_embeds } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 512 ], + * // type: 'float32', + * // data: Float32Array(1024) [ ... ], + * // size: 1024 + * // } + * ``` + */ +export class CLIPTextModelWithProjection extends CLIPPreTrainedModel { +} +/** + * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output) + * + * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`. + * + * ```javascript + * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@xenova/transformers'; + * + * // Load processor and vision model + * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); + * + * // Read image and run processor + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * + * // Compute embeddings + * const { image_embeds } = await vision_model(image_inputs); + * // Tensor { + * // dims: [ 1, 512 ], + * // type: 'float32', + * // data: Float32Array(512) [ ... ], + * // size: 512 + * // } + * ``` + */ +export class CLIPVisionModelWithProjection extends CLIPPreTrainedModel { +} +export class SiglipPreTrainedModel extends PreTrainedModel { +} +/** + * SigLIP Text and Vision Model with a projection layers on top + * + * **Example:** Perform zero-shot image classification with a `SiglipModel`. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); + * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); + * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Run tokenization + * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; + * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); + * + * // Read image and run processor + * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg'); + * const image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * const output = await model({ ...text_inputs, ...image_inputs }); + * // { + * // logits_per_image: Tensor { + * // dims: [ 1, 2 ], + * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], + * // }, + * // logits_per_text: Tensor { + * // dims: [ 2, 1 ], + * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], + * // }, + * // text_embeds: Tensor { + * // dims: [ 2, 768 ], + * // data: Float32Array(1536) [ ... ], + * // }, + * // image_embeds: Tensor { + * // dims: [ 1, 768 ], + * // data: Float32Array(768) [ ... ], + * // } + * // } + * ``` + */ +export class SiglipModel extends SiglipPreTrainedModel { +} +/** + * The text model from SigLIP without any head or projection on top. + * + * **Example:** Compute text embeddings with `SiglipTextModel`. + * + * ```javascript + * import { AutoTokenizer, SiglipTextModel } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); + * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Run tokenization + * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; + * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); + * + * // Compute embeddings + * const { pooler_output } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 768 ], + * // type: 'float32', + * // data: Float32Array(1536) [ ... ], + * // size: 1536 + * // } + * ``` + */ +export class SiglipTextModel extends SiglipPreTrainedModel { +} +/** + * The vision model from SigLIP without any head or projection on top. + * + * **Example:** Compute vision embeddings with `SiglipVisionModel`. + * + * ```javascript + * import { AutoProcessor, SiglipVisionModel, RawImage} from '@xenova/transformers'; + * + * // Load processor and vision model + * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); + * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224'); + * + * // Read image and run processor + * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * const image_inputs = await processor(image); + * + * // Compute embeddings + * const { pooler_output } = await vision_model(image_inputs); + * // Tensor { + * // dims: [ 1, 768 ], + * // type: 'float32', + * // data: Float32Array(768) [ ... ], + * // size: 768 + * // } + * ``` + */ +export class SiglipVisionModel extends CLIPPreTrainedModel { +} +export class ChineseCLIPPreTrainedModel extends PreTrainedModel { +} +export class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { +} +export class CLIPSegPreTrainedModel extends PreTrainedModel { +} +export class CLIPSegModel extends CLIPSegPreTrainedModel { +} +/** + * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation. + * + * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model. + * + * ```javascript + * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@xenova/transformers'; + * + * // Load tokenizer, processor, and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined'); + * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined'); + * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined'); + * + * // Run tokenization + * const texts = ['a glass', 'something to fill', 'wood', 'a jar']; + * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Read image and run processor + * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true'); + * const image_inputs = await processor(image); + * + * // Run model with both text and pixel inputs + * const { logits } = await model({ ...text_inputs, ...image_inputs }); + * // logits: Tensor { + * // dims: [4, 352, 352], + * // type: 'float32', + * // data: Float32Array(495616) [ ... ], + * // size: 495616 + * // } + * ``` + * + * You can visualize the predictions as follows: + * ```javascript + * const preds = logits + * .unsqueeze_(1) + * .sigmoid_() + * .mul_(255) + * .round_() + * .to('uint8'); + * + * for (let i = 0; i < preds.dims[0]; ++i) { + * const img = RawImage.fromTensor(preds[i]); + * img.save(`prediction_${i}.png`); + * } + * ``` + */ +export class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { +} +export class GPT2PreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPT2PreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class GPT2Model extends GPT2PreTrainedModel { +} +/** + * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks. + */ +export class GPT2LMHeadModel extends GPT2PreTrainedModel { +} +export class GPTNeoPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTNeoPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class GPTNeoModel extends GPTNeoPreTrainedModel { +} +export class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { +} +export class GPTNeoXPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTNeoXPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class GPTNeoXModel extends GPTNeoXPreTrainedModel { +} +export class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { +} +export class GPTJPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTJPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class GPTJModel extends GPTJPreTrainedModel { +} +export class GPTJForCausalLM extends GPTJPreTrainedModel { +} +export class GPTBigCodePreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `GPTBigCodePreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class GPTBigCodeModel extends GPTBigCodePreTrainedModel { +} +export class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { +} +export class CodeGenPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `CodeGenPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * CodeGenModel is a class representing a code generation model without a language model head. + */ +export class CodeGenModel extends CodeGenPreTrainedModel { +} +/** + * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class. + */ +export class CodeGenForCausalLM extends CodeGenPreTrainedModel { +} +/** + * The bare LLama Model outputting raw hidden-states without any specific head on top. + */ +export class LlamaPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `LlamaPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * The bare LLaMA Model outputting raw hidden-states without any specific head on top. + */ +export class LlamaModel extends LlamaPreTrainedModel { +} +export class LlamaForCausalLM extends LlamaPreTrainedModel { +} +export class PhiPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `PhiPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * The bare Phi Model outputting raw hidden-states without any specific head on top. + */ +export class PhiModel extends PhiPreTrainedModel { +} +export class PhiForCausalLM extends PhiPreTrainedModel { +} +/** + * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class BloomPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `BloomPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top. + */ +export class BloomModel extends BloomPreTrainedModel { +} +/** + * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class BloomForCausalLM extends BloomPreTrainedModel { +} +export class MptPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `MptPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top. + */ +export class MptModel extends MptPreTrainedModel { +} +/** + * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class MptForCausalLM extends MptPreTrainedModel { +} +export class OPTPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `OPTPreTrainedModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +/** + * The bare OPT Model outputting raw hidden-states without any specific head on top. + */ +export class OPTModel extends OPTPreTrainedModel { +} +/** + * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). + */ +export class OPTForCausalLM extends OPTPreTrainedModel { +} +export class ViTPreTrainedModel extends PreTrainedModel { +} +export class ViTModel extends ViTPreTrainedModel { +} +export class ViTForImageClassification extends ViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class VitMattePreTrainedModel extends PreTrainedModel { +} +/** + * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes. + * + * **Example:** Perform image matting with a `VitMatteForImageMatting` model. + * ```javascript + * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@xenova/transformers'; + * + * // Load processor and model + * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646'); + * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646'); + * + * // Load image and trimap + * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png'); + * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png'); + * + * // Prepare image + trimap for the model + * const inputs = await processor(image, trimap); + * + * // Predict alpha matte + * const { alphas } = await model(inputs); + * // Tensor { + * // dims: [ 1, 1, 640, 960 ], + * // type: 'float32', + * // size: 614400, + * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ] + * // } + * ``` + * + * You can visualize the alpha matte as follows: + * ```javascript + * import { Tensor, cat } from '@xenova/transformers'; + * + * // Visualize predicted alpha matte + * const imageTensor = new Tensor( + * 'uint8', + * new Uint8Array(image.data), + * [image.height, image.width, image.channels] + * ).transpose(2, 0, 1); + * + * // Convert float (0-1) alpha matte to uint8 (0-255) + * const alphaChannel = alphas + * .squeeze(0) + * .mul_(255) + * .clamp_(0, 255) + * .round_() + * .to('uint8'); + * + * // Concatenate original image with predicted alpha + * const imageData = cat([imageTensor, alphaChannel], 0); + * + * // Save output image + * const outputImage = RawImage.fromTensor(imageData); + * outputImage.save('output.png'); + * ``` + */ +export class VitMatteForImageMatting extends VitMattePreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class MobileViTPreTrainedModel extends PreTrainedModel { +} +export class MobileViTModel extends MobileViTPreTrainedModel { +} +export class MobileViTForImageClassification extends MobileViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class OwlViTPreTrainedModel extends PreTrainedModel { +} +export class OwlViTModel extends OwlViTPreTrainedModel { +} +export class OwlViTForObjectDetection extends OwlViTPreTrainedModel { +} +export class BeitPreTrainedModel extends PreTrainedModel { +} +export class BeitModel extends BeitPreTrainedModel { +} +export class BeitForImageClassification extends BeitPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class DetrPreTrainedModel extends PreTrainedModel { +} +export class DetrModel extends DetrPreTrainedModel { +} +export class DetrForObjectDetection extends DetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class DetrForSegmentation extends DetrPreTrainedModel { + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + _call(model_inputs: any): Promise; +} +export class DetrObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }: { + logits: Tensor; + pred_boxes: Tensor; + }); + logits: Tensor; + pred_boxes: Tensor; +} +export class DetrSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.pred_boxes Predicted boxes. + * @param {Tensor} output.pred_masks Predicted masks. + */ + constructor({ logits, pred_boxes, pred_masks }: { + logits: Tensor; + pred_boxes: Tensor; + pred_masks: Tensor; + }); + logits: Tensor; + pred_boxes: Tensor; + pred_masks: Tensor; +} +export class TableTransformerPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) + * outputting raw hidden-states without any specific head on top. + */ +export class TableTransformerModel extends TableTransformerPreTrainedModel { +} +/** + * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) + * with object detection heads on top, for tasks such as COCO detection. + */ +export class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { +} +export class DeiTPreTrainedModel extends PreTrainedModel { +} +export class DeiTModel extends DeiTPreTrainedModel { +} +export class DeiTForImageClassification extends DeiTPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class ResNetPreTrainedModel extends PreTrainedModel { +} +/** + * The bare ResNet model outputting raw features without any specific head on top. + */ +export class ResNetModel extends ResNetPreTrainedModel { +} +/** + * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ResNetForImageClassification extends ResNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class SwinPreTrainedModel extends PreTrainedModel { +} +export class SwinModel extends SwinPreTrainedModel { +} +export class SwinForImageClassification extends SwinPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class Swin2SRPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top. + */ +export class Swin2SRModel extends Swin2SRPreTrainedModel { +} +/** + * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration. + * + * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`. + * + * ```javascript + * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@xenova/transformers'; + * + * // Load processor and model + * const model_id = 'Xenova/swin2SR-classical-sr-x2-64'; + * const processor = await AutoProcessor.from_pretrained(model_id); + * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id); + * + * // Prepare model inputs + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; + * const image = await RawImage.fromURL(url); + * const inputs = await processor(image); + * + * // Run model + * const outputs = await model(inputs); + * + * // Convert Tensor to RawImage + * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8'); + * const outputImage = RawImage.fromTensor(output); + * // RawImage { + * // data: Uint8Array(786432) [ 41, 31, 24, ... ], + * // width: 512, + * // height: 512, + * // channels: 3 + * // } + * ``` + */ +export class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { +} +export class DPTPreTrainedModel extends PreTrainedModel { +} +/** + * The bare DPT Model transformer outputting raw hidden-states without any specific head on top. + */ +export class DPTModel extends DPTPreTrainedModel { +} +/** + * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2. + * + * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`. + * ```javascript + * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers'; + * + * // Load model and processor + * const model_id = 'Xenova/dpt-hybrid-midas'; + * const model = await DPTForDepthEstimation.from_pretrained(model_id); + * const processor = await AutoProcessor.from_pretrained(model_id); + * + * // Load image from URL + * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; + * const image = await RawImage.fromURL(url); + * + * // Prepare image for the model + * const inputs = await processor(image); + * + * // Run model + * const { predicted_depth } = await model(inputs); + * + * // Interpolate to original size + * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false); + * + * // Visualize the prediction + * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8'); + * const depth = RawImage.fromTensor(formatted); + * // RawImage { + * // data: Uint8Array(307200) [ 85, 85, 84, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * ``` + */ +export class DPTForDepthEstimation extends DPTPreTrainedModel { +} +export class GLPNPreTrainedModel extends PreTrainedModel { +} +/** + * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. + */ +export class GLPNModel extends GLPNPreTrainedModel { +} +/** + * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2. + * + * **Example:** Depth estimation w/ `Xenova/glpn-kitti`. + * ```javascript + * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@xenova/transformers'; + * + * // Load model and processor + * const model_id = 'Xenova/glpn-kitti'; + * const model = await GLPNForDepthEstimation.from_pretrained(model_id); + * const processor = await AutoProcessor.from_pretrained(model_id); + * + * // Load image from URL + * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; + * const image = await RawImage.fromURL(url); + * + * // Prepare image for the model + * const inputs = await processor(image); + * + * // Run model + * const { predicted_depth } = await model(inputs); + * + * // Interpolate to original size + * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false); + * + * // Visualize the prediction + * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8'); + * const depth = RawImage.fromTensor(formatted); + * // RawImage { + * // data: Uint8Array(307200) [ 207, 169, 154, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * ``` + */ +export class GLPNForDepthEstimation extends GLPNPreTrainedModel { +} +export class DonutSwinPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Step-by-step Document Parsing. + * + * ```javascript + * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers'; + * + * // Choose model to use + * const model_id = 'Xenova/donut-base-finetuned-cord-v2'; + * + * // Prepare image inputs + * const processor = await AutoProcessor.from_pretrained(model_id); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png'; + * const image = await RawImage.read(url); + * const image_inputs = await processor(image); + * + * // Prepare decoder inputs + * const tokenizer = await AutoTokenizer.from_pretrained(model_id); + * const task_prompt = ''; + * const decoder_input_ids = tokenizer(task_prompt, { + * add_special_tokens: false, + * }).input_ids; + * + * // Create the model + * const model = await AutoModelForVision2Seq.from_pretrained(model_id); + * + * // Run inference + * const output = await model.generate(image_inputs.pixel_values, { + * decoder_input_ids, + * max_length: model.config.decoder.max_position_embeddings, + * }); + * + * // Decode output + * const decoded = tokenizer.batch_decode(output)[0]; + * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000 + * ``` + * + * **Example:** Step-by-step Document Visual Question Answering (DocVQA) + * + * ```javascript + * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@xenova/transformers'; + * + * // Choose model to use + * const model_id = 'Xenova/donut-base-finetuned-docvqa'; + * + * // Prepare image inputs + * const processor = await AutoProcessor.from_pretrained(model_id); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; + * const image = await RawImage.read(url); + * const image_inputs = await processor(image); + * + * // Prepare decoder inputs + * const tokenizer = await AutoTokenizer.from_pretrained(model_id); + * const question = 'What is the invoice number?'; + * const task_prompt = `${question}`; + * const decoder_input_ids = tokenizer(task_prompt, { + * add_special_tokens: false, + * }).input_ids; + * + * // Create the model + * const model = await AutoModelForVision2Seq.from_pretrained(model_id); + * + * // Run inference + * const output = await model.generate(image_inputs.pixel_values, { + * decoder_input_ids, + * max_length: model.config.decoder.max_position_embeddings, + * }); + * + * // Decode output + * const decoded = tokenizer.batch_decode(output)[0]; + * // What is the invoice number? us-001 + * ``` + */ +export class DonutSwinModel extends DonutSwinPreTrainedModel { +} +export class ConvNextPreTrainedModel extends PreTrainedModel { +} +/** + * The bare ConvNext model outputting raw features without any specific head on top. + */ +export class ConvNextModel extends ConvNextPreTrainedModel { +} +/** + * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ConvNextForImageClassification extends ConvNextPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class ConvNextV2PreTrainedModel extends PreTrainedModel { +} +/** + * The bare ConvNextV2 model outputting raw features without any specific head on top. + */ +export class ConvNextV2Model extends ConvNextV2PreTrainedModel { +} +/** + * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. + */ +export class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class Dinov2PreTrainedModel extends PreTrainedModel { +} +/** + * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top. + */ +export class Dinov2Model extends Dinov2PreTrainedModel { +} +/** + * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. + */ +export class Dinov2ForImageClassification extends Dinov2PreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class YolosPreTrainedModel extends PreTrainedModel { +} +export class YolosModel extends YolosPreTrainedModel { +} +export class YolosForObjectDetection extends YolosPreTrainedModel { + /** + * @param {any} model_inputs + */ + _call(model_inputs: any): Promise; +} +export class YolosObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }: { + logits: Tensor; + pred_boxes: Tensor; + }); + logits: Tensor; + pred_boxes: Tensor; +} +export class SamPreTrainedModel extends PreTrainedModel { +} +/** + * Segment Anything Model (SAM) for generating segmentation masks, given an input image + * and optional 2D location and bounding boxes. + * + * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`. + * ```javascript + * import { SamModel, AutoProcessor, RawImage } from '@xenova/transformers'; + * + * const model = await SamModel.from_pretrained('Xenova/sam-vit-base'); + * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base'); + * + * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'; + * const raw_image = await RawImage.read(img_url); + * const input_points = [[[450, 600]]] // 2D localization of a window + * + * const inputs = await processor(raw_image, input_points); + * const outputs = await model(inputs); + * + * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes); + * // [ + * // Tensor { + * // dims: [ 1, 3, 1764, 2646 ], + * // type: 'bool', + * // data: Uint8Array(14002632) [ ... ], + * // size: 14002632 + * // } + * // ] + * const scores = outputs.iou_scores; + * // Tensor { + * // dims: [ 1, 1, 3 ], + * // type: 'float32', + * // data: Float32Array(3) [ + * // 0.8892380595207214, + * // 0.9311248064041138, + * // 0.983696699142456 + * // ], + * // size: 3 + * // } + * ``` + */ +export class SamModel extends SamPreTrainedModel { + /** + * Creates a new instance of the `SamModel` class. + * @param {Object} config The configuration object specifying the hyperparameters and other model settings. + * @param {Object} vision_encoder The ONNX session containing the vision encoder model. + * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model. + */ + constructor(config: any, vision_encoder: any, prompt_encoder_mask_decoder: any); + prompt_encoder_mask_decoder: any; + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. + * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. + */ + get_image_embeddings({ pixel_values }: { + pixel_values: Tensor; + }): Promise<{ + image_embeddings: Tensor; + image_positional_embeddings: Tensor; + }>; + /** + * @typedef {Object} SamModelInputs Object containing the model inputs. + * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. + * These can be obtained using a `SamProcessor`. + * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`. + * This is used by the prompt encoder to encode the prompt. + * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. + * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: + * - `1`: the point is a point that contains the object of interest + * - `0`: the point is a point that does not contain the object of interest + * - `-1`: the point corresponds to the background + * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder + * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. + * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. + */ + /** + * @param {SamModelInputs} model_inputs Object containing the model inputs. + * @returns {Promise} The output of the model. + */ + forward(model_inputs: { + /** + * Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. + * These can be obtained using a `SamProcessor`. + */ + pixel_values: Tensor; + /** + * Input 2D spatial points with shape `(batch_size, num_points, 2)`. + * This is used by the prompt encoder to encode the prompt. + */ + input_points: Tensor; + /** + * Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. + * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: + * - `1`: the point is a point that contains the object of interest + * - `0`: the point is a point that does not contain the object of interest + * - `-1`: the point corresponds to the background + * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder + */ + input_labels?: Tensor; + /** + * Image embeddings used by the mask decoder. + */ + image_embeddings?: Tensor; + /** + * Image positional embeddings used by the mask decoder. + */ + image_positional_embeddings?: Tensor; + }): Promise; + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + _call(model_inputs: any): Promise; +} +/** + * Base class for Segment-Anything model's output. + */ +export class SamImageSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + */ + constructor({ iou_scores, pred_masks }: { + iou_scores: Tensor; + pred_masks: Tensor; + }); + iou_scores: Tensor; + pred_masks: Tensor; +} +export class MarianPreTrainedModel extends PreTrainedModel { +} +export class MarianModel extends MarianPreTrainedModel { +} +export class MarianMTModel extends MarianPreTrainedModel { + /** + * Creates a new instance of the `MarianMTModel` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {any} decoder_merged_session + * @param {any} generation_config + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + decoder_merged_session: any; + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +export class M2M100PreTrainedModel extends PreTrainedModel { +} +export class M2M100Model extends M2M100PreTrainedModel { +} +export class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { + /** + * Creates a new instance of the `M2M100ForConditionalGeneration` class. + * @param {Object} config The model configuration object. + * @param {Object} session The ONNX session object. + * @param {any} decoder_merged_session + * @param {any} generation_config + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: any); + decoder_merged_session: any; + generation_config: any; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; +} +export class Wav2Vec2PreTrainedModel extends PreTrainedModel { +} +/** + * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `Wav2Vec2Model` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m'); + * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000); + * const inputs = await processor(audio); + * + * // Run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/mms-300m'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 1144, 1024 ], + * // type: 'float32', + * // data: Float32Array(1171456) [ ... ], + * // size: 1171456 + * // } + * // } + * ``` + */ +export class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { +} +export class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + _call(model_inputs: { + input_values: Tensor; + attention_mask: Tensor; + }): Promise; +} +export class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +export class HubertPreTrainedModel extends PreTrainedModel { +} +/** + * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `HubertModel` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960'); + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); + * const inputs = await processor(audio); + * + * // Load and run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 549, 768 ], + * // type: 'float32', + * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...], + * // size: 421632 + * // } + * // } + * ``` + */ +export class HubertModel extends Wav2Vec2PreTrainedModel { +} +/** + * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). + */ +export class HubertForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + _call(model_inputs: { + input_values: Tensor; + attention_mask: Tensor; + }): Promise; +} +/** + * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. + */ +export class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class WavLMPreTrainedModel extends PreTrainedModel { +} +/** + * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top. + * + * **Example:** Load and run a `WavLMModel` for feature extraction. + * + * ```javascript + * import { AutoProcessor, AutoModel, read_audio } from '@xenova/transformers'; + * + * // Read and preprocess audio + * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base'); + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); + * const inputs = await processor(audio); + * + * // Run model with inputs + * const model = await AutoModel.from_pretrained('Xenova/wavlm-base'); + * const output = await model(inputs); + * // { + * // last_hidden_state: Tensor { + * // dims: [ 1, 549, 768 ], + * // type: 'float32', + * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...], + * // size: 421632 + * // } + * // } + * ``` + */ +export class WavLMModel extends WavLMPreTrainedModel { +} +/** + * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). + */ +export class WavLMForCTC extends WavLMPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + _call(model_inputs: { + input_values: Tensor; + attention_mask: Tensor; + }): Promise; +} +/** + * WavLM Model with a sequence classification head on top (a linear layer over the pooled output). + */ +export class WavLMForSequenceClassification extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + _call(model_inputs: any): Promise; +} +/** + * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. + */ +export class SpeechT5PreTrainedModel extends PreTrainedModel { +} +/** + * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets. + */ +export class SpeechT5Model extends SpeechT5PreTrainedModel { +} +/** + * SpeechT5 Model with a speech encoder and a text decoder. + * + * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`. + * ```javascript + * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@xenova/transformers'; + * + * // Load the tokenizer and processor + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts'); + * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts'); + * + * // Load the models + * // NOTE: We use the unquantized versions as they are more accurate + * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { quantized: false }); + * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { quantized: false }); + * + * // Load speaker embeddings from URL + * const speaker_embeddings_data = new Float32Array( + * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer() + * ); + * const speaker_embeddings = new Tensor( + * 'float32', + * speaker_embeddings_data, + * [1, speaker_embeddings_data.length] + * ) + * + * // Run tokenization + * const { input_ids } = tokenizer('Hello, my dog is cute'); + * + * // Generate waveform + * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder }); + * console.log(waveform) + * // Tensor { + * // dims: [ 26112 ], + * // type: 'float32', + * // size: 26112, + * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ], + * // } + * ``` + */ +export class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { +} +/** + * SpeechT5 Model with a text encoder and a speech decoder. + */ +export class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel { + /** + * Creates a new instance of the `SpeechT5ForTextToSpeech` class. + * @param {Object} config The model configuration. + * @param {any} session session for the model. + * @param {any} decoder_merged_session session for the decoder. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + decoder_merged_session: any; + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_decoder_layers: any; + num_decoder_heads: any; + decoder_dim_kv: number; + num_encoder_layers: any; + num_encoder_heads: any; + encoder_dim_kv: number; + /** + * @typedef {Object} SpeechOutput + * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape + * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided + * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. + * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape + * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. + */ + /** + * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. + * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. + * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. + * @param {Object} options Optional parameters for generating speech. + * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. + * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. + * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. + * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. + * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. + * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. + */ + generate_speech(input_values: Tensor, speaker_embeddings: Tensor, { threshold, minlenratio, maxlenratio, vocoder, }?: { + threshold?: number; + minlenratio?: number; + maxlenratio?: number; + vocoder?: any; + output_cross_attentions?: boolean; + }): Promise<{ + /** + * The predicted log-mel spectrogram of shape + * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided + */ + spectrogram?: Tensor; + /** + * The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. + */ + waveform?: Tensor; + /** + * The outputs of the decoder's cross-attention layers of shape + * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. + */ + cross_attentions?: Tensor; + }>; +} +/** + * HiFi-GAN vocoder. + * + * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage. + */ +export class SpeechT5HifiGan extends PreTrainedModel { +} +export class TrOCRPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `TrOCRPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_encoder_layers: any; + num_decoder_layers: any; + num_encoder_heads: any; + num_decoder_heads: any; + encoder_dim_kv: number; + decoder_dim_kv: number; +} +/** + * The TrOCR Decoder with a language modeling head. + */ +export class TrOCRForCausalLM extends TrOCRPreTrainedModel { +} +/** + * The bare Mistral Model outputting raw hidden-states without any specific head on top. + */ +export class MistralPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `MistralPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class MistralModel extends MistralPreTrainedModel { +} +export class MistralForCausalLM extends MistralPreTrainedModel { +} +/** + * The bare Falcon Model outputting raw hidden-states without any specific head on top. + */ +export class FalconPreTrainedModel extends PreTrainedModel { + /** + * Creates a new instance of the `FalconPreTrainedModel` class. + * @param {Object} config The configuration of the model. + * @param {any} session The ONNX session containing the model weights. + * @param {GenerationConfig} generation_config The generation configuration. + */ + constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType); + generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType; + num_heads: any; + num_layers: any; + dim_kv: number; +} +export class FalconModel extends FalconPreTrainedModel { +} +export class FalconForCausalLM extends FalconPreTrainedModel { +} +export class ClapPreTrainedModel extends PreTrainedModel { +} +export class ClapModel extends ClapPreTrainedModel { +} +/** + * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output). + * + * **Example:** Compute text embeddings with `ClapTextModelWithProjection`. + * + * ```javascript + * import { AutoTokenizer, ClapTextModelWithProjection } from '@xenova/transformers'; + * + * // Load tokenizer and text model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused'); + * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); + * + * // Run tokenization + * const texts = ['a sound of a cat', 'a sound of a dog']; + * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); + * + * // Compute embeddings + * const { text_embeds } = await text_model(text_inputs); + * // Tensor { + * // dims: [ 2, 512 ], + * // type: 'float32', + * // data: Float32Array(1024) [ ... ], + * // size: 1024 + * // } + * ``` + */ +export class ClapTextModelWithProjection extends ClapPreTrainedModel { +} +/** + * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output). + * + * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`. + * + * ```javascript + * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@xenova/transformers'; + * + * // Load processor and audio model + * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused'); + * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); + * + * // Read audio and run processor + * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'); + * const audio_inputs = await processor(audio); + * + * // Compute embeddings + * const { audio_embeds } = await audio_model(audio_inputs); + * // Tensor { + * // dims: [ 1, 512 ], + * // type: 'float32', + * // data: Float32Array(512) [ ... ], + * // size: 512 + * // } + * ``` + */ +export class ClapAudioModelWithProjection extends ClapPreTrainedModel { +} +export class VitsPreTrainedModel extends PreTrainedModel { +} +/** + * The complete VITS model, for text-to-speech synthesis. + * + * **Example:** Generate speech from text with `VitsModel`. + * ```javascript + * import { AutoTokenizer, VitsModel } from '@xenova/transformers'; + * + * // Load the tokenizer and model + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng'); + * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng'); + * + * // Run tokenization + * const inputs = tokenizer('I love transformers'); + * + * // Generate waveform + * const { waveform } = await model(inputs); + * // Tensor { + * // dims: [ 1, 35328 ], + * // type: 'float32', + * // data: Float32Array(35328) [ ... ], + * // size: 35328, + * // } + * ``` + */ +export class VitsModel extends VitsPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} The outputs for the VITS model. + */ + _call(model_inputs: any): Promise; +} +export class SegformerPreTrainedModel extends PreTrainedModel { +} +/** + * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. + */ +export class SegformerModel extends SegformerPreTrainedModel { +} +/** + * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet. + */ +export class SegformerForImageClassification extends SegformerPreTrainedModel { +} +/** + * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes. + */ +export class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { +} +/** + * Base class of all AutoModels. Contains the `from_pretrained` function + * which is used to instantiate pretrained models. + */ +export class PretrainedMixin { + /** + * Mapping from model type to model class. + * @type {Map[]} + */ + static MODEL_CLASS_MAPPINGS: Map[]; + /** + * Whether to attempt to instantiate the base class (`PretrainedModel`) if + * the model type is not found in the mapping. + */ + static BASE_IF_FAIL: boolean; + /** + * Instantiate one of the model classes of the library from a pretrained model. + * + * The model class to instantiate is selected based on the `model_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. + * + * @returns {Promise} A new instance of the `PreTrainedModel` class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name, }?: import("./utils/hub.js").PretrainedOptions): Promise; +} +/** + * Helper class which is used to instantiate pretrained models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModel.from_pretrained('bert-base-uncased'); + */ +export class AutoModel extends PretrainedMixin { +} +/** + * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased-finetuned-sst-2-english'); + */ +export class AutoModelForSequenceClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTokenClassification.from_pretrained('Davlan/distilbert-base-multilingual-cased-ner-hrl'); + */ +export class AutoModelForTokenClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSeq2SeqLM.from_pretrained('t5-small'); + */ +export class AutoModelForSeq2SeqLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en'); + */ +export class AutoModelForSpeechSeq2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts'); + */ +export class AutoModelForTextToSpectrogram extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng'); + */ +export class AutoModelForTextToWaveform extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForCausalLM.from_pretrained('gpt2'); + */ +export class AutoModelForCausalLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForMaskedLM.from_pretrained('bert-base-uncased'); + */ +export class AutoModelForMaskedLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForQuestionAnswering.from_pretrained('distilbert-base-cased-distilled-squad'); + */ +export class AutoModelForQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForVision2Seq.from_pretrained('nlpconnect/vit-gpt2-image-captioning'); + */ +export class AutoModelForVision2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForImageClassification.from_pretrained('google/vit-base-patch16-224'); + */ +export class AutoModelForImageClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForImageSegmentation.from_pretrained('facebook/detr-resnet-50-panoptic'); + */ +export class AutoModelForImageSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024'); + */ +export class AutoModelForSemanticSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForObjectDetection.from_pretrained('facebook/detr-resnet-50'); + */ +export class AutoModelForObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForZeroShotObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +/** + * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function. + * The chosen model class is determined by the type specified in the model config. + * + * @example + * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base'); + */ +export class AutoModelForMaskGeneration extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForCTC extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForAudioClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForDocumentQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForImageMatting extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForImageToImage extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class AutoModelForDepthEstimation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS: Map[]; +} +export class Seq2SeqLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. + * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. + * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + */ + constructor({ logits, past_key_values, encoder_outputs, decoder_attentions, cross_attentions }: { + logits: Tensor; + past_key_values: Tensor; + encoder_outputs: Tensor; + decoder_attentions?: Tensor; + cross_attentions?: Tensor; + }); + logits: Tensor; + past_key_values: Tensor; + encoder_outputs: Tensor; + decoder_attentions: Tensor; + cross_attentions: Tensor; +} +/** + * Base class for outputs of sentence classification models. + */ +export class SequenceClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). + */ + constructor({ logits }: { + logits: Tensor; + }); + logits: Tensor; +} +/** + * Base class for outputs of token classification models. + */ +export class TokenClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification scores (before SoftMax). + */ + constructor({ logits }: { + logits: Tensor; + }); + logits: Tensor; +} +/** + * Base class for masked language models outputs. + */ +export class MaskedLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + */ + constructor({ logits }: { + logits: Tensor; + }); + logits: Tensor; +} +/** + * Base class for outputs of question answering models. + */ +export class QuestionAnsweringModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.start_logits Span-start scores (before SoftMax). + * @param {Tensor} output.end_logits Span-end scores (before SoftMax). + */ + constructor({ start_logits, end_logits }: { + start_logits: Tensor; + end_logits: Tensor; + }); + start_logits: Tensor; + end_logits: Tensor; +} +/** + * Base class for causal language model (or autoregressive) outputs. + */ +export class CausalLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + */ + constructor({ logits }: { + logits: Tensor; + }); + logits: Tensor; +} +/** + * Base class for causal language model (or autoregressive) outputs. + */ +export class CausalLMOutputWithPast extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) + * that can be used (see `past_key_values` input) to speed up sequential decoding. + */ + constructor({ logits, past_key_values }: { + logits: Tensor; + past_key_values: Tensor; + }); + logits: Tensor; + past_key_values: Tensor; +} +export class ImageMattingOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. + */ + constructor({ alphas }: { + alphas: Tensor; + }); + alphas: Tensor; +} +/** + * Describes the outputs for the VITS model. + */ +export class VitsModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. + * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. + * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. + */ + constructor({ waveform, spectrogram }: { + waveform: Tensor; + spectrogram: Tensor; + }); + waveform: Tensor; + spectrogram: Tensor; +} +export type InferenceSession = import('onnxruntime-web').InferenceSession; +/** + * Runs a single step of the text generation process for a given beam. + * + * @param {Object} self The decoder object. + * @param {Object} beam The beam to run. + * @param {Tensor} beam.input The input tensor. + * @param {Tensor} beam.model_input_ids The input ids to the model. + * @param {Tensor} beam.attention_mask The attention mask. + * @param {Object} beam.prev_model_outputs The past key values. + * @param {number[]} beam.output_token_ids The output token ids. + * @returns {Promise} The output of the generation step. + * @private + */ +declare function decoderRunBeam(self: any, beam: { + input: Tensor; + model_input_ids: Tensor; + attention_mask: Tensor; + prev_model_outputs: any; + output_token_ids: number[]; +}): Promise; +/** + * Starts the generation of text by initializing the beams for the given input token IDs. + * @param {Object} self The text generation model object. + * @param {Tensor} inputTokenIds An tensor of input token IDs to generate text from. + * @param {Object} generation_config The generation config. + * @param {number} numOutputTokens The maximum number of tokens to generate for each beam. + * @param {Tensor} [inputs_attention_mask] The attention mask tensor for the input token IDs. + * @returns {Object[]} An array of beams initialized with the given inputs and parameters. + * @private + */ +declare function decoderStartBeams(self: any, inputTokenIds: Tensor, generation_config: any, numOutputTokens: number, inputs_attention_mask?: Tensor): any[]; +/** + * Update a beam with a new token ID. + * @param {Object} beam The beam to update. + * @param {number} newTokenId The new token ID to add to the beam's output. + * @private + */ +declare function decoderUpdatebeam(beam: any, newTokenId: number): void; +/** + * Forward pass of an encoder model. + * @param {Object} self The encoder model. + * @param {Object} model_inputs The input data to be used for the forward pass. + * @returns {Promise} Promise that resolves with an object containing the model's outputs. + * @private + */ +declare function encoderForward(self: any, model_inputs: any): Promise; +import { Tensor } from './utils/tensor.js'; +export {}; +//# sourceMappingURL=models.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/models.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/models.d.ts.map new file mode 100644 index 000000000..d87a33fe3 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/models.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/models.js"],"names":[],"mappings":";;;;AA8oBA;;GAEG;AACH;IA+DI;;;;;;;;;;;;;;OAcG;IACH,sDATW,MAAM,sGAKN,OAAO,gBAAgB,EAAE,iBAAiB,GAExC,QAAQ,eAAe,CAAC,CAmEpC;IA5ID;;;;OAIG;IACH,kCAFW,GAAG,EAsCb;IA3CD,wBAA8B;IAU1B,YAAoB;IACpB,aAAsB;IAKtB,sBAAyB;IACzB,gCAAoB;IACpB,yCAA0B;IAC1B,sCAAuB;IACvB,gCAAoB;IAyBxB;;;;MAIE;IACF,WAHY,QAAQ,OAAO,EAAE,CAAC,CAa7B;IAoFD;;;;OAIG;IACH,0BAFa,YAAe,CAI3B;IAED;;;;;;OAMG;IACH,4BAHa,YAAe,CAK3B;IAED;;;;;OAKG;IACH,8BAwHC;IAED;;;;;OAKG;IACH,0CAHW,OAAO,uBAAuB,EAAE,oBAAoB,GAClD,OAAO,uBAAuB,EAAE,oBAAoB,CAkBhE;IAED;;OAEG;IAEH;;;;;;;;;;;;OAYG;IACH,8FAPW,sIAAwB,IAAI,qBAC5B,MAAO,IAAI;QAEM,qBAAqB;qBAmMhD;IAED;;;;;OAKG;IACH,4BAwBC;IAED;;;;;OAKG;IACH,gCAYC;IAED;;;;;;OAMG;IACH,+DAmBC;IAED;;;;;OAKG;IACH,wCAcC;IAED;;;;;OAKG;IACH,8DA0DC;IAED;;;;;;;;OAQG;IACH,sBAEC;IAED;;;;;OAKG;IACH,gBAEC;IAED;;;;;OAKG;IACH,mBAEC;CACJ;AAID;CAA4B;AAE5B;;GAEG;AACH;IACI;;;;;OAKG;IACH;QAJ0B,iBAAiB,EAAhC,MAAM;QACU,aAAa,GAA7B,MAAM;QACU,UAAU,GAA1B,MAAM;OAOhB;IAHG,0BAA0C;IAC1C,sBAAkC;IAClC,mBAA4B;CAEnC;AAGD;CAA4D;AAC5D;CAAsD;AAEtD;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAAgE;AAEhE;;GAEG;AACH;CAA8D;AAE9D;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;CAAgE;AAEhE;;GAEG;AACH;CAA8D;AAE9D;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;CAA+D;AAE/D;;;;GAIG;AACH;CAA4D;AAE5D;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;CAAiE;AAEjE;;GAEG;AACH;CAAgE;AAEhE;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAA+D;AAE/D;;GAEG;AACH;CAA4D;AAE5D;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAAiE;AAEjE;;GAEG;AACH;CAAgE;AAEhE;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAAkE;AAClE;CAAkE;AAElE;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAGD;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAMD;CAA2D;AAE3D;;GAEG;AACH;CAAoD;AAEpD;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;;GAGG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAMD;CAAkE;AAClE;CAAkE;AAElE;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAA6D;AAE7D;;GAEG;AACH;CAAwD;AAExD;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;CAAmE;AACnE;CAAoE;AACpE;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AACD;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AACD;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;CAA8D;AAC9D;CAA0D;AAC1D;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AACD;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AACD;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAMD;CAA0D;AAE1D;CAAkD;AAElD;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,kCAJW,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAwD;IACxD,uBAA8C;IAC9C,oBAAsC;IAEtC,wBAAgD;IAChD,uBAA8C;IAC9C,oBAAsC;CAE7C;AAMD;;GAEG;AACH;CAA8D;AAE9D;;GAEG;AACH;CAA0D;AAE1D;;GAEG;AACH;IACI;;;;;;OAMG;IACH,kCAJW,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAwD;IACxD,uBAA8C;IAC9C,oBAAsC;IAEtC,wBAAgD;IAChD,uBAA8C;IAC9C,oBAAsC;CAE7C;AAMD;CAA2D;AAE3D;CAAoD;AAEpD;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,oBALW,GAAG,WACH,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAwD;IACxD,uBAA8C;IAC9C,oBAAsC;IAEtC,wBAAgD;IAChD,uBAA8C;IAC9C,oBAAsC;CAE7C;AAKD;CAA4D;AAE5D;;GAEG;AACH;CAAsD;AAEtD;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,4FAYC;IAVG,4BAAoD;IACpD,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAGzE;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAMD;CAA6D;AAE7D;;GAEG;AACH;CAAwD;AAExD;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,4FAYC;IAVG,4BAAoD;IACpD,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAGzE;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAGD;IACI;;;;;OAKG;IACH,8EAWC;IATG,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAEzE;AAMD;CAAkE;AAElE;;GAEG;AACH;CAAkE;AAElE;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,oBALW,GAAG,WACH,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAEzE;AAMD;CAAuE;AAEvE;;GAEG;AACH;CAA4E;AAE5E;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,oBALW,GAAG,WACH,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAEzE;AAMD;CAA+D;AAC/D;CAA4D;AAE5D;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAMD;;GAEG;AACH;CAA2D;AAE3D;;GAEG;AACH;CAAoD;AAEpD;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAAkE;AAClE;CAAkE;AAElE;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,cAAc,CAAC,CAInC;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,qBAAqB,CAAC,CAI1C;CACJ;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH,0BAFa,QAAQ,4BAA4B,CAAC,CAIjD;CACJ;AAKD;CAA2D;AAE3D;;GAEG;AACH;CAAoD;AAEpD;;;GAGG;AACH;CAAqE;AAKrE;CAA+D;AAE/D;;GAEG;AACH;CAA4D;AAE5D;;GAEG;AACH;IAKI;;;;;;OAMG;IACH,4FAYC;IAtBD,iCAAgC;IAY5B,4BAAoD;IACpD,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAGtE;;;;;;;;OAQG;IAEH;;;;;;OAMG;IACH,wEAFa,YAAe,CAqD3B;IAED;;;;;;;;;;;OAWG;IACH;QAR0C,gBAAgB,EAA/C,MAAM,EAAE,EAAE,EAAE;QACmB,kBAAkB,EAAjD,MAAM,EAAE,EAAE,EAAE;QACiB,SAAS,EAAtC,MAAM,EAAE,EAAE;wBACV,MAAM,EAAE,EAAE,eACV,MAAM,mBACN,MAAM,GACJ,MAAM,CA2FlB;CACJ;AAID;;GAEG;AACH;IAGI;;;;;;OAMG;IACH,+DAHW,GAAG,0BAiDb;IA5CG,4BAAoD;IACpD,uBAA0C;IA0B1C,yBAAsD;IAGlD,wBAAoD;IACpD,uBAAkD;IAClD,oBAA4C;IAE5C,wBAAoD;IACpD,uBAAkD;IAClD,oBAA4C;IAI5C,gBAAoC;IACpC,eAAkC;IAClC,YAA4B;CAGvC;AAKD;CAA4D;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH;CAAsD;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAQC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAOC;AAMD;CAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH;CAA0D;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAQC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAOC;AAGD;CAAmE;AAEnE;CAAoE;AAMpE;CAA+D;AAE/D;CAA4D;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH;CAA2E;AAM3E;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAmC;IACnC,gBAAqC;IACrC,eAAiD;CAExD;AAED;CAAsD;AAEtD;;GAEG;AACH;CAA4D;AAQ5D;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAsC;IACtC,gBAAwC;IACxC,eAAsD;CAE7D;AACD;CAA0D;AAE1D;CAAgE;AAKhE;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAgD;IAChD,gBAA+C;IAC/C,eAAsD;CAE7D;AACD;CAA4D;AAE5D;CAAkE;AAMlE;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAmC;IACnC,gBAAqC;IACrC,eAAiD;CAExD;AAED;CAAsD;AAEtD;CAA4D;AAM5D;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAmC;IACnC,gBAAqC;IACrC,eAAiD;CAExD;AAED;CAAkE;AAElE;CAAwE;AAKxE;IACI;;;;;OAKG;IACH,uLAUC;IARG,+IAA0C;IAK1C,eAAmC;IACnC,gBAAqC;IACrC,eAAiD;CAExD;AACD;;GAEG;AACH;CAA4D;AAE5D;;GAEG;AACH;CAAkE;AAOlE;;GAEG;AACH;IACI;;;;;OAKG;IACH,uLAUC;IARG,+IAA0C;IAK1C,eAAmF;IACnF,gBAA+C;IAC/C,eAAuE;CAE9E;AACD;;GAEG;AACH;CAAwD;AAExD;CAA8D;AAM9D;IACI;;;;;OAKG;IACH,uLAUC;IARG,+IAA0C;IAK1C,eAAgD;IAChD,gBAA+C;IAC/C,eAAsD;CAE7D;AACD;;GAEG;AACH;CAAoD;AAEpD;CAA0D;AAM1D;;GAEG;AACH;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAmC;IACnC,gBAAqC;IACrC,eAAsD;CAE7D;AAED;;GAEG;AACH;CAAwD;AAExD;;GAEG;AACH;CAA8D;AAK9D;IACI;;;;;OAKG;IACH,uLAUC;IARG,+IAA0C;IAK1C,eAAoC;IACpC,gBAAsC;IACtC,eAAkD;CAEzD;AAED;;GAEG;AACH;CAAoD;AAEpD;;GAEG;AACH;CAA0D;AAM1D;IACI;;;;;OAKG;IACH,uLAUC;IARG,+IAA0C;IAK1C,eAAgD;IAChD,gBAA+C;IAC/C,eAAsD;CAE7D;AAED;;GAEG;AACH;CAAoD;AAEpD;;GAEG;AACH;CAA0D;AAI1D;CAA2D;AAC3D;CAAoD;AACpD;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAID;CAAgE;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,+BAIb;CACJ;AAID;CAAiE;AACjE;CAAgE;AAChE;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAMD;CAA8D;AAC9D;CAA0D;AAC1D;CAAuE;AAKvE;CAA4D;AAC5D;CAAsD;AACtD;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAKD;CAA4D;AAC5D;CAAsD;AACtD;IACI;;OAEG;IACH,oBAFW,GAAG,sCAIb;CACJ;AAED;IACI;;;;OAIG;IACH,0BAFa,QAAQ,sBAAsB,CAAC,CAI3C;CACJ;AAED;IACI;;;;;OAKG;IACH;QAJ0B,MAAM,EAArB,MAAM;QACS,UAAU,EAAzB,MAAM;OAOhB;IAFG,eAAoB;IACpB,mBAA4B;CAEnC;AAED;IACI;;;;;OAKG;IACH;QAJ0B,MAAM,EAArB,MAAM;QACS,UAAU,EAAzB,MAAM;QACS,UAAU,EAAzB,MAAM;OAOhB;IAHG,eAAoB;IACpB,mBAA4B;IAC5B,mBAA4B;CAEnC;AAID;CAAwE;AAExE;;;GAGG;AACH;CAA8E;AAE9E;;;GAGG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,kDAIb;CACJ;AACD;CAAwF;AAKxF;CAA4D;AAC5D;CAAsD;AACtD;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAKD;;GAEG;AACH;CAA8D;AAE9D;;GAEG;AACH;CAA0D;AAE1D;;GAEG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAKD;CAA4D;AAC5D;CAAsD;AACtD;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAID;CAA+D;AAE/D;;GAEG;AACH;CAA4D;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH;CAA8E;AAI9E;CAA2D;AAE3D;;GAEG;AACH;CAAoD;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH;CAAiE;AAIjE;CAA4D;AAE5D;;GAEG;AACH;CAAsD;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH;CAAmE;AAInE;CAAiE;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyEG;AACH;CAAgE;AAKhE;CAAgE;AAEhE;;GAEG;AACH;CAA8D;AAE9D;;GAEG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAKD;CAAkE;AAElE;;GAEG;AACH;CAAkE;AAElE;;GAEG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAID;CAA8D;AAE9D;;GAEG;AACH;CAA0D;AAE1D;;GAEG;AACH;IACI;;OAEG;IACH,oBAFW,GAAG,qCAIb;CACJ;AAKD;CAA6D;AAC7D;CAAwD;AACxD;IACI;;OAEG;IACH,oBAFW,GAAG,uCAIb;CACJ;AAED;IACI;;;;;OAKG;IACH;QAJ0B,MAAM,EAArB,MAAM;QACS,UAAU,EAAzB,MAAM;OAOhB;IAFG,eAAoB;IACpB,mBAA4B;CAEnC;AAKD;CAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH;IACI;;;;;OAKG;IACH,2EAFW,GAAG,EAKb;IADG,iCAA8D;IAGlE;;;;;OAKG;IACH;QAHgC,YAAY,EAAjC,MAAM;QACJ,QAAQ;QAAE,gBAAgB,EAAE,MAAM,CAAC;QAAC,2BAA2B,EAAE,MAAM,CAAA;KAAE,CAAC,CAUtF;IAED;;;;;;;;;;;;;;OAcG;IAEH;;;OAGG;IACH;;;;;sBAlBc,MAAM;;;;;sBAEN,MAAM;;;;;;;;;uBAEN,MAAM;;;;2BAMN,MAAM;;;;sCACN,MAAM;QAKP,YAAe,CA+B3B;IAED;;;;OAIG;IACH,0BAFa,QAAQ,0BAA0B,CAAC,CAI/C;CACJ;AAGD;;GAEG;AACH;IACI;;;;OAIG;IACH;QAH0B,UAAU,EAAzB,MAAM;QACS,UAAU,EAAzB,MAAM;OAMhB;IAFG,mBAA4B;IAC5B,mBAA4B;CAEnC;AAMD;CAA8D;AAE9D;CAA0D;AAE1D;IAEI;;;;;;MAME;IACF,+DAHU,GAAG,qBACH,GAAG,EAcZ;IAVG,4BAAoD;IACpD,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAEzE;AAKD;CAA8D;AAE9D;CAA0D;AAE1D;IAEI;;;;;;MAME;IACF,+DAHU,GAAG,qBACH,GAAG,EAcZ;IAVG,4BAAoD;IACpD,uBAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;IAElE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAkE;CAGzE;AAKD;CAAgE;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAA8D;AAE9D;IACI;;;;OAIG;IACH;QAHgC,YAAY,EAAjC,MAAM;QACe,cAAc,EAAnC,MAAM;gCAIhB;CACJ;AAED;IACI;;;;OAIG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAKD;CAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAA4D;AAE5D;;GAEG;AACH;IACI;;;;OAIG;IACH;QAHgC,YAAY,EAAjC,MAAM;QACe,cAAc,EAAnC,MAAM;gCAIhB;CACJ;AAED;;GAEG;AACH;IACI;;;;OAIG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAKD;;GAEG;AACH;CAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAAwD;AAExD;;GAEG;AACH;IACI;;;;OAIG;IACH;QAHgC,YAAY,EAAjC,MAAM;QACe,cAAc,EAAnC,MAAM;gCAIhB;CACJ;AAED;;GAEG;AACH;IACI;;;;OAIG;IACH,0BAFa,QAAQ,wBAAwB,CAAC,CAI7C;CACJ;AAID;;GAEG;AACH;CAAgE;AAEhE;;GAEG;AACH;CAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH;CAAwE;AAExE;;GAEG;AACH;IAEI;;;;;;OAMG;IACH,kCAJW,GAAG,0BACH,GAAG,kJAeb;IAVG,4BAAoD;IACpD,+IAA0C;IAE1C,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAsE;IAEtE,wBAAoD;IACpD,uBAA4D;IAC5D,uBAAsE;IAG1E;;;;;;;OAOG;IAEH;;;;;;;;;;;OAWG;IACH,8BAVW,MAAM,sBACN,MAAM;QAEW,SAAS,GAA1B,MAAM;QACW,WAAW,GAA5B,MAAM;QACW,WAAW,GAA5B,MAAM;QACW,OAAO;QACN,uBAAuB,GAAzC,OAAO;;;;;;sBAhBJ,MAAM;;;;mBAEN,MAAM;;;;;2BACN,MAAM;OAsFnB;CACJ;AAED;;;;GAIG;AACH;CAEC;AAMD;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,wBAA8E;IAApD,wBAAoD;IAC9E,uBAAqF;IAA5D,uBAA4D;IACrF,uBAAwF;IAAlE,uBAAkE;CAE/F;AAED;;GAEG;AACH;CAA8D;AAO9D;;GAEG;AACH;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAgD;IAChD,gBAA+C;IAC/C,eAAuE;CAE9E;AAED;CAA4D;AAE5D;CAAkE;AAKlE;;GAEG;AACH;IACI;;;;;OAKG;IACH,kCAHW,GAAG,kJAab;IARG,+IAA0C;IAK1C,eAAgD;IAChD,gBAA+C;IAC/C,eAAuE;CAE9E;AAED;CAA0D;AAE1D;CAAgE;AAMhE;CAA4D;AAE5D;CAAsD;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAQC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH;CAOC;AAMD;CAA4D;AAE5D;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH;IACI;;;;OAIG;IACH,0BAFa,QAAQ,eAAe,CAAC,CAIpC;CACJ;AAKD;CAAiE;AAEjE;;GAEG;AACH;CAAgE;AAEhE;;GAEG;AACH;CAAiF;AAEjF;;GAEG;AACH;CAAkF;AASlF;;;GAGG;AACH;IACI;;;OAGG;IACH,6BAFU,IAAI,MAAM,MAAS,EAAE,CAEI;IAEnC;;;OAGG;IACH,6BAA4B;IAvwI5B;;;;;;;;;;;;;;OAcG;IACH,wOAiEC;CAuuIJ;AAiUD;;;;;;GAMG;AACH;CAKC;AAED;;;;;;GAMG;AACH;IACI,8FAAgF;CACnF;AAED;;;;;;GAMG;AACH;IACI,2FAA6E;CAChF;AAED;;;;;;GAMG;AACH;IACI,8IAA6E;CAChF;AAED;;;;;;GAMG;AACH;IACI,8IAAyE;CAC5E;AAED;;;;;;GAMG;AACH;IACI,wFAA4E;CAC/E;AAED;;;;;;GAMG;AACH;IACI,0EAAyE;CAC5E;AAED;;;;;;GAMG;AACH;IACI,wHAAiE;CACpE;AAED;;;;;;GAMG;AACH;IACI,gFAAkE;CACrE;AAED;;;;;;GAMG;AACH;IACI,yFAA2E;CAC9E;AAED;;;;;;GAMG;AACH;IACI,0FAAqE;CACxE;AAED;;;;;;GAMG;AACH;IACI,gGAA6E;CAChF;AAED;;;;;;GAMG;AACH;IACI,4FAA2E;CAC9E;AAED;;;;;;GAMG;AACH;IACI,iGAA8E;CACjF;AAED;;;;;;GAMG;AACH;IACI,uFAAyE;CAC5E;AAED;IACI,yFAAmF;CACtF;AAGD;;;;;;GAMG;AACH;IACI,yEAAwE;CAC3E;AAED;IACI,+EAA4D;CAC/D;AAED;IACI,0FAA6E;CAChF;AAED;IACI,0FAAoF;CACvF;AAED;IACI,wFAAsE;CACzE;AAED;IACI,+FAAuE;CAC1E;AAED;IACI,sFAAyE;CAC5E;AAKD;IACI;;;;;;;OAOG;IACH;QAN0B,MAAM,EAArB,MAAM;QACS,eAAe,EAA9B,MAAM;QACS,eAAe,EAA9B,MAAM;QACU,kBAAkB,GAAlC,MAAM;QACU,gBAAgB,GAAhC,MAAM;OAShB;IALG,eAAoB;IACpB,wBAAsC;IACtC,wBAAsC;IACtC,2BAA4C;IAC5C,yBAAwC;CAE/C;AAED;;GAEG;AACH;IACI;;;OAGG;IACH;QAF0B,MAAM,EAArB,MAAM;OAKhB;IADG,eAAoB;CAE3B;AAED;;GAEG;AACH;IACI;;;OAGG;IACH;QAF0B,MAAM,EAArB,MAAM;OAKhB;IADG,eAAoB;CAE3B;AAED;;GAEG;AACH;IACI;;;OAGG;IACH;QAF0B,MAAM,EAArB,MAAM;OAKhB;IADG,eAAoB;CAE3B;AAED;;GAEG;AACH;IACI;;;;OAIG;IACH;QAH0B,YAAY,EAA3B,MAAM;QACS,UAAU,EAAzB,MAAM;OAMhB;IAFG,qBAAgC;IAChC,mBAA4B;CAEnC;AAGD;;GAEG;AACH;IACI;;;OAGG;IACH;QAF0B,MAAM,EAArB,MAAM;OAKhB;IADG,eAAoB;CAE3B;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH;QAJ0B,MAAM,EAArB,MAAM;QACS,eAAe,EAA9B,MAAM;OAOhB;IAFG,eAAoB;IACpB,wBAAsC;CAE7C;AAED;IACI;;;OAGG;IACH;QAF0B,MAAM,EAArB,MAAM;OAKhB;IADG,eAAoB;CAE3B;AAED;;GAEG;AACH;IACI;;;;;OAKG;IACH;QAJ0B,QAAQ,EAAvB,MAAM;QACS,WAAW,EAA1B,MAAM;OAOhB;IAFG,iBAAwB;IACxB,oBAA8B;CAErC;+BA3kLa,OAAO,iBAAiB,EAAE,gBAAgB;AAqgBxD;;;;;;;;;;;;GAYG;AACH;IARwB,KAAK,EAAlB,MAAM;IACO,eAAe,EAA5B,MAAM;IACO,cAAc,EAA3B,MAAM;IACO,kBAAkB;IAChB,gBAAgB,EAA/B,MAAM,EAAE;IACN,YAAe,CAwB3B;AApFD;;;;;;;;;GASG;AACH,6DAPW,MAAM,2CAEN,MAAM,0BACN,MAAM,GACJ,KAAQ,CAyCpB;AAsCD;;;;;GAKG;AACH,0DAHW,MAAM,QAMhB;AAvJD;;;;;;GAMG;AACH,+DAHa,YAAe,CAkB3B;uBAvbM,mBAAmB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts b/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts new file mode 100644 index 000000000..840a5dac5 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts @@ -0,0 +1,2330 @@ +/** + * @typedef {keyof typeof SUPPORTED_TASKS} TaskType + * @typedef {keyof typeof TASK_ALIASES} AliasType + * @typedef {TaskType | AliasType} PipelineType All possible pipeline types. + * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes. + * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes. + * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes. + */ +/** + * Utility factory method to build a `Pipeline` object. + * + * @template {PipelineType} T The type of pipeline to return. + * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are: + * - `"audio-classification"`: will return a `AudioClassificationPipeline`. + * - `"automatic-speech-recognition"`: will return a `AutomaticSpeechRecognitionPipeline`. + * - `"depth-estimation"`: will return a `DepthEstimationPipeline`. + * - `"document-question-answering"`: will return a `DocumentQuestionAnsweringPipeline`. + * - `"feature-extraction"`: will return a `FeatureExtractionPipeline`. + * - `"fill-mask"`: will return a `FillMaskPipeline`. + * - `"image-classification"`: will return a `ImageClassificationPipeline`. + * - `"image-segmentation"`: will return a `ImageSegmentationPipeline`. + * - `"image-to-text"`: will return a `ImageToTextPipeline`. + * - `"object-detection"`: will return a `ObjectDetectionPipeline`. + * - `"question-answering"`: will return a `QuestionAnsweringPipeline`. + * - `"summarization"`: will return a `SummarizationPipeline`. + * - `"text2text-generation"`: will return a `Text2TextGenerationPipeline`. + * - `"text-classification"` (alias "sentiment-analysis" available): will return a `TextClassificationPipeline`. + * - `"text-generation"`: will return a `TextGenerationPipeline`. + * - `"token-classification"` (alias "ner" available): will return a `TokenClassificationPipeline`. + * - `"translation"`: will return a `TranslationPipeline`. + * - `"translation_xx_to_yy"`: will return a `TranslationPipeline`. + * - `"zero-shot-classification"`: will return a `ZeroShotClassificationPipeline`. + * - `"zero-shot-audio-classification"`: will return a `ZeroShotAudioClassificationPipeline`. + * - `"zero-shot-image-classification"`: will return a `ZeroShotImageClassificationPipeline`. + * - `"zero-shot-object-detection"`: will return a `ZeroShotObjectDetectionPipeline`. + * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used. + * @param {import('./utils/hub.js').PretrainedOptions} [options] Optional parameters for the pipeline. + * @returns {Promise} A Pipeline object for the specified task. + * @throws {Error} If an unsupported pipeline is requested. + */ +export function pipeline(task: T, model?: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, }?: import('./utils/hub.js').PretrainedOptions): Promise; +declare const Pipeline_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * @callback DisposeType Disposes the item. + * @returns {Promise} A promise that resolves when the item has been disposed. + * + * @typedef {Object} Disposable + * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed. + */ +/** + * The Pipeline class is the class from which all pipelines inherit. + * Refer to this class for methods shared across different pipelines. + * @extends Callable + */ +export class Pipeline extends Pipeline_base { + /** + * Create a new Pipeline. + * @param {Object} options An object containing the following properties: + * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. + * @param {PreTrainedModel} [options.model] The model used by the pipeline. + * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). + * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). + */ + constructor({ task, model, tokenizer, processor }: { + task?: string; + model?: PreTrainedModel; + tokenizer?: PreTrainedTokenizer; + processor?: Processor; + }); + task: string; + model: PreTrainedModel; + tokenizer: PreTrainedTokenizer; + processor: Processor; + dispose(): Promise; +} +declare const TextClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType; +/** + * @typedef {Object} ModelTokenizerConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. + * + * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline. + */ +/** + * @typedef {Object} ModelProcessorConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {Processor} processor The processor used by the pipeline. + * + * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline. + * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline. + */ +/** + * @typedef {Object} ModelTokenizerProcessorConstructorArgs + * @property {string} task The task of the pipeline. Useful for specifying subtasks. + * @property {PreTrainedModel} model The model used by the pipeline. + * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. + * @property {Processor} processor The processor used by the pipeline. + * + * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline. + * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline. + */ +/** + * @typedef {Object} TextClassificationSingle + * @property {string} label The label predicted. + * @property {number} score The corresponding probability. + * @typedef {TextClassificationSingle[]} TextClassificationOutput + * + * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines. + * @property {number} [topk=1] The number of top predictions to be returned. + * + * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs. + * @param {string|string[]} texts The input text(s) to be classified. + * @param {TextClassificationPipelineOptions} [options] The options to use for text classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType + */ +/** + * Text classification pipeline using any `ModelForSequenceClassification`. + * + * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`. + * ```javascript + * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english'); + * const output = await classifier('I love transformers!'); + * // [{ label: 'POSITIVE', score: 0.999788761138916 }] + * ``` + * + * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes). + * ```javascript + * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment'); + * const output = await classifier('Le meilleur film de tous les temps.', { topk: 5 }); + * // [ + * // { label: '5 stars', score: 0.9610759615898132 }, + * // { label: '4 stars', score: 0.03323351591825485 }, + * // { label: '3 stars', score: 0.0036155181005597115 }, + * // { label: '1 star', score: 0.0011325967498123646 }, + * // { label: '2 stars', score: 0.0009423971059732139 } + * // ] + * ``` + * + * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes). + * ```javascript + * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert'); + * const output = await classifier('I hate you!', { topk: null }); + * // [ + * // { label: 'toxic', score: 0.9593140482902527 }, + * // { label: 'insult', score: 0.16187334060668945 }, + * // { label: 'obscene', score: 0.03452680632472038 }, + * // { label: 'identity_hate', score: 0.0223250575363636 }, + * // { label: 'threat', score: 0.019197041168808937 }, + * // { label: 'severe_toxic', score: 0.005651099607348442 } + * // ] + * ``` + */ +export class TextClassificationPipeline extends TextClassificationPipeline_base { + _call(texts: string | string[], options?: TextClassificationPipelineOptions): Promise; +} +declare const TokenClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType; +/** + * @typedef {Object} TokenClassificationSingle + * @property {string} word The token/word classified. This is obtained by decoding the selected tokens. + * @property {number} score The corresponding probability for `entity`. + * @property {string} entity The entity predicted for that token/word. + * @property {number} index The index of the corresponding token in the sentence. + * @property {number} [start] The index of the start of the corresponding entity in the sentence. + * @property {number} [end] The index of the end of the corresponding entity in the sentence. + * @typedef {TokenClassificationSingle[]} TokenClassificationOutput + * + * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines. + * @property {string[]} [ignore_labels] A list of labels to ignore. + * + * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs. + * @param {string|string[]} texts One or several texts (or one list of texts) for token classification. + * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification. + * @returns {Promise} The result. + * + * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType + */ +/** + * Named Entity Recognition pipeline using any `ModelForTokenClassification`. + * + * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`. + * ```javascript + * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); + * const output = await classifier('My name is Sarah and I live in London'); + * // [ + * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' }, + * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' } + * // ] + * ``` + * + * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels). + * ```javascript + * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); + * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] }); + * // [ + * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' }, + * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' }, + * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' }, + * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' }, + * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' }, + * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' }, + * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' }, + * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' } + * // ] + * ``` + */ +export class TokenClassificationPipeline extends TokenClassificationPipeline_base { + _call(texts: string | string[], options?: TokenClassificationPipelineOptions): Promise; +} +declare const QuestionAnsweringPipeline_base: new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType; +/** + * @typedef {Object} QuestionAnsweringOutput + * @property {number} score The probability associated to the answer. + * @property {number} [start] The character start index of the answer (in the tokenized version of the input). + * @property {number} [end] The character end index of the answer (in the tokenized version of the input). + * @property {string} answer The answer to the question. + * + * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines. + * @property {number} [topk=1] The number of top answer predictions to be returned. + * + * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s). + * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument). + * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument). + * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering. + * @returns {Promise} An array or object containing the predicted answers and scores. + * + * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType + */ +/** + * Question Answering pipeline using any `ModelForQuestionAnswering`. + * + * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`. + * ```javascript + * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad'); + * const question = 'Who was Jim Henson?'; + * const context = 'Jim Henson was a nice puppet.'; + * const output = await answerer(question, context); + * // { + * // answer: "a nice puppet", + * // score: 0.5768911502526741 + * // } + * ``` + */ +export class QuestionAnsweringPipeline extends QuestionAnsweringPipeline_base { + _call(question: string | string[], context: string | string[], options?: QuestionAnsweringPipelineOptions): Promise; +} +declare const FillMaskPipeline_base: new (options: TextPipelineConstructorArgs) => FillMaskPipelineType; +/** + * @typedef {Object} FillMaskSingle + * @property {string} sequence The corresponding input with the mask token prediction. + * @property {number} score The corresponding probability. + * @property {number} token The predicted token id (to replace the masked one). + * @property {string} token_str The predicted token (to replace the masked one). + * @typedef {FillMaskSingle[]} FillMaskOutput + * + * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines. + * @property {number} [topk=5] When passed, overrides the number of predictions to return. + * + * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs. + * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens. + * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling. + * @returns {Promise} An array of objects containing the score, predicted token, predicted token string, + * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text). + * If only one input text is given, the output will be an array of objects. + * @throws {Error} When the mask token is not found in the input text. + * + * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType + */ +/** + * Masked language modeling prediction pipeline using any `ModelWithLMHead`. + * + * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`. + * ```javascript + * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); + * const output = await unmasker('The goal of life is [MASK].'); + * // [ + * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' }, + * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' }, + * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' }, + * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' }, + * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' } + * // ] + * ``` + * + * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result). + * ```javascript + * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); + * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { topk: 1 }); + * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }] + * ``` + */ +export class FillMaskPipeline extends FillMaskPipeline_base { + _call(texts: string | string[], options?: FillMaskPipelineOptions): Promise; +} +declare const Text2TextGenerationPipeline_base: new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType; +/** + * @typedef {Object} Text2TextGenerationSingle + * @property {string} generated_text The generated text. + * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput + * + * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs. + * @param {string|string[]} texts Input text for the encoder. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType + */ +/** + * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks. + * + * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`. + * ```javascript + * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M'); + * const output = await generator('how can I become more healthy?', { + * max_new_tokens: 100, + * }); + * // [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }] + * ``` + */ +export class Text2TextGenerationPipeline extends Text2TextGenerationPipeline_base { + /** @type {'generated_text'} */ + _key: 'generated_text'; + _call(texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType): Promise; +} +declare const SummarizationPipeline_base: new (options: TextPipelineConstructorArgs) => SummarizationPipelineType; +/** + * @typedef {Object} SummarizationSingle + * @property {string} summary_text The summary text. + * @typedef {SummarizationSingle[]} SummarizationOutput + * + * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs. + * @param {string|string[]} texts One or several articles (or one list of articles) to summarize. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType + */ +/** + * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline. + * + * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`. + * ```javascript + * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6'); + * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' + + * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' + + * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' + + * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' + + * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' + + * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' + + * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' + + * 'tallest free-standing structure in France after the Millau Viaduct.'; + * const output = await generator(text, { + * max_new_tokens: 100, + * }); + * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }] + * ``` + */ +export class SummarizationPipeline extends SummarizationPipeline_base { + /** @type {'summary_text'} */ + _key: 'summary_text'; +} +declare const TranslationPipeline_base: new (options: TextPipelineConstructorArgs) => TranslationPipelineType; +/** + * @typedef {Object} TranslationSingle + * @property {string} translation_text The translated text. + * @typedef {TranslationSingle[]} TranslationOutput + * + * @callback TranslationPipelineCallback Translate the text(s) given as inputs. + * @param {string|string[]} texts Texts to be translated. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} + * + * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType + */ +/** + * Translates text from one language to another. + * + * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`. + * + * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M'); + * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', { + * src_lang: 'hin_Deva', // Hindi + * tgt_lang: 'fra_Latn', // French + * }); + * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }] + * ``` + * + * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`. + * + * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/m2m100_418M'); + * const output = await translator('生活就像一盒巧克力。', { + * src_lang: 'zh', // Chinese + * tgt_lang: 'en', // English + * }); + * // [{ translation_text: 'Life is like a box of chocolate.' }] + * ``` + * + * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`. + * + * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered) + * for the full list of languages and their corresponding codes. + * + * ```javascript + * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt'); + * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', { + * src_lang: 'hi_IN', // Hindi + * tgt_lang: 'fr_XX', // French + * }); + * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }] + * ``` + */ +export class TranslationPipeline extends TranslationPipeline_base { + /** @type {'translation_text'} */ + _key: 'translation_text'; +} +declare const TextGenerationPipeline_base: new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType; +/** + * @typedef {Object} TextGenerationSingle + * @property {string} generated_text The generated text. + * @typedef {TextGenerationSingle[]} TextGenerationOutput + * + * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines. + * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences. + * @typedef {import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams} TextGenerationConfig + * + * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs. + * @param {string|string[]} texts One or several prompts (or one list of prompts) to complete. + * @param {TextGenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An array or object containing the generated texts. + * + * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType + */ +/** + * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. + * This pipeline predicts the words that will follow a specified text prompt. + * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig). + * + * **Example:** Text generation with `Xenova/distilgpt2` (default settings). + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); + * const text = 'I enjoy walking with my cute dog,'; + * const output = await generator(text); + * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }] + * ``` + * + * **Example:** Text generation with `Xenova/distilgpt2` (custom settings). + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); + * const text = 'Once upon a time, there was'; + * const output = await generator(text, { + * temperature: 2, + * max_new_tokens: 10, + * repetition_penalty: 1.5, + * no_repeat_ngram_size: 2, + * num_beams: 2, + * num_return_sequences: 2, + * }); + * // [{ + * // "generated_text": "Once upon a time, there was an abundance of information about the history and activities that" + * // }, { + * // "generated_text": "Once upon a time, there was an abundance of information about the most important and influential" + * // }] + * ``` + * + * **Example:** Run code generation with `Xenova/codegen-350M-mono`. + * ```javascript + * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono'); + * const text = 'def fib(n):'; + * const output = await generator(text, { + * max_new_tokens: 44, + * }); + * // [{ + * // generated_text: 'def fib(n):\n' + + * // ' if n == 0:\n' + + * // ' return 0\n' + + * // ' elif n == 1:\n' + + * // ' return 1\n' + + * // ' else:\n' + + * // ' return fib(n-1) + fib(n-2)\n' + * // }] + * ``` + */ +export class TextGenerationPipeline extends TextGenerationPipeline_base { + _call(texts: string | string[], options?: TextGenerationConfig): Promise; +} +declare const ZeroShotClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType; +/** + * @typedef {Object} ZeroShotClassificationOutput + * @property {string} sequence The sequence for which this is the output. + * @property {string[]} labels The labels sorted by order of likelihood. + * @property {number[]} scores The probabilities for each of the labels. + * + * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines. + * @property {string} [hypothesis_template="This example is {}."] The template used to turn each + * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder. + * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true. + * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence + * is 1. If `true`, the labels are considered independent and probabilities are normalized for each + * candidate by doing a softmax of the entailment score vs. the contradiction score. + * + * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large. + * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into. + * Can be a single label, a string of comma-separated labels, or a list of labels. + * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType + */ +/** + * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` + * trained on NLI (natural language inference) tasks. Equivalent of `text-classification` + * pipelines, but these models don't require a hardcoded number of potential classes, they + * can be chosen at runtime. It usually means it's slower but it is **much** more flexible. + * + * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`. + * ```javascript + * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli'); + * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.'; + * const labels = [ 'mobile', 'billing', 'website', 'account access' ]; + * const output = await classifier(text, labels); + * // { + * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.', + * // labels: [ 'mobile', 'website', 'billing', 'account access' ], + * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ] + * // } + * ``` + * + * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label). + * ```javascript + * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall'); + * const text = 'I have a problem with my iphone that needs to be resolved asap!'; + * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ]; + * const output = await classifier(text, labels, { multi_label: true }); + * // { + * // sequence: 'I have a problem with my iphone that needs to be resolved asap!', + * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ], + * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ] + * // } + * ``` + */ +export class ZeroShotClassificationPipeline extends ZeroShotClassificationPipeline_base { + label2id: { + [k: string]: any; + }; + entailment_id: any; + contradiction_id: any; + _call(texts: string | string[], candidate_labels: string | string[], options?: ZeroShotClassificationPipelineOptions): Promise; +} +declare const FeatureExtractionPipeline_base: new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType; +/** + * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines. + * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use. + * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension. + * + * @callback FeatureExtractionPipelineCallback Extract the features of the input(s). + * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of. + * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction. + * @returns {Promise} The features computed by the model. + * + * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType + */ +/** + * Feature extraction pipeline using no model head. This pipeline extracts the hidden + * states from the base transformer, which can be used as features in downstream tasks. + * + * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization). + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); + * const output = await extractor('This is a simple test.'); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...], + * // dims: [1, 8, 768] + * // } + * ``` + * + * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization). + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); + * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...], + * // dims: [1, 768] + * // } + * ``` + * + * **Example:** Calculating embeddings with `sentence-transformers` models. + * ```javascript + * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2'); + * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); + * // Tensor { + * // type: 'float32', + * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...], + * // dims: [1, 384] + * // } + * ``` + */ +export class FeatureExtractionPipeline extends FeatureExtractionPipeline_base { + _call(texts: string | string[], options?: FeatureExtractionPipelineOptions): Promise; +} +declare const AudioClassificationPipeline_base: new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType; +/** + * @typedef {Object} AudioClassificationSingle + * @property {string} label The label predicted. + * @property {number} score The corresponding probability. + * @typedef {AudioClassificationSingle[]} AudioClassificationOutput + * + * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines. + * @property {number} [topk=null] The number of top labels that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of labels available in the model configuration, + * it will default to the number of labels. + * + * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType + */ +/** + * Audio classification pipeline using any `AutoModelForAudioClassification`. + * This pipeline predicts the class of a raw waveform or an audio file. + * + * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`. + * ```javascript + * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await classifier(url); + * // [ + * // { label: 'male', score: 0.9981542229652405 }, + * // { label: 'female', score: 0.001845747814513743 } + * // ] + * ``` + * + * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results. + * ```javascript + * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'; + * const output = await classifier(url, { topk: 4 }); + * // [ + * // { label: 'Meow', score: 0.5617874264717102 }, + * // { label: 'Cat', score: 0.22365376353263855 }, + * // { label: 'Domestic animals, pets', score: 0.1141069084405899 }, + * // { label: 'Animal', score: 0.08985692262649536 }, + * // ] + * ``` + */ +export class AudioClassificationPipeline extends AudioClassificationPipeline_base { + _call(audio: AudioPipelineInputs, options?: AudioClassificationPipelineOptions): Promise; +} +declare const ZeroShotAudioClassificationPipeline_base: new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType; +/** + * @typedef {Object} ZeroShotAudioClassificationOutput + * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. + * @property {number} score The score attributed by the model for that label (between 0 and 1). + * + * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines. + * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels` + * to attempt the audio classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_audio`. + * + * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs. + * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {string[]} candidate_labels The candidate labels for this audio. + * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification. + * @returns {Promise} An array of objects containing the predicted labels and scores. + * + * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType + */ +/** + * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you + * provide an audio and a set of `candidate_labels`. + * + * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`. + * ```javascript + * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused'); + * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav'; + * const candidate_labels = ['dog', 'vaccum cleaner']; + * const scores = await classifier(audio, candidate_labels); + * // [ + * // { score: 0.9993992447853088, label: 'dog' }, + * // { score: 0.0006007603369653225, label: 'vaccum cleaner' } + * // ] + * ``` + */ +export class ZeroShotAudioClassificationPipeline extends ZeroShotAudioClassificationPipeline_base { + _call(audio: AudioPipelineInputs, candidate_labels: string[], options?: ZeroShotAudioClassificationPipelineOptions): Promise; +} +declare const AutomaticSpeechRecognitionPipeline_base: new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType; +/** + * @typedef {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: number[], token_timestamps?: number[]}} ChunkCallbackItem + * @callback ChunkCallback + * @param {ChunkCallbackItem} chunk The chunk to process. + */ +/** + * @typedef {Object} Chunk + * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds. + * @property {string} text The recognized text. + */ +/** + * @typedef {Object} AutomaticSpeechRecognitionOutput + * @property {string} text The recognized text. + * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list + * containing all the various text chunks identified by the model. + * + * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines. + * @property {boolean|'word'} [kwargs.return_timestamps] Whether to return timestamps or not. Default is `false`. + * @property {number} [kwargs.chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking). + * @property {number} [kwargs.stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`. + * @property {ChunkCallback} [kwargs.chunk_callback] Callback function to be called with each chunk processed. + * @property {boolean} [kwargs.force_full_sequences] Whether to force outputting full sequences or not. Default is `false`. + * @property {string} [kwargs.language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known. + * @property {string} [kwargs.task] The task to perform. Default is `null`, meaning it should be auto-detected. + * @property {number[][]} [kwargs.forced_decoder_ids] A list of pairs of integers which indicates a mapping from generation indices to token indices + * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123. + * @property {number} [num_frames] The number of frames in the input audio. + * @typedef {import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig + * + * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text. + * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either: + * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate + * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. + * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. + * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). + * @param {AutomaticSpeechRecognitionConfig} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`. + * + * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType + */ +/** + * Pipeline that aims at extracting spoken text contained within some audio. + * + * **Example:** Transcribe English. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url); + * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." } + * ``` + * + * **Example:** Transcribe English w/ timestamps. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url, { return_timestamps: true }); + * // { + * // text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." + * // chunks: [ + * // { timestamp: [0, 8], text: " And so my fellow Americans ask not what your country can do for you" } + * // { timestamp: [8, 11], text: " ask what you can do for your country." } + * // ] + * // } + * ``` + * + * **Example:** Transcribe English w/ word-level timestamps. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; + * const output = await transcriber(url, { return_timestamps: 'word' }); + * // { + * // "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.", + * // "chunks": [ + * // { "text": " And", "timestamp": [0, 0.78] }, + * // { "text": " so", "timestamp": [0.78, 1.06] }, + * // { "text": " my", "timestamp": [1.06, 1.46] }, + * // ... + * // { "text": " for", "timestamp": [9.72, 9.92] }, + * // { "text": " your", "timestamp": [9.92, 10.22] }, + * // { "text": " country.", "timestamp": [10.22, 13.5] } + * // ] + * // } + * ``` + * + * **Example:** Transcribe French. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; + * const output = await transcriber(url, { language: 'french', task: 'transcribe' }); + * // { text: " J'adore, j'aime, je n'aime pas, je déteste." } + * ``` + * + * **Example:** Translate French to English. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; + * const output = await transcriber(url, { language: 'french', task: 'translate' }); + * // { text: " I love, I like, I don't like, I hate." } + * ``` + * + * **Example:** Transcribe/translate audio longer than 30 seconds. + * ```javascript + * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav'; + * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 }); + * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" } + * ``` + */ +export class AutomaticSpeechRecognitionPipeline extends AutomaticSpeechRecognitionPipeline_base { + _call(audio: AudioPipelineInputs, options?: AutomaticSpeechRecognitionConfig): Promise; + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + private _call_wav2vec2; + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + private _call_whisper; +} +declare const ImageToTextPipeline_base: new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType; +/** + * @typedef {Object} ImageToTextSingle + * @property {string} generated_text The generated text. + * @typedef {ImageToTextSingle[]} ImageToTextOutput + * + * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} texts The images to be captioned. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object (or array of objects) containing the generated text(s). + * + * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType + */ +/** + * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image. + * + * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`. + * ```javascript + * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await captioner(url); + * // [{ generated_text: 'a cat laying on a couch with another cat' }] + * ``` + * + * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`. + * ```javascript + * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg'; + * const output = await captioner(url); + * // [{ generated_text: 'Mr. Brown commented icily.' }] + * ``` + */ +export class ImageToTextPipeline extends ImageToTextPipeline_base { + _call(texts: ImagePipelineInputs, options?: import('./utils/generation.js').GenerationConfigType): Promise; +} +declare const ImageClassificationPipeline_base: new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType; +/** + * @typedef {Object} ImageClassificationSingle + * @property {string} label The label identified by the model. + * @property {number} score The score attributed by the model for that label. + * @typedef {ImageClassificationSingle[]} ImageClassificationOutput + * + * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines. + * @property {number} [topk=1] The number of top labels that will be returned by the pipeline. + * + * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images(s) to be classified. + * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification. + * @returns {Promise} An array or object containing the predicted labels and scores. + * + * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType + */ +/** + * Image classification pipeline using any `AutoModelForImageClassification`. + * This pipeline predicts the class of an image. + * + * **Example:** Classify an image. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // ] + * ``` + * + * **Example:** Classify an image and return top `n` classes. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, { topk: 3 }); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // { label: 'tiger cat', score: 0.3634825646877289 }, + * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, + * // ] + * ``` + * + * **Example:** Classify an image and return all classes. + * ```javascript + * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, { topk: 0 }); + * // [ + * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, + * // { label: 'tiger cat', score: 0.3634825646877289 }, + * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, + * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 }, + * // ... + * // ] + * ``` + */ +export class ImageClassificationPipeline extends ImageClassificationPipeline_base { + _call(images: ImagePipelineInputs, options?: ImageClassificationPipelineOptions): Promise; +} +declare const ImageSegmentationPipeline_base: new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType; +/** + * @typedef {Object} ImageSegmentationPipelineOutput + * @property {string} label The label of the segment. + * @property {number|null} score The score of the segment. + * @property {RawImage} mask The mask of the segment. + * + * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines. + * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks. + * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. + * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments. + * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`], + * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order). + * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels. + * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes. + * + * @callback ImageSegmentationPipelineCallback Segment the input images. + * @param {ImagePipelineInputs} images The input images. + * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation. + * @returns {Promise} The annotated segments. + * + * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType + */ +/** + * Image segmentation pipeline using any `AutoModelForXXXSegmentation`. + * This pipeline predicts masks of objects and their classes. + * + * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`. + * ```javascript + * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await segmenter(url); + * // [ + * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } }, + * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } } + * // ] + * ``` + */ +export class ImageSegmentationPipeline extends ImageSegmentationPipeline_base { + subtasks_mapping: { + panoptic: string; + instance: string; + semantic: string; + }; + _call(images: ImagePipelineInputs, options?: ImageSegmentationPipelineOptions): Promise; +} +declare const ZeroShotImageClassificationPipeline_base: new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType; +/** + * @typedef {Object} ZeroShotImageClassificationOutput + * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. + * @property {number} score The score attributed by the model for that label (between 0 and 1). + * + * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines. + * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels` + * to attempt the image classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_image`. + * + * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {string[]} candidate_labels The candidate labels for this image. + * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification. + * @returns {Promise} An array of objects containing the predicted labels and scores. + * + * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType + */ +/** + * Zero shot image classification pipeline. This pipeline predicts the class of + * an image when you provide an image and a set of `candidate_labels`. + * + * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`. + * ```javascript + * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; + * const output = await classifier(url, ['tiger', 'horse', 'dog']); + * // [ + * // { score: 0.9993917942047119, label: 'tiger' }, + * // { score: 0.0003519294841680676, label: 'horse' }, + * // { score: 0.0002562698791734874, label: 'dog' } + * // ] + * ``` + */ +export class ZeroShotImageClassificationPipeline extends ZeroShotImageClassificationPipeline_base { + _call(images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotImageClassificationPipelineOptions): Promise; +} +declare const ObjectDetectionPipeline_base: new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType; +/** + * @typedef {Object} ObjectDetectionPipelineSingle + * @property {string} label The class label identified by the model. + * @property {number} score The score attributed by the model for that label. + * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true. + * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput + * + * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines. + * @property {number} [threshold=0.9] The threshold used to filter boxes by score. + * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). + * + * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection. + * @returns {Promise} A list of objects or a list of list of objects. + * + * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType + */ +/** + * Object detection pipeline using any `AutoModelForObjectDetection`. + * This pipeline predicts bounding boxes of objects and their classes. + * + * **Example:** Run object-detection with `Xenova/detr-resnet-50`. + * ```javascript + * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50'); + * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const output = await detector(img, { threshold: 0.9 }); + * // [{ + * // score: 0.9976370930671692, + * // label: "remote", + * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 } + * // }, + * // ... + * // { + * // score: 0.9984092116355896, + * // label: "cat", + * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 } + * // }] + * ``` + */ +export class ObjectDetectionPipeline extends ObjectDetectionPipeline_base { + _call(images: ImagePipelineInputs, options?: ObjectDetectionPipelineOptions): Promise; +} +declare const ZeroShotObjectDetectionPipeline_base: new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType; +/** + * @typedef {Object} ZeroShotObjectDetectionOutput + * @property {string} label Text query corresponding to the found object. + * @property {number} score Score corresponding to the object (between 0 and 1). + * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true. + * + * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines. + * @property {number} [threshold=0.1] The probability necessary to make a prediction. + * @property {number} [topk=null] The number of top predictions that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of predictions available, it will default + * to the number of predictions. + * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). + * + * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The input images. + * @param {string[]} candidate_labels What the model should recognize in the image. + * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection. + * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes. + * + * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType + */ +/** + * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of + * objects when you provide an image and a set of `candidate_labels`. + * + * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`. + * ```javascript + * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png'; + * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag']; + * const output = await detector(url, candidate_labels); + * // [ + * // { + * // score: 0.24392342567443848, + * // label: 'human face', + * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 } + * // }, + * // { + * // score: 0.15129457414150238, + * // label: 'american flag', + * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 } + * // }, + * // { + * // score: 0.13649864494800568, + * // label: 'helmet', + * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 } + * // }, + * // { + * // score: 0.10262022167444229, + * // label: 'rocket', + * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 } + * // } + * // ] + * ``` + * + * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold). + * ```javascript + * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png'; + * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera']; + * const output = await detector(url, candidate_labels, { topk: 4, threshold: 0.05 }); + * // [ + * // { + * // score: 0.1606510728597641, + * // label: 'sunglasses', + * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 } + * // }, + * // { + * // score: 0.08935828506946564, + * // label: 'hat', + * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 } + * // }, + * // { + * // score: 0.08530698716640472, + * // label: 'camera', + * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 } + * // }, + * // { + * // score: 0.08349756896495819, + * // label: 'book', + * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 } + * // } + * // ] + * ``` + */ +export class ZeroShotObjectDetectionPipeline extends ZeroShotObjectDetectionPipeline_base { + _call(images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotObjectDetectionPipelineOptions): Promise; +} +declare const DocumentQuestionAnsweringPipeline_base: new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType; +/** + * @typedef {Object} DocumentQuestionAnsweringSingle + * @property {string} answer The generated text. + * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput + * + * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document. + * @param {ImageInput} image The image of the document to use. + * @param {string} question A question to ask of the document. + * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model. + * @returns {Promise} An object (or array of objects) containing the answer(s). + * + * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType + */ +/** + * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. + * The inputs/outputs are similar to the (extractive) question answering pipeline; however, + * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context. + * + * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`. + * ```javascript + * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa'); + * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; + * const question = 'What is the invoice number?'; + * const output = await qa_pipeline(image, question); + * // [{ answer: 'us-001' }] + * ``` + */ +export class DocumentQuestionAnsweringPipeline extends DocumentQuestionAnsweringPipeline_base { + _call(image: ImageInput, question: string, options?: import('./utils/generation.js').GenerationConfigType): Promise; +} +declare const TextToAudioPipeline_base: new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType; +/** + * @typedef {Object} VocoderOptions + * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder. + * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs + */ +/** + * @typedef {Object} TextToAudioOutput + * @property {Float32Array} audio The generated audio waveform. + * @property {number} sampling_rate The sampling rate of the generated audio waveform. + * + * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines. + * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it). + * + * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs. + * @param {string|string[]} texts The text(s) to generate. + * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method. + * @returns {Promise} An object containing the generated audio and sampling rate. + * + * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType + */ +/** + * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. + * This pipeline generates an audio file from an input text and optional other conditional inputs. + * + * **Example:** Generate audio from text with `Xenova/speecht5_tts`. + * ```javascript + * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false }); + * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin'; + * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings }); + * // { + * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...], + * // sampling_rate: 16000 + * // } + * ``` + * + * You can then save the audio to a .wav file with the `wavefile` package: + * ```javascript + * import wavefile from 'wavefile'; + * import fs from 'fs'; + * + * const wav = new wavefile.WaveFile(); + * wav.fromScratch(1, out.sampling_rate, '32f', out.audio); + * fs.writeFileSync('out.wav', wav.toBuffer()); + * ``` + * + * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107). + * ```javascript + * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra'); + * const out = await synthesizer('Bonjour'); + * // { + * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...], + * // sampling_rate: 16000 + * // } + * ``` + */ +export class TextToAudioPipeline extends TextToAudioPipeline_base { + DEFAULT_VOCODER_ID: string; + vocoder: PreTrainedModel; + _call(texts: string | string[], options: TextToAudioPipelineOptions): Promise; + _call_text_to_waveform(text_inputs: any): Promise<{ + audio: any; + sampling_rate: any; + }>; + _call_text_to_spectrogram(text_inputs: any, { speaker_embeddings }: { + speaker_embeddings: any; + }): Promise<{ + audio: any; + sampling_rate: any; + }>; +} +declare const ImageToImagePipeline_base: new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType; +/** + * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The images to transform. + * @returns {Promise} The transformed image or list of images. + * + * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType + */ +/** + * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input. + * + * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64` + * ```javascript + * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; + * const output = await upscaler(url); + * // RawImage { + * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ], + * // width: 512, + * // height: 512, + * // channels: 3 + * // } + * ``` + */ +export class ImageToImagePipeline extends ImageToImagePipeline_base { + _call(images: ImagePipelineInputs): Promise; +} +declare const DepthEstimationPipeline_base: new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType; +/** + * @typedef {Object} DepthEstimationPipelineOutput + * @property {Tensor} predicted_depth The raw depth map predicted by the model. + * @property {RawImage} depth The processed depth map as an image (with the same size as the input image). + * + * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs. + * @param {ImagePipelineInputs} images The images to compute depth for. + * @returns {Promise} An image or a list of images containing result(s). + * + * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType + */ +/** + * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image. + * + * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas` + * ```javascript + * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas'); + * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; + * const out = await depth_estimator(url); + * // { + * // predicted_depth: Tensor { + * // dims: [ 384, 384 ], + * // type: 'float32', + * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ], + * // size: 147456 + * // }, + * // depth: RawImage { + * // data: Uint8Array(307200) [ 86, 86, 86, ... ], + * // width: 640, + * // height: 480, + * // channels: 1 + * // } + * // } + * ``` + */ +export class DepthEstimationPipeline extends DepthEstimationPipeline_base { + _call(images: ImagePipelineInputs): Promise; +} +export type ImageInput = string | RawImage | URL; +export type ImagePipelineInputs = ImageInput | ImageInput[]; +export type AudioInput = string | URL | Float32Array | Float64Array; +export type AudioPipelineInputs = AudioInput | AudioInput[]; +export type BoundingBox = { + /** + * The minimum x coordinate of the bounding box. + */ + xmin: number; + /** + * The minimum y coordinate of the bounding box. + */ + ymin: number; + /** + * The maximum x coordinate of the bounding box. + */ + xmax: number; + /** + * The maximum y coordinate of the bounding box. + */ + ymax: number; +}; +export type TaskType = keyof typeof SUPPORTED_TASKS; +export type AliasType = keyof typeof TASK_ALIASES; +/** + * All possible pipeline types. + */ +export type PipelineType = TaskType | AliasType; +/** + * A mapping of pipeline names to their corresponding pipeline classes. + */ +export type SupportedTasks = { + "text-classification": TextClassificationPipeline; + "token-classification": TokenClassificationPipeline; + "question-answering": QuestionAnsweringPipeline; + "fill-mask": FillMaskPipeline; + summarization: SummarizationPipeline; + translation: TranslationPipeline; + "text2text-generation": Text2TextGenerationPipeline; + "text-generation": TextGenerationPipeline; + "zero-shot-classification": ZeroShotClassificationPipeline; + "audio-classification": AudioClassificationPipeline; + "zero-shot-audio-classification": ZeroShotAudioClassificationPipeline; + "automatic-speech-recognition": AutomaticSpeechRecognitionPipeline; + "text-to-audio": TextToAudioPipeline; + "image-to-text": ImageToTextPipeline; + "image-classification": ImageClassificationPipeline; + "image-segmentation": ImageSegmentationPipeline; + "zero-shot-image-classification": ZeroShotImageClassificationPipeline; + "object-detection": ObjectDetectionPipeline; + "zero-shot-object-detection": ZeroShotObjectDetectionPipeline; + "document-question-answering": DocumentQuestionAnsweringPipeline; + "image-to-image": ImageToImagePipeline; + "depth-estimation": DepthEstimationPipeline; + "feature-extraction": FeatureExtractionPipeline; +}; +/** + * A mapping from pipeline aliases to their corresponding pipeline classes. + */ +export type AliasTasks = { + "sentiment-analysis": TextClassificationPipeline; + ner: TokenClassificationPipeline; + asr: AutomaticSpeechRecognitionPipeline; + "text-to-speech": TextToAudioPipeline; + embeddings: FeatureExtractionPipeline; +}; +/** + * A mapping from all pipeline names and aliases to their corresponding pipeline classes. + */ +export type AllTasks = SupportedTasks & AliasTasks; +/** + * Disposes the item. + */ +export type DisposeType = () => Promise; +export type Disposable = { + /** + * A promise that resolves when the pipeline has been disposed. + */ + dispose: DisposeType; +}; +export type ModelTokenizerConstructorArgs = { + /** + * The task of the pipeline. Useful for specifying subtasks. + */ + task: string; + /** + * The model used by the pipeline. + */ + model: PreTrainedModel; + /** + * The tokenizer used by the pipeline. + */ + tokenizer: PreTrainedTokenizer; +}; +/** + * An object used to instantiate a text-based pipeline. + */ +export type TextPipelineConstructorArgs = ModelTokenizerConstructorArgs; +export type ModelProcessorConstructorArgs = { + /** + * The task of the pipeline. Useful for specifying subtasks. + */ + task: string; + /** + * The model used by the pipeline. + */ + model: PreTrainedModel; + /** + * The processor used by the pipeline. + */ + processor: Processor; +}; +/** + * An object used to instantiate an audio-based pipeline. + */ +export type AudioPipelineConstructorArgs = ModelProcessorConstructorArgs; +/** + * An object used to instantiate an image-based pipeline. + */ +export type ImagePipelineConstructorArgs = ModelProcessorConstructorArgs; +export type ModelTokenizerProcessorConstructorArgs = { + /** + * The task of the pipeline. Useful for specifying subtasks. + */ + task: string; + /** + * The model used by the pipeline. + */ + model: PreTrainedModel; + /** + * The tokenizer used by the pipeline. + */ + tokenizer: PreTrainedTokenizer; + /** + * The processor used by the pipeline. + */ + processor: Processor; +}; +/** + * An object used to instantiate a text- and audio-based pipeline. + */ +export type TextAudioPipelineConstructorArgs = ModelTokenizerProcessorConstructorArgs; +/** + * An object used to instantiate a text- and image-based pipeline. + */ +export type TextImagePipelineConstructorArgs = ModelTokenizerProcessorConstructorArgs; +export type TextClassificationSingle = { + /** + * The label predicted. + */ + label: string; + /** + * The corresponding probability. + */ + score: number; +}; +export type TextClassificationOutput = TextClassificationSingle[]; +/** + * Parameters specific to text classification pipelines. + */ +export type TextClassificationPipelineOptions = { + /** + * The number of top predictions to be returned. + */ + topk?: number; +}; +/** + * Classify the text(s) given as inputs. + */ +export type TextClassificationPipelineCallback = (texts: string | string[], options?: TextClassificationPipelineOptions) => Promise; +export type TextClassificationPipelineType = TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable; +export type TokenClassificationSingle = { + /** + * The token/word classified. This is obtained by decoding the selected tokens. + */ + word: string; + /** + * The corresponding probability for `entity`. + */ + score: number; + /** + * The entity predicted for that token/word. + */ + entity: string; + /** + * The index of the corresponding token in the sentence. + */ + index: number; + /** + * The index of the start of the corresponding entity in the sentence. + */ + start?: number; + /** + * The index of the end of the corresponding entity in the sentence. + */ + end?: number; +}; +export type TokenClassificationOutput = TokenClassificationSingle[]; +/** + * Parameters specific to token classification pipelines. + */ +export type TokenClassificationPipelineOptions = { + /** + * A list of labels to ignore. + */ + ignore_labels?: string[]; +}; +/** + * Classify each token of the text(s) given as inputs. + */ +export type TokenClassificationPipelineCallback = (texts: string | string[], options?: TokenClassificationPipelineOptions) => Promise; +export type TokenClassificationPipelineType = TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable; +export type QuestionAnsweringOutput = { + /** + * The probability associated to the answer. + */ + score: number; + /** + * The character start index of the answer (in the tokenized version of the input). + */ + start?: number; + /** + * The character end index of the answer (in the tokenized version of the input). + */ + end?: number; + /** + * The answer to the question. + */ + answer: string; +}; +/** + * Parameters specific to question answering pipelines. + */ +export type QuestionAnsweringPipelineOptions = { + /** + * The number of top answer predictions to be returned. + */ + topk?: number; +}; +/** + * Answer the question(s) given as inputs by using the context(s). + */ +export type QuestionAnsweringPipelineCallback = (question: string | string[], context: string | string[], options?: QuestionAnsweringPipelineOptions) => Promise; +export type QuestionAnsweringPipelineType = TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable; +export type FillMaskSingle = { + /** + * The corresponding input with the mask token prediction. + */ + sequence: string; + /** + * The corresponding probability. + */ + score: number; + /** + * The predicted token id (to replace the masked one). + */ + token: number; + /** + * The predicted token (to replace the masked one). + */ + token_str: string; +}; +export type FillMaskOutput = FillMaskSingle[]; +/** + * Parameters specific to fill mask pipelines. + */ +export type FillMaskPipelineOptions = { + /** + * When passed, overrides the number of predictions to return. + */ + topk?: number; +}; +/** + * Fill the masked token in the text(s) given as inputs. + */ +export type FillMaskPipelineCallback = (texts: string | string[], options?: FillMaskPipelineOptions) => Promise; +export type FillMaskPipelineType = TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable; +export type Text2TextGenerationSingle = { + /** + * The generated text. + */ + generated_text: string; +}; +export type Text2TextGenerationOutput = Text2TextGenerationSingle[]; +/** + * Generate the output text(s) using text(s) given as inputs. + */ +export type Text2TextGenerationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise; +export type Text2TextGenerationPipelineType = TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable; +export type SummarizationSingle = { + /** + * The summary text. + */ + summary_text: string; +}; +export type SummarizationOutput = SummarizationSingle[]; +/** + * Summarize the text(s) given as inputs. + */ +export type SummarizationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise; +export type SummarizationPipelineType = TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable; +export type TranslationSingle = { + /** + * The translated text. + */ + translation_text: string; +}; +export type TranslationOutput = TranslationSingle[]; +/** + * Translate the text(s) given as inputs. + */ +export type TranslationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise; +export type TranslationPipelineType = TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable; +export type TextGenerationSingle = { + /** + * The generated text. + */ + generated_text: string; +}; +export type TextGenerationOutput = TextGenerationSingle[]; +/** + * Parameters specific to text-generation pipelines. + */ +export type TextGenerationSpecificParams = { + /** + * Whether or not to add special tokens when tokenizing the sequences. + */ + add_special_tokens?: boolean; +}; +export type TextGenerationConfig = import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams; +/** + * Complete the prompt(s) given as inputs. + */ +export type TextGenerationPipelineCallback = (texts: string | string[], options?: TextGenerationConfig) => Promise; +export type TextGenerationPipelineType = TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable; +export type ZeroShotClassificationOutput = { + /** + * The sequence for which this is the output. + */ + sequence: string; + /** + * The labels sorted by order of likelihood. + */ + labels: string[]; + /** + * The probabilities for each of the labels. + */ + scores: number[]; +}; +/** + * Parameters specific to zero-shot classification pipelines. + */ +export type ZeroShotClassificationPipelineOptions = { + /** + * The template used to turn each + * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder. + */ + hypothesis_template?: string; + /** + * Whether or not multiple candidate labels can be true. + * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence + * is 1. If `true`, the labels are considered independent and probabilities are normalized for each + * candidate by doing a softmax of the entailment score vs. the contradiction score. + */ + multi_label?: boolean; +}; +/** + * Classify the sequence(s) given as inputs. + */ +export type ZeroShotClassificationPipelineCallback = (texts: string | string[], candidate_labels: string | string[], options?: ZeroShotClassificationPipelineOptions) => Promise; +export type ZeroShotClassificationPipelineType = TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable; +/** + * Parameters specific to feature extraction pipelines. + */ +export type FeatureExtractionPipelineOptions = { + /** + * The pooling method to use. + */ + pooling?: 'none' | 'mean' | 'cls'; + /** + * Whether or not to normalize the embeddings in the last dimension. + */ + normalize?: boolean; +}; +/** + * Extract the features of the input(s). + */ +export type FeatureExtractionPipelineCallback = (texts: string | string[], options?: FeatureExtractionPipelineOptions) => Promise; +export type FeatureExtractionPipelineType = TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable; +export type AudioClassificationSingle = { + /** + * The label predicted. + */ + label: string; + /** + * The corresponding probability. + */ + score: number; +}; +export type AudioClassificationOutput = AudioClassificationSingle[]; +/** + * Parameters specific to audio classification pipelines. + */ +export type AudioClassificationPipelineOptions = { + /** + * The number of top labels that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of labels available in the model configuration, + * it will default to the number of labels. + */ + topk?: number; +}; +/** + * Classify the sequence(s) given as inputs. + */ +export type AudioClassificationPipelineCallback = (audio: AudioPipelineInputs, options?: AudioClassificationPipelineOptions) => Promise; +export type AudioClassificationPipelineType = AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable; +export type ZeroShotAudioClassificationOutput = { + /** + * The label identified by the model. It is one of the suggested `candidate_label`. + */ + label: string; + /** + * The score attributed by the model for that label (between 0 and 1). + */ + score: number; +}; +/** + * Parameters specific to zero-shot audio classification pipelines. + */ +export type ZeroShotAudioClassificationPipelineOptions = { + /** + * The sentence used in conjunction with `candidate_labels` + * to attempt the audio classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_audio`. + */ + hypothesis_template?: string; +}; +/** + * Classify the sequence(s) given as inputs. + */ +export type ZeroShotAudioClassificationPipelineCallback = (audio: AudioPipelineInputs, candidate_labels: string[], options?: ZeroShotAudioClassificationPipelineOptions) => Promise; +export type ZeroShotAudioClassificationPipelineType = TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable; +export type ChunkCallbackItem = { + stride: number[]; + input_features: Tensor; + is_last: boolean; + tokens?: number[]; + token_timestamps?: number[]; +}; +export type ChunkCallback = (chunk: ChunkCallbackItem) => any; +export type Chunk = { + /** + * The start and end timestamp of the chunk in seconds. + */ + timestamp: [number, number]; + /** + * The recognized text. + */ + text: string; +}; +export type AutomaticSpeechRecognitionOutput = { + /** + * The recognized text. + */ + text: string; + /** + * When using `return_timestamps`, the `chunks` will become a list + * containing all the various text chunks identified by the model. + */ + chunks?: Chunk[]; +}; +/** + * Parameters specific to automatic-speech-recognition pipelines. + */ +export type AutomaticSpeechRecognitionSpecificParams = { + /** + * Whether to return timestamps or not. Default is `false`. + */ + return_timestamps?: boolean | 'word'; + /** + * The length of audio chunks to process in seconds. Default is 0 (no chunking). + */ + chunk_length_s?: number; + /** + * The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`. + */ + stride_length_s?: number; + /** + * Callback function to be called with each chunk processed. + */ + chunk_callback?: ChunkCallback; + /** + * Whether to force outputting full sequences or not. Default is `false`. + */ + force_full_sequences?: boolean; + /** + * The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known. + */ + language?: string; + /** + * The task to perform. Default is `null`, meaning it should be auto-detected. + */ + task?: string; + /** + * A list of pairs of integers which indicates a mapping from generation indices to token indices + * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123. + */ + forced_decoder_ids?: number[][]; + /** + * The number of frames in the input audio. + */ + num_frames?: number; +}; +export type AutomaticSpeechRecognitionConfig = import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams; +/** + * Transcribe the audio sequence(s) given as inputs to text. + */ +export type AutomaticSpeechRecognitionPipelineCallback = (audio: AudioPipelineInputs, options?: AutomaticSpeechRecognitionConfig) => Promise; +export type AutomaticSpeechRecognitionPipelineType = TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable; +export type ImageToTextSingle = { + /** + * The generated text. + */ + generated_text: string; +}; +export type ImageToTextOutput = ImageToTextSingle[]; +/** + * Assign labels to the image(s) passed as inputs. + */ +export type ImageToTextPipelineCallback = (texts: ImagePipelineInputs, options?: import('./utils/generation.js').GenerationConfigType) => Promise; +export type ImageToTextPipelineType = TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable; +export type ImageClassificationSingle = { + /** + * The label identified by the model. + */ + label: string; + /** + * The score attributed by the model for that label. + */ + score: number; +}; +export type ImageClassificationOutput = ImageClassificationSingle[]; +/** + * Parameters specific to image classification pipelines. + */ +export type ImageClassificationPipelineOptions = { + /** + * The number of top labels that will be returned by the pipeline. + */ + topk?: number; +}; +/** + * Assign labels to the image(s) passed as inputs. + */ +export type ImageClassificationPipelineCallback = (images: ImagePipelineInputs, options?: ImageClassificationPipelineOptions) => Promise; +export type ImageClassificationPipelineType = ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable; +export type ImageSegmentationPipelineOutput = { + /** + * The label of the segment. + */ + label: string; + /** + * The score of the segment. + */ + score: number | null; + /** + * The mask of the segment. + */ + mask: RawImage; +}; +/** + * Parameters specific to image segmentation pipelines. + */ +export type ImageSegmentationPipelineOptions = { + /** + * Probability threshold to filter out predicted masks. + */ + threshold?: number; + /** + * Threshold to use when turning the predicted masks into binary values. + */ + mask_threshold?: number; + /** + * Mask overlap threshold to eliminate small, disconnected segments. + */ + overlap_mask_area_threshold?: number; + /** + * Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`], + * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order). + */ + subtask?: null | string; + /** + * List of label ids to fuse. If not set, do not fuse any labels. + */ + label_ids_to_fuse?: number[]; + /** + * List of target sizes for the input images. If not set, use the original image sizes. + */ + target_sizes?: number[][]; +}; +/** + * Segment the input images. + */ +export type ImageSegmentationPipelineCallback = (images: ImagePipelineInputs, options?: ImageSegmentationPipelineOptions) => Promise; +export type ImageSegmentationPipelineType = ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable; +export type ZeroShotImageClassificationOutput = { + /** + * The label identified by the model. It is one of the suggested `candidate_label`. + */ + label: string; + /** + * The score attributed by the model for that label (between 0 and 1). + */ + score: number; +}; +/** + * Parameters specific to zero-shot image classification pipelines. + */ +export type ZeroShotImageClassificationPipelineOptions = { + /** + * The sentence used in conjunction with `candidate_labels` + * to attempt the image classification by replacing the placeholder with the candidate_labels. + * Then likelihood is estimated by using `logits_per_image`. + */ + hypothesis_template?: string; +}; +/** + * Assign labels to the image(s) passed as inputs. + */ +export type ZeroShotImageClassificationPipelineCallback = (images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotImageClassificationPipelineOptions) => Promise; +export type ZeroShotImageClassificationPipelineType = TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable; +export type ObjectDetectionPipelineSingle = { + /** + * The class label identified by the model. + */ + label: string; + /** + * The score attributed by the model for that label. + */ + score: number; + /** + * The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true. + */ + box: BoundingBox; +}; +export type ObjectDetectionPipelineOutput = ObjectDetectionPipelineSingle[]; +/** + * Parameters specific to object detection pipelines. + */ +export type ObjectDetectionPipelineOptions = { + /** + * The threshold used to filter boxes by score. + */ + threshold?: number; + /** + * Whether to return the boxes coordinates in percentage (true) or in pixels (false). + */ + percentage?: boolean; +}; +/** + * Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + */ +export type ObjectDetectionPipelineCallback = (images: ImagePipelineInputs, options?: ObjectDetectionPipelineOptions) => Promise; +export type ObjectDetectionPipelineType = ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable; +export type ZeroShotObjectDetectionOutput = { + /** + * Text query corresponding to the found object. + */ + label: string; + /** + * Score corresponding to the object (between 0 and 1). + */ + score: number; + /** + * Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true. + */ + box: BoundingBox; +}; +/** + * Parameters specific to zero-shot object detection pipelines. + */ +export type ZeroShotObjectDetectionPipelineOptions = { + /** + * The probability necessary to make a prediction. + */ + threshold?: number; + /** + * The number of top predictions that will be returned by the pipeline. + * If the provided number is `null` or higher than the number of predictions available, it will default + * to the number of predictions. + */ + topk?: number; + /** + * Whether to return the boxes coordinates in percentage (true) or in pixels (false). + */ + percentage?: boolean; +}; +/** + * Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + */ +export type ZeroShotObjectDetectionPipelineCallback = (images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotObjectDetectionPipelineOptions) => Promise; +export type ZeroShotObjectDetectionPipelineType = TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable; +export type DocumentQuestionAnsweringSingle = { + /** + * The generated text. + */ + answer: string; +}; +export type DocumentQuestionAnsweringOutput = DocumentQuestionAnsweringSingle[]; +/** + * Answer the question given as input by using the document. + */ +export type DocumentQuestionAnsweringPipelineCallback = (image: ImageInput, question: string, options?: import('./utils/generation.js').GenerationConfigType) => Promise; +export type DocumentQuestionAnsweringPipelineType = TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable; +export type VocoderOptions = { + /** + * The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder. + */ + vocoder?: PreTrainedModel; +}; +export type TextToAudioPipelineConstructorArgs = TextAudioPipelineConstructorArgs & VocoderOptions; +export type TextToAudioOutput = { + /** + * The generated audio waveform. + */ + audio: Float32Array; + /** + * The sampling rate of the generated audio waveform. + */ + sampling_rate: number; +}; +/** + * Parameters specific to text-to-audio pipelines. + */ +export type TextToAudioPipelineOptions = { + /** + * The speaker embeddings (if the model requires it). + */ + speaker_embeddings?: Tensor | Float32Array | string | URL; +}; +/** + * Generates speech/audio from the inputs. + */ +export type TextToAudioPipelineCallback = (texts: string | string[], options: TextToAudioPipelineOptions) => Promise; +export type TextToAudioPipelineType = TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable; +/** + * Transform the image(s) passed as inputs. + */ +export type ImageToImagePipelineCallback = (images: ImagePipelineInputs) => Promise; +export type ImageToImagePipelineType = ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable; +export type DepthEstimationPipelineOutput = { + /** + * The raw depth map predicted by the model. + */ + predicted_depth: Tensor; + /** + * The processed depth map as an image (with the same size as the input image). + */ + depth: RawImage; +}; +/** + * Predicts the depth for the image(s) passed as inputs. + */ +export type DepthEstimationPipelineCallback = (images: ImagePipelineInputs) => Promise; +export type DepthEstimationPipelineType = ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable; +import { PreTrainedModel } from './models.js'; +import { PreTrainedTokenizer } from './tokenizers.js'; +import { Processor } from './processors.js'; +import { Tensor } from './utils/tensor.js'; +import { RawImage } from './utils/image.js'; +declare const SUPPORTED_TASKS: Readonly<{ + "text-classification": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof TextClassificationPipeline; + model: typeof AutoModelForSequenceClassification; + default: { + model: string; + }; + type: string; + }; + "token-classification": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof TokenClassificationPipeline; + model: typeof AutoModelForTokenClassification; + default: { + model: string; + }; + type: string; + }; + "question-answering": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof QuestionAnsweringPipeline; + model: typeof AutoModelForQuestionAnswering; + default: { + model: string; + }; + type: string; + }; + "fill-mask": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof FillMaskPipeline; + model: typeof AutoModelForMaskedLM; + default: { + model: string; + }; + type: string; + }; + summarization: { + tokenizer: typeof AutoTokenizer; + pipeline: typeof SummarizationPipeline; + model: typeof AutoModelForSeq2SeqLM; + default: { + model: string; + }; + type: string; + }; + translation: { + tokenizer: typeof AutoTokenizer; + pipeline: typeof TranslationPipeline; + model: typeof AutoModelForSeq2SeqLM; + default: { + model: string; + }; + type: string; + }; + "text2text-generation": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof Text2TextGenerationPipeline; + model: typeof AutoModelForSeq2SeqLM; + default: { + model: string; + }; + type: string; + }; + "text-generation": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof TextGenerationPipeline; + model: typeof AutoModelForCausalLM; + default: { + model: string; + }; + type: string; + }; + "zero-shot-classification": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof ZeroShotClassificationPipeline; + model: typeof AutoModelForSequenceClassification; + default: { + model: string; + }; + type: string; + }; + "audio-classification": { + pipeline: typeof AudioClassificationPipeline; + model: typeof AutoModelForAudioClassification; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "zero-shot-audio-classification": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof ZeroShotAudioClassificationPipeline; + model: typeof AutoModel; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "automatic-speech-recognition": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof AutomaticSpeechRecognitionPipeline; + model: (typeof AutoModelForSpeechSeq2Seq)[]; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "text-to-audio": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof TextToAudioPipeline; + model: (typeof AutoModelForTextToSpectrogram | typeof AutoModelForTextToWaveform)[]; + processor: (typeof AutoProcessor)[]; + default: { + model: string; + }; + type: string; + }; + "image-to-text": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof ImageToTextPipeline; + model: typeof AutoModelForVision2Seq; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "image-classification": { + pipeline: typeof ImageClassificationPipeline; + model: typeof AutoModelForImageClassification; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "image-segmentation": { + pipeline: typeof ImageSegmentationPipeline; + model: (typeof AutoModelForImageSegmentation)[]; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "zero-shot-image-classification": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof ZeroShotImageClassificationPipeline; + model: typeof AutoModel; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "object-detection": { + pipeline: typeof ObjectDetectionPipeline; + model: typeof AutoModelForObjectDetection; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "zero-shot-object-detection": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof ZeroShotObjectDetectionPipeline; + model: typeof AutoModelForZeroShotObjectDetection; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "document-question-answering": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof DocumentQuestionAnsweringPipeline; + model: typeof AutoModelForDocumentQuestionAnswering; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "image-to-image": { + pipeline: typeof ImageToImagePipeline; + model: typeof AutoModelForImageToImage; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "depth-estimation": { + pipeline: typeof DepthEstimationPipeline; + model: typeof AutoModelForDepthEstimation; + processor: typeof AutoProcessor; + default: { + model: string; + }; + type: string; + }; + "feature-extraction": { + tokenizer: typeof AutoTokenizer; + pipeline: typeof FeatureExtractionPipeline; + model: typeof AutoModel; + default: { + model: string; + }; + type: string; + }; +}>; +declare const TASK_ALIASES: Readonly<{ + "sentiment-analysis": "text-classification"; + ner: "token-classification"; + asr: "automatic-speech-recognition"; + "text-to-speech": "text-to-audio"; + embeddings: "feature-extraction"; +}>; +import { AutoTokenizer } from './tokenizers.js'; +import { AutoModelForSequenceClassification } from './models.js'; +import { AutoModelForTokenClassification } from './models.js'; +import { AutoModelForQuestionAnswering } from './models.js'; +import { AutoModelForMaskedLM } from './models.js'; +import { AutoModelForSeq2SeqLM } from './models.js'; +import { AutoModelForCausalLM } from './models.js'; +import { AutoModelForAudioClassification } from './models.js'; +import { AutoProcessor } from './processors.js'; +import { AutoModel } from './models.js'; +import { AutoModelForSpeechSeq2Seq } from './models.js'; +import { AutoModelForTextToSpectrogram } from './models.js'; +import { AutoModelForTextToWaveform } from './models.js'; +import { AutoModelForVision2Seq } from './models.js'; +import { AutoModelForImageClassification } from './models.js'; +import { AutoModelForImageSegmentation } from './models.js'; +import { AutoModelForObjectDetection } from './models.js'; +import { AutoModelForZeroShotObjectDetection } from './models.js'; +import { AutoModelForDocumentQuestionAnswering } from './models.js'; +import { AutoModelForImageToImage } from './models.js'; +import { AutoModelForDepthEstimation } from './models.js'; +export {}; +//# sourceMappingURL=pipelines.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts.map new file mode 100644 index 000000000..a128b8cc3 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/pipelines.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pipelines.d.ts","sourceRoot":"","sources":["../src/pipelines.js"],"names":[],"mappings":"AAu5FA;;;;;;;GAOG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,kEALW,MAAM,qFACN,OAAO,gBAAgB,EAAE,iBAAiB,wBA6DpD;;;;;AAz2FD;;;;;;GAMG;AAEH;;;;GAIG;AACH;IACI;;;;;;;OAOG;IACH;QAL4B,IAAI,GAArB,MAAM;QACoB,KAAK,GAA/B,eAAe;QACe,SAAS,GAAvC,mBAAmB;QACC,SAAS,GAA7B,SAAS;OAQnB;IAJG,aAAgB;IAChB,uBAAkB;IAClB,+BAA0B;IAC1B,qBAA0B;IA1B/B,WACU,QAAQ,IAAI,CAAC,CAEvB;CA8BF;6DAuFyE,2BAA2B,KAAK,8BAA8B;AArFxI;;;;;;;GAOG;AAEH;;;;;;;;GAQG;AAGH;;;;;;;;;GASG;AAEH;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH;IA7CG,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,iCAAiC,GAC/B,QAAQ,2BAAyB,0BAA0B,CAAC,CAEtE;CA0FF;8DAoD0E,2BAA2B,KAAK,+BAA+B;AAlD1I;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH;IArCG,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,kCAAkC,GAChC,QAAQ,4BAA0B,2BAA2B,CAAC,CAExE;CAsGF;4DAoCwE,2BAA2B,KAAK,6BAA6B;AAlCtI;;;;;;;;;;;;;;;;;GAiBG;AAEH;;;;;;;;;;;;;;GAcG;AACH;IAxBG,gBACQ,MAAM,GAAC,MAAM,EAAE,WACf,MAAM,GAAC,MAAM,EAAE,YACf,gCAAgC,GAC9B,QAAQ,uBAAuB,GAAC,uBAAuB,EAAE,CAAC,CAEpE;CAgFF;mDAgD+D,2BAA2B,KAAK,oBAAoB;AA7CpH;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH;IAlCG,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,uBAAuB,GACrB,QAAQ,iBAAe,gBAAgB,CAAC,CAGlD;CAgFF;8DA4B0E,2BAA2B,KAAK,+BAA+B;AAzB1I;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;GAWG;AACH;IACI,+BAA+B;IAC/B,MADW,gBAAgB,CACH;IAtBzB,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,OAAO,uBAAuB,EAAE,oBAAoB,GAClD,QAAQ,4BAA0B,2BAA2B,CAAC,CAExE;CAwEF;wDAoCoE,2BAA2B,KAAK,yBAAyB;AAjC9H;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH;IACI,6BAA6B;IAC7B,MADW,cAAc,CACH;CASzB;sDA6DkE,2BAA2B,KAAK,uBAAuB;AA1D1H;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH;IACI,iCAAiC;IACjC,MADW,kBAAkB,CACH;CAS7B;yDAsEqE,2BAA2B,KAAK,0BAA0B;AAnEhI;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH;IA1DG,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,oBAAoB,GAClB,QAAQ,uBAAqB,sBAAsB,CAAC,CAE9D;CAoGF;iEA0D6E,2BAA2B,KAAK,kCAAkC;AAxDhJ;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH;IASQ;;MAIC;IAED,mBAAgD;IAMhD,sBAAyF;IA/D9F,aACQ,MAAM,GAAC,MAAM,EAAE,oBACf,MAAM,GAAC,MAAM,EAAE,YAEf,qCAAqC,GACnC,QAAQ,4BAA4B,GAAC,4BAA4B,EAAE,CAAC,CAE9E;CAgIF;4DAoDwE,2BAA2B,KAAK,6BAA6B;AAlDtI;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH;IA7CG,aACQ,MAAM,GAAC,MAAM,EAAE,YACf,gCAAgC,GAC9B,QAAQ,MAAM,CAAC,CAEzB;CAuFF;8DAyD0E,4BAA4B,KAAK,+BAA+B;AAnD3I;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH;IAxCG,aACQ,mBAAmB,YAKnB,kCAAkC,GAChC,QAAQ,4BAA0B,2BAA2B,CAAC,CAExE;CA0EF;sEAyCkF,gCAAgC,KAAK,uCAAuC;AAvC/J;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;;;;;;;;;GAeG;AACH;IA7BG,aACQ,mBAAmB,oBAKnB,MAAM,EAAE,YACR,0CAA0C,GACxC,QAAQ,iCAAiC,EAAE,GAAC,iCAAiC,EAAE,EAAE,CAAC,CAE5F;CAsEF;qEAiHiF,gCAAgC,KAAK,sCAAsC;AA/G7J;;;;GAIG;AAEH;;;;GAIG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AACH;IAhFG,aACQ,mBAAmB,YAKnB,gCAAgC,GAC9B,QAAQ,gCAAgC,GAAC,gCAAgC,EAAE,CAAC,CAEtF;IA8FC;;;OAGG;IACH,uBAgCC;IAED;;;OAGG;IACH,sBAsHC;CACJ;sDAkCkE,gCAAgC,KAAK,uBAAuB;AAhC/H;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH;IA3BG,aACQ,mBAAmB,YACnB,OAAO,uBAAuB,EAAE,oBAAoB,GAClD,QAAQ,oBAAkB,mBAAmB,CAAC,CAExD;CAoDF;8DA2D0E,4BAA4B,KAAK,+BAA+B;AAzD3I;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH;IAhDG,cACQ,mBAAmB,YACnB,kCAAkC,GAChC,QAAQ,4BAA0B,2BAA2B,CAAC,CAExE;CAmFF;4DAwCwE,4BAA4B,KAAK,6BAA6B;AAtCvI;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;;;;;;;;GAcG;AACH;IAQQ;;;;MAKC;IApCN,cACQ,mBAAmB,YACnB,gCAAgC,GAC9B,QAAQ,+BAA+B,EAAE,CAAC,CAEpD;CA8HF;sEAqCkF,gCAAgC,KAAK,uCAAuC;AAnC/J;;;;;;;;;;;;;;;;;GAiBG;AAEH;;;;;;;;;;;;;;;GAeG;AACH;IAzBG,cACQ,mBAAmB,oBACnB,MAAM,EAAE,YACR,0CAA0C,GACxC,QAAQ,iCAAiC,EAAE,GAAC,iCAAiC,EAAE,EAAE,CAAC,CAE5F;CA0EF;0DA4CsE,4BAA4B,KAAK,2BAA2B;AAzCnI;;;;;;;;;;;;;;;;;GAiBG;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH;IA9BG,cACQ,mBAAmB,YACnB,8BAA8B,GAC5B,QAAQ,gCAA8B,+BAA+B,CAAC,CAEhF;CAuEF;kEAyF8E,gCAAgC,KAAK,mCAAmC;AAtFvJ;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AACH;IAzEG,cACQ,mBAAmB,oBACnB,MAAM,EAAE,YACR,sCAAsC,GACpC,QAAQ,6BAA6B,EAAE,GAAC,6BAA6B,EAAE,EAAE,CAAC,CAEpF;CA2HF;oEA8BgF,gCAAgC,KAAK,qCAAqC;AA5B3J;;;;;;;;;;;;GAYG;AAEH;;;;;;;;;;;;;GAaG;AACH;IAvBG,aACQ,UAAU,YACV,MAAM,YACN,OAAO,uBAAuB,EAAE,oBAAoB,GAClD,QAAQ,kCAAgC,iCAAiC,CAAC,CAEpF;CAiEF;sDA4DkE,kCAAkC,KAAK,uBAAuB;AAzDjI;;;;GAIG;AAEH;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH;IACI,2BAA8C;IAU1C,yBAAsC;IAtD3C,aACQ,MAAM,GAAC,MAAM,EAAE,WACf,0BAA0B,GACxB,QAAQ,iBAAiB,CAAC,CAEpC;IAkEC;;;OAgBC;IAED;;;;;OAyCC;CACJ;uDA0BmE,4BAA4B,KAAK,wBAAwB;AAxB7H;;;;;;GAMG;AAEH;;;;;;;;;;;;;;;GAeG;AACH;IAvBG,cACQ,mBAAmB,GACjB,QAAQ,QAAQ,GAAC,QAAQ,EAAE,CAAC,CAEtC;CA4CF;0DAsCsE,4BAA4B,KAAK,2BAA2B;AApCnI;;;;;;;;;;GAUG;AAEH;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH;IA/BG,cACQ,mBAAmB,GACjB,QAAQ,6BAA6B,GAAC,6BAA6B,EAAE,CAAC,CAEhF;CAwDF;yBA5iFY,MAAM,GAAG,QAAQ,GAAG,GAAG;kCACvB,UAAU,GAAC,UAAU,EAAE;yBAmBvB,MAAM,GAAG,GAAG,GAAG,YAAY,GAAG,YAAY;kCAC1C,UAAU,GAAC,UAAU,EAAE;;;;;UA2BtB,MAAM;;;;UACN,MAAM;;;;UACN,MAAM;;;;UACN,MAAM;;uBA4xFP,MAAM,sBAAsB;wBAC5B,MAAM,mBAAmB;;;;2BACzB,QAAQ,GAAG,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAGpB,cAAc,GAAG,UAAU;;;;gCA3wF3B,QAAQ,IAAI,CAAC;;;;;aAGZ,WAAW;;;;;;UAiCX,MAAM;;;;WACN,eAAe;;;;eACf,mBAAmB;;;;;0CAEpB,6BAA6B;;;;;UAK5B,MAAM;;;;WACN,eAAe;;;;eACf,SAAS;;;;;2CAEV,6BAA6B;;;;2CAC7B,6BAA6B;;;;;UAM5B,MAAM;;;;WACN,eAAe;;;;eACf,mBAAmB;;;;eACnB,SAAS;;;;;+CAEV,sCAAsC;;;;+CACtC,sCAAsC;;;;;WAKrC,MAAM;;;;WACN,MAAM;;uCACP,wBAAwB,EAAE;;;;;;;;WAGzB,MAAM;;;;;yDAGT,MAAM,GAAC,MAAM,EAAE,YACf,iCAAiC,KAC/B,QAAQ,2BAAyB,0BAA0B,CAAC;6CAE5D,2BAA2B,GAAG,kCAAkC,GAAG,UAAU;;;;;UA8F5E,MAAM;;;;WACN,MAAM;;;;YACN,MAAM;;;;WACN,MAAM;;;;YACN,MAAM;;;;UACN,MAAM;;wCACP,yBAAyB,EAAE;;;;;;;;oBAG1B,MAAM,EAAE;;;;;0DAGX,MAAM,GAAC,MAAM,EAAE,YACf,kCAAkC,KAChC,QAAQ,4BAA0B,2BAA2B,CAAC;8CAE9D,2BAA2B,GAAG,mCAAmC,GAAG,UAAU;;;;;WA0G7E,MAAM;;;;YACN,MAAM;;;;UACN,MAAM;;;;YACN,MAAM;;;;;;;;;WAGN,MAAM;;;;;2DAGT,MAAM,GAAC,MAAM,EAAE,WACf,MAAM,GAAC,MAAM,EAAE,YACf,gCAAgC,KAC9B,QAAQ,uBAAuB,GAAC,uBAAuB,EAAE,CAAC;4CAE1D,2BAA2B,GAAG,iCAAiC,GAAG,UAAU;;;;;cAqF3E,MAAM;;;;WACN,MAAM;;;;WACN,MAAM;;;;eACN,MAAM;;6BACP,cAAc,EAAE;;;;;;;;WAGf,MAAM;;;;;+CAGT,MAAM,GAAC,MAAM,EAAE,YACf,uBAAuB,KACrB,QAAQ,iBAAe,gBAAgB,CAAC;mCAKxC,2BAA2B,GAAG,wBAAwB,GAAG,UAAU;;;;;oBAmFlE,MAAM;;wCACP,yBAAyB,EAAE;;;;0DAG7B,MAAM,GAAC,MAAM,EAAE,YACf,OAAO,uBAAuB,EAAE,oBAAoB,KAClD,QAAQ,4BAA0B,2BAA2B,CAAC;8CAE9D,2BAA2B,GAAG,mCAAmC,GAAG,UAAU;;;;;kBA6E7E,MAAM;;kCACP,mBAAmB,EAAE;;;;oDAGvB,MAAM,GAAC,MAAM,EAAE,YACf,OAAO,uBAAuB,EAAE,oBAAoB,KAClD,QAAQ,sBAAoB,qBAAqB,CAAC;wCAElD,2BAA2B,GAAG,6BAA6B,GAAG,UAAU;;;;;sBAuCvE,MAAM;;gCACP,iBAAiB,EAAE;;;;kDAGrB,MAAM,GAAC,MAAM,EAAE,YACf,OAAO,uBAAuB,EAAE,oBAAoB,KAClD,QAAQ,oBAAkB,mBAAmB,CAAC;sCAE9C,2BAA2B,GAAG,2BAA2B,GAAG,UAAU;;;;;oBAgErE,MAAM;;mCACP,oBAAoB,EAAE;;;;;;;;yBAGrB,OAAO;;mCACR,OAAO,uBAAuB,EAAE,oBAAoB,GAAG,4BAA4B;;;;qDAGrF,MAAM,GAAC,MAAM,EAAE,YACf,oBAAoB,KAClB,QAAQ,uBAAqB,sBAAsB,CAAC;yCAEpD,2BAA2B,GAAG,8BAA8B,GAAG,UAAU;;;;;cAwGxE,MAAM;;;;YACN,MAAM,EAAE;;;;YACR,MAAM,EAAE;;;;;;;;;;0BAGR,MAAM;;;;;;;kBAEN,OAAO;;;;;6DAMV,MAAM,GAAC,MAAM,EAAE,oBACf,MAAM,GAAC,MAAM,EAAE,YAEf,qCAAqC,KACnC,QAAQ,4BAA4B,GAAC,4BAA4B,EAAE,CAAC;iDAEpE,2BAA2B,GAAG,sCAAsC,GAAG,UAAU;;;;;;;;cAoIhF,MAAM,GAAC,MAAM,GAAC,KAAK;;;;gBACnB,OAAO;;;;;wDAGV,MAAM,GAAC,MAAM,EAAE,YACf,gCAAgC,KAC9B,QAAQ,MAAM,CAAC;4CAEf,2BAA2B,GAAG,iCAAiC,GAAG,UAAU;;;;;WA+F3E,MAAM;;;;WACN,MAAM;;wCACP,yBAAyB,EAAE;;;;;;;;;;WAG1B,MAAM;;;;;0DAKT,mBAAmB,YAKnB,kCAAkC,KAChC,QAAQ,4BAA0B,2BAA2B,CAAC;8CAE9D,4BAA4B,GAAG,mCAAmC,GAAG,UAAU;;;;;WA8E9E,MAAM;;;;WACN,MAAM;;;;;;;;;;;0BAGN,MAAM;;;;;kEAKT,mBAAmB,oBAKnB,MAAM,EAAE,YACR,0CAA0C,KACxC,QAAQ,iCAAiC,EAAE,GAAC,iCAAiC,EAAE,EAAE,CAAC;sDAElF,gCAAgC,GAAG,2CAA2C,GAAG,UAAU;gCAyE3F;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAA;CAAC;oCAE9G,iBAAiB;;;;;eAKd,CAAC,MAAM,EAAE,MAAM,CAAC;;;;UAChB,MAAM;;;;;;UAKN,MAAM;;;;;aACN,KAAK,EAAE;;;;;;;;;wBAIP,OAAO,GAAC,MAAM;;;;qBACd,MAAM;;;;sBACN,MAAM;;;;qBACN,aAAa;;;;2BACb,OAAO;;;;eACP,MAAM;;;;WACN,MAAM;;;;;yBACN,MAAM,EAAE,EAAE;;;;iBAEV,MAAM;;+CACP,OAAO,uBAAuB,EAAE,oBAAoB,GAAG,wCAAwC;;;;iEAGjG,mBAAmB,YAKnB,gCAAgC,KAC9B,QAAQ,gCAAgC,GAAC,gCAAgC,EAAE,CAAC;qDAE5E,gCAAgC,GAAG,0CAA0C,GAAG,UAAU;;;;;oBAmQzF,MAAM;;gCACP,iBAAiB,EAAE;;;;kDAGrB,mBAAmB,YACnB,OAAO,uBAAuB,EAAE,oBAAoB,KAClD,QAAQ,oBAAkB,mBAAmB,CAAC;sCAE9C,gCAAgC,GAAG,2BAA2B,GAAG,UAAU;;;;;WAwD1E,MAAM;;;;WACN,MAAM;;wCACP,yBAAyB,EAAE;;;;;;;;WAG1B,MAAM;;;;;2DAGT,mBAAmB,YACnB,kCAAkC,KAChC,QAAQ,4BAA0B,2BAA2B,CAAC;8CAE9D,4BAA4B,GAAG,mCAAmC,GAAG,UAAU;;;;;WAuF9E,MAAM;;;;WACN,MAAM,GAAC,IAAI;;;;UACX,QAAQ;;;;;;;;;gBAGR,MAAM;;;;qBACN,MAAM;;;;kCACN,MAAM;;;;;cACN,IAAI,GAAC,MAAM;;;;wBAEX,MAAM,EAAE;;;;mBACR,MAAM,EAAE,EAAE;;;;;yDAGb,mBAAmB,YACnB,gCAAgC,KAC9B,QAAQ,+BAA+B,EAAE,CAAC;4CAE1C,4BAA4B,GAAG,iCAAiC,GAAG,UAAU;;;;;WAkI5E,MAAM;;;;WACN,MAAM;;;;;;;;;;;0BAGN,MAAM;;;;;mEAKT,mBAAmB,oBACnB,MAAM,EAAE,YACR,0CAA0C,KACxC,QAAQ,iCAAiC,EAAE,GAAC,iCAAiC,EAAE,EAAE,CAAC;sDAElF,gCAAgC,GAAG,2CAA2C,GAAG,UAAU;;;;;WA+E1F,MAAM;;;;WACN,MAAM;;;;SACN,WAAW;;4CACZ,6BAA6B,EAAE;;;;;;;;gBAG9B,MAAM;;;;iBACN,OAAO;;;;;uDAGV,mBAAmB,YACnB,8BAA8B,KAC5B,QAAQ,gCAA8B,+BAA+B,CAAC;0CAEtE,4BAA4B,GAAG,+BAA+B,GAAG,UAAU;;;;;WA4E1E,MAAM;;;;WACN,MAAM;;;;SACN,WAAW;;;;;;;;;gBAGX,MAAM;;;;;;WACN,MAAM;;;;iBAGN,OAAO;;;;;+DAGV,mBAAmB,oBACnB,MAAM,EAAE,YACR,sCAAsC,KACpC,QAAQ,6BAA6B,EAAE,GAAC,6BAA6B,EAAE,EAAE,CAAC;kDAE1E,gCAAgC,GAAG,uCAAuC,GAAG,UAAU;;;;;YA+HtF,MAAM;;8CACP,+BAA+B,EAAE;;;;gEAGnC,UAAU,YACV,MAAM,YACN,OAAO,uBAAuB,EAAE,oBAAoB,KAClD,QAAQ,kCAAgC,iCAAiC,CAAC;oDAE1E,gCAAgC,GAAG,yCAAyC,GAAG,UAAU;;;;;cAsExF,eAAe;;iDAChB,gCAAgC,GAAG,cAAc;;;;;WAKhD,YAAY;;;;mBACZ,MAAM;;;;;;;;;yBAGN,MAAM,GAAC,YAAY,GAAC,MAAM,GAAC,GAAG;;;;;kDAGjC,MAAM,GAAC,MAAM,EAAE,WACf,0BAA0B,KACxB,QAAQ,iBAAiB,CAAC;sCAE1B,kCAAkC,GAAG,2BAA2B,GAAG,UAAU;;;;oDAkI/E,mBAAmB,KACjB,QAAQ,QAAQ,GAAC,QAAQ,EAAE,CAAC;uCAE5B,4BAA4B,GAAG,4BAA4B,GAAG,UAAU;;;;;qBAgDvE,MAAM;;;;WACN,QAAQ;;;;;uDAGX,mBAAmB,KACjB,QAAQ,6BAA6B,GAAC,6BAA6B,EAAE,CAAC;0CAEtE,4BAA4B,GAAG,+BAA+B,GAAG,UAAU;gCAnhFjF,aAAa;oCAxBb,iBAAiB;0BA4BjB,iBAAiB;uBAsBjB,mBAAmB;yBACD,kBAAkB;AAkjF3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiRE;AAIF;;;;;;GASG;8BAn4FI,iBAAiB;mDAwBjB,aAAa;gDAAb,aAAa;8CAAb,aAAa;qCAAb,aAAa;sCAAb,aAAa;qCAAb,aAAa;gDAAb,aAAa;8BAIb,iBAAiB;0BAJjB,aAAa;0CAAb,aAAa;8CAAb,aAAa;2CAAb,aAAa;uCAAb,aAAa;gDAAb,aAAa;8CAAb,aAAa;4CAAb,aAAa;oDAAb,aAAa;sDAAb,aAAa;yCAAb,aAAa;4CAAb,aAAa"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts b/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts new file mode 100644 index 000000000..b604b1244 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts @@ -0,0 +1,715 @@ +declare const FeatureExtractor_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * Base class for feature extractors. + * + * @extends Callable + */ +export class FeatureExtractor extends FeatureExtractor_base { + /** + * Constructs a new FeatureExtractor instance. + * + * @param {Object} config The configuration for the feature extractor. + */ + constructor(config: any); + config: any; +} +/** + * @typedef {object} ImageFeatureExtractorResult + * @property {Tensor} pixel_values The pixel values of the batched preprocessed images. + * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]]. + * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]]. + */ +/** + * Feature extractor for image models. + * + * @extends FeatureExtractor + */ +export class ImageFeatureExtractor extends FeatureExtractor { + /** + * Constructs a new ImageFeatureExtractor instance. + * + * @param {Object} config The configuration for the feature extractor. + * @param {number[]} config.image_mean The mean values for image normalization. + * @param {number[]} config.image_std The standard deviation values for image normalization. + * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range. + * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values. + * @param {boolean} config.do_normalize Whether to normalize the image pixel values. + * @param {boolean} config.do_resize Whether to resize the image. + * @param {number} config.resample What method to use for resampling. + * @param {number} config.size The size to resize the image to. + */ + constructor(config: { + image_mean: number[]; + image_std: number[]; + do_rescale: boolean; + rescale_factor: number; + do_normalize: boolean; + do_resize: boolean; + resample: number; + size: number; + }); + image_mean: any; + image_std: any; + resample: any; + do_rescale: any; + rescale_factor: any; + do_normalize: any; + do_resize: any; + do_thumbnail: any; + size: any; + size_divisibility: any; + do_center_crop: any; + crop_size: any; + do_convert_rgb: any; + do_crop_margin: any; + pad_size: any; + do_pad: any; + /** + * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any + * corresponding dimension of the specified size. + * @param {RawImage} image The image to be resized. + * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. + * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. + * @returns {Promise} The resized image. + */ + thumbnail(image: RawImage, size: { + height: number; + width: number; + }, resample?: string | 0 | 1 | 2 | 3 | 4 | 5): Promise; + /** + * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). + * @param {RawImage} image The image to be cropped. + * @param {number} gray_threshold Value below which pixels are considered to be gray. + * @returns {Promise} The cropped image. + */ + crop_margin(image: RawImage, gray_threshold?: number): Promise; + /** + * Pad the image by a certain amount. + * @param {Float32Array} pixelData The pixel data to pad. + * @param {number[]} imgDims The dimensions of the image. + * @param {{width:number; height:number}|number} padSize The dimensions of the padded image. + * @param {Object} options The options for padding. + * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. + * @param {boolean} [options.center=false] Whether to center the image. + * @param {number} [options.constant_values=0] The constant value to use for padding. + * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. + */ + pad_image(pixelData: Float32Array, imgDims: number[], padSize: { + width: number; + height: number; + } | number, { mode, center, constant_values, }?: { + mode?: 'constant' | 'symmetric'; + center?: boolean; + constant_values?: number; + }): [Float32Array, number[]]; + /** + * Rescale the image' pixel values by `this.rescale_factor`. + * @param {Float32Array} pixelData The pixel data to rescale. + * @returns {void} + */ + rescale(pixelData: Float32Array): void; + /** + * Find the target (width, height) dimension of the output image after + * resizing given the input image and the desired size. + * @param {RawImage} image The image to resize. + * @param {any} size The size to use for resizing the image. + * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. + */ + get_resize_output_image_size(image: RawImage, size: any): [number, number]; + /** + * Resizes the image. + * @param {RawImage} image The image to resize. + * @returns {Promise} The resized image. + */ + resize(image: RawImage): Promise; + /** + * @typedef {object} PreprocessedImage + * @property {HeightWidth} original_size The original size of the image. + * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. + * @property {Tensor} pixel_values The pixel values of the preprocessed image. + */ + /** + * Preprocesses the given image. + * + * @param {RawImage} image The image to preprocess. + * @param {Object} overrides The overrides for the preprocessing options. + * @returns {Promise} The preprocessed image. + */ + preprocess(image: RawImage, { do_normalize, do_pad, do_convert_rgb, do_convert_grayscale, }?: any): Promise<{ + /** + * The original size of the image. + */ + original_size: HeightWidth; + /** + * The reshaped input size of the image. + */ + reshaped_input_size: HeightWidth; + /** + * The pixel values of the preprocessed image. + */ + pixel_values: Tensor; + }>; + /** + * Calls the feature extraction process on an array of images, + * preprocesses each image, and concatenates the resulting + * features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. + */ + _call(images: RawImage[], ...args: any[]): Promise; +} +export class SegformerFeatureExtractor extends ImageFeatureExtractor { + /** + * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps. + * @param {*} outputs Raw outputs of the model. + * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size + * (height, width) of each prediction. If unset, predictions will not be resized. + * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps. + */ + post_process_semantic_segmentation(outputs: any, target_sizes?: number[][]): { + segmentation: Tensor; + labels: number[]; + }[]; +} +export class BitImageProcessor extends ImageFeatureExtractor { +} +export class DPTFeatureExtractor extends ImageFeatureExtractor { +} +export class GLPNFeatureExtractor extends ImageFeatureExtractor { +} +export class CLIPFeatureExtractor extends ImageFeatureExtractor { +} +export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { +} +export class SiglipImageProcessor extends ImageFeatureExtractor { +} +export class ConvNextFeatureExtractor extends ImageFeatureExtractor { + constructor(config: any); + /** + * Percentage of the image to crop. Only has an effect if this.size < 384. + */ + crop_pct: any; + resize(image: any): Promise; +} +export class ConvNextImageProcessor extends ConvNextFeatureExtractor { +} +export class ViTFeatureExtractor extends ImageFeatureExtractor { +} +export class ViTImageProcessor extends ImageFeatureExtractor { +} +export class MobileViTFeatureExtractor extends ImageFeatureExtractor { +} +export class OwlViTFeatureExtractor extends ImageFeatureExtractor { + /** + * Post-processes the outputs of the model (for object detection). + * @param {Object} outputs The outputs of the model that must be post-processed + * @param {Tensor} outputs.logits The logits + * @param {Tensor} outputs.pred_boxes The predicted boxes. + * @param {number} [threshold=0.5] The threshold to use for the scores. + * @param {number[][]} [target_sizes=null] The sizes of the original images. + * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed. + * @return {Object[]} An array of objects containing the post-processed outputs. + * @private + */ + post_process_object_detection(outputs: { + logits: Tensor; + pred_boxes: Tensor; + }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[]; +} +export class DeiTFeatureExtractor extends ImageFeatureExtractor { +} +export class BeitFeatureExtractor extends ImageFeatureExtractor { +} +export class DonutFeatureExtractor extends ImageFeatureExtractor { + pad_image(pixelData: any, imgDims: any, padSize: any, options?: {}): [Float32Array, number[]]; +} +export class NougatImageProcessor extends DonutFeatureExtractor { +} +/** + * @typedef {object} DetrFeatureExtractorResultProps + * @property {Tensor} pixel_mask + * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult + */ +/** + * Detr Feature Extractor. + * + * @extends ImageFeatureExtractor + */ +export class DetrFeatureExtractor extends ImageFeatureExtractor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + _call(images: RawImage[]): Promise; + /** + * Post-processes the outputs of the model (for object detection). + * @param {Object} outputs The outputs of the model that must be post-processed + * @param {Tensor} outputs.logits The logits + * @param {Tensor} outputs.pred_boxes The predicted boxes. + * @param {number} [threshold=0.5] The threshold to use for the scores. + * @param {number[][]} [target_sizes=null] The sizes of the original images. + * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed. + * @return {Object[]} An array of objects containing the post-processed outputs. + * @private + */ + post_process_object_detection(outputs: { + logits: Tensor; + pred_boxes: Tensor; + }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[]; + /** + * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. + * @param {Tensor} class_logits The class logits. + * @param {Tensor} mask_logits The mask logits. + * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks. + * @param {number} num_labels The number of labels. + * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels. + */ + remove_low_and_no_objects(class_logits: Tensor, mask_logits: Tensor, object_mask_threshold: number, num_labels: number): [Tensor[], number[], number[]]; + /** + * Checks whether the segment is valid or not. + * @param {Int32Array} mask_labels Labels for each pixel in the mask. + * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks. + * @param {number} k The class id of the segment. + * @param {number} mask_threshold The mask threshold. + * @param {number} overlap_mask_area_threshold The overlap mask area threshold. + * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels. + */ + check_segment_validity(mask_labels: Int32Array, mask_probs: Tensor[], k: number, mask_threshold?: number, overlap_mask_area_threshold?: number): [boolean, number[]]; + /** + * Computes the segments. + * @param {Tensor[]} mask_probs The mask probabilities. + * @param {number[]} pred_scores The predicted scores. + * @param {number[]} pred_labels The predicted labels. + * @param {number} mask_threshold The mask threshold. + * @param {number} overlap_mask_area_threshold The overlap mask area threshold. + * @param {Set} label_ids_to_fuse The label ids to fuse. + * @param {number[]} target_size The target size of the image. + * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments. + */ + compute_segments(mask_probs: Tensor[], pred_scores: number[], pred_labels: number[], mask_threshold: number, overlap_mask_area_threshold: number, label_ids_to_fuse?: Set, target_size?: number[]): [Tensor, Array<{ + id: number; + label_id: number; + score: number; + }>]; + /** + * Post-process the model output to generate the final panoptic segmentation. + * @param {*} outputs The model output to post process + * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. + * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. + * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask. + * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together. + * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to. + * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} + */ + post_process_panoptic_segmentation(outputs: any, threshold?: number, mask_threshold?: number, overlap_mask_area_threshold?: number, label_ids_to_fuse?: Set, target_sizes?: number[][]): Array<{ + segmentation: Tensor; + segments_info: Array<{ + id: number; + label_id: number; + score: number; + }>; + }>; + post_process_instance_segmentation(): void; +} +export class YolosFeatureExtractor extends ImageFeatureExtractor { + /** + * Post-processes the outputs of the model (for object detection). + * @param {Object} outputs The outputs of the model that must be post-processed + * @param {Tensor} outputs.logits The logits + * @param {Tensor} outputs.pred_boxes The predicted boxes. + * @param {number} [threshold=0.5] The threshold to use for the scores. + * @param {number[][]} [target_sizes=null] The sizes of the original images. + * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed. + * @return {Object[]} An array of objects containing the post-processed outputs. + * @private + */ + post_process_object_detection(outputs: { + logits: Tensor; + pred_boxes: Tensor; + }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[]; +} +/** + * @typedef {object} SamImageProcessorResult + * @property {Tensor} pixel_values + * @property {HeightWidth[]} original_sizes + * @property {HeightWidth[]} reshaped_input_sizes + * @property {Tensor} [input_points] + * @property {Tensor} [input_labels] + */ +export class SamImageProcessor extends ImageFeatureExtractor { + /** + * + * @param {any} input_points + * @param {HeightWidth[]} original_sizes + * @param {HeightWidth[]} reshaped_input_sizes + * @returns {Tensor} + */ + reshape_input_points(input_points: any, original_sizes: HeightWidth[], reshaped_input_sizes: HeightWidth[]): Tensor; + /** + * + * @param {any} input_labels + * @param {Tensor} input_points + * @returns {Tensor} + */ + add_input_labels(input_labels: any, input_points: Tensor): Tensor; + /** + * @param {any[]} images The URL(s) of the image(s) to extract features from. + * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user. + * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. + * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. + * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. + * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. + * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. + * @returns {Promise} + */ + _call(images: any[], input_points?: any, input_labels?: any): Promise; + /** + * Remove padding and upscale masks to the original image size. + * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. + * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. + * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. + * @param {Object} options Optional parameters for post-processing. + * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. + * @param {boolean} [options.binarize] Whether to binarize the masks. + * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. + * @param {number} [options.pad_size.height] The height the images were padded to. + * @param {number} [options.pad_size.width] The width the images were padded to. + * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. + */ + post_process_masks(masks: Tensor, original_sizes: number[][], reshaped_input_sizes: number[][], { mask_threshold, binarize, pad_size, }?: { + mask_threshold?: number; + binarize?: boolean; + pad_size?: { + height?: number; + width?: number; + }; + }): Tensor[]; +} +export class Swin2SRImageProcessor extends ImageFeatureExtractor { + pad_image(pixelData: any, imgDims: any, padSize: any, options?: {}): [Float32Array, number[]]; +} +export class VitMatteImageProcessor extends ImageFeatureExtractor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @param {RawImage[]} trimaps The trimaps(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + _call(images: RawImage[], trimaps: RawImage[]): Promise; +} +export class WhisperFeatureExtractor extends FeatureExtractor { + constructor(config: any); + window: Float64Array; + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform: Float32Array | Float64Array): { + data: Float32Array; + dims: number[]; + }; + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + _call(audio: Float32Array | Float64Array): Promise<{ + input_features: Tensor; + }>; +} +export class Wav2Vec2FeatureExtractor extends FeatureExtractor { + /** + * @param {Float32Array} input_values + * @returns {Float32Array} + */ + _zero_mean_unit_var_norm(input_values: Float32Array): Float32Array; + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. + */ + _call(audio: Float32Array | Float64Array): Promise<{ + input_values: Tensor; + attention_mask: Tensor; + }>; +} +export class ASTFeatureExtractor extends FeatureExtractor { + constructor(config: any); + mel_filters: number[][]; + window: Float64Array; + mean: any; + std: any; + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform: Float32Array | Float64Array, max_length: number): { + data: Float32Array; + dims: number[]; + }; + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + _call(audio: Float32Array | Float64Array): Promise<{ + input_values: Tensor; + }>; +} +export class ClapFeatureExtractor extends FeatureExtractor { + constructor(config: any); + mel_filters: number[][]; + mel_filters_slaney: number[][]; + window: Float64Array; + /** + * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. + * + * Four different path are possible: + * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram + * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram + * are then stacked together. They will later be used for `feature_fusion`. + * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is + * padded based on `padding`. + * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded + * based on `padding`, and is repeated `4` times. + * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel + * spectrogram will be computed on a random crop of the waveform. + * + * @param {Float32Array|Float64Array} waveform The input waveform. + * @param {number} max_length The maximum length of the waveform. + * @param {string} truncation The truncation strategy to use. + * @param {string} padding The padding strategy to use. + * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. + */ + _get_input_mel(waveform: Float32Array | Float64Array, max_length: number, truncation: string, padding: string): { + data: Float32Array; + dims: number[]; + longer: boolean; + }; + /** + * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. + * In CLAP, two different filter banks are used depending on the truncation pattern: + * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from + * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` + * is set to `"fusion"`. + * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used + * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original + * implementation when the truncation mode is not `"fusion"`. + * + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number[][]} mel_filters The mel filters to use. + * @param {number} [max_length=null] The maximum number of frames to return. + * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + _extract_fbank_features(waveform: Float32Array | Float64Array, mel_filters: number[][], max_length?: number): { + data: Float32Array; + dims: number[]; + }; + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + _call(audio: Float32Array | Float64Array, { max_length, }?: { + max_length?: any; + }): Promise<{ + input_features: Tensor; + }>; +} +export class SpeechT5FeatureExtractor extends FeatureExtractor { +} +declare const Processor_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * Represents a Processor that extracts features from an input. + * @extends Callable + */ +export class Processor extends Processor_base { + /** + * Creates a new Processor with the given feature extractor. + * @param {FeatureExtractor} feature_extractor The function used to extract features from the input. + */ + constructor(feature_extractor: FeatureExtractor); + feature_extractor: FeatureExtractor; + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + _call(input: any, ...args: any[]): Promise; +} +export class SamProcessor extends Processor { + /** + * @borrows SamImageProcessor#_call as _call + */ + _call(...args: any[]): Promise; + /** + * @borrows SamImageProcessor#post_process_masks as post_process_masks + */ + post_process_masks(...args: any[]): any; + /** + * @borrows SamImageProcessor#reshape_input_points as reshape_input_points + */ + reshape_input_points(...args: any[]): any; +} +/** + * Represents a WhisperProcessor that extracts features from an audio input. + * @extends Processor + */ +export class WhisperProcessor extends Processor { + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + _call(audio: any): Promise; +} +export class Wav2Vec2ProcessorWithLM extends Processor { + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + _call(audio: any): Promise; +} +export class SpeechT5Processor extends Processor { + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + _call(input: any): Promise; +} +export class OwlViTProcessor extends Processor { +} +/** + * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function. + * The chosen processor class is determined by the type specified in the processor config. + * + * **Example:** Load a processor using `from_pretrained`. + * ```javascript + * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en'); + * ``` + * + * **Example:** Run an image through a processor. + * ```javascript + * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * let image_inputs = await processor(image); + * // { + * // "pixel_values": { + * // "dims": [ 1, 3, 224, 224 ], + * // "type": "float32", + * // "data": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ], + * // "size": 150528 + * // }, + * // "original_sizes": [ + * // [ 533, 800 ] + * // ], + * // "reshaped_input_sizes": [ + * // [ 224, 224 ] + * // ] + * // } + * ``` + */ +export class AutoProcessor { + static FEATURE_EXTRACTOR_CLASS_MAPPING: { + WhisperFeatureExtractor: typeof WhisperFeatureExtractor; + ViTFeatureExtractor: typeof ViTFeatureExtractor; + MobileViTFeatureExtractor: typeof MobileViTFeatureExtractor; + OwlViTFeatureExtractor: typeof OwlViTFeatureExtractor; + CLIPFeatureExtractor: typeof CLIPFeatureExtractor; + ChineseCLIPFeatureExtractor: typeof ChineseCLIPFeatureExtractor; + SiglipImageProcessor: typeof SiglipImageProcessor; + ConvNextFeatureExtractor: typeof ConvNextFeatureExtractor; + ConvNextImageProcessor: typeof ConvNextImageProcessor; + SegformerFeatureExtractor: typeof SegformerFeatureExtractor; + BitImageProcessor: typeof BitImageProcessor; + DPTFeatureExtractor: typeof DPTFeatureExtractor; + GLPNFeatureExtractor: typeof GLPNFeatureExtractor; + BeitFeatureExtractor: typeof BeitFeatureExtractor; + DeiTFeatureExtractor: typeof DeiTFeatureExtractor; + DetrFeatureExtractor: typeof DetrFeatureExtractor; + YolosFeatureExtractor: typeof YolosFeatureExtractor; + DonutFeatureExtractor: typeof DonutFeatureExtractor; + NougatImageProcessor: typeof NougatImageProcessor; + ViTImageProcessor: typeof ViTImageProcessor; + VitMatteImageProcessor: typeof VitMatteImageProcessor; + SamImageProcessor: typeof SamImageProcessor; + Swin2SRImageProcessor: typeof Swin2SRImageProcessor; + Wav2Vec2FeatureExtractor: typeof Wav2Vec2FeatureExtractor; + SpeechT5FeatureExtractor: typeof SpeechT5FeatureExtractor; + ASTFeatureExtractor: typeof ASTFeatureExtractor; + ClapFeatureExtractor: typeof ClapFeatureExtractor; + }; + static PROCESSOR_CLASS_MAPPING: { + WhisperProcessor: typeof WhisperProcessor; + Wav2Vec2ProcessorWithLM: typeof Wav2Vec2ProcessorWithLM; + SamProcessor: typeof SamProcessor; + SpeechT5Processor: typeof SpeechT5Processor; + OwlViTProcessor: typeof OwlViTProcessor; + }; + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new instance of the Processor class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import('./utils/hub.js').PretrainedOptions): Promise; +} +/** + * Named tuple to indicate the order we are using is (height x width), even though + * the Graphics’ industry standard is (width x height). + */ +export type HeightWidth = [height: number, width: number]; +export type ImageFeatureExtractorResult = { + /** + * The pixel values of the batched preprocessed images. + */ + pixel_values: Tensor; + /** + * Array of two-dimensional tuples like [[480, 640]]. + */ + original_sizes: HeightWidth[]; + /** + * Array of two-dimensional tuples like [[1000, 1330]]. + */ + reshaped_input_sizes: HeightWidth[]; +}; +export type DetrFeatureExtractorResultProps = { + pixel_mask: Tensor; +}; +export type DetrFeatureExtractorResult = ImageFeatureExtractorResult & DetrFeatureExtractorResultProps; +export type SamImageProcessorResult = { + pixel_values: Tensor; + original_sizes: HeightWidth[]; + reshaped_input_sizes: HeightWidth[]; + input_points?: Tensor; + input_labels?: Tensor; +}; +import { RawImage } from './utils/image.js'; +import { Tensor } from './utils/tensor.js'; +export {}; +//# sourceMappingURL=processors.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts.map new file mode 100644 index 000000000..15d6e0394 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/processors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"processors.d.ts","sourceRoot":"","sources":["../src/processors.js"],"names":[],"mappings":";;;;AAsKA;;;;GAIG;AACH;IACI;;;;OAIG;IACH,yBAGC;IADG,YAAoB;CAE3B;AAED;;;;;GAKG;AAEH;;;;GAIG;AACH;IAEI;;;;;;;;;;;;OAYG;IACH;QAT4B,UAAU,EAA3B,MAAM,EAAE;QACS,SAAS,EAA1B,MAAM,EAAE;QACQ,UAAU,EAA1B,OAAO;QACQ,cAAc,EAA7B,MAAM;QACU,YAAY,EAA5B,OAAO;QACS,SAAS,EAAzB,OAAO;QACQ,QAAQ,EAAvB,MAAM;QACS,IAAI,EAAnB,MAAM;OA+BhB;IA1BG,gBAA4D;IAC5D,eAAyD;IAEzD,cAAyC;IACzC,gBAAgD;IAChD,oBAA6D;IAC7D,kBAA4C;IAE5C,eAAsC;IACtC,kBAA4C;IAC5C,UAA4B;IAC5B,uBAAkF;IAElF,oBAAgD;IAChD,eAAsC;IACtC,oBAAwD;IACxD,oBAAgD;IAEhD,cAAoC;IACpC,YAAgC;IASpC;;;;;;;OAOG;IACH,iBALW,QAAQ;gBACA,MAAM;eAAQ,MAAM;kBAC5B,MAAM,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAC5B,QAAQ,QAAQ,CAAC,CAsB7B;IAGD;;;;;OAKG;IACH,mBAJW,QAAQ,mBACR,MAAM,GACJ,QAAQ,QAAQ,CAAC,CAgC7B;IAED;;;;;;;;;;OAUG;IACH,qBATW,YAAY,WACZ,MAAM,EAAE,WACR;QAAC,KAAK,EAAC,MAAM,CAAC;QAAC,MAAM,EAAC,MAAM,CAAA;KAAC,GAAC,MAAM;QAEH,IAAI,GAArC,UAAU,GAAC,WAAW;QACJ,MAAM,GAAxB,OAAO;QACU,eAAe,GAAhC,MAAM;QACJ,CAAC,YAAY,EAAE,MAAM,EAAE,CAAC,CA6EpC;IAED;;;;OAIG;IACH,mBAHW,YAAY,GACV,IAAI,CAMhB;IAED;;;;;;OAMG;IACH,oCAJW,QAAQ,QACR,GAAG,GACD,CAAC,MAAM,EAAE,MAAM,CAAC,CA+D5B;IAED;;;;OAIG;IACH,cAHW,QAAQ,GACN,QAAQ,QAAQ,CAAC,CAO7B;IAED;;;;;OAKG;IAEH;;;;;;OAMG;IACH,kBAJW,QAAQ;;;;;;;;;;;;sBANL,MAAM;OA4GnB;IAED;;;;;;;OAOG;IACH,cAJW,QAAQ,EAAE,WACP,GAAG,KACJ,QAAQ,2BAA2B,CAAC,CAqBhD;CAEJ;AAED;IAEI;;;;;;OAMG;IACH,gEAJW,MAAM,EAAE,EAAE,GAER;QAAC,YAAY,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAC,EAAE,CAwDtD;CACJ;AACD;CAAgE;AAChE;CAAkE;AAClE;CAAmE;AACnE;CAAmE;AACnE;CAA0E;AAC1E;CAAmE;AACnE;IACI,yBAOC;IAJG;;OAEG;IACH,cAAmD;IAGvD,iCA4BC;CACJ;AACD;CAAwE;AACxE;CAAkE;AAClE;CAAgE;AAEhE;CAAwE;AACxE;IA/qBA;;;;;;;;;;OAUG;IACH;;;qFAmEC;CAsmBA;AACD;CAAmE;AACnE;CAAmE;AACnE;IACI,8FAuBC;CACJ;AACD;CAAmE;AAEnE;;;;GAIG;AAEH;;;;GAIG;AACH;IACI;;;;;OAKG;IACH,cAHW,QAAQ,EAAE,GACR,QAAQ,0BAA0B,CAAC,CAgB/C;IAnvBL;;;;;;;;;;OAUG;IACH;;;qFAmEC;IAorBG;;;;;;;OAOG;IACH,wCANW,MAAM,eACN,MAAM,yBACN,MAAM,cACN,MAAM,GACJ,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CA6B1C;IAED;;;;;;;;OAQG;IACH,oCAPW,UAAU,cACV,MAAM,EAAE,KACR,MAAM,mBACN,MAAM,gCACN,MAAM,GACJ,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC,CAmC/B;IAED;;;;;;;;;;OAUG;IACH,6BATW,MAAM,EAAE,eACR,MAAM,EAAE,eACR,MAAM,EAAE,kBACR,MAAM,+BACN,MAAM,sBACN,IAAI,MAAM,CAAC,gBACX,MAAM,EAAE,GACN,CAAC,MAAM,EAAE,MAAM;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAC,CAAC,CAAC,CAkG1E;IAED;;;;;;;;;OASG;IACH,6DAPW,MAAM,mBACN,MAAM,gCACN,MAAM,sBACN,IAAI,MAAM,CAAC,iBACX,MAAM,EAAE,EAAE,GACR,MAAM;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM;YAAC,EAAE,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAC,CAAC,CAAA;KAAC,CAAC,CAuE/G;IAED,2CAGC;CACJ;AAED;IAvhCA;;;;;;;;;;OAUG;IACH;;;qFAmEC;CA88BA;AAED;;;;;;;GAOG;AAEH;IAEI;;;;;;OAMG;IACH,mCALW,GAAG,kBACH,aAAa,wBACb,aAAa,GACX,MAAM,CA0ClB;IAED;;;;;OAKG;IACH,+BAJW,GAAG,gBACH,MAAM,GACJ,MAAM,CAoBlB;IACD;;;;;;;;;OASG;IACH,cATW,GAAG,EAAE,iBACL,GAAG,iBAGH,GAAG,GAGD,QAAQ,uBAAuB,CAAC,CAqB5C;IAED;;;;;;;;;;;;OAYG;IACH,0BAXW,MAAM,kBACN,MAAM,EAAE,EAAE,wBACV,MAAM,EAAE,EAAE;QAEO,cAAc,GAA/B,MAAM;QACY,QAAQ,GAA1B,OAAO;QACU,QAAQ;YACC,MAAM,GAAhC,MAAM;YACoB,KAAK,GAA/B,MAAM;;QACJ,MAAM,EAAE,CAwDpB;CACJ;AAED;IACI,8FAiBC;CACJ;AAED;IACI;;;;;;OAMG;IACH,cAJW,QAAQ,EAAE,WACV,QAAQ,EAAE,GACR,QAAQ,2BAA2B,CAAC,CAiChD;CACJ;AAED;IAEI,yBAeC;IADG,qBAAwD;IAG5D;;;;OAIG;IACH,kCAHW,YAAY,GAAC,YAAY;cAChB,YAAY;cAAQ,MAAM,EAAE;MAyB/C;IAED;;;;OAIG;IACH,aAHW,YAAY,GAAC,YAAY,GACvB,QAAQ;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,CAAC,CA2B/C;CACJ;AAED;IAEI;;;OAGG;IACH,uCAHW,YAAY,GACV,YAAY,CAQxB;IAED;;;;OAIG;IACH,aAHW,YAAY,GAAC,YAAY;sBACC,MAAM;wBAAkB,MAAM;OAsBlE;CACJ;AAED;IAGI,yBA2BC;IARG,wBAA8B;IAE9B,qBAEE;IAEF,UAA4B;IAC5B,SAA0B;IAG9B;;;;;OAKG;IACH,kCAJW,YAAY,GAAC,YAAY,cACzB,MAAM,GACJ;QAAC,IAAI,EAAE,YAAY,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAC,CAwBhD;IAGD;;;;OAIG;IACH,aAHW,YAAY,GAAC,YAAY,GACvB,QAAQ;QAAE,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC,CAoB7C;CACJ;AAED;IAEI,yBAyBC;IAtBG,wBAQC;IAED,+BAQC;IAED,qBAAkE;IAKtE;;;;;;;;;;;;;;;;;;;OAmBG;IACH,yBANW,YAAY,GAAC,YAAY,cACzB,MAAM,cACN,MAAM,WACN,MAAM;cACI,YAAY;cAAQ,MAAM,EAAE;gBAAU,OAAO;MAiDjE;IAED;;;;;;;;;;;;;;OAcG;IACH,kCALW,YAAY,GAAC,YAAY,eACzB,MAAM,EAAE,EAAE,eACV,MAAM,GACJ;QAAC,IAAI,EAAE,YAAY,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAC,CAoBhD;IAGD;;;;OAIG;IACH,aAHW,YAAY,GAAC,YAAY;;QACvB,QAAQ;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,CAAC,CAsB/C;CACJ;AAID;CAAkE;;;;;AAElE;;;GAGG;AACH;IACI;;;OAGG;IACH,+BAFW,gBAAgB,EAM1B;IAFG,oCAA0C;IAI9C;;;;;OAKG;IACH,aAJW,GAAG,WACA,GAAG,KACJ,QAAQ,GAAG,CAAC,CAIxB;CACJ;AAED;IACI;;OAEG;IACH,oCAEC;IAED;;OAEG;IACH,wCAGC;IACD;;OAEG;IACH,0CAGC;CACJ;AAED;;;GAGG;AACH;IACI;;;;OAIG;IACH,aAHW,GAAG,GACD,QAAQ,GAAG,CAAC,CAIxB;CACJ;AAGD;IACI;;;;OAIG;IACH,aAHW,GAAG,GACD,QAAQ,GAAG,CAAC,CAIxB;CACJ;AAED;IACI;;;;OAIG;IACH,aAHW,GAAG,GACD,QAAQ,GAAG,CAAC,CAIxB;CACJ;AAED;CAAkD;AAIlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH;IACI;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA6BC;IAED;;;;;;MAMC;IAED;;;;;;;;;;;;;;OAcG;IACH,sDATW,MAAM,0EAKN,OAAO,gBAAgB,EAAE,iBAAiB,GAExC,QAAQ,SAAS,CAAC,CAuC9B;CACJ;;;;;0BAvxDY,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC;;;;;kBAqC9B,MAAM;;;;oBACN,aAAa;;;;0BACb,aAAa;;;gBA2lBb,MAAM;;yCACP,2BAA2B,GAAG,+BAA+B;;kBA0U5D,MAAM;oBACN,aAAa;0BACb,aAAa;mBACb,MAAM;mBACN,MAAM;;yBA7jCK,kBAAkB;uBAFgB,mBAAmB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts b/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts new file mode 100644 index 000000000..b33c028b0 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts @@ -0,0 +1,912 @@ +declare const TokenizerModel_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * Abstract base class for tokenizer models. + * + * @extends Callable + */ +export class TokenizerModel extends TokenizerModel_base { + /** + * Instantiates a new TokenizerModel instance based on the configuration object provided. + * @param {Object} config The configuration object for the TokenizerModel. + * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. + * @returns {TokenizerModel} A new instance of a TokenizerModel. + * @throws Will throw an error if the TokenizerModel type in the config is not recognized. + */ + static fromConfig(config: any, ...args: any[]): TokenizerModel; + /** + * Creates a new instance of TokenizerModel. + * @param {Object} config The configuration object for the TokenizerModel. + */ + constructor(config: any); + config: any; + /** @type {string[]} */ + vocab: string[]; + /** + * A mapping of tokens to ids. + * @type {Map} + */ + tokens_to_ids: Map; + unk_token_id: any; + unk_token: any; + end_of_word_suffix: any; + /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */ + fuse_unk: boolean; + /** + * Internal function to call the TokenizerModel instance. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded token IDs. + */ + _call(tokens: string[]): string[]; + /** + * Encodes a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded tokens. + * @throws Will throw an error if not implemented in a subclass. + */ + encode(tokens: string[]): string[]; + /** + * Converts a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to convert. + * @returns {number[]} The converted token IDs. + */ + convert_tokens_to_ids(tokens: string[]): number[]; + /** + * Converts a list of token IDs into a list of tokens. + * @param {number[]} ids The token IDs to convert. + * @returns {string[]} The converted tokens. + */ + convert_ids_to_tokens(ids: number[]): string[]; +} +declare const PreTrainedTokenizer_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +export class PreTrainedTokenizer extends PreTrainedTokenizer_base { + /** + * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. + * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, legacy, }?: PretrainedTokenizerOptions): Promise; + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON: any, tokenizerConfig: any); + return_token_type_ids: boolean; + _default_chat_template: string; + _tokenizer_config: any; + normalizer: Normalizer; + pre_tokenizer: PreTokenizer; + model: TokenizerModel; + post_processor: PostProcessor; + decoder: Decoder; + special_tokens: any[]; + all_special_ids: number[]; + /** @type {AddedToken[]} */ + added_tokens: AddedToken[]; + additional_special_tokens: any; + added_tokens_regex: RegExp; + mask_token: string; + mask_token_id: number; + pad_token: string; + pad_token_id: number; + sep_token: string; + sep_token_id: number; + unk_token: string; + unk_token_id: number; + model_max_length: any; + /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */ + remove_space: boolean; + clean_up_tokenization_spaces: any; + do_lowercase_and_remove_accent: any; + /** @type {'right'|'left'} */ + padding_side: 'right' | 'left'; + legacy: boolean; + chat_template: any; + _compiled_template_cache: Map; + /** + * Returns the value of the first matching key in the tokenizer config object. + * @param {...string} keys One or more keys to search for in the tokenizer config object. + * @returns {string|null} The value associated with the first matching key, or null if no match is found. + * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". + */ + getToken(...keys: string[]): string | null; + /** + * @typedef {number[]|number[][]|Tensor} BatchEncodingItem + * + * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. + * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. + * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. + * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. + */ + /** + * Encode/tokenize the given text(s). + * @param {string|string[]} text The text to tokenize. + * @param {Object} options An optional object containing the following properties: + * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. + * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. + * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. + * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. + * @returns {BatchEncoding} Object to be passed to the model. + */ + _call(text: string | string[], { text_pair, add_special_tokens, padding, truncation, max_length, return_tensor, }?: { + text_pair?: string | string[]; + padding?: boolean | 'max_length'; + add_special_tokens?: boolean; + truncation?: boolean; + max_length?: number; + return_tensor?: boolean; + }): { + /** + * List of token ids to be fed to a model. + */ + input_ids: number[] | Tensor | number[][]; + /** + * List of indices specifying which tokens should be attended to by the model. + */ + attention_mask: number[] | Tensor | number[][]; + /** + * List of token type ids to be fed to a model. + */ + token_type_ids?: number[] | Tensor | number[][]; + }; + /** + * Encodes a single text using the preprocessor pipeline of the tokenizer. + * + * @param {string|null} text The text to encode. + * @returns {string[]|null} The encoded tokens. + */ + _encode_text(text: string | null): string[] | null; + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {string|null} text_pair The optional second text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @returns {EncodingSingle} An object containing the encoded text. + * @private + */ + private _encode_plus; + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {string|null} text_pair The optional second text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @returns {number[]} An array of token IDs representing the encoded text(s). + */ + encode(text: string, text_pair?: string | null, { add_special_tokens, }?: { + add_special_tokens?: boolean; + }): number[]; + /** + * Decode a batch of tokenized sequences. + * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. + * @param {Object} decode_args (Optional) Object with decoding arguments. + * @returns {string[]} List of decoded sequences. + */ + batch_decode(batch: number[][] | Tensor, decode_args?: any): string[]; + /** + * Decodes a sequence of token IDs back to a string. + * + * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode. + * @param {Object} [decode_args={}] + * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. + * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. + * + * @returns {string} The decoded string. + * @throws {Error} If `token_ids` is not a non-empty array of integers. + */ + decode(token_ids: number[] | Tensor, decode_args?: { + skip_special_tokens?: boolean; + clean_up_tokenization_spaces?: boolean; + }): string; + /** + * Decode a single list of token ids to a string. + * @param {number[]} token_ids List of token ids to decode + * @param {Object} decode_args Optional arguments for decoding + * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding + * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. + * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. + * @returns {string} The decoded string + */ + decode_single(token_ids: number[], { skip_special_tokens, clean_up_tokenization_spaces, }: { + skip_special_tokens?: boolean; + clean_up_tokenization_spaces?: boolean; + }): string; + get default_chat_template(): string; + _warned_about_chat_template: boolean; + /** + * @typedef {Object} Message + * @property {string} role The role of the message (e.g., "user" or "assistant" or "system"). + * @property {string} content The content of the message. + */ + /** + * Converts a list of message objects with `"role"` and `"content"` keys to a list of token + * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to + * determine the format and control tokens to use when converting. When chat_template is None, it will fall back + * to the default_chat_template specified at the class level. + * + * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. + * + * **Example:** Applying a chat template to a conversation. + * + * ```javascript + * import { AutoTokenizer } from "@xenova/transformers"; + * + * const tokenizer = await AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1"); + * + * const chat = [ + * { "role": "user", "content": "Hello, how are you?" }, + * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, + * { "role": "user", "content": "I'd like to show off how chat templating works!" }, + * ] + * + * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); + * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" + * + * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); + * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] + * ``` + * + * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If + * this is not passed, the model's default chat template will be used instead. + * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate + * the start of an assistant message. This is useful when you want to generate a response from the model. + * Note that this argument will be passed to the chat template, and so it must be supported in the + * template for this argument to have any effect. + * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. + * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. + * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. + * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. + * If not specified, the tokenizer's `max_length` attribute will be used as a default. + * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. + * @returns {string | Tensor | number[]| number[][]} The tokenized output. + */ + apply_chat_template(conversation: { + /** + * The role of the message (e.g., "user" or "assistant" or "system"). + */ + role: string; + /** + * The content of the message. + */ + content: string; + }[], { chat_template, add_generation_prompt, tokenize, padding, truncation, max_length, return_tensor, }?: { + chat_template?: string; + add_generation_prompt?: boolean; + tokenize?: boolean; + padding?: boolean; + truncation?: boolean; + max_length?: number; + return_tensor?: boolean; + }): string | Tensor | number[] | number[][]; +} +/** + * BertTokenizer is a class used to tokenize text for BERT models. + * @extends PreTrainedTokenizer + */ +export class BertTokenizer extends PreTrainedTokenizer { +} +/** + * Albert tokenizer + * @extends PreTrainedTokenizer + */ +export class AlbertTokenizer extends PreTrainedTokenizer { +} +export class MobileBertTokenizer extends PreTrainedTokenizer { +} +export class SqueezeBertTokenizer extends PreTrainedTokenizer { +} +export class DebertaTokenizer extends PreTrainedTokenizer { +} +export class DebertaV2Tokenizer extends PreTrainedTokenizer { +} +export class HerbertTokenizer extends PreTrainedTokenizer { +} +export class ConvBertTokenizer extends PreTrainedTokenizer { +} +export class RoFormerTokenizer extends PreTrainedTokenizer { +} +export class DistilBertTokenizer extends PreTrainedTokenizer { +} +export class CamembertTokenizer extends PreTrainedTokenizer { +} +export class XLMTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); +} +export class ElectraTokenizer extends PreTrainedTokenizer { +} +export class T5Tokenizer extends PreTrainedTokenizer { +} +export class GPT2Tokenizer extends PreTrainedTokenizer { +} +export class BartTokenizer extends PreTrainedTokenizer { +} +export class MBartTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); + languageRegex: RegExp; + language_codes: any[]; + lang_to_token: (x: any) => any; + /** + * Helper function to build translation inputs for an `MBartTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any; +} +export class MBart50Tokenizer extends MBartTokenizer { +} +export class RobertaTokenizer extends PreTrainedTokenizer { +} +export class BloomTokenizer extends GPT2Tokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); +} +export class LlamaTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); + DEFAULT_SYSTEM_PROMPT: string; + use_default_system_prompt: any; + legacy: any; + get default_chat_template(): any; +} +export class CodeLlamaTokenizer extends LlamaTokenizer { +} +export class XLMRobertaTokenizer extends PreTrainedTokenizer { +} +export class MPNetTokenizer extends PreTrainedTokenizer { +} +export class FalconTokenizer extends PreTrainedTokenizer { +} +export class GPTNeoXTokenizer extends PreTrainedTokenizer { +} +export class EsmTokenizer extends PreTrainedTokenizer { +} +/** + * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models. + * + * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project + * that open-sources models capable of delivering high-quality translations directly + * between any pair of 200+ languages — including low-resource languages like Asturian, + * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere, + * regardless of their language preferences. For more information, check out their + * [paper](https://arxiv.org/abs/2207.04672). + * + * For a list of supported languages (along with their language codes), + * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200} + */ +export class NllbTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); + languageRegex: RegExp; + language_codes: any[]; + lang_to_token: (x: any) => any; + /** + * Helper function to build translation inputs for an `NllbTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any; +} +/** + * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models. + * + * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many + * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125) + * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository. + * + * For a list of supported languages (along with their language codes), + * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered} + */ +export class M2M100Tokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); + languageRegex: RegExp; + language_codes: any[]; + lang_to_token: (x: any) => string; + /** + * Helper function to build translation inputs for an `M2M100Tokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any; +} +/** + * WhisperTokenizer tokenizer + * @extends PreTrainedTokenizer + */ +export class WhisperTokenizer extends PreTrainedTokenizer { + /** + * Decodes automatic speech recognition (ASR) sequences. + * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. + * @param {Object} options The options to use for decoding. + * @returns {Array, text: string}>}>} The decoded sequences. + */ + _decode_asr(sequences: Array<{ + tokens: number[]; + token_timestamps?: number[]; + stride: number[]; + }>, { return_timestamps, return_language, time_precision, force_full_sequences }?: any): (string | { + chunks?: undefined | Array<{ + language: string | null; + timestamp: Array; + text: string; + }>; + })[]; + /** + * Finds the longest common sequence among the provided sequences. + * @param {number[][]} sequences An array of sequences of token ids to compare. + * @returns {number[][]} The longest common sequence found. + * @throws {Error} If there is a bug within the function. + * @private + */ + private findLongestCommonSequence; + /** @private */ + private collateWordTimestamps; + /** + * Groups tokens by word. Returns a tuple containing a list of strings with the words, + * and a list of `token_id` sequences with the tokens making up each word. + * @param {number[]} tokens + * @param {string} [language] + * @param {string} prepend_punctionations + * @param {string} append_punctuations + * + * @private + */ + private combineTokensIntoWords; + /** + * @param {number[]} token_ids List of token IDs to decode. + * @param {Object} decode_args Optional arguments for decoding + * @private + */ + private decodeWithTimestamps; + /** + * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. + * @param {number[]} tokens + * @returns {*} + * @private + */ + private splitTokensOnUnicode; + /** + * Combine tokens into words by splitting at whitespace and punctuation tokens. + * @param {number[]} tokens + * @private + */ + private splitTokensOnSpaces; + /** + * Merges punctuation tokens with neighboring words. + * @param {string[]} words + * @param {number[][]} tokens + * @param {number[][]} indices + * @param {string} prepended + * @param {string} appended + * @private + */ + private mergePunctuations; + /** + * Helper function to build translation inputs for a `WhisperTokenizer`, + * depending on the language, task, and whether to predict timestamp tokens. + * + * Used to override the prefix tokens appended to the start of the label sequence. + * + * **Example: Get ids for a language** + * ```javascript + * // instantiate the tokenizer and set the prefix token to Spanish + * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny'); + * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' }); + * // [(1, 50262), (2, 50363)] + * ``` + * + * @param {Object} options Options to generate the decoder prompt. + * @param {string} [options.language] The language of the transcription text. + * The corresponding language id token is appended to the start of the sequence for multilingual + * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended + * to the start of sequence. + * @param {string} [options.task] Task identifier to append at the start of sequence (if any). + * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and + * "translate" for speech translation. + * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence. + * @returns {number[][]} The decoder prompt ids. + */ + get_decoder_prompt_ids({ language, task, no_timestamps, }?: { + language?: string; + task?: string; + no_timestamps?: boolean; + }): number[][]; +} +export class CodeGenTokenizer extends PreTrainedTokenizer { +} +export class CLIPTokenizer extends PreTrainedTokenizer { +} +export class SiglipTokenizer extends PreTrainedTokenizer { +} +/** + * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers). + * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results. + */ +export class MarianTokenizer extends PreTrainedTokenizer { + languageRegex: RegExp; + supported_language_codes: string[]; + /** + * Encodes a single text. Overriding this method is necessary since the language codes + * must be removed before encoding with sentencepiece model. + * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 + * + * @param {string|null} text The text to encode. + * @returns {Array} The encoded tokens. + */ + _encode_text(text: string | null): any[]; +} +export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { +} +export class BlenderbotTokenizer extends PreTrainedTokenizer { +} +export class BlenderbotSmallTokenizer extends BlenderbotTokenizer { +} +export class SpeechT5Tokenizer extends PreTrainedTokenizer { +} +export class NougatTokenizer extends PreTrainedTokenizer { +} +export class VitsTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON: any, tokenizerConfig: any); +} +/** + * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function. + * The chosen tokenizer class is determined by the type specified in the tokenizer config. + * + * @example + * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); + */ +export class AutoTokenizer { + static TOKENIZER_CLASS_MAPPING: { + T5Tokenizer: typeof T5Tokenizer; + DistilBertTokenizer: typeof DistilBertTokenizer; + CamembertTokenizer: typeof CamembertTokenizer; + DebertaTokenizer: typeof DebertaTokenizer; + DebertaV2Tokenizer: typeof DebertaV2Tokenizer; + BertTokenizer: typeof BertTokenizer; + HerbertTokenizer: typeof HerbertTokenizer; + ConvBertTokenizer: typeof ConvBertTokenizer; + RoFormerTokenizer: typeof RoFormerTokenizer; + XLMTokenizer: typeof XLMTokenizer; + ElectraTokenizer: typeof ElectraTokenizer; + MobileBertTokenizer: typeof MobileBertTokenizer; + SqueezeBertTokenizer: typeof SqueezeBertTokenizer; + AlbertTokenizer: typeof AlbertTokenizer; + GPT2Tokenizer: typeof GPT2Tokenizer; + BartTokenizer: typeof BartTokenizer; + MBartTokenizer: typeof MBartTokenizer; + MBart50Tokenizer: typeof MBart50Tokenizer; + RobertaTokenizer: typeof RobertaTokenizer; + WhisperTokenizer: typeof WhisperTokenizer; + CodeGenTokenizer: typeof CodeGenTokenizer; + CLIPTokenizer: typeof CLIPTokenizer; + SiglipTokenizer: typeof SiglipTokenizer; + MarianTokenizer: typeof MarianTokenizer; + BloomTokenizer: typeof BloomTokenizer; + NllbTokenizer: typeof NllbTokenizer; + M2M100Tokenizer: typeof M2M100Tokenizer; + LlamaTokenizer: typeof LlamaTokenizer; + CodeLlamaTokenizer: typeof CodeLlamaTokenizer; + XLMRobertaTokenizer: typeof XLMRobertaTokenizer; + MPNetTokenizer: typeof MPNetTokenizer; + FalconTokenizer: typeof FalconTokenizer; + GPTNeoXTokenizer: typeof GPTNeoXTokenizer; + EsmTokenizer: typeof EsmTokenizer; + Wav2Vec2CTCTokenizer: typeof Wav2Vec2CTCTokenizer; + BlenderbotTokenizer: typeof BlenderbotTokenizer; + BlenderbotSmallTokenizer: typeof BlenderbotSmallTokenizer; + SpeechT5Tokenizer: typeof SpeechT5Tokenizer; + NougatTokenizer: typeof NougatTokenizer; + VitsTokenizer: typeof VitsTokenizer; + PreTrainedTokenizer: typeof PreTrainedTokenizer; + }; + /** + * Instantiate one of the tokenizer classes of the library from a pretrained model. + * + * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @returns {Promise} A new instance of the PreTrainedTokenizer class. + */ + static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, legacy, }?: PretrainedTokenizerOptions): Promise; +} +/** + * Additional tokenizer-specific properties. + */ +export type TokenizerProperties = { + /** + * Whether or not the `legacy` behavior of the tokenizer should be used. + */ + legacy?: boolean; +}; +export type PretrainedTokenizerOptions = import('./utils/hub.js').PretrainedOptions & TokenizerProperties; +export type BPENode = { + /** + * The token associated with the node + */ + token: string; + /** + * A positional bias for the node. + */ + bias: number; + /** + * The score of the node. + */ + score?: number; + /** + * The previous node in the linked list. + */ + prev?: BPENode; + /** + * The next node in the linked list. + */ + next?: BPENode; +}; +export type SplitDelimiterBehavior = 'removed' | 'isolated' | 'mergedWithPrevious' | 'mergedWithNext' | 'contiguous'; +export type PostProcessedOutput = { + /** + * List of token produced by the post-processor. + */ + tokens: string[]; + /** + * List of token type ids produced by the post-processor. + */ + token_type_ids?: number[]; +}; +export type EncodingSingle = { + /** + * List of token ids to be fed to a model. + */ + input_ids: number[]; + /** + * List of token type ids to be fed to a model + */ + attention_mask: number[]; + /** + * List of indices specifying which tokens should be attended to by the model + */ + token_type_ids?: number[]; +}; +declare const Normalizer_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * A base class for text normalization. + * @abstract + */ +declare class Normalizer extends Normalizer_base { + /** + * Factory method for creating normalizers from config objects. + * @static + * @param {Object} config The configuration object for the normalizer. + * @returns {Normalizer} A Normalizer object. + * @throws {Error} If an unknown Normalizer type is specified in the config. + */ + static fromConfig(config: any): Normalizer; + /** + * @param {Object} config The configuration object for the normalizer. + */ + constructor(config: any); + config: any; + /** + * Normalize the input text. + * @abstract + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + * @throws {Error} If this method is not implemented in a subclass. + */ + normalize(text: string): string; + /** + * Alias for {@link Normalizer#normalize}. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + _call(text: string): string; +} +declare const PreTokenizer_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * A callable class representing a pre-tokenizer used in tokenization. Subclasses + * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic. + * @extends Callable + */ +declare class PreTokenizer extends PreTokenizer_base { + /** + * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. + * + * @static + * @param {Object} config A configuration object for the pre-tokenizer. + * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. + * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. + */ + static fromConfig(config: any): PreTokenizer; + /** + * Method that should be implemented by subclasses to define the specific pre-tokenization logic. + * + * @abstract + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} The pre-tokenized text. + * @throws {Error} If the method is not implemented in the subclass. + */ + pre_tokenize_text(text: string, options?: any): string[]; + /** + * Tokenizes the given text into pre-tokens. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + pre_tokenize(text: string | string[], options?: any): string[]; + /** + * Alias for {@link PreTokenizer#pre_tokenize}. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + _call(text: string | string[], options?: any): string[]; +} +declare const PostProcessor_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * @typedef {Object} PostProcessedOutput + * @property {string[]} tokens List of token produced by the post-processor. + * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor. + */ +/** + * @typedef {Object} EncodingSingle + * @property {number[]} input_ids List of token ids to be fed to a model. + * @property {number[]} attention_mask List of token type ids to be fed to a model + * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model + */ +/** + * @extends Callable + */ +declare class PostProcessor extends PostProcessor_base { + /** + * Factory method to create a PostProcessor object from a configuration object. + * + * @param {Object} config Configuration object representing a PostProcessor. + * @returns {PostProcessor} A PostProcessor object created from the given configuration. + * @throws {Error} If an unknown PostProcessor type is encountered. + */ + static fromConfig(config: any): PostProcessor; + /** + * @param {Object} config The configuration for the post-processor. + */ + constructor(config: any); + config: any; + /** + * Method to be implemented in subclass to apply post-processing on the given tokens. + * + * @param {Array} tokens The input tokens to be post-processed. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + * @throws {Error} If the method is not implemented in subclass. + */ + post_process(tokens: any[], ...args: any[]): PostProcessedOutput; + /** + * Alias for {@link PostProcessor#post_process}. + * @param {Array} tokens The text or array of texts to post-process. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + */ + _call(tokens: any[], ...args: any[]): PostProcessedOutput; +} +declare const Decoder_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * The base class for token decoders. + * @extends Callable + */ +declare class Decoder extends Decoder_base { + /** + * Creates a decoder instance based on the provided configuration. + * + * @param {Object} config The configuration object. + * @returns {Decoder} A decoder instance. + * @throws {Error} If an unknown decoder type is provided. + */ + static fromConfig(config: any): Decoder; + /** + * Creates an instance of `Decoder`. + * + * @param {Object} config The configuration object. + */ + constructor(config: any); + config: any; + /** @type {AddedToken[]} */ + added_tokens: AddedToken[]; + end_of_word_suffix: any; + trim_offsets: any; + /** + * Calls the `decode` method. + * + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + _call(tokens: string[]): string; + /** + * Decodes a list of tokens. + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + decode(tokens: string[]): string; + /** + * Apply the decoder to a list of tokens. + * + * @param {string[]} tokens The list of tokens. + * @returns {string[]} The decoded list of tokens. + * @throws {Error} If the `decode_chain` method is not implemented in the subclass. + */ + decode_chain(tokens: string[]): string[]; +} +/** + * Represent a token added by the user on top of the existing Model vocabulary. + * AddedToken can be configured to specify the behavior they should have in various situations like: + * - Whether they should only match single words + * - Whether to include any whitespace on its left or right + */ +declare class AddedToken { + /** + * Creates a new instance of AddedToken. + * @param {Object} config Added token configuration object. + * @param {string} config.content The content of the added token. + * @param {number} config.id The id of the added token. + * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. + * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. + * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. + * @param {boolean} [config.normalized=false] Whether this token should be normalized. + * @param {boolean} [config.special=false] Whether this token is special. + */ + constructor(config: { + content: string; + id: number; + single_word?: boolean; + lstrip?: boolean; + rstrip?: boolean; + normalized?: boolean; + special?: boolean; + }); + content: string; + id: number; + single_word: boolean; + lstrip: boolean; + rstrip: boolean; + special: boolean; + normalized: boolean; +} +import { Tensor } from './utils/tensor.js'; +export {}; +//# sourceMappingURL=tokenizers.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts.map new file mode 100644 index 000000000..089898b48 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/tokenizers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tokenizers.d.ts","sourceRoot":"","sources":["../src/tokenizers.js"],"names":[],"mappings":";;;;AAoQA;;;;GAIG;AACH;IA0BI;;;;;;OAMG;IACH,gDAHa,cAAc,CAqB1B;IAlDD;;;OAGG;IACH,yBAmBC;IAjBG,YAAoB;IAEpB,uBAAuB;IACvB,OADW,MAAM,EAAE,CACJ;IAEf;;;OAGG;IACH,eAFU,IAAI,MAAM,EAAE,MAAM,CAAC,CAEC;IAE9B,kBAA6B;IAC7B,eAA0B;IAC1B,wBAAmC;IAEnC,uFAAuF;IACvF,UADW,OAAO,CAC2B;IA8BjD;;;;OAIG;IACH,cAHW,MAAM,EAAE,GACN,MAAM,EAAE,CASpB;IAED;;;;;OAKG;IACH,eAJW,MAAM,EAAE,GACN,MAAM,EAAE,CAKpB;IAED;;;;OAIG;IACH,8BAHW,MAAM,EAAE,GACN,MAAM,EAAE,CAIpB;IAED;;;;OAIG;IACH,2BAHW,MAAM,EAAE,GACN,MAAM,EAAE,CAIpB;CACJ;;;;;AAk/DD;IAsHI;;;;;;;;OAQG;IACH,sDANW,MAAM,kFACN,0BAA0B,GAGxB,QAAQ,mBAAmB,CAAC,CAsBxC;IA9ID;;;;OAIG;IACH,sDAiFC;IA1FD,+BAA8B;IAE9B,+BAAmO;IAU/N,uBAAwC;IAGxC,uBAAiE;IACjE,4BAAyE;IACzE,sBAA4E;IAC5E,8BAA4E;IAC5E,iBAAwD;IAGxD,sBAAwB;IACxB,0BAAyB;IAEzB,2BAA2B;IAC3B,cADW,UAAU,EAAE,CACD;IAetB,+BAAgF;IAgBhF,2BAEQ;IAGR,mBAA6C;IAC7C,sBAAkE;IAElE,kBAAwD;IACxD,qBAAgE;IAEhE,kBAA2C;IAC3C,qBAAgE;IAEhE,kBAA4D;IAC5D,qBAAgE;IAEhE,sBAAwD;IAExD,6HAA6H;IAC7H,cADW,OAAO,CAC8B;IAEhD,kCAAwF;IACxF,oCAA6F;IAG7F,6BAA6B;IAC7B,cADW,OAAO,GAAC,MAAM,CACE;IAE3B,gBAAmB;IAEnB,mBAA0D;IAC1D,wCAAyC;IAG7C;;;;;OAKG;IACH,kBAJc,MAAM,KACP,MAAM,GAAC,IAAI,CAoBvB;IAiCD;;;;;;;OAOG;IAEH;;;;;;;;;;;OAWG;IACH,YAVW,MAAM,GAAC,MAAM,EAAE;QAEW,SAAS,GAAnC,MAAM,GAAC,MAAM,EAAE;QACgB,OAAO,GAAtC,OAAO,GAAC,YAAY;QACF,kBAAkB,GAApC,OAAO;QACW,UAAU,GAA5B,OAAO;QACU,UAAU,GAA3B,MAAM;QACY,aAAa,GAA/B,OAAO;;;;;;;;;;;;;;MAyJjB;IAED;;;;;OAKG;IACH,mBAHW,MAAM,GAAC,IAAI,GACT,MAAM,EAAE,GAAC,IAAI,CAsCzB;IAED;;;;;;;;;OASG;IACH,qBAqBC;IAED;;;;;;;;OAQG;IACH,aANW,MAAM,cACN,MAAM,GAAC,IAAI;QAEO,kBAAkB,GAApC,OAAO;QACL,MAAM,EAAE,CASpB;IAED;;;;;OAKG;IACH,oBAJW,MAAM,EAAE,EAAE,GAAC,MAAM,sBAEf,MAAM,EAAE,CAOpB;IAED;;;;;;;;;;OAUG;IACH,kBARW,MAAM,EAAE,GAAC,MAAM;QAEO,mBAAmB,GAAzC,OAAO;QACe,4BAA4B,GAAlD,OAAO;QAEL,MAAM,CAgBlB;IAED;;;;;;;;OAQG;IACH,yBAPW,MAAM,EAAE;QAEc,mBAAmB,GAAzC,OAAO;QACe,4BAA4B,GAAlD,OAAO;QAEL,MAAM,CAiClB;IAED,oCAYC;IAJO,qCAAuC;IAM/C;;;;OAIG;IAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2CG;IACH;;;;cAhDc,MAAM;;;;iBACN,MAAM;;QAiCQ,aAAa,GAA9B,MAAM;QAEY,qBAAqB,GAAvC,OAAO;QAIW,QAAQ,GAA1B,OAAO;QACW,OAAO,GAAzB,OAAO;QACW,UAAU,GAA5B,OAAO;QACU,UAAU,GAA3B,MAAM;QAEY,aAAa,GAA/B,OAAO;QACL,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,GAAE,MAAM,EAAE,EAAE,CA+ClD;CACJ;AAED;;;GAGG;AACH;CAEC;AACD;;;GAGG;AACH;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAEC;AACD;CAAgE;AAChE;CAA+D;AAC/D;IAGI,sDAGC;CACJ;AACD;CAEC;AAED;CAAwD;AACxD;CAEC;AACD;CAA0D;AAC1D;IACI,sDAMC;IAHG,sBAA0C;IAC1C,sBAAiF;IACjF,+BAA2B;IAG/B;;;;;;OAMG;IACH,sCALW,MAAM,GAAC,MAAM,EAAE,qDAOzB;CACJ;AACD;CAAwD;AAExD;CAA6D;AAE7D;IAEI,sDASC;CACJ;AAID;IAUI,sDAcC;IArBD,8BAKgG;IAI5F,+BAAmF;IAEnF,YAA4C;IAgChD,iCAIC;CACJ;AACD;CAA0D;AAE1D;CAAgE;AAChE;CAA2D;AAE3D;CAA4D;AAE5D;CAA6D;AAE7D;CAAyD;AAqDzD;;;;;;;;;;;;GAYG;AACH;IAEI,sDAMC;IAHG,sBAA+C;IAC/C,sBAAiF;IACjF,+BAA2B;IAG/B;;;;;;OAMG;IACH,sCALW,MAAM,GAAC,MAAM,EAAE,qDAOzB;CACJ;AAED;;;;;;;;;GASG;AACH;IACI,sDAQC;IALG,sBAAuC;IACvC,sBAE6B;IAC7B,kCAAoC;IAGxC;;;;;;OAMG;IACH,sCALW,MAAM,GAAC,MAAM,EAAE,qDAOzB;CACJ;AA6HD;;;GAGG;AACH;IAGI;;;;;OAKG;IACH,uBAJW,MAAM;QAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAC,CAAC;iBAE/C,SAAS,GAAC,MAAM;YAAC,QAAQ,EAAE,MAAM,GAAC,IAAI,CAAC;YAAC,SAAS,EAAE,MAAM,MAAM,GAAC,IAAI,CAAC,CAAC;YAAC,IAAI,EAAE,MAAM,CAAA;SAAC,CAAC;SA4RxH;IAED;;;;;;OAMG;IACH,kCAsFC;IAED,eAAe;IACf,8BAgBC;IAED;;;;;;;;;OASG;IACH,+BAaC;IAwBD;;;;OAIG;IACH,6BA0BC;IAED;;;;;OAKG;IACH,6BAqCC;IAED;;;;OAIG;IACH,4BAoCC;IAED;;;;;;;;OAQG;IACH,0BA+CC;IAED;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH;QAV4B,QAAQ,GAAzB,MAAM;QAIW,IAAI,GAArB,MAAM;QAGY,aAAa,GAA/B,OAAO;QACL,MAAM,EAAE,EAAE,CA0EtB;CACJ;AACD;CAA6D;AAC7D;CAA0D;AAC1D;CAA4D;AAE5D;;;GAGG;AACH;IASQ,sBAAqC;IAErC,mCAEC;IAKL;;;;;;;OAOG;IACH,mBAHW,MAAM,GAAC,IAAI,SAsBrB;CAEJ;AAED;CAAiE;AAEjE;CAEC;AACD;CAAqE;AAErE;CAA8D;AAE9D;CAA4D;AAE5D;IAEI,sDAKC;CACJ;AACD;;;;;;GAMG;AACH;IACI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA4CC;IAGD;;;;;;;;;;;;;;OAcG;IACH,sDATW,MAAM,6FAKN,0BAA0B,GAExB,QAAQ,mBAAmB,CAAC,CA+BxC;CACJ;;;;;;;;aA3qIa,OAAO;;yCACR,OAAO,gBAAgB,EAAE,iBAAiB,GAAG,mBAAmB;;;;;WAyiB/D,MAAM;;;;UACN,MAAM;;;;YACN,MAAM;;;;WACN,OAAO;;;;WACP,OAAO;;qCAgzBR,SAAS,GAAC,UAAU,GAAC,oBAAoB,GAAC,gBAAgB,GAAC,YAAY;;;;;YAqGtE,MAAM,EAAE;;;;qBACR,MAAM,EAAE;;;;;;eAMR,MAAM,EAAE;;;;oBACR,MAAM,EAAE;;;;qBACR,MAAM,EAAE;;;;;;AA3oBtB;;;GAGG;AACH;IASI;;;;;;OAMG;IACH,gCAHa,UAAU,CA+BtB;IA3CD;;OAEG;IACH,yBAGC;IADG,YAAoB;IAwCxB;;;;;;OAMG;IACH,gBAJW,MAAM,GACJ,MAAM,CAKlB;IAED;;;;OAIG;IACH,YAHW,MAAM,GACJ,MAAM,CAIlB;CAEJ;;;;;AA+SD;;;;GAIG;AACH;IACI;;;;;;;KAOC;IACD,gCAHW,YAAY,CA6BtB;IAED;;;;;;;;OAQG;IACH,wBALW,MAAM,kBAEJ,MAAM,EAAE,CAKpB;IAED;;;;;OAKG;IACH,mBAJW,MAAM,GAAC,MAAM,EAAE,kBAEb,MAAM,EAAE,CAOpB;IAED;;;;;OAKG;IACH,YAJW,MAAM,GAAC,MAAM,EAAE,kBAEb,MAAM,EAAE,CAIpB;CACJ;;;;;AA8LD;;;;GAIG;AAGH;;;;;GAKG;AAGH;;GAEG;AACH;IAUI;;;;;;OAMG;IACH,gCAHa,aAAa,CAoBzB;IAhCD;;OAEG;IACH,yBAGC;IADG,YAAoB;IA6BxB;;;;;;;OAOG;IACH,6CAHa,mBAAmB,CAK/B;IAED;;;;;OAKG;IACH,sCAFa,mBAAmB,CAI/B;CACJ;;;;;AAwHD;;;GAGG;AACH;IAiBI;;;;;;KAMC;IACD,gCAHW,OAAO,CAgCjB;IAnDD;;;;MAIE;IACF,yBAQC;IANG,YAAoB;IAEpB,2BAA2B;IAC3B,cADW,UAAU,EAAE,CACD;IACtB,wBAA8B;IAC9B,kBAAuC;IAyC3C;;;;;MAKE;IACF,cAHU,MAAM,EAAE,GACN,MAAM,CAIjB;IAED;;;;MAIE;IACF,eAHU,MAAM,EAAE,GACN,MAAM,CAIjB;IAED;;;;;;OAMG;IACH,qBAJW,MAAM,EAAE,GACN,MAAM,EAAE,CAKpB;CAEJ;AAtiDD;;;;;GAKG;AACH;IACI;;;;;;;;;;OAUG;IACH;QAR0B,OAAO,EAAtB,MAAM;QACS,EAAE,EAAjB,MAAM;QACW,WAAW,GAA5B,OAAO;QACU,MAAM,GAAvB,OAAO;QACU,MAAM,GAAvB,OAAO;QACU,UAAU,GAA3B,OAAO;QACU,OAAO,GAAxB,OAAO;OAUjB;IAPG,gBAA6B;IAC7B,WAAmB;IACnB,qBAA8C;IAC9C,gBAAoC;IACpC,gBAAoC;IACpC,iBAAsC;IACtC,oBAA2C;CAElD;uBA/NsB,mBAAmB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts b/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts new file mode 100644 index 000000000..3b83ad482 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts @@ -0,0 +1,11 @@ +export * from "./pipelines.js"; +export * from "./env.js"; +export * from "./models.js"; +export * from "./tokenizers.js"; +export * from "./processors.js"; +export * from "./configs.js"; +export * from "./utils/audio.js"; +export * from "./utils/image.js"; +export * from "./utils/tensor.js"; +export * from "./utils/maths.js"; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts.map new file mode 100644 index 000000000..7994743ed --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.ts","sourceRoot":"","sources":["../src/transformers.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts new file mode 100644 index 000000000..a670b3658 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts @@ -0,0 +1,121 @@ +/** + * Helper function to read audio from a path/URL. + * @param {string|URL} url The path/URL to load the audio from. + * @param {number} sampling_rate The sampling rate to use when decoding the audio. + * @returns {Promise} The decoded audio as a `Float32Array`. + */ +export function read_audio(url: string | URL, sampling_rate: number): Promise; +/** + * Generates a Hanning window of length M. + * + * @param {number} M The length of the Hanning window to generate. + * @returns {Float64Array} The generated Hanning window. + */ +export function hanning(M: number): Float64Array; +/** + * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and + * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters + * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these + * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency. + * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`). + * @param {number} num_mel_filters Number of mel filters to generate. + * @param {number} min_frequency Lowest frequency of interest in Hz. + * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`. + * @param {number} sampling_rate Sample rate of the audio waveform. + * @param {string} [norm] If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization). + * @param {string} [mel_scale] The mel frequency scale to use, `"htk"` or `"slaney"`. + * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space. + * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters. + * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`). + * This is a projection matrix to go from a spectrogram to a mel spectrogram. + */ +export function mel_filter_bank(num_frequency_bins: number, num_mel_filters: number, min_frequency: number, max_frequency: number, sampling_rate: number, norm?: string, mel_scale?: string, triangularize_in_mel_space?: boolean): number[][]; +/** + * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform. + * + * This function can create the following kinds of spectrograms: + * - amplitude spectrogram (`power = 1.0`) + * - power spectrogram (`power = 2.0`) + * - complex-valued spectrogram (`power = None`) + * - log spectrogram (use `log_mel` argument) + * - mel spectrogram (provide `mel_filters`) + * - log-mel spectrogram (provide `mel_filters` and `log_mel`) + * + * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. + * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, + * typically the next power of two. + * + * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform. + * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be + * shorter than `frame_length`, but we're assuming the array has already been zero-padded. + * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`). + * @param {number} hop_length The stride between successive analysis frames in samples. + * @param {Object} options + * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have. + * For optimal speed, this should be a power of two. If `null`, uses `frame_length`. + * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers. + * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame + * `t` will start at time `t * hop_length`. + * @param {string} [options.pad_mode="reflect"] Padding mode used when `center` is `true`. Possible values are: `"constant"` (pad with zeros), + * `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values). + * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1` + * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins. + * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT. + * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`. + * If supplied, applies this filter bank to create a mel spectrogram. + * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks. + * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are: + * `null` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). + * Can only be used when `power` is not `null`. + * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set + * the loudest part to 0 dB. Must be greater than zero. + * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`. + * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB. + * Must be greater than zero. + * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the + * peak value and the smallest value will never be more than 80 dB. Must be greater than zero. + * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in + * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters. + * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value. + * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames. + * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`. + * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram). + */ +export function spectrogram(waveform: Float32Array | Float64Array, window: Float32Array | Float64Array, frame_length: number, hop_length: number, { fft_length, power, center, pad_mode, onesided, preemphasis, mel_filters, mel_floor, log_mel, reference, min_value, db_range, remove_dc_offset, max_num_frames, do_pad, transpose, }?: { + fft_length?: number; + power?: number; + center?: boolean; + pad_mode?: string; + onesided?: boolean; + preemphasis?: number; + mel_filters?: number[][]; + mel_floor?: number; + log_mel?: string; + reference?: number; + min_value?: number; + db_range?: number; + remove_dc_offset?: boolean; + max_num_frames?: number; + do_pad?: boolean; + transpose?: boolean; +}): { + data: Float32Array; + dims: number[]; +}; +/** + * Returns an array containing the specified window. + * @param {number} window_length The length of the window in samples. + * @param {string} name The name of the window function. + * @param {Object} options Additional options. + * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric. + * @param {number} [options.frame_length=null] The length of the analysis frames in samples. + * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded. + * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided. + * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`. + */ +export function window_function(window_length: number, name: string, { periodic, frame_length, center, }?: { + periodic?: boolean; + frame_length?: number; + center?: boolean; +}): Float64Array; +//# sourceMappingURL=audio.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts.map new file mode 100644 index 000000000..b5df9ec03 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/audio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"audio.d.ts","sourceRoot":"","sources":["../../src/utils/audio.js"],"names":[],"mappings":"AAkBA;;;;;GAKG;AACH,gCAJW,MAAM,GAAC,GAAG,iBACV,MAAM,GACJ,QAAQ,YAAY,CAAC,CAuDjC;AAED;;;;;GAKG;AACH,2BAHW,MAAM,GACJ,YAAY,CAiBxB;AAqGD;;;;;;;;;;;;;;;;GAgBG;AACH,oDAZW,MAAM,mBACN,MAAM,iBACN,MAAM,iBACN,MAAM,iBACN,MAAM,SACN,MAAM,cACN,MAAM,+BACN,OAAO,GAEL,MAAM,EAAE,EAAE,CAkDtB;AAqHD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,sCApCW,YAAY,GAAC,YAAY,UACzB,YAAY,GAAC,YAAY,gBAEzB,MAAM,cACN,MAAM;IAEW,UAAU,GAA3B,MAAM;IAEW,KAAK,GAAtB,MAAM;IACY,MAAM,GAAxB,OAAO;IAEU,QAAQ,GAAzB,MAAM;IAEY,QAAQ,GAA1B,OAAO;IAEU,WAAW,GAA5B,MAAM;IACe,WAAW,GAAhC,MAAM,EAAE,EAAE;IAEO,SAAS,GAA1B,MAAM;IACW,OAAO,GAAxB,MAAM;IAGW,SAAS,GAA1B,MAAM;IAEW,SAAS,GAA1B,MAAM;IAGW,QAAQ,GAAzB,MAAM;IAEY,gBAAgB,GAAlC,OAAO;IAEU,cAAc,GAA/B,MAAM;IACY,MAAM,GAAxB,OAAO;IACW,SAAS,GAA3B,OAAO;;UACE,YAAY;UAAQ,MAAM,EAAE;EA8L/C;AAED;;;;;;;;;;GAUG;AACH,+CATW,MAAM,QACN,MAAM;IAEY,QAAQ,GAA1B,OAAO;IACU,YAAY,GAA7B,MAAM;IAEY,MAAM,GAAxB,OAAO;IACL,YAAY,CA+BxB"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts new file mode 100644 index 000000000..6d5e7e0c0 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts @@ -0,0 +1,99 @@ +/** + * @file Core utility functions/classes for Transformers.js. + * + * These are only used internally, meaning an end-user shouldn't + * need to access anything here. + * + * @module utils/core + */ +/** + * Helper function to dispatch progress callbacks. + * + * @param {Function} progress_callback The progress callback function to dispatch. + * @param {any} data The data to pass to the progress callback function. + * @returns {void} + * @private + */ +export function dispatchCallback(progress_callback: Function, data: any): void; +/** + * Reverses the keys and values of an object. + * + * @param {Object} data The object to reverse. + * @returns {Object} The reversed object. + * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript + */ +export function reverseDictionary(data: any): any; +/** + * Escapes regular expression special characters from a string by replacing them with their escaped counterparts. + * + * @param {string} string The string to escape. + * @returns {string} The escaped string. + */ +export function escapeRegExp(string: string): string; +/** + * Check if a value is a typed array. + * @param {*} val The value to check. + * @returns {boolean} True if the value is a `TypedArray`, false otherwise. + * + * Adapted from https://stackoverflow.com/a/71091338/13989043 + */ +export function isTypedArray(val: any): boolean; +/** + * Check if a value is an integer. + * @param {*} x The value to check. + * @returns {boolean} True if the value is a string, false otherwise. + */ +export function isIntegralNumber(x: any): boolean; +/** + * Check if a value is exists. + * @param {*} x The value to check. + * @returns {boolean} True if the value exists, false otherwise. + */ +export function exists(x: any): boolean; +/** + * Calculates the dimensions of a nested array. + * + * @param {any[]} arr The nested array to calculate dimensions for. + * @returns {number[]} An array containing the dimensions of the input array. + */ +export function calculateDimensions(arr: any[]): number[]; +/** + * Replicate python's .pop() method for objects. + * @param {Object} obj The object to pop from. + * @param {string} key The key to pop. + * @param {*} defaultValue The default value to return if the key does not exist. + * @returns {*} The value of the popped key. + * @throws {Error} If the key does not exist and no default value is provided. + */ +export function pop(obj: any, key: string, defaultValue?: any): any; +/** + * Efficiently merge arrays, creating a new copy. + * Adapted from https://stackoverflow.com/a/6768642/13989043 + * @param {Array[]} arrs Arrays to merge. + * @returns {Array} The merged array. + */ +export function mergeArrays(...arrs: any[][]): any[]; +/** + * Compute the Cartesian product of given arrays + * @param {...Array} a Arrays to compute the product + * @returns {Array} Returns the computed Cartesian product as an array + * @private + */ +export function product(...a: any[][]): any[]; +/** + * Calculates the index offset for a given index and window size. + * @param {number} i The index. + * @param {number} w The window size. + * @returns {number} The index offset. + */ +export function calculateReflectOffset(i: number, w: number): number; +/** + * A base class for creating callable objects. + * + * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}} + */ +export const Callable: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +//# sourceMappingURL=core.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts.map new file mode 100644 index 000000000..4c54845cc --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/utils/core.js"],"names":[],"mappings":"AACA;;;;;;;GAOG;AAEH;;;;;;;GAOG;AACH,oEAJW,GAAG,GACD,IAAI,CAKhB;AAED;;;;;;GAMG;AACH,kDAGC;AAED;;;;;GAKG;AACH,qCAHW,MAAM,GACJ,MAAM,CAIlB;AAoCD;;;;;;GAMG;AACH,wCAJa,OAAO,CAMnB;AAGD;;;;GAIG;AACH,0CAFa,OAAO,CAInB;AAED;;;;GAIG;AACH,gCAFa,OAAO,CAInB;AAED;;;;;GAKG;AACH,yCAHW,GAAG,EAAE,GACH,MAAM,EAAE,CAUpB;AAED;;;;;;;GAOG;AACH,mCALW,MAAM,2BAehB;AAED;;;;;GAKG;AACH,qCAHY,OAAO,SAKlB;AAED;;;;;GAKG;AACH,8CAIC;AAED;;;;;GAKG;AACH,0CAJW,MAAM,KACN,MAAM,GACJ,MAAM,CAIlB;AAlID;;;;GAIG;AACH;cAF+B,GAAG,EAAE,GAAG,GAAG;mBAAiB,GAAG,EAAE,GAAG,GAAG;EA6BnE"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts new file mode 100644 index 000000000..1741f75a2 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts @@ -0,0 +1,224 @@ +/** + * @file Custom data structures. + * + * These are only used internally, meaning an end-user shouldn't + * need to access anything here. + * + * @module utils/data-structures + */ +/** + * Efficient Heap-based Implementation of a Priority Queue. + * It uses an array-based binary heap, where the root is at index `0`, and the + * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively. + * + * Adapted from the following sources: + * - https://stackoverflow.com/a/42919752/13989043 (original) + * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements) + */ +export class PriorityQueue { + /** + * Create a new PriorityQueue. + * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap. + */ + constructor(comparator?: Function); + _heap: any[]; + _comparator: Function; + /** + * The size of the queue + */ + get size(): number; + /** + * Check if the queue is empty. + * @returns {boolean} `true` if the queue is empty, `false` otherwise. + */ + isEmpty(): boolean; + /** + * Return the element with the highest priority in the queue. + * @returns {any} The highest priority element in the queue. + */ + peek(): any; + /** + * Add one or more elements to the queue. + * @param {...any} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + push(...values: any[]): number; + /** + * Add multiple elements to the queue. + * @param {any[]} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + extend(values: any[]): number; + /** + * Remove and return the element with the highest priority in the queue. + * @returns {any} The element with the highest priority in the queue. + */ + pop(): any; + /** + * Replace the element with the highest priority in the queue with a new value. + * @param {*} value The new value. + * @returns {*} The replaced value. + */ + replace(value: any): any; + /** + * Compute the index for the parent of the node at index `i`. + * @param {number} i The index of the node to get the parent of. + * @returns {number} The index of the parent node. + * @private + */ + private _parent; + /** + * Compute the index for the left child of the node at index `i`. + * @param {number} i The index of the node to get the left child of. + * @returns {number} The index of the left child. + * @private + */ + private _left; + /** + * Compute the index for the right child of the node at index `i`. + * @param {number} i The index of the node to get the right child of. + * @returns {number} The index of the right child. + * @private + */ + private _right; + /** + * Check if the element at index `i` is greater than the element at index `j`. + * @param {number} i The index of the first element to compare. + * @param {number} j The index of the second element to compare. + * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. + * @private + */ + private _greater; + /** + * Swap the elements at indices `i` and `j`. + * @param {number} i The index of the first element to swap. + * @param {number} j The index of the second element to swap. + * @private + */ + private _swap; + /** + * Maintain the heap property by updating positions in the heap, + * starting at the last element and moving up the heap. + * @private + */ + private _siftUp; + /** + * Maintain the heap property by updating positions in the heap, + * starting at the first element and moving down the heap. + * @private + */ + private _siftDown; +} +/** + * A trie structure to efficiently store and search for strings. + */ +export class CharTrie { + root: CharTrieNode; + /** + * Adds one or more `texts` to the trie. + * @param {string[]} texts The strings to add to the trie. + */ + extend(texts: string[]): void; + /** + * Adds text to the trie. + * @param {string} text The string to add to the trie. + */ + push(text: string): void; + /** + * Searches the trie for all strings with a common prefix of `text`. + * @param {string} text The common prefix to search for. + * @yields {string} Each string in the trie that has `text` as a prefix. + */ + commonPrefixSearch(text: string): Generator; +} +/** + * A lattice data structure to be used for tokenization. + */ +export class TokenLattice { + /** + * Creates a new TokenLattice instance. + * + * @param {string} sentence The input sentence to be tokenized. + * @param {number} bosTokenId The beginning-of-sequence token ID. + * @param {number} eosTokenId The end-of-sequence token ID. + */ + constructor(sentence: string, bosTokenId: number, eosTokenId: number); + sentence: string; + len: number; + bosTokenId: number; + eosTokenId: number; + nodes: TokenLatticeNode[]; + beginNodes: any[][]; + endNodes: any[][]; + /** + * Inserts a new token node into the token lattice. + * + * @param {number} pos The starting position of the token. + * @param {number} length The length of the token. + * @param {number} score The score of the token. + * @param {number} tokenId The token ID of the token. + */ + insert(pos: number, length: number, score: number, tokenId: number): void; + /** + * Implements the Viterbi algorithm to compute the most likely sequence of tokens. + * + * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens. + */ + viterbi(): TokenLatticeNode[]; + /** + * @param {TokenLatticeNode} node + * @returns {string} The array of nodes representing the most likely sequence of tokens. + */ + piece(node: TokenLatticeNode): string; + /** + * @returns {Array} The array of nodes representing the most likely sequence of tokens. + */ + tokens(): any[]; + /** + * @returns {Array} The array of nodes representing the most likely sequence of tokens. + */ + tokenIds(): any[]; +} +/** + * Represents a node in a character trie. + */ +declare class CharTrieNode { + /** + * Returns a new `CharTrieNode` instance with default values. + * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. + */ + static default(): CharTrieNode; + /** + * Create a new CharTrieNode. + * @param {boolean} isLeaf Whether the node is a leaf node or not. + * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. + */ + constructor(isLeaf: boolean, children: Map); + isLeaf: boolean; + children: Map; +} +declare class TokenLatticeNode { + /** + * Represents a node in a token lattice for a given sentence. + * @param {number} tokenId The ID of the token associated with this node. + * @param {number} nodeId The ID of this node. + * @param {number} pos The starting position of the token in the sentence. + * @param {number} length The length of the token. + * @param {number} score The score associated with the token. + */ + constructor(tokenId: number, nodeId: number, pos: number, length: number, score: number); + tokenId: number; + nodeId: number; + pos: number; + length: number; + score: number; + prev: any; + backtraceScore: number; + /** + * Returns a clone of this node. + * @returns {TokenLatticeNode} A clone of this node. + */ + clone(): TokenLatticeNode; +} +export {}; +//# sourceMappingURL=data-structures.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts.map new file mode 100644 index 000000000..66b9a21b0 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/data-structures.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"data-structures.d.ts","sourceRoot":"","sources":["../../src/utils/data-structures.js"],"names":[],"mappings":"AACA;;;;;;;GAOG;AAGH;;;;;;;;GAQG;AACH;IAEI;;;OAGG;IACH,mCAGC;IAFG,aAAe;IACf,sBAA6B;IAGjC;;OAEG;IACH,mBAEC;IAED;;;OAGG;IACH,WAFa,OAAO,CAInB;IAED;;;OAGG;IACH,QAFa,GAAG,CAIf;IAED;;;;OAIG;IACH,gBAHe,GAAG,KACL,MAAM,CAIlB;IAED;;;;OAIG;IACH,eAHW,GAAG,EAAE,GACH,MAAM,CAQlB;IAED;;;OAGG;IACH,OAFa,GAAG,CAWf;IAED;;;;OAIG;IACH,yBAKC;IAED;;;;;OAKG;IACH,gBAEC;IAED;;;;;OAKG;IACH,cAEC;IAED;;;;;OAKG;IACH,eAEC;IAED;;;;;;OAMG;IACH,iBAEC;IAED;;;;;OAKG;IACH,cAIC;IAED;;;;OAIG;IACH,gBAMC;IACD;;;;OAIG;IACH,kBAYC;CACJ;AAED;;GAEG;AACH;IAEQ,mBAAkC;IAGtC;;;OAGG;IACH,cAFW,MAAM,EAAE,QAMlB;IAED;;;OAGG;IACH,WAFW,MAAM,QAahB;IAED;;;;OAIG;IACH,yBAHW,MAAM,oCAchB;CACJ;AAyBD;;GAEG;AACH;IACI;;;;;;OAMG;IACH,sBAJW,MAAM,cACN,MAAM,cACN,MAAM,EAiBhB;IAdG,iBAAwB;IACxB,YAA0B;IAC1B,mBAA4B;IAC5B,mBAA4B;IAC5B,0BAAe;IACf,oBAAgE;IAChE,kBAA8D;IAUlE;;;;;;;OAOG;IACH,YALW,MAAM,UACN,MAAM,SACN,MAAM,WACN,MAAM,QAQhB;IAED;;;;OAIG;IACH,WAFa,gBAAgB,EAAE,CA+C9B;IAED;;;OAGG;IACH,YAHW,gBAAgB,GACd,MAAM,CAIlB;IAED;;OAEG;IACH,gBAGC;IAED;;OAEG;IACH,kBAGC;CACJ;AA9ID;;GAEG;AACH;IAWI;;;OAGG;IACH,kBAFa,YAAY,CAIxB;IAhBD;;;;OAIG;IACH,oBAHW,OAAO,YACP,IAAI,MAAM,EAAE,YAAY,CAAC,EAKnC;IAFG,gBAAoB;IACpB,oCAAwB;CAU/B;AA0HD;IACI;;;;;;;OAOG;IACH,qBANW,MAAM,UACN,MAAM,OACN,MAAM,UACN,MAAM,SACN,MAAM,EAUhB;IAPG,gBAAsB;IACtB,eAAoB;IACpB,YAAc;IACd,eAAoB;IACpB,cAAkB;IAClB,UAAgB;IAChB,uBAAyB;IAG7B;;;OAGG;IACH,SAFa,gBAAgB,CAO5B;CACJ"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts new file mode 100644 index 000000000..1688d6a6d --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts @@ -0,0 +1,593 @@ +declare const LogitsProcessorList_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * A class representing a list of logits processors. A logits processor is a function that modifies the logits + * output of a language model. This class provides methods for adding new processors and applying all processors to a + * batch of logits. + * + * @extends Callable + */ +export class LogitsProcessorList extends LogitsProcessorList_base { + processors: any[]; + /** + * Adds a new logits processor to the list. + * + * @param {LogitsProcessor} item The logits processor function to add. + */ + push(item: LogitsProcessor): void; + /** + * Adds multiple logits processors to the list. + * + * @param {LogitsProcessor[]} items The logits processor functions to add. + */ + extend(items: LogitsProcessor[]): void; + /** + * Applies all logits processors in the list to a batch of logits, modifying them in-place. + * + * @param {number[]} input_ids The input IDs for the language model. + * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single + * input sequence in the batch. + */ + _call(input_ids: number[], batchedLogits: number[][]): void; + [Symbol.iterator](): IterableIterator; +} +declare const LogitsProcessor_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * Base class for processing logits. + * @extends Callable + */ +export class LogitsProcessor extends LogitsProcessor_base { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {Array} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids: any[], logits: Tensor): void; +} +/** + * A logits processor that forces a specific token to be generated by the decoder. + * + * @extends LogitsProcessor + */ +export class ForceTokensLogitsProcessor extends LogitsProcessor { + /** + * Constructs a new instance of `ForceTokensLogitsProcessor`. + * + * @param {Array} forced_decoder_ids The ids of tokens that should be forced. + */ + constructor(forced_decoder_ids: any[]); + force_token_map: { + [k: string]: any; + }; + /** + * Apply the processor to the input logits. + * + * @param {Array} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @returns {Tensor} The processed logits. + */ + _call(input_ids: any[], logits: Tensor): Tensor; +} +/** + * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence. + * @extends LogitsProcessor + */ +export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedBOSTokenLogitsProcessor. + * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. + */ + constructor(bos_token_id: number); + bos_token_id: number; + /** + * Apply the BOS token forcing to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with BOS token forcing. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * A logits processor that forces end-of-sequence token probability to 1. + * + * @extends LogitsProcessor + */ +export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedEOSTokenLogitsProcessor. + * @param {number} max_length Max length of the sequence. + * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced. + */ + constructor(max_length: number, forced_eos_token_id: number | number[]); + max_length: number; + forced_eos_token_id: number | number[]; + /** + * Apply the processor to input_ids and logits. + * + * @param {number[]} input_ids The input ids. + * @param {Tensor} logits The logits tensor. + */ + _call(input_ids: number[], logits: Tensor): void; +} +/** + * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts + * generating using `begin_index` tokens. This should ensure that the tokens defined by + * `begin_suppress_tokens` at not sampled at the begining of the generation. + * @extends LogitsProcessor + */ +export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { + /** + * Create a SuppressTokensAtBeginLogitsProcessor. + * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. + * @param {number} begin_index The number of tokens to generate before suppressing tokens. + */ + constructor(begin_suppress_tokens: number[], begin_index: number); + begin_suppress_tokens: number[]; + begin_index: number; + /** + * Apply the BOS token forcing to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with BOS token forcing. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * A LogitsProcessor that handles adding timestamps to generated text. + * @extends LogitsProcessor + */ +export class WhisperTimeStampLogitsProcessor extends LogitsProcessor { + /** + * Constructs a new WhisperTimeStampLogitsProcessor. + * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model. + * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token. + * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp. + * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp. + * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear. + */ + constructor(generate_config: { + eos_token_id: number; + no_timestamps_token_id: number; + forced_decoder_ids?: number[][]; + max_initial_timestamp_index?: number; + }); + eos_token_id: number; + no_timestamps_token_id: number; + timestamp_begin: number; + begin_index: number; + max_initial_timestamp_index: number; + /** + * Modify the logits to handle timestamp tokens. + * @param {Array} input_ids The input sequence of tokens. + * @param {Tensor} logits The logits output by the model. + * @returns {Tensor} The modified logits. + */ + _call(input_ids: any[], logits: Tensor): Tensor; +} +/** + * A logits processor that disallows ngrams of a certain size to be repeated. + * + * @extends LogitsProcessor + */ +export class NoRepeatNGramLogitsProcessor extends LogitsProcessor { + /** + * Create a NoRepeatNGramLogitsProcessor. + * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. + */ + constructor(no_repeat_ngram_size: number); + no_repeat_ngram_size: number; + /** + * Generate n-grams from a sequence of token ids. + * @param {number[]} prevInputIds List of previous input ids + * @returns {Map} Map of generated n-grams + */ + getNgrams(prevInputIds: number[]): Map; + /** + * Generate n-grams from a sequence of token ids. + * @param {Map} bannedNgrams Map of banned n-grams + * @param {number[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + getGeneratedNgrams(bannedNgrams: Map, prevInputIds: number[]): number[]; + /** + * Calculate banned n-gram tokens + * @param {number[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + calcBannedNgramTokens(prevInputIds: number[]): number[]; + /** + * Apply the no-repeat-ngram processor to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with no-repeat-ngram processing. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * A logits processor that penalises repeated output tokens. + * + * @extends LogitsProcessor + */ +export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { + /** + * Create a RepetitionPenaltyLogitsProcessor. + * @param {number} penalty The penalty to apply for repeated tokens. + */ + constructor(penalty: number); + penalty: number; + /** + * Apply the repetition penalty to the logits. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The logits with repetition penalty processing. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * A logits processor that enforces a minimum number of tokens. + * + * @extends LogitsProcessor + */ +export class MinLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinLengthLogitsProcessor. + * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(min_length: number, eos_token_id: number | number[]); + min_length: number; + eos_token_id: number[]; + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * A logits processor that enforces a minimum number of new tokens. + * + * @extends LogitsProcessor + */ +export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinNewTokensLengthLogitsProcessor. + * @param {number} prompt_length_to_skip The input tokens length. + * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(prompt_length_to_skip: number, min_new_tokens: number, eos_token_id: number | number[]); + prompt_length_to_skip: number; + min_new_tokens: number; + eos_token_id: number[]; + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids: any[], logits: any): any; +} +export class NoBadWordsLogitsProcessor extends LogitsProcessor { + /** + * Create a `NoBadWordsLogitsProcessor`. + * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. + * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(bad_words_ids: number[][], eos_token_id: number | number[]); + bad_words_ids: number[][]; + eos_token_id: number[]; + /** + * Apply logit processor. + * @param {Array} input_ids The input IDs. + * @param {Object} logits The logits. + * @returns {Object} The processed logits. + */ + _call(input_ids: any[], logits: any): any; +} +/** + * @typedef {Object} GenerationConfigType The default configuration parameters. + * @property {number} [max_length=20] The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set. + * @property {number} [max_new_tokens=null] The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @property {number} [min_length=0] The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set. + * @property {number} [min_new_tokens=null] The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @property {boolean|"never"} [early_stopping=false] Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: + * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; + * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; + * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). + * @property {number} [max_time=null] The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed. + * + * @property {boolean} [do_sample=false] Whether or not to use sampling; use greedy decoding otherwise. + * @property {number} [num_beams=1] Number of beams for beam search. 1 means no beam search. + * @property {number} [num_beam_groups=1] Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details. + * @property {number} [penalty_alpha=null] The values balance the model confidence and the degeneration penalty in contrastive search decoding. + * @property {boolean} [use_cache=true] Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. + * + * @property {number} [temperature=1.0] The value used to modulate the next token probabilities. + * @property {number} [top_k=50] The number of highest probability vocabulary tokens to keep for top-k-filtering. + * @property {number} [top_p=1.0] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. + * @property {number} [typical_p=1.0] Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details. + * @property {number} [epsilon_cutoff=0.0] If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + * @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + * @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled. + * @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + * @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. + * @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. + * @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once. + * @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`. + * @property {number[][]|number[][][]} [force_words_ids=null] List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. + * @property {boolean} [renormalize_logits=false] Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. + * @property {Object[]} [constraints=null] Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. + * + * @property {number} [forced_bos_token_id=null] The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token. + * @property {number|number[]} [forced_eos_token_id=null] The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens. + * @property {boolean} [remove_invalid_values=false] Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. + * @property {number[]} [exponential_decay_length_penalty=null] This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. + * @property {number[]} [suppress_tokens=null] A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @property {number[]} [begin_suppress_tokens=null] A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @property {number[][]} [forced_decoder_ids=null] A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123. + * + * @property {number} [num_return_sequences=1] The number of independently computed returned sequences for each element in the batch. + * @property {boolean} [output_attentions=false] Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details. + * @property {boolean} [output_hidden_states=false] Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details. + * @property {boolean} [output_scores=false] Whether or not to return the prediction scores. See `scores` under returned tensors for more details. + * @property {boolean} [return_dict_in_generate=false] Whether or not to return a `ModelOutput` instead of a plain tuple. + * + * @property {number} [pad_token_id=null] The id of the *padding* token. + * @property {number} [bos_token_id=null] The id of the *beginning-of-sequence* token. + * @property {number|number[]} [eos_token_id=null] The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + * + * @property {number} [encoder_no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. + * @property {number} [decoder_start_token_id=null] If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. + * + * @property {Object} [generation_kwargs={}] Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass. + */ +/** + * Class that holds a configuration for a generation task. + * @type {new (kwargs?: GenerationConfigType) => GenerationConfigType} + */ +export const GenerationConfig: new (kwargs?: GenerationConfigType) => GenerationConfigType; +declare const Sampler_base: new () => { + (...args: any[]): any; + _call(...args: any[]): any; +}; +/** + * Sampler is a base class for all sampling methods used for text generation. + */ +export class Sampler extends Sampler_base { + /** + * Returns a Sampler object based on the specified options. + * @param {GenerationConfigType} generation_config An object containing options for the sampler. + * @returns {Sampler} A Sampler object. + */ + static getSampler(generation_config: GenerationConfigType): Sampler; + /** + * Creates a new Sampler object with the specified generation config. + * @param {GenerationConfigType} generation_config The generation config. + */ + constructor(generation_config: GenerationConfigType); + generation_config: GenerationConfigType; + /** + * Executes the sampler, using the specified logits. + * @param {Tensor} logits + * @param {number} index + * @returns {void} + */ + _call(logits: Tensor, index?: number): void; + /** + * Abstract method for sampling the logits. + * @param {Tensor} logits + * @param {number} index + * @throws {Error} + */ + sample(logits: Tensor, index: number): void; + /** + * Returns the specified logits as an array, with temperature applied. + * @param {Tensor} logits + * @param {number} index + * @returns {Float32Array} + */ + getLogits(logits: Tensor, index: number): Float32Array; + /** + * Selects an item randomly based on the specified probabilities. + * @param {Array} probabilities An array of probabilities to use for selection. + * @returns {number} The index of the selected item. + */ + randomSelect(probabilities: any[]): number; +} +/** + * The default configuration parameters. + */ +export type GenerationConfigType = { + /** + * The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set. + */ + max_length?: number; + /** + * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. + */ + max_new_tokens?: number; + /** + * The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set. + */ + min_length?: number; + /** + * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. + */ + min_new_tokens?: number; + /** + * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: + * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; + * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; + * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). + */ + early_stopping?: boolean | "never"; + /** + * The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed. + */ + max_time?: number; + /** + * Whether or not to use sampling; use greedy decoding otherwise. + */ + do_sample?: boolean; + /** + * Number of beams for beam search. 1 means no beam search. + */ + num_beams?: number; + /** + * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details. + */ + num_beam_groups?: number; + /** + * The values balance the model confidence and the degeneration penalty in contrastive search decoding. + */ + penalty_alpha?: number; + /** + * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. + */ + use_cache?: boolean; + /** + * The value used to modulate the next token probabilities. + */ + temperature?: number; + /** + * The number of highest probability vocabulary tokens to keep for top-k-filtering. + */ + top_k?: number; + /** + * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. + */ + top_p?: number; + /** + * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details. + */ + typical_p?: number; + /** + * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + */ + epsilon_cutoff?: number; + /** + * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. + */ + eta_cutoff?: number; + /** + * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled. + */ + diversity_penalty?: number; + /** + * The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + */ + repetition_penalty?: number; + /** + * The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. + */ + encoder_repetition_penalty?: number; + /** + * Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. + */ + length_penalty?: number; + /** + * If set to int > 0, all ngrams of that size can only occur once. + */ + no_repeat_ngram_size?: number; + /** + * List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`. + */ + bad_words_ids?: number[][]; + /** + * List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. + */ + force_words_ids?: number[][] | number[][][]; + /** + * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. + */ + renormalize_logits?: boolean; + /** + * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. + */ + constraints?: any[]; + /** + * The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token. + */ + forced_bos_token_id?: number; + /** + * The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + forced_eos_token_id?: number | number[]; + /** + * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. + */ + remove_invalid_values?: boolean; + /** + * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. + */ + exponential_decay_length_penalty?: number[]; + /** + * A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + */ + suppress_tokens?: number[]; + /** + * A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + */ + begin_suppress_tokens?: number[]; + /** + * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123. + */ + forced_decoder_ids?: number[][]; + /** + * The number of independently computed returned sequences for each element in the batch. + */ + num_return_sequences?: number; + /** + * Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details. + */ + output_attentions?: boolean; + /** + * Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details. + */ + output_hidden_states?: boolean; + /** + * Whether or not to return the prediction scores. See `scores` under returned tensors for more details. + */ + output_scores?: boolean; + /** + * Whether or not to return a `ModelOutput` instead of a plain tuple. + */ + return_dict_in_generate?: boolean; + /** + * The id of the *padding* token. + */ + pad_token_id?: number; + /** + * The id of the *beginning-of-sequence* token. + */ + bos_token_id?: number; + /** + * The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + eos_token_id?: number | number[]; + /** + * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. + */ + encoder_no_repeat_ngram_size?: number; + /** + * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. + */ + decoder_start_token_id?: number; + /** + * Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass. + */ + generation_kwargs?: any; +}; +import { Tensor } from './tensor.js'; +export {}; +//# sourceMappingURL=generation.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts.map new file mode 100644 index 000000000..62e720b5f --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/generation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"generation.d.ts","sourceRoot":"","sources":["../../src/utils/generation.js"],"names":[],"mappings":";;;;AAoBA;;;;;;GAMG;AACH;IAMQ,kBAAoB;IAGxB;;;;OAIG;IACH,WAFW,eAAe,QAIzB;IAED;;;;OAIG;IACH,cAFW,eAAe,EAAE,QAI3B;IAED;;;;;;OAMG;IACH,iBAJW,MAAM,EAAE,iBACR,MAAM,EAAE,EAAE,QAYpB;IAED,2CAEC;CACJ;;;;;AAED;;;GAGG;AACH;IACI;;;;;;;OAOG;IACH,gCAHW,MAAM,QAKhB;CACJ;AAED;;;;GAIG;AACH;IACI;;;;OAIG;IACH,uCAGC;IADG;;MAAmE;IAGvE;;;;;;OAMG;IACH,gCAHW,MAAM,GACJ,MAAM,CASlB;CACJ;AAED;;;GAGG;AACH;IACI;;;OAGG;IACH,0BAFW,MAAM,EAKhB;IADG,qBAAgC;IAGpC;;;;;OAKG;IACH,0CAMC;CACJ;AAED;;;;GAIG;AACH;IACI;;;;OAIG;IACH,wBAHW,MAAM,uBACN,MAAM,GAAC,MAAM,EAAE,EAMzB;IAFG,mBAA4B;IAC5B,uCAA8C;IAGlD;;;;;OAKG;IACH,iBAHW,MAAM,EAAE,UACR,MAAM,QAKhB;CACJ;AAED;;;;;GAKG;AACH;IACI;;;;OAIG;IACH,mCAHW,MAAM,EAAE,eACR,MAAM,EAMhB;IAFG,gCAAkD;IAClD,oBAA8B;IAGlC;;;;;OAKG;IACH,0CAOC;CACJ;AAED;;;GAGG;AACH;IACI;;;;;;;OAOG;IACH;QALmC,YAAY,EAApC,MAAM;QACkB,sBAAsB,EAA9C,MAAM;QACuB,kBAAkB,GAA/C,MAAM,EAAE,EAAE;QACe,2BAA2B,GAApD,MAAM;OAchB;IAVG,qBAAgD;IAChD,+BAAoE;IACpE,wBAAsD;IAEtD,oBAAwE;IAIxE,oCAA8E;IAIlF;;;;;OAKG;IACH,gCAHW,MAAM,GACJ,MAAM,CA2ClB;CACJ;AAED;;;;GAIG;AACH;IACI;;;OAGG;IACH,kCAFW,MAAM,EAKhB;IADG,6BAAgD;IAGpD;;;;OAIG;IACH,wBAHW,MAAM,EAAE,GACN,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC,CAyBjC;IAED;;;;;OAKG;IACH,iCAJW,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC,gBACrB,MAAM,EAAE,GACN,MAAM,EAAE,CAMpB;IAED;;;;OAIG;IACH,oCAHW,MAAM,EAAE,GACN,MAAM,EAAE,CAapB;IAED;;;;;OAKG;IACH,0CAOC;CACJ;AAED;;;;GAIG;AACH;IACI;;;OAGG;IACH,qBAFW,MAAM,EAKhB;IADG,gBAAsB;IAG1B;;;;;OAKG;IACH,0CAYC;CACJ;AAED;;;;GAIG;AACH;IACI;;;;OAIG;IACH,wBAHW,MAAM,gBACN,MAAM,GAAC,MAAM,EAAE,EAMzB;IAFG,mBAA4B;IAC5B,uBAA+E;IAGnF;;;;;OAKG;IACH,0CAQC;CACJ;AAED;;;;GAIG;AACH;IACI;;;;;OAKG;IACH,mCAJW,MAAM,kBACN,MAAM,gBACN,MAAM,GAAC,MAAM,EAAE,EAOzB;IAHG,8BAAkD;IAClD,uBAAoC;IACpC,uBAA+E;IAGnF;;;;;OAKG;IACH,0CASC;CACJ;AAED;IACI;;;;OAIG;IACH,2BAHW,MAAM,EAAE,EAAE,gBACV,MAAM,GAAC,MAAM,EAAE,EAMzB;IAFG,0BAAkC;IAClC,uBAA+E;IAGnF;;;;;OAKG;IACH,0CAsBC;CACJ;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AAEH;;;GAGG;AACH,6CAFwB,oBAAoB,KAAK,oBAAoB,CAmElE;;;;;AAEH;;GAEG;AACH;IA4EI;;;;OAIG;IACH,qCAHW,oBAAoB,GAClB,OAAO,CAwBnB;IAtGD;;;OAGG;IACH,+BAFW,oBAAoB,EAK9B;IADG,wCAA0C;IAG9C;;;;;OAKG;IACH,cAJW,MAAM,UACN,MAAM,GACJ,IAAI,CAMhB;IAED;;;;;OAKG;IACH,eAJW,MAAM,SACN,MAAM,QAKhB;IAED;;;;;OAKG;IACH,kBAJW,MAAM,SACN,MAAM,GACJ,YAAY,CAmBxB;IAED;;;;OAIG;IACH,oCAFa,MAAM,CAclB;CA8BJ;;;;;;;;iBA1Oa,MAAM;;;;qBACN,MAAM;;;;iBACN,MAAM;;;;qBACN,MAAM;;;;;;;qBACN,OAAO,GAAC,OAAO;;;;eAIf,MAAM;;;;gBAEN,OAAO;;;;gBACP,MAAM;;;;sBACN,MAAM;;;;oBACN,MAAM;;;;gBACN,OAAO;;;;kBAEP,MAAM;;;;YACN,MAAM;;;;YACN,MAAM;;;;gBACN,MAAM;;;;qBACN,MAAM;;;;iBACN,MAAM;;;;wBACN,MAAM;;;;yBACN,MAAM;;;;iCACN,MAAM;;;;qBACN,MAAM;;;;2BACN,MAAM;;;;oBACN,MAAM,EAAE,EAAE;;;;sBACV,MAAM,EAAE,EAAE,GAAC,MAAM,EAAE,EAAE,EAAE;;;;yBACvB,OAAO;;;;kBACP,KAAQ;;;;0BAER,MAAM;;;;0BACN,MAAM,GAAC,MAAM,EAAE;;;;4BACf,OAAO;;;;uCACP,MAAM,EAAE;;;;sBACR,MAAM,EAAE;;;;4BACR,MAAM,EAAE;;;;yBACR,MAAM,EAAE,EAAE;;;;2BAEV,MAAM;;;;wBACN,OAAO;;;;2BACP,OAAO;;;;oBACP,OAAO;;;;8BACP,OAAO;;;;mBAEP,MAAM;;;;mBACN,MAAM;;;;mBACN,MAAM,GAAC,MAAM,EAAE;;;;mCAEf,MAAM;;;;6BACN,MAAM;;;;;;uBAvkBG,aAAa"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts new file mode 100644 index 000000000..cfd26cbf7 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts @@ -0,0 +1,154 @@ +/** + * Helper function to get a file, using either the Fetch API or FileSystem API. + * + * @param {URL|string} urlOrPath The URL/path of the file to get. + * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API). + */ +export function getFile(urlOrPath: URL | string): Promise; +/** + * + * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API. + * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached. + * + * @param {string} path_or_repo_id This can be either: + * - a string, the *model id* of a model repo on huggingface.co. + * - a path to a *directory* potentially containing the file. + * @param {string} filename The name of the file to locate in `path_or_repo`. + * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. + * @param {PretrainedOptions} [options] An object containing optional parameters. + * + * @throws Will throw an error if the file is not found and `fatal` is true. + * @returns {Promise} A Promise that resolves with the file content as a buffer. + */ +export function getModelFile(path_or_repo_id: string, filename: string, fatal?: boolean, options?: PretrainedOptions): Promise; +/** + * Fetches a JSON file from a given path and file name. + * + * @param {string} modelPath The path to the directory containing the file. + * @param {string} fileName The name of the file to fetch. + * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. + * @param {PretrainedOptions} [options] An object containing optional parameters. + * @returns {Promise} The JSON data parsed into a JavaScript object. + * @throws Will throw an error if the file is not found and `fatal` is true. + */ +export function getModelJSON(modelPath: string, fileName: string, fatal?: boolean, options?: PretrainedOptions): Promise; +/** + * Options for loading a pretrained model. + */ +export type PretrainedOptions = { + /** + * Whether to load the 8-bit quantized version of the model (only applicable when loading model files). + */ + quantized?: boolean | null; + /** + * If specified, this function will be called during model construction, to provide the user with progress updates. + */ + progress_callback?: Function; + /** + * Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: + * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). + * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. + */ + config?: any; + /** + * Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. + */ + cache_dir?: string; + /** + * Whether or not to only look at local files (e.g., not try downloading the model). + */ + local_files_only?: boolean; + /** + * The specific model version to use. It can be a branch name, a tag name, or a commit id, + * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. + * NOTE: This setting is ignored for local requests. + */ + revision?: string; + /** + * If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models. + */ + model_file_name?: string; +}; +/** + * @typedef {Object} PretrainedOptions Options for loading a pretrained model. + * @property {boolean?} [quantized=true] Whether to load the 8-bit quantized version of the model (only applicable when loading model files). + * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates. + * @property {Object} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: + * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). + * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. + * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. + * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model). + * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id, + * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. + * NOTE: This setting is ignored for local requests. + * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models. + */ +declare class FileResponse { + /** + * Creates a new `FileResponse` object. + * @param {string|URL} filePath + */ + constructor(filePath: string | URL); + /** + * Mapping from file extensions to MIME types. + */ + _CONTENT_TYPE_MAP: { + txt: string; + html: string; + css: string; + js: string; + json: string; + png: string; + jpg: string; + jpeg: string; + gif: string; + }; + filePath: string | URL; + headers: Headers; + exists: any; + status: number; + statusText: string; + body: ReadableStream; + /** + * Updates the 'content-type' header property of the response based on the extension of + * the file specified by the filePath property of the current object. + * @returns {void} + */ + updateContentType(): void; + /** + * Clone the current FileResponse object. + * @returns {FileResponse} A new FileResponse object with the same properties as the current object. + */ + clone(): FileResponse; + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with an ArrayBuffer containing the file's contents. + * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + arrayBuffer(): Promise; + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a Blob containing the file's contents. + * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + blob(): Promise; + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a string containing the file's contents. + * @returns {Promise} A Promise that resolves with a string containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + text(): Promise; + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a parsed JavaScript object containing the file's contents. + * + * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + json(): Promise; +} +export {}; +//# sourceMappingURL=hub.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts.map new file mode 100644 index 000000000..75192575c --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/hub.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hub.d.ts","sourceRoot":"","sources":["../../src/utils/hub.js"],"names":[],"mappings":"AA4KA;;;;;GAKG;AACH,mCAHW,GAAG,GAAC,MAAM,GACR,QAAQ,YAAY,GAAC,QAAQ,CAAC,CAgC1C;AA2GD;;;;;;;;;;;;;;GAcG;AACH,8CAVW,MAAM,YAGN,MAAM,UACN,OAAO,YACP,iBAAiB,gBA4O3B;AAED;;;;;;;;;GASG;AACH,wCAPW,MAAM,YACN,MAAM,UACN,OAAO,YACP,iBAAiB,GACf,YAAe,CAc3B;;;;;;;;gBAnjBa,OAAO;;;;;;;;;;;;;;gBAKP,MAAM;;;;uBACN,OAAO;;;;;;eACP,MAAM;;;;sBAGN,MAAM;;AAZpB;;;;;;;;;;;;;GAaG;AAEH;IAeI;;;OAGG;IACH,sBAFW,MAAM,GAAC,GAAG,EA8BpB;IA9CD;;OAEG;IACH;;;;;;;;;;MAUC;IAMG,uBAAwB;IACxB,iBAA4B;IAE5B,YAAqC;IAEjC,eAAiB;IACjB,mBAAsB;IAQtB,0BAOE;IAQV;;;;OAIG;IACH,qBAFa,IAAI,CAMhB;IAED;;;OAGG;IACH,SAFa,YAAY,CASxB;IAED;;;;;OAKG;IACH,eAHa,QAAQ,WAAW,CAAC,CAMhC;IAED;;;;;OAKG;IACH,QAHa,QAAQ,IAAI,CAAC,CAMzB;IAED;;;;;OAKG;IACH,QAHa,QAAQ,MAAM,CAAC,CAM3B;IAED;;;;;;OAMG;IACH,QAHa,YAAe,CAK3B;CACJ"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts new file mode 100644 index 000000000..cd912a7c7 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts @@ -0,0 +1,111 @@ +export class RawImage { + /** + * Helper method for reading an image from a variety of input types. + * @param {RawImage|string|URL} input + * @returns The image object. + * + * **Example:** Read image from a URL. + * ```javascript + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * // RawImage { + * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], + * // "width": 800, + * // "height": 533, + * // "channels": 3 + * // } + * ``` + */ + static read(input: RawImage | string | URL): Promise; + /** + * Read an image from a URL or file path. + * @param {string|URL} url The URL or file path to read the image from. + * @returns {Promise} The image object. + */ + static fromURL(url: string | URL): Promise; + /** + * Helper method to create a new Image from a blob. + * @param {Blob} blob The blob to read the image from. + * @returns {Promise} The image object. + */ + static fromBlob(blob: Blob): Promise; + /** + * Helper method to create a new Image from a tensor + * @param {import('./tensor.js').Tensor} tensor + */ + static fromTensor(tensor: import('./tensor.js').Tensor, channel_format?: string): RawImage; + /** + * Create a new `RawImage` object. + * @param {Uint8ClampedArray|Uint8Array} data The pixel data. + * @param {number} width The width of the image. + * @param {number} height The height of the image. + * @param {1|2|3|4} channels The number of channels. + */ + constructor(data: Uint8ClampedArray | Uint8Array, width: number, height: number, channels: 1 | 2 | 3 | 4); + data: Uint8Array | Uint8ClampedArray; + width: number; + height: number; + channels: 2 | 1 | 3 | 4; + /** + * Returns the size of the image (width, height). + * @returns {[number, number]} The size of the image (width, height). + */ + get size(): [number, number]; + /** + * Convert the image to grayscale format. + * @returns {RawImage} `this` to support chaining. + */ + grayscale(): RawImage; + /** + * Convert the image to RGB format. + * @returns {RawImage} `this` to support chaining. + */ + rgb(): RawImage; + /** + * Convert the image to RGBA format. + * @returns {RawImage} `this` to support chaining. + */ + rgba(): RawImage; + /** + * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. + * @param {number} width The width of the new image. + * @param {number} height The height of the new image. + * @param {Object} options Additional options for resizing. + * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. + * @returns {Promise} `this` to support chaining. + */ + resize(width: number, height: number, { resample, }?: { + resample?: 0 | 1 | 2 | 3 | 4 | 5 | string; + }): Promise; + pad([left, right, top, bottom]: [any, any, any, any]): Promise; + crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise; + center_crop(crop_width: any, crop_height: any): Promise; + toBlob(type?: string, quality?: number): Promise; + toCanvas(): any; + /** + * Helper method to update the image data. + * @param {Uint8ClampedArray} data The new image data. + * @param {number} width The new width of the image. + * @param {number} height The new height of the image. + * @param {1|2|3|4|null} [channels] The new number of channels of the image. + * @private + */ + private _update; + /** + * Clone the image + * @returns {RawImage} The cloned image + */ + clone(): RawImage; + /** + * Helper method for converting image to have a certain number of channels + * @param {number} numChannels The number of channels. Must be 1, 3, or 4. + * @returns {RawImage} `this` to support chaining. + */ + convert(numChannels: number): RawImage; + /** + * Save the image to the given path. + * @param {string} path The path to save the image to. + */ + save(path: string): Promise; + toSharp(): any; +} +//# sourceMappingURL=image.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts.map new file mode 100644 index 000000000..d2c91292b --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/image.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../src/utils/image.js"],"names":[],"mappings":"AA4EA;IAwBI;;;;;;;;;;;;;;;OAeG;IACH,mBAdW,QAAQ,GAAC,MAAM,GAAC,GAAG,qBAsB7B;IAGD;;;;OAIG;IACH,oBAHW,MAAM,GAAC,GAAG,GACR,QAAQ,QAAQ,CAAC,CAS7B;IAED;;;;OAIG;IACH,sBAHW,IAAI,GACF,QAAQ,QAAQ,CAAC,CAoB7B;IAED;;;OAGG;IACH,0BAFW,OAAO,aAAa,EAAE,MAAM,qCA0BtC;IApHD;;;;;;OAMG;IACH,kBALW,iBAAiB,GAAC,UAAU,SAC5B,MAAM,UACN,MAAM,YACN,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,EAOjB;IAJG,qCAAgB;IAChB,cAAkB;IAClB,eAAoB;IACpB,wBAAwB;IAG5B;;;OAGG;IACH,6BAEC;IAkGD;;;OAGG;IACH,aAFa,QAAQ,CAuBpB;IAED;;;OAGG;IACH,OAFa,QAAQ,CA6BpB;IAED;;;OAGG;IACH,QAFa,QAAQ,CA+BpB;IAED;;;;;;;OAOG;IACH,cANW,MAAM,UACN,MAAM;QAEuB,QAAQ,GAArC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,MAAM;QAChB,QAAQ,QAAQ,CAAC,CAqE7B;IAED,oEA0CC;IAED,uEAkDC;IAED,6DAiHC;IAED,sDAOC;IAED,gBAiBC;IAED;;;;;;;OAOG;IACH,gBAQC;IAED;;;OAGG;IACH,SAFa,QAAQ,CAIpB;IAED;;;;OAIG;IACH,qBAHW,MAAM,GACJ,QAAQ,CAmBpB;IAED;;;OAGG;IACH,WAFW,MAAM,gBAsChB;IAED,eAYC;CACJ"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts new file mode 100644 index 000000000..840ce70da --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts @@ -0,0 +1,277 @@ +/** + * @file Helper module for mathematical processing. + * + * These functions and classes are only used internally, + * meaning an end-user shouldn't need to access anything here. + * + * @module utils/maths + */ +/** + * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray + * @typedef {BigInt64Array | BigUint64Array} BigTypedArray + * @typedef {TypedArray | BigTypedArray} AnyTypedArray + */ +/** + * @param {TypedArray} input + */ +export function interpolate_data(input: TypedArray, [in_channels, in_height, in_width]: [any, any, any], [out_height, out_width]: [any, any], mode?: string, align_corners?: boolean): any; +/** + * Helper method to transpose a `AnyTypedArray` directly + * @template {AnyTypedArray} T + * @param {T} array + * @param {number[]} dims + * @param {number[]} axes + * @returns {[T, number[]]} The transposed array and the new shape. + */ +export function transpose_data(array: T, dims: number[], axes: number[]): [T, number[]]; +/** + * Compute the softmax of an array of numbers. + * @template {TypedArray|number[]} T + * @param {T} arr The array of numbers to compute the softmax of. + * @returns {T} The softmax array. + */ +export function softmax(arr: T): T; +/** + * Calculates the logarithm of the softmax function for the input array. + * @template {TypedArray|number[]} T + * @param {T} arr The input array to calculate the log_softmax function for. + * @returns {T} The resulting log_softmax array. + */ +export function log_softmax(arr: T): T; +/** + * Calculates the dot product of two arrays. + * @param {number[]} arr1 The first array. + * @param {number[]} arr2 The second array. + * @returns {number} The dot product of arr1 and arr2. + */ +export function dot(arr1: number[], arr2: number[]): number; +/** + * Get the top k items from an iterable, sorted by descending order + * @param {any[]|TypedArray} items The items to be sorted + * @param {number|null} [top_k=0] The number of top items to return (default: 0 = return all) + * @returns {[number, any][]} The top k items, sorted by descending order + */ +export function getTopItems(items: any[] | TypedArray, top_k?: number | null): [number, any][]; +/** + * Computes the cosine similarity between two arrays. + * + * @param {number[]} arr1 The first array. + * @param {number[]} arr2 The second array. + * @returns {number} The cosine similarity between the two arrays. + */ +export function cos_sim(arr1: number[], arr2: number[]): number; +/** + * Calculates the magnitude of a given array. + * @param {number[]} arr The array to calculate the magnitude of. + * @returns {number} The magnitude of the array. + */ +export function magnitude(arr: number[]): number; +/** + * Returns the value and index of the minimum element in an array. + * @param {number[]|TypedArray} arr array of numbers. + * @returns {number[]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin] + * @throws {Error} If array is empty. + */ +export function min(arr: number[] | TypedArray): number[]; +/** + * Returns the value and index of the maximum element in an array. + * @param {number[]|AnyTypedArray} arr array of numbers. + * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax] + * @throws {Error} If array is empty. + */ +export function max(arr: number[] | AnyTypedArray): [number, number]; +/** + * Performs median filter on the provided data. Padding is done by mirroring the data. + * @param {AnyTypedArray} data The input array + * @param {number} windowSize The window size + */ +export function medianFilter(data: AnyTypedArray, windowSize: number): any; +/** + * Helper function to round a number to a given number of decimals + * @param {number} num The number to round + * @param {number} decimals The number of decimals + * @returns {number} The rounded number + */ +export function round(num: number, decimals: number): number; +export class FFT { + constructor(fft_length: any); + fft_length: any; + isPowerOfTwo: boolean; + fft: P2FFT | NP2FFT; + outputBufferSize: number; + realTransform(out: any, input: any): void; + transform(out: any, input: any): void; +} +export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export type BigTypedArray = BigInt64Array | BigUint64Array; +export type AnyTypedArray = TypedArray | BigTypedArray; +/** + * Implementation of Radix-4 FFT. + * + * P2FFT class provides functionality for performing Fast Fourier Transform on arrays + * which are a power of two in length. + * Code adapted from https://www.npmjs.com/package/fft.js + */ +declare class P2FFT { + /** + * @param {number} size The size of the input array. Must be a power of two larger than 1. + * @throws {Error} FFT size must be a power of two larger than 1. + */ + constructor(size: number); + size: number; + _csize: number; + table: Float64Array; + _width: number; + _bitrev: Int32Array; + /** + * Create a complex number array with size `2 * size` + * + * @returns {Float64Array} A complex number array with size `2 * size` + */ + createComplexArray(): Float64Array; + /** + * Converts a complex number representation stored in a Float64Array to an array of real numbers. + * + * @param {Float64Array} complex The complex number representation to be converted. + * @param {number[]} [storage] An optional array to store the result in. + * @returns {number[]} An array of real numbers representing the input complex number representation. + */ + fromComplexArray(complex: Float64Array, storage?: number[]): number[]; + /** + * Convert a real-valued input array to a complex-valued output array. + * @param {Float64Array} input The real-valued input array. + * @param {Float64Array} [storage] Optional buffer to store the output array. + * @returns {Float64Array} The complex-valued output array. + */ + toComplexArray(input: Float64Array, storage?: Float64Array): Float64Array; + /** + * Completes the spectrum by adding its mirrored negative frequency components. + * @param {Float64Array} spectrum The input spectrum. + * @returns {void} + */ + completeSpectrum(spectrum: Float64Array): void; + /** + * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. + * + * @param {Float64Array} out The output buffer to store the result. + * @param {Float64Array} data The input data to transform. + * + * @throws {Error} Input and output buffers must be different. + * + * @returns {void} + */ + transform(out: Float64Array, data: Float64Array): void; + /** + * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. + * The input buffer must contain real values only, while the output buffer will contain complex values. The input and + * output buffers must be different. + * + * @param {Float64Array} out The output buffer. + * @param {Float64Array} data The input buffer containing real values. + * + * @throws {Error} If the input and output buffers are the same. + */ + realTransform(out: Float64Array, data: Float64Array): void; + /** + * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. + * The `out` array must be a different buffer than the `data` array. The `out` array will contain the + * result of the transformation. The `data` array will not be modified. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input data to transform. + * @throws {Error} If `out` and `data` refer to the same buffer. + * @returns {void} + */ + inverseTransform(out: Float64Array, data: Float64Array): void; + /** + * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {number} inv A scaling factor to apply to the transform. + * @returns {void} + */ + _transform4(out: Float64Array, data: Float64Array, inv: number): void; + /** + * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {Float64Array} out The output buffer for the transformed data. + * @param {number} outOff The offset at which to write the output data. + * @param {number} off The offset at which to begin reading the input data. + * @param {number} step The step size for indexing the input data. + * @returns {void} + */ + _singleTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void; + /** + * Performs radix-4 transformation on input data of length 8 + * + * @param {Float64Array} data Input data array of length 8 + * @param {Float64Array} out Output data array of length 8 + * @param {number} outOff Index of output array to start writing from + * @param {number} off Index of input array to start reading from + * @param {number} step Step size between elements in input array + * @param {number} inv Scaling factor for inverse transform + * + * @returns {void} + */ + _singleTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void; + /** + * Real input radix-4 implementation + * @param {Float64Array} out Output array for the transformed data + * @param {Float64Array} data Input array of real data to be transformed + * @param {number} inv The scale factor used to normalize the inverse transform + */ + _realTransform4(out: Float64Array, data: Float64Array, inv: number): void; + /** + * Performs a single real input radix-2 transformation on the provided data + * + * @param {Float64Array} data The input data array + * @param {Float64Array} out The output data array + * @param {number} outOff The output offset + * @param {number} off The input offset + * @param {number} step The step + * + * @returns {void} + */ + _singleRealTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void; + /** + * Computes a single real-valued transform using radix-4 algorithm. + * This method is only called for len=8. + * + * @param {Float64Array} data The input data array. + * @param {Float64Array} out The output data array. + * @param {number} outOff The offset into the output array. + * @param {number} off The offset into the input array. + * @param {number} step The step size for the input array. + * @param {number} inv The value of inverse. + */ + _singleRealTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void; +} +/** + * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays + * which are not a power of two in length. In such cases, the chirp-z transform is used. + * + * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156 + */ +declare class NP2FFT { + /** + * Constructs a new NP2FFT object. + * @param {number} fft_length The length of the FFT + */ + constructor(fft_length: number); + bufferSize: number; + _a: number; + _chirpBuffer: Float64Array; + _buffer1: Float64Array; + _buffer2: Float64Array; + _outBuffer1: Float64Array; + _outBuffer2: Float64Array; + _slicedChirpBuffer: Float64Array; + _f: P2FFT; + _transform(output: any, input: any, real: any): void; + transform(output: any, input: any): void; + realTransform(output: any, input: any): void; +} +export {}; +//# sourceMappingURL=maths.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts.map new file mode 100644 index 000000000..7c92f4f42 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/maths.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"maths.d.ts","sourceRoot":"","sources":["../../src/utils/maths.js"],"names":[],"mappings":"AACA;;;;;;;GAOG;AAEH;;;;GAIG;AAEH;;GAEG;AACH,wCAFW,UAAU,yIAqEpB;AAGD;;;;;;;GAOG;AACH,wEAJW,MAAM,EAAE,QACR,MAAM,EAAE,iBAiClB;AAGD;;;;;GAKG;AACH,oEAeC;AAED;;;;;GAKG;AACH,wEAQC;AAED;;;;;GAKG;AACH,0BAJW,MAAM,EAAE,QACR,MAAM,EAAE,GACN,MAAM,CAIlB;AAGD;;;;;GAKG;AACH,mCAJW,GAAG,EAAE,GAAC,UAAU,UAChB,MAAM,GAAC,IAAI,GACT,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAc3B;AAED;;;;;;GAMG;AACH,8BAJW,MAAM,EAAE,QACR,MAAM,EAAE,GACN,MAAM,CAgBlB;AAED;;;;GAIG;AACH,+BAHW,MAAM,EAAE,GACN,MAAM,CAIlB;AAGD;;;;;GAKG;AACH,yBAJW,MAAM,EAAE,GAAC,UAAU,GACjB,MAAM,EAAE,CAcpB;AAGD;;;;;GAKG;AACH,yBAJW,MAAM,EAAE,GAAC,aAAa,GACpB,CAAC,MAAM,EAAE,MAAM,CAAC,CAc5B;AA0nBD;;;;GAIG;AACH,mCAHW,aAAa,cACb,MAAM,OAmChB;AAED;;;;;GAKG;AACH,2BAJW,MAAM,YACN,MAAM,GACJ,MAAM,CAKlB;AAxED;IACI,6BAUC;IATG,gBAA4B;IAC5B,sBAA4C;IAExC,oBAAgC;IAChC,yBAAsC;IAO9C,0CAEC;IAED,sCAEC;CACJ;yBA13BY,SAAS,GAAG,UAAU,GAAG,iBAAiB,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,WAAW,GAAG,YAAY,GAAG,YAAY;4BAC9H,aAAa,GAAG,cAAc;4BAC9B,UAAU,GAAG,aAAa;AAwQvC;;;;;;GAMG;AACH;IACI;;;OAGG;IACH,kBAHW,MAAM,EAoChB;IAhCG,aAAoB;IAIpB,eAAuB;IAEvB,oBAA4C;IAe5C,eAAiD;IAGjD,oBAA+C;IAUnD;;;;OAIG;IACH,sBAFa,YAAY,CAIxB;IAED;;;;;;OAMG;IACH,0BAJW,YAAY,YACZ,MAAM,EAAE,GACN,MAAM,EAAE,CAOpB;IAED;;;;;OAKG;IACH,sBAJW,YAAY,YACZ,YAAY,GACV,YAAY,CASxB;IAED;;;;OAIG;IACH,2BAHW,YAAY,GACV,IAAI,CAShB;IAED;;;;;;;;;OASG;IACH,eAPW,YAAY,QACZ,YAAY,GAIV,IAAI,CAOhB;IAED;;;;;;;;;OASG;IACH,mBALW,YAAY,QACZ,YAAY,QAStB;IAED;;;;;;;;;OASG;IACH,sBALW,YAAY,QACZ,YAAY,GAEV,IAAI,CAShB;IAED;;;;;;;OAOG;IACH,iBALW,YAAY,QACZ,YAAY,OACZ,MAAM,GACJ,IAAI,CA0FhB;IAED;;;;;;;;;OASG;IACH,wBAPW,YAAY,OACZ,YAAY,UACZ,MAAM,OACN,MAAM,QACN,MAAM,GACJ,IAAI,CAehB;IAED;;;;;;;;;;;OAWG;IACH,wBATW,YAAY,OACZ,YAAY,UACZ,MAAM,OACN,MAAM,QACN,MAAM,OACN,MAAM,GAEJ,IAAI,CAqChB;IAED;;;;;OAKG;IACH,qBAJW,YAAY,QACZ,YAAY,OACZ,MAAM,QA0FhB;IAED;;;;;;;;;;OAUG;IACH,4BARW,YAAY,OACZ,YAAY,UACZ,MAAM,OACN,MAAM,QACN,MAAM,GAEJ,IAAI,CAahB;IAED;;;;;;;;;;OAUG;IACH,4BAPW,YAAY,OACZ,YAAY,UACZ,MAAM,OACN,MAAM,QACN,MAAM,OACN,MAAM,QA6BhB;CACJ;AAED;;;;;GAKG;AACH;IAEI;;;OAGG;IACH,wBAFW,MAAM,EAkDhB;IA3CG,mBAAwB;IACxB,WAAW;IAMX,2BAA4C;IAC5C,uBAAwC;IACxC,uBAAwC;IACxC,0BAA2C;IAC3C,0BAA2C;IA0B3C,iCAA8C;IAI9C,UAAgC;IAIpC,qDA8CC;IAED,yCAEC;IAED,6CAEC;CACJ"} \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts b/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts new file mode 100644 index 000000000..da2650e42 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts @@ -0,0 +1,299 @@ +/** + * Transposes a tensor according to the provided axes. + * @param {any} tensor The input tensor to transpose. + * @param {Array} axes The axes to transpose the tensor along. + * @returns {Tensor} The transposed tensor. + */ +export function transpose(tensor: any, axes: any[]): Tensor; +/** + * Interpolates an Tensor to the given size. + * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w]) + * @param {number[]} size The output size of the image + * @param {string} mode The interpolation mode + * @param {boolean} align_corners Whether to align corners. + * @returns {Tensor} The interpolated tensor. + */ +export function interpolate(input: Tensor, [out_height, out_width]: number[], mode?: string, align_corners?: boolean): Tensor; +/** + * Perform mean pooling of the last hidden state followed by a normalization step. + * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim] + * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength] + * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim]. + */ +export function mean_pooling(last_hidden_state: Tensor, attention_mask: Tensor): Tensor; +/** + * Concatenates an array of tensors along a specified dimension. + * @param {Tensor[]} tensors The array of tensors to concatenate. + * @param {number} dim The dimension to concatenate along. + * @returns {Tensor} The concatenated tensor. + */ +export function cat(tensors: Tensor[], dim?: number): Tensor; +/** + * Stack an array of tensors along a specified dimension. + * @param {Tensor[]} tensors The array of tensors to stack. + * @param {number} dim The dimension to stack along. + * @returns {Tensor} The stacked tensor. + */ +export function stack(tensors: Tensor[], dim?: number): Tensor; +/** + * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions. + * @param {Tensor} input the input tenso + * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced. + * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1. + * @param {boolean} keepdim whether the output tensor has dim retained or not. + * @returns {Tensor[]} A tuple of (std, mean) tensors. + */ +export function std_mean(input: Tensor, dim?: number | null, correction?: number, keepdim?: boolean): Tensor[]; +/** + * Returns the mean value of each row of the input tensor in the given dimension dim. + * @param {Tensor} input the input tensor. + * @param {number|null} dim the dimension to reduce. + * @param {boolean} keepdim whether the output tensor has dim retained or not. + * @returns A new tensor with means taken along the specified dimension. + */ +export function mean(input: Tensor, dim?: number | null, keepdim?: boolean): Tensor; +/** + * + * Measures similarity between two temporal sequences (e.g., input audio and output tokens + * to generate token-level timestamps). + * @param {Tensor} matrix + * @returns {number[][]} + */ +export function dynamicTimeWarping(matrix: Tensor): number[][]; +/** + * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size. + * @param {number[]} size A sequence of integers defining the shape of the output tensor. + */ +export function ones(size: number[]): Tensor; +/** + * Returns a tensor filled with the scalar value 1, with the same size as input. + * @param {Tensor} tensor The size of input will determine size of the output tensor. + * @returns The ones tensor. + */ +export function ones_like(tensor: Tensor): Tensor; +export class Tensor { + /** + * Create a new Tensor or copy an existing Tensor. + * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args + */ + constructor(...args: [DataType, DataArray, number[]] | [import('onnxruntime-common').Tensor]); + /** @type {number[]} Dimensions of the tensor. */ + dims: number[]; + /** @type {DataType} Type of the tensor. */ + type: DataType; + /** @type {DataArray} The data stored in the tensor. */ + data: DataArray; + /** @type {number} The number of elements in the tensor. */ + size: number; + /** + * Index into a Tensor object. + * @param {number} index The index to access. + * @returns {Tensor} The data at the specified index. + */ + _getitem(index: number): Tensor; + /** + * @param {number|bigint} item The item to search for in the tensor + * @returns {number} The index of the first occurrence of item in the tensor data. + */ + indexOf(item: number | bigint): number; + /** + * @param {number} index + * @param {number} iterSize + * @param {any} iterDims + * @returns {Tensor} + */ + _subarray(index: number, iterSize: number, iterDims: any): Tensor; + /** + * Returns the value of this tensor as a standard JavaScript Number. This only works + * for tensors with one element. For other cases, see `Tensor.tolist()`. + * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. + * @throws {Error} If the tensor has more than one element. + */ + item(): number | bigint; + /** + * Convert tensor data to a n-dimensional JS list + * @returns {Array} + */ + tolist(): any[]; + /** + * Return a new Tensor with the sigmoid function applied to each element. + * @returns {Tensor} The tensor with the sigmoid function applied. + */ + sigmoid(): Tensor; + /** + * Applies the sigmoid function to the tensor in place. + * @returns {Tensor} Returns `this`. + */ + sigmoid_(): Tensor; + /** + * Return a new Tensor with every element multiplied by a constant. + * @param {number} val The value to multiply by. + * @returns {Tensor} The new tensor. + */ + mul(val: number): Tensor; + /** + * Multiply the tensor by a constant in place. + * @param {number} val The value to multiply by. + * @returns {Tensor} Returns `this`. + */ + mul_(val: number): Tensor; + /** + * Return a new Tensor with every element added by a constant. + * @param {number} val The value to add by. + * @returns {Tensor} The new tensor. + */ + add(val: number): Tensor; + /** + * Add the tensor by a constant in place. + * @param {number} val The value to add by. + * @returns {Tensor} Returns `this`. + */ + add_(val: number): Tensor; + clone(): Tensor; + slice(...slices: any[]): Tensor; + /** + * Return a transposed version of this Tensor, according to the provided dimensions. + * @param {...number} dims Dimensions to transpose. + * @returns {Tensor} The transposed tensor. + */ + transpose(...dims: number[]): Tensor; + /** + * Returns the sum of each row of the input tensor in the given dimension dim. + * + * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. + * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. + * @returns The summed tensor + */ + sum(dim?: number, keepdim?: boolean): Tensor; + /** + * Returns the matrix norm or vector norm of a given tensor. + * @param {number|string} [p='fro'] The order of norm + * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. + * If dim is None, the norm will be calculated across all dimensions of input. + * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. + * @returns {Tensor} The norm of the tensor. + */ + norm(p?: number | string, dim?: number, keepdim?: boolean): Tensor; + /** + * Performs `L_p` normalization of inputs over specified dimension. Operates in place. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} `this` for operation chaining. + */ + normalize_(p?: number, dim?: number): Tensor; + /** + * Performs `L_p` normalization of inputs over specified dimension. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} The normalized tensor. + */ + normalize(p?: number, dim?: number): Tensor; + /** + * Compute and return the stride of this tensor. + * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. + * @returns {number[]} The stride of this tensor. + */ + stride(): number[]; + /** + * Returns a tensor with all specified dimensions of input of size 1 removed. + * + * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. + * If you would like a copy, use `tensor.clone()` before squeezing. + * + * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions. + * @returns The squeezed tensor + */ + squeeze(dim?: number): Tensor; + /** + * In-place version of @see {@link Tensor.squeeze} + */ + squeeze_(dim?: any): this; + /** + * Returns a new tensor with a dimension of size one inserted at the specified position. + * + * NOTE: The returned tensor shares the same underlying data with this tensor. + * + * @param {number} dim The index at which to insert the singleton dimension + * @returns The unsqueezed tensor + */ + unsqueeze(dim?: number): Tensor; + /** + * In-place version of @see {@link Tensor.unsqueeze} + */ + unsqueeze_(dim?: any): this; + /** + * In-place version of @see {@link Tensor.flatten} + */ + flatten_(start_dim?: number, end_dim?: number): this; + /** + * Flattens input by reshaping it into a one-dimensional tensor. + * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` + * and ending with `end_dim` are flattened. The order of elements in input is unchanged. + * @param {number} start_dim the first dim to flatten + * @param {number} end_dim the last dim to flatten + * @returns The flattened tensor. + */ + flatten(start_dim?: number, end_dim?: number): Tensor; + /** + * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. + * @param {...number} dims the desired size + * @returns {Tensor} The tensor with the same data but different shape + */ + view(...dims: number[]): Tensor; + neg_(): this; + neg(): Tensor; + /** + * In-place version of @see {@link Tensor.clamp} + */ + clamp_(min: any, max: any): this; + /** + * Clamps all elements in input into the range [ min, max ] + * @param {number} min lower-bound of the range to be clamped to + * @param {number} max upper-bound of the range to be clamped to + * @returns the output tensor. + */ + clamp(min: number, max: number): Tensor; + /** + * In-place version of @see {@link Tensor.round} + */ + round_(): this; + /** + * Rounds elements of input to the nearest integer. + * @returns the output tensor. + */ + round(): Tensor; + /** + * Performs Tensor dtype conversion. + * @param {DataType} type The desired data type. + * @returns {Tensor} The converted tensor. + */ + to(type: DataType): Tensor; + /** + * Returns an iterator object for iterating over the tensor data in row-major order. + * If the tensor has more than one dimension, the iterator will yield subarrays. + * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. + */ + [Symbol.iterator](): Iterator; +} +/** + * This creates a nested array of a given type and depth (see examples). + */ +export type NestArray = Acc['length'] extends Depth ? T : NestArray; +export type DataType = keyof typeof DataTypeMap; +export type DataArray = import('./maths.js').AnyTypedArray | any[]; +declare const DataTypeMap: Readonly<{ + float32: Float32ArrayConstructor; + float64: Float64ArrayConstructor; + string: ArrayConstructor; + int8: Int8ArrayConstructor; + uint8: Uint8ArrayConstructor; + int16: Int16ArrayConstructor; + uint16: Uint16ArrayConstructor; + int32: Int32ArrayConstructor; + uint32: Uint32ArrayConstructor; + int64: BigInt64ArrayConstructor; + uint64: BigUint64ArrayConstructor; + bool: Uint8ArrayConstructor; +}>; +export {}; +//# sourceMappingURL=tensor.d.ts.map \ No newline at end of file diff --git a/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts.map b/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts.map new file mode 100644 index 000000000..23e7637d3 --- /dev/null +++ b/core/vendor/node_modules/@xenova/transformers/types/utils/tensor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tensor.d.ts","sourceRoot":"","sources":["../../src/utils/tensor.js"],"names":[],"mappings":"AAyqBA;;;;;GAKG;AACH,kCAJW,GAAG,gBAED,MAAM,CAKlB;AAGD;;;;;;;GAOG;AACH,mCANW,MAAM,2BACN,MAAM,EAAE,SACR,MAAM,kBACN,OAAO,GACL,MAAM,CAiBlB;AAED;;;;;GAKG;AACH,gDAJW,MAAM,kBACN,MAAM,GACJ,MAAM,CAwClB;AAgED;;;;;GAKG;AACH,6BAJW,MAAM,EAAE,QACR,MAAM,GACJ,MAAM,CAyDlB;AAED;;;;;GAKG;AACH,+BAJW,MAAM,EAAE,QACR,MAAM,GACJ,MAAM,CAMlB;AAGD;;;;;;;GAOG;AACH,gCANW,MAAM,QACN,MAAM,GAAC,IAAI,eACX,MAAM,YACN,OAAO,GACL,MAAM,EAAE,CA8DpB;AAGD;;;;;;GAMG;AACH,4BALW,MAAM,QACN,MAAM,GAAC,IAAI,YACX,OAAO,UAsDjB;AAGD;;;;;;GAMG;AACH,2CAHW,MAAM,GACJ,MAAM,EAAE,EAAE,CAsFtB;AAWD;;;GAGG;AACH,2BAFW,MAAM,EAAE,UASlB;AAED;;;;GAIG;AACH,kCAHW,MAAM,UAKhB;AA7lCD;IAaI;;;OAGG;IACH,qBAFW,CAAC,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,GAAC,CAAC,OAAO,oBAAoB,EAAE,MAAM,CAAC,EAmC/E;IAjDD,iDAAiD;IACjD,MADW,MAAM,EAAE,CACd;IAEL,2CAA2C;IAC3C,MADW,QAAQ,CACd;IAEL,uDAAuD;IACvD,MADW,SAAS,CACf;IAEL,2DAA2D;IAC3D,MADW,MAAM,CACZ;IA4DL;;;;OAIG;IACH,gBAHW,MAAM,GACJ,MAAM,CAalB;IAED;;;OAGG;IACH,cAHW,MAAM,GAAC,MAAM,GACX,MAAM,CAUlB;IAED;;;;;OAKG;IACH,iBALW,MAAM,YACN,MAAM,YACN,GAAG,GACD,MAAM,CAYlB;IAED;;;;;OAKG;IACH,QAHa,MAAM,GAAC,MAAM,CAQzB;IAED;;;OAGG;IACH,gBAEC;IAED;;;OAGG;IACH,WAFa,MAAM,CAIlB;IAED;;;OAGG;IACH,YAFa,MAAM,CAOlB;IAED;;;;OAIG;IACH,SAHW,MAAM,GACJ,MAAM,CAIlB;IAED;;;;OAIG;IACH,UAHW,MAAM,GACJ,MAAM,CAOlB;IAGD;;;;OAIG;IACH,SAHW,MAAM,GACJ,MAAM,CAIlB;IAED;;;;OAIG;IACH,UAHW,MAAM,GACJ,MAAM,CAOlB;IACD,gBAEC;IAED,gCA8DC;IAED;;;;OAIG;IACH,mBAHe,MAAM,KACR,MAAM,CAIlB;IAOD;;;;;;OAMG;IACH,UAJW,MAAM,YACN,OAAO,UAKjB;IAED;;;;;;;OAOG;IACH,SANW,MAAM,GAAC,MAAM,QACb,MAAM,YAEN,OAAO,GACL,MAAM,CA0DlB;IAED;;;;;OAKG;IACH,eAJW,MAAM,QACN,MAAM,GACJ,MAAM,CA2BlB;IAED;;;;;OAKG;IACH,cAJW,MAAM,QACN,MAAM,GACJ,MAAM,CAIlB;IAED;;;;OAIG;IACH,UAFa,MAAM,EAAE,CAIpB;IAED;;;;;;;;OAQG;IACH,cAHW,MAAM,UAShB;IAED;;OAEG;IACH,0BAGC;IAED;;;;;;;OAOG;IACH,gBAHW,MAAM,UAShB;IAED;;OAEG;IACH,4BAGC;IAED;;OAEG;IACH,qDAUC;IAED;;;;;;;OAOG;IACH,oBAJW,MAAM,YACN,MAAM,UAKhB;IAED;;;;OAIG;IACH,cAHe,MAAM,KACR,MAAM,CAuBlB;IAED,aAKC;IACD,cAEC;IAED;;OAEG;IACH,iCAKC;IAED;;;;;OAKG;IACH,WAJW,MAAM,OACN,MAAM,UAKhB;IAED;;OAEG;IACH,eAKC;IAED;;;OAGG;IACH,gBAEC;IAED;;;;OAIG;IACH,SAHW,QAAQ,GACN,MAAM,CAYlB;IAjhBD;;;;OAIG;IACH,mDAYC;CAigBJ;;;;2EAcY,GAAG,CAAC,QAAQ,CAAC,SAAS,KAAK,GAAG,CAAC,GAAG,UAAU,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,CAAC;uBA1lBxE,MAAM,kBAAkB;wBACxB,OAAO,YAAY,EAAE,aAAa,GAAG,GAAG,EAAE;AAjBvD;;;;;;;;;;;;;GAaG"} \ No newline at end of file diff --git a/webworker/package-lock.json b/core/vendor/package-lock.json similarity index 68% rename from webworker/package-lock.json rename to core/vendor/package-lock.json index 8465da2a1..64225d017 100644 --- a/webworker/package-lock.json +++ b/core/vendor/package-lock.json @@ -1,387 +1,15 @@ { - "name": "webworker", + "name": "vendor", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "webworker", + "name": "vendor", "version": "1.0.0", "license": "ISC", "dependencies": { - "@xenova/transformers": "^2.13.4" - }, - "devDependencies": { - "esbuild": "^0.19.11", - "typescript": "^5.3.3" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz", - "integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz", - "integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz", - "integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz", - "integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz", - "integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz", - "integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz", - "integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz", - "integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz", - "integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz", - "integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz", - "integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz", - "integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz", - "integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz", - "integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz", - "integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz", - "integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz", - "integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz", - "integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz", - "integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz", - "integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz", - "integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz", - "integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz", - "integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" + "@xenova/transformers": "^2.14.0" } }, "node_modules/@huggingface/jinja": { @@ -452,17 +80,17 @@ "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==" }, "node_modules/@types/node": { - "version": "20.10.8", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.8.tgz", - "integrity": "sha512-f8nQs3cLxbAFc00vEU59yf9UyGUftkPaLGfvbVOIDdx2i1b8epBqj2aNGyP19fiyXWvlmZ7qC1XLjAzw/OKIeA==", + "version": "20.11.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.3.tgz", + "integrity": "sha512-nrlmbvGPNGaj84IJZXMPhQuCMEVTT/hXZMJJG/aIqVL9fKxqk814sGGtJA4GI6hpJSLQjpi6cn0Qx9eOf9SDVg==", "dependencies": { "undici-types": "~5.26.4" } }, "node_modules/@xenova/transformers": { - "version": "2.13.4", - "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.13.4.tgz", - "integrity": "sha512-yk8yDvQaCTEZJsasoUj+FWEM9dVcNdDXlushzJ0KjFe2oUOJ3XqICAJz1Htz/vWtM20ErGt509EKogACGYlpxA==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.14.0.tgz", + "integrity": "sha512-rQ3O7SW5EM64b6XFZGx3XQ2cfiroefxUwU9ShfSpEZyhd082GvwNJJKndxgaukse1hZP1JUDoT0DfjDiq4IZiw==", "dependencies": { "@huggingface/jinja": "^0.1.0", "onnxruntime-web": "1.14.0", @@ -609,44 +237,6 @@ "once": "^1.4.0" } }, - "node_modules/esbuild": { - "version": "0.19.11", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz", - "integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==", - "dev": true, - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.19.11", - "@esbuild/android-arm": "0.19.11", - "@esbuild/android-arm64": "0.19.11", - "@esbuild/android-x64": "0.19.11", - "@esbuild/darwin-arm64": "0.19.11", - "@esbuild/darwin-x64": "0.19.11", - "@esbuild/freebsd-arm64": "0.19.11", - "@esbuild/freebsd-x64": "0.19.11", - "@esbuild/linux-arm": "0.19.11", - "@esbuild/linux-arm64": "0.19.11", - "@esbuild/linux-ia32": "0.19.11", - "@esbuild/linux-loong64": "0.19.11", - "@esbuild/linux-mips64el": "0.19.11", - "@esbuild/linux-ppc64": "0.19.11", - "@esbuild/linux-riscv64": "0.19.11", - "@esbuild/linux-s390x": "0.19.11", - "@esbuild/linux-x64": "0.19.11", - "@esbuild/netbsd-x64": "0.19.11", - "@esbuild/openbsd-x64": "0.19.11", - "@esbuild/sunos-x64": "0.19.11", - "@esbuild/win32-arm64": "0.19.11", - "@esbuild/win32-ia32": "0.19.11", - "@esbuild/win32-x64": "0.19.11" - } - }, "node_modules/expand-template": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", @@ -1107,19 +697,6 @@ "node": "*" } }, - "node_modules/typescript": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", - "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", diff --git a/core/vendor/package.json b/core/vendor/package.json new file mode 100644 index 000000000..a7838e858 --- /dev/null +++ b/core/vendor/package.json @@ -0,0 +1,14 @@ +{ + "name": "vendor", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "@xenova/transformers": "^2.14.0" + } +} diff --git a/extensions/vscode/.continueignore b/extensions/vscode/.continueignore new file mode 100644 index 000000000..27949aaf3 --- /dev/null +++ b/extensions/vscode/.continueignore @@ -0,0 +1 @@ +media \ No newline at end of file diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 7078ee554..994c9efa0 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -9,4 +9,5 @@ src/client gui exe -sync.node \ No newline at end of file +sync.node +bin \ No newline at end of file diff --git a/extensions/vscode/.vscodeignore b/extensions/vscode/.vscodeignore index 41c28b28b..9d59dbe5c 100644 --- a/extensions/vscode/.vscodeignore +++ b/extensions/vscode/.vscodeignore @@ -9,8 +9,6 @@ vsc-extension-quickstart.md **/.eslintrc.json **/*.map **/*.ts -scripts/env/** -scripts/.env **/.env **/env node_modules/** @@ -18,9 +16,11 @@ node_modules/** **/.pytest_cache **/__pycache__ -scripts/data -scripts/env -scripts/.continue_env_installed +manual-testing-sandbox +esbuild.js +esbuild.test.mjs +importMetaUrl.js +scripts server/exe/** !out/node_modules/** diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 9916e35e5..ad5990313 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -851,7 +851,8 @@ "url", "http", "codebase", - "problems" + "problems", + "folder" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -861,7 +862,8 @@ "Enter a URL and use the contents of the webpage as context", "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", "Use embeddings to automatically find relevant files from throughout the codebase", - "Reference all linting errors and warnings in the currently open file" + "Reference all linting errors and warnings in the currently open file", + "Include important files from a folder in the prompt, as determined by similarity search" ], "type": "string" }, @@ -902,7 +904,7 @@ "if": { "properties": { "name": { - "enum": ["codebase"] + "enum": ["codebase", "folder"] } } }, diff --git a/extensions/vscode/esbuild.js b/extensions/vscode/esbuild.js index 5bf7b6ad4..3d75a5aa2 100644 --- a/extensions/vscode/esbuild.js +++ b/extensions/vscode/esbuild.js @@ -1,15 +1,16 @@ const esbuild = require("esbuild"); const ncp = require("ncp").ncp; const fs = require("fs"); -const { exec } = require("child_process"); (async () => { + console.log("Bundling with esbuild..."); + // Bundles the extension into one file await esbuild.build({ entryPoints: ["src/extension.ts"], bundle: true, outfile: "out/extension.js", - external: ["vscode", "esbuild", "../sync.node"], + external: ["vscode", "esbuild"], format: "cjs", platform: "node", sourcemap: true, @@ -17,69 +18,39 @@ const { exec } = require("child_process"); // eslint-disable-next-line @typescript-eslint/naming-convention ".node": "file", }, + + // To allow import.meta.path for transformers.js + // https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 + inject: ["./importMetaUrl.js"], + define: { "import.meta.url": "importMetaUrl" }, }); - exec("npm run build-release:rust", (error, stdout, stderr) => { - if (error) { - console.log("Error building sync.node"); - console.log("stdout: ", stdout); - console.log("stderr: ", stderr); - throw error; - } + fs.mkdirSync("out/node_modules", { recursive: true }); - if (process.env.target === "darwin-arm64") { - // Remove the old binary - exec("rm -rf sync.node", (error, stdout, stderr) => { - if (error) { - console.log("Error removing sync.node"); - console.log("stdout: ", stdout); - console.log("stderr: ", stderr); - throw error; - } - }); - - // Download the prebuilt binary - exec( - "curl -L https://continue-server-binaries.s3.us-west-1.amazonaws.com/apple-silicon/sync.node -o sync.node", - (error, stdout, stderr) => { - if (error) { - console.log("Error downloading sync.node"); - console.log("stdout: ", stdout); - console.log("stderr: ", stderr); - throw error; - } - } - ); - } - - fs.mkdirSync("out/node_modules", { recursive: true }); - - ncp.ncp("node_modules/esbuild", "out/node_modules/esbuild", function (err) { + const NODE_MODULES_TO_COPY = ["esbuild", "@lancedb"]; + NODE_MODULES_TO_COPY.forEach((mod) => { + ncp.ncp(`node_modules/${mod}`, `out/node_modules/${mod}`, function (err) { if (err) { return console.error(err); } }); + }); - // Return instead of copying if on ARM - // This is an env var created in the GH Action - // We will instead download the prebuilt binaries - if ( - process.env.target === "darwin-arm64" || - process.env.target === "linux-arm64" || - process.env.target === "win-arm64" - ) { - console.log("Skipping copying binaries"); - return; + // Return instead of copying if on ARM + // This is an env var created in the GH Action + // We will instead download the prebuilt binaries + if ( + process.env.target === "darwin-arm64" || + process.env.target === "linux-arm64" || + process.env.target === "win-arm64" + ) { + console.log("Skipping copying binaries"); + return; + } + + ncp.ncp("node_modules/@esbuild", "out/node_modules/@esbuild", function (err) { + if (err) { + return console.error(err); } - - ncp.ncp( - "node_modules/@esbuild", - "out/node_modules/@esbuild", - function (err) { - if (err) { - return console.error(err); - } - } - ); }); })(); diff --git a/extensions/vscode/importMetaUrl.js b/extensions/vscode/importMetaUrl.js new file mode 100644 index 000000000..0508c8d33 --- /dev/null +++ b/extensions/vscode/importMetaUrl.js @@ -0,0 +1,2 @@ +// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 +export var importMetaUrl = require("url").pathToFileURL(__filename); diff --git a/extensions/vscode/logging.ini b/extensions/vscode/logging.ini deleted file mode 100644 index 5b4786194..000000000 --- a/extensions/vscode/logging.ini +++ /dev/null @@ -1,27 +0,0 @@ -[loggers] -keys=root - -[handlers] -keys=logfile,logconsole - -[formatters] -keys=logformatter - -[logger_root] -level=INFO -handlers=logfile, logconsole - -[formatter_logformatter] -format=[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s - -[handler_logfile] -class=handlers.RotatingFileHandler -level=INFO -args=('logfile.log','a') -formatter=logformatter - -[handler_logconsole] -class=handlers.logging.StreamHandler -level=INFO -args=() -formatter=logformatter \ No newline at end of file diff --git a/extensions/vscode/logging.yaml b/extensions/vscode/logging.yaml deleted file mode 100644 index 391041ef9..000000000 --- a/extensions/vscode/logging.yaml +++ /dev/null @@ -1,30 +0,0 @@ -version: 1 -disable_existing_loggers: False -formatters: - default: - (): 'uvicorn.logging.DefaultFormatter' - fmt: '%(asctime)s %(levelprefix)-9s %(name)s -: %(message)s' - access: - (): 'uvicorn.logging.AccessFormatter' - fmt: '%(asctime)s %(levelprefix)-9s %(name)s -: %(client_addr)s - "%(request_line)s" %(status_code)s' -handlers: - default: - class: logging.StreamHandler - formatter: default - stream: ext://sys.stderr - access: - class: logging.StreamHandler - formatter: access - stream: ext://sys.stdout -loggers: - uvicorn: - level: INFO - handlers: - - default - uvicorn.error: - level: INFO - uvicorn.access: - level: INFO - propagate: False - handlers: - - access \ No newline at end of file diff --git a/extensions/vscode/models/README.md b/extensions/vscode/models/README.md new file mode 100644 index 000000000..23c735a99 --- /dev/null +++ b/extensions/vscode/models/README.md @@ -0,0 +1 @@ +all-MiniLM-L6-v2 is the sentence transformers model used with transformers.js to locally generate codebase embeddings. diff --git a/gui/public/models/all-MiniLM-L6-v2/README.md b/extensions/vscode/models/all-MiniLM-L6-v2/README.md similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/README.md rename to extensions/vscode/models/all-MiniLM-L6-v2/README.md diff --git a/gui/public/models/all-MiniLM-L6-v2/config.json b/extensions/vscode/models/all-MiniLM-L6-v2/config.json similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/config.json rename to extensions/vscode/models/all-MiniLM-L6-v2/config.json diff --git a/gui/public/models/all-MiniLM-L6-v2/onnx/model_quantized.onnx b/extensions/vscode/models/all-MiniLM-L6-v2/onnx/model_quantized.onnx similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/onnx/model_quantized.onnx rename to extensions/vscode/models/all-MiniLM-L6-v2/onnx/model_quantized.onnx diff --git a/gui/public/models/all-MiniLM-L6-v2/special_tokens_map.json b/extensions/vscode/models/all-MiniLM-L6-v2/special_tokens_map.json similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/special_tokens_map.json rename to extensions/vscode/models/all-MiniLM-L6-v2/special_tokens_map.json diff --git a/gui/public/models/all-MiniLM-L6-v2/tokenizer.json b/extensions/vscode/models/all-MiniLM-L6-v2/tokenizer.json similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/tokenizer.json rename to extensions/vscode/models/all-MiniLM-L6-v2/tokenizer.json diff --git a/gui/public/models/all-MiniLM-L6-v2/tokenizer_config.json b/extensions/vscode/models/all-MiniLM-L6-v2/tokenizer_config.json similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/tokenizer_config.json rename to extensions/vscode/models/all-MiniLM-L6-v2/tokenizer_config.json diff --git a/gui/public/models/all-MiniLM-L6-v2/vocab.txt b/extensions/vscode/models/all-MiniLM-L6-v2/vocab.txt similarity index 100% rename from gui/public/models/all-MiniLM-L6-v2/vocab.txt rename to extensions/vscode/models/all-MiniLM-L6-v2/vocab.txt diff --git a/extensions/vscode/openapitools.json b/extensions/vscode/openapitools.json deleted file mode 100644 index 04369381e..000000000 --- a/extensions/vscode/openapitools.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", - "spaces": 2, - "generator-cli": { - "version": "6.4.0" - } -} diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3a4bf3e9d..79f979208 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,7 +1,7 @@ { "name": "continue", "version": "0.9.16", - "lockfileVersion": 2, + "lockfileVersion": 3, "requires": true, "packages": { "": { @@ -24,6 +24,7 @@ "highlightable": "^1.3.0-beta.0", "http-proxy": "^1.18.1", "http-proxy-middleware": "^2.0.6", + "ignore": "^5.3.0", "jest": "^29.7.0", "ncp": "^2.0.0", "node-machine-id": "^1.1.12", @@ -36,6 +37,7 @@ "tailwindcss": "^3.3.2", "undici": "^6.2.0", "uuidv4": "^6.2.13", + "vectordb": "^0.4.3", "vscode-languageclient": "^8.0.2", "ws": "^8.13.0" }, @@ -77,13 +79,18 @@ "version": "1.0.0", "license": "Apache-2.0", "dependencies": { + "@xenova/transformers": "^2.14.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", + "vectordb": "^0.4.3", "web-tree-sitter": "^0.20.8" }, "devDependencies": { @@ -95,6 +102,26 @@ "ts-jest": "^29.1.1" } }, + "node_modules/@75lb/deep-merge": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz", + "integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==", + "dependencies": { + "lodash.assignwith": "^4.2.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@75lb/deep-merge/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", @@ -118,6 +145,33 @@ "node": ">=6.0.0" } }, + "node_modules/@apache-arrow/ts": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", + "integrity": "sha512-CtwAvLkK0CZv7xsYeCo91ml6PvlfzAmAJZkRYuz2GNBwfYufj5SVi0iuSMwIMkcU/szVwvLdzORSLa5PlF/2ug==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + } + }, + "node_modules/@apache-arrow/ts/node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/@apache-arrow/ts/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "node_modules/@babel/code-frame": { "version": "7.23.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", @@ -1700,6 +1754,66 @@ "integrity": "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==", "dev": true }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.3.tgz", + "integrity": "sha512-47CvvSaV1EdUsFEpXUJApTk+hMzAhCxVizipCFUlXCgcmzpCDL86wNgJij/X9a+j6zADhIX//Lsu0qd/an/Bpw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-darwin-x64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.3.tgz", + "integrity": "sha512-UlZZv8CmJIuRJNJG+Y1VmFsGyPR8W/72Q5EwgMMsSES6zpMQ9pNdBDWhL3UGX6nMRgnbprkwYiWJ3xHhJvtqtw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.3.tgz", + "integrity": "sha512-L6NVJr/lKEd8+904FzZNpT8BGQMs2cHNYbGJMIaVvGnMiIJgKAFKtOyGtdDjoe1xRZoEw21yjRGksGbnRO5wHQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.3.tgz", + "integrity": "sha512-OBx3WF3pK0xNfFJeErmuD9R2QWLa3XdeZspyTsIrQmBDeKj3HKh8y7Scpx4NH5Y09+9JNqRRKRZN7OqWTYhITg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.3.tgz", + "integrity": "sha512-n9IvR81NXZKnSN91mrgeXbEyCiGM+YLJpOgbdHoEtMP04VDnS+iSU4jGOtQBKErvWeCJQaGFQ9qzdcVchpRGyw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@lukeed/csprng": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.0.1.tgz", @@ -1730,6 +1844,11 @@ "node": ">= 12.13.0" } }, + "node_modules/@neon-rs/load": { + "version": "0.0.74", + "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", + "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" + }, "node_modules/@nestjs/axios": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-0.0.8.tgz", @@ -2195,6 +2314,16 @@ "integrity": "sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==", "dev": true }, + "node_modules/@types/command-line-args": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.0.tgz", + "integrity": "sha512-UuKzKpJJ/Ief6ufIaIzr3A/0XnluX7RvFgwkV89Yzvm77wCh1kFaFmqN8XEnGcN62EuHdedQjEMb8mYxFLGPyA==" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", + "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" + }, "node_modules/@types/connect": { "version": "3.4.38", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", @@ -2398,6 +2527,11 @@ "form-data": "^3.0.0" } }, + "node_modules/@types/pad-left": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@types/pad-left/-/pad-left-2.1.1.tgz", + "integrity": "sha512-Xd22WCRBydkGSApl5Bw0PhAOHKSVjNL3E3AwzKaps96IMraPqy5BvZIsBVK6JLwdybUzjHnuWVwpDd0JjTfHXA==" + }, "node_modules/@types/prettier": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", @@ -2759,29 +2893,6 @@ "yauzl": "^2.9.2" } }, - "node_modules/@vscode/ripgrep/node_modules/agent-base": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", - "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", - "dependencies": { - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@vscode/ripgrep/node_modules/https-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.2.tgz", - "integrity": "sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==", - "dependencies": { - "agent-base": "^7.0.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/@vscode/test-electron": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.8.tgz", @@ -2797,6 +2908,19 @@ "node": ">=16" } }, + "node_modules/@vscode/test-electron/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/@vscode/vsce": { "version": "2.22.0", "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-2.22.0.tgz", @@ -3101,6 +3225,36 @@ "node": ">= 8" } }, + "node_modules/apache-arrow": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-14.0.2.tgz", + "integrity": "sha512-EBO2xJN36/XoY81nhLcwCJgFwkboDZeyNQ+OPsG7bCoQjc2BT0aTyH/MR6SrL+LirSNz+cYqjGRlupMMlP1aEg==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/apache-arrow/node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/apache-arrow/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "node_modules/aproba": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", @@ -3142,6 +3296,14 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, + "node_modules/array-back": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", + "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", + "engines": { + "node": ">=6" + } + }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -3202,11 +3364,11 @@ "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==" }, "node_modules/axios": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.5.tgz", - "integrity": "sha512-9pU/8mmjSSOb4CXVsvGIevN+MlO/t9OWtKadTaLuN85Gge3HGorUckgp8A/2FH4V4hJ7JuQ3LIeI7KAV9ITZrQ==", + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", + "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", "dependencies": { - "follow-redirects": "^1.15.0", + "follow-redirects": "^1.15.4", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } @@ -3725,6 +3887,20 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, "node_modules/char-regex": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", @@ -4031,6 +4207,50 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/command-line-args": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", + "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==", + "dependencies": { + "array-back": "^3.1.0", + "find-replace": "^3.0.0", + "lodash.camelcase": "^4.3.0", + "typical": "^4.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/command-line-usage": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.1.tgz", + "integrity": "sha512-NCyznE//MuTjwi3y84QVUGEOT+P5oto1e1Pk/jFPVdPPfsG03qpTIl3yw6etR+v73d0lXsoojRpvbru2sqePxQ==", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^3.0.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/command-line-usage/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/command-line-usage/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/commander": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", @@ -4509,9 +4729,9 @@ } }, "node_modules/detect-libc": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz", - "integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", "engines": { "node": ">=8" } @@ -5495,6 +5715,17 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, + "node_modules/find-replace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", + "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", + "dependencies": { + "array-back": "^3.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -5543,6 +5774,11 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/flatbuffers": { + "version": "23.5.26", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", + "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==" + }, "node_modules/flatted": { "version": "3.2.7", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", @@ -6124,15 +6360,26 @@ } }, "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.2.tgz", + "integrity": "sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==", "dependencies": { - "agent-base": "6", + "agent-base": "^7.0.2", "debug": "4" }, "engines": { - "node": ">= 6" + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent/node_modules/agent-base": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", + "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" } }, "node_modules/human-signals": { @@ -6182,10 +6429,9 @@ ] }, "node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", + "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", "engines": { "node": ">= 4" } @@ -6563,20 +6809,6 @@ "node": ">=10" } }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/istanbul-lib-report": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", @@ -7240,6 +7472,14 @@ "node": ">=4" } }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -7502,6 +7742,16 @@ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, + "node_modules/lodash.assignwith": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz", + "integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -7658,6 +7908,18 @@ "node": ">= 6" } }, + "node_modules/make-fetch-happen/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/make-fetch-happen/node_modules/lru-cache": { "version": "7.14.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.14.1.tgz", @@ -8938,6 +9200,17 @@ "node": ">=6" } }, + "node_modules/pad-left": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", + "integrity": "sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA==", + "dependencies": { + "repeat-string": "^1.5.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/pako": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", @@ -9881,6 +10154,14 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "engines": { + "node": ">=0.10" + } + }, "node_modules/request": { "version": "2.88.2", "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", @@ -10201,9 +10482,9 @@ } }, "node_modules/semver": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", - "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dependencies": { "lru-cache": "^6.0.0" }, @@ -10548,6 +10829,14 @@ "node": ">= 0.8" } }, + "node_modules/stream-read-all": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz", + "integrity": "sha512-EWZT9XOceBPlVJRrYcykW8jyRSZYbkb/0ZK36uLEmoWVO5gxBOnntNTseNzfREsqxqdfEGQrD8SXQ3QWbBmq8A==", + "engines": { + "node": ">=10" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -10748,6 +11037,42 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/table-layout": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz", + "integrity": "sha512-rpyNZYRw+/C+dYkcQ3Pr+rLxW4CfHpXjPDnG7lYhdRoUcZTUt+KEsX+94RGp/aVp/MQU35JCITv2T/beY4m+hw==", + "dependencies": { + "@75lb/deep-merge": "^1.1.1", + "array-back": "^6.2.2", + "command-line-args": "^5.2.1", + "command-line-usage": "^7.0.0", + "stream-read-all": "^3.0.1", + "typical": "^7.1.1", + "wordwrapjs": "^5.1.0" + }, + "bin": { + "table-layout": "bin/cli.js" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/tailwindcss": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.2.tgz", @@ -11167,6 +11492,14 @@ "node": ">=14.17" } }, + "node_modules/typical": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", + "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", + "engines": { + "node": ">=8" + } + }, "node_modules/uc.micro": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", @@ -11468,6 +11801,33 @@ "node": ">= 0.8" } }, + "node_modules/vectordb": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.3.tgz", + "integrity": "sha512-7ToixoZgAB/hn44EE4ftcdE74SGRX+wmGejatTQodFBiYD9RQLW8LIuGo8MmT+AkYEDAuOR98jTEFUwnEU5sqA==", + "cpu": [ + "x64", + "arm64" + ], + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@apache-arrow/ts": "^14.0.2", + "@neon-rs/load": "^0.0.74", + "apache-arrow": "^14.0.2", + "axios": "^1.4.0" + }, + "optionalDependencies": { + "@lancedb/vectordb-darwin-arm64": "0.4.3", + "@lancedb/vectordb-darwin-x64": "0.4.3", + "@lancedb/vectordb-linux-arm64-gnu": "0.4.3", + "@lancedb/vectordb-linux-x64-gnu": "0.4.3", + "@lancedb/vectordb-win32-x64-msvc": "0.4.3" + } + }, "node_modules/verror": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", @@ -11812,6 +12172,14 @@ "node": ">=0.10.0" } }, + "node_modules/wordwrapjs": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.0.tgz", + "integrity": "sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg==", + "engines": { + "node": ">=12.17" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -11989,8619 +12357,5 @@ "url": "https://github.com/sponsors/sindresorhus" } } - }, - "dependencies": { - "@alloc/quick-lru": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", - "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==" - }, - "@ampproject/remapping": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", - "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", - "requires": { - "@jridgewell/gen-mapping": "^0.3.0", - "@jridgewell/trace-mapping": "^0.3.9" - } - }, - "@babel/code-frame": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", - "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", - "requires": { - "@babel/highlight": "^7.23.4", - "chalk": "^2.4.2" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@babel/compat-data": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", - "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==" - }, - "@babel/core": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.6.tgz", - "integrity": "sha512-FxpRyGjrMJXh7X3wGLGhNDCRiwpWEF74sKjTLDJSG5Kyvow3QZaG0Adbqzi9ZrVjTWpsX+2cxWXD71NMg93kdw==", - "requires": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-compilation-targets": "^7.23.6", - "@babel/helper-module-transforms": "^7.23.3", - "@babel/helpers": "^7.23.6", - "@babel/parser": "^7.23.6", - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.6", - "@babel/types": "^7.23.6", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "dependencies": { - "semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" - } - } - }, - "@babel/generator": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", - "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", - "requires": { - "@babel/types": "^7.23.6", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" - } - }, - "@babel/helper-compilation-targets": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", - "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", - "requires": { - "@babel/compat-data": "^7.23.5", - "@babel/helper-validator-option": "^7.23.5", - "browserslist": "^4.22.2", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "dependencies": { - "lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "requires": { - "yallist": "^3.0.2" - } - }, - "semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" - }, - "yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" - } - } - }, - "@babel/helper-environment-visitor": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", - "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==" - }, - "@babel/helper-function-name": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", - "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", - "requires": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - } - }, - "@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", - "requires": { - "@babel/types": "^7.22.5" - } - }, - "@babel/helper-module-imports": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", - "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", - "requires": { - "@babel/types": "^7.22.15" - } - }, - "@babel/helper-module-transforms": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", - "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", - "requires": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" - } - }, - "@babel/helper-plugin-utils": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", - "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==" - }, - "@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", - "requires": { - "@babel/types": "^7.22.5" - } - }, - "@babel/helper-split-export-declaration": { - "version": "7.22.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", - "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", - "requires": { - "@babel/types": "^7.22.5" - } - }, - "@babel/helper-string-parser": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", - "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==" - }, - "@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==" - }, - "@babel/helper-validator-option": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", - "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==" - }, - "@babel/helpers": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.6.tgz", - "integrity": "sha512-wCfsbN4nBidDRhpDhvcKlzHWCTlgJYUUdSJfzXb2NuBssDSIjc3xcb+znA7l+zYsFljAcGM0aFkN40cR3lXiGA==", - "requires": { - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.6", - "@babel/types": "^7.23.6" - } - }, - "@babel/highlight": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", - "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", - "requires": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "@babel/parser": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", - "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==" - }, - "@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "requires": { - "@babel/helper-plugin-utils": "^7.12.13" - } - }, - "@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-jsx": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.23.3.tgz", - "integrity": "sha512-EB2MELswq55OHUoRZLGg/zC7QWUKfNLpE57m/S2yr1uEneIgsTgrSzXP3NXEsMkVn76OlaVVnzN+ugObuYGwhg==", - "requires": { - "@babel/helper-plugin-utils": "^7.22.5" - } - }, - "@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "requires": { - "@babel/helper-plugin-utils": "^7.14.5" - } - }, - "@babel/plugin-syntax-typescript": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.23.3.tgz", - "integrity": "sha512-9EiNjVJOMwCO+43TqoTrgQ8jMwcAd0sWyXi9RPfIsLTj4R2MADDDQXELhffaUx/uJv2AYcxBgPwH6j4TIA4ytQ==", - "requires": { - "@babel/helper-plugin-utils": "^7.22.5" - } - }, - "@babel/runtime": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", - "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", - "requires": { - "regenerator-runtime": "^0.13.11" - } - }, - "@babel/template": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", - "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", - "requires": { - "@babel/code-frame": "^7.22.13", - "@babel/parser": "^7.22.15", - "@babel/types": "^7.22.15" - } - }, - "@babel/traverse": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.6.tgz", - "integrity": "sha512-czastdK1e8YByZqezMPFiZ8ahwVMh/ESl9vPgvgdB9AmFMGP5jfpFax74AQgl5zj4XHzqeYAg2l8PuUeRS1MgQ==", - "requires": { - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.23.6", - "@babel/types": "^7.23.6", - "debug": "^4.3.1", - "globals": "^11.1.0" - }, - "dependencies": { - "globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" - } - } - }, - "@babel/types": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz", - "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==", - "requires": { - "@babel/helper-string-parser": "^7.23.4", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" - } - }, - "@bcherny/json-schema-ref-parser": { - "version": "10.0.5-fork", - "resolved": "https://registry.npmjs.org/@bcherny/json-schema-ref-parser/-/json-schema-ref-parser-10.0.5-fork.tgz", - "integrity": "sha512-E/jKbPoca1tfUPj3iSbitDZTGnq6FUFjkH6L8U2oDwSuwK1WhnnVtCG7oFOTg/DDnyoXbQYUiUiGOibHqaGVnw==", - "dev": true, - "requires": { - "@jsdevtools/ono": "^7.1.3", - "@types/json-schema": "^7.0.6", - "call-me-maybe": "^1.0.1", - "js-yaml": "^4.1.0" - } - }, - "@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==" - }, - "@electron/rebuild": { - "version": "3.2.10", - "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-3.2.10.tgz", - "integrity": "sha512-SUBM6Mwi3yZaDFQjZzfGKpYTtOp9m60glounwX6tfGeVc/ZOl4jbquktUcyy7gYSLDWFLtKkftkY2xgMJZLQgg==", - "requires": { - "@malept/cross-spawn-promise": "^2.0.0", - "chalk": "^4.0.0", - "debug": "^4.1.1", - "detect-libc": "^2.0.1", - "fs-extra": "^10.0.0", - "got": "^11.7.0", - "lzma-native": "^8.0.5", - "node-abi": "^3.0.0", - "node-api-version": "^0.1.4", - "node-gyp": "^9.0.0", - "ora": "^5.1.0", - "semver": "^7.3.5", - "tar": "^6.0.5", - "yargs": "^17.0.1" - } - }, - "@esbuild/android-arm": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.18.20.tgz", - "integrity": "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==", - "optional": true - }, - "@esbuild/android-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz", - "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==", - "dev": true, - "optional": true - }, - "@esbuild/android-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz", - "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==", - "dev": true, - "optional": true - }, - "@esbuild/darwin-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz", - "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==", - "dev": true, - "optional": true - }, - "@esbuild/darwin-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", - "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==", - "dev": true, - "optional": true - }, - "@esbuild/freebsd-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz", - "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==", - "dev": true, - "optional": true - }, - "@esbuild/freebsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz", - "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==", - "dev": true, - "optional": true - }, - "@esbuild/linux-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz", - "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", - "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==", - "dev": true, - "optional": true - }, - "@esbuild/linux-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz", - "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==", - "dev": true, - "optional": true - }, - "@esbuild/linux-loong64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz", - "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==", - "dev": true, - "optional": true - }, - "@esbuild/linux-mips64el": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz", - "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==", - "dev": true, - "optional": true - }, - "@esbuild/linux-ppc64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz", - "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==", - "dev": true, - "optional": true - }, - "@esbuild/linux-riscv64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz", - "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-s390x": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz", - "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==", - "dev": true, - "optional": true - }, - "@esbuild/linux-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", - "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==", - "dev": true, - "optional": true - }, - "@esbuild/netbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", - "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==", - "dev": true, - "optional": true - }, - "@esbuild/openbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", - "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==", - "dev": true, - "optional": true - }, - "@esbuild/sunos-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz", - "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==", - "dev": true, - "optional": true - }, - "@esbuild/win32-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", - "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==", - "dev": true, - "optional": true - }, - "@esbuild/win32-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz", - "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==", - "dev": true, - "optional": true - }, - "@esbuild/win32-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", - "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", - "dev": true, - "optional": true - }, - "@eslint-community/eslint-utils": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", - "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^3.3.0" - } - }, - "@eslint-community/regexpp": { - "version": "4.10.0", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.10.0.tgz", - "integrity": "sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA==", - "dev": true - }, - "@eslint/eslintrc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.1.tgz", - "integrity": "sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==", - "dev": true, - "requires": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.4.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - } - }, - "@fastify/busboy": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", - "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==" - }, - "@gar/promisify": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz", - "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==" - }, - "@humanwhocodes/config-array": { - "version": "0.11.8", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.8.tgz", - "integrity": "sha512-UybHIJzJnR5Qc/MsD9Kr+RpO2h+/P1GhOwdiLPXK5TWk5sgTdu88bTD9UP+CKbPPh5Rni1u0GjAdYQLemG8g+g==", - "dev": true, - "requires": { - "@humanwhocodes/object-schema": "^1.2.1", - "debug": "^4.1.1", - "minimatch": "^3.0.5" - } - }, - "@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true - }, - "@humanwhocodes/object-schema": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", - "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", - "dev": true - }, - "@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "requires": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "dependencies": { - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "requires": { - "p-locate": "^4.1.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "requires": { - "p-limit": "^2.2.0" - } - }, - "resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" - } - } - }, - "@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==" - }, - "@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "requires": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0" - } - }, - "@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", - "requires": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "requires": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0" - } - }, - "@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "requires": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" - } - }, - "@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "requires": { - "jest-get-type": "^29.6.3" - } - }, - "@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "requires": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - } - }, - "@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "requires": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" - } - }, - "@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", - "requires": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "requires": { - "@sinclair/typebox": "^0.27.8" - } - }, - "@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", - "requires": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - } - }, - "@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "requires": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - } - }, - "@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", - "requires": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "slash": "^3.0.0" - } - }, - "@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "requires": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - } - }, - "@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", - "requires": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - } - }, - "@jridgewell/gen-mapping": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", - "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", - "requires": { - "@jridgewell/set-array": "^1.0.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" - } - }, - "@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==" - }, - "@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==" - }, - "@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" - }, - "@jridgewell/trace-mapping": { - "version": "0.3.18", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", - "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", - "requires": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" - }, - "dependencies": { - "@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==" - } - } - }, - "@jsdevtools/ono": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz", - "integrity": "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==", - "dev": true - }, - "@lukeed/csprng": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.0.1.tgz", - "integrity": "sha512-uSvJdwQU5nK+Vdf6zxcWAY2A8r7uqe+gePwLWzJ+fsQehq18pc0I2hJKwypZ2aLM90+Er9u1xn4iLJPZ+xlL4g==", - "dev": true - }, - "@malept/cross-spawn-promise": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz", - "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==", - "requires": { - "cross-spawn": "^7.0.1" - } - }, - "@nestjs/axios": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-0.0.8.tgz", - "integrity": "sha512-oJyfR9/h9tVk776il0829xyj3b2e81yTu6HjPraxynwNtMNGqZBHHmAQL24yMB3tVbBM0RvG3eUXH8+pRCGwlg==", - "dev": true, - "requires": { - "axios": "0.27.2" - }, - "dependencies": { - "axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "dev": true, - "requires": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } - } - }, - "@nestjs/common": { - "version": "8.4.7", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-8.4.7.tgz", - "integrity": "sha512-m/YsbcBal+gA5CFrDpqXqsSfylo+DIQrkFY3qhVIltsYRfu8ct8J9pqsTO6OPf3mvqdOpFGrV5sBjoyAzOBvsw==", - "dev": true, - "requires": { - "axios": "0.27.2", - "iterare": "1.2.1", - "tslib": "2.4.0", - "uuid": "8.3.2" - }, - "dependencies": { - "axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "dev": true, - "requires": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } - } - }, - "@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "requires": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - } - }, - "@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==" - }, - "@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "requires": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - } - }, - "@npmcli/fs": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-2.1.2.tgz", - "integrity": "sha512-yOJKRvohFOaLqipNtwYB9WugyZKhC/DZC4VYPmpaCzDBrA8YpK3qHZ8/HGscMnE4GqbkLNuVcCnxkeQEdGt6LQ==", - "requires": { - "@gar/promisify": "^1.1.3", - "semver": "^7.3.5" - } - }, - "@npmcli/move-file": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-2.0.1.tgz", - "integrity": "sha512-mJd2Z5TjYWq/ttPLLGqArdtnC74J6bOzg4rMDnN+p1xTacZ2yPRCk2y0oSWQtygLR9YVQXgOcONrwtnk3JupxQ==", - "requires": { - "mkdirp": "^1.0.4", - "rimraf": "^3.0.2" - } - }, - "@nuxtjs/opencollective": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz", - "integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==", - "dev": true, - "requires": { - "chalk": "^4.1.0", - "consola": "^2.15.0", - "node-fetch": "^2.6.1" - } - }, - "@openapitools/openapi-generator-cli": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.6.0.tgz", - "integrity": "sha512-M/aOpR7G+Y1nMf+ofuar8pGszajgfhs1aSPSijkcr2tHTxKAI3sA3YYcOGbszxaNRKFyvOcDq+KP9pcJvKoCHg==", - "dev": true, - "requires": { - "@nestjs/axios": "0.0.8", - "@nestjs/common": "9.3.11", - "@nestjs/core": "9.3.11", - "@nuxtjs/opencollective": "0.3.2", - "chalk": "4.1.2", - "commander": "8.3.0", - "compare-versions": "4.1.4", - "concurrently": "6.5.1", - "console.table": "0.10.0", - "fs-extra": "10.1.0", - "glob": "7.1.6", - "inquirer": "8.2.5", - "lodash": "4.17.21", - "reflect-metadata": "0.1.13", - "rxjs": "7.8.0", - "tslib": "2.0.3" - }, - "dependencies": { - "@nestjs/common": { - "version": "9.3.11", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-9.3.11.tgz", - "integrity": "sha512-IFZ2G/5UKWC2Uo7tJ4SxGed2+aiA+sJyWeWsGTogKVDhq90oxVBToh+uCDeI31HNUpqYGoWmkletfty42zUd8A==", - "dev": true, - "requires": { - "iterare": "1.2.1", - "tslib": "2.5.0", - "uid": "2.0.1" - }, - "dependencies": { - "tslib": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", - "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==", - "dev": true - } - } - }, - "@nestjs/core": { - "version": "9.3.11", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-9.3.11.tgz", - "integrity": "sha512-CI27a2JFd5rvvbgkalWqsiwQNhcP4EAG5BUK8usjp29wVp1kx30ghfBT8FLqIgmkRVo65A0IcEnWsxeXMntkxQ==", - "dev": true, - "requires": { - "@nuxtjs/opencollective": "0.3.2", - "fast-safe-stringify": "2.1.1", - "iterare": "1.2.1", - "path-to-regexp": "3.2.0", - "tslib": "2.5.0", - "uid": "2.0.1" - }, - "dependencies": { - "tslib": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", - "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==", - "dev": true - } - } - }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "path-to-regexp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.2.0.tgz", - "integrity": "sha512-jczvQbCUS7XmS7o+y1aEO9OBVFeZBQ1MDSEqmO7xSoPgOPoowY/SxLpZ6Vh97/8qHZOteiCKb7gkG9gA2ZUxJA==", - "dev": true - }, - "tslib": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.0.3.tgz", - "integrity": "sha512-uZtkfKblCEQtZKBF6EBXVZeQNl82yqtDQdv+eck8u7tdPxjLu2/lp5/uPW+um2tpuxINHWy3GhiccY7QgEaVHQ==", - "dev": true - } - } - }, - "@reduxjs/toolkit": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-1.9.3.tgz", - "integrity": "sha512-GU2TNBQVofL09VGmuSioNPQIu6Ml0YLf4EJhgj0AvBadRlCGzUWet8372LjvO4fqKZF2vH1xU0htAa7BrK9pZg==", - "requires": { - "immer": "^9.0.16", - "redux": "^4.2.0", - "redux-thunk": "^2.4.2", - "reselect": "^4.1.7" - } - }, - "@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==" - }, - "@sindresorhus/is": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", - "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==" - }, - "@sinonjs/commons": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", - "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", - "requires": { - "type-detect": "4.0.8" - } - }, - "@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "requires": { - "@sinonjs/commons": "^3.0.0" - } - }, - "@socket.io/component-emitter": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", - "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" - }, - "@szmarczak/http-timer": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz", - "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==", - "requires": { - "defer-to-connect": "^2.0.0" - } - }, - "@tootallnate/once": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", - "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", - "dev": true - }, - "@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "requires": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "@types/babel__generator": { - "version": "7.6.8", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", - "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", - "requires": { - "@babel/types": "^7.0.0" - } - }, - "@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "@types/babel__traverse": { - "version": "7.20.4", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.4.tgz", - "integrity": "sha512-mSM/iKUk5fDDrEV/e83qY+Cr3I1+Q3qqTuEn++HAWYjEa1+NxZr6CNrcJGf2ZTnq4HoFGC3zaTPZTobCzCFukA==", - "requires": { - "@babel/types": "^7.20.7" - } - }, - "@types/body-parser": { - "version": "1.19.5", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", - "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", - "devOptional": true, - "requires": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "@types/cacheable-request": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz", - "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==", - "requires": { - "@types/http-cache-semantics": "*", - "@types/keyv": "^3.1.4", - "@types/node": "*", - "@types/responselike": "^1.0.0" - } - }, - "@types/caseless": { - "version": "0.12.2", - "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.2.tgz", - "integrity": "sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==", - "dev": true - }, - "@types/connect": { - "version": "3.4.38", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", - "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "devOptional": true, - "requires": { - "@types/node": "*" - } - }, - "@types/cors": { - "version": "2.8.17", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", - "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/debug": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.8.tgz", - "integrity": "sha512-/vPO1EPOs306Cvhwv7KfVfYvOJqA/S/AXjaHQiJboCZzcNDb+TIJFN9/2C9DZ//ijSKWioNyUxD792QmDJ+HKQ==", - "requires": { - "@types/ms": "*" - } - }, - "@types/express": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", - "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", - "devOptional": true, - "requires": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "*" - } - }, - "@types/express-serve-static-core": { - "version": "4.17.41", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.41.tgz", - "integrity": "sha512-OaJ7XLaelTgrvlZD8/aa0vvvxZdUmlCn6MtWeB7TkiKW70BQLc9XEPpDLPdbo52ZhXUCrznlWdCHWxJWtdyajA==", - "devOptional": true, - "requires": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "@types/follow-redirects": { - "version": "1.14.4", - "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz", - "integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/glob": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-8.0.0.tgz", - "integrity": "sha512-l6NQsDDyQUVeoTynNpC9uRvCUint/gSUXQA2euwmTuWGvPY5LSDUu6tkCtJB2SvGQlJQzLaKqcGZP4//7EDveA==", - "dev": true, - "requires": { - "@types/minimatch": "*", - "@types/node": "*" - } - }, - "@types/graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "requires": { - "@types/node": "*" - } - }, - "@types/hast": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.4.tgz", - "integrity": "sha512-wLEm0QvaoawEDoTRwzTXp4b4jpwiJDvR5KMnFnVodm3scufTlBOWRD6N1OBf9TZMhjlNsSfcO5V+7AF4+Vy+9g==", - "requires": { - "@types/unist": "*" - } - }, - "@types/hoist-non-react-statics": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz", - "integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==", - "requires": { - "@types/react": "*", - "hoist-non-react-statics": "^3.3.0" - } - }, - "@types/http-cache-semantics": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz", - "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==" - }, - "@types/http-errors": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", - "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", - "devOptional": true - }, - "@types/http-proxy": { - "version": "1.17.14", - "resolved": "https://registry.npmjs.org/@types/http-proxy/-/http-proxy-1.17.14.tgz", - "integrity": "sha512-SSrD0c1OQzlFX7pGu1eXxSEjemej64aaNPRhhVYUGqXh0BtldAAx37MG8btcumvpgKyZp1F5Gn3JkktdxiFv6w==", - "requires": { - "@types/node": "*" - } - }, - "@types/istanbul-lib-coverage": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", - "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==" - }, - "@types/istanbul-lib-report": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", - "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", - "requires": { - "@types/istanbul-lib-coverage": "*" - } - }, - "@types/istanbul-reports": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", - "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", - "requires": { - "@types/istanbul-lib-report": "*" - } - }, - "@types/jest": { - "version": "29.5.11", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.11.tgz", - "integrity": "sha512-S2mHmYIVe13vrm6q4kN6fLYYAka15ALQki/vgDC3mIukEOx8WJlv0kQPM+d4w8Gp6u0uSdKND04IlTXBv0rwnQ==", - "requires": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "@types/json-schema": { - "version": "7.0.11", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.11.tgz", - "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", - "dev": true - }, - "@types/keyv": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", - "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==", - "requires": { - "@types/node": "*" - } - }, - "@types/lodash": { - "version": "4.14.191", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.191.tgz", - "integrity": "sha512-BdZ5BCCvho3EIXw6wUCXHe7rS53AIDPLE+JzwgT+OsJk53oBfbSmZZ7CX4VaRoN78N+TJpFi9QPlfIVNmJYWxQ==", - "dev": true - }, - "@types/mdast": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.11.tgz", - "integrity": "sha512-Y/uImid8aAwrEA24/1tcRZwpxX3pIFTSilcNDKSPn+Y2iDywSEachzRuvgAYYLR3wpGXAsMbv5lvKLDZLeYPAw==", - "requires": { - "@types/unist": "*" - } - }, - "@types/mime": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", - "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", - "devOptional": true - }, - "@types/minimatch": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz", - "integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==", - "dev": true - }, - "@types/ms": { - "version": "0.7.31", - "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz", - "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==" - }, - "@types/node": { - "version": "16.18.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.11.tgz", - "integrity": "sha512-3oJbGBUWuS6ahSnEq1eN2XrCyf4YsWI8OyCvo7c64zQJNplk3mO84t53o8lfTk+2ji59g5ycfc6qQ3fdHliHuA==" - }, - "@types/node-fetch": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.2.tgz", - "integrity": "sha512-DHqhlq5jeESLy19TYhLakJ07kNumXWjcDdxXsLUMJZ6ue8VZJj4kLPQVE/2mdHh3xZziNF1xppu5lwmS53HR+A==", - "dev": true, - "requires": { - "@types/node": "*", - "form-data": "^3.0.0" - } - }, - "@types/prettier": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", - "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", - "dev": true - }, - "@types/prop-types": { - "version": "15.7.5", - "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz", - "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==" - }, - "@types/qs": { - "version": "6.9.10", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.10.tgz", - "integrity": "sha512-3Gnx08Ns1sEoCrWssEgTSJs/rsT2vhGP+Ja9cnnk9k4ALxinORlQneLXFeFKOTJMOeZUFD1s7w+w2AphTpvzZw==", - "devOptional": true - }, - "@types/range-parser": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "devOptional": true - }, - "@types/react": { - "version": "18.0.28", - "resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.28.tgz", - "integrity": "sha512-RD0ivG1kEztNBdoAK7lekI9M+azSnitIn85h4iOiaLjaTrMjzslhaqCGaI4IyCJ1RljWiLCEu4jyrLLgqxBTew==", - "requires": { - "@types/prop-types": "*", - "@types/scheduler": "*", - "csstype": "^3.0.2" - } - }, - "@types/react-dom": { - "version": "18.2.4", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.2.4.tgz", - "integrity": "sha512-G2mHoTMTL4yoydITgOGwWdWMVd8sNgyEP85xVmMKAPUBwQWm9wBPQUmvbeF4V3WBY1P7mmL4BkjQ0SqUpf1snw==", - "devOptional": true, - "requires": { - "@types/react": "*" - } - }, - "@types/request": { - "version": "2.48.8", - "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.8.tgz", - "integrity": "sha512-whjk1EDJPcAR2kYHRbFl/lKeeKYTi05A15K9bnLInCVroNDCtXce57xKdI0/rQaA3K+6q0eFyUBPmqfSndUZdQ==", - "dev": true, - "requires": { - "@types/caseless": "*", - "@types/node": "*", - "@types/tough-cookie": "*", - "form-data": "^2.5.0" - }, - "dependencies": { - "form-data": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz", - "integrity": "sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.6", - "mime-types": "^2.1.12" - } - } - } - }, - "@types/responselike": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", - "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", - "requires": { - "@types/node": "*" - } - }, - "@types/scheduler": { - "version": "0.16.2", - "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz", - "integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew==" - }, - "@types/semver": { - "version": "7.5.6", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.6.tgz", - "integrity": "sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==", - "dev": true - }, - "@types/send": { - "version": "0.17.4", - "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", - "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", - "devOptional": true, - "requires": { - "@types/mime": "^1", - "@types/node": "*" - } - }, - "@types/serve-static": { - "version": "1.15.5", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.5.tgz", - "integrity": "sha512-PDRk21MnK70hja/YF8AHfC7yIsiQHn1rcXx7ijCFBX/k+XQJhQT/gw3xekXKJvx+5SXaMMS8oqQy09Mzvz2TuQ==", - "devOptional": true, - "requires": { - "@types/http-errors": "*", - "@types/mime": "*", - "@types/node": "*" - } - }, - "@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==" - }, - "@types/tough-cookie": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.2.tgz", - "integrity": "sha512-Q5vtl1W5ue16D+nIaW8JWebSSraJVlK+EthKn7e7UcD4KWsaSJ8BqGPXNaPghgtcn/fhvrN17Tv8ksUsQpiplw==", - "dev": true - }, - "@types/unist": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.6.tgz", - "integrity": "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==" - }, - "@types/use-sync-external-store": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz", - "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==" - }, - "@types/uuid": { - "version": "8.3.4", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.4.tgz", - "integrity": "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==" - }, - "@types/vscode": { - "version": "1.67.0", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.67.0.tgz", - "integrity": "sha512-GH8BDf8cw9AC9080uneJfulhSa7KHSMI2s/CyKePXoGNos9J486w2V4YKoeNUqIEkW4hKoEAWp6/cXTwyGj47g==", - "dev": true - }, - "@types/ws": { - "version": "8.5.4", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", - "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/yargs": { - "version": "17.0.32", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz", - "integrity": "sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==", - "requires": { - "@types/yargs-parser": "*" - } - }, - "@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==" - }, - "@typescript-eslint/eslint-plugin": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", - "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", - "dev": true, - "requires": { - "@eslint-community/regexpp": "^4.4.0", - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/type-utils": "5.62.0", - "@typescript-eslint/utils": "5.62.0", - "debug": "^4.3.4", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "natural-compare-lite": "^1.4.0", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/parser": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", - "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", - "dev": true, - "requires": { - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/typescript-estree": "5.62.0", - "debug": "^4.3.4" - } - }, - "@typescript-eslint/scope-manager": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", - "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0" - } - }, - "@typescript-eslint/type-utils": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", - "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", - "dev": true, - "requires": { - "@typescript-eslint/typescript-estree": "5.62.0", - "@typescript-eslint/utils": "5.62.0", - "debug": "^4.3.4", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/types": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", - "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", - "dev": true - }, - "@typescript-eslint/typescript-estree": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", - "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/utils": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", - "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", - "dev": true, - "requires": { - "@eslint-community/eslint-utils": "^4.2.0", - "@types/json-schema": "^7.0.9", - "@types/semver": "^7.3.12", - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/typescript-estree": "5.62.0", - "eslint-scope": "^5.1.1", - "semver": "^7.3.7" - } - }, - "@typescript-eslint/visitor-keys": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", - "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.62.0", - "eslint-visitor-keys": "^3.3.0" - } - }, - "@vscode/ripgrep": { - "version": "1.15.9", - "resolved": "https://registry.npmjs.org/@vscode/ripgrep/-/ripgrep-1.15.9.tgz", - "integrity": "sha512-4q2PXRvUvr3bF+LsfrifmUZgSPmCNcUZo6SbEAZgArIChchkezaxLoIeQMJe/z3CCKStvaVKpBXLxN3Z8lQjFQ==", - "requires": { - "https-proxy-agent": "^7.0.2", - "proxy-from-env": "^1.1.0", - "yauzl": "^2.9.2" - }, - "dependencies": { - "agent-base": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", - "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", - "requires": { - "debug": "^4.3.4" - } - }, - "https-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.2.tgz", - "integrity": "sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==", - "requires": { - "agent-base": "^7.0.2", - "debug": "4" - } - } - } - }, - "@vscode/test-electron": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.8.tgz", - "integrity": "sha512-b4aZZsBKtMGdDljAsOPObnAi7+VWIaYl3ylCz1jTs+oV6BZ4TNHcVNC3xUn0azPeszBmwSBDQYfFESIaUQnrOg==", - "dev": true, - "requires": { - "http-proxy-agent": "^4.0.1", - "https-proxy-agent": "^5.0.0", - "jszip": "^3.10.1", - "semver": "^7.5.2" - } - }, - "@vscode/vsce": { - "version": "2.22.0", - "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-2.22.0.tgz", - "integrity": "sha512-8df4uJiM3C6GZ2Sx/KilSKVxsetrTBBIUb3c0W4B1EWHcddioVs5mkyDKtMNP0khP/xBILVSzlXxhV+nm2rC9A==", - "dev": true, - "requires": { - "azure-devops-node-api": "^11.0.1", - "chalk": "^2.4.2", - "cheerio": "^1.0.0-rc.9", - "commander": "^6.2.1", - "glob": "^7.0.6", - "hosted-git-info": "^4.0.2", - "jsonc-parser": "^3.2.0", - "keytar": "^7.7.0", - "leven": "^3.1.0", - "markdown-it": "^12.3.2", - "mime": "^1.3.4", - "minimatch": "^3.0.3", - "parse-semver": "^1.1.1", - "read": "^1.0.7", - "semver": "^7.5.2", - "tmp": "^0.2.1", - "typed-rest-client": "^1.8.4", - "url-join": "^4.0.1", - "xml2js": "^0.5.0", - "yauzl": "^2.3.1", - "yazl": "^2.2.2" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "commander": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", - "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true - }, - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" - }, - "accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "requires": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - } - }, - "acorn": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", - "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", - "dev": true - }, - "acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "requires": {} - }, - "agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "requires": { - "debug": "4" - } - }, - "agentkeepalive": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.2.1.tgz", - "integrity": "sha512-Zn4cw2NEqd+9fiSVWMscnjyQ1a8Yfoc5oBajLeo5w+YBHgDUcEBY2hS4YpTz6iN5f/2zQiktcuM6tS8x1p9dpA==", - "requires": { - "debug": "^4.1.0", - "depd": "^1.1.2", - "humanize-ms": "^1.2.1" - }, - "dependencies": { - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==" - } - } - }, - "aggregate-error": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-4.0.1.tgz", - "integrity": "sha512-0poP0T7el6Vq3rstR8Mn4V/IQrpBLO6POkUSrN7RhyY+GF/InCFShQzsQ39T25gkHhLgSLByyAz+Kjb+c2L98w==", - "requires": { - "clean-stack": "^4.0.0", - "indent-string": "^5.0.0" - } - }, - "ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "requires": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "requires": { - "type-fest": "^0.21.3" - }, - "dependencies": { - "type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==" - } - } - }, - "ansi-regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", - "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==" - }, - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "requires": { - "color-convert": "^2.0.1" - } - }, - "any-promise": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==" - }, - "anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - } - }, - "aproba": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", - "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" - }, - "are-we-there-yet": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-3.0.1.tgz", - "integrity": "sha512-QZW4EDmGwlYur0Yyf/b2uGucHQMa8aFUP7eu9ddR73vvhFyt4V0Vl3QHPcTNJ8l6qYOBdxgXdnBXQrHilfRQBg==", - "requires": { - "delegates": "^1.0.0", - "readable-stream": "^3.6.0" - }, - "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "arg": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", - "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==" - }, - "argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" - }, - "array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true - }, - "arrify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-3.0.0.tgz", - "integrity": "sha512-tLkvA81vQG/XqE2mjDkGQHoOINtMHtysSnemrmoGe6PydDPMRbVugqyk4A6V/WDWEfm3l+0d8anA9r8cv/5Jaw==" - }, - "asn1": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", - "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", - "requires": { - "safer-buffer": "~2.1.0" - } - }, - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==" - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" - }, - "aws-sign2": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", - "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==" - }, - "aws4": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz", - "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==" - }, - "axios": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.5.tgz", - "integrity": "sha512-9pU/8mmjSSOb4CXVsvGIevN+MlO/t9OWtKadTaLuN85Gge3HGorUckgp8A/2FH4V4hJ7JuQ3LIeI7KAV9ITZrQ==", - "requires": { - "follow-redirects": "^1.15.0", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - }, - "dependencies": { - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } - } - }, - "azure-devops-node-api": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-11.2.0.tgz", - "integrity": "sha512-XdiGPhrpaT5J8wdERRKs5g8E0Zy1pvOYTli7z9E8nmOn3YGp4FhtjhrOyFmX/8veWCwdI69mCHKJw6l+4J/bHA==", - "dev": true, - "requires": { - "tunnel": "0.0.6", - "typed-rest-client": "^1.8.4" - } - }, - "babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "requires": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - } - }, - "babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "dependencies": { - "istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "requires": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - } - }, - "semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==" - } - } - }, - "babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "requires": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - } - }, - "babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", - "requires": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" - } - }, - "babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "requires": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" - } - }, - "bail": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", - "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==" - }, - "balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" - }, - "base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" - }, - "bcrypt-pbkdf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", - "requires": { - "tweetnacl": "^0.14.3" - } - }, - "binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==" - }, - "bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "requires": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - }, - "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", - "requires": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - } - } - }, - "boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", - "dev": true - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "requires": { - "fill-range": "^7.0.1" - } - }, - "browserslist": { - "version": "4.22.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.2.tgz", - "integrity": "sha512-0UgcrvQmBDvZHFGdYUehrCNIazki7/lUP3kkoi/r3YB2amZbFM9J43ZRkJTXBUZK4gmx56+Sqk9+Vs9mwZx9+A==", - "requires": { - "caniuse-lite": "^1.0.30001565", - "electron-to-chromium": "^1.4.601", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.13" - } - }, - "bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "requires": { - "node-int64": "^0.4.0" - } - }, - "buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "requires": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "buffer-crc32": { - "version": "0.2.13", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", - "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==" - }, - "buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==" - }, - "bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" - }, - "cacache": { - "version": "16.1.3", - "resolved": "https://registry.npmjs.org/cacache/-/cacache-16.1.3.tgz", - "integrity": "sha512-/+Emcj9DAXxX4cwlLmRI9c166RuL3w30zp4R7Joiv2cQTtTtA+jeuCAjH3ZlGnYS3tKENSrKhAzVVP9GVyzeYQ==", - "requires": { - "@npmcli/fs": "^2.1.0", - "@npmcli/move-file": "^2.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "glob": "^8.0.1", - "infer-owner": "^1.0.4", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "p-map": "^4.0.0", - "promise-inflight": "^1.0.1", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11", - "unique-filename": "^2.0.0" - }, - "dependencies": { - "lru-cache": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.14.1.tgz", - "integrity": "sha512-ysxwsnTKdAx96aTRdhDOCQfDgbHnt8SK0KY8SEjO0wHinhWOFTESbjVCMPbU1uGXg/ch4lifqx0wfjOawU2+WA==" - } - } - }, - "cacheable-lookup": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", - "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==" - }, - "cacheable-request": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", - "integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", - "requires": { - "clone-response": "^1.0.2", - "get-stream": "^5.1.0", - "http-cache-semantics": "^4.0.0", - "keyv": "^4.0.0", - "lowercase-keys": "^2.0.0", - "normalize-url": "^6.0.1", - "responselike": "^2.0.0" - }, - "dependencies": { - "get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "requires": { - "pump": "^3.0.0" - } - } - } - }, - "call-bind": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", - "requires": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - } - }, - "call-me-maybe": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", - "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==", - "dev": true - }, - "callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" - }, - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" - }, - "camelcase-css": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", - "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==" - }, - "caniuse-lite": { - "version": "1.0.30001570", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001570.tgz", - "integrity": "sha512-+3e0ASu4sw1SWaoCtvPeyXp+5PsjigkSt8OXZbF9StH5pQWbxEjLAZE3n8Aup5udop1uRiKA7a4utUk/uoSpUw==" - }, - "cargo-cp-artifact": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/cargo-cp-artifact/-/cargo-cp-artifact-0.1.8.tgz", - "integrity": "sha512-3j4DaoTrsCD1MRkTF2Soacii0Nx7UHCce0EwUf4fHnggwiE4fbmF2AbnfzayR36DF8KGadfh7M/Yfy625kgPlA==", - "dev": true - }, - "caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" - }, - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==" - }, - "character-entities": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", - "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==" - }, - "chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", - "dev": true - }, - "cheerio": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz", - "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==", - "dev": true, - "requires": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" - } - }, - "cheerio-select": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", - "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", - "dev": true, - "requires": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - } - }, - "chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", - "requires": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "fsevents": "~2.3.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "dependencies": { - "glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "requires": { - "is-glob": "^4.0.1" - } - } - } - }, - "chownr": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", - "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==" - }, - "ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==" - }, - "cjs-module-lexer": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", - "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==" - }, - "clean-stack": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-4.2.0.tgz", - "integrity": "sha512-LYv6XPxoyODi36Dp976riBtSY27VmFo+MKqEU9QCCWyTrdEPDog+RWA7xQWHi6Vbp61j5c4cdzzX1NidnwtUWg==", - "requires": { - "escape-string-regexp": "5.0.0" - }, - "dependencies": { - "escape-string-regexp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", - "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==" - } - } - }, - "cli-color": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-2.0.3.tgz", - "integrity": "sha512-OkoZnxyC4ERN3zLzZaY9Emb7f/MhBOIpePv0Ycok0fJYT+Ouo00UBEIwsVsr0yoow++n5YWlSUgST9GKhNHiRQ==", - "dev": true, - "requires": { - "d": "^1.0.1", - "es5-ext": "^0.10.61", - "es6-iterator": "^2.0.3", - "memoizee": "^0.4.15", - "timers-ext": "^0.1.7" - } - }, - "cli-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", - "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", - "requires": { - "restore-cursor": "^3.1.0" - } - }, - "cli-spinners": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.7.0.tgz", - "integrity": "sha512-qu3pN8Y3qHNgE2AFweciB1IfMnmZ/fsNTEE+NOFjmGB2F/7rLhnhzppvpCnN4FovtP26k8lHyy9ptEbNwWFLzw==" - }, - "cli-width": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", - "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", - "dev": true - }, - "cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "clone": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", - "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==" - }, - "clone-response": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", - "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==", - "requires": { - "mimic-response": "^1.0.0" - } - }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==" - }, - "collect-v8-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", - "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==" - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" - }, - "color-support": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==" - }, - "combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "comma-separated-tokens": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==" - }, - "commander": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", - "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "dev": true - }, - "compare-versions": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-4.1.4.tgz", - "integrity": "sha512-FemMreK9xNyL8gQevsdRMrvO4lFCkQP7qbuktn1q8ndcNk1+0mz7lgE7b/sNvbhVgY4w6tMN1FDp6aADjqw2rw==", - "dev": true - }, - "compute-scroll-into-view": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-2.0.4.tgz", - "integrity": "sha512-y/ZA3BGnxoM/QHHQ2Uy49CLtnWPbt4tTPpEEZiEmmiWBFKjej7nEyH8Ryz54jH0MLXflUYA3Er2zUxPSJu5R+g==" - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" - }, - "concurrently": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.5.1.tgz", - "integrity": "sha512-FlSwNpGjWQfRwPLXvJ/OgysbBxPkWpiVjy1042b0U7on7S7qwwMIILRj7WTN1mTgqa582bG6NFuScOoh6Zgdag==", - "dev": true, - "requires": { - "chalk": "^4.1.0", - "date-fns": "^2.16.1", - "lodash": "^4.17.21", - "rxjs": "^6.6.3", - "spawn-command": "^0.0.2-1", - "supports-color": "^8.1.0", - "tree-kill": "^1.2.2", - "yargs": "^16.2.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "dev": true, - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", - "dev": true, - "requires": { - "tslib": "^1.9.0" - } - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - }, - "supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - }, - "tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true - }, - "yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "dev": true, - "requires": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - } - }, - "yargs-parser": { - "version": "20.2.4", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", - "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", - "dev": true - } - } - }, - "consola": { - "version": "2.15.3", - "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", - "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", - "dev": true - }, - "console-control-strings": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" - }, - "console.table": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/console.table/-/console.table-0.10.0.tgz", - "integrity": "sha512-dPyZofqggxuvSf7WXvNjuRfnsOk1YazkVP8FdxH4tcH2c37wc79/Yl6Bhr7Lsu00KMgy2ql/qCMuNu8xctZM8g==", - "dev": true, - "requires": { - "easy-table": "1.1.0" - } - }, - "content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "requires": { - "safe-buffer": "5.2.1" - } - }, - "content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==" - }, - "convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" - }, - "cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==" - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" - }, - "core": { - "version": "file:../../core", - "requires": { - "@types/handlebars": "^4.1.0", - "@types/jest": "^29.5.11", - "@types/mustache": "^4.2.5", - "@types/uuid": "^9.0.7", - "dotenv": "^16.3.1", - "fastest-levenshtein": "^1.0.16", - "handlebars": "^4.7.8", - "jest": "^29.7.0", - "js-tiktoken": "^1.0.8", - "openai": "^4.20.1", - "replicate": "^0.23.0", - "ts-jest": "^29.1.1", - "uuid": "^9.0.1", - "web-tree-sitter": "^0.20.8" - } - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" - }, - "cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "requires": { - "object-assign": "^4", - "vary": "^1" - } - }, - "create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "requires": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - } - }, - "cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "requires": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - } - }, - "css-select": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz", - "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==", - "dev": true, - "requires": { - "boolbase": "^1.0.0", - "css-what": "^6.1.0", - "domhandler": "^5.0.2", - "domutils": "^3.0.1", - "nth-check": "^2.0.1" - } - }, - "css-what": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", - "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", - "dev": true - }, - "cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==" - }, - "csstype": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.1.tgz", - "integrity": "sha512-DJR/VvkAvSZW9bTouZue2sSxDwdTN92uHjqeKVm+0dAqdfNykRzQ95tay8aXMBAAPpUiq4Qcug2L7neoRh2Egw==" - }, - "d": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz", - "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==", - "dev": true, - "requires": { - "es5-ext": "^0.10.50", - "type": "^1.0.1" - } - }, - "dashdash": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", - "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", - "requires": { - "assert-plus": "^1.0.0" - } - }, - "date-fns": { - "version": "2.29.3", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.29.3.tgz", - "integrity": "sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA==", - "dev": true - }, - "debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "requires": { - "ms": "2.1.2" - } - }, - "decode-named-character-reference": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz", - "integrity": "sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==", - "requires": { - "character-entities": "^2.0.0" - } - }, - "decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "requires": { - "mimic-response": "^3.1.0" - }, - "dependencies": { - "mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==" - } - } - }, - "dedent": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", - "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", - "requires": {} - }, - "deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "dev": true - }, - "deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true - }, - "deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==" - }, - "defaults": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", - "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", - "requires": { - "clone": "^1.0.2" - } - }, - "defer-to-connect": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", - "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==" - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==" - }, - "delegates": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", - "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==" - }, - "depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" - }, - "dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==" - }, - "destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" - }, - "detect-libc": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz", - "integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w==" - }, - "detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==" - }, - "didyoumean": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", - "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==" - }, - "diff": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", - "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==" - }, - "diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==" - }, - "dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "requires": { - "path-type": "^4.0.0" - } - }, - "dlv": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", - "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==" - }, - "doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "dom-serializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", - "dev": true, - "requires": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "entities": "^4.2.0" - } - }, - "domelementtype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", - "dev": true - }, - "domhandler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", - "dev": true, - "requires": { - "domelementtype": "^2.3.0" - } - }, - "domutils": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.0.1.tgz", - "integrity": "sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==", - "dev": true, - "requires": { - "dom-serializer": "^2.0.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.1" - } - }, - "downshift": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/downshift/-/downshift-7.6.0.tgz", - "integrity": "sha512-VSoTVynTAsabou/hbZ6HJHUVhtBiVOjQoBsCPcQq5eAROIGP+9XKMp9asAKQ3cEcUP4oe0fFdD2pziUjhFY33Q==", - "requires": { - "@babel/runtime": "^7.14.8", - "compute-scroll-into-view": "^2.0.4", - "prop-types": "^15.7.2", - "react-is": "^17.0.2", - "tslib": "^2.3.0" - } - }, - "easy-table": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz", - "integrity": "sha512-oq33hWOSSnl2Hoh00tZWaIPi1ievrD9aFG82/IgjlycAnW9hHx5PkJiXpxPsgEE+H7BsbVQXFVFST8TEXS6/pA==", - "dev": true, - "requires": { - "wcwidth": ">=1.0.1" - } - }, - "ecc-jsbn": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", - "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", - "requires": { - "jsbn": "~0.1.0", - "safer-buffer": "^2.1.0" - } - }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" - }, - "electron-to-chromium": { - "version": "1.4.614", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.614.tgz", - "integrity": "sha512-X4ze/9Sc3QWs6h92yerwqv7aB/uU8vCjZcrMjA8N9R1pjMFRe44dLsck5FzLilOYvcXuDn93B+bpGYyufc70gQ==" - }, - "emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==" - }, - "emoji-regex": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.2.1.tgz", - "integrity": "sha512-97g6QgOk8zlDRdgq1WxwgTMgEWGVAQvB5Fdpgc1MkNy56la5SKP9GsMXKDOdqwn90/41a8yPwIGk1Y6WVbeMQA==" - }, - "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==" - }, - "encoding": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", - "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", - "optional": true, - "requires": { - "iconv-lite": "^0.6.2" - }, - "dependencies": { - "iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "optional": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - } - } - } - }, - "end-of-stream": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", - "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "requires": { - "once": "^1.4.0" - } - }, - "engine.io-client": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.5.2.tgz", - "integrity": "sha512-CQZqbrpEYnrpGqC07a9dJDz4gePZUgTPMU3NKJPSeQOyw27Tst4Pl3FemKoFGAlHzgZmKjoRmiJvbWfhCXUlIg==", - "requires": { - "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.1", - "engine.io-parser": "~5.2.1", - "ws": "~8.11.0", - "xmlhttprequest-ssl": "~2.0.0" - }, - "dependencies": { - "ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "requires": {} - } - } - }, - "engine.io-parser": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.1.tgz", - "integrity": "sha512-9JktcM3u18nU9N2Lz3bWeBgxVgOKpw7yhRaoxQA3FUDZzzw+9WlA6p4G4u0RixNkg14fH7EfEc/RhpurtiROTQ==" - }, - "entities": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz", - "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==", - "dev": true - }, - "env-paths": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", - "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==" - }, - "err-code": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", - "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==" - }, - "error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "requires": { - "is-arrayish": "^0.2.1" - } - }, - "es5-ext": { - "version": "0.10.62", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.62.tgz", - "integrity": "sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==", - "dev": true, - "requires": { - "es6-iterator": "^2.0.3", - "es6-symbol": "^3.1.3", - "next-tick": "^1.1.0" - } - }, - "es6-iterator": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", - "dev": true, - "requires": { - "d": "1", - "es5-ext": "^0.10.35", - "es6-symbol": "^3.1.1" - } - }, - "es6-symbol": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz", - "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==", - "dev": true, - "requires": { - "d": "^1.0.1", - "ext": "^1.1.2" - } - }, - "es6-weak-map": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.3.tgz", - "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==", - "dev": true, - "requires": { - "d": "1", - "es5-ext": "^0.10.46", - "es6-iterator": "^2.0.3", - "es6-symbol": "^3.1.1" - } - }, - "esbuild": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz", - "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==", - "dev": true, - "requires": { - "@esbuild/android-arm": "0.17.19", - "@esbuild/android-arm64": "0.17.19", - "@esbuild/android-x64": "0.17.19", - "@esbuild/darwin-arm64": "0.17.19", - "@esbuild/darwin-x64": "0.17.19", - "@esbuild/freebsd-arm64": "0.17.19", - "@esbuild/freebsd-x64": "0.17.19", - "@esbuild/linux-arm": "0.17.19", - "@esbuild/linux-arm64": "0.17.19", - "@esbuild/linux-ia32": "0.17.19", - "@esbuild/linux-loong64": "0.17.19", - "@esbuild/linux-mips64el": "0.17.19", - "@esbuild/linux-ppc64": "0.17.19", - "@esbuild/linux-riscv64": "0.17.19", - "@esbuild/linux-s390x": "0.17.19", - "@esbuild/linux-x64": "0.17.19", - "@esbuild/netbsd-x64": "0.17.19", - "@esbuild/openbsd-x64": "0.17.19", - "@esbuild/sunos-x64": "0.17.19", - "@esbuild/win32-arm64": "0.17.19", - "@esbuild/win32-ia32": "0.17.19", - "@esbuild/win32-x64": "0.17.19" - }, - "dependencies": { - "@esbuild/android-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", - "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==", - "dev": true, - "optional": true - } - } - }, - "escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" - }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" - }, - "escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true - }, - "eslint": { - "version": "8.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.32.0.tgz", - "integrity": "sha512-nETVXpnthqKPFyuY2FNjz/bEd6nbosRgKbkgS/y1C7LJop96gYHWpiguLecMHQ2XCPxn77DS0P+68WzG6vkZSQ==", - "dev": true, - "requires": { - "@eslint/eslintrc": "^1.4.1", - "@humanwhocodes/config-array": "^0.11.8", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "ajv": "^6.10.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.1.1", - "eslint-utils": "^3.0.0", - "eslint-visitor-keys": "^3.3.0", - "espree": "^9.4.0", - "esquery": "^1.4.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "grapheme-splitter": "^1.0.4", - "ignore": "^5.2.0", - "import-fresh": "^3.0.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-sdsl": "^4.1.4", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.1", - "regexpp": "^3.2.0", - "strip-ansi": "^6.0.1", - "strip-json-comments": "^3.1.0", - "text-table": "^0.2.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "eslint-scope": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.1.tgz", - "integrity": "sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==", - "dev": true, - "requires": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - } - }, - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "requires": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - } - }, - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - } - } - }, - "eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true - }, - "espree": { - "version": "9.4.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", - "integrity": "sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==", - "dev": true, - "requires": { - "acorn": "^8.8.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.3.0" - } - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" - }, - "esquery": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", - "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", - "dev": true, - "requires": { - "estraverse": "^5.1.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } - } - }, - "esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "requires": { - "estraverse": "^5.2.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } - } - }, - "estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true - }, - "esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true - }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==" - }, - "event-emitter": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", - "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==", - "dev": true, - "requires": { - "d": "1", - "es5-ext": "~0.10.14" - } - }, - "eventemitter3": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==" - }, - "execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "requires": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - } - }, - "exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==" - }, - "expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "dev": true - }, - "expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "requires": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" - } - }, - "express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", - "requires": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.1", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.5.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.2.0", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.7", - "qs": "6.11.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - } - } - }, - "ext": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", - "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", - "dev": true, - "requires": { - "type": "^2.7.2" - }, - "dependencies": { - "type": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/type/-/type-2.7.2.tgz", - "integrity": "sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw==", - "dev": true - } - } - }, - "extend": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" - }, - "external-editor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", - "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", - "dev": true, - "requires": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - }, - "dependencies": { - "tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "dev": true, - "requires": { - "os-tmpdir": "~1.0.2" - } - } - } - }, - "extsprintf": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", - "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==" - }, - "fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - }, - "fast-glob": { - "version": "3.2.12", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.12.tgz", - "integrity": "sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==", - "requires": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - }, - "dependencies": { - "glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "requires": { - "is-glob": "^4.0.1" - } - } - } - }, - "fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" - }, - "fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true - }, - "fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true - }, - "fastq": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", - "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", - "requires": { - "reusify": "^1.0.4" - } - }, - "fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "requires": { - "bser": "2.1.1" - } - }, - "fd-slicer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", - "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", - "requires": { - "pend": "~1.2.0" - } - }, - "figures": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", - "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5" - }, - "dependencies": { - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true - } - } - }, - "file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "requires": { - "flat-cache": "^3.0.4" - } - }, - "fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "requires": { - "to-regex-range": "^5.0.1" - } - }, - "finalhandler": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", - "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", - "requires": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - } - } - }, - "find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "requires": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - } - }, - "fkill": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fkill/-/fkill-8.1.0.tgz", - "integrity": "sha512-XrPKdURVYoXerpYx+zhhaXrO9vHVflnGD4JhwjOwg03vKwyOH6eZ+EY69aKDD+q1EbCzviVmD+9OG9rwQy+z/A==", - "requires": { - "aggregate-error": "^4.0.0", - "execa": "^5.1.1", - "pid-port": "^0.2.0", - "process-exists": "^4.1.0", - "ps-list": "^7.2.0", - "taskkill": "^4.0.0" - } - }, - "flat-cache": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", - "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", - "dev": true, - "requires": { - "flatted": "^3.1.0", - "rimraf": "^3.0.2" - } - }, - "flatted": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", - "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", - "dev": true - }, - "follow-redirects": { - "version": "1.15.4", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", - "integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==" - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==" - }, - "form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - }, - "forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" - }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==" - }, - "fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "dev": true - }, - "fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "requires": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - } - }, - "fs-minipass": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", - "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", - "requires": { - "minipass": "^3.0.0" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" - }, - "fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "optional": true - }, - "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" - }, - "gauge": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz", - "integrity": "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==", - "requires": { - "aproba": "^1.0.3 || ^2.0.0", - "color-support": "^1.1.3", - "console-control-strings": "^1.1.0", - "has-unicode": "^2.0.1", - "signal-exit": "^3.0.7", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "wide-align": "^1.1.5" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==" - }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" - }, - "get-intrinsic": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz", - "integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==", - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.3" - } - }, - "get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==" - }, - "get-stdin": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-8.0.0.tgz", - "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==", - "dev": true - }, - "get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==" - }, - "getpass": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", - "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", - "requires": { - "assert-plus": "^1.0.0" - } - }, - "github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "dev": true - }, - "glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - }, - "dependencies": { - "brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "requires": { - "balanced-match": "^1.0.0" - } - }, - "minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", - "requires": { - "brace-expansion": "^2.0.1" - } - } - } - }, - "glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "requires": { - "is-glob": "^4.0.3" - } - }, - "globals": { - "version": "13.19.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.19.0.tgz", - "integrity": "sha512-dkQ957uSRWHw7CFXLUtUHQI3g3aWApYhfNR2O6jn/907riyTYKVBmxYVROkBcY614FSSeSJh7Xm7SrUWCxvJMQ==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } - }, - "globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "requires": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - } - }, - "got": { - "version": "11.8.6", - "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz", - "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==", - "requires": { - "@sindresorhus/is": "^4.0.0", - "@szmarczak/http-timer": "^4.0.5", - "@types/cacheable-request": "^6.0.1", - "@types/responselike": "^1.0.0", - "cacheable-lookup": "^5.0.3", - "cacheable-request": "^7.0.2", - "decompress-response": "^6.0.0", - "http2-wrapper": "^1.0.0-beta.5.2", - "lowercase-keys": "^2.0.0", - "p-cancelable": "^2.0.0", - "responselike": "^2.0.0" - } - }, - "graceful-fs": { - "version": "4.2.10", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", - "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==" - }, - "grapheme-splitter": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", - "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", - "dev": true - }, - "graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true - }, - "har-schema": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", - "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==" - }, - "har-validator": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", - "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", - "requires": { - "ajv": "^6.12.3", - "har-schema": "^2.0.0" - } - }, - "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" - }, - "has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" - }, - "has-unicode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" - }, - "hast-util-whitespace": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-2.0.1.tgz", - "integrity": "sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==" - }, - "highlight.js": { - "version": "11.7.0", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.7.0.tgz", - "integrity": "sha512-1rRqesRFhMO/PRF+G86evnyJkCgaZFOI+Z6kdj15TA18funfoqJXvgPCLSf0SWq3SRfg1j3HlDs8o4s3EGq1oQ==" - }, - "highlightable": { - "version": "1.3.0-beta.0", - "resolved": "https://registry.npmjs.org/highlightable/-/highlightable-1.3.0-beta.0.tgz", - "integrity": "sha512-pDgzsLBus8oscL7KOqZ5rVMXgCnEmoig+G5gWoDczMm1SFDsNLzRwmNjkJoKdiA3q0oW/f+VqZ3W2YzG5lXQYA==", - "requires": { - "@types/react": "^18.0.28", - "emoji-regex": "^10.2.1", - "react": "^18.2.0", - "react-dom": "^18.2.0" - } - }, - "hoist-non-react-statics": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", - "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", - "requires": { - "react-is": "^16.7.0" - }, - "dependencies": { - "react-is": { - "version": "16.13.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" - } - } - }, - "hosted-git-info": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", - "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", - "dev": true, - "requires": { - "lru-cache": "^6.0.0" - } - }, - "html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==" - }, - "htmlparser2": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz", - "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==", - "dev": true, - "requires": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "domutils": "^3.0.1", - "entities": "^4.3.0" - } - }, - "http-cache-semantics": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", - "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" - }, - "http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "requires": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - } - }, - "http-proxy": { - "version": "1.18.1", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", - "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", - "requires": { - "eventemitter3": "^4.0.0", - "follow-redirects": "^1.0.0", - "requires-port": "^1.0.0" - } - }, - "http-proxy-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", - "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", - "dev": true, - "requires": { - "@tootallnate/once": "1", - "agent-base": "6", - "debug": "4" - } - }, - "http-proxy-middleware": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz", - "integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==", - "requires": { - "@types/http-proxy": "^1.17.8", - "http-proxy": "^1.18.1", - "is-glob": "^4.0.1", - "is-plain-obj": "^3.0.0", - "micromatch": "^4.0.2" - } - }, - "http-signature": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", - "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", - "requires": { - "assert-plus": "^1.0.0", - "jsprim": "^1.2.2", - "sshpk": "^1.7.0" - } - }, - "http2-wrapper": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", - "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", - "requires": { - "quick-lru": "^5.1.1", - "resolve-alpn": "^1.0.0" - } - }, - "https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "requires": { - "agent-base": "6", - "debug": "4" - } - }, - "human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==" - }, - "humanize-ms": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", - "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", - "requires": { - "ms": "^2.0.0" - } - }, - "iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" - }, - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true - }, - "immediate": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", - "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", - "dev": true - }, - "immer": { - "version": "9.0.19", - "resolved": "https://registry.npmjs.org/immer/-/immer-9.0.19.tgz", - "integrity": "sha512-eY+Y0qcsB4TZKwgQzLaE/lqYMlKhv5J9dyd2RhhtGhNo2njPXDqU9XPfcNfa3MIDsdtZt5KlkIsirlo4dHsWdQ==" - }, - "import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "requires": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - } - }, - "import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", - "requires": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==" - }, - "indent-string": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", - "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==" - }, - "infer-owner": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", - "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==" - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true - }, - "inline-style-parser": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.1.1.tgz", - "integrity": "sha512-7NXolsK4CAS5+xvdj5OMMbI962hU/wvwoxk+LWR9Ek9bVtyuuYScDN6eS0rUm6TxApFpw7CX1o4uJzcd4AyD3Q==" - }, - "inquirer": { - "version": "8.2.5", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.5.tgz", - "integrity": "sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ==", - "dev": true, - "requires": { - "ansi-escapes": "^4.2.1", - "chalk": "^4.1.1", - "cli-cursor": "^3.1.0", - "cli-width": "^3.0.0", - "external-editor": "^3.0.3", - "figures": "^3.0.0", - "lodash": "^4.17.21", - "mute-stream": "0.0.8", - "ora": "^5.4.1", - "run-async": "^2.4.0", - "rxjs": "^7.5.5", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0", - "through": "^2.3.6", - "wrap-ansi": "^7.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "ip": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", - "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" - }, - "ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" - }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" - }, - "is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "requires": { - "binary-extensions": "^2.0.0" - } - }, - "is-buffer": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz", - "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==" - }, - "is-ci": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", - "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", - "dev": true, - "requires": { - "ci-info": "^2.0.0" - }, - "dependencies": { - "ci-info": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", - "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", - "dev": true - } - } - }, - "is-core-module": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.12.1.tgz", - "integrity": "sha512-Q4ZuBAe2FUsKtyQJoQHlvP8OvBERxO3jEmy1I7hcRXcJBGGHFh/aJBswbXuS9sgrDH2QUO8ilkwNPHvHMd8clg==", - "requires": { - "has": "^1.0.3" - } - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==" - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" - }, - "is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==" - }, - "is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "requires": { - "is-extglob": "^2.1.1" - } - }, - "is-interactive": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", - "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==" - }, - "is-lambda": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", - "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==" - }, - "is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" - }, - "is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true - }, - "is-plain-obj": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz", - "integrity": "sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==" - }, - "is-promise": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", - "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==", - "dev": true - }, - "is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==" - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" - }, - "is-unicode-supported": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==" - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "dev": true - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" - }, - "isstream": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" - }, - "istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==" - }, - "istanbul-lib-instrument": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz", - "integrity": "sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA==", - "requires": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "dependencies": { - "semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "requires": { - "lru-cache": "^6.0.0" - } - } - } - }, - "istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "requires": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - } - }, - "istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "requires": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - } - }, - "istanbul-reports": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", - "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", - "requires": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - } - }, - "iterare": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", - "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", - "dev": true - }, - "jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", - "requires": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" - } - }, - "jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", - "requires": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0" - } - }, - "jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", - "requires": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - } - }, - "jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "requires": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" - } - }, - "jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "requires": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "dependencies": { - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "requires": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - } - }, - "jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", - "requires": { - "detect-newline": "^3.0.0" - } - }, - "jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", - "requires": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" - } - }, - "jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", - "requires": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - } - }, - "jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==" - }, - "jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "requires": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "fsevents": "^2.3.2", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - } - }, - "jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", - "requires": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - } - }, - "jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "requires": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - } - }, - "jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "requires": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - } - }, - "jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "requires": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-util": "^29.7.0" - } - }, - "jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "requires": {} - }, - "jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==" - }, - "jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", - "requires": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - } - }, - "jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", - "requires": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" - } - }, - "jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", - "requires": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - } - }, - "jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "requires": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "dependencies": { - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "requires": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - } - }, - "jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", - "requires": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - } - }, - "jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", - "requires": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "leven": "^3.1.0", - "pretty-format": "^29.7.0" - }, - "dependencies": { - "camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==" - } - } - }, - "jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "requires": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" - } - }, - "jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", - "requires": { - "@types/node": "*", - "jest-util": "^29.7.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "dependencies": { - "supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "jiti": { - "version": "1.18.2", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.18.2.tgz", - "integrity": "sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg==" - }, - "js-sdsl": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.2.0.tgz", - "integrity": "sha512-dyBIzQBDkCqCu+0upx25Y2jGdbTGxE9fshMsCdK0ViOongpV+n5tXRcZY9v7CaVQ79AGS9KA1KHtojxiM7aXSQ==", - "dev": true - }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" - }, - "js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "requires": { - "argparse": "^2.0.1" - } - }, - "jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" - }, - "jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==" - }, - "json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==" - }, - "json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" - }, - "json-schema": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", - "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" - }, - "json-schema-to-typescript": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/json-schema-to-typescript/-/json-schema-to-typescript-12.0.0.tgz", - "integrity": "sha512-Uk/BDIAo8vqepPBhM86UhNMHgCv7JulicNj/BgnQPHE1fGCoej0UTtcEYzXU/uk6lSvbZCf7pccW+dnNMrr5rg==", - "dev": true, - "requires": { - "@bcherny/json-schema-ref-parser": "10.0.5-fork", - "@types/json-schema": "^7.0.11", - "@types/lodash": "^4.14.182", - "@types/prettier": "^2.6.1", - "cli-color": "^2.0.2", - "get-stdin": "^8.0.0", - "glob": "^7.1.6", - "glob-promise": "^4.2.2", - "is-glob": "^4.0.3", - "lodash": "^4.17.21", - "minimist": "^1.2.6", - "mkdirp": "^1.0.4", - "mz": "^2.7.0", - "prettier": "^2.6.2" - }, - "dependencies": { - "@types/glob": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz", - "integrity": "sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==", - "dev": true, - "requires": { - "@types/minimatch": "*", - "@types/node": "*" - } - }, - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "glob-promise": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/glob-promise/-/glob-promise-4.2.2.tgz", - "integrity": "sha512-xcUzJ8NWN5bktoTIX7eOclO1Npxd/dyVqUJxlLIDasT4C7KZyqlPIwkdJ0Ypiy3p2ZKahTjK4M9uC3sNSfNMzw==", - "dev": true, - "requires": { - "@types/glob": "^7.1.3" - } - } - } - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" - }, - "json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" - }, - "jsonc-parser": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", - "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", - "dev": true - }, - "jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "requires": { - "graceful-fs": "^4.1.6", - "universalify": "^2.0.0" - } - }, - "jsprim": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", - "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", - "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.3.0", - "json-schema": "0.4.0", - "verror": "1.10.0" - } - }, - "jszip": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", - "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", - "dev": true, - "requires": { - "lie": "~3.3.0", - "pako": "~1.0.2", - "readable-stream": "~2.3.6", - "setimmediate": "^1.0.5" - } - }, - "keytar": { - "version": "7.9.0", - "resolved": "https://registry.npmjs.org/keytar/-/keytar-7.9.0.tgz", - "integrity": "sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==", - "dev": true, - "requires": { - "node-addon-api": "^4.3.0", - "prebuild-install": "^7.0.1" - } - }, - "keyv": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.2.tgz", - "integrity": "sha512-5MHbFaKn8cNSmVW7BYnijeAVlE4cYA/SVkifVgrh7yotnfhKmjuXpDKjrABLnT0SfHWV21P8ow07OGfRrNDg8g==", - "requires": { - "json-buffer": "3.0.1" - } - }, - "kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==" - }, - "leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==" - }, - "levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - } - }, - "lie": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", - "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", - "dev": true, - "requires": { - "immediate": "~3.0.5" - } - }, - "lilconfig": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", - "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==" - }, - "lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" - }, - "linkify-it": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", - "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", - "dev": true, - "requires": { - "uc.micro": "^1.0.1" - } - }, - "locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "requires": { - "p-locate": "^5.0.0" - } - }, - "lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true - }, - "lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true - }, - "log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", - "requires": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" - } - }, - "loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "requires": { - "js-tokens": "^3.0.0 || ^4.0.0" - } - }, - "lowercase-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", - "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" - }, - "lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "requires": { - "yallist": "^4.0.0" - } - }, - "lru-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/lru-queue/-/lru-queue-0.1.0.tgz", - "integrity": "sha512-BpdYkt9EvGl8OfWHDQPISVpcl5xZthb+XPsbELj5AQXxIC8IriDZIQYjBJPEm5rS420sjZ0TLEzRcq5KdBhYrQ==", - "dev": true, - "requires": { - "es5-ext": "~0.10.2" - } - }, - "lzma-native": { - "version": "8.0.6", - "resolved": "https://registry.npmjs.org/lzma-native/-/lzma-native-8.0.6.tgz", - "integrity": "sha512-09xfg67mkL2Lz20PrrDeNYZxzeW7ADtpYFbwSQh9U8+76RIzx5QsJBMy8qikv3hbUPfpy6hqwxt6FcGK81g9AA==", - "requires": { - "node-addon-api": "^3.1.0", - "node-gyp-build": "^4.2.1", - "readable-stream": "^3.6.0" - }, - "dependencies": { - "node-addon-api": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", - "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==" - }, - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "requires": { - "semver": "^7.5.3" - } - }, - "make-fetch-happen": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-10.2.1.tgz", - "integrity": "sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w==", - "requires": { - "agentkeepalive": "^4.2.1", - "cacache": "^16.1.0", - "http-cache-semantics": "^4.1.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.0", - "is-lambda": "^1.0.1", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-fetch": "^2.0.3", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "promise-retry": "^2.0.1", - "socks-proxy-agent": "^7.0.0", - "ssri": "^9.0.0" - }, - "dependencies": { - "@tootallnate/once": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", - "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==" - }, - "http-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", - "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", - "requires": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - } - }, - "lru-cache": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.14.1.tgz", - "integrity": "sha512-ysxwsnTKdAx96aTRdhDOCQfDgbHnt8SK0KY8SEjO0wHinhWOFTESbjVCMPbU1uGXg/ch4lifqx0wfjOawU2+WA==" - } - } - }, - "makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "requires": { - "tmpl": "1.0.5" - } - }, - "markdown-it": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", - "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", - "dev": true, - "requires": { - "argparse": "^2.0.1", - "entities": "~2.1.0", - "linkify-it": "^3.0.1", - "mdurl": "^1.0.1", - "uc.micro": "^1.0.5" - }, - "dependencies": { - "entities": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", - "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", - "dev": true - } - } - }, - "mdast-util-definitions": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-5.1.2.tgz", - "integrity": "sha512-8SVPMuHqlPME/z3gqVwWY4zVXn8lqKv/pAhC57FuJ40ImXyBpmO5ukh98zB2v7Blql2FiHjHv9LVztSIqjY+MA==", - "requires": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", - "unist-util-visit": "^4.0.0" - } - }, - "mdast-util-from-markdown": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.1.tgz", - "integrity": "sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==", - "requires": { - "@types/mdast": "^3.0.0", - "@types/unist": "^2.0.0", - "decode-named-character-reference": "^1.0.0", - "mdast-util-to-string": "^3.1.0", - "micromark": "^3.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-decode-string": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "unist-util-stringify-position": "^3.0.0", - "uvu": "^0.5.0" - } - }, - "mdast-util-to-hast": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-12.3.0.tgz", - "integrity": "sha512-pits93r8PhnIoU4Vy9bjW39M2jJ6/tdHyja9rrot9uujkN7UTU9SDnE6WNJz/IGyQk3XHX6yNNtrBH6cQzm8Hw==", - "requires": { - "@types/hast": "^2.0.0", - "@types/mdast": "^3.0.0", - "mdast-util-definitions": "^5.0.0", - "micromark-util-sanitize-uri": "^1.1.0", - "trim-lines": "^3.0.0", - "unist-util-generated": "^2.0.0", - "unist-util-position": "^4.0.0", - "unist-util-visit": "^4.0.0" - } - }, - "mdast-util-to-string": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-3.2.0.tgz", - "integrity": "sha512-V4Zn/ncyN1QNSqSBxTrMOLpjr+IKdHl2v3KVLoWmDPscP4r9GcCi71gjgvUV1SFSKh92AjAG4peFuBl2/YgCJg==", - "requires": { - "@types/mdast": "^3.0.0" - } - }, - "mdurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", - "integrity": "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", - "dev": true - }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==" - }, - "memoizee": { - "version": "0.4.15", - "resolved": "https://registry.npmjs.org/memoizee/-/memoizee-0.4.15.tgz", - "integrity": "sha512-UBWmJpLZd5STPm7PMUlOw/TSy972M+z8gcyQ5veOnSDRREz/0bmpyTfKt3/51DhEBqCZQn1udM/5flcSPYhkdQ==", - "dev": true, - "requires": { - "d": "^1.0.1", - "es5-ext": "^0.10.53", - "es6-weak-map": "^2.0.3", - "event-emitter": "^0.3.5", - "is-promise": "^2.2.2", - "lru-queue": "^0.1.0", - "next-tick": "^1.1.0", - "timers-ext": "^0.1.7" - } - }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" - }, - "merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" - }, - "merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==" - }, - "micromark": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.2.0.tgz", - "integrity": "sha512-uD66tJj54JLYq0De10AhWycZWGQNUvDI55xPgk2sQM5kn1JYlhbCMTtEeT27+vAhW2FBQxLlOmS3pmA7/2z4aA==", - "requires": { - "@types/debug": "^4.0.0", - "debug": "^4.0.0", - "decode-named-character-reference": "^1.0.0", - "micromark-core-commonmark": "^1.0.1", - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-chunked": "^1.0.0", - "micromark-util-combine-extensions": "^1.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-encode": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-resolve-all": "^1.0.0", - "micromark-util-sanitize-uri": "^1.0.0", - "micromark-util-subtokenize": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.1", - "uvu": "^0.5.0" - } - }, - "micromark-core-commonmark": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.1.0.tgz", - "integrity": "sha512-BgHO1aRbolh2hcrzL2d1La37V0Aoz73ymF8rAcKnohLy93titmv62E0gP8Hrx9PKcKrqCZ1BbLGbP3bEhoXYlw==", - "requires": { - "decode-named-character-reference": "^1.0.0", - "micromark-factory-destination": "^1.0.0", - "micromark-factory-label": "^1.0.0", - "micromark-factory-space": "^1.0.0", - "micromark-factory-title": "^1.0.0", - "micromark-factory-whitespace": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-chunked": "^1.0.0", - "micromark-util-classify-character": "^1.0.0", - "micromark-util-html-tag-name": "^1.0.0", - "micromark-util-normalize-identifier": "^1.0.0", - "micromark-util-resolve-all": "^1.0.0", - "micromark-util-subtokenize": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.1", - "uvu": "^0.5.0" - } - }, - "micromark-factory-destination": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-1.1.0.tgz", - "integrity": "sha512-XaNDROBgx9SgSChd69pjiGKbV+nfHGDPVYFs5dOoDd7ZnMAE+Cuu91BCpsY8RT2NP9vo/B8pds2VQNCLiu0zhg==", - "requires": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-factory-label": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.1.0.tgz", - "integrity": "sha512-OLtyez4vZo/1NjxGhcpDSbHQ+m0IIGnT8BoPamh+7jVlzLJBH98zzuCoUeMxvM6WsNeh8wx8cKvqLiPHEACn0w==", - "requires": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" - } - }, - "micromark-factory-space": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-1.1.0.tgz", - "integrity": "sha512-cRzEj7c0OL4Mw2v6nwzttyOZe8XY/Z8G0rzmWQZTBi/jjwyw/U4uqKtUORXQrR5bAZZnbTI/feRV/R7hc4jQYQ==", - "requires": { - "micromark-util-character": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-factory-title": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.1.0.tgz", - "integrity": "sha512-J7n9R3vMmgjDOCY8NPw55jiyaQnH5kBdV2/UXCtZIpnHH3P6nHUKaH7XXEYuWwx/xUJcawa8plLBEjMPU24HzQ==", - "requires": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-factory-whitespace": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-1.1.0.tgz", - "integrity": "sha512-v2WlmiymVSp5oMg+1Q0N1Lxmt6pMhIHD457whWM7/GUlEks1hI9xj5w3zbc4uuMKXGisksZk8DzP2UyGbGqNsQ==", - "requires": { - "micromark-factory-space": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-util-character": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-1.2.0.tgz", - "integrity": "sha512-lXraTwcX3yH/vMDaFWCQJP1uIszLVebzUa3ZHdrgxr7KEU/9mL4mVgCpGbyhvNLNlauROiNUq7WN5u7ndbY6xg==", - "requires": { - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-util-chunked": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-1.1.0.tgz", - "integrity": "sha512-Ye01HXpkZPNcV6FiyoW2fGZDUw4Yc7vT0E9Sad83+bEDiCJ1uXu0S3mr8WLpsz3HaG3x2q0HM6CTuPdcZcluFQ==", - "requires": { - "micromark-util-symbol": "^1.0.0" - } - }, - "micromark-util-classify-character": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-1.1.0.tgz", - "integrity": "sha512-SL0wLxtKSnklKSUplok1WQFoGhUdWYKggKUiqhX+Swala+BtptGCu5iPRc+xvzJ4PXE/hwM3FNXsfEVgoZsWbw==", - "requires": { - "micromark-util-character": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-util-combine-extensions": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.1.0.tgz", - "integrity": "sha512-Q20sp4mfNf9yEqDL50WwuWZHUrCO4fEyeDCnMGmG5Pr0Cz15Uo7KBs6jq+dq0EgX4DPwwrh9m0X+zPV1ypFvUA==", - "requires": { - "micromark-util-chunked": "^1.0.0", - "micromark-util-types": "^1.0.0" - } - }, - "micromark-util-decode-numeric-character-reference": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.1.0.tgz", - "integrity": "sha512-m9V0ExGv0jB1OT21mrWcuf4QhP46pH1KkfWy9ZEezqHKAxkj4mPCy3nIH1rkbdMlChLHX531eOrymlwyZIf2iw==", - "requires": { - "micromark-util-symbol": "^1.0.0" - } - }, - "micromark-util-decode-string": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.1.0.tgz", - "integrity": "sha512-YphLGCK8gM1tG1bd54azwyrQRjCFcmgj2S2GoJDNnh4vYtnL38JS8M4gpxzOPNyHdNEpheyWXCTnnTDY3N+NVQ==", - "requires": { - "decode-named-character-reference": "^1.0.0", - "micromark-util-character": "^1.0.0", - "micromark-util-decode-numeric-character-reference": "^1.0.0", - "micromark-util-symbol": "^1.0.0" - } - }, - "micromark-util-encode": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-1.1.0.tgz", - "integrity": "sha512-EuEzTWSTAj9PA5GOAs992GzNh2dGQO52UvAbtSOMvXTxv3Criqb6IOzJUBCmEqrrXSblJIJBbFFv6zPxpreiJw==" - }, - "micromark-util-html-tag-name": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.2.0.tgz", - "integrity": "sha512-VTQzcuQgFUD7yYztuQFKXT49KghjtETQ+Wv/zUjGSGBioZnkA4P1XXZPT1FHeJA6RwRXSF47yvJ1tsJdoxwO+Q==" - }, - "micromark-util-normalize-identifier": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.1.0.tgz", - "integrity": "sha512-N+w5vhqrBihhjdpM8+5Xsxy71QWqGn7HYNUvch71iV2PM7+E3uWGox1Qp90loa1ephtCxG2ftRV/Conitc6P2Q==", - "requires": { - "micromark-util-symbol": "^1.0.0" - } - }, - "micromark-util-resolve-all": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-1.1.0.tgz", - "integrity": "sha512-b/G6BTMSg+bX+xVCshPTPyAu2tmA0E4X98NSR7eIbeC6ycCqCeE7wjfDIgzEbkzdEVJXRtOG4FbEm/uGbCRouA==", - "requires": { - "micromark-util-types": "^1.0.0" - } - }, - "micromark-util-sanitize-uri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.2.0.tgz", - "integrity": "sha512-QO4GXv0XZfWey4pYFndLUKEAktKkG5kZTdUNaTAkzbuJxn2tNBOr+QtxR2XpWaMhbImT2dPzyLrPXLlPhph34A==", - "requires": { - "micromark-util-character": "^1.0.0", - "micromark-util-encode": "^1.0.0", - "micromark-util-symbol": "^1.0.0" - } - }, - "micromark-util-subtokenize": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.1.0.tgz", - "integrity": "sha512-kUQHyzRoxvZO2PuLzMt2P/dwVsTiivCK8icYTeR+3WgbuPqfHgPPy7nFKbeqRivBvn/3N3GBiNC+JRTMSxEC7A==", - "requires": { - "micromark-util-chunked": "^1.0.0", - "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0", - "uvu": "^0.5.0" - } - }, - "micromark-util-symbol": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-1.1.0.tgz", - "integrity": "sha512-uEjpEYY6KMs1g7QfJ2eX1SQEV+ZT4rUD3UcF6l57acZvLNK7PBZL+ty82Z1qhK1/yXIY4bdx04FKMgR0g4IAag==" - }, - "micromark-util-types": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-1.1.0.tgz", - "integrity": "sha512-ukRBgie8TIAcacscVHSiddHjO4k/q3pnedmzMQ4iwDcK0FtFCohKOlFbaOL/mPgfnPsL3C1ZyxJa4sbWrBl3jg==" - }, - "micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", - "requires": { - "braces": "^3.0.2", - "picomatch": "^2.3.1" - } - }, - "mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" - }, - "mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==" - }, - "mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "requires": { - "mime-db": "1.52.0" - } - }, - "mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" - }, - "mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" - }, - "minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", - "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", - "dev": true - }, - "minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "requires": { - "yallist": "^4.0.0" - } - }, - "minipass-collect": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz", - "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==", - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-fetch": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-2.1.2.tgz", - "integrity": "sha512-LT49Zi2/WMROHYoqGgdlQIZh8mLPZmOrN2NdJjMXxYe4nkN6FUyuPuOAOedNJDrx0IRGg9+4guZewtp8hE6TxA==", - "requires": { - "encoding": "^0.1.13", - "minipass": "^3.1.6", - "minipass-sized": "^1.0.3", - "minizlib": "^2.1.2" - } - }, - "minipass-flush": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", - "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-pipeline": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", - "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", - "requires": { - "minipass": "^3.0.0" - } - }, - "minipass-sized": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", - "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", - "requires": { - "minipass": "^3.0.0" - } - }, - "minizlib": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", - "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", - "requires": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - } - }, - "mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==" - }, - "mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "dev": true - }, - "mri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", - "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==" - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "mute-stream": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", - "dev": true - }, - "mz": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", - "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", - "requires": { - "any-promise": "^1.0.0", - "object-assign": "^4.0.1", - "thenify-all": "^1.0.0" - } - }, - "nanoid": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", - "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==" - }, - "napi-build-utils": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", - "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==", - "dev": true - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==" - }, - "natural-compare-lite": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", - "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", - "dev": true - }, - "ncp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ncp/-/ncp-2.0.0.tgz", - "integrity": "sha512-zIdGUrPRFTUELUvr3Gmc7KZ2Sw/h1PiVM0Af/oHB6zgnV1ikqSfRk+TOufi79aHYCW3NiOXmr1BP5nWbzojLaA==" - }, - "negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==" - }, - "next-tick": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", - "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", - "dev": true - }, - "node-abi": { - "version": "3.31.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.31.0.tgz", - "integrity": "sha512-eSKV6s+APenqVh8ubJyiu/YhZgxQpGP66ntzUb3lY1xB9ukSRaGnx0AIxI+IM+1+IVYC1oWobgG5L3Lt9ARykQ==", - "requires": { - "semver": "^7.3.5" - } - }, - "node-addon-api": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", - "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==", - "dev": true - }, - "node-api-version": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.1.4.tgz", - "integrity": "sha512-KGXihXdUChwJAOHO53bv9/vXcLmdUsZ6jIptbvYvkpKfth+r7jw44JkVxQFA3kX5nQjzjmGu1uAu/xNNLNlI5g==", - "requires": { - "semver": "^7.3.5" - } - }, - "node-fetch": { - "version": "2.6.8", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.8.tgz", - "integrity": "sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg==", - "dev": true, - "requires": { - "whatwg-url": "^5.0.0" - } - }, - "node-gyp": { - "version": "9.3.1", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-9.3.1.tgz", - "integrity": "sha512-4Q16ZCqq3g8awk6UplT7AuxQ35XN4R/yf/+wSAwcBUAjg7l58RTactWaP8fIDTi0FzI7YcVLujwExakZlfWkXg==", - "requires": { - "env-paths": "^2.2.0", - "glob": "^7.1.4", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^10.0.3", - "nopt": "^6.0.0", - "npmlog": "^6.0.0", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "tar": "^6.1.2", - "which": "^2.0.2" - }, - "dependencies": { - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "node-gyp-build": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.6.0.tgz", - "integrity": "sha512-NTZVKn9IylLwUzaKjkas1e4u2DLNcV4rdYagA4PWdPwW87Bi7z+BznyKSRwS/761tV/lzCGXplWsiaMjLqP2zQ==" - }, - "node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==" - }, - "node-machine-id": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/node-machine-id/-/node-machine-id-1.1.12.tgz", - "integrity": "sha512-QNABxbrPa3qEIfrE6GOJ7BYIuignnJw7iQ2YPbc3Nla1HzRJjXzZOiikfF8m7eAMfichLt3M4VgLOetqgDmgGQ==" - }, - "node-releases": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==" - }, - "nopt": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-6.0.0.tgz", - "integrity": "sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==", - "requires": { - "abbrev": "^1.0.0" - } - }, - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" - }, - "normalize-url": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", - "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==" - }, - "npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "requires": { - "path-key": "^3.0.0" - } - }, - "npmlog": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-6.0.2.tgz", - "integrity": "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==", - "requires": { - "are-we-there-yet": "^3.0.0", - "console-control-strings": "^1.1.0", - "gauge": "^4.0.3", - "set-blocking": "^2.0.0" - } - }, - "nth-check": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", - "dev": true, - "requires": { - "boolbase": "^1.0.0" - } - }, - "oauth-sign": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" - }, - "object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==" - }, - "object-hash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", - "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==" - }, - "object-inspect": { - "version": "1.12.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", - "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==" - }, - "on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "requires": { - "ee-first": "1.1.1" - } - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "requires": { - "wrappy": "1" - } - }, - "onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "requires": { - "mimic-fn": "^2.1.0" - } - }, - "optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", - "dev": true, - "requires": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.3" - } - }, - "ora": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", - "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", - "requires": { - "bl": "^4.1.0", - "chalk": "^4.1.0", - "cli-cursor": "^3.1.0", - "cli-spinners": "^2.5.0", - "is-interactive": "^1.0.0", - "is-unicode-supported": "^0.1.0", - "log-symbols": "^4.1.0", - "strip-ansi": "^6.0.0", - "wcwidth": "^1.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", - "dev": true - }, - "ovsx": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/ovsx/-/ovsx-0.8.3.tgz", - "integrity": "sha512-LG7wTzy4eYV/KolFeO4AwWPzQSARvCONzd5oHQlNvYOlji2r/zjbdK8pyObZN84uZlk6rQBWrJrAdJfh/SX0Hg==", - "dev": true, - "requires": { - "@vscode/vsce": "^2.19.0", - "commander": "^6.1.0", - "follow-redirects": "^1.14.6", - "is-ci": "^2.0.0", - "leven": "^3.1.0", - "semver": "^7.5.2", - "tmp": "^0.2.1" - }, - "dependencies": { - "commander": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", - "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", - "dev": true - } - } - }, - "p-cancelable": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", - "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==" - }, - "p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "requires": { - "yocto-queue": "^0.1.0" - } - }, - "p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "requires": { - "p-limit": "^3.0.2" - } - }, - "p-map": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", - "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", - "requires": { - "aggregate-error": "^3.0.0" - }, - "dependencies": { - "aggregate-error": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", - "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", - "requires": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - } - }, - "clean-stack": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", - "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" - }, - "indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" - } - } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" - }, - "pako": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", - "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", - "dev": true - }, - "parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "requires": { - "callsites": "^3.0.0" - } - }, - "parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - } - }, - "parse-semver": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/parse-semver/-/parse-semver-1.1.1.tgz", - "integrity": "sha512-Eg1OuNntBMH0ojvEKSrvDSnwLmvVuUOSdylH/pSCPNMIspLlweJyIWXCE+k/5hm3cj/EBUYwmWkjhBALNP4LXQ==", - "dev": true, - "requires": { - "semver": "^5.1.0" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - } - } - }, - "parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "dev": true, - "requires": { - "entities": "^4.4.0" - } - }, - "parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz", - "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==", - "dev": true, - "requires": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - } - }, - "parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" - }, - "path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==" - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==" - }, - "path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" - }, - "path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" - }, - "path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" - }, - "path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true - }, - "pend": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", - "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==" - }, - "performance-now": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==" - }, - "picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" - }, - "picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" - }, - "pid-port": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/pid-port/-/pid-port-0.2.0.tgz", - "integrity": "sha512-xVU9H1FCRSeGrD9Oim5bLg2U7B2BgW0qzK2oahpV5BIf9hwzqQaWyOkOVC0Kgbsc90A9x6525beawx+QK+JduQ==", - "requires": { - "execa": "^5.1.1" - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==" - }, - "pirates": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", - "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==" - }, - "pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "requires": { - "find-up": "^4.0.0" - }, - "dependencies": { - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "requires": { - "p-locate": "^4.1.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "requires": { - "p-limit": "^2.2.0" - } - } - } - }, - "postcss": { - "version": "8.4.24", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.24.tgz", - "integrity": "sha512-M0RzbcI0sO/XJNucsGjvWU9ERWxb/ytp1w6dKtxTKgixdtQDq4rmx/g8W1hnaheq9jgwL/oyEdH5Bc4WwJKMqg==", - "requires": { - "nanoid": "^3.3.6", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - } - }, - "postcss-import": { - "version": "15.1.0", - "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", - "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", - "requires": { - "postcss-value-parser": "^4.0.0", - "read-cache": "^1.0.0", - "resolve": "^1.1.7" - } - }, - "postcss-js": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", - "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", - "requires": { - "camelcase-css": "^2.0.1" - } - }, - "postcss-load-config": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.1.tgz", - "integrity": "sha512-vEJIc8RdiBRu3oRAI0ymerOn+7rPuMvRXslTvZUKZonDHFIczxztIyJ1urxM1x9JXEikvpWWTUUqal5j/8QgvA==", - "requires": { - "lilconfig": "^2.0.5", - "yaml": "^2.1.1" - } - }, - "postcss-nested": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.0.1.tgz", - "integrity": "sha512-mEp4xPMi5bSWiMbsgoPfcP74lsWLHkQbZc3sY+jWYd65CUwXrUaTp0fmNpa01ZcETKlIgUdFN/MpS2xZtqL9dQ==", - "requires": { - "postcss-selector-parser": "^6.0.11" - } - }, - "postcss-selector-parser": { - "version": "6.0.13", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz", - "integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==", - "requires": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - } - }, - "postcss-value-parser": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", - "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" - }, - "posthog-node": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-3.1.2.tgz", - "integrity": "sha512-atPGYjiK+QvtseKKsrUxMrzN84sIVs9jTa7nx5hl999gJly1S3J5r0DApwZ69NKfJkVIeLTCJyT0kyS+7WqDSw==", - "requires": { - "axios": "^0.27.0", - "rusha": "^0.8.14" - }, - "dependencies": { - "axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "requires": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } - } - }, - "prebuild-install": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", - "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", - "dev": true, - "requires": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^1.0.1", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - } - }, - "prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true - }, - "prettier": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz", - "integrity": "sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw==", - "dev": true - }, - "pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "requires": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==" - }, - "react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" - } - } - }, - "process-exists": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/process-exists/-/process-exists-4.1.0.tgz", - "integrity": "sha512-BBJoiorUKoP2AuM5q/yKwIfT1YWRHsaxjW+Ayu9erLhqKOfnXzzVVML0XTYoQZuI1YvcWKmc1dh06DEy4+KzfA==", - "requires": { - "ps-list": "^6.3.0" - }, - "dependencies": { - "ps-list": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/ps-list/-/ps-list-6.3.0.tgz", - "integrity": "sha512-qau0czUSB0fzSlBOQt0bo+I2v6R+xiQdj78e1BR/Qjfl5OHWJ/urXi8+ilw1eHe+5hSeDI1wrwVTgDp2wst4oA==" - } - } - }, - "process-nextick-args": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "dev": true - }, - "promise-inflight": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", - "integrity": "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==" - }, - "promise-retry": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", - "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", - "requires": { - "err-code": "^2.0.2", - "retry": "^0.12.0" - } - }, - "prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "requires": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - } - }, - "prop-types": { - "version": "15.8.1", - "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", - "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", - "requires": { - "loose-envify": "^1.4.0", - "object-assign": "^4.1.1", - "react-is": "^16.13.1" - }, - "dependencies": { - "react-is": { - "version": "16.13.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" - } - } - }, - "property-information": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-6.2.0.tgz", - "integrity": "sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==" - }, - "proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "requires": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - } - }, - "proxy-from-env": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", - "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" - }, - "ps-list": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/ps-list/-/ps-list-7.2.0.tgz", - "integrity": "sha512-v4Bl6I3f2kJfr5o80ShABNHAokIgY+wFDTQfE+X3zWYgSGQOCBeYptLZUpoOALBqO5EawmDN/tjTldJesd0ujQ==" - }, - "psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" - }, - "pump": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "punycode": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.2.2.tgz", - "integrity": "sha512-vKAcKbHEGA3cKbkNWwsA9MjHgIg4/X/xO/PnVQ/Pxt5eNC8/F726fGNlUlwwPej7NkmTg9OBWP4ovYvtdPtmXw==" - }, - "pure-rand": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz", - "integrity": "sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==" - }, - "qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", - "requires": { - "side-channel": "^1.0.4" - } - }, - "queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==" - }, - "quick-lru": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", - "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==" - }, - "range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" - }, - "raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", - "requires": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - } - }, - "rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "dev": true, - "requires": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "dependencies": { - "strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "dev": true - } - } - }, - "react": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz", - "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==", - "requires": { - "loose-envify": "^1.1.0" - } - }, - "react-dom": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz", - "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", - "requires": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.0" - } - }, - "react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==" - }, - "react-markdown": { - "version": "8.0.7", - "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-8.0.7.tgz", - "integrity": "sha512-bvWbzG4MtOU62XqBx3Xx+zB2raaFFsq4mYiAzfjXJMEz2sixgeAfraA3tvzULF02ZdOMUOKTBFFaZJDDrq+BJQ==", - "requires": { - "@types/hast": "^2.0.0", - "@types/prop-types": "^15.0.0", - "@types/unist": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "hast-util-whitespace": "^2.0.0", - "prop-types": "^15.0.0", - "property-information": "^6.0.0", - "react-is": "^18.0.0", - "remark-parse": "^10.0.0", - "remark-rehype": "^10.0.0", - "space-separated-tokens": "^2.0.0", - "style-to-object": "^0.4.0", - "unified": "^10.0.0", - "unist-util-visit": "^4.0.0", - "vfile": "^5.0.0" - }, - "dependencies": { - "react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" - } - } - }, - "react-redux": { - "version": "8.0.5", - "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.0.5.tgz", - "integrity": "sha512-Q2f6fCKxPFpkXt1qNRZdEDLlScsDWyrgSj0mliK59qU6W5gvBiKkdMEG2lJzhd1rCctf0hb6EtePPLZ2e0m1uw==", - "requires": { - "@babel/runtime": "^7.12.1", - "@types/hoist-non-react-statics": "^3.3.1", - "@types/use-sync-external-store": "^0.0.3", - "hoist-non-react-statics": "^3.3.2", - "react-is": "^18.0.0", - "use-sync-external-store": "^1.0.0" - }, - "dependencies": { - "react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" - } - } - }, - "read": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", - "integrity": "sha512-rSOKNYUmaxy0om1BNjMN4ezNT6VKK+2xF4GBhc81mkH7L60i6dp8qPYrkndNLT3QPphoII3maL9PVC9XmhHwVQ==", - "dev": true, - "requires": { - "mute-stream": "~0.0.4" - } - }, - "read-cache": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", - "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", - "requires": { - "pify": "^2.3.0" - } - }, - "readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - }, - "dependencies": { - "safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true - } - } - }, - "readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "requires": { - "picomatch": "^2.2.1" - } - }, - "redux": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz", - "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==", - "requires": { - "@babel/runtime": "^7.9.2" - } - }, - "redux-thunk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz", - "integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==", - "requires": {} - }, - "reflect-metadata": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", - "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", - "dev": true - }, - "regenerator-runtime": { - "version": "0.13.11", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", - "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" - }, - "regexpp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true - }, - "remark-parse": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-10.0.2.tgz", - "integrity": "sha512-3ydxgHa/ZQzG8LvC7jTXccARYDcRld3VfcgIIFs7bI6vbRSxJJmzgLEIIoYKyrfhaY+ujuWaf/PJiMZXoiCXgw==", - "requires": { - "@types/mdast": "^3.0.0", - "mdast-util-from-markdown": "^1.0.0", - "unified": "^10.0.0" - } - }, - "remark-rehype": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-10.1.0.tgz", - "integrity": "sha512-EFmR5zppdBp0WQeDVZ/b66CWJipB2q2VLNFMabzDSGR66Z2fQii83G5gTBbgGEnEEA0QRussvrFHxk1HWGJskw==", - "requires": { - "@types/hast": "^2.0.0", - "@types/mdast": "^3.0.0", - "mdast-util-to-hast": "^12.1.0", - "unified": "^10.0.0" - } - }, - "request": { - "version": "2.88.2", - "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", - "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", - "requires": { - "aws-sign2": "~0.7.0", - "aws4": "^1.8.0", - "caseless": "~0.12.0", - "combined-stream": "~1.0.6", - "extend": "~3.0.2", - "forever-agent": "~0.6.1", - "form-data": "~2.3.2", - "har-validator": "~5.1.3", - "http-signature": "~1.2.0", - "is-typedarray": "~1.0.0", - "isstream": "~0.1.2", - "json-stringify-safe": "~5.0.1", - "mime-types": "~2.1.19", - "oauth-sign": "~0.9.0", - "performance-now": "^2.1.0", - "qs": "~6.5.2", - "safe-buffer": "^5.1.2", - "tough-cookie": "~2.5.0", - "tunnel-agent": "^0.6.0", - "uuid": "^3.3.2" - }, - "dependencies": { - "form-data": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.6", - "mime-types": "^2.1.12" - } - }, - "qs": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", - "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==" - }, - "uuid": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" - } - } - }, - "require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" - }, - "requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==" - }, - "reselect": { - "version": "4.1.7", - "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.7.tgz", - "integrity": "sha512-Zu1xbUt3/OPwsXL46hvOOoQrap2azE7ZQbokq61BQfiXvhewsKDwhMeZjTX9sX0nvw1t/U5Audyn1I9P/m9z0A==" - }, - "resolve": { - "version": "1.22.2", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.2.tgz", - "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==", - "requires": { - "is-core-module": "^2.11.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - } - }, - "resolve-alpn": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz", - "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==" - }, - "resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "requires": { - "resolve-from": "^5.0.0" - }, - "dependencies": { - "resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" - } - } - }, - "resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true - }, - "resolve.exports": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", - "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==" - }, - "responselike": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", - "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==", - "requires": { - "lowercase-keys": "^2.0.0" - } - }, - "restore-cursor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", - "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", - "requires": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - } - }, - "retry": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", - "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==" - }, - "reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" - }, - "rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "requires": { - "glob": "^7.1.3" - }, - "dependencies": { - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "rollup": { - "version": "3.23.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-3.23.1.tgz", - "integrity": "sha512-ybRdFVHOoljGEFILHLd2g/qateqUdjE6YS41WXq4p3C/WwD3xtWxV4FYWETA1u9TeXQc5K8L8zHE5d/scOvrOQ==", - "dev": true, - "requires": { - "fsevents": "~2.3.2" - } - }, - "run-async": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", - "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", - "dev": true - }, - "run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "requires": { - "queue-microtask": "^1.2.2" - } - }, - "rusha": { - "version": "0.8.14", - "resolved": "https://registry.npmjs.org/rusha/-/rusha-0.8.14.tgz", - "integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA==" - }, - "rxjs": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.0.tgz", - "integrity": "sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==", - "dev": true, - "requires": { - "tslib": "^2.1.0" - } - }, - "sade": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", - "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", - "requires": { - "mri": "^1.1.0" - } - }, - "safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" - }, - "safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", - "dev": true - }, - "scheduler": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", - "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==", - "requires": { - "loose-envify": "^1.1.0" - } - }, - "semver": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", - "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", - "requires": { - "lru-cache": "^6.0.0" - } - }, - "send": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", - "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", - "requires": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - }, - "dependencies": { - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - } - } - }, - "ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - } - } - }, - "serve-static": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", - "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", - "requires": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.18.0" - } - }, - "set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" - }, - "setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", - "dev": true - }, - "setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" - }, - "shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "requires": { - "shebang-regex": "^3.0.0" - } - }, - "shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" - }, - "side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "requires": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - } - }, - "signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" - }, - "simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "dev": true - }, - "simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "dev": true, - "requires": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==" - }, - "slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==" - }, - "smart-buffer": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==" - }, - "socket.io-client": { - "version": "4.7.2", - "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.7.2.tgz", - "integrity": "sha512-vtA0uD4ibrYD793SOIAwlo8cj6haOeMHrGvwPxJsxH7CeIksqJ+3Zc06RvWTIFgiSqx4A3sOnTXpfAEE2Zyz6w==", - "requires": { - "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.2", - "engine.io-client": "~6.5.2", - "socket.io-parser": "~4.2.4" - } - }, - "socket.io-parser": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", - "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", - "requires": { - "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.1" - } - }, - "socks": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", - "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", - "requires": { - "ip": "^2.0.0", - "smart-buffer": "^4.2.0" - } - }, - "socks-proxy-agent": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-7.0.0.tgz", - "integrity": "sha512-Fgl0YPZ902wEsAyiQ+idGd1A7rSFx/ayC1CQVMw5P+EQx2V0SgpGtf6OKFhVjPflPUl9YMmEOnmfjCdMUsygww==", - "requires": { - "agent-base": "^6.0.2", - "debug": "^4.3.3", - "socks": "^2.6.2" - } - }, - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" - }, - "source-map-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", - "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==" - }, - "source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "space-separated-tokens": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==" - }, - "spawn-command": { - "version": "0.0.2-1", - "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2-1.tgz", - "integrity": "sha512-n98l9E2RMSJ9ON1AKisHzz7V42VDiBQGY6PB1BwRglz99wpVsSuGzQ+jOi6lFXBGVTCrRpltvjm+/XA+tpeJrg==", - "dev": true - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==" - }, - "sshpk": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", - "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", - "requires": { - "asn1": "~0.2.3", - "assert-plus": "^1.0.0", - "bcrypt-pbkdf": "^1.0.0", - "dashdash": "^1.12.0", - "ecc-jsbn": "~0.1.1", - "getpass": "^0.1.1", - "jsbn": "~0.1.0", - "safer-buffer": "^2.0.2", - "tweetnacl": "~0.14.0" - } - }, - "ssri": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.1.tgz", - "integrity": "sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q==", - "requires": { - "minipass": "^3.1.1" - } - }, - "stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "requires": { - "escape-string-regexp": "^2.0.0" - }, - "dependencies": { - "escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==" - } - } - }, - "statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "requires": { - "safe-buffer": "~5.1.0" - }, - "dependencies": { - "safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - } - } - }, - "string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "requires": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "requires": { - "ansi-regex": "^6.0.1" - } - }, - "strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==" - }, - "strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==" - }, - "strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==" - }, - "style-to-object": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.4.1.tgz", - "integrity": "sha512-HFpbb5gr2ypci7Qw+IOhnP2zOU7e77b+rzM+wTzXzfi1PrtBCX0E7Pk4wL4iTLnhzZ+JgEGAhX81ebTg/aYjQw==", - "requires": { - "inline-style-parser": "0.1.1" - } - }, - "sucrase": { - "version": "3.32.0", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.32.0.tgz", - "integrity": "sha512-ydQOU34rpSyj2TGyz4D2p8rbktIOZ8QY9s+DGLvFU1i5pWJE8vkpruCjGCMHsdXwnD7JDcS+noSwM/a7zyNFDQ==", - "requires": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "glob": "7.1.6", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "ts-interface-checker": "^0.1.9" - }, - "dependencies": { - "commander": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", - "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" - }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "requires": { - "has-flag": "^4.0.0" - } - }, - "supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" - }, - "tailwindcss": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.2.tgz", - "integrity": "sha512-9jPkMiIBXvPc2KywkraqsUfbfj+dHDb+JPWtSJa9MLFdrPyazI7q6WX2sUrm7R9eVR7qqv3Pas7EvQFzxKnI6w==", - "requires": { - "@alloc/quick-lru": "^5.2.0", - "arg": "^5.0.2", - "chokidar": "^3.5.3", - "didyoumean": "^1.2.2", - "dlv": "^1.1.3", - "fast-glob": "^3.2.12", - "glob-parent": "^6.0.2", - "is-glob": "^4.0.3", - "jiti": "^1.18.2", - "lilconfig": "^2.1.0", - "micromatch": "^4.0.5", - "normalize-path": "^3.0.0", - "object-hash": "^3.0.0", - "picocolors": "^1.0.0", - "postcss": "^8.4.23", - "postcss-import": "^15.1.0", - "postcss-js": "^4.0.1", - "postcss-load-config": "^4.0.1", - "postcss-nested": "^6.0.1", - "postcss-selector-parser": "^6.0.11", - "postcss-value-parser": "^4.2.0", - "resolve": "^1.22.2", - "sucrase": "^3.32.0" - } - }, - "tar": { - "version": "6.1.13", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.13.tgz", - "integrity": "sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw==", - "requires": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^4.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" - }, - "dependencies": { - "minipass": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.0.0.tgz", - "integrity": "sha512-g2Uuh2jEKoht+zvO6vJqXmYpflPqzRBT+Th2h01DKh5z7wbY/AZ2gCQ78cP70YoHPyFdY30YBV5WxgLOEwOykw==", - "requires": { - "yallist": "^4.0.0" - } - } - } - }, - "tar-fs": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", - "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", - "dev": true, - "requires": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - }, - "dependencies": { - "chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "dev": true - } - } - }, - "tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "dev": true, - "requires": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, - "taskkill": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/taskkill/-/taskkill-4.0.0.tgz", - "integrity": "sha512-h+BGQ8ExIUZ81h4iHRvatZY5eeBBl2WZk31MmMdFG9LBTc5eCH5u/bzZ7phaPH3bsiB7WhM7YTkOyB2dyFQfXg==", - "requires": { - "arrify": "^3.0.0", - "execa": "^5.1.1" - } - }, - "test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "requires": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "dependencies": { - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - } - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true - }, - "thenify": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", - "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", - "requires": { - "any-promise": "^1.0.0" - } - }, - "thenify-all": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", - "requires": { - "thenify": ">= 3.1.0 < 4" - } - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", - "dev": true - }, - "timers-ext": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/timers-ext/-/timers-ext-0.1.7.tgz", - "integrity": "sha512-b85NUNzTSdodShTIbky6ZF02e8STtVVfD+fu4aXXShEELpozH+bCpJLYMPZbsABN2wDH7fJpqIoXxJpzbf0NqQ==", - "dev": true, - "requires": { - "es5-ext": "~0.10.46", - "next-tick": "1" - } - }, - "tmp": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", - "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", - "dev": true, - "requires": { - "rimraf": "^3.0.0" - } - }, - "tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==" - }, - "to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==" - }, - "to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "requires": { - "is-number": "^7.0.0" - } - }, - "toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" - }, - "tough-cookie": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", - "requires": { - "psl": "^1.1.28", - "punycode": "^2.1.1" - } - }, - "tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true - }, - "tree-kill": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", - "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", - "dev": true - }, - "trim-lines": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==" - }, - "trough": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/trough/-/trough-2.1.0.tgz", - "integrity": "sha512-AqTiAOLcj85xS7vQ8QkAV41hPDIJ71XJB4RCUrzo/1GM2CQwhkJGaf9Hgr7BOugMRpgGUrqRg/DrBDl4H40+8g==" - }, - "ts-interface-checker": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", - "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==" - }, - "tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" - }, - "tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "requires": { - "tslib": "^1.8.1" - }, - "dependencies": { - "tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true - } - } - }, - "tunnel": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", - "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", - "dev": true - }, - "tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "requires": { - "safe-buffer": "^5.0.1" - } - }, - "tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" - }, - "type": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz", - "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==", - "dev": true - }, - "type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1" - } - }, - "type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==" - }, - "type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true - }, - "type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "requires": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - } - }, - "typed-rest-client": { - "version": "1.8.9", - "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.9.tgz", - "integrity": "sha512-uSmjE38B80wjL85UFX3sTYEUlvZ1JgCRhsWj/fJ4rZ0FqDUFoIuodtiVeE+cUqiVTOKPdKrp/sdftD15MDek6g==", - "dev": true, - "requires": { - "qs": "^6.9.1", - "tunnel": "0.0.6", - "underscore": "^1.12.1" - } - }, - "typescript": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", - "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - "dev": true - }, - "uc.micro": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", - "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", - "dev": true - }, - "uid": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.1.tgz", - "integrity": "sha512-PF+1AnZgycpAIEmNtjxGBVmKbZAQguaa4pBUq6KNaGEcpzZ2klCNZLM34tsjp76maN00TttiiUf6zkIBpJQm2A==", - "dev": true, - "requires": { - "@lukeed/csprng": "^1.0.0" - } - }, - "underscore": { - "version": "1.13.6", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", - "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==", - "dev": true - }, - "undici": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.2.0.tgz", - "integrity": "sha512-bglzaehBOLMe+BfK+Gv5Vpwpgdq2skaEBbSH92tcAv37wHHHTEGu43boyfTaHB+mwSo3VjyD/8d+ytPGeqsFIg==", - "requires": { - "@fastify/busboy": "^2.0.0" - } - }, - "unified": { - "version": "10.1.2", - "resolved": "https://registry.npmjs.org/unified/-/unified-10.1.2.tgz", - "integrity": "sha512-pUSWAi/RAnVy1Pif2kAoeWNBa3JVrx0MId2LASj8G+7AiHWoKZNTomq6LG326T68U7/e263X6fTdcXIy7XnF7Q==", - "requires": { - "@types/unist": "^2.0.0", - "bail": "^2.0.0", - "extend": "^3.0.0", - "is-buffer": "^2.0.0", - "is-plain-obj": "^4.0.0", - "trough": "^2.0.0", - "vfile": "^5.0.0" - }, - "dependencies": { - "is-plain-obj": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", - "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==" - } - } - }, - "unique-filename": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-2.0.1.tgz", - "integrity": "sha512-ODWHtkkdx3IAR+veKxFV+VBkUMcN+FaqzUUd7IZzt+0zhDZFPFxhlqwPF3YQvMHx1TD0tdgYl+kuPnJ8E6ql7A==", - "requires": { - "unique-slug": "^3.0.0" - } - }, - "unique-slug": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-3.0.0.tgz", - "integrity": "sha512-8EyMynh679x/0gqE9fT9oilG+qEt+ibFyqjuVTsZn1+CMxH+XLlpvr2UZx4nVcCwTpx81nICr2JQFkM+HPLq4w==", - "requires": { - "imurmurhash": "^0.1.4" - } - }, - "unist-util-generated": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unist-util-generated/-/unist-util-generated-2.0.1.tgz", - "integrity": "sha512-qF72kLmPxAw0oN2fwpWIqbXAVyEqUzDHMsbtPvOudIlUzXYFIeQIuxXQCRCFh22B7cixvU0MG7m3MW8FTq/S+A==" - }, - "unist-util-is": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-5.2.1.tgz", - "integrity": "sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw==", - "requires": { - "@types/unist": "^2.0.0" - } - }, - "unist-util-position": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-4.0.4.tgz", - "integrity": "sha512-kUBE91efOWfIVBo8xzh/uZQ7p9ffYRtUbMRZBNFYwf0RK8koUMx6dGUfwylLOKmaT2cs4wSW96QoYUSXAyEtpg==", - "requires": { - "@types/unist": "^2.0.0" - } - }, - "unist-util-stringify-position": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-3.0.3.tgz", - "integrity": "sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg==", - "requires": { - "@types/unist": "^2.0.0" - } - }, - "unist-util-visit": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-4.1.2.tgz", - "integrity": "sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==", - "requires": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0", - "unist-util-visit-parents": "^5.1.1" - } - }, - "unist-util-visit-parents": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz", - "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==", - "requires": { - "@types/unist": "^2.0.0", - "unist-util-is": "^5.0.0" - } - }, - "universalify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", - "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" - }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" - }, - "update-browserslist-db": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", - "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", - "requires": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" - } - }, - "uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "requires": { - "punycode": "^2.1.0" - } - }, - "url-join": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", - "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", - "dev": true - }, - "use-sync-external-store": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", - "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==", - "requires": {} - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" - }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==" - }, - "uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" - }, - "uuidv4": { - "version": "6.2.13", - "resolved": "https://registry.npmjs.org/uuidv4/-/uuidv4-6.2.13.tgz", - "integrity": "sha512-AXyzMjazYB3ovL3q051VLH06Ixj//Knx7QnUSi1T//Ie3io6CpsPu9nVMOx5MoLWh6xV0B9J0hIaxungxXUbPQ==", - "requires": { - "@types/uuid": "8.3.4", - "uuid": "8.3.2" - } - }, - "uvu": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz", - "integrity": "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA==", - "requires": { - "dequal": "^2.0.0", - "diff": "^5.0.0", - "kleur": "^4.0.3", - "sade": "^1.7.3" - }, - "dependencies": { - "kleur": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", - "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==" - } - } - }, - "v8-to-istanbul": { - "version": "9.2.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.2.0.tgz", - "integrity": "sha512-/EH/sDgxU2eGxajKdwLCDmQ4FWq+kpi3uCmBGpw1xJtnAxEjlD8j8PEiGWpCIMIs3ciNAgH0d3TTJiUkYzyZjA==", - "requires": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - } - }, - "vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==" - }, - "verror": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", - "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", - "requires": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - } - }, - "vfile": { - "version": "5.3.7", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-5.3.7.tgz", - "integrity": "sha512-r7qlzkgErKjobAmyNIkkSpizsFPYiUPuJb5pNW1RB4JcYVZhs4lIbVqk8XPk033CV/1z8ss5pkax8SuhGpcG8g==", - "requires": { - "@types/unist": "^2.0.0", - "is-buffer": "^2.0.0", - "unist-util-stringify-position": "^3.0.0", - "vfile-message": "^3.0.0" - } - }, - "vfile-message": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-3.1.4.tgz", - "integrity": "sha512-fa0Z6P8HUrQN4BZaX05SIVXic+7kE3b05PWAtPuYP9QLHsLKYR7/AlLW3NtOrpXRLeawpDLMsVkmk5DG0NXgWw==", - "requires": { - "@types/unist": "^2.0.0", - "unist-util-stringify-position": "^3.0.0" - } - }, - "vite": { - "version": "4.3.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.3.9.tgz", - "integrity": "sha512-qsTNZjO9NoJNW7KnOrgYwczm0WctJ8m/yqYAMAK9Lxt4SoySUfS5S8ia9K7JHpa3KEeMfyF8LoJ3c5NeBJy6pg==", - "dev": true, - "requires": { - "esbuild": "^0.17.5", - "fsevents": "~2.3.2", - "postcss": "^8.4.23", - "rollup": "^3.21.0" - } - }, - "vsce": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/vsce/-/vsce-2.15.0.tgz", - "integrity": "sha512-P8E9LAZvBCQnoGoizw65JfGvyMqNGlHdlUXD1VAuxtvYAaHBKLBdKPnpy60XKVDAkQCfmMu53g+gq9FM+ydepw==", - "dev": true, - "requires": { - "azure-devops-node-api": "^11.0.1", - "chalk": "^2.4.2", - "cheerio": "^1.0.0-rc.9", - "commander": "^6.1.0", - "glob": "^7.0.6", - "hosted-git-info": "^4.0.2", - "keytar": "^7.7.0", - "leven": "^3.1.0", - "markdown-it": "^12.3.2", - "mime": "^1.3.4", - "minimatch": "^3.0.3", - "parse-semver": "^1.1.1", - "read": "^1.0.7", - "semver": "^5.1.0", - "tmp": "^0.2.1", - "typed-rest-client": "^1.8.4", - "url-join": "^4.0.1", - "xml2js": "^0.4.23", - "yauzl": "^2.3.1", - "yazl": "^2.2.2" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "commander": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", - "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true - }, - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true - }, - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "xml2js": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", - "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", - "dev": true, - "requires": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - } - } - } - }, - "vscode-jsonrpc": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz", - "integrity": "sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ==" - }, - "vscode-languageclient": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-8.0.2.tgz", - "integrity": "sha512-lHlthJtphG9gibGb/y72CKqQUxwPsMXijJVpHEC2bvbFqxmkj9LwQ3aGU9dwjBLqsX1S4KjShYppLvg1UJDF/Q==", - "requires": { - "minimatch": "^3.0.4", - "semver": "^7.3.5", - "vscode-languageserver-protocol": "3.17.2" - } - }, - "vscode-languageserver-protocol": { - "version": "3.17.2", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz", - "integrity": "sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg==", - "requires": { - "vscode-jsonrpc": "8.0.2", - "vscode-languageserver-types": "3.17.2" - } - }, - "vscode-languageserver-types": { - "version": "3.17.2", - "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz", - "integrity": "sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA==" - }, - "walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "requires": { - "makeerror": "1.0.12" - } - }, - "wcwidth": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", - "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", - "requires": { - "defaults": "^1.0.3" - } - }, - "webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true - }, - "whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, - "requires": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "requires": { - "isexe": "^2.0.0" - } - }, - "wide-align": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", - "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", - "requires": { - "string-width": "^1.0.2 || 2 || 3 || 4" - } - }, - "word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true - }, - "wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" - }, - "write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "requires": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - } - }, - "ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "requires": {} - }, - "xml2js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", - "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", - "dev": true, - "requires": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - } - }, - "xmlbuilder": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", - "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", - "dev": true - }, - "xmlhttprequest-ssl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", - "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==" - }, - "y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" - }, - "yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, - "yaml": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.1.tgz", - "integrity": "sha512-2eHWfjaoXgTBC2jNM1LRef62VQa0umtvRiDSk6HSzW7RvS5YtkabJrwYLLEKWBc8a5U2PTSCs+dJjUTJdlHsWQ==" - }, - "yargs": { - "version": "17.6.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.2.tgz", - "integrity": "sha512-1/9UrdHjDZc0eOU0HxOHoS78C69UD3JRMvzlJ7S79S2nTaWRA/whGCTV8o9e/N/1Va9YIV7Q4sOxD8VV4pCWOw==", - "requires": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - } - }, - "yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==" - }, - "yauzl": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", - "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", - "requires": { - "buffer-crc32": "~0.2.3", - "fd-slicer": "~1.1.0" - } - }, - "yazl": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/yazl/-/yazl-2.5.1.tgz", - "integrity": "sha512-phENi2PLiHnHb6QBVot+dJnaAZ0xosj7p3fWl+znIjBDlnMI2PsZCJZ306BPTFOaHf5qdDEI8x5qFrSOBN5vrw==", - "dev": true, - "requires": { - "buffer-crc32": "~0.2.3" - } - }, - "yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==" - } } } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index bf9326c97..82ca08ef4 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -378,6 +378,7 @@ "@typescript-eslint/parser": "^5.45.0", "@vscode/test-electron": "^2.2.0", "@vscode/vsce": "^2.22.0", + "cargo-cp-artifact": "^0.1", "esbuild": "^0.17.19", "eslint": "^8.28.0", "glob": "^8.0.3", @@ -385,8 +386,7 @@ "ovsx": "^0.8.3", "typescript": "^5.3.3", "vite": "^4.3.9", - "vsce": "^2.15.0", - "cargo-cp-artifact": "^0.1" + "vsce": "^2.15.0" }, "dependencies": { "@electron/rebuild": "^3.2.10", @@ -404,6 +404,7 @@ "highlightable": "^1.3.0-beta.0", "http-proxy": "^1.18.1", "http-proxy-middleware": "^2.0.6", + "ignore": "^5.3.0", "jest": "^29.7.0", "ncp": "^2.0.0", "node-machine-id": "^1.1.12", @@ -416,6 +417,7 @@ "tailwindcss": "^3.3.2", "undici": "^6.2.0", "uuidv4": "^6.2.13", + "vectordb": "^0.4.3", "vscode-languageclient": "^8.0.2", "ws": "^8.13.0" }, diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 684e11825..6bdcecb35 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -24,6 +24,66 @@ exec("npm install", (error) => { console.log("stderr: ", stderr); throw error; } + + // Copy over some files required for native modules + + // sqlite3 + ncp( + path.join(__dirname, "../../../core/node_modules/sqlite3/build"), + path.join(__dirname, "../out/build"), + (error) => { + if (error) console.warn("Error copying sqlite3 files", error); + } + ); + + // onnxruntime-node + ncp( + path.join(__dirname, "../../../core/node_modules/onnxruntime-node/bin"), + path.join(__dirname, "../bin"), + (error) => { + if (error) + console.warn("Error copying onnxruntime-node files", error); + } + ); + if (process.env.target) { + // If building for production, only need the binaries for current platform + if (!process.env.target.startsWith("darwin")) { + fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/darwin"), { + recursive: true, + }); + } + if (!process.env.target.startsWith("linux")) { + fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/linux"), { + recursive: true, + }); + } + if (!process.env.target.startsWith("win")) { + fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/win32"), { + recursive: true, + }); + } + } + + // tree-sitter-wasms + ncp( + path.join( + __dirname, + "../../../core/node_modules/tree-sitter-wasms/out" + ), + path.join(__dirname, "../out/tree-sitter-wasms"), + (error) => { + if (error) + console.warn("Error copying tree-sitter-wasms files", error); + } + ); + fs.copyFileSync( + path.join( + __dirname, + "../../../core/node_modules/web-tree-sitter/tree-sitter.wasm" + ), + path.join(__dirname, "../out/tree-sitter.wasm") + ); + // Then copy over the dist folder to the Intellij extension const intellijExtensionWebviewPath = path.join( "..", @@ -41,7 +101,7 @@ exec("npm install", (error) => { fs.copyFileSync(indexHtmlPath, path.join("tmp_index.html")); fs.rmSync(intellijExtensionWebviewPath, { recursive: true }); fs.mkdirSync(intellijExtensionWebviewPath, { recursive: true }); - console.log(process.cwd()); + ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.log( diff --git a/extensions/vscode/server_version.txt b/extensions/vscode/server_version.txt deleted file mode 100644 index da5ce2084..000000000 --- a/extensions/vscode/server_version.txt +++ /dev/null @@ -1 +0,0 @@ -0.0.101 \ No newline at end of file diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index babd89fca..f9c0f0d37 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -7,10 +7,10 @@ import IdeProtocolClient from "../continueIdeClient"; import { ContinueGUIWebviewViewProvider } from "../debugPanel"; import registerQuickFixProvider from "../lang-server/codeActions"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import { vsCodeIndexCodebase } from "../util/indexCodebase"; import { getExtensionUri } from "../util/vscode"; import { setupInlineTips } from "./inlineTips"; import { startProxy } from "./proxy"; -// const sync = require("../sync.node"); export let extensionContext: vscode.ExtensionContext | undefined = undefined; export let ideProtocolClient: IdeProtocolClient; @@ -88,4 +88,5 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); startProxy(); + vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories()); } diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/continueIdeClient.ts index 4528d7cef..97a507bf7 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/continueIdeClient.ts @@ -13,15 +13,22 @@ import { rejectSuggestionCommand, showSuggestion as showSuggestionInEditor, } from "./suggestions"; +import { vsCodeIndexCodebase } from "./util/indexCodebase"; +import { defaultIgnoreFile, traverseDirectory } from "./util/traverseDirectory"; import { getUniqueId, openEditorAndRevealRange, uriFromFilePath, } from "./util/vscode"; +const util = require("util"); +const exec = util.promisify(require("child_process").exec); const continueVirtualDocumentScheme = "continue"; class IdeProtocolClient { + private static PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = + {}; + private readonly context: vscode.ExtensionContext; constructor(context: vscode.ExtensionContext) { @@ -52,6 +59,32 @@ class IdeProtocolClient { } }); + // Refresh index when branch is changed + this.getWorkspaceDirectories().forEach(async (dir) => { + const repo = await this.getRepo(vscode.Uri.file(dir)); + if (repo) { + repo.state.onDidChange(() => { + console.log("didUpdate"); + // args passed to this callback are always undefined, so keep track of previous branch + const currentBranch = repo?.state?.HEAD?.name; + if (currentBranch) { + if (IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) { + if ( + currentBranch !== + IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] + ) { + // Trigger refresh of index only in this directory + vsCodeIndexCodebase([dir]); + } + } + + IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = + currentBranch; + } + }); + } + }); + // Register a content provider for the readonly virtual documents const documentContentProvider = new (class implements vscode.TextDocumentContentProvider @@ -311,101 +344,21 @@ class IdeProtocolClient { directory: string, recursive: boolean ): Promise { - const nameAndType = ( - await vscode.workspace.fs.readDirectory(uriFromFilePath(directory)) - ).filter(([name, type]) => { - const DEFAULT_IGNORE_FILETYPES = [ - "DS_Store", - "-lock.json", - "lock", - "log", - "ttf", - "png", - "jpg", - "jpeg", - "gif", - "mp4", - "svg", - "ico", - "pdf", - "zip", - "gz", - "tar", - "dmg", - "tgz", - "rar", - "7z", - "exe", - "dll", - "obj", - "o", - "a", - "lib", - "so", - "dylib", - "ncb", - "sdf", - "woff", - "woff2", - "eot", - "cur", - "avi", - "mpg", - "mpeg", - "mov", - "mp3", - "mp4", - "mkv", - "mkv", - "webm", - "jar", - ]; - const DEFAULT_IGNORE_DIRS = [ - ".git", - ".vscode", - ".idea", - ".vs", - "venv", - ".venv", - "env", - ".env", - "node_modules", - "dist", - "build", - "target", - "out", - "bin", - ".pytest_cache", - ".vscode-test", - ".continue", - "__pycache__", - ]; - if ( - !DEFAULT_IGNORE_DIRS.some((dir) => - name.split(path.sep).includes(dir) - ) && - !DEFAULT_IGNORE_FILETYPES.some((filetype) => name.endsWith(filetype)) - ) { - return name; - } - }); - - let absolutePaths = nameAndType - .filter(([name, type]) => type === vscode.FileType.File) - .map(([name, type]) => path.join(directory, name)); - if (recursive) { - for (const [name, type] of nameAndType) { - if (type === vscode.FileType.Directory) { - const subdirectory = path.join(directory, name); - const subdirectoryContents = await this.getDirectoryContents( - subdirectory, - recursive - ); - absolutePaths = absolutePaths.concat(subdirectoryContents); - } - } + if (!recursive) { + return ( + await vscode.workspace.fs.readDirectory(uriFromFilePath(directory)) + ) + .filter(([name, type]) => { + type === vscode.FileType.File && !defaultIgnoreFile.ignores(name); + }) + .map(([name, type]) => path.join(directory, name)); } - return absolutePaths; + + const allFiles: string[] = []; + for await (const file of traverseDirectory(directory, [])) { + allFiles.push(file); + } + return allFiles; } getAbsolutePath(filepath: string): string { @@ -474,7 +427,7 @@ class IdeProtocolClient { return terminalContents; } - async getRepo(): Promise { + private async _getRepo(forDirectory: vscode.Uri): Promise { // Use the native git extension to get the branch name const extension = vscode.extensions.getExtension("vscode.git"); if ( @@ -482,42 +435,52 @@ class IdeProtocolClient { !extension.isActive || typeof vscode.workspace.workspaceFolders === "undefined" ) { - return "NONE"; + return undefined; } const git = extension.exports.getAPI(1); - let repo = git.getRepository(vscode.workspace.workspaceFolders[0].uri); - if (!repo) { - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - resolve(null); - }, 5000); - extension.exports.b.onDidChangeState((s: any) => { - clearTimeout(timeout); - resolve(null); - }); - }); + return git.getRepository(forDirectory); + } - let repo = git.getRepository(vscode.workspace.workspaceFolders[0].uri); - return repo; + async getRepo(forDirectory: vscode.Uri): Promise { + let repo = await this._getRepo(forDirectory); + let i = 0; + while (!repo) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + i++; + if (i >= 20) { + return undefined; + } + repo = await this._getRepo(forDirectory); } return repo; } - async getBranch(): Promise { - const repo = await this.getRepo(); + async getBranch(forDirectory: vscode.Uri) { + let repo = await this.getRepo(forDirectory); + if (repo === undefined) { + const { stdout } = await exec("git rev-parse --abbrev-ref HEAD", { + cwd: forDirectory.fsPath, + }); + return stdout?.trim() || "NONE"; + } return repo?.state?.HEAD?.name || "NONE"; } async getDiff(): Promise { - const repo = await this.getRepo(); + let diffs = []; - if (!repo) { - return ""; + for (const dir of this.getWorkspaceDirectories()) { + const repo = await this.getRepo(vscode.Uri.file(dir)); + if (!repo) { + continue; + } + + diffs.push((await repo.getDiff()).join("\n")); } - return (await repo.getDiff()).join("\n"); + return diffs.join("\n\n"); } getHighlightedCode(): RangeInFile[] { diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index d51711fab..3b5808ef6 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -302,6 +302,10 @@ export function getSidebarContent( respond(await ide.getWorkspaceDirs()); break; } + case "listFolders": { + respond(await ide.listFolders()); + break; + } case "writeFile": { respond( await ide.writeFile(data.message.path, data.message.contents) @@ -352,10 +356,9 @@ export function getSidebarContent( case "retrieveChunks": { respond( await ide.retrieveChunks( - data.message.v, + data.message.text, data.message.n, - data.message.tags, - data.message.providerId + data.message.directory ) ); break; diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index a8ff286e0..5ea2aeca4 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -25,10 +25,13 @@ import { intermediateToFinalConfig, serializedToIntermediateConfig, } from "core/config/load"; +import { LanceDbIndex } from "core/indexing/LanceDbIndex"; +import { IndexTag } from "core/indexing/types"; import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; +import { configHandler } from "./loadConfig"; import mergeJson from "./util/merge"; +import { traverseDirectory } from "./util/traverseDirectory"; import { getExtensionUri } from "./util/vscode"; -const sync = require("../sync.node"); async function buildConfigTs(browser: boolean) { if (!fs.existsSync(getConfigTsPath())) { @@ -133,6 +136,27 @@ class VsCodeIde implements IDE { ); }); + migrate("foldersContextProvider", () => { + if ( + !config.contextProviders?.filter((cp) => cp.name === "folders") + ?.length + ) { + config.contextProviders = [ + ...(config.contextProviders || []), + { + name: "folders", + params: {}, + }, + ]; + } + + fs.writeFileSync( + configPath, + JSON.stringify(config, undefined, 2), + "utf8" + ); + }); + migrate("renameFreeTrialProvider", () => { contents = contents.replace(/openai-free-trial/g, "free-trial"); fs.writeFileSync(configPath, contents, "utf8"); @@ -235,6 +259,19 @@ class VsCodeIde implements IDE { } } + async listFolders(): Promise { + const allDirs: string[] = []; + + const workspaceDirs = await this.getWorkspaceDirs(); + for (const directory of workspaceDirs) { + for await (const dir of traverseDirectory(directory, [], false)) { + allDirs.push(dir); + } + } + + return allDirs; + } + async getWorkspaceDirs(): Promise { return ideProtocolClient.getWorkspaceDirectories(); } @@ -374,36 +411,42 @@ class VsCodeIde implements IDE { async getFilesToEmbed( providerId: string ): Promise<[string, string, string][]> { - let results = []; - let branch = await ideProtocolClient.getBranch(); - for (let dir of await this.getWorkspaceDirs()) { - let tag = `${dir}::${branch}::${providerId}`; // TODO (don't build the string here ideally) - let filesToEmbed = sync.sync_results(dir, branch, providerId); - results.push(...filesToEmbed.map((r: any) => [tag, r.name, r.hash])); - } - return results; + return []; } async sendEmbeddingForChunk( chunk: Chunk, embedding: number[], tags: string[] - ) { - sync.add_chunk(chunk, tags, embedding); - } + ) {} async retrieveChunks( - v: number[], + text: string, n: number, - tags: string[], - providerId: string + directory: string | undefined ): Promise { - // TODO: OR clause with tags - let branch = await ideProtocolClient.getBranch(); - let dirs = await this.getWorkspaceDirs(); - let mainTag = `${dirs[0] || "NONE"}::${branch}::${providerId}`; - let chunks = sync.retrieve(n, [...tags, mainTag], v); - return chunks; + const embeddingsProvider = (await configHandler.loadConfig(new VsCodeIde())) + .embeddingsProvider; + if (!embeddingsProvider) { + return []; + } + const lanceDbIndex = new LanceDbIndex(embeddingsProvider, (path) => + ideProtocolClient.readFile(path) + ); + + const tags = await Promise.all( + (await this.getWorkspaceDirs()).map(async (dir) => { + let branch = await ideProtocolClient.getBranch(vscode.Uri.file(dir)); + let tag: IndexTag = { + directory: dir, + branch, + artifactId: lanceDbIndex.artifactId, + }; + return tag; + }) + ); + let chunks = await lanceDbIndex.retrieve(tags, text, n, directory); + return chunks as any[]; } } diff --git a/extensions/vscode/src/util/indexCodebase.ts b/extensions/vscode/src/util/indexCodebase.ts new file mode 100644 index 000000000..347c6538a --- /dev/null +++ b/extensions/vscode/src/util/indexCodebase.ts @@ -0,0 +1,92 @@ +import { LanceDbIndex } from "core/indexing/LanceDbIndex"; +import { getComputeDeleteAddRemove } from "core/indexing/refreshIndex"; +import { CodebaseIndex, IndexTag, LastModifiedMap } from "core/indexing/types"; +import * as vscode from "vscode"; +import { ideProtocolClient } from "../activation/activate"; +import { debugPanelWebview } from "../debugPanel"; +import { VsCodeIde } from "../ideProtocol"; +import { configHandler } from "../loadConfig"; + +const vscodeGetStats = async ( + directory: string | undefined +): Promise => { + const files = await new VsCodeIde().listWorkspaceContents(directory); + const pathToLastModified: { [path: string]: number } = {}; + await Promise.all( + files.map(async (file) => { + let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file)); + pathToLastModified[file] = stat.mtime; + }) + ); + + return pathToLastModified; +}; + +async function getIndexesToBuild(): Promise { + const indexes = []; + + const ide = new VsCodeIde(); + const config = await configHandler.loadConfig(ide); + if (config.embeddingsProvider) { + indexes.push(new LanceDbIndex(config.embeddingsProvider, ide.readFile)); + } + + return indexes; +} + +export async function vsCodeIndexCodebase(workspaceDirs: string[]) { + const update = (progress: number) => { + debugPanelWebview?.postMessage({ type: "indexProgress", progress }); + }; + + const indexesToBuild = await getIndexesToBuild(); + + let completedDirs = 0; + + for (let directory of workspaceDirs) { + const stats = await vscodeGetStats(directory); + const branch = await ideProtocolClient.getBranch( + vscode.Uri.file(directory) + ); + let completedIndexes = 0; + + try { + for (let codebaseIndex of indexesToBuild) { + const tag: IndexTag = { + directory, + branch, + artifactId: codebaseIndex.artifactId, + }; + const [results, markComplete] = await getComputeDeleteAddRemove( + tag, + stats, + (filepath) => ideProtocolClient.readFile(filepath) + ); + + console.log("RESULTS: ", results); + + for await (let progress of codebaseIndex.update( + tag, + results, + markComplete + )) { + update( + (completedDirs + + (completedIndexes + progress) / indexesToBuild.length) / + workspaceDirs.length + ); + } + completedIndexes++; + update( + (completedDirs + completedIndexes / indexesToBuild.length) / + workspaceDirs.length + ); + } + } catch (e) { + console.warn("Error refreshing index: ", e); + } + + completedDirs++; + update(completedDirs / workspaceDirs.length); + } +} diff --git a/extensions/vscode/src/util/traverseDirectory.ts b/extensions/vscode/src/util/traverseDirectory.ts new file mode 100644 index 000000000..510f4d1e6 --- /dev/null +++ b/extensions/vscode/src/util/traverseDirectory.ts @@ -0,0 +1,180 @@ +import ignore from "ignore"; +import * as path from "path"; +import * as vscode from "vscode"; +import { uriFromFilePath } from "./vscode"; + +const DEFAULT_IGNORE_FILETYPES = [ + "*.DS_Store", + "*-lock.json", + "*.lock", + "*.log", + "*.ttf", + "*.png", + "*.jpg", + "*.jpeg", + "*.gif", + "*.mp4", + "*.svg", + "*.ico", + "*.pdf", + "*.zip", + "*.gz", + "*.tar", + "*.dmg", + "*.tgz", + "*.rar", + "*.7z", + "*.exe", + "*.dll", + "*.obj", + "*.o", + "*.a", + "*.lib", + "*.so", + "*.dylib", + "*.ncb", + "*.sdf", + "*.woff", + "*.woff2", + "*.eot", + "*.cur", + "*.avi", + "*.mpg", + "*.mpeg", + "*.mov", + "*.mp3", + "*.mp4", + "*.mkv", + "*.mkv", + "*.webm", + "*.jar", + "*.onnx", +]; +export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); +const DEFAULT_IGNORE_DIRS = [ + ".git", + ".vscode", + ".idea", + ".vs", + "venv", + ".venv", + "env", + ".env", + "node_modules", + "dist", + "build", + "target", + "out", + "bin", + ".pytest_cache", + ".vscode-test", + ".continue", + "__pycache__", +]; +const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); + +function isIgnoreFilepath(filepath: string): boolean { + return ( + filepath.endsWith(".gitignore") || filepath.endsWith(".continueignore") + ); +} + +/** + * Given glob pattern, returns first non-wildcard path, rest of glob, and whether there was a leading wildcard + */ +function splitGlob(glob: string): [string | undefined, string, boolean] { + const segs = glob.split("/"); + let wildcards = 0; + while (segs[0] === "**") { + segs.shift(); + wildcards++; + } + return [segs.shift(), segs.join("/"), wildcards > 0]; +} + +export async function* traverseDirectory( + directory: string, + gitIgnorePatterns: string[], + returnFiles: boolean = true +): AsyncGenerator { + const nodes = await vscode.workspace.fs.readDirectory( + uriFromFilePath(directory) + ); + const files: string[] = []; + const dirs: string[] = []; + const ignorePatterns: string[] = []; + for (const [name, type] of nodes) { + switch (type) { + case vscode.FileType.Directory: + if (!defaultIgnoreDir.ignores(name)) { + dirs.push(name); + } + break; + case vscode.FileType.File: + if (!defaultIgnoreFile.ignores(name)) { + if (isIgnoreFilepath(name)) { + // Make sure you are respecting windows with linux dev container + const bytes = await vscode.workspace.fs.readFile( + uriFromFilePath(path.join(directory, name)) + ); + const contents = new TextDecoder().decode(bytes); + ignorePatterns.push( + ...contents.split("\n").filter((p) => p.trim() !== "") + ); + } else { + files.push(name); + } + } + break; + case vscode.FileType.SymbolicLink: + break; + case vscode.FileType.Unknown: + break; + } + } + + const allIgnorePatterns = [...gitIgnorePatterns, ...ignorePatterns]; + const ig = ignore().add(allIgnorePatterns); + + for (const node of returnFiles ? files : dirs) { + if (!ig.ignores(node)) { + yield path.join(directory, node); + } + } + + const subDirIgnorePatterns: { [key: string]: string[] } = {}; + const wildcardPatterns: string[] = []; + for (const ignorePattern of allIgnorePatterns) { + const [first, rest, leadingWildcard] = splitGlob(ignorePattern); + if (leadingWildcard) { + wildcardPatterns.push("**/" + rest); + } + if (first) { + if (subDirIgnorePatterns[first] === undefined) { + subDirIgnorePatterns[first] = []; + } + subDirIgnorePatterns[first].push(rest); + } + } + const entries = Object.entries(subDirIgnorePatterns); + + for (const dir of dirs) { + // Recurse if not ignored + if (!ig.ignores(dir)) { + // For patterns who can potentially match items of this subdir, strip the subdir from the start + const keepPatterns = [...wildcardPatterns]; + for (const [startPattern, subDirPatterns] of entries) { + if (ignore().add(startPattern).ignores(dir)) { + keepPatterns.push(...subDirPatterns); + } + } + for await (const file of traverseDirectory( + path.join(directory, dir), + keepPatterns, + returnFiles + )) { + yield file; + } + } + } +} diff --git a/extensions/vscode/src/util/vscode.ts b/extensions/vscode/src/util/vscode.ts index 27047f66d..dccc75905 100644 --- a/extensions/vscode/src/util/vscode.ts +++ b/extensions/vscode/src/util/vscode.ts @@ -120,14 +120,23 @@ function windowsToPosix(windowsPath: string): string { return posixPath; } +function isWindowsLocalButNotRemote(): boolean { + return ( + vscode.env.remoteName !== undefined && + ["wsl", "ssh-remote", "dev-container", "attached-container"].includes( + vscode.env.remoteName + ) && + process.platform === "win32" + ); +} + +export function getPathSep(): string { + return isWindowsLocalButNotRemote() ? "/" : path.sep; +} + export function uriFromFilePath(filepath: string): vscode.Uri { if (vscode.env.remoteName) { - if ( - ["wsl", "ssh-remote", "dev-container", "attached-container"].includes( - vscode.env.remoteName - ) && - process.platform === "win32" - ) { + if (isWindowsLocalButNotRemote()) { filepath = windowsToPosix(filepath); } return vscode.Uri.parse( diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 2b2f4af6b..40e367be5 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -2,6 +2,14 @@ # yarn lockfile v1 +"@75lb/deep-merge@^1.1.1": + version "1.1.1" + resolved "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz" + integrity sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw== + dependencies: + lodash.assignwith "^4.2.0" + typical "^7.1.1" + "@alloc/quick-lru@^5.2.0": version "5.2.0" resolved "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz" @@ -15,6 +23,22 @@ "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" +"@apache-arrow/ts@^14.0.2": + version "14.0.2" + resolved "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz" + integrity sha512-CtwAvLkK0CZv7xsYeCo91ml6PvlfzAmAJZkRYuz2GNBwfYufj5SVi0iuSMwIMkcU/szVwvLdzORSLa5PlF/2ug== + dependencies: + "@types/command-line-args" "5.2.0" + "@types/command-line-usage" "5.0.2" + "@types/node" "20.3.0" + "@types/pad-left" "2.1.1" + command-line-args "5.2.1" + command-line-usage "7.0.1" + flatbuffers "23.5.26" + json-bignum "^0.0.3" + pad-left "^2.1.0" + tslib "^2.5.3" + "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13", "@babel/code-frame@^7.22.13", "@babel/code-frame@^7.23.5": version "7.23.5" resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz" @@ -650,6 +674,11 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== +"@lancedb/vectordb-darwin-arm64@0.4.3": + version "0.4.3" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.3.tgz" + integrity sha512-47CvvSaV1EdUsFEpXUJApTk+hMzAhCxVizipCFUlXCgcmzpCDL86wNgJij/X9a+j6zADhIX//Lsu0qd/an/Bpw== + "@lukeed/csprng@^1.0.0": version "1.0.1" resolved "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.0.1.tgz" @@ -662,6 +691,11 @@ dependencies: cross-spawn "^7.0.1" +"@neon-rs/load@^0.0.74": + version "0.0.74" + resolved "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz" + integrity sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg== + "@nestjs/axios@0.0.8": version "0.0.8" resolved "https://registry.npmjs.org/@nestjs/axios/-/axios-0.0.8.tgz" @@ -880,6 +914,16 @@ resolved "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.2.tgz" integrity sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w== +"@types/command-line-args@5.2.0": + version "5.2.0" + resolved "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.0.tgz" + integrity sha512-UuKzKpJJ/Ief6ufIaIzr3A/0XnluX7RvFgwkV89Yzvm77wCh1kFaFmqN8XEnGcN62EuHdedQjEMb8mYxFLGPyA== + +"@types/command-line-usage@5.0.2": + version "5.0.2" + resolved "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz" + integrity sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg== + "@types/connect@*": version "3.4.38" resolved "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz" @@ -1062,6 +1106,16 @@ resolved "https://registry.npmjs.org/@types/node/-/node-16.18.11.tgz" integrity sha512-3oJbGBUWuS6ahSnEq1eN2XrCyf4YsWI8OyCvo7c64zQJNplk3mO84t53o8lfTk+2ji59g5ycfc6qQ3fdHliHuA== +"@types/node@20.3.0": + version "20.3.0" + resolved "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz" + integrity sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ== + +"@types/pad-left@2.1.1": + version "2.1.1" + resolved "https://registry.npmjs.org/@types/pad-left/-/pad-left-2.1.1.tgz" + integrity sha512-Xd22WCRBydkGSApl5Bw0PhAOHKSVjNL3E3AwzKaps96IMraPqy5BvZIsBVK6JLwdybUzjHnuWVwpDd0JjTfHXA== + "@types/prettier@^2.6.1": version "2.7.2" resolved "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz" @@ -1443,6 +1497,22 @@ anymatch@^3.0.3, anymatch@~3.1.2: normalize-path "^3.0.0" picomatch "^2.0.4" +apache-arrow@^14.0.2: + version "14.0.2" + resolved "https://registry.npmjs.org/apache-arrow/-/apache-arrow-14.0.2.tgz" + integrity sha512-EBO2xJN36/XoY81nhLcwCJgFwkboDZeyNQ+OPsG7bCoQjc2BT0aTyH/MR6SrL+LirSNz+cYqjGRlupMMlP1aEg== + dependencies: + "@types/command-line-args" "5.2.0" + "@types/command-line-usage" "5.0.2" + "@types/node" "20.3.0" + "@types/pad-left" "2.1.1" + command-line-args "5.2.1" + command-line-usage "7.0.1" + flatbuffers "23.5.26" + json-bignum "^0.0.3" + pad-left "^2.1.0" + tslib "^2.5.3" + "aproba@^1.0.3 || ^2.0.0": version "2.0.0" resolved "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz" @@ -1473,6 +1543,16 @@ argparse@^2.0.1: resolved "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +array-back@^3.0.1, array-back@^3.1.0: + version "3.1.0" + resolved "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz" + integrity sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q== + +array-back@^6.2.2: + version "6.2.2" + resolved "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz" + integrity sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw== + array-flatten@1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz" @@ -1523,12 +1603,12 @@ axios@^0.27.0: follow-redirects "^1.14.9" form-data "^4.0.0" -axios@^1.2.5: - version "1.2.5" - resolved "https://registry.npmjs.org/axios/-/axios-1.2.5.tgz" - integrity sha512-9pU/8mmjSSOb4CXVsvGIevN+MlO/t9OWtKadTaLuN85Gge3HGorUckgp8A/2FH4V4hJ7JuQ3LIeI7KAV9ITZrQ== +axios@^1.2.5, axios@^1.4.0: + version "1.6.5" + resolved "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz" + integrity sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg== dependencies: - follow-redirects "^1.15.0" + follow-redirects "^1.15.4" form-data "^4.0.0" proxy-from-env "^1.1.0" @@ -1819,6 +1899,13 @@ caseless@~0.12.0: resolved "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz" integrity sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw== +chalk-template@^0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz" + integrity sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg== + dependencies: + chalk "^4.1.2" + chalk@^2.4.2: version "2.4.2" resolved "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" @@ -1828,7 +1915,7 @@ chalk@^2.4.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" -chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1, chalk@4.1.2: +chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1, chalk@^4.1.2, chalk@4.1.2: version "4.1.2" resolved "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== @@ -2037,6 +2124,26 @@ comma-separated-tokens@^2.0.0: resolved "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz" integrity sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg== +command-line-args@^5.2.1, command-line-args@5.2.1: + version "5.2.1" + resolved "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz" + integrity sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg== + dependencies: + array-back "^3.1.0" + find-replace "^3.0.0" + lodash.camelcase "^4.3.0" + typical "^4.0.0" + +command-line-usage@^7.0.0, command-line-usage@7.0.1: + version "7.0.1" + resolved "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.1.tgz" + integrity sha512-NCyznE//MuTjwi3y84QVUGEOT+P5oto1e1Pk/jFPVdPPfsG03qpTIl3yw6etR+v73d0lXsoojRpvbru2sqePxQ== + dependencies: + array-back "^6.2.2" + chalk-template "^0.4.0" + table-layout "^3.0.0" + typical "^7.1.1" + commander@^4.0.0: version "4.1.1" resolved "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz" @@ -2139,13 +2246,18 @@ core-util-is@~1.0.0, core-util-is@1.0.2: version "1.0.0" resolved "file:../../core" dependencies: + "@xenova/transformers" "^2.14.0" dotenv "^16.3.1" fastest-levenshtein "^1.0.16" handlebars "^4.7.8" js-tiktoken "^1.0.8" openai "^4.20.1" replicate "^0.23.0" + sqlite "^5.1.1" + sqlite3 "^5.1.7" + tree-sitter-wasms "^0.1.6" uuid "^9.0.1" + vectordb "^0.4.3" web-tree-sitter "^0.20.8" cors@^2.8.5: @@ -2315,9 +2427,9 @@ destroy@1.2.0: integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== detect-libc@^2.0.0, detect-libc@^2.0.1: - version "2.0.1" - resolved "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz" - integrity sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w== + version "2.0.2" + resolved "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz" + integrity sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw== detect-newline@^3.0.0: version "3.1.0" @@ -2924,6 +3036,13 @@ finalhandler@1.2.0: statuses "2.0.1" unpipe "~1.0.0" +find-replace@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz" + integrity sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ== + dependencies: + array-back "^3.0.1" + find-up@^4.0.0: version "4.1.0" resolved "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz" @@ -2968,12 +3087,17 @@ flat-cache@^3.0.4: flatted "^3.1.0" rimraf "^3.0.2" +flatbuffers@23.5.26: + version "23.5.26" + resolved "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz" + integrity sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ== + flatted@^3.1.0: version "3.2.7" resolved "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz" integrity sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ== -follow-redirects@^1.0.0, follow-redirects@^1.14.6, follow-redirects@^1.14.9, follow-redirects@^1.15.0, follow-redirects@^1.15.4: +follow-redirects@^1.0.0, follow-redirects@^1.14.6, follow-redirects@^1.14.9, follow-redirects@^1.15.4: version "1.15.4" resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz" integrity sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw== @@ -3494,10 +3618,10 @@ ieee754@^1.1.13: resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== -ignore@^5.2.0: - version "5.2.4" - resolved "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz" - integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== +ignore@^5.2.0, ignore@^5.3.0: + version "5.3.0" + resolved "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz" + integrity sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg== immediate@~3.0.5: version "3.0.6" @@ -4173,6 +4297,11 @@ jsesc@^2.5.1: resolved "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz" integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA== +json-bignum@^0.0.3: + version "0.0.3" + resolved "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz" + integrity sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg== + json-buffer@3.0.1: version "3.0.1" resolved "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz" @@ -4338,6 +4467,16 @@ locate-path@^6.0.0: dependencies: p-locate "^5.0.0" +lodash.assignwith@^4.2.0: + version "4.2.0" + resolved "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz" + integrity sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g== + +lodash.camelcase@^4.3.0: + version "4.3.0" + resolved "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz" + integrity sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA== + lodash.merge@^4.6.2: version "4.6.2" resolved "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz" @@ -5174,6 +5313,13 @@ p-try@^2.0.0: resolved "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== +pad-left@^2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz" + integrity sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA== + dependencies: + repeat-string "^1.5.4" + pako@~1.0.2: version "1.0.11" resolved "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz" @@ -5715,6 +5861,11 @@ remark-rehype@^10.0.0: mdast-util-to-hast "^12.1.0" unified "^10.0.0" +repeat-string@^1.5.4: + version "1.6.1" + resolved "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz" + integrity sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w== + request@^2.88.2: version "2.88.2" resolved "https://registry.npmjs.org/request/-/request-2.88.2.tgz" @@ -5916,14 +6067,7 @@ semver@^6.3.1: resolved "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz" integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== -semver@^7.3.5, semver@^7.3.7, semver@^7.5.2, semver@^7.5.3: - version "7.5.3" - resolved "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz" - integrity sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ== - dependencies: - lru-cache "^6.0.0" - -semver@^7.5.4: +semver@^7.3.5, semver@^7.3.7, semver@^7.5.2, semver@^7.5.3, semver@^7.5.4: version "7.5.4" resolved "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz" integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== @@ -6131,6 +6275,11 @@ statuses@2.0.1: resolved "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== +stream-read-all@^3.0.1: + version "3.0.1" + resolved "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz" + integrity sha512-EWZT9XOceBPlVJRrYcykW8jyRSZYbkb/0ZK36uLEmoWVO5gxBOnntNTseNzfREsqxqdfEGQrD8SXQ3QWbBmq8A== + string_decoder@^1.1.1, string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz" @@ -6249,6 +6398,19 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== +table-layout@^3.0.0: + version "3.0.2" + resolved "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz" + integrity sha512-rpyNZYRw+/C+dYkcQ3Pr+rLxW4CfHpXjPDnG7lYhdRoUcZTUt+KEsX+94RGp/aVp/MQU35JCITv2T/beY4m+hw== + dependencies: + "@75lb/deep-merge" "^1.1.1" + array-back "^6.2.2" + command-line-args "^5.2.1" + command-line-usage "^7.0.0" + stream-read-all "^3.0.1" + typical "^7.1.1" + wordwrapjs "^5.1.0" + tailwindcss@^3.3.2: version "3.3.2" resolved "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.2.tgz" @@ -6444,6 +6606,11 @@ tslib@^2.1.0, tslib@^2.3.0, tslib@2.4.0: resolved "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz" integrity sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ== +tslib@^2.5.3: + version "2.6.2" + resolved "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz" + integrity sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q== + tslib@2.0.3: version "2.0.3" resolved "https://registry.npmjs.org/tslib/-/tslib-2.0.3.tgz" @@ -6532,6 +6699,16 @@ typescript@^5.3.3, "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4 resolved "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz" integrity sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw== +typical@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz" + integrity sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw== + +typical@^7.1.1: + version "7.1.1" + resolved "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz" + integrity sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA== + uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" resolved "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz" @@ -6713,6 +6890,22 @@ vary@^1, vary@~1.1.2: resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz" integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg== +vectordb@^0.4.3: + version "0.4.3" + resolved "https://registry.npmjs.org/vectordb/-/vectordb-0.4.3.tgz" + integrity sha512-7ToixoZgAB/hn44EE4ftcdE74SGRX+wmGejatTQodFBiYD9RQLW8LIuGo8MmT+AkYEDAuOR98jTEFUwnEU5sqA== + dependencies: + "@apache-arrow/ts" "^14.0.2" + "@neon-rs/load" "^0.0.74" + apache-arrow "^14.0.2" + axios "^1.4.0" + optionalDependencies: + "@lancedb/vectordb-darwin-arm64" "0.4.3" + "@lancedb/vectordb-darwin-x64" "0.4.3" + "@lancedb/vectordb-linux-arm64-gnu" "0.4.3" + "@lancedb/vectordb-linux-x64-gnu" "0.4.3" + "@lancedb/vectordb-win32-x64-msvc" "0.4.3" + verror@1.10.0: version "1.10.0" resolved "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz" @@ -6850,6 +7043,11 @@ word-wrap@^1.2.3: resolved "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== +wordwrapjs@^5.1.0: + version "5.1.0" + resolved "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.0.tgz" + integrity sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg== + wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz" diff --git a/gui/package-lock.json b/gui/package-lock.json index 2ea136ae9..70c216665 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -66,13 +66,18 @@ "version": "1.0.0", "license": "Apache-2.0", "dependencies": { + "@xenova/transformers": "^2.14.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", + "vectordb": "^0.4.3", "web-tree-sitter": "^0.20.8" }, "devDependencies": { @@ -7481,6 +7486,7 @@ "@types/jest": "^29.5.11", "@types/mustache": "^4.2.5", "@types/uuid": "^9.0.7", + "@xenova/transformers": "^2.14.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", @@ -7488,8 +7494,12 @@ "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", "ts-jest": "^29.1.1", "uuid": "^9.0.1", + "vectordb": "^0.4.3", "web-tree-sitter": "^0.20.8" } }, diff --git a/gui/package.json b/gui/package.json index f231737dc..7d6cb128e 100644 --- a/gui/package.json +++ b/gui/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "scripts": { "dev": "vite", - "build": "cd ../webworker && npm i && npm run build && cd ../gui && tsc && vite build", + "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { diff --git a/gui/public/ort-wasm/ort-wasm-simd.wasm b/gui/public/ort-wasm/ort-wasm-simd.wasm deleted file mode 100644 index b4985f027..000000000 Binary files a/gui/public/ort-wasm/ort-wasm-simd.wasm and /dev/null differ diff --git a/gui/public/tree-sitter.wasm b/gui/public/tree-sitter.wasm deleted file mode 100644 index d9ca0da7b..000000000 Binary files a/gui/public/tree-sitter.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-bash.wasm b/gui/public/tree-sitter/tree-sitter-bash.wasm deleted file mode 100755 index 7453c7e0e..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-bash.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-c.wasm b/gui/public/tree-sitter/tree-sitter-c.wasm deleted file mode 100755 index 8a5e66c8f..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-c.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-c_sharp.wasm b/gui/public/tree-sitter/tree-sitter-c_sharp.wasm deleted file mode 100755 index 644a3f8c7..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-c_sharp.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-css.wasm b/gui/public/tree-sitter/tree-sitter-css.wasm deleted file mode 100755 index 711c7732f..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-css.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-go.wasm b/gui/public/tree-sitter/tree-sitter-go.wasm deleted file mode 100755 index 2b1b8ff0e..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-go.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-html.wasm b/gui/public/tree-sitter/tree-sitter-html.wasm deleted file mode 100755 index 83f45f5b8..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-html.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-java.wasm b/gui/public/tree-sitter/tree-sitter-java.wasm deleted file mode 100755 index 941c48b50..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-java.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-javascript.wasm b/gui/public/tree-sitter/tree-sitter-javascript.wasm deleted file mode 100755 index 5857388d3..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-javascript.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-json.wasm b/gui/public/tree-sitter/tree-sitter-json.wasm deleted file mode 100755 index 548879fac..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-json.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-julia.wasm b/gui/public/tree-sitter/tree-sitter-julia.wasm deleted file mode 100755 index 1c7c854f2..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-julia.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-php.wasm b/gui/public/tree-sitter/tree-sitter-php.wasm deleted file mode 100755 index b4bf9a241..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-php.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-python.wasm b/gui/public/tree-sitter/tree-sitter-python.wasm deleted file mode 100755 index 6b70578f3..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-python.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-ruby.wasm b/gui/public/tree-sitter/tree-sitter-ruby.wasm deleted file mode 100755 index d9939a91e..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-ruby.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-rust.wasm b/gui/public/tree-sitter/tree-sitter-rust.wasm deleted file mode 100755 index ea26a9124..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-rust.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-scala.wasm b/gui/public/tree-sitter/tree-sitter-scala.wasm deleted file mode 100755 index 4c9cad9fd..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-scala.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-tsx.wasm b/gui/public/tree-sitter/tree-sitter-tsx.wasm deleted file mode 100755 index 67291adaa..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-tsx.wasm and /dev/null differ diff --git a/gui/public/tree-sitter/tree-sitter-typescript.wasm b/gui/public/tree-sitter/tree-sitter-typescript.wasm deleted file mode 100755 index e4d6f01d5..000000000 Binary files a/gui/public/tree-sitter/tree-sitter-typescript.wasm and /dev/null differ diff --git a/gui/public/worker.js b/gui/public/worker.js deleted file mode 100644 index 1e098fbdc..000000000 --- a/gui/public/worker.js +++ /dev/null @@ -1,29063 +0,0 @@ -(() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __commonJS = (cb, mod2) => function __require() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 - )); - - // (disabled):fs - var require_fs = __commonJS({ - "(disabled):fs"() { - } - }); - - // (disabled):path - var require_path = __commonJS({ - "(disabled):path"() { - } - }); - - // (disabled):stream/web - var require_web = __commonJS({ - "(disabled):stream/web"() { - } - }); - - // (disabled):url - var require_url = __commonJS({ - "(disabled):url"() { - } - }); - - // (disabled):node_modules/onnxruntime-node/dist/index.js - var require_dist = __commonJS({ - "(disabled):node_modules/onnxruntime-node/dist/index.js"() { - } - }); - - // node_modules/onnxruntime-common/dist/ort-common.node.js - var require_ort_common_node = __commonJS({ - "node_modules/onnxruntime-common/dist/ort-common.node.js"(exports2) { - (() => { - "use strict"; - var e = { d: (t2, r2) => { - for (var n2 in r2) - e.o(r2, n2) && !e.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: r2[n2] }); - }, o: (e2, t2) => Object.prototype.hasOwnProperty.call(e2, t2), r: (e2) => { - "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true }); - } }, t = {}; - e.r(t), e.d(t, { InferenceSession: () => c, Tensor: () => g, env: () => i, registerBackend: () => o }); - const r = {}, n = [], o = (e2, t2, o2) => { - if (!t2 || "function" != typeof t2.init || "function" != typeof t2.createSessionHandler) - throw new TypeError("not a valid backend"); - { - const i2 = r[e2]; - if (void 0 === i2) - r[e2] = { backend: t2, priority: o2 }; - else { - if (i2.priority > o2) - return; - if (i2.priority === o2 && i2.backend !== t2) - throw new Error(`cannot register backend "${e2}" using priority ${o2}`); - } - if (o2 >= 0) { - const t3 = n.indexOf(e2); - -1 !== t3 && n.splice(t3, 1); - for (let t4 = 0; t4 < n.length; t4++) - if (r[n[t4]].priority <= o2) - return void n.splice(t4, 0, e2); - n.push(e2); - } - } - }, i = new class { - constructor() { - this.wasm = {}, this.webgl = {}, this.logLevelInternal = "warning"; - } - set logLevel(e2) { - if (void 0 !== e2) { - if ("string" != typeof e2 || -1 === ["verbose", "info", "warning", "error", "fatal"].indexOf(e2)) - throw new Error(`Unsupported logging level: ${e2}`); - this.logLevelInternal = e2; - } - } - get logLevel() { - return this.logLevelInternal; - } - }(), a = "undefined" != typeof BigInt64Array && "function" == typeof BigInt64Array.from, s = "undefined" != typeof BigUint64Array && "function" == typeof BigUint64Array.from, d = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), f = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]); - a && (d.set("int64", BigInt64Array), f.set(BigInt64Array, "int64")), s && (d.set("uint64", BigUint64Array), f.set(BigUint64Array, "uint64")); - class h { - constructor(e2, t2, r2) { - let n2, o2, i2; - if ("string" == typeof e2) - if (n2 = e2, i2 = r2, "string" === e2) { - if (!Array.isArray(t2)) - throw new TypeError("A string tensor's data must be a string array."); - o2 = t2; - } else { - const r3 = d.get(e2); - if (void 0 === r3) - throw new TypeError(`Unsupported tensor type: ${e2}.`); - if (Array.isArray(t2)) - o2 = r3.from(t2); - else { - if (!(t2 instanceof r3)) - throw new TypeError(`A ${n2} tensor's data must be type of ${r3}`); - o2 = t2; - } - } - else if (i2 = t2, Array.isArray(e2)) { - if (0 === e2.length) - throw new TypeError("Tensor type cannot be inferred from an empty array."); - const t3 = typeof e2[0]; - if ("string" === t3) - n2 = "string", o2 = e2; - else { - if ("boolean" !== t3) - throw new TypeError(`Invalid element type of data array: ${t3}.`); - n2 = "bool", o2 = Uint8Array.from(e2); - } - } else { - const t3 = f.get(e2.constructor); - if (void 0 === t3) - throw new TypeError(`Unsupported type for tensor data: ${e2.constructor}.`); - n2 = t3, o2 = e2; - } - if (void 0 === i2) - i2 = [o2.length]; - else if (!Array.isArray(i2)) - throw new TypeError("A tensor's dims must be a number array"); - const a2 = ((e3) => { - let t3 = 1; - for (let r3 = 0; r3 < e3.length; r3++) { - const n3 = e3[r3]; - if ("number" != typeof n3 || !Number.isSafeInteger(n3)) - throw new TypeError(`dims[${r3}] must be an integer, got: ${n3}`); - if (n3 < 0) - throw new RangeError(`dims[${r3}] must be a non-negative integer, got: ${n3}`); - t3 *= n3; - } - return t3; - })(i2); - if (a2 !== o2.length) - throw new Error(`Tensor's size(${a2}) does not match data length(${o2.length}).`); - this.dims = i2, this.type = n2, this.data = o2, this.size = a2; - } - static bufferToTensor(e2, t2) { - if (void 0 === e2) - throw new Error("Image buffer must be defined"); - if (void 0 === t2.height || void 0 === t2.width) - throw new Error("Image height and width must be defined"); - const { height: r2, width: n2 } = t2, o2 = t2.norm; - let i2, a2; - i2 = void 0 === o2 || void 0 === o2.mean ? 255 : o2.mean, a2 = void 0 === o2 || void 0 === o2.bias ? 0 : o2.bias; - const s2 = void 0 !== t2.bitmapFormat ? t2.bitmapFormat : "RGBA", d2 = void 0 !== t2.tensorFormat && void 0 !== t2.tensorFormat ? t2.tensorFormat : "RGB", f2 = r2 * n2, g2 = "RGBA" === d2 ? new Float32Array(4 * f2) : new Float32Array(3 * f2); - let m2 = 4, c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = f2, b = 2 * f2, v = -1; - "RGB" === s2 && (m2 = 3, c2 = 0, l2 = 1, w2 = 2, u = -1), "RGBA" === d2 ? v = 3 * f2 : "RBG" === d2 ? (p = 0, b = f2, y = 2 * f2) : "BGR" === d2 && (b = 0, y = f2, p = 2 * f2); - for (let t3 = 0; t3 < f2; t3++, c2 += m2, w2 += m2, l2 += m2, u += m2) - g2[p++] = (e2[c2] + a2) / i2, g2[y++] = (e2[l2] + a2) / i2, g2[b++] = (e2[w2] + a2) / i2, -1 !== v && -1 !== u && (g2[v++] = (e2[u] + a2) / i2); - return new h("float32", g2, "RGBA" === d2 ? [1, 4, r2, n2] : [1, 3, r2, n2]); - } - static async fromImage(e2, t2) { - const r2 = "undefined" != typeof HTMLImageElement && e2 instanceof HTMLImageElement, n2 = "undefined" != typeof ImageData && e2 instanceof ImageData, o2 = "undefined" != typeof ImageBitmap && e2 instanceof ImageBitmap, i2 = "undefined" != typeof String && (e2 instanceof String || "string" == typeof e2); - let a2, s2 = {}; - if (r2) { - const r3 = document.createElement("canvas"), n3 = r3.getContext("2d"); - if (null == n3) - throw new Error("Can not access image data"); - { - let o3 = e2.naturalHeight, i3 = e2.naturalWidth; - if (void 0 !== t2 && void 0 !== t2.resizedHeight && void 0 !== t2.resizedWidth && (o3 = t2.resizedHeight, i3 = t2.resizedWidth), void 0 !== t2) { - if (s2 = t2, void 0 !== t2.tensorFormat) - throw new Error("Image input config format must be RGBA for HTMLImageElement"); - if (s2.tensorFormat = "RGBA", void 0 !== t2.height && t2.height !== o3) - throw new Error("Image input config height doesn't match HTMLImageElement height"); - if (s2.height = o3, void 0 !== t2.width && t2.width !== i3) - throw new Error("Image input config width doesn't match HTMLImageElement width"); - s2.width = i3; - } else - s2.tensorFormat = "RGBA", s2.height = o3, s2.width = i3; - r3.width = i3, r3.height = o3, n3.drawImage(e2, 0, 0, i3, o3), a2 = n3.getImageData(0, 0, i3, o3).data; - } - } else { - if (!n2) { - if (o2) { - if (void 0 === t2) - throw new Error("Please provide image config with format for Imagebitmap"); - if (void 0 !== t2.bitmapFormat) - throw new Error("Image input config format must be defined for ImageBitmap"); - const r3 = document.createElement("canvas").getContext("2d"); - if (null != r3) { - const n3 = e2.height, o3 = e2.width; - if (r3.drawImage(e2, 0, 0, o3, n3), a2 = r3.getImageData(0, 0, o3, n3).data, void 0 !== t2) { - if (void 0 !== t2.height && t2.height !== n3) - throw new Error("Image input config height doesn't match ImageBitmap height"); - if (s2.height = n3, void 0 !== t2.width && t2.width !== o3) - throw new Error("Image input config width doesn't match ImageBitmap width"); - s2.width = o3; - } else - s2.height = n3, s2.width = o3; - return h.bufferToTensor(a2, s2); - } - throw new Error("Can not access image data"); - } - if (i2) - return new Promise((r3, n3) => { - const o3 = document.createElement("canvas"), i3 = o3.getContext("2d"); - if (!e2 || !i3) - return n3(); - const a3 = new Image(); - a3.crossOrigin = "Anonymous", a3.src = e2, a3.onload = () => { - o3.width = a3.width, o3.height = a3.height, i3.drawImage(a3, 0, 0, o3.width, o3.height); - const e3 = i3.getImageData(0, 0, o3.width, o3.height); - if (void 0 !== t2) { - if (void 0 !== t2.height && t2.height !== o3.height) - throw new Error("Image input config height doesn't match ImageBitmap height"); - if (s2.height = o3.height, void 0 !== t2.width && t2.width !== o3.width) - throw new Error("Image input config width doesn't match ImageBitmap width"); - s2.width = o3.width; - } else - s2.height = o3.height, s2.width = o3.width; - r3(h.bufferToTensor(e3.data, s2)); - }; - }); - throw new Error("Input data provided is not supported - aborted tensor creation"); - } - { - const r3 = "RGBA"; - let n3, o3; - if (void 0 !== t2 && void 0 !== t2.resizedWidth && void 0 !== t2.resizedHeight ? (n3 = t2.resizedHeight, o3 = t2.resizedWidth) : (n3 = e2.height, o3 = e2.width), void 0 !== t2) { - if (s2 = t2, void 0 !== t2.bitmapFormat && t2.bitmapFormat !== r3) - throw new Error("Image input config format must be RGBA for ImageData"); - s2.bitmapFormat = "RGBA"; - } else - s2.bitmapFormat = "RGBA"; - if (s2.height = n3, s2.width = o3, void 0 !== t2) { - const t3 = document.createElement("canvas"); - t3.width = o3, t3.height = n3; - const r4 = t3.getContext("2d"); - if (null == r4) - throw new Error("Can not access image data"); - r4.putImageData(e2, 0, 0), a2 = r4.getImageData(0, 0, o3, n3).data; - } else - a2 = e2.data; - } - } - if (void 0 !== a2) - return h.bufferToTensor(a2, s2); - throw new Error("Input data provided is not supported - aborted tensor creation"); - } - toImageData(e2) { - var t2, r2; - const n2 = document.createElement("canvas").getContext("2d"); - let o2; - if (null == n2) - throw new Error("Can not access image data"); - { - const i2 = this.dims[3], a2 = this.dims[2], s2 = this.dims[1], d2 = void 0 !== e2 && void 0 !== e2.format ? e2.format : "RGB", f2 = void 0 !== e2 && void 0 !== (null === (t2 = e2.norm) || void 0 === t2 ? void 0 : t2.mean) ? e2.norm.mean : 255, h2 = void 0 !== e2 && void 0 !== (null === (r2 = e2.norm) || void 0 === r2 ? void 0 : r2.bias) ? e2.norm.bias : 0, g2 = a2 * i2; - if (void 0 !== e2) { - if (void 0 !== e2.height && e2.height !== a2) - throw new Error("Image output config height doesn't match tensor height"); - if (void 0 !== e2.width && e2.width !== i2) - throw new Error("Image output config width doesn't match tensor width"); - if (void 0 !== e2.format && 4 === s2 && "RGBA" !== e2.format || 3 === s2 && "RGB" !== e2.format && "BGR" !== e2.format) - throw new Error("Tensor format doesn't match input tensor dims"); - } - const m2 = 4; - let c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = g2, b = 2 * g2, v = -1; - "RGBA" === d2 ? (p = 0, y = g2, b = 2 * g2, v = 3 * g2) : "RGB" === d2 ? (p = 0, y = g2, b = 2 * g2) : "RBG" === d2 && (p = 0, b = g2, y = 2 * g2), o2 = n2.createImageData(i2, a2); - for (let e3 = 0; e3 < a2 * i2; c2 += m2, l2 += m2, w2 += m2, u += m2, e3++) - o2.data[c2] = (this.data[p++] - h2) * f2, o2.data[l2] = (this.data[y++] - h2) * f2, o2.data[w2] = (this.data[b++] - h2) * f2, o2.data[u] = -1 === v ? 255 : (this.data[v++] - h2) * f2; - } - return o2; - } - reshape(e2) { - return new h(this.type, this.data, e2); - } - } - const g = h; - class m { - constructor(e2) { - this.handler = e2; - } - async run(e2, t2, r2) { - const n2 = {}; - let o2 = {}; - if ("object" != typeof e2 || null === e2 || e2 instanceof g || Array.isArray(e2)) - throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); - let i2 = true; - if ("object" == typeof t2) { - if (null === t2) - throw new TypeError("Unexpected argument[1]: cannot be null."); - if (t2 instanceof g) - throw new TypeError("'fetches' cannot be a Tensor"); - if (Array.isArray(t2)) { - if (0 === t2.length) - throw new TypeError("'fetches' cannot be an empty array."); - i2 = false; - for (const e3 of t2) { - if ("string" != typeof e3) - throw new TypeError("'fetches' must be a string array or an object."); - if (-1 === this.outputNames.indexOf(e3)) - throw new RangeError(`'fetches' contains invalid output name: ${e3}.`); - n2[e3] = null; - } - if ("object" == typeof r2 && null !== r2) - o2 = r2; - else if (void 0 !== r2) - throw new TypeError("'options' must be an object."); - } else { - let e3 = false; - const a3 = Object.getOwnPropertyNames(t2); - for (const r3 of this.outputNames) - if (-1 !== a3.indexOf(r3)) { - const o3 = t2[r3]; - (null === o3 || o3 instanceof g) && (e3 = true, i2 = false, n2[r3] = o3); - } - if (e3) { - if ("object" == typeof r2 && null !== r2) - o2 = r2; - else if (void 0 !== r2) - throw new TypeError("'options' must be an object."); - } else - o2 = t2; - } - } else if (void 0 !== t2) - throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); - for (const t3 of this.inputNames) - if (void 0 === e2[t3]) - throw new Error(`input '${t3}' is missing in 'feeds'.`); - if (i2) - for (const e3 of this.outputNames) - n2[e3] = null; - const a2 = await this.handler.run(e2, n2, o2), s2 = {}; - for (const e3 in a2) - Object.hasOwnProperty.call(a2, e3) && (s2[e3] = new g(a2[e3].type, a2[e3].data, a2[e3].dims)); - return s2; - } - static async create(e2, t2, o2, i2) { - let a2, s2 = {}; - if ("string" == typeof e2) { - if (a2 = e2, "object" == typeof t2 && null !== t2) - s2 = t2; - else if (void 0 !== t2) - throw new TypeError("'options' must be an object."); - } else if (e2 instanceof Uint8Array) { - if (a2 = e2, "object" == typeof t2 && null !== t2) - s2 = t2; - else if (void 0 !== t2) - throw new TypeError("'options' must be an object."); - } else { - if (!(e2 instanceof ArrayBuffer || "undefined" != typeof SharedArrayBuffer && e2 instanceof SharedArrayBuffer)) - throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); - { - const r2 = e2; - let n2 = 0, d3 = e2.byteLength; - if ("object" == typeof t2 && null !== t2) - s2 = t2; - else if ("number" == typeof t2) { - if (n2 = t2, !Number.isSafeInteger(n2)) - throw new RangeError("'byteOffset' must be an integer."); - if (n2 < 0 || n2 >= r2.byteLength) - throw new RangeError(`'byteOffset' is out of range [0, ${r2.byteLength}).`); - if (d3 = e2.byteLength - n2, "number" == typeof o2) { - if (d3 = o2, !Number.isSafeInteger(d3)) - throw new RangeError("'byteLength' must be an integer."); - if (d3 <= 0 || n2 + d3 > r2.byteLength) - throw new RangeError(`'byteLength' is out of range (0, ${r2.byteLength - n2}].`); - if ("object" == typeof i2 && null !== i2) - s2 = i2; - else if (void 0 !== i2) - throw new TypeError("'options' must be an object."); - } else if (void 0 !== o2) - throw new TypeError("'byteLength' must be a number."); - } else if (void 0 !== t2) - throw new TypeError("'options' must be an object."); - a2 = new Uint8Array(r2, n2, d3); - } - } - const d2 = (s2.executionProviders || []).map((e3) => "string" == typeof e3 ? e3 : e3.name), f2 = await (async (e3) => { - const t3 = 0 === e3.length ? n : e3, o3 = []; - for (const e4 of t3) { - const t4 = r[e4]; - if (t4) { - if (t4.initialized) - return t4.backend; - if (t4.aborted) - continue; - const r2 = !!t4.initPromise; - try { - return r2 || (t4.initPromise = t4.backend.init()), await t4.initPromise, t4.initialized = true, t4.backend; - } catch (n2) { - r2 || o3.push({ name: e4, err: n2 }), t4.aborted = true; - } finally { - delete t4.initPromise; - } - } - } - throw new Error(`no available backend found. ERR: ${o3.map((e4) => `[${e4.name}] ${e4.err}`).join(", ")}`); - })(d2), h2 = await f2.createSessionHandler(a2, s2); - return new m(h2); - } - startProfiling() { - this.handler.startProfiling(); - } - endProfiling() { - this.handler.endProfiling(); - } - get inputNames() { - return this.handler.inputNames; - } - get outputNames() { - return this.handler.outputNames; - } - } - const c = m; - var l = exports2; - for (var w in t) - l[w] = t[w]; - t.__esModule && Object.defineProperty(l, "__esModule", { value: true }); - })(); - } - }); - - // node_modules/onnxruntime-web/dist/ort-web.min.js - var require_ort_web_min = __commonJS({ - "node_modules/onnxruntime-web/dist/ort-web.min.js"(exports, module) { - !function(t, e) { - if ("object" == typeof exports && "object" == typeof module) - module.exports = e(require_ort_common_node()); - else if ("function" == typeof define && define.amd) - define([], e); - else { - var n = "object" == typeof exports ? e(require_ort_common_node()) : e(t.ort); - for (var r in n) - ("object" == typeof exports ? exports : t)[r] = n[r]; - } - }(self, (__WEBPACK_EXTERNAL_MODULE__1670__) => (() => { - var __webpack_modules__ = { 3474: (t, e, n) => { - var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) { - function e2() { - return $.buffer != C && H($.buffer), F; - } - function r2() { - return $.buffer != C && H($.buffer), N; - } - function i() { - return $.buffer != C && H($.buffer), L; - } - function o() { - return $.buffer != C && H($.buffer), R; - } - function a() { - return $.buffer != C && H($.buffer), j; - } - var s, u, c; - t2 = t2 || {}, s || (s = void 0 !== t2 ? t2 : {}), s.ready = new Promise(function(t3, e3) { - u = t3, c = e3; - }); - var l, p, f, d, h, g, b = Object.assign({}, s), m = "./this.program", y = (t3, e3) => { - throw e3; - }, _ = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x = s.ENVIRONMENT_IS_PTHREAD || false, T = ""; - function S(t3) { - return s.locateFile ? s.locateFile(t3, T) : T + t3; - } - if (w) { - let e3; - T = v ? n(908).dirname(T) + "/" : "//", g = () => { - h || (d = n(1384), h = n(908)); - }, l = function(t3, e4) { - return g(), t3 = h.normalize(t3), d.readFileSync(t3, e4 ? void 0 : "utf8"); - }, f = (t3) => ((t3 = l(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), p = (t3, e4, n2) => { - g(), t3 = h.normalize(t3), d.readFile(t3, function(t4, r3) { - t4 ? n2(t4) : e4(r3.buffer); - }); - }, 1 < process.argv.length && (m = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", function(t3) { - if (!(t3 instanceof ut)) - throw t3; - }), process.on("unhandledRejection", function(t3) { - throw t3; - }), y = (t3, e4) => { - if (J()) - throw process.exitCode = t3, e4; - e4 instanceof ut || P("exiting due to exception: " + e4), process.exit(t3); - }, s.inspect = function() { - return "[Emscripten Module object]"; - }; - try { - e3 = n(9925); - } catch (t3) { - throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), t3; - } - n.g.Worker = e3.Worker; - } else - (_ || v) && (v ? T = self.location.href : "undefined" != typeof document && document.currentScript && (T = document.currentScript.src), _scriptDir && (T = _scriptDir), T = 0 !== T.indexOf("blob:") ? T.substr(0, T.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", w || (l = (t3) => { - var e3 = new XMLHttpRequest(); - return e3.open("GET", t3, false), e3.send(null), e3.responseText; - }, v && (f = (t3) => { - var e3 = new XMLHttpRequest(); - return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response); - }), p = (t3, e3, n2) => { - var r3 = new XMLHttpRequest(); - r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => { - 200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2(); - }, r3.onerror = n2, r3.send(null); - })); - w && "undefined" == typeof performance && (n.g.performance = n(6953).performance); - var O = console.log.bind(console), A = console.warn.bind(console); - w && (g(), O = (t3) => d.writeSync(1, t3 + "\n"), A = (t3) => d.writeSync(2, t3 + "\n")); - var E, I = s.print || O, P = s.printErr || A; - Object.assign(s, b), b = null, s.thisProgram && (m = s.thisProgram), s.quit && (y = s.quit), s.wasmBinary && (E = s.wasmBinary); - var D = s.noExitRuntime || false; - "object" != typeof WebAssembly && it("no native wasm support detected"); - var $, k, C, F, N, L, R, j, M = false, U = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; - function V(t3, e3, n2) { - var r3 = (e3 >>>= 0) + n2; - for (n2 = e3; t3[n2] && !(n2 >= r3); ) - ++n2; - if (16 < n2 - e3 && t3.buffer && U) - return U.decode(t3.buffer instanceof SharedArrayBuffer ? t3.slice(e3, n2) : t3.subarray(e3, n2)); - for (r3 = ""; e3 < n2; ) { - var i2 = t3[e3++]; - if (128 & i2) { - var o2 = 63 & t3[e3++]; - if (192 == (224 & i2)) - r3 += String.fromCharCode((31 & i2) << 6 | o2); - else { - var a2 = 63 & t3[e3++]; - 65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2)); - } - } else - r3 += String.fromCharCode(i2); - } - return r3; - } - function B(t3, e3) { - return (t3 >>>= 0) ? V(r2(), t3, e3) : ""; - } - function z(t3, e3, n2, r3) { - if (!(0 < r3)) - return 0; - var i2 = n2 >>>= 0; - r3 = n2 + r3 - 1; - for (var o2 = 0; o2 < t3.length; ++o2) { - var a2 = t3.charCodeAt(o2); - if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) { - if (n2 >= r3) - break; - e3[n2++ >>> 0] = a2; - } else { - if (2047 >= a2) { - if (n2 + 1 >= r3) - break; - e3[n2++ >>> 0] = 192 | a2 >> 6; - } else { - if (65535 >= a2) { - if (n2 + 2 >= r3) - break; - e3[n2++ >>> 0] = 224 | a2 >> 12; - } else { - if (n2 + 3 >= r3) - break; - e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63; - } - e3[n2++ >>> 0] = 128 | a2 >> 6 & 63; - } - e3[n2++ >>> 0] = 128 | 63 & a2; - } - } - return e3[n2 >>> 0] = 0, n2 - i2; - } - function G(t3) { - for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) { - var r3 = t3.charCodeAt(n2); - 127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3; - } - return e3; - } - function H(t3) { - C = t3, s.HEAP8 = F = new Int8Array(t3), s.HEAP16 = new Int16Array(t3), s.HEAP32 = L = new Int32Array(t3), s.HEAPU8 = N = new Uint8Array(t3), s.HEAPU16 = new Uint16Array(t3), s.HEAPU32 = R = new Uint32Array(t3), s.HEAPF32 = new Float32Array(t3), s.HEAPF64 = j = new Float64Array(t3); - } - x && (C = s.buffer); - var W = s.INITIAL_MEMORY || 16777216; - if (x) - $ = s.wasmMemory, C = s.buffer; - else if (s.wasmMemory) - $ = s.wasmMemory; - else if (!(($ = new WebAssembly.Memory({ initial: W / 65536, maximum: 65536, shared: true })).buffer instanceof SharedArrayBuffer)) - throw P("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), w && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory"); - $ && (C = $.buffer), W = C.byteLength, H(C); - var q, X = [], Y = [], K = [], Z = []; - function J() { - return D || false; - } - function Q() { - var t3 = s.preRun.shift(); - X.unshift(t3); - } - var tt, et = 0, nt = null, rt = null; - function it(t3) { - throw x ? postMessage({ cmd: "onAbort", arg: t3 }) : s.onAbort && s.onAbort(t3), P(t3 = "Aborted(" + t3 + ")"), M = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), c(t3), t3; - } - function ot() { - return tt.startsWith("data:application/octet-stream;base64,"); - } - function at() { - var t3 = tt; - try { - if (t3 == tt && E) - return new Uint8Array(E); - if (f) - return f(t3); - throw "both async and sync fetching of the wasm failed"; - } catch (t4) { - it(t4); - } - } - tt = "ort-wasm-threaded.wasm", ot() || (tt = S(tt)); - var st = {}; - function ut(t3) { - this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3; - } - function ct(t3) { - (t3 = dt.Vb[t3]) || it(), dt.mc(t3); - } - function lt(t3) { - var e3 = dt.Cc(); - if (!e3) - return 6; - dt.ac.push(e3), dt.Vb[t3.Ub] = e3, e3.Ub = t3.Ub; - var n2 = { cmd: "run", start_routine: t3.Ic, arg: t3.zc, pthread_ptr: t3.Ub }; - return e3.$b = () => { - n2.time = performance.now(), e3.postMessage(n2, t3.Nc); - }, e3.loaded && (e3.$b(), delete e3.$b), 0; - } - function pt(t3) { - if (x) - return qt(1, 1, t3); - J() || (dt.oc(), s.onExit && s.onExit(t3), M = true), y(t3, new ut(t3)); - } - function ft(t3, e3) { - if (!e3 && x) - throw bt(t3), "unwind"; - J() || x || (me(), ht(K), be(0), re[1].length && ie(1, 10), re[2].length && ie(2, 10), dt.oc()), pt(t3); - } - var dt = { Yb: [], ac: [], qc: [], Vb: {}, fc: function() { - x && dt.Ec(); - }, Pc: function() { - }, Ec: function() { - dt.receiveObjectTransfer = dt.Gc, dt.threadInitTLS = dt.pc, dt.setExitStatus = dt.nc, D = false; - }, nc: function() { - }, oc: function() { - for (var t3 of Object.values(dt.Vb)) - dt.mc(t3); - for (t3 of dt.Yb) - t3.terminate(); - dt.Yb = []; - }, mc: function(t3) { - var e3 = t3.Ub; - delete dt.Vb[e3], dt.Yb.push(t3), dt.ac.splice(dt.ac.indexOf(t3), 1), t3.Ub = 0, xe(e3); - }, Gc: function() { - }, pc: function() { - dt.qc.forEach((t3) => t3()); - }, Fc: function(t3, e3) { - t3.onmessage = (n2) => { - var r3 = (n2 = n2.data).cmd; - if (t3.Ub && (dt.Bc = t3.Ub), n2.targetThread && n2.targetThread != de()) { - var i2 = dt.Vb[n2.Qc]; - i2 ? i2.postMessage(n2, n2.transferList) : P('Internal error! Worker sent a message "' + r3 + '" to target pthread ' + n2.targetThread + ", but that thread no longer exists!"); - } else - "processProxyingQueue" === r3 ? Vt(n2.queue) : "spawnThread" === r3 ? lt(n2) : "cleanupThread" === r3 ? ct(n2.thread) : "killThread" === r3 ? (n2 = n2.thread, r3 = dt.Vb[n2], delete dt.Vb[n2], r3.terminate(), xe(n2), dt.ac.splice(dt.ac.indexOf(r3), 1), r3.Ub = 0) : "cancelThread" === r3 ? dt.Vb[n2.thread].postMessage({ cmd: "cancel" }) : "loaded" === r3 ? (t3.loaded = true, e3 && e3(t3), t3.$b && (t3.$b(), delete t3.$b)) : "print" === r3 ? I("Thread " + n2.threadId + ": " + n2.text) : "printErr" === r3 ? P("Thread " + n2.threadId + ": " + n2.text) : "alert" === r3 ? alert("Thread " + n2.threadId + ": " + n2.text) : "setimmediate" === n2.target ? t3.postMessage(n2) : "onAbort" === r3 ? s.onAbort && s.onAbort(n2.arg) : r3 && P("worker sent an unknown command " + r3); - dt.Bc = void 0; - }, t3.onerror = (t4) => { - throw P("worker sent an error! " + t4.filename + ":" + t4.lineno + ": " + t4.message), t4; - }, w && (t3.on("message", function(e4) { - t3.onmessage({ data: e4 }); - }), t3.on("error", function(e4) { - t3.onerror(e4); - }), t3.on("detachedExit", function() { - })), t3.postMessage({ cmd: "load", urlOrBlob: s.mainScriptUrlOrBlob || _scriptDir, wasmMemory: $, wasmModule: k }); - }, yc: function() { - var t3 = S("ort-wasm-threaded.worker.js"); - dt.Yb.push(new Worker(t3)); - }, Cc: function() { - return 0 == dt.Yb.length && (dt.yc(), dt.Fc(dt.Yb[0])), dt.Yb.pop(); - } }; - function ht(t3) { - for (; 0 < t3.length; ) - t3.shift()(s); - } - function gt(t3) { - var e3 = Ae(); - return t3 = t3(), Ee(e3), t3; - } - function bt(t3) { - if (x) - return qt(2, 0, t3); - try { - ft(t3); - } catch (t4) { - t4 instanceof ut || "unwind" == t4 || y(1, t4); - } - } - s.PThread = dt, s.establishStackSpace = function() { - var t3 = de(), e3 = i()[t3 + 44 >> 2 >>> 0]; - t3 = i()[t3 + 48 >> 2 >>> 0], Oe(e3, e3 - t3), Ee(e3); - }; - var mt = []; - function yt(t3) { - var e3 = mt[t3]; - return e3 || (t3 >= mt.length && (mt.length = t3 + 1), mt[t3] = e3 = q.get(t3)), e3; - } - s.invokeEntryPoint = function(t3, e3) { - t3 = yt(t3)(e3), J() ? dt.nc(t3) : Te(t3); - }; - var _t, vt, wt = [], xt = 0, Tt = 0; - function St(t3) { - this.Zb = t3, this.Sb = t3 - 24, this.xc = function(t4) { - o()[this.Sb + 4 >> 2 >>> 0] = t4; - }, this.bc = function() { - return o()[this.Sb + 4 >> 2 >>> 0]; - }, this.wc = function(t4) { - o()[this.Sb + 8 >> 2 >>> 0] = t4; - }, this.Dc = function() { - return o()[this.Sb + 8 >> 2 >>> 0]; - }, this.rc = function() { - i()[this.Sb >> 2 >>> 0] = 0; - }, this.hc = function(t4) { - t4 = t4 ? 1 : 0, e2()[this.Sb + 12 >> 0 >>> 0] = t4; - }, this.uc = function() { - return 0 != e2()[this.Sb + 12 >> 0 >>> 0]; - }, this.ic = function(t4) { - t4 = t4 ? 1 : 0, e2()[this.Sb + 13 >> 0 >>> 0] = t4; - }, this.kc = function() { - return 0 != e2()[this.Sb + 13 >> 0 >>> 0]; - }, this.fc = function(t4, e3) { - this.cc(0), this.xc(t4), this.wc(e3), this.rc(), this.hc(false), this.ic(false); - }, this.sc = function() { - Atomics.add(i(), this.Sb >> 2, 1); - }, this.Hc = function() { - return 1 === Atomics.sub(i(), this.Sb >> 2, 1); - }, this.cc = function(t4) { - o()[this.Sb + 16 >> 2 >>> 0] = t4; - }, this.tc = function() { - return o()[this.Sb + 16 >> 2 >>> 0]; - }, this.vc = function() { - if (De(this.bc())) - return o()[this.Zb >> 2 >>> 0]; - var t4 = this.tc(); - return 0 !== t4 ? t4 : this.Zb; - }; - } - function Ot(t3) { - return ge(new St(t3).Sb); - } - function At(t3, e3, n2, r3) { - return x ? qt(3, 1, t3, e3, n2, r3) : Et(t3, e3, n2, r3); - } - function Et(t3, e3, n2, r3) { - if ("undefined" == typeof SharedArrayBuffer) - return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; - var i2 = []; - return x && 0 === i2.length ? At(t3, e3, n2, r3) : (t3 = { Ic: n2, Ub: t3, zc: r3, Nc: i2 }, x ? (t3.Oc = "spawnThread", postMessage(t3, i2), 0) : lt(t3)); - } - function It(t3, e3, n2) { - return x ? qt(4, 1, t3, e3, n2) : 0; - } - function Pt(t3, e3) { - if (x) - return qt(5, 1, t3, e3); - } - function Dt(t3, e3) { - if (x) - return qt(6, 1, t3, e3); - } - function $t(t3, e3, n2) { - if (x) - return qt(7, 1, t3, e3, n2); - } - function kt(t3, e3, n2) { - return x ? qt(8, 1, t3, e3, n2) : 0; - } - function Ct(t3, e3) { - if (x) - return qt(9, 1, t3, e3); - } - function Ft(t3, e3, n2) { - if (x) - return qt(10, 1, t3, e3, n2); - } - function Nt(t3, e3, n2, r3) { - if (x) - return qt(11, 1, t3, e3, n2, r3); - } - function Lt(t3, e3, n2, r3) { - if (x) - return qt(12, 1, t3, e3, n2, r3); - } - function Rt(t3, e3, n2, r3) { - if (x) - return qt(13, 1, t3, e3, n2, r3); - } - function jt(t3) { - if (x) - return qt(14, 1, t3); - } - function Mt(t3, e3) { - if (x) - return qt(15, 1, t3, e3); - } - function Ut(t3, e3, n2) { - if (x) - return qt(16, 1, t3, e3, n2); - } - function Vt(t3) { - Atomics.store(i(), t3 >> 2, 1), de() && we(t3), Atomics.compareExchange(i(), t3 >> 2, 1, 0); - } - function Bt(t3) { - return o()[t3 >>> 2] + 4294967296 * i()[t3 + 4 >>> 2]; - } - function zt(t3, e3, n2, r3, i2, o2) { - return x ? qt(17, 1, t3, e3, n2, r3, i2, o2) : -52; - } - function Gt(t3, e3, n2, r3, i2, o2) { - if (x) - return qt(18, 1, t3, e3, n2, r3, i2, o2); - } - function Ht(t3) { - var n2 = G(t3) + 1, r3 = he(n2); - return r3 && z(t3, e2(), r3, n2), r3; - } - function Wt(t3, e3, n2) { - function r3(t4) { - return (t4 = t4.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t4[1] : "GMT"; - } - if (x) - return qt(19, 1, t3, e3, n2); - var a2 = (/* @__PURE__ */ new Date()).getFullYear(), s2 = new Date(a2, 0, 1), u2 = new Date(a2, 6, 1); - a2 = s2.getTimezoneOffset(); - var c2 = u2.getTimezoneOffset(), l2 = Math.max(a2, c2); - i()[t3 >> 2 >>> 0] = 60 * l2, i()[e3 >> 2 >>> 0] = Number(a2 != c2), t3 = r3(s2), e3 = r3(u2), t3 = Ht(t3), e3 = Ht(e3), c2 < a2 ? (o()[n2 >> 2 >>> 0] = t3, o()[n2 + 4 >> 2 >>> 0] = e3) : (o()[n2 >> 2 >>> 0] = e3, o()[n2 + 4 >> 2 >>> 0] = t3); - } - function qt(t3, e3) { - var n2 = arguments.length - 2, r3 = arguments; - return gt(() => { - for (var i2 = Ie(8 * n2), o2 = i2 >> 3, s2 = 0; s2 < n2; s2++) { - var u2 = r3[2 + s2]; - a()[o2 + s2 >>> 0] = u2; - } - return ve(t3, n2, i2, e3); - }); - } - s.executeNotifiedProxyingQueue = Vt, vt = w ? () => { - var t3 = process.hrtime(); - return 1e3 * t3[0] + t3[1] / 1e6; - } : x ? () => performance.now() - s.__performance_now_clock_drift : () => performance.now(); - var Xt, Yt = [], Kt = {}; - function Zt() { - if (!Xt) { - var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: m || "./this.program" }; - for (t3 in Kt) - void 0 === Kt[t3] ? delete e3[t3] : e3[t3] = Kt[t3]; - var n2 = []; - for (t3 in e3) - n2.push(t3 + "=" + e3[t3]); - Xt = n2; - } - return Xt; - } - function Jt(t3, n2) { - if (x) - return qt(20, 1, t3, n2); - var r3 = 0; - return Zt().forEach(function(i2, a2) { - var s2 = n2 + r3; - for (a2 = o()[t3 + 4 * a2 >> 2 >>> 0] = s2, s2 = 0; s2 < i2.length; ++s2) - e2()[a2++ >> 0 >>> 0] = i2.charCodeAt(s2); - e2()[a2 >> 0 >>> 0] = 0, r3 += i2.length + 1; - }), 0; - } - function Qt(t3, e3) { - if (x) - return qt(21, 1, t3, e3); - var n2 = Zt(); - o()[t3 >> 2 >>> 0] = n2.length; - var r3 = 0; - return n2.forEach(function(t4) { - r3 += t4.length + 1; - }), o()[e3 >> 2 >>> 0] = r3, 0; - } - function te(t3) { - return x ? qt(22, 1, t3) : 52; - } - function ee(t3, e3, n2, r3) { - return x ? qt(23, 1, t3, e3, n2, r3) : 52; - } - function ne(t3, e3, n2, r3, i2) { - return x ? qt(24, 1, t3, e3, n2, r3, i2) : 70; - } - var re = [null, [], []]; - function ie(t3, e3) { - var n2 = re[t3]; - 0 === e3 || 10 === e3 ? ((1 === t3 ? I : P)(V(n2, 0)), n2.length = 0) : n2.push(e3); - } - function oe(t3, e3, n2, i2) { - if (x) - return qt(25, 1, t3, e3, n2, i2); - for (var a2 = 0, s2 = 0; s2 < n2; s2++) { - var u2 = o()[e3 >> 2 >>> 0], c2 = o()[e3 + 4 >> 2 >>> 0]; - e3 += 8; - for (var l2 = 0; l2 < c2; l2++) - ie(t3, r2()[u2 + l2 >>> 0]); - a2 += c2; - } - return o()[i2 >> 2 >>> 0] = a2, 0; - } - var ae = 0; - function se(t3) { - return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400); - } - var ue = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ce = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function le(t3, n2, r3, o2) { - function a2(t4, e3, n3) { - for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e3; ) - t4 = n3[0] + t4; - return t4; - } - function s2(t4, e3) { - return a2(t4, e3, "0"); - } - function u2(t4, e3) { - function n3(t5) { - return 0 > t5 ? -1 : 0 < t5 ? 1 : 0; - } - var r4; - return 0 === (r4 = n3(t4.getFullYear() - e3.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e3.getMonth())) && (r4 = n3(t4.getDate() - e3.getDate())), r4; - } - function c2(t4) { - switch (t4.getDay()) { - case 0: - return new Date(t4.getFullYear() - 1, 11, 29); - case 1: - return t4; - case 2: - return new Date(t4.getFullYear(), 0, 3); - case 3: - return new Date(t4.getFullYear(), 0, 2); - case 4: - return new Date(t4.getFullYear(), 0, 1); - case 5: - return new Date(t4.getFullYear() - 1, 11, 31); - case 6: - return new Date(t4.getFullYear() - 1, 11, 30); - } - } - function l2(t4) { - var e3 = t4.Wb; - for (t4 = new Date(new Date(t4.Xb + 1900, 0, 1).getTime()); 0 < e3; ) { - var n3 = t4.getMonth(), r4 = (se(t4.getFullYear()) ? ue : ce)[n3]; - if (!(e3 > r4 - t4.getDate())) { - t4.setDate(t4.getDate() + e3); - break; - } - e3 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1)); - } - return n3 = new Date(t4.getFullYear() + 1, 0, 4), e3 = c2(new Date(t4.getFullYear(), 0, 4)), n3 = c2(n3), 0 >= u2(e3, t4) ? 0 >= u2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1; - } - var p2 = i()[o2 + 40 >> 2 >>> 0]; - for (var f2 in o2 = { Lc: i()[o2 >> 2 >>> 0], Kc: i()[o2 + 4 >> 2 >>> 0], dc: i()[o2 + 8 >> 2 >>> 0], jc: i()[o2 + 12 >> 2 >>> 0], ec: i()[o2 + 16 >> 2 >>> 0], Xb: i()[o2 + 20 >> 2 >>> 0], Tb: i()[o2 + 24 >> 2 >>> 0], Wb: i()[o2 + 28 >> 2 >>> 0], Rc: i()[o2 + 32 >> 2 >>> 0], Jc: i()[o2 + 36 >> 2 >>> 0], Mc: p2 ? B(p2) : "" }, r3 = B(r3), p2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) - r3 = r3.replace(new RegExp(f2, "g"), p2[f2]); - var d2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), h2 = "January February March April May June July August September October November December".split(" "); - for (f2 in p2 = { "%a": function(t4) { - return d2[t4.Tb].substring(0, 3); - }, "%A": function(t4) { - return d2[t4.Tb]; - }, "%b": function(t4) { - return h2[t4.ec].substring(0, 3); - }, "%B": function(t4) { - return h2[t4.ec]; - }, "%C": function(t4) { - return s2((t4.Xb + 1900) / 100 | 0, 2); - }, "%d": function(t4) { - return s2(t4.jc, 2); - }, "%e": function(t4) { - return a2(t4.jc, 2, " "); - }, "%g": function(t4) { - return l2(t4).toString().substring(2); - }, "%G": function(t4) { - return l2(t4); - }, "%H": function(t4) { - return s2(t4.dc, 2); - }, "%I": function(t4) { - return 0 == (t4 = t4.dc) ? t4 = 12 : 12 < t4 && (t4 -= 12), s2(t4, 2); - }, "%j": function(t4) { - for (var e3 = 0, n3 = 0; n3 <= t4.ec - 1; e3 += (se(t4.Xb + 1900) ? ue : ce)[n3++]) - ; - return s2(t4.jc + e3, 3); - }, "%m": function(t4) { - return s2(t4.ec + 1, 2); - }, "%M": function(t4) { - return s2(t4.Kc, 2); - }, "%n": function() { - return "\n"; - }, "%p": function(t4) { - return 0 <= t4.dc && 12 > t4.dc ? "AM" : "PM"; - }, "%S": function(t4) { - return s2(t4.Lc, 2); - }, "%t": function() { - return " "; - }, "%u": function(t4) { - return t4.Tb || 7; - }, "%U": function(t4) { - return s2(Math.floor((t4.Wb + 7 - t4.Tb) / 7), 2); - }, "%V": function(t4) { - var e3 = Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7); - if (2 >= (t4.Tb + 371 - t4.Wb - 2) % 7 && e3++, e3) - 53 == e3 && (4 == (n3 = (t4.Tb + 371 - t4.Wb) % 7) || 3 == n3 && se(t4.Xb) || (e3 = 1)); - else { - e3 = 52; - var n3 = (t4.Tb + 7 - t4.Wb - 1) % 7; - (4 == n3 || 5 == n3 && se(t4.Xb % 400 - 1)) && e3++; - } - return s2(e3, 2); - }, "%w": function(t4) { - return t4.Tb; - }, "%W": function(t4) { - return s2(Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7), 2); - }, "%y": function(t4) { - return (t4.Xb + 1900).toString().substring(2); - }, "%Y": function(t4) { - return t4.Xb + 1900; - }, "%z": function(t4) { - var e3 = 0 <= (t4 = t4.Jc); - return t4 = Math.abs(t4) / 60, (e3 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4); - }, "%Z": function(t4) { - return t4.Mc; - }, "%%": function() { - return "%"; - } }, r3 = r3.replace(/%%/g, "\0\0"), p2) - r3.includes(f2) && (r3 = r3.replace(new RegExp(f2, "g"), p2[f2](o2))); - return f2 = function(t4) { - var e3 = Array(G(t4) + 1); - return z(t4, e3, 0, e3.length), e3; - }(r3 = r3.replace(/\0\0/g, "%")), f2.length > n2 ? 0 : (function(t4, n3) { - e2().set(t4, n3 >>> 0); - }(f2, t3), f2.length - 1); - } - dt.fc(); - var pe = [null, pt, bt, At, It, Pt, Dt, $t, kt, Ct, Ft, Nt, Lt, Rt, jt, Mt, Ut, zt, Gt, Wt, Jt, Qt, te, ee, ne, oe], fe = { b: function(t3) { - return he(t3 + 24) + 24; - }, n: function(t3) { - return (t3 = new St(t3)).uc() || (t3.hc(true), xt--), t3.ic(false), wt.push(t3), t3.sc(), t3.vc(); - }, ma: function(t3) { - throw P("Unexpected exception thrown, this is not properly supported - aborting"), M = true, t3; - }, x: function() { - Se(0); - var t3 = wt.pop(); - if (t3.Hc() && !t3.kc()) { - var e3 = t3.Dc(); - e3 && yt(e3)(t3.Zb), Ot(t3.Zb); - } - Tt = 0; - }, e: function() { - var t3 = Tt; - if (!t3) - return ae = 0; - var e3 = new St(t3); - e3.cc(t3); - var n2 = e3.bc(); - if (!n2) - return ae = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (Pe(o2, n2, e3.Sb + 16)) - return ae = o2, t3; - } - return ae = n2, t3; - }, l: function() { - var t3 = Tt; - if (!t3) - return ae = 0; - var e3 = new St(t3); - e3.cc(t3); - var n2 = e3.bc(); - if (!n2) - return ae = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (Pe(o2, n2, e3.Sb + 16)) - return ae = o2, t3; - } - return ae = n2, t3; - }, h: function() { - var t3 = Tt; - if (!t3) - return ae = 0; - var e3 = new St(t3); - e3.cc(t3); - var n2 = e3.bc(); - if (!n2) - return ae = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (Pe(o2, n2, e3.Sb + 16)) - return ae = o2, t3; - } - return ae = n2, t3; - }, t: Ot, M: function() { - var t3 = wt.pop(); - t3 || it("no exception to throw"); - var e3 = t3.Zb; - throw t3.kc() || (wt.push(t3), t3.ic(true), t3.hc(false), xt++), Tt = e3, e3; - }, c: function(t3, e3, n2) { - throw new St(t3).fc(e3, n2), Tt = t3, xt++, t3; - }, pa: function() { - return xt; - }, Fa: function(t3) { - ye(t3, !v, 1, !_), dt.pc(); - }, T: function(t3) { - x ? postMessage({ cmd: "cleanupThread", thread: t3 }) : ct(t3); - }, xa: Et, j: function(t3) { - throw Tt || (Tt = t3), t3; - }, H: It, Ma: Pt, ua: Dt, wa: $t, oa: kt, Ka: Ct, Ca: Ft, Ja: Nt, V: Lt, va: Rt, sa: jt, La: Mt, ta: Ut, Ta: function() { - }, X: function() { - it("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); - }, Ua: function() { - it("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); - }, W: function() { - return Date.now(); - }, ya: function() { - return 2097152; - }, Oa: function() { - return true; - }, za: function(t3, e3, n2, r3) { - if (t3 == e3) - setTimeout(() => Vt(r3)); - else if (x) - postMessage({ targetThread: t3, cmd: "processProxyingQueue", queue: r3 }); - else { - if (!(t3 = dt.Vb[t3])) - return; - t3.postMessage({ cmd: "processProxyingQueue", queue: r3 }); - } - return 1; - }, Ea: function() { - return -1; - }, Pa: function(t3, e3) { - t3 = new Date(1e3 * Bt(t3)), i()[e3 >> 2 >>> 0] = t3.getUTCSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), t3 = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i()[e3 + 28 >> 2 >>> 0] = t3; - }, Qa: function(t3, e3) { - t3 = new Date(1e3 * Bt(t3)), i()[e3 >> 2 >>> 0] = t3.getSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getDay(); - var n2 = new Date(t3.getFullYear(), 0, 1), r3 = (t3.getTime() - n2.getTime()) / 864e5 | 0; - i()[e3 + 28 >> 2 >>> 0] = r3, i()[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(), r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(), t3 = 0 | (r3 != (n2 = n2.getTimezoneOffset()) && t3.getTimezoneOffset() == Math.min(n2, r3)), i()[e3 + 32 >> 2 >>> 0] = t3; - }, Ra: function(t3) { - var e3 = new Date(i()[t3 + 20 >> 2 >>> 0] + 1900, i()[t3 + 16 >> 2 >>> 0], i()[t3 + 12 >> 2 >>> 0], i()[t3 + 8 >> 2 >>> 0], i()[t3 + 4 >> 2 >>> 0], i()[t3 >> 2 >>> 0], 0), n2 = i()[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), o2 = new Date(e3.getFullYear(), 0, 1), a2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), s2 = o2.getTimezoneOffset(), u2 = Math.min(s2, a2); - return 0 > n2 ? i()[t3 + 32 >> 2 >>> 0] = Number(a2 != s2 && u2 == r3) : 0 < n2 != (u2 == r3) && (a2 = Math.max(s2, a2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? u2 : a2) - r3))), i()[t3 + 24 >> 2 >>> 0] = e3.getDay(), n2 = (e3.getTime() - o2.getTime()) / 864e5 | 0, i()[t3 + 28 >> 2 >>> 0] = n2, i()[t3 >> 2 >>> 0] = e3.getSeconds(), i()[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), i()[t3 + 8 >> 2 >>> 0] = e3.getHours(), i()[t3 + 12 >> 2 >>> 0] = e3.getDate(), i()[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0; - }, Aa: zt, Ba: Gt, Sa: function t3(e3, n2, r3) { - t3.Ac || (t3.Ac = true, Wt(e3, n2, r3)); - }, y: function() { - it(""); - }, U: function() { - if (!w && !v) { - var t3 = "Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"; - _t || (_t = {}), _t[t3] || (_t[t3] = 1, w && (t3 = "warning: " + t3), P(t3)); - } - }, ra: function() { - return 4294901760; - }, B: vt, Ia: function(t3, e3, n2) { - r2().copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0); - }, F: function() { - return w ? n(3993).cpus().length : navigator.hardwareConcurrency; - }, Da: function(t3, e3, n2) { - Yt.length = e3, n2 >>= 3; - for (var r3 = 0; r3 < e3; r3++) - Yt[r3] = a()[n2 + r3 >>> 0]; - return (0 > t3 ? st[-t3 - 1] : pe[t3]).apply(null, Yt); - }, qa: function(t3) { - var e3 = r2().length; - if ((t3 >>>= 0) <= e3 || 4294901760 < t3) - return false; - for (var n2 = 1; 4 >= n2; n2 *= 2) { - var i2 = e3 * (1 + 0.2 / n2); - i2 = Math.min(i2, t3 + 100663296); - var o2 = Math; - i2 = Math.max(t3, i2), o2 = o2.min.call(o2, 4294901760, i2 + (65536 - i2 % 65536) % 65536); - t: { - try { - $.grow(o2 - C.byteLength + 65535 >>> 16), H($.buffer); - var a2 = 1; - break t; - } catch (t4) { - } - a2 = void 0; - } - if (a2) - return true; - } - return false; - }, Na: function() { - throw "unwind"; - }, Ga: Jt, Ha: Qt, J: ft, I: te, S: ee, ga: ne, R: oe, d: function() { - return ae; - }, na: function t3(r3, i2) { - t3.lc || (t3.lc = function() { - if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) { - var t4 = new Uint8Array(1); - return () => (crypto.getRandomValues(t4), t4[0]); - } - if (w) - try { - var e3 = n(Object(function() { - var t5 = new Error("Cannot find module 'crypto'"); - throw t5.code = "MODULE_NOT_FOUND", t5; - }())); - return () => e3.randomBytes(1)[0]; - } catch (t5) { - } - return () => it("randomDevice"); - }()); - for (var o2 = 0; o2 < i2; o2++) - e2()[r3 + o2 >> 0 >>> 0] = t3.lc(); - return 0; - }, ia: function(t3, e3, n2) { - var r3 = Ae(); - try { - return yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ja: function(t3, e3, n2) { - var r3 = Ae(); - try { - return yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, K: function(t3) { - var e3 = Ae(); - try { - return yt(t3)(); - } catch (t4) { - if (Ee(e3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, f: function(t3, e3) { - var n2 = Ae(); - try { - return yt(t3)(e3); - } catch (t4) { - if (Ee(n2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, P: function(t3, e3, n2) { - var r3 = Ae(); - try { - return yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, Q: function(t3, e3, n2) { - var r3 = Ae(); - try { - return yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, k: function(t3, e3, n2) { - var r3 = Ae(); - try { - return yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, p: function(t3, e3, n2, r3) { - var i2 = Ae(); - try { - return yt(t3)(e3, n2, r3); - } catch (t4) { - if (Ee(i2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, q: function(t3, e3, n2, r3, i2) { - var o2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2); - } catch (t4) { - if (Ee(o2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, N: function(t3, e3, n2, r3, i2, o2) { - var a2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (Ee(a2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, s: function(t3, e3, n2, r3, i2, o2) { - var a2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (Ee(a2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, w: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (Ee(s2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, L: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (Ee(u2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, E: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { - var f2 = Ae(); - try { - return yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); - } catch (t4) { - if (Ee(f2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Ae(); - try { - return Me(t3, e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (Ee(u2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, _: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Ae(); - try { - return ke(t3, e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (Ee(s2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, Z: function(t3, e3, n2, r3, i2) { - var o2 = Ae(); - try { - return Ue(t3, e3, n2, r3, i2); - } catch (t4) { - if (Ee(o2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ca: function(t3, e3, n2, r3) { - var i2 = Ae(); - try { - return Re(t3, e3, n2, r3); - } catch (t4) { - if (Ee(i2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, $: function(t3) { - var e3 = Ae(); - try { - return $e(t3); - } catch (t4) { - if (Ee(e3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ba: function(t3, e3) { - var n2 = Ae(); - try { - return je(t3, e3); - } catch (t4) { - if (Ee(n2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, Y: function(t3, e3, n2) { - var r3 = Ae(); - try { - return Ce(t3, e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, g: function(t3) { - var e3 = Ae(); - try { - yt(t3)(); - } catch (t4) { - if (Ee(e3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, r: function(t3, e3) { - var n2 = Ae(); - try { - yt(t3)(e3); - } catch (t4) { - if (Ee(n2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, i: function(t3, e3, n2) { - var r3 = Ae(); - try { - yt(t3)(e3, n2); - } catch (t4) { - if (Ee(r3), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ha: function(t3, e3, n2, r3) { - var i2 = Ae(); - try { - yt(t3)(e3, n2, r3); - } catch (t4) { - if (Ee(i2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, m: function(t3, e3, n2, r3) { - var i2 = Ae(); - try { - yt(t3)(e3, n2, r3); - } catch (t4) { - if (Ee(i2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, v: function(t3, e3, n2, r3, i2) { - var o2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2); - } catch (t4) { - if (Ee(o2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, u: function(t3, e3, n2, r3, i2, o2) { - var a2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (Ee(a2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, O: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (Ee(s2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, A: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (Ee(u2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ka: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) { - var c2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2); - } catch (t4) { - if (Ee(c2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) { - var p2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2); - } catch (t4) { - if (Ee(p2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) { - var b2 = Ae(); - try { - yt(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2); - } catch (t4) { - if (Ee(b2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, fa: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Ae(); - try { - Fe(t3, e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (Ee(u2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, da: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { - var f2 = Ae(); - try { - Le(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); - } catch (t4) { - if (Ee(f2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, ea: function(t3, e3, n2, r3, i2, o2) { - var a2 = Ae(); - try { - Ne(t3, e3, n2, r3, i2, o2); - } catch (t4) { - if (Ee(a2), t4 !== t4 + 0) - throw t4; - Se(1, 0); - } - }, o: function(t3) { - return t3; - }, a: $ || s.wasmMemory, G: function(t3) { - ae = t3; - }, la: le, z: function(t3, e3, n2, r3) { - return le(t3, e3, n2, r3); - } }; - !function() { - function t3(t4, e4) { - s.asm = t4.exports, dt.qc.push(s.asm.sb), q = s.asm.ub, Y.unshift(s.asm.Va), k = e4, x || (et--, s.monitorRunDependencies && s.monitorRunDependencies(et), 0 == et && (null !== nt && (clearInterval(nt), nt = null), rt && (t4 = rt, rt = null, t4()))); - } - function e3(e4) { - t3(e4.instance, e4.module); - } - function n2(t4) { - return function() { - if (!E && (_ || v)) { - if ("function" == typeof fetch && !tt.startsWith("file://")) - return fetch(tt, { credentials: "same-origin" }).then(function(t5) { - if (!t5.ok) - throw "failed to load wasm binary file at '" + tt + "'"; - return t5.arrayBuffer(); - }).catch(function() { - return at(); - }); - if (p) - return new Promise(function(t5, e4) { - p(tt, function(e5) { - t5(new Uint8Array(e5)); - }, e4); - }); - } - return Promise.resolve().then(function() { - return at(); - }); - }().then(function(t5) { - return WebAssembly.instantiate(t5, r3); - }).then(function(t5) { - return t5; - }).then(t4, function(t5) { - P("failed to asynchronously prepare wasm: " + t5), it(t5); - }); - } - var r3 = { a: fe }; - if (x || (et++, s.monitorRunDependencies && s.monitorRunDependencies(et)), s.instantiateWasm) - try { - return s.instantiateWasm(r3, t3); - } catch (t4) { - return P("Module.instantiateWasm callback failed with error: " + t4), false; - } - (E || "function" != typeof WebAssembly.instantiateStreaming || ot() || tt.startsWith("file://") || w || "function" != typeof fetch ? n2(e3) : fetch(tt, { credentials: "same-origin" }).then(function(t4) { - return WebAssembly.instantiateStreaming(t4, r3).then(e3, function(t5) { - return P("wasm streaming compile failed: " + t5), P("falling back to ArrayBuffer instantiation"), n2(e3); - }); - })).catch(c); - }(), s.___wasm_call_ctors = function() { - return (s.___wasm_call_ctors = s.asm.Va).apply(null, arguments); - }, s._OrtInit = function() { - return (s._OrtInit = s.asm.Wa).apply(null, arguments); - }, s._OrtCreateSessionOptions = function() { - return (s._OrtCreateSessionOptions = s.asm.Xa).apply(null, arguments); - }, s._OrtAppendExecutionProvider = function() { - return (s._OrtAppendExecutionProvider = s.asm.Ya).apply(null, arguments); - }, s._OrtAddSessionConfigEntry = function() { - return (s._OrtAddSessionConfigEntry = s.asm.Za).apply(null, arguments); - }, s._OrtReleaseSessionOptions = function() { - return (s._OrtReleaseSessionOptions = s.asm._a).apply(null, arguments); - }, s._OrtCreateSession = function() { - return (s._OrtCreateSession = s.asm.$a).apply(null, arguments); - }, s._OrtReleaseSession = function() { - return (s._OrtReleaseSession = s.asm.ab).apply(null, arguments); - }, s._OrtGetInputCount = function() { - return (s._OrtGetInputCount = s.asm.bb).apply(null, arguments); - }, s._OrtGetOutputCount = function() { - return (s._OrtGetOutputCount = s.asm.cb).apply(null, arguments); - }, s._OrtGetInputName = function() { - return (s._OrtGetInputName = s.asm.db).apply(null, arguments); - }, s._OrtGetOutputName = function() { - return (s._OrtGetOutputName = s.asm.eb).apply(null, arguments); - }, s._OrtFree = function() { - return (s._OrtFree = s.asm.fb).apply(null, arguments); - }, s._OrtCreateTensor = function() { - return (s._OrtCreateTensor = s.asm.gb).apply(null, arguments); - }, s._OrtGetTensorData = function() { - return (s._OrtGetTensorData = s.asm.hb).apply(null, arguments); - }, s._OrtReleaseTensor = function() { - return (s._OrtReleaseTensor = s.asm.ib).apply(null, arguments); - }, s._OrtCreateRunOptions = function() { - return (s._OrtCreateRunOptions = s.asm.jb).apply(null, arguments); - }, s._OrtAddRunConfigEntry = function() { - return (s._OrtAddRunConfigEntry = s.asm.kb).apply(null, arguments); - }, s._OrtReleaseRunOptions = function() { - return (s._OrtReleaseRunOptions = s.asm.lb).apply(null, arguments); - }, s._OrtRun = function() { - return (s._OrtRun = s.asm.mb).apply(null, arguments); - }, s._OrtEndProfiling = function() { - return (s._OrtEndProfiling = s.asm.nb).apply(null, arguments); - }; - var de = s._pthread_self = function() { - return (de = s._pthread_self = s.asm.ob).apply(null, arguments); - }, he = s._malloc = function() { - return (he = s._malloc = s.asm.pb).apply(null, arguments); - }, ge = s._free = function() { - return (ge = s._free = s.asm.qb).apply(null, arguments); - }, be = s._fflush = function() { - return (be = s._fflush = s.asm.rb).apply(null, arguments); - }; - s.__emscripten_tls_init = function() { - return (s.__emscripten_tls_init = s.asm.sb).apply(null, arguments); - }; - var me = s.___funcs_on_exit = function() { - return (me = s.___funcs_on_exit = s.asm.tb).apply(null, arguments); - }, ye = s.__emscripten_thread_init = function() { - return (ye = s.__emscripten_thread_init = s.asm.vb).apply(null, arguments); - }; - s.__emscripten_thread_crashed = function() { - return (s.__emscripten_thread_crashed = s.asm.wb).apply(null, arguments); - }; - var _e, ve = s._emscripten_run_in_main_runtime_thread_js = function() { - return (ve = s._emscripten_run_in_main_runtime_thread_js = s.asm.xb).apply(null, arguments); - }, we = s.__emscripten_proxy_execute_task_queue = function() { - return (we = s.__emscripten_proxy_execute_task_queue = s.asm.yb).apply(null, arguments); - }, xe = s.__emscripten_thread_free_data = function() { - return (xe = s.__emscripten_thread_free_data = s.asm.zb).apply(null, arguments); - }, Te = s.__emscripten_thread_exit = function() { - return (Te = s.__emscripten_thread_exit = s.asm.Ab).apply(null, arguments); - }, Se = s._setThrew = function() { - return (Se = s._setThrew = s.asm.Bb).apply(null, arguments); - }, Oe = s._emscripten_stack_set_limits = function() { - return (Oe = s._emscripten_stack_set_limits = s.asm.Cb).apply(null, arguments); - }, Ae = s.stackSave = function() { - return (Ae = s.stackSave = s.asm.Db).apply(null, arguments); - }, Ee = s.stackRestore = function() { - return (Ee = s.stackRestore = s.asm.Eb).apply(null, arguments); - }, Ie = s.stackAlloc = function() { - return (Ie = s.stackAlloc = s.asm.Fb).apply(null, arguments); - }, Pe = s.___cxa_can_catch = function() { - return (Pe = s.___cxa_can_catch = s.asm.Gb).apply(null, arguments); - }, De = s.___cxa_is_pointer_type = function() { - return (De = s.___cxa_is_pointer_type = s.asm.Hb).apply(null, arguments); - }, $e = s.dynCall_j = function() { - return ($e = s.dynCall_j = s.asm.Ib).apply(null, arguments); - }, ke = s.dynCall_iiiiij = function() { - return (ke = s.dynCall_iiiiij = s.asm.Jb).apply(null, arguments); - }, Ce = s.dynCall_jii = function() { - return (Ce = s.dynCall_jii = s.asm.Kb).apply(null, arguments); - }, Fe = s.dynCall_viiiiij = function() { - return (Fe = s.dynCall_viiiiij = s.asm.Lb).apply(null, arguments); - }, Ne = s.dynCall_vjji = function() { - return (Ne = s.dynCall_vjji = s.asm.Mb).apply(null, arguments); - }, Le = s.dynCall_viiijjjii = function() { - return (Le = s.dynCall_viiijjjii = s.asm.Nb).apply(null, arguments); - }, Re = s.dynCall_iij = function() { - return (Re = s.dynCall_iij = s.asm.Ob).apply(null, arguments); - }, je = s.dynCall_ji = function() { - return (je = s.dynCall_ji = s.asm.Pb).apply(null, arguments); - }, Me = s.dynCall_iiiiiij = function() { - return (Me = s.dynCall_iiiiiij = s.asm.Qb).apply(null, arguments); - }, Ue = s.dynCall_iiij = function() { - return (Ue = s.dynCall_iiij = s.asm.Rb).apply(null, arguments); - }; - function Ve() { - function t3() { - if (!_e && (_e = true, s.calledRun = true, !M) && (x || ht(Y), u(s), s.onRuntimeInitialized && s.onRuntimeInitialized(), !x)) { - if (s.postRun) - for ("function" == typeof s.postRun && (s.postRun = [s.postRun]); s.postRun.length; ) { - var t4 = s.postRun.shift(); - Z.unshift(t4); - } - ht(Z); - } - } - if (!(0 < et)) - if (x) - u(s), x || ht(Y), postMessage({ cmd: "loaded" }); - else { - if (s.preRun) - for ("function" == typeof s.preRun && (s.preRun = [s.preRun]); s.preRun.length; ) - Q(); - ht(X), 0 < et || (s.setStatus ? (s.setStatus("Running..."), setTimeout(function() { - setTimeout(function() { - s.setStatus(""); - }, 1), t3(); - }, 1)) : t3()); - } - } - if (s.UTF8ToString = B, s.stringToUTF8 = function(t3, e3, n2) { - return z(t3, r2(), e3, n2); - }, s.lengthBytesUTF8 = G, s.keepRuntimeAlive = J, s.wasmMemory = $, s.stackSave = Ae, s.stackRestore = Ee, s.stackAlloc = Ie, s.ExitStatus = ut, s.PThread = dt, rt = function t3() { - _e || Ve(), _e || (rt = t3); - }, s.preInit) - for ("function" == typeof s.preInit && (s.preInit = [s.preInit]); 0 < s.preInit.length; ) - s.preInit.pop()(); - return Ve(), t2.ready; - }); - t.exports = r; - }, 932: (t, e, n) => { - var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) { - var e2, r2, i; - t2 = t2 || {}, e2 || (e2 = void 0 !== t2 ? t2 : {}), e2.ready = new Promise(function(t3, e3) { - r2 = t3, i = e3; - }); - var o, a, s, u, c, l, p = Object.assign({}, e2), f = "./this.program", d = (t3, e3) => { - throw e3; - }, h = "object" == typeof window, g = "function" == typeof importScripts, b = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, m = ""; - b ? (m = g ? n(908).dirname(m) + "/" : "//", l = () => { - c || (u = n(1384), c = n(908)); - }, o = function(t3, e3) { - return l(), t3 = c.normalize(t3), u.readFileSync(t3, e3 ? void 0 : "utf8"); - }, s = (t3) => ((t3 = o(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), a = (t3, e3, n2) => { - l(), t3 = c.normalize(t3), u.readFile(t3, function(t4, r3) { - t4 ? n2(t4) : e3(r3.buffer); - }); - }, 1 < process.argv.length && (f = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", function(t3) { - if (!(t3 instanceof K)) - throw t3; - }), process.on("unhandledRejection", function(t3) { - throw t3; - }), d = (t3, e3) => { - if (w || 0 < U) - throw process.exitCode = t3, e3; - e3 instanceof K || v("exiting due to exception: " + e3), process.exit(t3); - }, e2.inspect = function() { - return "[Emscripten Module object]"; - }) : (h || g) && (g ? m = self.location.href : "undefined" != typeof document && document.currentScript && (m = document.currentScript.src), _scriptDir && (m = _scriptDir), m = 0 !== m.indexOf("blob:") ? m.substr(0, m.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", o = (t3) => { - var e3 = new XMLHttpRequest(); - return e3.open("GET", t3, false), e3.send(null), e3.responseText; - }, g && (s = (t3) => { - var e3 = new XMLHttpRequest(); - return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response); - }), a = (t3, e3, n2) => { - var r3 = new XMLHttpRequest(); - r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => { - 200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2(); - }, r3.onerror = n2, r3.send(null); - }); - var y, _ = e2.print || console.log.bind(console), v = e2.printErr || console.warn.bind(console); - Object.assign(e2, p), p = null, e2.thisProgram && (f = e2.thisProgram), e2.quit && (d = e2.quit), e2.wasmBinary && (y = e2.wasmBinary); - var w = e2.noExitRuntime || false; - "object" != typeof WebAssembly && W("no native wasm support detected"); - var x, T, S, O, A, E, I = false, P = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; - function D(t3, e3, n2) { - var r3 = (e3 >>>= 0) + n2; - for (n2 = e3; t3[n2] && !(n2 >= r3); ) - ++n2; - if (16 < n2 - e3 && t3.buffer && P) - return P.decode(t3.subarray(e3, n2)); - for (r3 = ""; e3 < n2; ) { - var i2 = t3[e3++]; - if (128 & i2) { - var o2 = 63 & t3[e3++]; - if (192 == (224 & i2)) - r3 += String.fromCharCode((31 & i2) << 6 | o2); - else { - var a2 = 63 & t3[e3++]; - 65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2)); - } - } else - r3 += String.fromCharCode(i2); - } - return r3; - } - function $(t3, e3) { - return (t3 >>>= 0) ? D(O, t3, e3) : ""; - } - function k(t3, e3, n2, r3) { - if (!(0 < r3)) - return 0; - var i2 = n2 >>>= 0; - r3 = n2 + r3 - 1; - for (var o2 = 0; o2 < t3.length; ++o2) { - var a2 = t3.charCodeAt(o2); - if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) { - if (n2 >= r3) - break; - e3[n2++ >>> 0] = a2; - } else { - if (2047 >= a2) { - if (n2 + 1 >= r3) - break; - e3[n2++ >>> 0] = 192 | a2 >> 6; - } else { - if (65535 >= a2) { - if (n2 + 2 >= r3) - break; - e3[n2++ >>> 0] = 224 | a2 >> 12; - } else { - if (n2 + 3 >= r3) - break; - e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63; - } - e3[n2++ >>> 0] = 128 | a2 >> 6 & 63; - } - e3[n2++ >>> 0] = 128 | 63 & a2; - } - } - return e3[n2 >>> 0] = 0, n2 - i2; - } - function C(t3) { - for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) { - var r3 = t3.charCodeAt(n2); - 127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3; - } - return e3; - } - function F() { - var t3 = x.buffer; - T = t3, e2.HEAP8 = S = new Int8Array(t3), e2.HEAP16 = new Int16Array(t3), e2.HEAP32 = A = new Int32Array(t3), e2.HEAPU8 = O = new Uint8Array(t3), e2.HEAPU16 = new Uint16Array(t3), e2.HEAPU32 = E = new Uint32Array(t3), e2.HEAPF32 = new Float32Array(t3), e2.HEAPF64 = new Float64Array(t3); - } - var N, L = [], R = [], j = [], M = [], U = 0; - function V() { - var t3 = e2.preRun.shift(); - L.unshift(t3); - } - var B, z = 0, G = null, H = null; - function W(t3) { - throw e2.onAbort && e2.onAbort(t3), v(t3 = "Aborted(" + t3 + ")"), I = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), i(t3), t3; - } - function q() { - return B.startsWith("data:application/octet-stream;base64,"); - } - if (B = "ort-wasm.wasm", !q()) { - var X = B; - B = e2.locateFile ? e2.locateFile(X, m) : m + X; - } - function Y() { - var t3 = B; - try { - if (t3 == B && y) - return new Uint8Array(y); - if (s) - return s(t3); - throw "both async and sync fetching of the wasm failed"; - } catch (t4) { - W(t4); - } - } - function K(t3) { - this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3; - } - function Z(t3) { - for (; 0 < t3.length; ) - t3.shift()(e2); - } - var J = [], Q = 0, tt = 0; - function et(t3) { - this.Db = t3, this.zb = t3 - 24, this.Ub = function(t4) { - E[this.zb + 4 >> 2 >>> 0] = t4; - }, this.Eb = function() { - return E[this.zb + 4 >> 2 >>> 0]; - }, this.Sb = function(t4) { - E[this.zb + 8 >> 2 >>> 0] = t4; - }, this.Wb = function() { - return E[this.zb + 8 >> 2 >>> 0]; - }, this.Tb = function() { - A[this.zb >> 2 >>> 0] = 0; - }, this.Ib = function(t4) { - S[this.zb + 12 >> 0 >>> 0] = t4 ? 1 : 0; - }, this.Pb = function() { - return 0 != S[this.zb + 12 >> 0 >>> 0]; - }, this.Jb = function(t4) { - S[this.zb + 13 >> 0 >>> 0] = t4 ? 1 : 0; - }, this.Lb = function() { - return 0 != S[this.zb + 13 >> 0 >>> 0]; - }, this.Rb = function(t4, e3) { - this.Fb(0), this.Ub(t4), this.Sb(e3), this.Tb(), this.Ib(false), this.Jb(false); - }, this.Nb = function() { - A[this.zb >> 2 >>> 0] += 1; - }, this.Xb = function() { - var t4 = A[this.zb >> 2 >>> 0]; - return A[this.zb >> 2 >>> 0] = t4 - 1, 1 === t4; - }, this.Fb = function(t4) { - E[this.zb + 16 >> 2 >>> 0] = t4; - }, this.Ob = function() { - return E[this.zb + 16 >> 2 >>> 0]; - }, this.Qb = function() { - if (Et(this.Eb())) - return E[this.Db >> 2 >>> 0]; - var t4 = this.Ob(); - return 0 !== t4 ? t4 : this.Db; - }; - } - function nt(t3) { - return _t(new et(t3).zb); - } - var rt = []; - function it(t3) { - var e3 = rt[t3]; - return e3 || (t3 >= rt.length && (rt.length = t3 + 1), rt[t3] = e3 = N.get(t3)), e3; - } - function ot(t3) { - var e3 = C(t3) + 1, n2 = yt(e3); - return n2 && k(t3, S, n2, e3), n2; - } - var at = {}; - function st() { - if (!ut) { - var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: f || "./this.program" }; - for (t3 in at) - void 0 === at[t3] ? delete e3[t3] : e3[t3] = at[t3]; - var n2 = []; - for (t3 in e3) - n2.push(t3 + "=" + e3[t3]); - ut = n2; - } - return ut; - } - var ut, ct = [null, [], []]; - function lt(t3, e3) { - var n2 = ct[t3]; - 0 === e3 || 10 === e3 ? ((1 === t3 ? _ : v)(D(n2, 0)), n2.length = 0) : n2.push(e3); - } - var pt = 0; - function ft(t3) { - return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400); - } - var dt = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ht = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function gt(t3, e3, n2, r3) { - function i2(t4, e4, n3) { - for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e4; ) - t4 = n3[0] + t4; - return t4; - } - function o2(t4, e4) { - return i2(t4, e4, "0"); - } - function a2(t4, e4) { - function n3(t5) { - return 0 > t5 ? -1 : 0 < t5 ? 1 : 0; - } - var r4; - return 0 === (r4 = n3(t4.getFullYear() - e4.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e4.getMonth())) && (r4 = n3(t4.getDate() - e4.getDate())), r4; - } - function s2(t4) { - switch (t4.getDay()) { - case 0: - return new Date(t4.getFullYear() - 1, 11, 29); - case 1: - return t4; - case 2: - return new Date(t4.getFullYear(), 0, 3); - case 3: - return new Date(t4.getFullYear(), 0, 2); - case 4: - return new Date(t4.getFullYear(), 0, 1); - case 5: - return new Date(t4.getFullYear() - 1, 11, 31); - case 6: - return new Date(t4.getFullYear() - 1, 11, 30); - } - } - function u2(t4) { - var e4 = t4.Bb; - for (t4 = new Date(new Date(t4.Cb + 1900, 0, 1).getTime()); 0 < e4; ) { - var n3 = t4.getMonth(), r4 = (ft(t4.getFullYear()) ? dt : ht)[n3]; - if (!(e4 > r4 - t4.getDate())) { - t4.setDate(t4.getDate() + e4); - break; - } - e4 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1)); - } - return n3 = new Date(t4.getFullYear() + 1, 0, 4), e4 = s2(new Date(t4.getFullYear(), 0, 4)), n3 = s2(n3), 0 >= a2(e4, t4) ? 0 >= a2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1; - } - var c2 = A[r3 + 40 >> 2 >>> 0]; - for (var l2 in r3 = { $b: A[r3 >> 2 >>> 0], Zb: A[r3 + 4 >> 2 >>> 0], Gb: A[r3 + 8 >> 2 >>> 0], Kb: A[r3 + 12 >> 2 >>> 0], Hb: A[r3 + 16 >> 2 >>> 0], Cb: A[r3 + 20 >> 2 >>> 0], Ab: A[r3 + 24 >> 2 >>> 0], Bb: A[r3 + 28 >> 2 >>> 0], bc: A[r3 + 32 >> 2 >>> 0], Yb: A[r3 + 36 >> 2 >>> 0], ac: c2 ? $(c2) : "" }, n2 = $(n2), c2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) - n2 = n2.replace(new RegExp(l2, "g"), c2[l2]); - var p2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), f2 = "January February March April May June July August September October November December".split(" "); - for (l2 in c2 = { "%a": function(t4) { - return p2[t4.Ab].substring(0, 3); - }, "%A": function(t4) { - return p2[t4.Ab]; - }, "%b": function(t4) { - return f2[t4.Hb].substring(0, 3); - }, "%B": function(t4) { - return f2[t4.Hb]; - }, "%C": function(t4) { - return o2((t4.Cb + 1900) / 100 | 0, 2); - }, "%d": function(t4) { - return o2(t4.Kb, 2); - }, "%e": function(t4) { - return i2(t4.Kb, 2, " "); - }, "%g": function(t4) { - return u2(t4).toString().substring(2); - }, "%G": function(t4) { - return u2(t4); - }, "%H": function(t4) { - return o2(t4.Gb, 2); - }, "%I": function(t4) { - return 0 == (t4 = t4.Gb) ? t4 = 12 : 12 < t4 && (t4 -= 12), o2(t4, 2); - }, "%j": function(t4) { - for (var e4 = 0, n3 = 0; n3 <= t4.Hb - 1; e4 += (ft(t4.Cb + 1900) ? dt : ht)[n3++]) - ; - return o2(t4.Kb + e4, 3); - }, "%m": function(t4) { - return o2(t4.Hb + 1, 2); - }, "%M": function(t4) { - return o2(t4.Zb, 2); - }, "%n": function() { - return "\n"; - }, "%p": function(t4) { - return 0 <= t4.Gb && 12 > t4.Gb ? "AM" : "PM"; - }, "%S": function(t4) { - return o2(t4.$b, 2); - }, "%t": function() { - return " "; - }, "%u": function(t4) { - return t4.Ab || 7; - }, "%U": function(t4) { - return o2(Math.floor((t4.Bb + 7 - t4.Ab) / 7), 2); - }, "%V": function(t4) { - var e4 = Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7); - if (2 >= (t4.Ab + 371 - t4.Bb - 2) % 7 && e4++, e4) - 53 == e4 && (4 == (n3 = (t4.Ab + 371 - t4.Bb) % 7) || 3 == n3 && ft(t4.Cb) || (e4 = 1)); - else { - e4 = 52; - var n3 = (t4.Ab + 7 - t4.Bb - 1) % 7; - (4 == n3 || 5 == n3 && ft(t4.Cb % 400 - 1)) && e4++; - } - return o2(e4, 2); - }, "%w": function(t4) { - return t4.Ab; - }, "%W": function(t4) { - return o2(Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7), 2); - }, "%y": function(t4) { - return (t4.Cb + 1900).toString().substring(2); - }, "%Y": function(t4) { - return t4.Cb + 1900; - }, "%z": function(t4) { - var e4 = 0 <= (t4 = t4.Yb); - return t4 = Math.abs(t4) / 60, (e4 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4); - }, "%Z": function(t4) { - return t4.ac; - }, "%%": function() { - return "%"; - } }, n2 = n2.replace(/%%/g, "\0\0"), c2) - n2.includes(l2) && (n2 = n2.replace(new RegExp(l2, "g"), c2[l2](r3))); - return l2 = function(t4) { - var e4 = Array(C(t4) + 1); - return k(t4, e4, 0, e4.length), e4; - }(n2 = n2.replace(/\0\0/g, "%")), l2.length > e3 ? 0 : (S.set(l2, t3 >>> 0), l2.length - 1); - } - var bt = { a: function(t3) { - return yt(t3 + 24) + 24; - }, m: function(t3) { - return (t3 = new et(t3)).Pb() || (t3.Ib(true), Q--), t3.Jb(false), J.push(t3), t3.Nb(), t3.Qb(); - }, ia: function(t3) { - throw v("Unexpected exception thrown, this is not properly supported - aborting"), I = true, t3; - }, w: function() { - xt(0); - var t3 = J.pop(); - if (t3.Xb() && !t3.Lb()) { - var e3 = t3.Wb(); - e3 && it(e3)(t3.Db), nt(t3.Db); - } - tt = 0; - }, d: function() { - var t3 = tt; - if (!t3) - return pt = 0; - var e3 = new et(t3); - e3.Fb(t3); - var n2 = e3.Eb(); - if (!n2) - return pt = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (At(o2, n2, e3.zb + 16)) - return pt = o2, t3; - } - return pt = n2, t3; - }, k: function() { - var t3 = tt; - if (!t3) - return pt = 0; - var e3 = new et(t3); - e3.Fb(t3); - var n2 = e3.Eb(); - if (!n2) - return pt = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (At(o2, n2, e3.zb + 16)) - return pt = o2, t3; - } - return pt = n2, t3; - }, g: function() { - var t3 = tt; - if (!t3) - return pt = 0; - var e3 = new et(t3); - e3.Fb(t3); - var n2 = e3.Eb(); - if (!n2) - return pt = 0, t3; - for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { - var o2 = r3[i2]; - if (0 === o2 || o2 === n2) - break; - if (At(o2, n2, e3.zb + 16)) - return pt = o2, t3; - } - return pt = n2, t3; - }, s: nt, L: function() { - var t3 = J.pop(); - t3 || W("no exception to throw"); - var e3 = t3.Db; - throw t3.Lb() || (J.push(t3), t3.Jb(true), t3.Ib(false), Q++), tt = e3, e3; - }, b: function(t3, e3, n2) { - throw new et(t3).Rb(e3, n2), tt = t3, Q++, t3; - }, la: function() { - return Q; - }, i: function(t3) { - throw tt || (tt = t3), t3; - }, H: function() { - return 0; - }, Ba: function() { - }, pa: function() { - }, ra: function() { - }, ka: function() { - return 0; - }, za: function() { - }, ua: function() { - }, ya: function() { - }, R: function() { - }, qa: function() { - }, na: function() { - }, Aa: function() { - }, oa: function() { - }, Ha: function() { - }, Ja: function() { - W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); - }, Ia: function() { - W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); - }, S: function() { - return Date.now(); - }, Ca: function() { - return true; - }, Da: function(t3, e3) { - t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getUTCSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), A[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), A[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0; - }, Ea: function(t3, e3) { - t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getHours(), A[e3 + 12 >> 2 >>> 0] = t3.getDate(), A[e3 + 16 >> 2 >>> 0] = t3.getMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getDay(); - var n2 = new Date(t3.getFullYear(), 0, 1); - A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - n2.getTime()) / 864e5 | 0, A[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(); - var r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(); - n2 = n2.getTimezoneOffset(), A[e3 + 32 >> 2 >>> 0] = 0 | (r3 != n2 && t3.getTimezoneOffset() == Math.min(n2, r3)); - }, Fa: function(t3) { - var e3 = new Date(A[t3 + 20 >> 2 >>> 0] + 1900, A[t3 + 16 >> 2 >>> 0], A[t3 + 12 >> 2 >>> 0], A[t3 + 8 >> 2 >>> 0], A[t3 + 4 >> 2 >>> 0], A[t3 >> 2 >>> 0], 0), n2 = A[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), i2 = new Date(e3.getFullYear(), 0, 1), o2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), a2 = i2.getTimezoneOffset(), s2 = Math.min(a2, o2); - return 0 > n2 ? A[t3 + 32 >> 2 >>> 0] = Number(o2 != a2 && s2 == r3) : 0 < n2 != (s2 == r3) && (o2 = Math.max(a2, o2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? s2 : o2) - r3))), A[t3 + 24 >> 2 >>> 0] = e3.getDay(), A[t3 + 28 >> 2 >>> 0] = (e3.getTime() - i2.getTime()) / 864e5 | 0, A[t3 >> 2 >>> 0] = e3.getSeconds(), A[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), A[t3 + 8 >> 2 >>> 0] = e3.getHours(), A[t3 + 12 >> 2 >>> 0] = e3.getDate(), A[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0; - }, sa: function() { - return -52; - }, ta: function() { - }, Ga: function t3(e3, n2, r3) { - t3.Vb || (t3.Vb = true, function(t4, e4, n3) { - function r4(t5) { - return (t5 = t5.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t5[1] : "GMT"; - } - var i2 = (/* @__PURE__ */ new Date()).getFullYear(), o2 = new Date(i2, 0, 1), a2 = new Date(i2, 6, 1); - i2 = o2.getTimezoneOffset(); - var s2 = a2.getTimezoneOffset(); - A[t4 >> 2 >>> 0] = 60 * Math.max(i2, s2), A[e4 >> 2 >>> 0] = Number(i2 != s2), t4 = r4(o2), e4 = r4(a2), t4 = ot(t4), e4 = ot(e4), s2 < i2 ? (E[n3 >> 2 >>> 0] = t4, E[n3 + 4 >> 2 >>> 0] = e4) : (E[n3 >> 2 >>> 0] = e4, E[n3 + 4 >> 2 >>> 0] = t4); - }(e3, n2, r3)); - }, B: function() { - W(""); - }, ma: function() { - return 4294901760; - }, I: b ? () => { - var t3 = process.hrtime(); - return 1e3 * t3[0] + t3[1] / 1e6; - } : () => performance.now(), xa: function(t3, e3, n2) { - O.copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0); - }, G: function(t3) { - var e3 = O.length; - if (4294901760 < (t3 >>>= 0)) - return false; - for (var n2 = 1; 4 >= n2; n2 *= 2) { - var r3 = e3 * (1 + 0.2 / n2); - r3 = Math.min(r3, t3 + 100663296); - var i2 = Math; - r3 = Math.max(t3, r3), i2 = i2.min.call(i2, 4294901760, r3 + (65536 - r3 % 65536) % 65536); - t: { - try { - x.grow(i2 - T.byteLength + 65535 >>> 16), F(); - var o2 = 1; - break t; - } catch (t4) { - } - o2 = void 0; - } - if (o2) - return true; - } - return false; - }, va: function(t3, e3) { - var n2 = 0; - return st().forEach(function(r3, i2) { - var o2 = e3 + n2; - for (i2 = E[t3 + 4 * i2 >> 2 >>> 0] = o2, o2 = 0; o2 < r3.length; ++o2) - S[i2++ >> 0 >>> 0] = r3.charCodeAt(o2); - S[i2 >> 0 >>> 0] = 0, n2 += r3.length + 1; - }), 0; - }, wa: function(t3, e3) { - var n2 = st(); - E[t3 >> 2 >>> 0] = n2.length; - var r3 = 0; - return n2.forEach(function(t4) { - r3 += t4.length + 1; - }), E[e3 >> 2 >>> 0] = r3, 0; - }, ba: function(t3) { - w || 0 < U || (wt(), Z(j), vt(0), ct[1].length && lt(1, 10), ct[2].length && lt(2, 10)), w || 0 < U || (e2.onExit && e2.onExit(t3), I = true), d(t3, new K(t3)); - }, E: function() { - return 52; - }, Q: function() { - return 52; - }, ca: function() { - return 70; - }, P: function(t3, e3, n2, r3) { - for (var i2 = 0, o2 = 0; o2 < n2; o2++) { - var a2 = E[e3 >> 2 >>> 0], s2 = E[e3 + 4 >> 2 >>> 0]; - e3 += 8; - for (var u2 = 0; u2 < s2; u2++) - lt(t3, O[a2 + u2 >>> 0]); - i2 += s2; - } - return E[r3 >> 2 >>> 0] = i2, 0; - }, c: function() { - return pt; - }, ja: function t3(e3, r3) { - t3.Mb || (t3.Mb = function() { - if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) { - var t4 = new Uint8Array(1); - return () => (crypto.getRandomValues(t4), t4[0]); - } - if (b) - try { - var e4 = n(Object(function() { - var t5 = new Error("Cannot find module 'crypto'"); - throw t5.code = "MODULE_NOT_FOUND", t5; - }())); - return () => e4.randomBytes(1)[0]; - } catch (t5) { - } - return () => W("randomDevice"); - }()); - for (var i2 = 0; i2 < r3; i2++) - S[e3 + i2 >> 0 >>> 0] = t3.Mb(); - return 0; - }, ea: function(t3, e3, n2) { - var r3 = Tt(); - try { - return it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, fa: function(t3, e3, n2) { - var r3 = Tt(); - try { - return it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, J: function(t3) { - var e3 = Tt(); - try { - return it(t3)(); - } catch (t4) { - if (St(e3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, e: function(t3, e3) { - var n2 = Tt(); - try { - return it(t3)(e3); - } catch (t4) { - if (St(n2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, N: function(t3, e3, n2) { - var r3 = Tt(); - try { - return it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, O: function(t3, e3, n2) { - var r3 = Tt(); - try { - return it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, j: function(t3, e3, n2) { - var r3 = Tt(); - try { - return it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, o: function(t3, e3, n2, r3) { - var i2 = Tt(); - try { - return it(t3)(e3, n2, r3); - } catch (t4) { - if (St(i2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, p: function(t3, e3, n2, r3, i2) { - var o2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2); - } catch (t4) { - if (St(o2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, M: function(t3, e3, n2, r3, i2, o2) { - var a2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (St(a2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, r: function(t3, e3, n2, r3, i2, o2) { - var a2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (St(a2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, v: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (St(s2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, K: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (St(u2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { - var f2 = Tt(); - try { - return it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); - } catch (t4) { - if (St(f2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, X: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Tt(); - try { - return Lt(t3, e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (St(u2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, V: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Tt(); - try { - return Pt(t3, e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (St(s2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, U: function(t3, e3, n2, r3, i2) { - var o2 = Tt(); - try { - return Rt(t3, e3, n2, r3, i2); - } catch (t4) { - if (St(o2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, Z: function(t3, e3, n2, r3) { - var i2 = Tt(); - try { - return Ft(t3, e3, n2, r3); - } catch (t4) { - if (St(i2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, W: function(t3) { - var e3 = Tt(); - try { - return It(t3); - } catch (t4) { - if (St(e3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, Y: function(t3, e3) { - var n2 = Tt(); - try { - return Nt(t3, e3); - } catch (t4) { - if (St(n2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, T: function(t3, e3, n2) { - var r3 = Tt(); - try { - return Dt(t3, e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, f: function(t3) { - var e3 = Tt(); - try { - it(t3)(); - } catch (t4) { - if (St(e3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, q: function(t3, e3) { - var n2 = Tt(); - try { - it(t3)(e3); - } catch (t4) { - if (St(n2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, h: function(t3, e3, n2) { - var r3 = Tt(); - try { - it(t3)(e3, n2); - } catch (t4) { - if (St(r3), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, da: function(t3, e3, n2, r3) { - var i2 = Tt(); - try { - it(t3)(e3, n2, r3); - } catch (t4) { - if (St(i2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, l: function(t3, e3, n2, r3) { - var i2 = Tt(); - try { - it(t3)(e3, n2, r3); - } catch (t4) { - if (St(i2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, t: function(t3, e3, n2, r3, i2) { - var o2 = Tt(); - try { - it(t3)(e3, n2, r3, i2); - } catch (t4) { - if (St(o2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, u: function(t3, e3, n2, r3, i2, o2) { - var a2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2); - } catch (t4) { - if (St(a2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, x: function(t3, e3, n2, r3, i2, o2, a2) { - var s2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2, a2); - } catch (t4) { - if (St(s2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, z: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (St(u2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, ga: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) { - var c2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2, a2, s2, u2); - } catch (t4) { - if (St(c2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, A: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) { - var p2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2); - } catch (t4) { - if (St(p2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) { - var b2 = Tt(); - try { - it(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2); - } catch (t4) { - if (St(b2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) { - var u2 = Tt(); - try { - $t(t3, e3, n2, r3, i2, o2, a2, s2); - } catch (t4) { - if (St(u2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, _: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { - var f2 = Tt(); - try { - Ct(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); - } catch (t4) { - if (St(f2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, $: function(t3, e3, n2, r3, i2, o2) { - var a2 = Tt(); - try { - kt(t3, e3, n2, r3, i2, o2); - } catch (t4) { - if (St(a2), t4 !== t4 + 0) - throw t4; - xt(1, 0); - } - }, n: function(t3) { - return t3; - }, F: function(t3) { - pt = t3; - }, ha: gt, y: function(t3, e3, n2, r3) { - return gt(t3, e3, n2, r3); - } }; - !function() { - function t3(t4) { - e2.asm = t4.exports, x = e2.asm.Ka, F(), N = e2.asm.ib, R.unshift(e2.asm.La), z--, e2.monitorRunDependencies && e2.monitorRunDependencies(z), 0 == z && (null !== G && (clearInterval(G), G = null), H && (t4 = H, H = null, t4())); - } - function n2(e3) { - t3(e3.instance); - } - function r3(t4) { - return function() { - if (!y && (h || g)) { - if ("function" == typeof fetch && !B.startsWith("file://")) - return fetch(B, { credentials: "same-origin" }).then(function(t5) { - if (!t5.ok) - throw "failed to load wasm binary file at '" + B + "'"; - return t5.arrayBuffer(); - }).catch(function() { - return Y(); - }); - if (a) - return new Promise(function(t5, e3) { - a(B, function(e4) { - t5(new Uint8Array(e4)); - }, e3); - }); - } - return Promise.resolve().then(function() { - return Y(); - }); - }().then(function(t5) { - return WebAssembly.instantiate(t5, o2); - }).then(function(t5) { - return t5; - }).then(t4, function(t5) { - v("failed to asynchronously prepare wasm: " + t5), W(t5); - }); - } - var o2 = { a: bt }; - if (z++, e2.monitorRunDependencies && e2.monitorRunDependencies(z), e2.instantiateWasm) - try { - return e2.instantiateWasm(o2, t3); - } catch (t4) { - return v("Module.instantiateWasm callback failed with error: " + t4), false; - } - (y || "function" != typeof WebAssembly.instantiateStreaming || q() || B.startsWith("file://") || b || "function" != typeof fetch ? r3(n2) : fetch(B, { credentials: "same-origin" }).then(function(t4) { - return WebAssembly.instantiateStreaming(t4, o2).then(n2, function(t5) { - return v("wasm streaming compile failed: " + t5), v("falling back to ArrayBuffer instantiation"), r3(n2); - }); - })).catch(i); - }(), e2.___wasm_call_ctors = function() { - return (e2.___wasm_call_ctors = e2.asm.La).apply(null, arguments); - }, e2._OrtInit = function() { - return (e2._OrtInit = e2.asm.Ma).apply(null, arguments); - }, e2._OrtCreateSessionOptions = function() { - return (e2._OrtCreateSessionOptions = e2.asm.Na).apply(null, arguments); - }, e2._OrtAppendExecutionProvider = function() { - return (e2._OrtAppendExecutionProvider = e2.asm.Oa).apply(null, arguments); - }, e2._OrtAddSessionConfigEntry = function() { - return (e2._OrtAddSessionConfigEntry = e2.asm.Pa).apply(null, arguments); - }, e2._OrtReleaseSessionOptions = function() { - return (e2._OrtReleaseSessionOptions = e2.asm.Qa).apply(null, arguments); - }, e2._OrtCreateSession = function() { - return (e2._OrtCreateSession = e2.asm.Ra).apply(null, arguments); - }, e2._OrtReleaseSession = function() { - return (e2._OrtReleaseSession = e2.asm.Sa).apply(null, arguments); - }, e2._OrtGetInputCount = function() { - return (e2._OrtGetInputCount = e2.asm.Ta).apply(null, arguments); - }, e2._OrtGetOutputCount = function() { - return (e2._OrtGetOutputCount = e2.asm.Ua).apply(null, arguments); - }, e2._OrtGetInputName = function() { - return (e2._OrtGetInputName = e2.asm.Va).apply(null, arguments); - }, e2._OrtGetOutputName = function() { - return (e2._OrtGetOutputName = e2.asm.Wa).apply(null, arguments); - }, e2._OrtFree = function() { - return (e2._OrtFree = e2.asm.Xa).apply(null, arguments); - }, e2._OrtCreateTensor = function() { - return (e2._OrtCreateTensor = e2.asm.Ya).apply(null, arguments); - }, e2._OrtGetTensorData = function() { - return (e2._OrtGetTensorData = e2.asm.Za).apply(null, arguments); - }, e2._OrtReleaseTensor = function() { - return (e2._OrtReleaseTensor = e2.asm._a).apply(null, arguments); - }, e2._OrtCreateRunOptions = function() { - return (e2._OrtCreateRunOptions = e2.asm.$a).apply(null, arguments); - }, e2._OrtAddRunConfigEntry = function() { - return (e2._OrtAddRunConfigEntry = e2.asm.ab).apply(null, arguments); - }, e2._OrtReleaseRunOptions = function() { - return (e2._OrtReleaseRunOptions = e2.asm.bb).apply(null, arguments); - }, e2._OrtRun = function() { - return (e2._OrtRun = e2.asm.cb).apply(null, arguments); - }, e2._OrtEndProfiling = function() { - return (e2._OrtEndProfiling = e2.asm.db).apply(null, arguments); - }; - var mt, yt = e2._malloc = function() { - return (yt = e2._malloc = e2.asm.eb).apply(null, arguments); - }, _t = e2._free = function() { - return (_t = e2._free = e2.asm.fb).apply(null, arguments); - }, vt = e2._fflush = function() { - return (vt = e2._fflush = e2.asm.gb).apply(null, arguments); - }, wt = e2.___funcs_on_exit = function() { - return (wt = e2.___funcs_on_exit = e2.asm.hb).apply(null, arguments); - }, xt = e2._setThrew = function() { - return (xt = e2._setThrew = e2.asm.jb).apply(null, arguments); - }, Tt = e2.stackSave = function() { - return (Tt = e2.stackSave = e2.asm.kb).apply(null, arguments); - }, St = e2.stackRestore = function() { - return (St = e2.stackRestore = e2.asm.lb).apply(null, arguments); - }, Ot = e2.stackAlloc = function() { - return (Ot = e2.stackAlloc = e2.asm.mb).apply(null, arguments); - }, At = e2.___cxa_can_catch = function() { - return (At = e2.___cxa_can_catch = e2.asm.nb).apply(null, arguments); - }, Et = e2.___cxa_is_pointer_type = function() { - return (Et = e2.___cxa_is_pointer_type = e2.asm.ob).apply(null, arguments); - }, It = e2.dynCall_j = function() { - return (It = e2.dynCall_j = e2.asm.pb).apply(null, arguments); - }, Pt = e2.dynCall_iiiiij = function() { - return (Pt = e2.dynCall_iiiiij = e2.asm.qb).apply(null, arguments); - }, Dt = e2.dynCall_jii = function() { - return (Dt = e2.dynCall_jii = e2.asm.rb).apply(null, arguments); - }, $t = e2.dynCall_viiiiij = function() { - return ($t = e2.dynCall_viiiiij = e2.asm.sb).apply(null, arguments); - }, kt = e2.dynCall_vjji = function() { - return (kt = e2.dynCall_vjji = e2.asm.tb).apply(null, arguments); - }, Ct = e2.dynCall_viiijjjii = function() { - return (Ct = e2.dynCall_viiijjjii = e2.asm.ub).apply(null, arguments); - }, Ft = e2.dynCall_iij = function() { - return (Ft = e2.dynCall_iij = e2.asm.vb).apply(null, arguments); - }, Nt = e2.dynCall_ji = function() { - return (Nt = e2.dynCall_ji = e2.asm.wb).apply(null, arguments); - }, Lt = e2.dynCall_iiiiiij = function() { - return (Lt = e2.dynCall_iiiiiij = e2.asm.xb).apply(null, arguments); - }, Rt = e2.dynCall_iiij = function() { - return (Rt = e2.dynCall_iiij = e2.asm.yb).apply(null, arguments); - }; - function jt() { - function t3() { - if (!mt && (mt = true, e2.calledRun = true, !I)) { - if (Z(R), r2(e2), e2.onRuntimeInitialized && e2.onRuntimeInitialized(), e2.postRun) - for ("function" == typeof e2.postRun && (e2.postRun = [e2.postRun]); e2.postRun.length; ) { - var t4 = e2.postRun.shift(); - M.unshift(t4); - } - Z(M); - } - } - if (!(0 < z)) { - if (e2.preRun) - for ("function" == typeof e2.preRun && (e2.preRun = [e2.preRun]); e2.preRun.length; ) - V(); - Z(L), 0 < z || (e2.setStatus ? (e2.setStatus("Running..."), setTimeout(function() { - setTimeout(function() { - e2.setStatus(""); - }, 1), t3(); - }, 1)) : t3()); - } - } - if (e2.UTF8ToString = $, e2.stringToUTF8 = function(t3, e3, n2) { - return k(t3, O, e3, n2); - }, e2.lengthBytesUTF8 = C, e2.stackSave = Tt, e2.stackRestore = St, e2.stackAlloc = Ot, H = function t3() { - mt || jt(), mt || (H = t3); - }, e2.preInit) - for ("function" == typeof e2.preInit && (e2.preInit = [e2.preInit]); 0 < e2.preInit.length; ) - e2.preInit.pop()(); - return jt(), t2.ready; - }); - t.exports = r; - }, 4537: (t) => { - "use strict"; - t.exports = function(t2, e) { - for (var n = new Array(arguments.length - 1), r = 0, i = 2, o = true; i < arguments.length; ) - n[r++] = arguments[i++]; - return new Promise(function(i2, a) { - n[r] = function(t3) { - if (o) - if (o = false, t3) - a(t3); - else { - for (var e2 = new Array(arguments.length - 1), n2 = 0; n2 < e2.length; ) - e2[n2++] = arguments[n2]; - i2.apply(null, e2); - } - }; - try { - t2.apply(e || null, n); - } catch (t3) { - o && (o = false, a(t3)); - } - }); - }; - }, 7419: (t, e) => { - "use strict"; - var n = e; - n.length = function(t2) { - var e2 = t2.length; - if (!e2) - return 0; - for (var n2 = 0; --e2 % 4 > 1 && "=" === t2.charAt(e2); ) - ++n2; - return Math.ceil(3 * t2.length) / 4 - n2; - }; - for (var r = new Array(64), i = new Array(123), o = 0; o < 64; ) - i[r[o] = o < 26 ? o + 65 : o < 52 ? o + 71 : o < 62 ? o - 4 : o - 59 | 43] = o++; - n.encode = function(t2, e2, n2) { - for (var i2, o2 = null, a2 = [], s = 0, u = 0; e2 < n2; ) { - var c = t2[e2++]; - switch (u) { - case 0: - a2[s++] = r[c >> 2], i2 = (3 & c) << 4, u = 1; - break; - case 1: - a2[s++] = r[i2 | c >> 4], i2 = (15 & c) << 2, u = 2; - break; - case 2: - a2[s++] = r[i2 | c >> 6], a2[s++] = r[63 & c], u = 0; - } - s > 8191 && ((o2 || (o2 = [])).push(String.fromCharCode.apply(String, a2)), s = 0); - } - return u && (a2[s++] = r[i2], a2[s++] = 61, 1 === u && (a2[s++] = 61)), o2 ? (s && o2.push(String.fromCharCode.apply(String, a2.slice(0, s))), o2.join("")) : String.fromCharCode.apply(String, a2.slice(0, s)); - }; - var a = "invalid encoding"; - n.decode = function(t2, e2, n2) { - for (var r2, o2 = n2, s = 0, u = 0; u < t2.length; ) { - var c = t2.charCodeAt(u++); - if (61 === c && s > 1) - break; - if (void 0 === (c = i[c])) - throw Error(a); - switch (s) { - case 0: - r2 = c, s = 1; - break; - case 1: - e2[n2++] = r2 << 2 | (48 & c) >> 4, r2 = c, s = 2; - break; - case 2: - e2[n2++] = (15 & r2) << 4 | (60 & c) >> 2, r2 = c, s = 3; - break; - case 3: - e2[n2++] = (3 & r2) << 6 | c, s = 0; - } - } - if (1 === s) - throw Error(a); - return n2 - o2; - }, n.test = function(t2) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t2); - }; - }, 9211: (t) => { - "use strict"; - function e() { - this._listeners = {}; - } - t.exports = e, e.prototype.on = function(t2, e2, n) { - return (this._listeners[t2] || (this._listeners[t2] = [])).push({ fn: e2, ctx: n || this }), this; - }, e.prototype.off = function(t2, e2) { - if (void 0 === t2) - this._listeners = {}; - else if (void 0 === e2) - this._listeners[t2] = []; - else - for (var n = this._listeners[t2], r = 0; r < n.length; ) - n[r].fn === e2 ? n.splice(r, 1) : ++r; - return this; - }, e.prototype.emit = function(t2) { - var e2 = this._listeners[t2]; - if (e2) { - for (var n = [], r = 1; r < arguments.length; ) - n.push(arguments[r++]); - for (r = 0; r < e2.length; ) - e2[r].fn.apply(e2[r++].ctx, n); - } - return this; - }; - }, 945: (t) => { - "use strict"; - function e(t2) { - return "undefined" != typeof Float32Array ? function() { - var e2 = new Float32Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[3]; - function i2(t3, r3, i3) { - e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3]; - } - function o2(t3, r3, i3) { - e2[0] = t3, r3[i3] = n2[3], r3[i3 + 1] = n2[2], r3[i3 + 2] = n2[1], r3[i3 + 3] = n2[0]; - } - function a(t3, r3) { - return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], e2[0]; - } - function s(t3, r3) { - return n2[3] = t3[r3], n2[2] = t3[r3 + 1], n2[1] = t3[r3 + 2], n2[0] = t3[r3 + 3], e2[0]; - } - t2.writeFloatLE = r2 ? i2 : o2, t2.writeFloatBE = r2 ? o2 : i2, t2.readFloatLE = r2 ? a : s, t2.readFloatBE = r2 ? s : a; - }() : function() { - function e2(t3, e3, n2, r2) { - var i2 = e3 < 0 ? 1 : 0; - if (i2 && (e3 = -e3), 0 === e3) - t3(1 / e3 > 0 ? 0 : 2147483648, n2, r2); - else if (isNaN(e3)) - t3(2143289344, n2, r2); - else if (e3 > 34028234663852886e22) - t3((i2 << 31 | 2139095040) >>> 0, n2, r2); - else if (e3 < 11754943508222875e-54) - t3((i2 << 31 | Math.round(e3 / 1401298464324817e-60)) >>> 0, n2, r2); - else { - var o2 = Math.floor(Math.log(e3) / Math.LN2); - t3((i2 << 31 | o2 + 127 << 23 | 8388607 & Math.round(e3 * Math.pow(2, -o2) * 8388608)) >>> 0, n2, r2); - } - } - function a(t3, e3, n2) { - var r2 = t3(e3, n2), i2 = 2 * (r2 >> 31) + 1, o2 = r2 >>> 23 & 255, a2 = 8388607 & r2; - return 255 === o2 ? a2 ? NaN : i2 * (1 / 0) : 0 === o2 ? 1401298464324817e-60 * i2 * a2 : i2 * Math.pow(2, o2 - 150) * (a2 + 8388608); - } - t2.writeFloatLE = e2.bind(null, n), t2.writeFloatBE = e2.bind(null, r), t2.readFloatLE = a.bind(null, i), t2.readFloatBE = a.bind(null, o); - }(), "undefined" != typeof Float64Array ? function() { - var e2 = new Float64Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[7]; - function i2(t3, r3, i3) { - e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3], r3[i3 + 4] = n2[4], r3[i3 + 5] = n2[5], r3[i3 + 6] = n2[6], r3[i3 + 7] = n2[7]; - } - function o2(t3, r3, i3) { - e2[0] = t3, r3[i3] = n2[7], r3[i3 + 1] = n2[6], r3[i3 + 2] = n2[5], r3[i3 + 3] = n2[4], r3[i3 + 4] = n2[3], r3[i3 + 5] = n2[2], r3[i3 + 6] = n2[1], r3[i3 + 7] = n2[0]; - } - function a(t3, r3) { - return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], n2[4] = t3[r3 + 4], n2[5] = t3[r3 + 5], n2[6] = t3[r3 + 6], n2[7] = t3[r3 + 7], e2[0]; - } - function s(t3, r3) { - return n2[7] = t3[r3], n2[6] = t3[r3 + 1], n2[5] = t3[r3 + 2], n2[4] = t3[r3 + 3], n2[3] = t3[r3 + 4], n2[2] = t3[r3 + 5], n2[1] = t3[r3 + 6], n2[0] = t3[r3 + 7], e2[0]; - } - t2.writeDoubleLE = r2 ? i2 : o2, t2.writeDoubleBE = r2 ? o2 : i2, t2.readDoubleLE = r2 ? a : s, t2.readDoubleBE = r2 ? s : a; - }() : function() { - function e2(t3, e3, n2, r2, i2, o2) { - var a2 = r2 < 0 ? 1 : 0; - if (a2 && (r2 = -r2), 0 === r2) - t3(0, i2, o2 + e3), t3(1 / r2 > 0 ? 0 : 2147483648, i2, o2 + n2); - else if (isNaN(r2)) - t3(0, i2, o2 + e3), t3(2146959360, i2, o2 + n2); - else if (r2 > 17976931348623157e292) - t3(0, i2, o2 + e3), t3((a2 << 31 | 2146435072) >>> 0, i2, o2 + n2); - else { - var s; - if (r2 < 22250738585072014e-324) - t3((s = r2 / 5e-324) >>> 0, i2, o2 + e3), t3((a2 << 31 | s / 4294967296) >>> 0, i2, o2 + n2); - else { - var u = Math.floor(Math.log(r2) / Math.LN2); - 1024 === u && (u = 1023), t3(4503599627370496 * (s = r2 * Math.pow(2, -u)) >>> 0, i2, o2 + e3), t3((a2 << 31 | u + 1023 << 20 | 1048576 * s & 1048575) >>> 0, i2, o2 + n2); - } - } - } - function a(t3, e3, n2, r2, i2) { - var o2 = t3(r2, i2 + e3), a2 = t3(r2, i2 + n2), s = 2 * (a2 >> 31) + 1, u = a2 >>> 20 & 2047, c = 4294967296 * (1048575 & a2) + o2; - return 2047 === u ? c ? NaN : s * (1 / 0) : 0 === u ? 5e-324 * s * c : s * Math.pow(2, u - 1075) * (c + 4503599627370496); - } - t2.writeDoubleLE = e2.bind(null, n, 0, 4), t2.writeDoubleBE = e2.bind(null, r, 4, 0), t2.readDoubleLE = a.bind(null, i, 0, 4), t2.readDoubleBE = a.bind(null, o, 4, 0); - }(), t2; - } - function n(t2, e2, n2) { - e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24; - } - function r(t2, e2, n2) { - e2[n2] = t2 >>> 24, e2[n2 + 1] = t2 >>> 16 & 255, e2[n2 + 2] = t2 >>> 8 & 255, e2[n2 + 3] = 255 & t2; - } - function i(t2, e2) { - return (t2[e2] | t2[e2 + 1] << 8 | t2[e2 + 2] << 16 | t2[e2 + 3] << 24) >>> 0; - } - function o(t2, e2) { - return (t2[e2] << 24 | t2[e2 + 1] << 16 | t2[e2 + 2] << 8 | t2[e2 + 3]) >>> 0; - } - t.exports = e(e); - }, 7199: (module) => { - "use strict"; - function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/, "re"))(moduleName); - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (t) { - } - return null; - } - module.exports = inquire; - }, 6662: (t) => { - "use strict"; - t.exports = function(t2, e, n) { - var r = n || 8192, i = r >>> 1, o = null, a = r; - return function(n2) { - if (n2 < 1 || n2 > i) - return t2(n2); - a + n2 > r && (o = t2(r), a = 0); - var s = e.call(o, a, a += n2); - return 7 & a && (a = 1 + (7 | a)), s; - }; - }; - }, 4997: (t, e) => { - "use strict"; - var n = e; - n.length = function(t2) { - for (var e2 = 0, n2 = 0, r = 0; r < t2.length; ++r) - (n2 = t2.charCodeAt(r)) < 128 ? e2 += 1 : n2 < 2048 ? e2 += 2 : 55296 == (64512 & n2) && 56320 == (64512 & t2.charCodeAt(r + 1)) ? (++r, e2 += 4) : e2 += 3; - return e2; - }, n.read = function(t2, e2, n2) { - if (n2 - e2 < 1) - return ""; - for (var r, i = null, o = [], a = 0; e2 < n2; ) - (r = t2[e2++]) < 128 ? o[a++] = r : r > 191 && r < 224 ? o[a++] = (31 & r) << 6 | 63 & t2[e2++] : r > 239 && r < 365 ? (r = ((7 & r) << 18 | (63 & t2[e2++]) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++]) - 65536, o[a++] = 55296 + (r >> 10), o[a++] = 56320 + (1023 & r)) : o[a++] = (15 & r) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++], a > 8191 && ((i || (i = [])).push(String.fromCharCode.apply(String, o)), a = 0); - return i ? (a && i.push(String.fromCharCode.apply(String, o.slice(0, a))), i.join("")) : String.fromCharCode.apply(String, o.slice(0, a)); - }, n.write = function(t2, e2, n2) { - for (var r, i, o = n2, a = 0; a < t2.length; ++a) - (r = t2.charCodeAt(a)) < 128 ? e2[n2++] = r : r < 2048 ? (e2[n2++] = r >> 6 | 192, e2[n2++] = 63 & r | 128) : 55296 == (64512 & r) && 56320 == (64512 & (i = t2.charCodeAt(a + 1))) ? (r = 65536 + ((1023 & r) << 10) + (1023 & i), ++a, e2[n2++] = r >> 18 | 240, e2[n2++] = r >> 12 & 63 | 128, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128) : (e2[n2++] = r >> 12 | 224, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128); - return n2 - o; - }; - }, 3442: (t, e) => { - "use strict"; - e.__esModule = true; - var n = function() { - function t2(e2) { - if (!e2) - throw new TypeError("Invalid argument; `value` has no value."); - this.value = t2.EMPTY, e2 && t2.isGuid(e2) && (this.value = e2); - } - return t2.isGuid = function(e2) { - var n2 = e2.toString(); - return e2 && (e2 instanceof t2 || t2.validator.test(n2)); - }, t2.create = function() { - return new t2([t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-")); - }, t2.createEmpty = function() { - return new t2("emptyguid"); - }, t2.parse = function(e2) { - return new t2(e2); - }, t2.raw = function() { - return [t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-"); - }, t2.gen = function(t3) { - for (var e2 = "", n2 = 0; n2 < t3; n2++) - e2 += (65536 * (1 + Math.random()) | 0).toString(16).substring(1); - return e2; - }, t2.prototype.equals = function(e2) { - return t2.isGuid(e2) && this.value === e2.toString(); - }, t2.prototype.isEmpty = function() { - return this.value === t2.EMPTY; - }, t2.prototype.toString = function() { - return this.value; - }, t2.prototype.toJSON = function() { - return { value: this.value }; - }, t2.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), t2.EMPTY = "00000000-0000-0000-0000-000000000000", t2; - }(); - e.Guid = n; - }, 3720: (t) => { - t.exports = n; - var e = null; - try { - e = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; - } catch (t2) { - } - function n(t2, e2, n2) { - this.low = 0 | t2, this.high = 0 | e2, this.unsigned = !!n2; - } - function r(t2) { - return true === (t2 && t2.__isLong__); - } - n.prototype.__isLong__, Object.defineProperty(n.prototype, "__isLong__", { value: true }), n.isLong = r; - var i = {}, o = {}; - function a(t2, e2) { - var n2, r2, a2; - return e2 ? (a2 = 0 <= (t2 >>>= 0) && t2 < 256) && (r2 = o[t2]) ? r2 : (n2 = u(t2, (0 | t2) < 0 ? -1 : 0, true), a2 && (o[t2] = n2), n2) : (a2 = -128 <= (t2 |= 0) && t2 < 128) && (r2 = i[t2]) ? r2 : (n2 = u(t2, t2 < 0 ? -1 : 0, false), a2 && (i[t2] = n2), n2); - } - function s(t2, e2) { - if (isNaN(t2)) - return e2 ? m : b; - if (e2) { - if (t2 < 0) - return m; - if (t2 >= d) - return x; - } else { - if (t2 <= -h) - return T; - if (t2 + 1 >= h) - return w; - } - return t2 < 0 ? s(-t2, e2).neg() : u(t2 % f | 0, t2 / f | 0, e2); - } - function u(t2, e2, r2) { - return new n(t2, e2, r2); - } - n.fromInt = a, n.fromNumber = s, n.fromBits = u; - var c = Math.pow; - function l(t2, e2, n2) { - if (0 === t2.length) - throw Error("empty string"); - if ("NaN" === t2 || "Infinity" === t2 || "+Infinity" === t2 || "-Infinity" === t2) - return b; - if ("number" == typeof e2 ? (n2 = e2, e2 = false) : e2 = !!e2, (n2 = n2 || 10) < 2 || 36 < n2) - throw RangeError("radix"); - var r2; - if ((r2 = t2.indexOf("-")) > 0) - throw Error("interior hyphen"); - if (0 === r2) - return l(t2.substring(1), e2, n2).neg(); - for (var i2 = s(c(n2, 8)), o2 = b, a2 = 0; a2 < t2.length; a2 += 8) { - var u2 = Math.min(8, t2.length - a2), p2 = parseInt(t2.substring(a2, a2 + u2), n2); - if (u2 < 8) { - var f2 = s(c(n2, u2)); - o2 = o2.mul(f2).add(s(p2)); - } else - o2 = (o2 = o2.mul(i2)).add(s(p2)); - } - return o2.unsigned = e2, o2; - } - function p(t2, e2) { - return "number" == typeof t2 ? s(t2, e2) : "string" == typeof t2 ? l(t2, e2) : u(t2.low, t2.high, "boolean" == typeof e2 ? e2 : t2.unsigned); - } - n.fromString = l, n.fromValue = p; - var f = 4294967296, d = f * f, h = d / 2, g = a(1 << 24), b = a(0); - n.ZERO = b; - var m = a(0, true); - n.UZERO = m; - var y = a(1); - n.ONE = y; - var _ = a(1, true); - n.UONE = _; - var v = a(-1); - n.NEG_ONE = v; - var w = u(-1, 2147483647, false); - n.MAX_VALUE = w; - var x = u(-1, -1, true); - n.MAX_UNSIGNED_VALUE = x; - var T = u(0, -2147483648, false); - n.MIN_VALUE = T; - var S = n.prototype; - S.toInt = function() { - return this.unsigned ? this.low >>> 0 : this.low; - }, S.toNumber = function() { - return this.unsigned ? (this.high >>> 0) * f + (this.low >>> 0) : this.high * f + (this.low >>> 0); - }, S.toString = function(t2) { - if ((t2 = t2 || 10) < 2 || 36 < t2) - throw RangeError("radix"); - if (this.isZero()) - return "0"; - if (this.isNegative()) { - if (this.eq(T)) { - var e2 = s(t2), n2 = this.div(e2), r2 = n2.mul(e2).sub(this); - return n2.toString(t2) + r2.toInt().toString(t2); - } - return "-" + this.neg().toString(t2); - } - for (var i2 = s(c(t2, 6), this.unsigned), o2 = this, a2 = ""; ; ) { - var u2 = o2.div(i2), l2 = (o2.sub(u2.mul(i2)).toInt() >>> 0).toString(t2); - if ((o2 = u2).isZero()) - return l2 + a2; - for (; l2.length < 6; ) - l2 = "0" + l2; - a2 = "" + l2 + a2; - } - }, S.getHighBits = function() { - return this.high; - }, S.getHighBitsUnsigned = function() { - return this.high >>> 0; - }, S.getLowBits = function() { - return this.low; - }, S.getLowBitsUnsigned = function() { - return this.low >>> 0; - }, S.getNumBitsAbs = function() { - if (this.isNegative()) - return this.eq(T) ? 64 : this.neg().getNumBitsAbs(); - for (var t2 = 0 != this.high ? this.high : this.low, e2 = 31; e2 > 0 && 0 == (t2 & 1 << e2); e2--) - ; - return 0 != this.high ? e2 + 33 : e2 + 1; - }, S.isZero = function() { - return 0 === this.high && 0 === this.low; - }, S.eqz = S.isZero, S.isNegative = function() { - return !this.unsigned && this.high < 0; - }, S.isPositive = function() { - return this.unsigned || this.high >= 0; - }, S.isOdd = function() { - return 1 == (1 & this.low); - }, S.isEven = function() { - return 0 == (1 & this.low); - }, S.equals = function(t2) { - return r(t2) || (t2 = p(t2)), (this.unsigned === t2.unsigned || this.high >>> 31 != 1 || t2.high >>> 31 != 1) && this.high === t2.high && this.low === t2.low; - }, S.eq = S.equals, S.notEquals = function(t2) { - return !this.eq(t2); - }, S.neq = S.notEquals, S.ne = S.notEquals, S.lessThan = function(t2) { - return this.comp(t2) < 0; - }, S.lt = S.lessThan, S.lessThanOrEqual = function(t2) { - return this.comp(t2) <= 0; - }, S.lte = S.lessThanOrEqual, S.le = S.lessThanOrEqual, S.greaterThan = function(t2) { - return this.comp(t2) > 0; - }, S.gt = S.greaterThan, S.greaterThanOrEqual = function(t2) { - return this.comp(t2) >= 0; - }, S.gte = S.greaterThanOrEqual, S.ge = S.greaterThanOrEqual, S.compare = function(t2) { - if (r(t2) || (t2 = p(t2)), this.eq(t2)) - return 0; - var e2 = this.isNegative(), n2 = t2.isNegative(); - return e2 && !n2 ? -1 : !e2 && n2 ? 1 : this.unsigned ? t2.high >>> 0 > this.high >>> 0 || t2.high === this.high && t2.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(t2).isNegative() ? -1 : 1; - }, S.comp = S.compare, S.negate = function() { - return !this.unsigned && this.eq(T) ? T : this.not().add(y); - }, S.neg = S.negate, S.add = function(t2) { - r(t2) || (t2 = p(t2)); - var e2 = this.high >>> 16, n2 = 65535 & this.high, i2 = this.low >>> 16, o2 = 65535 & this.low, a2 = t2.high >>> 16, s2 = 65535 & t2.high, c2 = t2.low >>> 16, l2 = 0, f2 = 0, d2 = 0, h2 = 0; - return d2 += (h2 += o2 + (65535 & t2.low)) >>> 16, f2 += (d2 += i2 + c2) >>> 16, l2 += (f2 += n2 + s2) >>> 16, l2 += e2 + a2, u((d2 &= 65535) << 16 | (h2 &= 65535), (l2 &= 65535) << 16 | (f2 &= 65535), this.unsigned); - }, S.subtract = function(t2) { - return r(t2) || (t2 = p(t2)), this.add(t2.neg()); - }, S.sub = S.subtract, S.multiply = function(t2) { - if (this.isZero()) - return b; - if (r(t2) || (t2 = p(t2)), e) - return u(e.mul(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned); - if (t2.isZero()) - return b; - if (this.eq(T)) - return t2.isOdd() ? T : b; - if (t2.eq(T)) - return this.isOdd() ? T : b; - if (this.isNegative()) - return t2.isNegative() ? this.neg().mul(t2.neg()) : this.neg().mul(t2).neg(); - if (t2.isNegative()) - return this.mul(t2.neg()).neg(); - if (this.lt(g) && t2.lt(g)) - return s(this.toNumber() * t2.toNumber(), this.unsigned); - var n2 = this.high >>> 16, i2 = 65535 & this.high, o2 = this.low >>> 16, a2 = 65535 & this.low, c2 = t2.high >>> 16, l2 = 65535 & t2.high, f2 = t2.low >>> 16, d2 = 65535 & t2.low, h2 = 0, m2 = 0, y2 = 0, _2 = 0; - return y2 += (_2 += a2 * d2) >>> 16, m2 += (y2 += o2 * d2) >>> 16, y2 &= 65535, m2 += (y2 += a2 * f2) >>> 16, h2 += (m2 += i2 * d2) >>> 16, m2 &= 65535, h2 += (m2 += o2 * f2) >>> 16, m2 &= 65535, h2 += (m2 += a2 * l2) >>> 16, h2 += n2 * d2 + i2 * f2 + o2 * l2 + a2 * c2, u((y2 &= 65535) << 16 | (_2 &= 65535), (h2 &= 65535) << 16 | (m2 &= 65535), this.unsigned); - }, S.mul = S.multiply, S.divide = function(t2) { - if (r(t2) || (t2 = p(t2)), t2.isZero()) - throw Error("division by zero"); - var n2, i2, o2; - if (e) - return this.unsigned || -2147483648 !== this.high || -1 !== t2.low || -1 !== t2.high ? u((this.unsigned ? e.div_u : e.div_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this; - if (this.isZero()) - return this.unsigned ? m : b; - if (this.unsigned) { - if (t2.unsigned || (t2 = t2.toUnsigned()), t2.gt(this)) - return m; - if (t2.gt(this.shru(1))) - return _; - o2 = m; - } else { - if (this.eq(T)) - return t2.eq(y) || t2.eq(v) ? T : t2.eq(T) ? y : (n2 = this.shr(1).div(t2).shl(1)).eq(b) ? t2.isNegative() ? y : v : (i2 = this.sub(t2.mul(n2)), o2 = n2.add(i2.div(t2))); - if (t2.eq(T)) - return this.unsigned ? m : b; - if (this.isNegative()) - return t2.isNegative() ? this.neg().div(t2.neg()) : this.neg().div(t2).neg(); - if (t2.isNegative()) - return this.div(t2.neg()).neg(); - o2 = b; - } - for (i2 = this; i2.gte(t2); ) { - n2 = Math.max(1, Math.floor(i2.toNumber() / t2.toNumber())); - for (var a2 = Math.ceil(Math.log(n2) / Math.LN2), l2 = a2 <= 48 ? 1 : c(2, a2 - 48), f2 = s(n2), d2 = f2.mul(t2); d2.isNegative() || d2.gt(i2); ) - d2 = (f2 = s(n2 -= l2, this.unsigned)).mul(t2); - f2.isZero() && (f2 = y), o2 = o2.add(f2), i2 = i2.sub(d2); - } - return o2; - }, S.div = S.divide, S.modulo = function(t2) { - return r(t2) || (t2 = p(t2)), e ? u((this.unsigned ? e.rem_u : e.rem_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this.sub(this.div(t2).mul(t2)); - }, S.mod = S.modulo, S.rem = S.modulo, S.not = function() { - return u(~this.low, ~this.high, this.unsigned); - }, S.and = function(t2) { - return r(t2) || (t2 = p(t2)), u(this.low & t2.low, this.high & t2.high, this.unsigned); - }, S.or = function(t2) { - return r(t2) || (t2 = p(t2)), u(this.low | t2.low, this.high | t2.high, this.unsigned); - }, S.xor = function(t2) { - return r(t2) || (t2 = p(t2)), u(this.low ^ t2.low, this.high ^ t2.high, this.unsigned); - }, S.shiftLeft = function(t2) { - return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low << t2, this.high << t2 | this.low >>> 32 - t2, this.unsigned) : u(0, this.low << t2 - 32, this.unsigned); - }, S.shl = S.shiftLeft, S.shiftRight = function(t2) { - return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low >>> t2 | this.high << 32 - t2, this.high >> t2, this.unsigned) : u(this.high >> t2 - 32, this.high >= 0 ? 0 : -1, this.unsigned); - }, S.shr = S.shiftRight, S.shiftRightUnsigned = function(t2) { - if (r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63)) - return this; - var e2 = this.high; - return t2 < 32 ? u(this.low >>> t2 | e2 << 32 - t2, e2 >>> t2, this.unsigned) : u(32 === t2 ? e2 : e2 >>> t2 - 32, 0, this.unsigned); - }, S.shru = S.shiftRightUnsigned, S.shr_u = S.shiftRightUnsigned, S.toSigned = function() { - return this.unsigned ? u(this.low, this.high, false) : this; - }, S.toUnsigned = function() { - return this.unsigned ? this : u(this.low, this.high, true); - }, S.toBytes = function(t2) { - return t2 ? this.toBytesLE() : this.toBytesBE(); - }, S.toBytesLE = function() { - var t2 = this.high, e2 = this.low; - return [255 & e2, e2 >>> 8 & 255, e2 >>> 16 & 255, e2 >>> 24, 255 & t2, t2 >>> 8 & 255, t2 >>> 16 & 255, t2 >>> 24]; - }, S.toBytesBE = function() { - var t2 = this.high, e2 = this.low; - return [t2 >>> 24, t2 >>> 16 & 255, t2 >>> 8 & 255, 255 & t2, e2 >>> 24, e2 >>> 16 & 255, e2 >>> 8 & 255, 255 & e2]; - }, n.fromBytes = function(t2, e2, r2) { - return r2 ? n.fromBytesLE(t2, e2) : n.fromBytesBE(t2, e2); - }, n.fromBytesLE = function(t2, e2) { - return new n(t2[0] | t2[1] << 8 | t2[2] << 16 | t2[3] << 24, t2[4] | t2[5] << 8 | t2[6] << 16 | t2[7] << 24, e2); - }, n.fromBytesBE = function(t2, e2) { - return new n(t2[4] << 24 | t2[5] << 16 | t2[6] << 8 | t2[7], t2[0] << 24 | t2[1] << 16 | t2[2] << 8 | t2[3], e2); - }; - }, 1446: (t, e, n) => { - "use strict"; - var r, i, o, a = n(2100), s = a.Reader, u = a.Writer, c = a.util, l = a.roots.default || (a.roots.default = {}); - l.onnx = ((o = {}).Version = (r = {}, (i = Object.create(r))[r[0] = "_START_VERSION"] = 0, i[r[1] = "IR_VERSION_2017_10_10"] = 1, i[r[2] = "IR_VERSION_2017_10_30"] = 2, i[r[3] = "IR_VERSION_2017_11_3"] = 3, i[r[4] = "IR_VERSION_2019_1_22"] = 4, i[r[5] = "IR_VERSION"] = 5, i), o.AttributeProto = function() { - function t2(t3) { - if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.name = "", t2.prototype.refAttrName = "", t2.prototype.docString = "", t2.prototype.type = 0, t2.prototype.f = 0, t2.prototype.i = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.s = c.newBuffer([]), t2.prototype.t = null, t2.prototype.g = null, t2.prototype.floats = c.emptyArray, t2.prototype.ints = c.emptyArray, t2.prototype.strings = c.emptyArray, t2.prototype.tensors = c.emptyArray, t2.prototype.graphs = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.f && t3.hasOwnProperty("f") && e2.uint32(21).float(t3.f), null != t3.i && t3.hasOwnProperty("i") && e2.uint32(24).int64(t3.i), null != t3.s && t3.hasOwnProperty("s") && e2.uint32(34).bytes(t3.s), null != t3.t && t3.hasOwnProperty("t") && l.onnx.TensorProto.encode(t3.t, e2.uint32(42).fork()).ldelim(), null != t3.g && t3.hasOwnProperty("g") && l.onnx.GraphProto.encode(t3.g, e2.uint32(50).fork()).ldelim(), null != t3.floats && t3.floats.length) { - e2.uint32(58).fork(); - for (var n2 = 0; n2 < t3.floats.length; ++n2) - e2.float(t3.floats[n2]); - e2.ldelim(); - } - if (null != t3.ints && t3.ints.length) { - for (e2.uint32(66).fork(), n2 = 0; n2 < t3.ints.length; ++n2) - e2.int64(t3.ints[n2]); - e2.ldelim(); - } - if (null != t3.strings && t3.strings.length) - for (n2 = 0; n2 < t3.strings.length; ++n2) - e2.uint32(74).bytes(t3.strings[n2]); - if (null != t3.tensors && t3.tensors.length) - for (n2 = 0; n2 < t3.tensors.length; ++n2) - l.onnx.TensorProto.encode(t3.tensors[n2], e2.uint32(82).fork()).ldelim(); - if (null != t3.graphs && t3.graphs.length) - for (n2 = 0; n2 < t3.graphs.length; ++n2) - l.onnx.GraphProto.encode(t3.graphs[n2], e2.uint32(90).fork()).ldelim(); - return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(106).string(t3.docString), null != t3.type && t3.hasOwnProperty("type") && e2.uint32(160).int32(t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && e2.uint32(170).string(t3.refAttrName), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.AttributeProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.name = t3.string(); - break; - case 21: - r2.refAttrName = t3.string(); - break; - case 13: - r2.docString = t3.string(); - break; - case 20: - r2.type = t3.int32(); - break; - case 2: - r2.f = t3.float(); - break; - case 3: - r2.i = t3.int64(); - break; - case 4: - r2.s = t3.bytes(); - break; - case 5: - r2.t = l.onnx.TensorProto.decode(t3, t3.uint32()); - break; - case 6: - r2.g = l.onnx.GraphProto.decode(t3, t3.uint32()); - break; - case 7: - if (r2.floats && r2.floats.length || (r2.floats = []), 2 == (7 & i2)) - for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.floats.push(t3.float()); - else - r2.floats.push(t3.float()); - break; - case 8: - if (r2.ints && r2.ints.length || (r2.ints = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.ints.push(t3.int64()); - else - r2.ints.push(t3.int64()); - break; - case 9: - r2.strings && r2.strings.length || (r2.strings = []), r2.strings.push(t3.bytes()); - break; - case 10: - r2.tensors && r2.tensors.length || (r2.tensors = []), r2.tensors.push(l.onnx.TensorProto.decode(t3, t3.uint32())); - break; - case 11: - r2.graphs && r2.graphs.length || (r2.graphs = []), r2.graphs.push(l.onnx.GraphProto.decode(t3, t3.uint32())); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) - return "name: string expected"; - if (null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && !c.isString(t3.refAttrName)) - return "refAttrName: string expected"; - if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) - return "docString: string expected"; - if (null != t3.type && t3.hasOwnProperty("type")) - switch (t3.type) { - default: - return "type: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - } - if (null != t3.f && t3.hasOwnProperty("f") && "number" != typeof t3.f) - return "f: number expected"; - if (null != t3.i && t3.hasOwnProperty("i") && !(c.isInteger(t3.i) || t3.i && c.isInteger(t3.i.low) && c.isInteger(t3.i.high))) - return "i: integer|Long expected"; - if (null != t3.s && t3.hasOwnProperty("s") && !(t3.s && "number" == typeof t3.s.length || c.isString(t3.s))) - return "s: buffer expected"; - if (null != t3.t && t3.hasOwnProperty("t") && (n2 = l.onnx.TensorProto.verify(t3.t))) - return "t." + n2; - if (null != t3.g && t3.hasOwnProperty("g") && (n2 = l.onnx.GraphProto.verify(t3.g))) - return "g." + n2; - if (null != t3.floats && t3.hasOwnProperty("floats")) { - if (!Array.isArray(t3.floats)) - return "floats: array expected"; - for (var e2 = 0; e2 < t3.floats.length; ++e2) - if ("number" != typeof t3.floats[e2]) - return "floats: number[] expected"; - } - if (null != t3.ints && t3.hasOwnProperty("ints")) { - if (!Array.isArray(t3.ints)) - return "ints: array expected"; - for (e2 = 0; e2 < t3.ints.length; ++e2) - if (!(c.isInteger(t3.ints[e2]) || t3.ints[e2] && c.isInteger(t3.ints[e2].low) && c.isInteger(t3.ints[e2].high))) - return "ints: integer|Long[] expected"; - } - if (null != t3.strings && t3.hasOwnProperty("strings")) { - if (!Array.isArray(t3.strings)) - return "strings: array expected"; - for (e2 = 0; e2 < t3.strings.length; ++e2) - if (!(t3.strings[e2] && "number" == typeof t3.strings[e2].length || c.isString(t3.strings[e2]))) - return "strings: buffer[] expected"; - } - if (null != t3.tensors && t3.hasOwnProperty("tensors")) { - if (!Array.isArray(t3.tensors)) - return "tensors: array expected"; - for (e2 = 0; e2 < t3.tensors.length; ++e2) - if (n2 = l.onnx.TensorProto.verify(t3.tensors[e2])) - return "tensors." + n2; - } - if (null != t3.graphs && t3.hasOwnProperty("graphs")) { - if (!Array.isArray(t3.graphs)) - return "graphs: array expected"; - for (e2 = 0; e2 < t3.graphs.length; ++e2) { - var n2; - if (n2 = l.onnx.GraphProto.verify(t3.graphs[e2])) - return "graphs." + n2; - } - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.AttributeProto) - return t3; - var e2 = new l.onnx.AttributeProto(); - switch (null != t3.name && (e2.name = String(t3.name)), null != t3.refAttrName && (e2.refAttrName = String(t3.refAttrName)), null != t3.docString && (e2.docString = String(t3.docString)), t3.type) { - case "UNDEFINED": - case 0: - e2.type = 0; - break; - case "FLOAT": - case 1: - e2.type = 1; - break; - case "INT": - case 2: - e2.type = 2; - break; - case "STRING": - case 3: - e2.type = 3; - break; - case "TENSOR": - case 4: - e2.type = 4; - break; - case "GRAPH": - case 5: - e2.type = 5; - break; - case "FLOATS": - case 6: - e2.type = 6; - break; - case "INTS": - case 7: - e2.type = 7; - break; - case "STRINGS": - case 8: - e2.type = 8; - break; - case "TENSORS": - case 9: - e2.type = 9; - break; - case "GRAPHS": - case 10: - e2.type = 10; - } - if (null != t3.f && (e2.f = Number(t3.f)), null != t3.i && (c.Long ? (e2.i = c.Long.fromValue(t3.i)).unsigned = false : "string" == typeof t3.i ? e2.i = parseInt(t3.i, 10) : "number" == typeof t3.i ? e2.i = t3.i : "object" == typeof t3.i && (e2.i = new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber())), null != t3.s && ("string" == typeof t3.s ? c.base64.decode(t3.s, e2.s = c.newBuffer(c.base64.length(t3.s)), 0) : t3.s.length && (e2.s = t3.s)), null != t3.t) { - if ("object" != typeof t3.t) - throw TypeError(".onnx.AttributeProto.t: object expected"); - e2.t = l.onnx.TensorProto.fromObject(t3.t); - } - if (null != t3.g) { - if ("object" != typeof t3.g) - throw TypeError(".onnx.AttributeProto.g: object expected"); - e2.g = l.onnx.GraphProto.fromObject(t3.g); - } - if (t3.floats) { - if (!Array.isArray(t3.floats)) - throw TypeError(".onnx.AttributeProto.floats: array expected"); - e2.floats = []; - for (var n2 = 0; n2 < t3.floats.length; ++n2) - e2.floats[n2] = Number(t3.floats[n2]); - } - if (t3.ints) { - if (!Array.isArray(t3.ints)) - throw TypeError(".onnx.AttributeProto.ints: array expected"); - for (e2.ints = [], n2 = 0; n2 < t3.ints.length; ++n2) - c.Long ? (e2.ints[n2] = c.Long.fromValue(t3.ints[n2])).unsigned = false : "string" == typeof t3.ints[n2] ? e2.ints[n2] = parseInt(t3.ints[n2], 10) : "number" == typeof t3.ints[n2] ? e2.ints[n2] = t3.ints[n2] : "object" == typeof t3.ints[n2] && (e2.ints[n2] = new c.LongBits(t3.ints[n2].low >>> 0, t3.ints[n2].high >>> 0).toNumber()); - } - if (t3.strings) { - if (!Array.isArray(t3.strings)) - throw TypeError(".onnx.AttributeProto.strings: array expected"); - for (e2.strings = [], n2 = 0; n2 < t3.strings.length; ++n2) - "string" == typeof t3.strings[n2] ? c.base64.decode(t3.strings[n2], e2.strings[n2] = c.newBuffer(c.base64.length(t3.strings[n2])), 0) : t3.strings[n2].length && (e2.strings[n2] = t3.strings[n2]); - } - if (t3.tensors) { - if (!Array.isArray(t3.tensors)) - throw TypeError(".onnx.AttributeProto.tensors: array expected"); - for (e2.tensors = [], n2 = 0; n2 < t3.tensors.length; ++n2) { - if ("object" != typeof t3.tensors[n2]) - throw TypeError(".onnx.AttributeProto.tensors: object expected"); - e2.tensors[n2] = l.onnx.TensorProto.fromObject(t3.tensors[n2]); - } - } - if (t3.graphs) { - if (!Array.isArray(t3.graphs)) - throw TypeError(".onnx.AttributeProto.graphs: array expected"); - for (e2.graphs = [], n2 = 0; n2 < t3.graphs.length; ++n2) { - if ("object" != typeof t3.graphs[n2]) - throw TypeError(".onnx.AttributeProto.graphs: object expected"); - e2.graphs[n2] = l.onnx.GraphProto.fromObject(t3.graphs[n2]); - } - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.floats = [], n2.ints = [], n2.strings = [], n2.tensors = [], n2.graphs = []), e2.defaults) { - if (n2.name = "", n2.f = 0, c.Long) { - var r2 = new c.Long(0, 0, false); - n2.i = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; - } else - n2.i = e2.longs === String ? "0" : 0; - e2.bytes === String ? n2.s = "" : (n2.s = [], e2.bytes !== Array && (n2.s = c.newBuffer(n2.s))), n2.t = null, n2.g = null, n2.docString = "", n2.type = e2.enums === String ? "UNDEFINED" : 0, n2.refAttrName = ""; - } - if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.f && t3.hasOwnProperty("f") && (n2.f = e2.json && !isFinite(t3.f) ? String(t3.f) : t3.f), null != t3.i && t3.hasOwnProperty("i") && ("number" == typeof t3.i ? n2.i = e2.longs === String ? String(t3.i) : t3.i : n2.i = e2.longs === String ? c.Long.prototype.toString.call(t3.i) : e2.longs === Number ? new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber() : t3.i), null != t3.s && t3.hasOwnProperty("s") && (n2.s = e2.bytes === String ? c.base64.encode(t3.s, 0, t3.s.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.s) : t3.s), null != t3.t && t3.hasOwnProperty("t") && (n2.t = l.onnx.TensorProto.toObject(t3.t, e2)), null != t3.g && t3.hasOwnProperty("g") && (n2.g = l.onnx.GraphProto.toObject(t3.g, e2)), t3.floats && t3.floats.length) { - n2.floats = []; - for (var i2 = 0; i2 < t3.floats.length; ++i2) - n2.floats[i2] = e2.json && !isFinite(t3.floats[i2]) ? String(t3.floats[i2]) : t3.floats[i2]; - } - if (t3.ints && t3.ints.length) - for (n2.ints = [], i2 = 0; i2 < t3.ints.length; ++i2) - "number" == typeof t3.ints[i2] ? n2.ints[i2] = e2.longs === String ? String(t3.ints[i2]) : t3.ints[i2] : n2.ints[i2] = e2.longs === String ? c.Long.prototype.toString.call(t3.ints[i2]) : e2.longs === Number ? new c.LongBits(t3.ints[i2].low >>> 0, t3.ints[i2].high >>> 0).toNumber() : t3.ints[i2]; - if (t3.strings && t3.strings.length) - for (n2.strings = [], i2 = 0; i2 < t3.strings.length; ++i2) - n2.strings[i2] = e2.bytes === String ? c.base64.encode(t3.strings[i2], 0, t3.strings[i2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.strings[i2]) : t3.strings[i2]; - if (t3.tensors && t3.tensors.length) - for (n2.tensors = [], i2 = 0; i2 < t3.tensors.length; ++i2) - n2.tensors[i2] = l.onnx.TensorProto.toObject(t3.tensors[i2], e2); - if (t3.graphs && t3.graphs.length) - for (n2.graphs = [], i2 = 0; i2 < t3.graphs.length; ++i2) - n2.graphs[i2] = l.onnx.GraphProto.toObject(t3.graphs[i2], e2); - return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.type && t3.hasOwnProperty("type") && (n2.type = e2.enums === String ? l.onnx.AttributeProto.AttributeType[t3.type] : t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && (n2.refAttrName = t3.refAttrName), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2.AttributeType = function() { - var t3 = {}, e2 = Object.create(t3); - return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "INT"] = 2, e2[t3[3] = "STRING"] = 3, e2[t3[4] = "TENSOR"] = 4, e2[t3[5] = "GRAPH"] = 5, e2[t3[6] = "FLOATS"] = 6, e2[t3[7] = "INTS"] = 7, e2[t3[8] = "STRINGS"] = 8, e2[t3[9] = "TENSORS"] = 9, e2[t3[10] = "GRAPHS"] = 10, e2; - }(), t2; - }(), o.ValueInfoProto = function() { - function t2(t3) { - if (t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.name = "", t2.prototype.type = null, t2.prototype.docString = "", t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - return e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.type && t3.hasOwnProperty("type") && l.onnx.TypeProto.encode(t3.type, e2.uint32(18).fork()).ldelim(), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(26).string(t3.docString), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ValueInfoProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.name = t3.string(); - break; - case 2: - r2.type = l.onnx.TypeProto.decode(t3, t3.uint32()); - break; - case 3: - r2.docString = t3.string(); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) - return "name: string expected"; - if (null != t3.type && t3.hasOwnProperty("type")) { - var e2 = l.onnx.TypeProto.verify(t3.type); - if (e2) - return "type." + e2; - } - return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.ValueInfoProto) - return t3; - var e2 = new l.onnx.ValueInfoProto(); - if (null != t3.name && (e2.name = String(t3.name)), null != t3.type) { - if ("object" != typeof t3.type) - throw TypeError(".onnx.ValueInfoProto.type: object expected"); - e2.type = l.onnx.TypeProto.fromObject(t3.type); - } - return null != t3.docString && (e2.docString = String(t3.docString)), e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - return e2.defaults && (n2.name = "", n2.type = null, n2.docString = ""), null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.type && t3.hasOwnProperty("type") && (n2.type = l.onnx.TypeProto.toObject(t3.type, e2)), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.NodeProto = function() { - function t2(t3) { - if (this.input = [], this.output = [], this.attribute = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.name = "", t2.prototype.opType = "", t2.prototype.domain = "", t2.prototype.attribute = c.emptyArray, t2.prototype.docString = "", t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.input && t3.input.length) - for (var n2 = 0; n2 < t3.input.length; ++n2) - e2.uint32(10).string(t3.input[n2]); - if (null != t3.output && t3.output.length) - for (n2 = 0; n2 < t3.output.length; ++n2) - e2.uint32(18).string(t3.output[n2]); - if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(26).string(t3.name), null != t3.opType && t3.hasOwnProperty("opType") && e2.uint32(34).string(t3.opType), null != t3.attribute && t3.attribute.length) - for (n2 = 0; n2 < t3.attribute.length; ++n2) - l.onnx.AttributeProto.encode(t3.attribute[n2], e2.uint32(42).fork()).ldelim(); - return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(58).string(t3.domain), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.NodeProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.input && r2.input.length || (r2.input = []), r2.input.push(t3.string()); - break; - case 2: - r2.output && r2.output.length || (r2.output = []), r2.output.push(t3.string()); - break; - case 3: - r2.name = t3.string(); - break; - case 4: - r2.opType = t3.string(); - break; - case 7: - r2.domain = t3.string(); - break; - case 5: - r2.attribute && r2.attribute.length || (r2.attribute = []), r2.attribute.push(l.onnx.AttributeProto.decode(t3, t3.uint32())); - break; - case 6: - r2.docString = t3.string(); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.input && t3.hasOwnProperty("input")) { - if (!Array.isArray(t3.input)) - return "input: array expected"; - for (var e2 = 0; e2 < t3.input.length; ++e2) - if (!c.isString(t3.input[e2])) - return "input: string[] expected"; - } - if (null != t3.output && t3.hasOwnProperty("output")) { - if (!Array.isArray(t3.output)) - return "output: array expected"; - for (e2 = 0; e2 < t3.output.length; ++e2) - if (!c.isString(t3.output[e2])) - return "output: string[] expected"; - } - if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) - return "name: string expected"; - if (null != t3.opType && t3.hasOwnProperty("opType") && !c.isString(t3.opType)) - return "opType: string expected"; - if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) - return "domain: string expected"; - if (null != t3.attribute && t3.hasOwnProperty("attribute")) { - if (!Array.isArray(t3.attribute)) - return "attribute: array expected"; - for (e2 = 0; e2 < t3.attribute.length; ++e2) { - var n2 = l.onnx.AttributeProto.verify(t3.attribute[e2]); - if (n2) - return "attribute." + n2; - } - } - return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.NodeProto) - return t3; - var e2 = new l.onnx.NodeProto(); - if (t3.input) { - if (!Array.isArray(t3.input)) - throw TypeError(".onnx.NodeProto.input: array expected"); - e2.input = []; - for (var n2 = 0; n2 < t3.input.length; ++n2) - e2.input[n2] = String(t3.input[n2]); - } - if (t3.output) { - if (!Array.isArray(t3.output)) - throw TypeError(".onnx.NodeProto.output: array expected"); - for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) - e2.output[n2] = String(t3.output[n2]); - } - if (null != t3.name && (e2.name = String(t3.name)), null != t3.opType && (e2.opType = String(t3.opType)), null != t3.domain && (e2.domain = String(t3.domain)), t3.attribute) { - if (!Array.isArray(t3.attribute)) - throw TypeError(".onnx.NodeProto.attribute: array expected"); - for (e2.attribute = [], n2 = 0; n2 < t3.attribute.length; ++n2) { - if ("object" != typeof t3.attribute[n2]) - throw TypeError(".onnx.NodeProto.attribute: object expected"); - e2.attribute[n2] = l.onnx.AttributeProto.fromObject(t3.attribute[n2]); - } - } - return null != t3.docString && (e2.docString = String(t3.docString)), e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.input = [], n2.output = [], n2.attribute = []), e2.defaults && (n2.name = "", n2.opType = "", n2.docString = "", n2.domain = ""), t3.input && t3.input.length) { - n2.input = []; - for (var r2 = 0; r2 < t3.input.length; ++r2) - n2.input[r2] = t3.input[r2]; - } - if (t3.output && t3.output.length) - for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) - n2.output[r2] = t3.output[r2]; - if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.opType && t3.hasOwnProperty("opType") && (n2.opType = t3.opType), t3.attribute && t3.attribute.length) - for (n2.attribute = [], r2 = 0; r2 < t3.attribute.length; ++r2) - n2.attribute[r2] = l.onnx.AttributeProto.toObject(t3.attribute[r2], e2); - return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.ModelProto = function() { - function t2(t3) { - if (this.opsetImport = [], this.metadataProps = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.irVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.opsetImport = c.emptyArray, t2.prototype.producerName = "", t2.prototype.producerVersion = "", t2.prototype.domain = "", t2.prototype.modelVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.docString = "", t2.prototype.graph = null, t2.prototype.metadataProps = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.irVersion && t3.hasOwnProperty("irVersion") && e2.uint32(8).int64(t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && e2.uint32(18).string(t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && e2.uint32(26).string(t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(34).string(t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && e2.uint32(40).int64(t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && l.onnx.GraphProto.encode(t3.graph, e2.uint32(58).fork()).ldelim(), null != t3.opsetImport && t3.opsetImport.length) - for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) - l.onnx.OperatorSetIdProto.encode(t3.opsetImport[n2], e2.uint32(66).fork()).ldelim(); - if (null != t3.metadataProps && t3.metadataProps.length) - for (n2 = 0; n2 < t3.metadataProps.length; ++n2) - l.onnx.StringStringEntryProto.encode(t3.metadataProps[n2], e2.uint32(114).fork()).ldelim(); - return e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ModelProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.irVersion = t3.int64(); - break; - case 8: - r2.opsetImport && r2.opsetImport.length || (r2.opsetImport = []), r2.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t3, t3.uint32())); - break; - case 2: - r2.producerName = t3.string(); - break; - case 3: - r2.producerVersion = t3.string(); - break; - case 4: - r2.domain = t3.string(); - break; - case 5: - r2.modelVersion = t3.int64(); - break; - case 6: - r2.docString = t3.string(); - break; - case 7: - r2.graph = l.onnx.GraphProto.decode(t3, t3.uint32()); - break; - case 14: - r2.metadataProps && r2.metadataProps.length || (r2.metadataProps = []), r2.metadataProps.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && !(c.isInteger(t3.irVersion) || t3.irVersion && c.isInteger(t3.irVersion.low) && c.isInteger(t3.irVersion.high))) - return "irVersion: integer|Long expected"; - if (null != t3.opsetImport && t3.hasOwnProperty("opsetImport")) { - if (!Array.isArray(t3.opsetImport)) - return "opsetImport: array expected"; - for (var e2 = 0; e2 < t3.opsetImport.length; ++e2) - if (n2 = l.onnx.OperatorSetIdProto.verify(t3.opsetImport[e2])) - return "opsetImport." + n2; - } - if (null != t3.producerName && t3.hasOwnProperty("producerName") && !c.isString(t3.producerName)) - return "producerName: string expected"; - if (null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && !c.isString(t3.producerVersion)) - return "producerVersion: string expected"; - if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) - return "domain: string expected"; - if (null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && !(c.isInteger(t3.modelVersion) || t3.modelVersion && c.isInteger(t3.modelVersion.low) && c.isInteger(t3.modelVersion.high))) - return "modelVersion: integer|Long expected"; - if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) - return "docString: string expected"; - if (null != t3.graph && t3.hasOwnProperty("graph") && (n2 = l.onnx.GraphProto.verify(t3.graph))) - return "graph." + n2; - if (null != t3.metadataProps && t3.hasOwnProperty("metadataProps")) { - if (!Array.isArray(t3.metadataProps)) - return "metadataProps: array expected"; - for (e2 = 0; e2 < t3.metadataProps.length; ++e2) { - var n2; - if (n2 = l.onnx.StringStringEntryProto.verify(t3.metadataProps[e2])) - return "metadataProps." + n2; - } - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.ModelProto) - return t3; - var e2 = new l.onnx.ModelProto(); - if (null != t3.irVersion && (c.Long ? (e2.irVersion = c.Long.fromValue(t3.irVersion)).unsigned = false : "string" == typeof t3.irVersion ? e2.irVersion = parseInt(t3.irVersion, 10) : "number" == typeof t3.irVersion ? e2.irVersion = t3.irVersion : "object" == typeof t3.irVersion && (e2.irVersion = new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber())), t3.opsetImport) { - if (!Array.isArray(t3.opsetImport)) - throw TypeError(".onnx.ModelProto.opsetImport: array expected"); - e2.opsetImport = []; - for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) { - if ("object" != typeof t3.opsetImport[n2]) - throw TypeError(".onnx.ModelProto.opsetImport: object expected"); - e2.opsetImport[n2] = l.onnx.OperatorSetIdProto.fromObject(t3.opsetImport[n2]); - } - } - if (null != t3.producerName && (e2.producerName = String(t3.producerName)), null != t3.producerVersion && (e2.producerVersion = String(t3.producerVersion)), null != t3.domain && (e2.domain = String(t3.domain)), null != t3.modelVersion && (c.Long ? (e2.modelVersion = c.Long.fromValue(t3.modelVersion)).unsigned = false : "string" == typeof t3.modelVersion ? e2.modelVersion = parseInt(t3.modelVersion, 10) : "number" == typeof t3.modelVersion ? e2.modelVersion = t3.modelVersion : "object" == typeof t3.modelVersion && (e2.modelVersion = new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber())), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.graph) { - if ("object" != typeof t3.graph) - throw TypeError(".onnx.ModelProto.graph: object expected"); - e2.graph = l.onnx.GraphProto.fromObject(t3.graph); - } - if (t3.metadataProps) { - if (!Array.isArray(t3.metadataProps)) - throw TypeError(".onnx.ModelProto.metadataProps: array expected"); - for (e2.metadataProps = [], n2 = 0; n2 < t3.metadataProps.length; ++n2) { - if ("object" != typeof t3.metadataProps[n2]) - throw TypeError(".onnx.ModelProto.metadataProps: object expected"); - e2.metadataProps[n2] = l.onnx.StringStringEntryProto.fromObject(t3.metadataProps[n2]); - } - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.opsetImport = [], n2.metadataProps = []), e2.defaults) { - if (c.Long) { - var r2 = new c.Long(0, 0, false); - n2.irVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; - } else - n2.irVersion = e2.longs === String ? "0" : 0; - n2.producerName = "", n2.producerVersion = "", n2.domain = "", c.Long ? (r2 = new c.Long(0, 0, false), n2.modelVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.modelVersion = e2.longs === String ? "0" : 0, n2.docString = "", n2.graph = null; - } - if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && ("number" == typeof t3.irVersion ? n2.irVersion = e2.longs === String ? String(t3.irVersion) : t3.irVersion : n2.irVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.irVersion) : e2.longs === Number ? new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber() : t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && (n2.producerName = t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && (n2.producerVersion = t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && ("number" == typeof t3.modelVersion ? n2.modelVersion = e2.longs === String ? String(t3.modelVersion) : t3.modelVersion : n2.modelVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.modelVersion) : e2.longs === Number ? new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber() : t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && (n2.graph = l.onnx.GraphProto.toObject(t3.graph, e2)), t3.opsetImport && t3.opsetImport.length) { - n2.opsetImport = []; - for (var i2 = 0; i2 < t3.opsetImport.length; ++i2) - n2.opsetImport[i2] = l.onnx.OperatorSetIdProto.toObject(t3.opsetImport[i2], e2); - } - if (t3.metadataProps && t3.metadataProps.length) - for (n2.metadataProps = [], i2 = 0; i2 < t3.metadataProps.length; ++i2) - n2.metadataProps[i2] = l.onnx.StringStringEntryProto.toObject(t3.metadataProps[i2], e2); - return n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.StringStringEntryProto = function() { - function t2(t3) { - if (t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.key = "", t2.prototype.value = "", t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - return e2 || (e2 = u.create()), null != t3.key && t3.hasOwnProperty("key") && e2.uint32(10).string(t3.key), null != t3.value && t3.hasOwnProperty("value") && e2.uint32(18).string(t3.value), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.StringStringEntryProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.key = t3.string(); - break; - case 2: - r2.value = t3.string(); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.key && t3.hasOwnProperty("key") && !c.isString(t3.key) ? "key: string expected" : null != t3.value && t3.hasOwnProperty("value") && !c.isString(t3.value) ? "value: string expected" : null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.StringStringEntryProto) - return t3; - var e2 = new l.onnx.StringStringEntryProto(); - return null != t3.key && (e2.key = String(t3.key)), null != t3.value && (e2.value = String(t3.value)), e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - return e2.defaults && (n2.key = "", n2.value = ""), null != t3.key && t3.hasOwnProperty("key") && (n2.key = t3.key), null != t3.value && t3.hasOwnProperty("value") && (n2.value = t3.value), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.TensorAnnotation = function() { - function t2(t3) { - if (this.quantParameterTensorNames = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.tensorName = "", t2.prototype.quantParameterTensorNames = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.tensorName && t3.hasOwnProperty("tensorName") && e2.uint32(10).string(t3.tensorName), null != t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) - for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) - l.onnx.StringStringEntryProto.encode(t3.quantParameterTensorNames[n2], e2.uint32(18).fork()).ldelim(); - return e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorAnnotation(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.tensorName = t3.string(); - break; - case 2: - r2.quantParameterTensorNames && r2.quantParameterTensorNames.length || (r2.quantParameterTensorNames = []), r2.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.tensorName && t3.hasOwnProperty("tensorName") && !c.isString(t3.tensorName)) - return "tensorName: string expected"; - if (null != t3.quantParameterTensorNames && t3.hasOwnProperty("quantParameterTensorNames")) { - if (!Array.isArray(t3.quantParameterTensorNames)) - return "quantParameterTensorNames: array expected"; - for (var e2 = 0; e2 < t3.quantParameterTensorNames.length; ++e2) { - var n2 = l.onnx.StringStringEntryProto.verify(t3.quantParameterTensorNames[e2]); - if (n2) - return "quantParameterTensorNames." + n2; - } - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.TensorAnnotation) - return t3; - var e2 = new l.onnx.TensorAnnotation(); - if (null != t3.tensorName && (e2.tensorName = String(t3.tensorName)), t3.quantParameterTensorNames) { - if (!Array.isArray(t3.quantParameterTensorNames)) - throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected"); - e2.quantParameterTensorNames = []; - for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) { - if ("object" != typeof t3.quantParameterTensorNames[n2]) - throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected"); - e2.quantParameterTensorNames[n2] = l.onnx.StringStringEntryProto.fromObject(t3.quantParameterTensorNames[n2]); - } - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.quantParameterTensorNames = []), e2.defaults && (n2.tensorName = ""), null != t3.tensorName && t3.hasOwnProperty("tensorName") && (n2.tensorName = t3.tensorName), t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) { - n2.quantParameterTensorNames = []; - for (var r2 = 0; r2 < t3.quantParameterTensorNames.length; ++r2) - n2.quantParameterTensorNames[r2] = l.onnx.StringStringEntryProto.toObject(t3.quantParameterTensorNames[r2], e2); - } - return n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.GraphProto = function() { - function t2(t3) { - if (this.node = [], this.initializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.node = c.emptyArray, t2.prototype.name = "", t2.prototype.initializer = c.emptyArray, t2.prototype.docString = "", t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.valueInfo = c.emptyArray, t2.prototype.quantizationAnnotation = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.node && t3.node.length) - for (var n2 = 0; n2 < t3.node.length; ++n2) - l.onnx.NodeProto.encode(t3.node[n2], e2.uint32(10).fork()).ldelim(); - if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(18).string(t3.name), null != t3.initializer && t3.initializer.length) - for (n2 = 0; n2 < t3.initializer.length; ++n2) - l.onnx.TensorProto.encode(t3.initializer[n2], e2.uint32(42).fork()).ldelim(); - if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(82).string(t3.docString), null != t3.input && t3.input.length) - for (n2 = 0; n2 < t3.input.length; ++n2) - l.onnx.ValueInfoProto.encode(t3.input[n2], e2.uint32(90).fork()).ldelim(); - if (null != t3.output && t3.output.length) - for (n2 = 0; n2 < t3.output.length; ++n2) - l.onnx.ValueInfoProto.encode(t3.output[n2], e2.uint32(98).fork()).ldelim(); - if (null != t3.valueInfo && t3.valueInfo.length) - for (n2 = 0; n2 < t3.valueInfo.length; ++n2) - l.onnx.ValueInfoProto.encode(t3.valueInfo[n2], e2.uint32(106).fork()).ldelim(); - if (null != t3.quantizationAnnotation && t3.quantizationAnnotation.length) - for (n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) - l.onnx.TensorAnnotation.encode(t3.quantizationAnnotation[n2], e2.uint32(114).fork()).ldelim(); - return e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.GraphProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.node && r2.node.length || (r2.node = []), r2.node.push(l.onnx.NodeProto.decode(t3, t3.uint32())); - break; - case 2: - r2.name = t3.string(); - break; - case 5: - r2.initializer && r2.initializer.length || (r2.initializer = []), r2.initializer.push(l.onnx.TensorProto.decode(t3, t3.uint32())); - break; - case 10: - r2.docString = t3.string(); - break; - case 11: - r2.input && r2.input.length || (r2.input = []), r2.input.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); - break; - case 12: - r2.output && r2.output.length || (r2.output = []), r2.output.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); - break; - case 13: - r2.valueInfo && r2.valueInfo.length || (r2.valueInfo = []), r2.valueInfo.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); - break; - case 14: - r2.quantizationAnnotation && r2.quantizationAnnotation.length || (r2.quantizationAnnotation = []), r2.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t3, t3.uint32())); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.node && t3.hasOwnProperty("node")) { - if (!Array.isArray(t3.node)) - return "node: array expected"; - for (var e2 = 0; e2 < t3.node.length; ++e2) - if (n2 = l.onnx.NodeProto.verify(t3.node[e2])) - return "node." + n2; - } - if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) - return "name: string expected"; - if (null != t3.initializer && t3.hasOwnProperty("initializer")) { - if (!Array.isArray(t3.initializer)) - return "initializer: array expected"; - for (e2 = 0; e2 < t3.initializer.length; ++e2) - if (n2 = l.onnx.TensorProto.verify(t3.initializer[e2])) - return "initializer." + n2; - } - if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) - return "docString: string expected"; - if (null != t3.input && t3.hasOwnProperty("input")) { - if (!Array.isArray(t3.input)) - return "input: array expected"; - for (e2 = 0; e2 < t3.input.length; ++e2) - if (n2 = l.onnx.ValueInfoProto.verify(t3.input[e2])) - return "input." + n2; - } - if (null != t3.output && t3.hasOwnProperty("output")) { - if (!Array.isArray(t3.output)) - return "output: array expected"; - for (e2 = 0; e2 < t3.output.length; ++e2) - if (n2 = l.onnx.ValueInfoProto.verify(t3.output[e2])) - return "output." + n2; - } - if (null != t3.valueInfo && t3.hasOwnProperty("valueInfo")) { - if (!Array.isArray(t3.valueInfo)) - return "valueInfo: array expected"; - for (e2 = 0; e2 < t3.valueInfo.length; ++e2) - if (n2 = l.onnx.ValueInfoProto.verify(t3.valueInfo[e2])) - return "valueInfo." + n2; - } - if (null != t3.quantizationAnnotation && t3.hasOwnProperty("quantizationAnnotation")) { - if (!Array.isArray(t3.quantizationAnnotation)) - return "quantizationAnnotation: array expected"; - for (e2 = 0; e2 < t3.quantizationAnnotation.length; ++e2) { - var n2; - if (n2 = l.onnx.TensorAnnotation.verify(t3.quantizationAnnotation[e2])) - return "quantizationAnnotation." + n2; - } - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.GraphProto) - return t3; - var e2 = new l.onnx.GraphProto(); - if (t3.node) { - if (!Array.isArray(t3.node)) - throw TypeError(".onnx.GraphProto.node: array expected"); - e2.node = []; - for (var n2 = 0; n2 < t3.node.length; ++n2) { - if ("object" != typeof t3.node[n2]) - throw TypeError(".onnx.GraphProto.node: object expected"); - e2.node[n2] = l.onnx.NodeProto.fromObject(t3.node[n2]); - } - } - if (null != t3.name && (e2.name = String(t3.name)), t3.initializer) { - if (!Array.isArray(t3.initializer)) - throw TypeError(".onnx.GraphProto.initializer: array expected"); - for (e2.initializer = [], n2 = 0; n2 < t3.initializer.length; ++n2) { - if ("object" != typeof t3.initializer[n2]) - throw TypeError(".onnx.GraphProto.initializer: object expected"); - e2.initializer[n2] = l.onnx.TensorProto.fromObject(t3.initializer[n2]); - } - } - if (null != t3.docString && (e2.docString = String(t3.docString)), t3.input) { - if (!Array.isArray(t3.input)) - throw TypeError(".onnx.GraphProto.input: array expected"); - for (e2.input = [], n2 = 0; n2 < t3.input.length; ++n2) { - if ("object" != typeof t3.input[n2]) - throw TypeError(".onnx.GraphProto.input: object expected"); - e2.input[n2] = l.onnx.ValueInfoProto.fromObject(t3.input[n2]); - } - } - if (t3.output) { - if (!Array.isArray(t3.output)) - throw TypeError(".onnx.GraphProto.output: array expected"); - for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) { - if ("object" != typeof t3.output[n2]) - throw TypeError(".onnx.GraphProto.output: object expected"); - e2.output[n2] = l.onnx.ValueInfoProto.fromObject(t3.output[n2]); - } - } - if (t3.valueInfo) { - if (!Array.isArray(t3.valueInfo)) - throw TypeError(".onnx.GraphProto.valueInfo: array expected"); - for (e2.valueInfo = [], n2 = 0; n2 < t3.valueInfo.length; ++n2) { - if ("object" != typeof t3.valueInfo[n2]) - throw TypeError(".onnx.GraphProto.valueInfo: object expected"); - e2.valueInfo[n2] = l.onnx.ValueInfoProto.fromObject(t3.valueInfo[n2]); - } - } - if (t3.quantizationAnnotation) { - if (!Array.isArray(t3.quantizationAnnotation)) - throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected"); - for (e2.quantizationAnnotation = [], n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) { - if ("object" != typeof t3.quantizationAnnotation[n2]) - throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected"); - e2.quantizationAnnotation[n2] = l.onnx.TensorAnnotation.fromObject(t3.quantizationAnnotation[n2]); - } - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.node = [], n2.initializer = [], n2.input = [], n2.output = [], n2.valueInfo = [], n2.quantizationAnnotation = []), e2.defaults && (n2.name = "", n2.docString = ""), t3.node && t3.node.length) { - n2.node = []; - for (var r2 = 0; r2 < t3.node.length; ++r2) - n2.node[r2] = l.onnx.NodeProto.toObject(t3.node[r2], e2); - } - if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), t3.initializer && t3.initializer.length) - for (n2.initializer = [], r2 = 0; r2 < t3.initializer.length; ++r2) - n2.initializer[r2] = l.onnx.TensorProto.toObject(t3.initializer[r2], e2); - if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.input && t3.input.length) - for (n2.input = [], r2 = 0; r2 < t3.input.length; ++r2) - n2.input[r2] = l.onnx.ValueInfoProto.toObject(t3.input[r2], e2); - if (t3.output && t3.output.length) - for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) - n2.output[r2] = l.onnx.ValueInfoProto.toObject(t3.output[r2], e2); - if (t3.valueInfo && t3.valueInfo.length) - for (n2.valueInfo = [], r2 = 0; r2 < t3.valueInfo.length; ++r2) - n2.valueInfo[r2] = l.onnx.ValueInfoProto.toObject(t3.valueInfo[r2], e2); - if (t3.quantizationAnnotation && t3.quantizationAnnotation.length) - for (n2.quantizationAnnotation = [], r2 = 0; r2 < t3.quantizationAnnotation.length; ++r2) - n2.quantizationAnnotation[r2] = l.onnx.TensorAnnotation.toObject(t3.quantizationAnnotation[r2], e2); - return n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o.TensorProto = function() { - function t2(t3) { - if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.dims = c.emptyArray, t2.prototype.dataType = 0, t2.prototype.segment = null, t2.prototype.floatData = c.emptyArray, t2.prototype.int32Data = c.emptyArray, t2.prototype.stringData = c.emptyArray, t2.prototype.int64Data = c.emptyArray, t2.prototype.name = "", t2.prototype.docString = "", t2.prototype.rawData = c.newBuffer([]), t2.prototype.externalData = c.emptyArray, t2.prototype.dataLocation = 0, t2.prototype.doubleData = c.emptyArray, t2.prototype.uint64Data = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.dims && t3.dims.length) { - e2.uint32(10).fork(); - for (var n2 = 0; n2 < t3.dims.length; ++n2) - e2.int64(t3.dims[n2]); - e2.ldelim(); - } - if (null != t3.dataType && t3.hasOwnProperty("dataType") && e2.uint32(16).int32(t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && l.onnx.TensorProto.Segment.encode(t3.segment, e2.uint32(26).fork()).ldelim(), null != t3.floatData && t3.floatData.length) { - for (e2.uint32(34).fork(), n2 = 0; n2 < t3.floatData.length; ++n2) - e2.float(t3.floatData[n2]); - e2.ldelim(); - } - if (null != t3.int32Data && t3.int32Data.length) { - for (e2.uint32(42).fork(), n2 = 0; n2 < t3.int32Data.length; ++n2) - e2.int32(t3.int32Data[n2]); - e2.ldelim(); - } - if (null != t3.stringData && t3.stringData.length) - for (n2 = 0; n2 < t3.stringData.length; ++n2) - e2.uint32(50).bytes(t3.stringData[n2]); - if (null != t3.int64Data && t3.int64Data.length) { - for (e2.uint32(58).fork(), n2 = 0; n2 < t3.int64Data.length; ++n2) - e2.int64(t3.int64Data[n2]); - e2.ldelim(); - } - if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(66).string(t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && e2.uint32(74).bytes(t3.rawData), null != t3.doubleData && t3.doubleData.length) { - for (e2.uint32(82).fork(), n2 = 0; n2 < t3.doubleData.length; ++n2) - e2.double(t3.doubleData[n2]); - e2.ldelim(); - } - if (null != t3.uint64Data && t3.uint64Data.length) { - for (e2.uint32(90).fork(), n2 = 0; n2 < t3.uint64Data.length; ++n2) - e2.uint64(t3.uint64Data[n2]); - e2.ldelim(); - } - if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(98).string(t3.docString), null != t3.externalData && t3.externalData.length) - for (n2 = 0; n2 < t3.externalData.length; ++n2) - l.onnx.StringStringEntryProto.encode(t3.externalData[n2], e2.uint32(106).fork()).ldelim(); - return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && e2.uint32(112).int32(t3.dataLocation), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - if (r2.dims && r2.dims.length || (r2.dims = []), 2 == (7 & i2)) - for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.dims.push(t3.int64()); - else - r2.dims.push(t3.int64()); - break; - case 2: - r2.dataType = t3.int32(); - break; - case 3: - r2.segment = l.onnx.TensorProto.Segment.decode(t3, t3.uint32()); - break; - case 4: - if (r2.floatData && r2.floatData.length || (r2.floatData = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.floatData.push(t3.float()); - else - r2.floatData.push(t3.float()); - break; - case 5: - if (r2.int32Data && r2.int32Data.length || (r2.int32Data = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.int32Data.push(t3.int32()); - else - r2.int32Data.push(t3.int32()); - break; - case 6: - r2.stringData && r2.stringData.length || (r2.stringData = []), r2.stringData.push(t3.bytes()); - break; - case 7: - if (r2.int64Data && r2.int64Data.length || (r2.int64Data = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.int64Data.push(t3.int64()); - else - r2.int64Data.push(t3.int64()); - break; - case 8: - r2.name = t3.string(); - break; - case 12: - r2.docString = t3.string(); - break; - case 9: - r2.rawData = t3.bytes(); - break; - case 13: - r2.externalData && r2.externalData.length || (r2.externalData = []), r2.externalData.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); - break; - case 14: - r2.dataLocation = t3.int32(); - break; - case 10: - if (r2.doubleData && r2.doubleData.length || (r2.doubleData = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.doubleData.push(t3.double()); - else - r2.doubleData.push(t3.double()); - break; - case 11: - if (r2.uint64Data && r2.uint64Data.length || (r2.uint64Data = []), 2 == (7 & i2)) - for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) - r2.uint64Data.push(t3.uint64()); - else - r2.uint64Data.push(t3.uint64()); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.dims && t3.hasOwnProperty("dims")) { - if (!Array.isArray(t3.dims)) - return "dims: array expected"; - for (var e2 = 0; e2 < t3.dims.length; ++e2) - if (!(c.isInteger(t3.dims[e2]) || t3.dims[e2] && c.isInteger(t3.dims[e2].low) && c.isInteger(t3.dims[e2].high))) - return "dims: integer|Long[] expected"; - } - if (null != t3.dataType && t3.hasOwnProperty("dataType") && !c.isInteger(t3.dataType)) - return "dataType: integer expected"; - if (null != t3.segment && t3.hasOwnProperty("segment") && (n2 = l.onnx.TensorProto.Segment.verify(t3.segment))) - return "segment." + n2; - if (null != t3.floatData && t3.hasOwnProperty("floatData")) { - if (!Array.isArray(t3.floatData)) - return "floatData: array expected"; - for (e2 = 0; e2 < t3.floatData.length; ++e2) - if ("number" != typeof t3.floatData[e2]) - return "floatData: number[] expected"; - } - if (null != t3.int32Data && t3.hasOwnProperty("int32Data")) { - if (!Array.isArray(t3.int32Data)) - return "int32Data: array expected"; - for (e2 = 0; e2 < t3.int32Data.length; ++e2) - if (!c.isInteger(t3.int32Data[e2])) - return "int32Data: integer[] expected"; - } - if (null != t3.stringData && t3.hasOwnProperty("stringData")) { - if (!Array.isArray(t3.stringData)) - return "stringData: array expected"; - for (e2 = 0; e2 < t3.stringData.length; ++e2) - if (!(t3.stringData[e2] && "number" == typeof t3.stringData[e2].length || c.isString(t3.stringData[e2]))) - return "stringData: buffer[] expected"; - } - if (null != t3.int64Data && t3.hasOwnProperty("int64Data")) { - if (!Array.isArray(t3.int64Data)) - return "int64Data: array expected"; - for (e2 = 0; e2 < t3.int64Data.length; ++e2) - if (!(c.isInteger(t3.int64Data[e2]) || t3.int64Data[e2] && c.isInteger(t3.int64Data[e2].low) && c.isInteger(t3.int64Data[e2].high))) - return "int64Data: integer|Long[] expected"; - } - if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) - return "name: string expected"; - if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) - return "docString: string expected"; - if (null != t3.rawData && t3.hasOwnProperty("rawData") && !(t3.rawData && "number" == typeof t3.rawData.length || c.isString(t3.rawData))) - return "rawData: buffer expected"; - if (null != t3.externalData && t3.hasOwnProperty("externalData")) { - if (!Array.isArray(t3.externalData)) - return "externalData: array expected"; - for (e2 = 0; e2 < t3.externalData.length; ++e2) { - var n2; - if (n2 = l.onnx.StringStringEntryProto.verify(t3.externalData[e2])) - return "externalData." + n2; - } - } - if (null != t3.dataLocation && t3.hasOwnProperty("dataLocation")) - switch (t3.dataLocation) { - default: - return "dataLocation: enum value expected"; - case 0: - case 1: - } - if (null != t3.doubleData && t3.hasOwnProperty("doubleData")) { - if (!Array.isArray(t3.doubleData)) - return "doubleData: array expected"; - for (e2 = 0; e2 < t3.doubleData.length; ++e2) - if ("number" != typeof t3.doubleData[e2]) - return "doubleData: number[] expected"; - } - if (null != t3.uint64Data && t3.hasOwnProperty("uint64Data")) { - if (!Array.isArray(t3.uint64Data)) - return "uint64Data: array expected"; - for (e2 = 0; e2 < t3.uint64Data.length; ++e2) - if (!(c.isInteger(t3.uint64Data[e2]) || t3.uint64Data[e2] && c.isInteger(t3.uint64Data[e2].low) && c.isInteger(t3.uint64Data[e2].high))) - return "uint64Data: integer|Long[] expected"; - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.TensorProto) - return t3; - var e2 = new l.onnx.TensorProto(); - if (t3.dims) { - if (!Array.isArray(t3.dims)) - throw TypeError(".onnx.TensorProto.dims: array expected"); - e2.dims = []; - for (var n2 = 0; n2 < t3.dims.length; ++n2) - c.Long ? (e2.dims[n2] = c.Long.fromValue(t3.dims[n2])).unsigned = false : "string" == typeof t3.dims[n2] ? e2.dims[n2] = parseInt(t3.dims[n2], 10) : "number" == typeof t3.dims[n2] ? e2.dims[n2] = t3.dims[n2] : "object" == typeof t3.dims[n2] && (e2.dims[n2] = new c.LongBits(t3.dims[n2].low >>> 0, t3.dims[n2].high >>> 0).toNumber()); - } - if (null != t3.dataType && (e2.dataType = 0 | t3.dataType), null != t3.segment) { - if ("object" != typeof t3.segment) - throw TypeError(".onnx.TensorProto.segment: object expected"); - e2.segment = l.onnx.TensorProto.Segment.fromObject(t3.segment); - } - if (t3.floatData) { - if (!Array.isArray(t3.floatData)) - throw TypeError(".onnx.TensorProto.floatData: array expected"); - for (e2.floatData = [], n2 = 0; n2 < t3.floatData.length; ++n2) - e2.floatData[n2] = Number(t3.floatData[n2]); - } - if (t3.int32Data) { - if (!Array.isArray(t3.int32Data)) - throw TypeError(".onnx.TensorProto.int32Data: array expected"); - for (e2.int32Data = [], n2 = 0; n2 < t3.int32Data.length; ++n2) - e2.int32Data[n2] = 0 | t3.int32Data[n2]; - } - if (t3.stringData) { - if (!Array.isArray(t3.stringData)) - throw TypeError(".onnx.TensorProto.stringData: array expected"); - for (e2.stringData = [], n2 = 0; n2 < t3.stringData.length; ++n2) - "string" == typeof t3.stringData[n2] ? c.base64.decode(t3.stringData[n2], e2.stringData[n2] = c.newBuffer(c.base64.length(t3.stringData[n2])), 0) : t3.stringData[n2].length && (e2.stringData[n2] = t3.stringData[n2]); - } - if (t3.int64Data) { - if (!Array.isArray(t3.int64Data)) - throw TypeError(".onnx.TensorProto.int64Data: array expected"); - for (e2.int64Data = [], n2 = 0; n2 < t3.int64Data.length; ++n2) - c.Long ? (e2.int64Data[n2] = c.Long.fromValue(t3.int64Data[n2])).unsigned = false : "string" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = parseInt(t3.int64Data[n2], 10) : "number" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = t3.int64Data[n2] : "object" == typeof t3.int64Data[n2] && (e2.int64Data[n2] = new c.LongBits(t3.int64Data[n2].low >>> 0, t3.int64Data[n2].high >>> 0).toNumber()); - } - if (null != t3.name && (e2.name = String(t3.name)), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.rawData && ("string" == typeof t3.rawData ? c.base64.decode(t3.rawData, e2.rawData = c.newBuffer(c.base64.length(t3.rawData)), 0) : t3.rawData.length && (e2.rawData = t3.rawData)), t3.externalData) { - if (!Array.isArray(t3.externalData)) - throw TypeError(".onnx.TensorProto.externalData: array expected"); - for (e2.externalData = [], n2 = 0; n2 < t3.externalData.length; ++n2) { - if ("object" != typeof t3.externalData[n2]) - throw TypeError(".onnx.TensorProto.externalData: object expected"); - e2.externalData[n2] = l.onnx.StringStringEntryProto.fromObject(t3.externalData[n2]); - } - } - switch (t3.dataLocation) { - case "DEFAULT": - case 0: - e2.dataLocation = 0; - break; - case "EXTERNAL": - case 1: - e2.dataLocation = 1; - } - if (t3.doubleData) { - if (!Array.isArray(t3.doubleData)) - throw TypeError(".onnx.TensorProto.doubleData: array expected"); - for (e2.doubleData = [], n2 = 0; n2 < t3.doubleData.length; ++n2) - e2.doubleData[n2] = Number(t3.doubleData[n2]); - } - if (t3.uint64Data) { - if (!Array.isArray(t3.uint64Data)) - throw TypeError(".onnx.TensorProto.uint64Data: array expected"); - for (e2.uint64Data = [], n2 = 0; n2 < t3.uint64Data.length; ++n2) - c.Long ? (e2.uint64Data[n2] = c.Long.fromValue(t3.uint64Data[n2])).unsigned = true : "string" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = parseInt(t3.uint64Data[n2], 10) : "number" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = t3.uint64Data[n2] : "object" == typeof t3.uint64Data[n2] && (e2.uint64Data[n2] = new c.LongBits(t3.uint64Data[n2].low >>> 0, t3.uint64Data[n2].high >>> 0).toNumber(true)); - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.dims = [], n2.floatData = [], n2.int32Data = [], n2.stringData = [], n2.int64Data = [], n2.doubleData = [], n2.uint64Data = [], n2.externalData = []), e2.defaults && (n2.dataType = 0, n2.segment = null, n2.name = "", e2.bytes === String ? n2.rawData = "" : (n2.rawData = [], e2.bytes !== Array && (n2.rawData = c.newBuffer(n2.rawData))), n2.docString = "", n2.dataLocation = e2.enums === String ? "DEFAULT" : 0), t3.dims && t3.dims.length) { - n2.dims = []; - for (var r2 = 0; r2 < t3.dims.length; ++r2) - "number" == typeof t3.dims[r2] ? n2.dims[r2] = e2.longs === String ? String(t3.dims[r2]) : t3.dims[r2] : n2.dims[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.dims[r2]) : e2.longs === Number ? new c.LongBits(t3.dims[r2].low >>> 0, t3.dims[r2].high >>> 0).toNumber() : t3.dims[r2]; - } - if (null != t3.dataType && t3.hasOwnProperty("dataType") && (n2.dataType = t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && (n2.segment = l.onnx.TensorProto.Segment.toObject(t3.segment, e2)), t3.floatData && t3.floatData.length) - for (n2.floatData = [], r2 = 0; r2 < t3.floatData.length; ++r2) - n2.floatData[r2] = e2.json && !isFinite(t3.floatData[r2]) ? String(t3.floatData[r2]) : t3.floatData[r2]; - if (t3.int32Data && t3.int32Data.length) - for (n2.int32Data = [], r2 = 0; r2 < t3.int32Data.length; ++r2) - n2.int32Data[r2] = t3.int32Data[r2]; - if (t3.stringData && t3.stringData.length) - for (n2.stringData = [], r2 = 0; r2 < t3.stringData.length; ++r2) - n2.stringData[r2] = e2.bytes === String ? c.base64.encode(t3.stringData[r2], 0, t3.stringData[r2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.stringData[r2]) : t3.stringData[r2]; - if (t3.int64Data && t3.int64Data.length) - for (n2.int64Data = [], r2 = 0; r2 < t3.int64Data.length; ++r2) - "number" == typeof t3.int64Data[r2] ? n2.int64Data[r2] = e2.longs === String ? String(t3.int64Data[r2]) : t3.int64Data[r2] : n2.int64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.int64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.int64Data[r2].low >>> 0, t3.int64Data[r2].high >>> 0).toNumber() : t3.int64Data[r2]; - if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && (n2.rawData = e2.bytes === String ? c.base64.encode(t3.rawData, 0, t3.rawData.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.rawData) : t3.rawData), t3.doubleData && t3.doubleData.length) - for (n2.doubleData = [], r2 = 0; r2 < t3.doubleData.length; ++r2) - n2.doubleData[r2] = e2.json && !isFinite(t3.doubleData[r2]) ? String(t3.doubleData[r2]) : t3.doubleData[r2]; - if (t3.uint64Data && t3.uint64Data.length) - for (n2.uint64Data = [], r2 = 0; r2 < t3.uint64Data.length; ++r2) - "number" == typeof t3.uint64Data[r2] ? n2.uint64Data[r2] = e2.longs === String ? String(t3.uint64Data[r2]) : t3.uint64Data[r2] : n2.uint64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.uint64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.uint64Data[r2].low >>> 0, t3.uint64Data[r2].high >>> 0).toNumber(true) : t3.uint64Data[r2]; - if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.externalData && t3.externalData.length) - for (n2.externalData = [], r2 = 0; r2 < t3.externalData.length; ++r2) - n2.externalData[r2] = l.onnx.StringStringEntryProto.toObject(t3.externalData[r2], e2); - return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && (n2.dataLocation = e2.enums === String ? l.onnx.TensorProto.DataLocation[t3.dataLocation] : t3.dataLocation), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2.DataType = function() { - var t3 = {}, e2 = Object.create(t3); - return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "UINT8"] = 2, e2[t3[3] = "INT8"] = 3, e2[t3[4] = "UINT16"] = 4, e2[t3[5] = "INT16"] = 5, e2[t3[6] = "INT32"] = 6, e2[t3[7] = "INT64"] = 7, e2[t3[8] = "STRING"] = 8, e2[t3[9] = "BOOL"] = 9, e2[t3[10] = "FLOAT16"] = 10, e2[t3[11] = "DOUBLE"] = 11, e2[t3[12] = "UINT32"] = 12, e2[t3[13] = "UINT64"] = 13, e2[t3[14] = "COMPLEX64"] = 14, e2[t3[15] = "COMPLEX128"] = 15, e2[t3[16] = "BFLOAT16"] = 16, e2; - }(), t2.Segment = function() { - function t3(t4) { - if (t4) - for (var e2 = Object.keys(t4), n2 = 0; n2 < e2.length; ++n2) - null != t4[e2[n2]] && (this[e2[n2]] = t4[e2[n2]]); - } - return t3.prototype.begin = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.end = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.create = function(e2) { - return new t3(e2); - }, t3.encode = function(t4, e2) { - return e2 || (e2 = u.create()), null != t4.begin && t4.hasOwnProperty("begin") && e2.uint32(8).int64(t4.begin), null != t4.end && t4.hasOwnProperty("end") && e2.uint32(16).int64(t4.end), e2; - }, t3.encodeDelimited = function(t4, e2) { - return this.encode(t4, e2).ldelim(); - }, t3.decode = function(t4, e2) { - t4 instanceof s || (t4 = s.create(t4)); - for (var n2 = void 0 === e2 ? t4.len : t4.pos + e2, r2 = new l.onnx.TensorProto.Segment(); t4.pos < n2; ) { - var i2 = t4.uint32(); - switch (i2 >>> 3) { - case 1: - r2.begin = t4.int64(); - break; - case 2: - r2.end = t4.int64(); - break; - default: - t4.skipType(7 & i2); - } - } - return r2; - }, t3.decodeDelimited = function(t4) { - return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); - }, t3.verify = function(t4) { - return "object" != typeof t4 || null === t4 ? "object expected" : null != t4.begin && t4.hasOwnProperty("begin") && !(c.isInteger(t4.begin) || t4.begin && c.isInteger(t4.begin.low) && c.isInteger(t4.begin.high)) ? "begin: integer|Long expected" : null != t4.end && t4.hasOwnProperty("end") && !(c.isInteger(t4.end) || t4.end && c.isInteger(t4.end.low) && c.isInteger(t4.end.high)) ? "end: integer|Long expected" : null; - }, t3.fromObject = function(t4) { - if (t4 instanceof l.onnx.TensorProto.Segment) - return t4; - var e2 = new l.onnx.TensorProto.Segment(); - return null != t4.begin && (c.Long ? (e2.begin = c.Long.fromValue(t4.begin)).unsigned = false : "string" == typeof t4.begin ? e2.begin = parseInt(t4.begin, 10) : "number" == typeof t4.begin ? e2.begin = t4.begin : "object" == typeof t4.begin && (e2.begin = new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber())), null != t4.end && (c.Long ? (e2.end = c.Long.fromValue(t4.end)).unsigned = false : "string" == typeof t4.end ? e2.end = parseInt(t4.end, 10) : "number" == typeof t4.end ? e2.end = t4.end : "object" == typeof t4.end && (e2.end = new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber())), e2; - }, t3.toObject = function(t4, e2) { - e2 || (e2 = {}); - var n2 = {}; - if (e2.defaults) { - if (c.Long) { - var r2 = new c.Long(0, 0, false); - n2.begin = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; - } else - n2.begin = e2.longs === String ? "0" : 0; - c.Long ? (r2 = new c.Long(0, 0, false), n2.end = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.end = e2.longs === String ? "0" : 0; - } - return null != t4.begin && t4.hasOwnProperty("begin") && ("number" == typeof t4.begin ? n2.begin = e2.longs === String ? String(t4.begin) : t4.begin : n2.begin = e2.longs === String ? c.Long.prototype.toString.call(t4.begin) : e2.longs === Number ? new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber() : t4.begin), null != t4.end && t4.hasOwnProperty("end") && ("number" == typeof t4.end ? n2.end = e2.longs === String ? String(t4.end) : t4.end : n2.end = e2.longs === String ? c.Long.prototype.toString.call(t4.end) : e2.longs === Number ? new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber() : t4.end), n2; - }, t3.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t3; - }(), t2.DataLocation = function() { - var t3 = {}, e2 = Object.create(t3); - return e2[t3[0] = "DEFAULT"] = 0, e2[t3[1] = "EXTERNAL"] = 1, e2; - }(), t2; - }(), o.TensorShapeProto = function() { - function t2(t3) { - if (this.dim = [], t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.dim = c.emptyArray, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - if (e2 || (e2 = u.create()), null != t3.dim && t3.dim.length) - for (var n2 = 0; n2 < t3.dim.length; ++n2) - l.onnx.TensorShapeProto.Dimension.encode(t3.dim[n2], e2.uint32(10).fork()).ldelim(); - return e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorShapeProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - i2 >>> 3 == 1 ? (r2.dim && r2.dim.length || (r2.dim = []), r2.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t3, t3.uint32()))) : t3.skipType(7 & i2); - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.dim && t3.hasOwnProperty("dim")) { - if (!Array.isArray(t3.dim)) - return "dim: array expected"; - for (var e2 = 0; e2 < t3.dim.length; ++e2) { - var n2 = l.onnx.TensorShapeProto.Dimension.verify(t3.dim[e2]); - if (n2) - return "dim." + n2; - } - } - return null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.TensorShapeProto) - return t3; - var e2 = new l.onnx.TensorShapeProto(); - if (t3.dim) { - if (!Array.isArray(t3.dim)) - throw TypeError(".onnx.TensorShapeProto.dim: array expected"); - e2.dim = []; - for (var n2 = 0; n2 < t3.dim.length; ++n2) { - if ("object" != typeof t3.dim[n2]) - throw TypeError(".onnx.TensorShapeProto.dim: object expected"); - e2.dim[n2] = l.onnx.TensorShapeProto.Dimension.fromObject(t3.dim[n2]); - } - } - return e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if ((e2.arrays || e2.defaults) && (n2.dim = []), t3.dim && t3.dim.length) { - n2.dim = []; - for (var r2 = 0; r2 < t3.dim.length; ++r2) - n2.dim[r2] = l.onnx.TensorShapeProto.Dimension.toObject(t3.dim[r2], e2); - } - return n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2.Dimension = function() { - function t3(t4) { - if (t4) - for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) - null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]); - } - var e2; - return t3.prototype.dimValue = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.dimParam = "", t3.prototype.denotation = "", Object.defineProperty(t3.prototype, "value", { get: c.oneOfGetter(e2 = ["dimValue", "dimParam"]), set: c.oneOfSetter(e2) }), t3.create = function(e3) { - return new t3(e3); - }, t3.encode = function(t4, e3) { - return e3 || (e3 = u.create()), null != t4.dimValue && t4.hasOwnProperty("dimValue") && e3.uint32(8).int64(t4.dimValue), null != t4.dimParam && t4.hasOwnProperty("dimParam") && e3.uint32(18).string(t4.dimParam), null != t4.denotation && t4.hasOwnProperty("denotation") && e3.uint32(26).string(t4.denotation), e3; - }, t3.encodeDelimited = function(t4, e3) { - return this.encode(t4, e3).ldelim(); - }, t3.decode = function(t4, e3) { - t4 instanceof s || (t4 = s.create(t4)); - for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TensorShapeProto.Dimension(); t4.pos < n2; ) { - var i2 = t4.uint32(); - switch (i2 >>> 3) { - case 1: - r2.dimValue = t4.int64(); - break; - case 2: - r2.dimParam = t4.string(); - break; - case 3: - r2.denotation = t4.string(); - break; - default: - t4.skipType(7 & i2); - } - } - return r2; - }, t3.decodeDelimited = function(t4) { - return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); - }, t3.verify = function(t4) { - if ("object" != typeof t4 || null === t4) - return "object expected"; - var e3 = {}; - if (null != t4.dimValue && t4.hasOwnProperty("dimValue") && (e3.value = 1, !(c.isInteger(t4.dimValue) || t4.dimValue && c.isInteger(t4.dimValue.low) && c.isInteger(t4.dimValue.high)))) - return "dimValue: integer|Long expected"; - if (null != t4.dimParam && t4.hasOwnProperty("dimParam")) { - if (1 === e3.value) - return "value: multiple values"; - if (e3.value = 1, !c.isString(t4.dimParam)) - return "dimParam: string expected"; - } - return null != t4.denotation && t4.hasOwnProperty("denotation") && !c.isString(t4.denotation) ? "denotation: string expected" : null; - }, t3.fromObject = function(t4) { - if (t4 instanceof l.onnx.TensorShapeProto.Dimension) - return t4; - var e3 = new l.onnx.TensorShapeProto.Dimension(); - return null != t4.dimValue && (c.Long ? (e3.dimValue = c.Long.fromValue(t4.dimValue)).unsigned = false : "string" == typeof t4.dimValue ? e3.dimValue = parseInt(t4.dimValue, 10) : "number" == typeof t4.dimValue ? e3.dimValue = t4.dimValue : "object" == typeof t4.dimValue && (e3.dimValue = new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber())), null != t4.dimParam && (e3.dimParam = String(t4.dimParam)), null != t4.denotation && (e3.denotation = String(t4.denotation)), e3; - }, t3.toObject = function(t4, e3) { - e3 || (e3 = {}); - var n2 = {}; - return e3.defaults && (n2.denotation = ""), null != t4.dimValue && t4.hasOwnProperty("dimValue") && ("number" == typeof t4.dimValue ? n2.dimValue = e3.longs === String ? String(t4.dimValue) : t4.dimValue : n2.dimValue = e3.longs === String ? c.Long.prototype.toString.call(t4.dimValue) : e3.longs === Number ? new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber() : t4.dimValue, e3.oneofs && (n2.value = "dimValue")), null != t4.dimParam && t4.hasOwnProperty("dimParam") && (n2.dimParam = t4.dimParam, e3.oneofs && (n2.value = "dimParam")), null != t4.denotation && t4.hasOwnProperty("denotation") && (n2.denotation = t4.denotation), n2; - }, t3.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t3; - }(), t2; - }(), o.TypeProto = function() { - function t2(t3) { - if (t3) - for (var e3 = Object.keys(t3), n2 = 0; n2 < e3.length; ++n2) - null != t3[e3[n2]] && (this[e3[n2]] = t3[e3[n2]]); - } - var e2; - return t2.prototype.tensorType = null, t2.prototype.denotation = "", Object.defineProperty(t2.prototype, "value", { get: c.oneOfGetter(e2 = ["tensorType"]), set: c.oneOfSetter(e2) }), t2.create = function(e3) { - return new t2(e3); - }, t2.encode = function(t3, e3) { - return e3 || (e3 = u.create()), null != t3.tensorType && t3.hasOwnProperty("tensorType") && l.onnx.TypeProto.Tensor.encode(t3.tensorType, e3.uint32(10).fork()).ldelim(), null != t3.denotation && t3.hasOwnProperty("denotation") && e3.uint32(50).string(t3.denotation), e3; - }, t2.encodeDelimited = function(t3, e3) { - return this.encode(t3, e3).ldelim(); - }, t2.decode = function(t3, e3) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e3 ? t3.len : t3.pos + e3, r2 = new l.onnx.TypeProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.tensorType = l.onnx.TypeProto.Tensor.decode(t3, t3.uint32()); - break; - case 6: - r2.denotation = t3.string(); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - if ("object" != typeof t3 || null === t3) - return "object expected"; - if (null != t3.tensorType && t3.hasOwnProperty("tensorType")) { - var e3 = l.onnx.TypeProto.Tensor.verify(t3.tensorType); - if (e3) - return "tensorType." + e3; - } - return null != t3.denotation && t3.hasOwnProperty("denotation") && !c.isString(t3.denotation) ? "denotation: string expected" : null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.TypeProto) - return t3; - var e3 = new l.onnx.TypeProto(); - if (null != t3.tensorType) { - if ("object" != typeof t3.tensorType) - throw TypeError(".onnx.TypeProto.tensorType: object expected"); - e3.tensorType = l.onnx.TypeProto.Tensor.fromObject(t3.tensorType); - } - return null != t3.denotation && (e3.denotation = String(t3.denotation)), e3; - }, t2.toObject = function(t3, e3) { - e3 || (e3 = {}); - var n2 = {}; - return e3.defaults && (n2.denotation = ""), null != t3.tensorType && t3.hasOwnProperty("tensorType") && (n2.tensorType = l.onnx.TypeProto.Tensor.toObject(t3.tensorType, e3), e3.oneofs && (n2.value = "tensorType")), null != t3.denotation && t3.hasOwnProperty("denotation") && (n2.denotation = t3.denotation), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2.Tensor = function() { - function t3(t4) { - if (t4) - for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) - null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]); - } - return t3.prototype.elemType = 0, t3.prototype.shape = null, t3.create = function(e3) { - return new t3(e3); - }, t3.encode = function(t4, e3) { - return e3 || (e3 = u.create()), null != t4.elemType && t4.hasOwnProperty("elemType") && e3.uint32(8).int32(t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && l.onnx.TensorShapeProto.encode(t4.shape, e3.uint32(18).fork()).ldelim(), e3; - }, t3.encodeDelimited = function(t4, e3) { - return this.encode(t4, e3).ldelim(); - }, t3.decode = function(t4, e3) { - t4 instanceof s || (t4 = s.create(t4)); - for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TypeProto.Tensor(); t4.pos < n2; ) { - var i2 = t4.uint32(); - switch (i2 >>> 3) { - case 1: - r2.elemType = t4.int32(); - break; - case 2: - r2.shape = l.onnx.TensorShapeProto.decode(t4, t4.uint32()); - break; - default: - t4.skipType(7 & i2); - } - } - return r2; - }, t3.decodeDelimited = function(t4) { - return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); - }, t3.verify = function(t4) { - if ("object" != typeof t4 || null === t4) - return "object expected"; - if (null != t4.elemType && t4.hasOwnProperty("elemType") && !c.isInteger(t4.elemType)) - return "elemType: integer expected"; - if (null != t4.shape && t4.hasOwnProperty("shape")) { - var e3 = l.onnx.TensorShapeProto.verify(t4.shape); - if (e3) - return "shape." + e3; - } - return null; - }, t3.fromObject = function(t4) { - if (t4 instanceof l.onnx.TypeProto.Tensor) - return t4; - var e3 = new l.onnx.TypeProto.Tensor(); - if (null != t4.elemType && (e3.elemType = 0 | t4.elemType), null != t4.shape) { - if ("object" != typeof t4.shape) - throw TypeError(".onnx.TypeProto.Tensor.shape: object expected"); - e3.shape = l.onnx.TensorShapeProto.fromObject(t4.shape); - } - return e3; - }, t3.toObject = function(t4, e3) { - e3 || (e3 = {}); - var n2 = {}; - return e3.defaults && (n2.elemType = 0, n2.shape = null), null != t4.elemType && t4.hasOwnProperty("elemType") && (n2.elemType = t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && (n2.shape = l.onnx.TensorShapeProto.toObject(t4.shape, e3)), n2; - }, t3.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t3; - }(), t2; - }(), o.OperatorSetIdProto = function() { - function t2(t3) { - if (t3) - for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) - null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); - } - return t2.prototype.domain = "", t2.prototype.version = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.create = function(e2) { - return new t2(e2); - }, t2.encode = function(t3, e2) { - return e2 || (e2 = u.create()), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(10).string(t3.domain), null != t3.version && t3.hasOwnProperty("version") && e2.uint32(16).int64(t3.version), e2; - }, t2.encodeDelimited = function(t3, e2) { - return this.encode(t3, e2).ldelim(); - }, t2.decode = function(t3, e2) { - t3 instanceof s || (t3 = s.create(t3)); - for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.OperatorSetIdProto(); t3.pos < n2; ) { - var i2 = t3.uint32(); - switch (i2 >>> 3) { - case 1: - r2.domain = t3.string(); - break; - case 2: - r2.version = t3.int64(); - break; - default: - t3.skipType(7 & i2); - } - } - return r2; - }, t2.decodeDelimited = function(t3) { - return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); - }, t2.verify = function(t3) { - return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain) ? "domain: string expected" : null != t3.version && t3.hasOwnProperty("version") && !(c.isInteger(t3.version) || t3.version && c.isInteger(t3.version.low) && c.isInteger(t3.version.high)) ? "version: integer|Long expected" : null; - }, t2.fromObject = function(t3) { - if (t3 instanceof l.onnx.OperatorSetIdProto) - return t3; - var e2 = new l.onnx.OperatorSetIdProto(); - return null != t3.domain && (e2.domain = String(t3.domain)), null != t3.version && (c.Long ? (e2.version = c.Long.fromValue(t3.version)).unsigned = false : "string" == typeof t3.version ? e2.version = parseInt(t3.version, 10) : "number" == typeof t3.version ? e2.version = t3.version : "object" == typeof t3.version && (e2.version = new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber())), e2; - }, t2.toObject = function(t3, e2) { - e2 || (e2 = {}); - var n2 = {}; - if (e2.defaults) - if (n2.domain = "", c.Long) { - var r2 = new c.Long(0, 0, false); - n2.version = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; - } else - n2.version = e2.longs === String ? "0" : 0; - return null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.version && t3.hasOwnProperty("version") && ("number" == typeof t3.version ? n2.version = e2.longs === String ? String(t3.version) : t3.version : n2.version = e2.longs === String ? c.Long.prototype.toString.call(t3.version) : e2.longs === Number ? new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber() : t3.version), n2; - }, t2.prototype.toJSON = function() { - return this.constructor.toObject(this, a.util.toJSONOptions); - }, t2; - }(), o), t.exports = l; - }, 2100: (t, e, n) => { - "use strict"; - t.exports = n(9482); - }, 9482: (t, e, n) => { - "use strict"; - var r = e; - function i() { - r.util._configure(), r.Writer._configure(r.BufferWriter), r.Reader._configure(r.BufferReader); - } - r.build = "minimal", r.Writer = n(1173), r.BufferWriter = n(3155), r.Reader = n(1408), r.BufferReader = n(593), r.util = n(9693), r.rpc = n(5994), r.roots = n(5054), r.configure = i, i(); - }, 1408: (t, e, n) => { - "use strict"; - t.exports = u; - var r, i = n(9693), o = i.LongBits, a = i.utf8; - function s(t2, e2) { - return RangeError("index out of range: " + t2.pos + " + " + (e2 || 1) + " > " + t2.len); - } - function u(t2) { - this.buf = t2, this.pos = 0, this.len = t2.length; - } - var c, l = "undefined" != typeof Uint8Array ? function(t2) { - if (t2 instanceof Uint8Array || Array.isArray(t2)) - return new u(t2); - throw Error("illegal buffer"); - } : function(t2) { - if (Array.isArray(t2)) - return new u(t2); - throw Error("illegal buffer"); - }, p = function() { - return i.Buffer ? function(t2) { - return (u.create = function(t3) { - return i.Buffer.isBuffer(t3) ? new r(t3) : l(t3); - })(t2); - } : l; - }; - function f() { - var t2 = new o(0, 0), e2 = 0; - if (!(this.len - this.pos > 4)) { - for (; e2 < 3; ++e2) { - if (this.pos >= this.len) - throw s(this); - if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) - return t2; - } - return t2.lo = (t2.lo | (127 & this.buf[this.pos++]) << 7 * e2) >>> 0, t2; - } - for (; e2 < 4; ++e2) - if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) - return t2; - if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 28) >>> 0, t2.hi = (t2.hi | (127 & this.buf[this.pos]) >> 4) >>> 0, this.buf[this.pos++] < 128) - return t2; - if (e2 = 0, this.len - this.pos > 4) { - for (; e2 < 5; ++e2) - if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) - return t2; - } else - for (; e2 < 5; ++e2) { - if (this.pos >= this.len) - throw s(this); - if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) - return t2; - } - throw Error("invalid varint encoding"); - } - function d(t2, e2) { - return (t2[e2 - 4] | t2[e2 - 3] << 8 | t2[e2 - 2] << 16 | t2[e2 - 1] << 24) >>> 0; - } - function h() { - if (this.pos + 8 > this.len) - throw s(this, 8); - return new o(d(this.buf, this.pos += 4), d(this.buf, this.pos += 4)); - } - u.create = p(), u.prototype._slice = i.Array.prototype.subarray || i.Array.prototype.slice, u.prototype.uint32 = (c = 4294967295, function() { - if (c = (127 & this.buf[this.pos]) >>> 0, this.buf[this.pos++] < 128) - return c; - if (c = (c | (127 & this.buf[this.pos]) << 7) >>> 0, this.buf[this.pos++] < 128) - return c; - if (c = (c | (127 & this.buf[this.pos]) << 14) >>> 0, this.buf[this.pos++] < 128) - return c; - if (c = (c | (127 & this.buf[this.pos]) << 21) >>> 0, this.buf[this.pos++] < 128) - return c; - if (c = (c | (15 & this.buf[this.pos]) << 28) >>> 0, this.buf[this.pos++] < 128) - return c; - if ((this.pos += 5) > this.len) - throw this.pos = this.len, s(this, 10); - return c; - }), u.prototype.int32 = function() { - return 0 | this.uint32(); - }, u.prototype.sint32 = function() { - var t2 = this.uint32(); - return t2 >>> 1 ^ -(1 & t2) | 0; - }, u.prototype.bool = function() { - return 0 !== this.uint32(); - }, u.prototype.fixed32 = function() { - if (this.pos + 4 > this.len) - throw s(this, 4); - return d(this.buf, this.pos += 4); - }, u.prototype.sfixed32 = function() { - if (this.pos + 4 > this.len) - throw s(this, 4); - return 0 | d(this.buf, this.pos += 4); - }, u.prototype.float = function() { - if (this.pos + 4 > this.len) - throw s(this, 4); - var t2 = i.float.readFloatLE(this.buf, this.pos); - return this.pos += 4, t2; - }, u.prototype.double = function() { - if (this.pos + 8 > this.len) - throw s(this, 4); - var t2 = i.float.readDoubleLE(this.buf, this.pos); - return this.pos += 8, t2; - }, u.prototype.bytes = function() { - var t2 = this.uint32(), e2 = this.pos, n2 = this.pos + t2; - if (n2 > this.len) - throw s(this, t2); - return this.pos += t2, Array.isArray(this.buf) ? this.buf.slice(e2, n2) : e2 === n2 ? new this.buf.constructor(0) : this._slice.call(this.buf, e2, n2); - }, u.prototype.string = function() { - var t2 = this.bytes(); - return a.read(t2, 0, t2.length); - }, u.prototype.skip = function(t2) { - if ("number" == typeof t2) { - if (this.pos + t2 > this.len) - throw s(this, t2); - this.pos += t2; - } else - do { - if (this.pos >= this.len) - throw s(this); - } while (128 & this.buf[this.pos++]); - return this; - }, u.prototype.skipType = function(t2) { - switch (t2) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - for (; 4 != (t2 = 7 & this.uint32()); ) - this.skipType(t2); - break; - case 5: - this.skip(4); - break; - default: - throw Error("invalid wire type " + t2 + " at offset " + this.pos); - } - return this; - }, u._configure = function(t2) { - r = t2, u.create = p(), r._configure(); - var e2 = i.Long ? "toLong" : "toNumber"; - i.merge(u.prototype, { int64: function() { - return f.call(this)[e2](false); - }, uint64: function() { - return f.call(this)[e2](true); - }, sint64: function() { - return f.call(this).zzDecode()[e2](false); - }, fixed64: function() { - return h.call(this)[e2](true); - }, sfixed64: function() { - return h.call(this)[e2](false); - } }); - }; - }, 593: (t, e, n) => { - "use strict"; - t.exports = o; - var r = n(1408); - (o.prototype = Object.create(r.prototype)).constructor = o; - var i = n(9693); - function o(t2) { - r.call(this, t2); - } - o._configure = function() { - i.Buffer && (o.prototype._slice = i.Buffer.prototype.slice); - }, o.prototype.string = function() { - var t2 = this.uint32(); - return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + t2, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + t2, this.len)); - }, o._configure(); - }, 5054: (t) => { - "use strict"; - t.exports = {}; - }, 5994: (t, e, n) => { - "use strict"; - e.Service = n(7948); - }, 7948: (t, e, n) => { - "use strict"; - t.exports = i; - var r = n(9693); - function i(t2, e2, n2) { - if ("function" != typeof t2) - throw TypeError("rpcImpl must be a function"); - r.EventEmitter.call(this), this.rpcImpl = t2, this.requestDelimited = Boolean(e2), this.responseDelimited = Boolean(n2); - } - (i.prototype = Object.create(r.EventEmitter.prototype)).constructor = i, i.prototype.rpcCall = function t2(e2, n2, i2, o, a) { - if (!o) - throw TypeError("request must be specified"); - var s = this; - if (!a) - return r.asPromise(t2, s, e2, n2, i2, o); - if (s.rpcImpl) - try { - return s.rpcImpl(e2, n2[s.requestDelimited ? "encodeDelimited" : "encode"](o).finish(), function(t3, n3) { - if (t3) - return s.emit("error", t3, e2), a(t3); - if (null !== n3) { - if (!(n3 instanceof i2)) - try { - n3 = i2[s.responseDelimited ? "decodeDelimited" : "decode"](n3); - } catch (t4) { - return s.emit("error", t4, e2), a(t4); - } - return s.emit("data", n3, e2), a(null, n3); - } - s.end(true); - }); - } catch (t3) { - return s.emit("error", t3, e2), void setTimeout(function() { - a(t3); - }, 0); - } - else - setTimeout(function() { - a(Error("already ended")); - }, 0); - }, i.prototype.end = function(t2) { - return this.rpcImpl && (t2 || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this; - }; - }, 1945: (t, e, n) => { - "use strict"; - t.exports = i; - var r = n(9693); - function i(t2, e2) { - this.lo = t2 >>> 0, this.hi = e2 >>> 0; - } - var o = i.zero = new i(0, 0); - o.toNumber = function() { - return 0; - }, o.zzEncode = o.zzDecode = function() { - return this; - }, o.length = function() { - return 1; - }; - var a = i.zeroHash = "\0\0\0\0\0\0\0\0"; - i.fromNumber = function(t2) { - if (0 === t2) - return o; - var e2 = t2 < 0; - e2 && (t2 = -t2); - var n2 = t2 >>> 0, r2 = (t2 - n2) / 4294967296 >>> 0; - return e2 && (r2 = ~r2 >>> 0, n2 = ~n2 >>> 0, ++n2 > 4294967295 && (n2 = 0, ++r2 > 4294967295 && (r2 = 0))), new i(n2, r2); - }, i.from = function(t2) { - if ("number" == typeof t2) - return i.fromNumber(t2); - if (r.isString(t2)) { - if (!r.Long) - return i.fromNumber(parseInt(t2, 10)); - t2 = r.Long.fromString(t2); - } - return t2.low || t2.high ? new i(t2.low >>> 0, t2.high >>> 0) : o; - }, i.prototype.toNumber = function(t2) { - if (!t2 && this.hi >>> 31) { - var e2 = 1 + ~this.lo >>> 0, n2 = ~this.hi >>> 0; - return e2 || (n2 = n2 + 1 >>> 0), -(e2 + 4294967296 * n2); - } - return this.lo + 4294967296 * this.hi; - }, i.prototype.toLong = function(t2) { - return r.Long ? new r.Long(0 | this.lo, 0 | this.hi, Boolean(t2)) : { low: 0 | this.lo, high: 0 | this.hi, unsigned: Boolean(t2) }; - }; - var s = String.prototype.charCodeAt; - i.fromHash = function(t2) { - return t2 === a ? o : new i((s.call(t2, 0) | s.call(t2, 1) << 8 | s.call(t2, 2) << 16 | s.call(t2, 3) << 24) >>> 0, (s.call(t2, 4) | s.call(t2, 5) << 8 | s.call(t2, 6) << 16 | s.call(t2, 7) << 24) >>> 0); - }, i.prototype.toHash = function() { - return String.fromCharCode(255 & this.lo, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, 255 & this.hi, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24); - }, i.prototype.zzEncode = function() { - var t2 = this.hi >> 31; - return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ t2) >>> 0, this.lo = (this.lo << 1 ^ t2) >>> 0, this; - }, i.prototype.zzDecode = function() { - var t2 = -(1 & this.lo); - return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ t2) >>> 0, this.hi = (this.hi >>> 1 ^ t2) >>> 0, this; - }, i.prototype.length = function() { - var t2 = this.lo, e2 = (this.lo >>> 28 | this.hi << 4) >>> 0, n2 = this.hi >>> 24; - return 0 === n2 ? 0 === e2 ? t2 < 16384 ? t2 < 128 ? 1 : 2 : t2 < 2097152 ? 3 : 4 : e2 < 16384 ? e2 < 128 ? 5 : 6 : e2 < 2097152 ? 7 : 8 : n2 < 128 ? 9 : 10; - }; - }, 9693: function(t, e, n) { - "use strict"; - var r = e; - function i(t2, e2, n2) { - for (var r2 = Object.keys(e2), i2 = 0; i2 < r2.length; ++i2) - void 0 !== t2[r2[i2]] && n2 || (t2[r2[i2]] = e2[r2[i2]]); - return t2; - } - function o(t2) { - function e2(t3, n2) { - if (!(this instanceof e2)) - return new e2(t3, n2); - Object.defineProperty(this, "message", { get: function() { - return t3; - } }), Error.captureStackTrace ? Error.captureStackTrace(this, e2) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), n2 && i(this, n2); - } - return (e2.prototype = Object.create(Error.prototype)).constructor = e2, Object.defineProperty(e2.prototype, "name", { get: function() { - return t2; - } }), e2.prototype.toString = function() { - return this.name + ": " + this.message; - }, e2; - } - r.asPromise = n(4537), r.base64 = n(7419), r.EventEmitter = n(9211), r.float = n(945), r.inquire = n(7199), r.utf8 = n(4997), r.pool = n(6662), r.LongBits = n(1945), r.isNode = Boolean(void 0 !== n.g && n.g && n.g.process && n.g.process.versions && n.g.process.versions.node), r.global = r.isNode && n.g || "undefined" != typeof window && window || "undefined" != typeof self && self || this, r.emptyArray = Object.freeze ? Object.freeze([]) : [], r.emptyObject = Object.freeze ? Object.freeze({}) : {}, r.isInteger = Number.isInteger || function(t2) { - return "number" == typeof t2 && isFinite(t2) && Math.floor(t2) === t2; - }, r.isString = function(t2) { - return "string" == typeof t2 || t2 instanceof String; - }, r.isObject = function(t2) { - return t2 && "object" == typeof t2; - }, r.isset = r.isSet = function(t2, e2) { - var n2 = t2[e2]; - return !(null == n2 || !t2.hasOwnProperty(e2)) && ("object" != typeof n2 || (Array.isArray(n2) ? n2.length : Object.keys(n2).length) > 0); - }, r.Buffer = function() { - try { - var t2 = r.inquire("buffer").Buffer; - return t2.prototype.utf8Write ? t2 : null; - } catch (t3) { - return null; - } - }(), r._Buffer_from = null, r._Buffer_allocUnsafe = null, r.newBuffer = function(t2) { - return "number" == typeof t2 ? r.Buffer ? r._Buffer_allocUnsafe(t2) : new r.Array(t2) : r.Buffer ? r._Buffer_from(t2) : "undefined" == typeof Uint8Array ? t2 : new Uint8Array(t2); - }, r.Array = "undefined" != typeof Uint8Array ? Uint8Array : Array, r.Long = r.global.dcodeIO && r.global.dcodeIO.Long || r.global.Long || r.inquire("long"), r.key2Re = /^true|false|0|1$/, r.key32Re = /^-?(?:0|[1-9][0-9]*)$/, r.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/, r.longToHash = function(t2) { - return t2 ? r.LongBits.from(t2).toHash() : r.LongBits.zeroHash; - }, r.longFromHash = function(t2, e2) { - var n2 = r.LongBits.fromHash(t2); - return r.Long ? r.Long.fromBits(n2.lo, n2.hi, e2) : n2.toNumber(Boolean(e2)); - }, r.merge = i, r.lcFirst = function(t2) { - return t2.charAt(0).toLowerCase() + t2.substring(1); - }, r.newError = o, r.ProtocolError = o("ProtocolError"), r.oneOfGetter = function(t2) { - for (var e2 = {}, n2 = 0; n2 < t2.length; ++n2) - e2[t2[n2]] = 1; - return function() { - for (var t3 = Object.keys(this), n3 = t3.length - 1; n3 > -1; --n3) - if (1 === e2[t3[n3]] && void 0 !== this[t3[n3]] && null !== this[t3[n3]]) - return t3[n3]; - }; - }, r.oneOfSetter = function(t2) { - return function(e2) { - for (var n2 = 0; n2 < t2.length; ++n2) - t2[n2] !== e2 && delete this[t2[n2]]; - }; - }, r.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }, r._configure = function() { - var t2 = r.Buffer; - t2 ? (r._Buffer_from = t2.from !== Uint8Array.from && t2.from || function(e2, n2) { - return new t2(e2, n2); - }, r._Buffer_allocUnsafe = t2.allocUnsafe || function(e2) { - return new t2(e2); - }) : r._Buffer_from = r._Buffer_allocUnsafe = null; - }; - }, 1173: (t, e, n) => { - "use strict"; - t.exports = p; - var r, i = n(9693), o = i.LongBits, a = i.base64, s = i.utf8; - function u(t2, e2, n2) { - this.fn = t2, this.len = e2, this.next = void 0, this.val = n2; - } - function c() { - } - function l(t2) { - this.head = t2.head, this.tail = t2.tail, this.len = t2.len, this.next = t2.states; - } - function p() { - this.len = 0, this.head = new u(c, 0, 0), this.tail = this.head, this.states = null; - } - var f = function() { - return i.Buffer ? function() { - return (p.create = function() { - return new r(); - })(); - } : function() { - return new p(); - }; - }; - function d(t2, e2, n2) { - e2[n2] = 255 & t2; - } - function h(t2, e2) { - this.len = t2, this.next = void 0, this.val = e2; - } - function g(t2, e2, n2) { - for (; t2.hi; ) - e2[n2++] = 127 & t2.lo | 128, t2.lo = (t2.lo >>> 7 | t2.hi << 25) >>> 0, t2.hi >>>= 7; - for (; t2.lo > 127; ) - e2[n2++] = 127 & t2.lo | 128, t2.lo = t2.lo >>> 7; - e2[n2++] = t2.lo; - } - function b(t2, e2, n2) { - e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24; - } - p.create = f(), p.alloc = function(t2) { - return new i.Array(t2); - }, i.Array !== Array && (p.alloc = i.pool(p.alloc, i.Array.prototype.subarray)), p.prototype._push = function(t2, e2, n2) { - return this.tail = this.tail.next = new u(t2, e2, n2), this.len += e2, this; - }, h.prototype = Object.create(u.prototype), h.prototype.fn = function(t2, e2, n2) { - for (; t2 > 127; ) - e2[n2++] = 127 & t2 | 128, t2 >>>= 7; - e2[n2] = t2; - }, p.prototype.uint32 = function(t2) { - return this.len += (this.tail = this.tail.next = new h((t2 >>>= 0) < 128 ? 1 : t2 < 16384 ? 2 : t2 < 2097152 ? 3 : t2 < 268435456 ? 4 : 5, t2)).len, this; - }, p.prototype.int32 = function(t2) { - return t2 < 0 ? this._push(g, 10, o.fromNumber(t2)) : this.uint32(t2); - }, p.prototype.sint32 = function(t2) { - return this.uint32((t2 << 1 ^ t2 >> 31) >>> 0); - }, p.prototype.uint64 = function(t2) { - var e2 = o.from(t2); - return this._push(g, e2.length(), e2); - }, p.prototype.int64 = p.prototype.uint64, p.prototype.sint64 = function(t2) { - var e2 = o.from(t2).zzEncode(); - return this._push(g, e2.length(), e2); - }, p.prototype.bool = function(t2) { - return this._push(d, 1, t2 ? 1 : 0); - }, p.prototype.fixed32 = function(t2) { - return this._push(b, 4, t2 >>> 0); - }, p.prototype.sfixed32 = p.prototype.fixed32, p.prototype.fixed64 = function(t2) { - var e2 = o.from(t2); - return this._push(b, 4, e2.lo)._push(b, 4, e2.hi); - }, p.prototype.sfixed64 = p.prototype.fixed64, p.prototype.float = function(t2) { - return this._push(i.float.writeFloatLE, 4, t2); - }, p.prototype.double = function(t2) { - return this._push(i.float.writeDoubleLE, 8, t2); - }; - var m = i.Array.prototype.set ? function(t2, e2, n2) { - e2.set(t2, n2); - } : function(t2, e2, n2) { - for (var r2 = 0; r2 < t2.length; ++r2) - e2[n2 + r2] = t2[r2]; - }; - p.prototype.bytes = function(t2) { - var e2 = t2.length >>> 0; - if (!e2) - return this._push(d, 1, 0); - if (i.isString(t2)) { - var n2 = p.alloc(e2 = a.length(t2)); - a.decode(t2, n2, 0), t2 = n2; - } - return this.uint32(e2)._push(m, e2, t2); - }, p.prototype.string = function(t2) { - var e2 = s.length(t2); - return e2 ? this.uint32(e2)._push(s.write, e2, t2) : this._push(d, 1, 0); - }, p.prototype.fork = function() { - return this.states = new l(this), this.head = this.tail = new u(c, 0, 0), this.len = 0, this; - }, p.prototype.reset = function() { - return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new u(c, 0, 0), this.len = 0), this; - }, p.prototype.ldelim = function() { - var t2 = this.head, e2 = this.tail, n2 = this.len; - return this.reset().uint32(n2), n2 && (this.tail.next = t2.next, this.tail = e2, this.len += n2), this; - }, p.prototype.finish = function() { - for (var t2 = this.head.next, e2 = this.constructor.alloc(this.len), n2 = 0; t2; ) - t2.fn(t2.val, e2, n2), n2 += t2.len, t2 = t2.next; - return e2; - }, p._configure = function(t2) { - r = t2, p.create = f(), r._configure(); - }; - }, 3155: (t, e, n) => { - "use strict"; - t.exports = o; - var r = n(1173); - (o.prototype = Object.create(r.prototype)).constructor = o; - var i = n(9693); - function o() { - r.call(this); - } - function a(t2, e2, n2) { - t2.length < 40 ? i.utf8.write(t2, e2, n2) : e2.utf8Write ? e2.utf8Write(t2, n2) : e2.write(t2, n2); - } - o._configure = function() { - o.alloc = i._Buffer_allocUnsafe, o.writeBytesBuffer = i.Buffer && i.Buffer.prototype instanceof Uint8Array && "set" === i.Buffer.prototype.set.name ? function(t2, e2, n2) { - e2.set(t2, n2); - } : function(t2, e2, n2) { - if (t2.copy) - t2.copy(e2, n2, 0, t2.length); - else - for (var r2 = 0; r2 < t2.length; ) - e2[n2++] = t2[r2++]; - }; - }, o.prototype.bytes = function(t2) { - i.isString(t2) && (t2 = i._Buffer_from(t2, "base64")); - var e2 = t2.length >>> 0; - return this.uint32(e2), e2 && this._push(o.writeBytesBuffer, e2, t2), this; - }, o.prototype.string = function(t2) { - var e2 = i.Buffer.byteLength(t2); - return this.uint32(e2), e2 && this._push(a, e2, t2), this; - }, o._configure(); - }, 7714: (t, e, n) => { - "use strict"; - e.R = void 0; - const r = n(6919), i = n(7448); - e.R = new class { - async init() { - } - async createSessionHandler(t2, e2) { - const n2 = new r.Session(e2); - return await n2.loadModel(t2), new i.OnnxjsSessionHandler(n2); - } - }(); - }, 4200: (t, e, n) => { - "use strict"; - e.c8 = e.rX = void 0; - const r = n(1670), i = n(5381), o = n(2157), a = n(2306); - e.rX = () => { - if (("number" != typeof r.env.wasm.initTimeout || r.env.wasm.initTimeout < 0) && (r.env.wasm.initTimeout = 0), "boolean" != typeof r.env.wasm.simd && (r.env.wasm.simd = true), "boolean" != typeof r.env.wasm.proxy && (r.env.wasm.proxy = false), "number" != typeof r.env.wasm.numThreads || !Number.isInteger(r.env.wasm.numThreads) || r.env.wasm.numThreads <= 0) { - const t2 = "undefined" == typeof navigator ? (0, i.cpus)().length : navigator.hardwareConcurrency; - r.env.wasm.numThreads = Math.min(4, Math.ceil((t2 || 1) / 2)); - } - }, e.c8 = new class { - async init() { - (0, e.rX)(), await (0, o.initWasm)(); - } - async createSessionHandler(t2, e2) { - const n2 = new a.OnnxruntimeWebAssemblySessionHandler(); - return await n2.loadModel(t2, e2), Promise.resolve(n2); - } - }(); - }, 6018: function(t, e, n) { - "use strict"; - var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2); - var i2 = Object.getOwnPropertyDescriptor(e2, n2); - i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { - return e2[n2]; - } }), Object.defineProperty(t2, r2, i2); - } : function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; - }), i = this && this.__exportStar || function(t2, e2) { - for (var n2 in t2) - "default" === n2 || Object.prototype.hasOwnProperty.call(e2, n2) || r(e2, t2, n2); - }; - Object.defineProperty(e, "__esModule", { value: true }), i(n(1670), e); - const o = n(1670); - { - const t2 = n(7714).R; - (0, o.registerBackend)("webgl", t2, -10); - } - { - const t2 = n(4200).c8; - (0, o.registerBackend)("cpu", t2, 10), (0, o.registerBackend)("wasm", t2, 10), (0, o.registerBackend)("xnnpack", t2, 9); - } - }, 246: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createAttributeWithCacheKey = void 0; - class n { - constructor(t2) { - Object.assign(this, t2); - } - get cacheKey() { - return this._cacheKey || (this._cacheKey = Object.getOwnPropertyNames(this).sort().map((t2) => `${this[t2]}`).join(";")), this._cacheKey; - } - } - e.createAttributeWithCacheKey = (t2) => new n(t2); - }, 7778: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.Attribute = void 0; - const r = n(1446), i = n(9395), o = n(9162), a = n(2517); - var s = i.onnxruntime.experimental.fbs; - class u { - constructor(t2) { - if (this._attributes = /* @__PURE__ */ new Map(), null != t2) { - for (const e2 of t2) - e2 instanceof r.onnx.AttributeProto ? this._attributes.set(e2.name, [u.getValue(e2), u.getType(e2)]) : e2 instanceof s.Attribute && this._attributes.set(e2.name(), [u.getValue(e2), u.getType(e2)]); - if (this._attributes.size < t2.length) - throw new Error("duplicated attribute names"); - } - } - set(t2, e2, n2) { - this._attributes.set(t2, [n2, e2]); - } - delete(t2) { - this._attributes.delete(t2); - } - getFloat(t2, e2) { - return this.get(t2, "float", e2); - } - getInt(t2, e2) { - return this.get(t2, "int", e2); - } - getString(t2, e2) { - return this.get(t2, "string", e2); - } - getTensor(t2, e2) { - return this.get(t2, "tensor", e2); - } - getFloats(t2, e2) { - return this.get(t2, "floats", e2); - } - getInts(t2, e2) { - return this.get(t2, "ints", e2); - } - getStrings(t2, e2) { - return this.get(t2, "strings", e2); - } - getTensors(t2, e2) { - return this.get(t2, "tensors", e2); - } - get(t2, e2, n2) { - const r2 = this._attributes.get(t2); - if (void 0 === r2) { - if (void 0 !== n2) - return n2; - throw new Error(`required attribute not found: ${t2}`); - } - if (r2[1] !== e2) - throw new Error(`type mismatch: expected ${e2} but got ${r2[1]}`); - return r2[0]; - } - static getType(t2) { - const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type(); - switch (e2) { - case r.onnx.AttributeProto.AttributeType.FLOAT: - return "float"; - case r.onnx.AttributeProto.AttributeType.INT: - return "int"; - case r.onnx.AttributeProto.AttributeType.STRING: - return "string"; - case r.onnx.AttributeProto.AttributeType.TENSOR: - return "tensor"; - case r.onnx.AttributeProto.AttributeType.FLOATS: - return "floats"; - case r.onnx.AttributeProto.AttributeType.INTS: - return "ints"; - case r.onnx.AttributeProto.AttributeType.STRINGS: - return "strings"; - case r.onnx.AttributeProto.AttributeType.TENSORS: - return "tensors"; - default: - throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[e2]}`); - } - } - static getValue(t2) { - const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type(); - if (e2 === r.onnx.AttributeProto.AttributeType.GRAPH || e2 === r.onnx.AttributeProto.AttributeType.GRAPHS) - throw new Error("graph attribute is not supported yet"); - const n2 = this.getValueNoCheck(t2); - if (e2 === r.onnx.AttributeProto.AttributeType.INT && a.LongUtil.isLong(n2)) - return a.LongUtil.longToNumber(n2); - if (e2 === r.onnx.AttributeProto.AttributeType.INTS) { - const t3 = n2, e3 = new Array(t3.length); - for (let n3 = 0; n3 < t3.length; n3++) { - const r2 = t3[n3]; - e3[n3] = a.LongUtil.longToNumber(r2); - } - return e3; - } - if (e2 === r.onnx.AttributeProto.AttributeType.TENSOR) - return t2 instanceof r.onnx.AttributeProto ? o.Tensor.fromProto(n2) : o.Tensor.fromOrtTensor(n2); - if (e2 === r.onnx.AttributeProto.AttributeType.TENSORS) { - if (t2 instanceof r.onnx.AttributeProto) - return n2.map((t3) => o.Tensor.fromProto(t3)); - if (t2 instanceof s.Attribute) - return n2.map((t3) => o.Tensor.fromOrtTensor(t3)); - } - if (e2 === r.onnx.AttributeProto.AttributeType.STRING && t2 instanceof r.onnx.AttributeProto) { - const t3 = n2; - return (0, a.decodeUtf8String)(t3); - } - return e2 === r.onnx.AttributeProto.AttributeType.STRINGS && t2 instanceof r.onnx.AttributeProto ? n2.map(a.decodeUtf8String) : n2; - } - static getValueNoCheck(t2) { - return t2 instanceof r.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(t2) : this.getValueNoCheckFromOrtFormat(t2); - } - static getValueNoCheckFromOnnxFormat(t2) { - switch (t2.type) { - case r.onnx.AttributeProto.AttributeType.FLOAT: - return t2.f; - case r.onnx.AttributeProto.AttributeType.INT: - return t2.i; - case r.onnx.AttributeProto.AttributeType.STRING: - return t2.s; - case r.onnx.AttributeProto.AttributeType.TENSOR: - return t2.t; - case r.onnx.AttributeProto.AttributeType.GRAPH: - return t2.g; - case r.onnx.AttributeProto.AttributeType.FLOATS: - return t2.floats; - case r.onnx.AttributeProto.AttributeType.INTS: - return t2.ints; - case r.onnx.AttributeProto.AttributeType.STRINGS: - return t2.strings; - case r.onnx.AttributeProto.AttributeType.TENSORS: - return t2.tensors; - case r.onnx.AttributeProto.AttributeType.GRAPHS: - return t2.graphs; - default: - throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t2.type]}`); - } - } - static getValueNoCheckFromOrtFormat(t2) { - switch (t2.type()) { - case s.AttributeType.FLOAT: - return t2.f(); - case s.AttributeType.INT: - return t2.i(); - case s.AttributeType.STRING: - return t2.s(); - case s.AttributeType.TENSOR: - return t2.t(); - case s.AttributeType.GRAPH: - return t2.g(); - case s.AttributeType.FLOATS: - return t2.floatsArray(); - case s.AttributeType.INTS: { - const e2 = []; - for (let n2 = 0; n2 < t2.intsLength(); n2++) - e2.push(t2.ints(n2)); - return e2; - } - case s.AttributeType.STRINGS: { - const e2 = []; - for (let n2 = 0; n2 < t2.stringsLength(); n2++) - e2.push(t2.strings(n2)); - return e2; - } - case s.AttributeType.TENSORS: { - const e2 = []; - for (let n2 = 0; n2 < t2.tensorsLength(); n2++) - e2.push(t2.tensors(n2)); - return e2; - } - default: - throw new Error(`unsupported attribute type: ${s.AttributeType[t2.type()]}`); - } - } - } - e.Attribute = u; - }, 7091: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.resolveBackend = e.backend = void 0; - const r = n(5038), i = /* @__PURE__ */ new Map(); - async function o(t2) { - const n2 = e.backend; - if (void 0 !== n2[t2] && function(t3) { - const e2 = t3; - return "initialize" in e2 && "function" == typeof e2.initialize && "createSessionHandler" in e2 && "function" == typeof e2.createSessionHandler && "dispose" in e2 && "function" == typeof e2.dispose; - }(n2[t2])) { - const e2 = n2[t2]; - let r2 = e2.initialize(); - if ("object" == typeof r2 && "then" in r2 && (r2 = await r2), r2) - return i.set(t2, e2), e2; - } - } - e.backend = { webgl: new r.WebGLBackend() }, e.resolveBackend = async function t2(e2) { - if (!e2) - return t2(["webgl"]); - { - const t3 = "string" == typeof e2 ? [e2] : e2; - for (const e3 of t3) { - const t4 = i.get(e3); - if (t4) - return t4; - const n2 = await o(e3); - if (n2) - return n2; - } - } - throw new Error("no available backend to use"); - }; - }, 5038: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.WebGLBackend = void 0; - const r = n(1670), i = n(6231), o = n(6416), a = n(7305); - e.WebGLBackend = class { - get contextId() { - return r.env.webgl.contextId; - } - set contextId(t2) { - r.env.webgl.contextId = t2; - } - get matmulMaxBatchSize() { - return r.env.webgl.matmulMaxBatchSize; - } - set matmulMaxBatchSize(t2) { - r.env.webgl.matmulMaxBatchSize = t2; - } - get textureCacheMode() { - return r.env.webgl.textureCacheMode; - } - set textureCacheMode(t2) { - r.env.webgl.textureCacheMode = t2; - } - get pack() { - return r.env.webgl.pack; - } - set pack(t2) { - r.env.webgl.pack = t2; - } - get async() { - return r.env.webgl.async; - } - set async(t2) { - r.env.webgl.async = t2; - } - initialize() { - try { - return this.glContext = (0, a.createWebGLContext)(this.contextId), "number" != typeof this.matmulMaxBatchSize && (this.matmulMaxBatchSize = 16), "string" != typeof this.textureCacheMode && (this.textureCacheMode = "full"), "boolean" != typeof this.pack && (this.pack = false), "boolean" != typeof this.async && (this.async = false), i.Logger.setWithEnv(r.env), i.Logger.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), true; - } catch (t2) { - return i.Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${t2}`), false; - } - } - createSessionHandler(t2) { - return new o.WebGLSessionHandler(this, t2); - } - dispose() { - this.glContext.dispose(); - } - }; - }, 5107: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.CoordsGlslLib = void 0; - const r = n(2517), i = n(8520), o = n(5060), a = n(7859), s = n(9390); - class u extends i.GlslLib { - constructor(t2) { - super(t2); - } - getFunctions() { - return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet()); - } - getCustomTypes() { - return {}; - } - offsetToCoords() { - return { offsetToCoords: new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ") }; - } - coordsToOffset() { - return { coordsToOffset: new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ") }; - } - getOutputSamplingSnippet() { - const t2 = this.context.outputTextureLayout; - return t2.isPacked ? this.getPackedOutputSamplingSnippet(t2) : this.getUnpackedOutputSamplingSnippet(t2); - } - getPackedOutputSamplingSnippet(t2) { - const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords"; - switch (e2.length) { - case 0: - r2[a2] = this.getOutputScalarCoords(); - break; - case 1: - r2[a2] = this.getOutputPacked1DCoords(e2, n2); - break; - case 2: - r2[a2] = this.getOutputPacked2DCoords(e2, n2); - break; - case 3: - r2[a2] = this.getOutputPacked3DCoords(e2, n2); - break; - default: - r2[a2] = this.getOutputPackedNDCoords(e2, n2); - } - const s2 = ` - void setOutput(vec4 val) { - ${(0, o.getGlsl)(this.context.glContext.version).output} = val; - } - `; - return r2.floatTextureSetRGBA = new i.GlslLibRoutine(s2), r2; - } - getUnpackedOutputSamplingSnippet(t2) { - const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords"; - switch (e2.length) { - case 0: - r2[a2] = this.getOutputScalarCoords(); - break; - case 1: - r2[a2] = this.getOutputUnpacked1DCoords(e2, n2); - break; - case 2: - r2[a2] = this.getOutputUnpacked2DCoords(e2, n2); - break; - case 3: - r2[a2] = this.getOutputUnpacked3DCoords(e2, n2); - break; - case 4: - r2[a2] = this.getOutputUnpacked4DCoords(e2, n2); - break; - case 5: - r2[a2] = this.getOutputUnpacked5DCoords(e2, n2); - break; - case 6: - r2[a2] = this.getOutputUnpacked6DCoords(e2, n2); - break; - default: - throw new Error(`Unsupported output dimensionality: ${e2.length}`); - } - const s2 = ` - void setOutput(float val) { - ${(0, o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); - } - `; - return r2.floatTextureSetR = new i.GlslLibRoutine(s2), r2; - } - getOutputScalarCoords() { - return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n "); - } - getOutputPacked1DCoords(t2, e2) { - const n2 = e2; - let r2 = ""; - return 1 === n2[0] ? (r2 = ` - int getOutputCoords() { - return 2 * int(TexCoords.y * ${n2[1]}.0); - } - `, new i.GlslLibRoutine(r2)) : 1 === n2[1] ? (r2 = ` - int getOutputCoords() { - return 2 * int(TexCoords.x * ${n2[0]}.0); - } - `, new i.GlslLibRoutine(r2)) : (r2 = ` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${n2[0]}, ${n2[1]})); - return 2 * (resTexRC.y * ${n2[0]} + resTexRC.x); - } - `, new i.GlslLibRoutine(r2)); - } - getOutputPacked2DCoords(t2, e2) { - let n2 = ""; - if (r.ArrayUtil.arraysEqual(t2, e2)) - return n2 = ` - ivec2 getOutputCoords() { - return 2 * ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); - } - `, new i.GlslLibRoutine(n2); - const o2 = e2, a2 = Math.ceil(t2[1] / 2); - return n2 = ` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${o2[0]}, ${o2[1]})); - - int index = resTexRC.y * ${o2[0]} + resTexRC.x; - - // reverse r and c order for packed texture - int r = imod(index, ${a2}) * 2; - int c = 2 * (index / ${a2}); - - return ivec2(r, c); - } - `, new i.GlslLibRoutine(n2); - } - getOutputPacked3DCoords(t2, e2) { - const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[2] / 2), o2 = r2 * Math.ceil(t2[1] / 2), a2 = ` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${n2[0]}, ${n2[1]})); - int index = resTexRC.y * ${n2[0]} + resTexRC.x; - - int b = index / ${o2}; - index -= b * ${o2}; - - // reverse r and c order for packed texture - int r = imod(index, ${r2}) * 2; - int c = 2 * (index / ${r2}); - - return ivec3(b, r, c); - } - `; - return new i.GlslLibRoutine(a2); - } - getOutputPackedNDCoords(t2, e2) { - const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[t2.length - 1] / 2), o2 = r2 * Math.ceil(t2[t2.length - 2] / 2); - let a2 = o2, s2 = "", u2 = "b, r, c"; - for (let e3 = 2; e3 < t2.length - 1; e3++) - a2 *= t2[t2.length - e3 - 1], s2 = ` - int b${e3} = index / ${a2}; - index -= b${e3} * ${a2}; - ` + s2, u2 = `b${e3}, ` + u2; - const c = ` - ivec${t2.length} getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${n2[0]}, ${n2[1]})); - int index = resTexRC.y * ${n2[0]} + resTexRC.x; - - ${s2} - - int b = index / ${o2}; - index -= b * ${o2}; - - // reverse r and c order for packed texture - int r = imod(index, ${r2}) * 2; - int c = 2 * (index / ${r2}); - - return ivec${t2.length}(${u2}); - } - `; - return new i.GlslLibRoutine(c); - } - getOutputUnpacked1DCoords(t2, e2) { - const n2 = ` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - return resTexRC.y * ${e2[0]} + resTexRC.x; - } - `; - return new i.GlslLibRoutine(n2); - } - getOutputUnpacked2DCoords(t2, e2) { - const n2 = ` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - int index = resTexRC.y * ${e2[0]} + resTexRC.x; - int r = index / ${t2[1]}; - int c = index - r * ${t2[1]}; - return ivec2(r, c); - } - `; - return new i.GlslLibRoutine(n2); - } - getOutputUnpacked3DCoords(t2, e2) { - let n2 = ""; - const r2 = t2.length; - let o2 = null; - r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; - for (let e3 = r2 - 3; e3 >= 0; --e3) - o2[e3] = o2[e3 + 1] * t2[e3 + 1]; - const a2 = ["r", "c", "d"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join(""); - return n2 = ` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - int index = resTexRC.y * ${e2[0]} + resTexRC.x; - ${s2} - return ivec3(r, c, d); - } - `, new i.GlslLibRoutine(n2); - } - getOutputUnpacked4DCoords(t2, e2) { - let n2 = ""; - const r2 = t2.length; - let o2 = null; - r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; - for (let e3 = r2 - 3; e3 >= 0; --e3) - o2[e3] = o2[e3 + 1] * t2[e3 + 1]; - const a2 = ["r", "c", "d", "d2"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join(""); - return n2 = ` - ivec4 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - int index = resTexRC.y * ${e2[0]} + resTexRC.x; - ${s2} - return ivec4(r, c, d, d2); - } - `, new i.GlslLibRoutine(n2); - } - getOutputUnpacked5DCoords(t2, e2) { - let n2 = ""; - const r2 = t2.length; - let o2 = null; - r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; - for (let e3 = r2 - 3; e3 >= 0; --e3) - o2[e3] = o2[e3 + 1] * t2[e3 + 1]; - const a2 = ["r", "c", "d", "d2", "d3"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join(""); - return n2 = ` - ivec5 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - int index = resTexRC.y * ${e2[0]} + resTexRC.x; - ${s2} - return ivec5(r, c, d, d2, d3); - } - `, new i.GlslLibRoutine(n2); - } - getOutputUnpacked6DCoords(t2, e2) { - let n2 = ""; - const r2 = t2.length; - let o2 = null; - r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; - for (let e3 = r2 - 3; e3 >= 0; --e3) - o2[e3] = o2[e3 + 1] * t2[e3 + 1]; - const a2 = ["r", "c", "d", "d2", "d3", "d4"], s2 = o2.map((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`).join(""); - return n2 = ` - ivec6 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e2[0]}, ${e2[1]})); - int index = resTexRC.y * ${e2[0]} + resTexRC.x; - ${s2} - return ivec6(r, c, d, d2, d3, d4); - } - `, new i.GlslLibRoutine(n2); - } - getCommonUtilFuncs() { - const t2 = {}; - let e2 = "uvFromFlat"; - t2[e2] = new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "), e2 = "packedUVfrom1D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "packedUVfrom2D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "packedUVfrom3D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "sampleTexture"; - const n2 = (0, o.getGlsl)(this.context.glContext.version); - return t2[e2] = new i.GlslLibRoutine(` - float sampleTexture(sampler2D textureSampler, vec2 uv) { - return ${n2.texture2D}(textureSampler, uv).r; - }`), t2; - } - getInputsSamplingSnippets() { - const t2 = {}, e2 = this.context.outputTextureLayout; - return this.context.programInfo.inputNames.forEach((n2, r2) => { - const i2 = this.context.inputTextureLayouts[r2], o2 = (0, s.generateShaderFuncNameFromInputSamplerName)(n2); - i2.isPacked ? t2[o2] = this.getPackedSamplerFromInput(o2, n2, i2) : t2[o2] = this.getUnpackedSamplerFromInput(o2, n2, i2); - const a2 = (0, s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n2); - i2.unpackedShape.length <= e2.unpackedShape.length && (i2.isPacked ? t2[a2] = this.getPackedSamplerAtOutputCoords(a2, i2, e2, n2) : t2[a2] = this.getUnpackedSamplerAtOutputCoords(a2, i2, e2, n2)); - }), t2; - } - getPackedSamplerAtOutputCoords(t2, e2, n2, o2) { - const a2 = e2.unpackedShape, u2 = n2.unpackedShape, c = o2, l = (0, s.generateShaderFuncNameFromInputSamplerName)(c), p = a2.length, f = u2.length, d = r.BroadcastUtil.getBroadcastDims(a2, u2), h = (0, s.getCoordsDataType)(f), g = f - p; - let b; - const m = (0, s.getGlChannels)(); - b = 0 === p ? "" : f < 2 && d.length >= 1 ? "coords = 0;" : d.map((t3) => `coords.${m[t3 + g]} = 0;`).join("\n"); - let y = ""; - y = f < 2 && p > 0 ? "coords" : a2.map((t3, e3) => `coords.${m[e3 + g]}`).join(", "); - let _ = "return outputValue;"; - const v = 1 === r.ShapeUtil.size(a2), w = 1 === r.ShapeUtil.size(u2); - if (1 !== p || v || w) { - if (v && !w) - _ = 1 === f ? "\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n " : "\n return vec4(outputValue.x);\n "; - else if (d.length) { - const t3 = p - 2, e3 = p - 1; - d.indexOf(t3) > -1 && d.indexOf(e3) > -1 ? _ = "return vec4(outputValue.x);" : d.indexOf(t3) > -1 ? _ = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf(e3) > -1 && (_ = "return vec4(outputValue.xx, outputValue.zz);"); - } - } else - _ = "\n return vec4(outputValue.xy, outputValue.xy);\n "; - const x = ` - vec4 ${t2}() { - ${h} coords = getOutputCoords(); - - int lastDim = coords.${m[f - 1]}; - coords.${m[f - 1]} = coords.${m[f - 2]}; - coords.${m[f - 2]} = lastDim; - - ${b} - vec4 outputValue = ${l}(${y}); - ${_} - } - `; - return new i.GlslLibRoutine(x, ["coordinates.getOutputCoords"]); - } - getUnpackedSamplerAtOutputCoords(t2, e2, n2, o2) { - const a2 = [n2.width, n2.height], u2 = [e2.width, e2.height], c = e2.unpackedShape.length, l = n2.unpackedShape.length, p = e2.unpackedShape, f = n2.unpackedShape, d = (0, s.generateShaderFuncNameFromInputSamplerName)(o2); - if (c === l && r.ArrayUtil.arraysEqual(u2, a2)) { - const e3 = ` - float ${t2}() { - return sampleTexture(${o2}, TexCoords); - } - `; - return new i.GlslLibRoutine(e3, ["coordinates.sampleTexture"]); - } - const h = (0, s.getCoordsDataType)(l), g = r.BroadcastUtil.getBroadcastDims(p, f), b = l - c; - let m; - const y = (0, s.getGlChannels)(); - m = 0 === c ? "" : l < 2 && g.length >= 1 ? "coords = 0;" : g.map((t3) => `coords.${y[t3 + b]} = 0;`).join("\n"); - let _ = ""; - _ = l < 2 && c > 0 ? "coords" : e2.unpackedShape.map((t3, e3) => `coords.${y[e3 + b]}`).join(", "); - const v = ` - float ${t2}() { - ${h} coords = getOutputCoords(); - ${m} - return ${d}(${_}); - } - `; - return new i.GlslLibRoutine(v, ["coordinates.getOutputCoords"]); - } - getPackedSamplerFromInput(t2, e2, n2) { - switch (n2.unpackedShape.length) { - case 0: - return this.getPackedSamplerScalar(t2, e2); - case 1: - return this.getPackedSampler1D(t2, e2, n2); - case 2: - return this.getPackedSampler2D(t2, e2, n2); - case 3: - return this.getPackedSampler3D(t2, e2, n2); - default: - return this.getPackedSamplerND(t2, e2, n2); - } - } - getUnpackedSamplerFromInput(t2, e2, n2) { - const r2 = n2.unpackedShape; - switch (r2.length) { - case 0: - return this.getUnpackedSamplerScalar(t2, e2, n2); - case 1: - return this.getUnpackedSampler1D(t2, e2, n2); - case 2: - return this.getUnpackedSampler2D(t2, e2, n2); - case 3: - return this.getUnpackedSampler3D(t2, e2, n2); - case 4: - return this.getUnpackedSampler4D(t2, e2, n2); - case 5: - return this.getUnpackedSampler5D(t2, e2, n2); - case 6: - return this.getUnpackedSampler6D(t2, e2, n2); - default: - throw new Error(`Unsupported dimension ${r2.length}-D`); - } - } - getPackedSamplerScalar(t2, e2) { - const n2 = ` - vec4 ${t2}() { - return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${e2}, halfCR); - } - `; - return new i.GlslLibRoutine(n2); - } - getPackedSampler1D(t2, e2, n2) { - const r2 = [n2.width, n2.height], a2 = [r2[1], r2[0]], s2 = (0, o.getGlsl)(this.context.glContext.version), u2 = `vec4 ${t2}(int index) { - vec2 uv = packedUVfrom1D( - ${a2[0]}, ${a2[1]}, index); - return ${s2.texture2D}(${e2}, uv); - }`; - return new i.GlslLibRoutine(u2, ["coordinates.packedUVfrom1D"]); - } - getPackedSampler2D(t2, e2, n2) { - const a2 = n2.unpackedShape, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = s2[0], l = s2[1]; - if (null != s2 && r.ArrayUtil.arraysEqual(a2, s2)) { - const n3 = `vec4 ${t2}(int row, int col) { - vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0); - return ${u2.texture2D}(${e2}, uv); - }`; - return new i.GlslLibRoutine(n3); - } - const p = s2, f = Math.ceil(a2[1] / 2), d = `vec4 ${t2}(int row, int col) { - vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col); - return ${u2.texture2D}(${e2}, uv); - }`; - return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom2D"]); - } - getPackedSampler3D(t2, e2, n2) { - const r2 = n2.unpackedShape, a2 = [n2.width, n2.height], u2 = [a2[0], a2[1]], c = (0, o.getGlsl)(this.context.glContext.version); - if (1 === r2[0]) { - const o2 = r2.slice(1), a3 = [1, 2], u3 = (0, s.squeezeInputShape)(r2, o2), c2 = ["b", "row", "col"], l2 = JSON.parse(JSON.stringify(n2)); - l2.unpackedShape = u3; - const p2 = this.getPackedSamplerFromInput(t2, e2, l2), f2 = `${p2.routineBody} - vec4 ${t2}(int b, int row, int col) { - return ${t2}(${(0, s.getSqueezedParams)(c2, a3)}); - } `; - return new i.GlslLibRoutine(f2, p2.dependencies); - } - const l = u2[0], p = u2[1], f = Math.ceil(r2[2] / 2), d = `vec4 ${t2}(int b, int row, int col) { - vec2 uv = packedUVfrom3D( - ${p}, ${l}, ${f * Math.ceil(r2[1] / 2)}, ${f}, b, row, col); - return ${c.texture2D}(${e2}, uv);}`; - return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom3D"]); - } - getPackedSamplerND(t2, e2, n2) { - const r2 = n2.unpackedShape, a2 = r2.length, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = [s2[0], s2[1]], l = c[1], p = c[0], f = Math.ceil(r2[a2 - 1] / 2); - let d = f * Math.ceil(r2[a2 - 2] / 2), h = "int b, int row, int col", g = `b * ${d} + (row / 2) * ${f} + (col / 2)`; - for (let t3 = 2; t3 < a2 - 1; t3++) - h = `int b${t3}, ` + h, d *= r2[a2 - t3 - 1], g = `b${t3} * ${d} + ` + g; - const b = `vec4 ${t2}(${h}) { - int index = ${g}; - int texR = index / ${p}; - int texC = index - texR * ${p}; - vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${l}); - return ${u2.texture2D}(${e2}, uv); - }`; - return new i.GlslLibRoutine(b); - } - getUnpackedSamplerScalar(t2, e2, n2) { - const [r2, o2] = [n2.width, n2.height]; - if (1 === r2 && 1 === o2) { - const n3 = ` - float ${t2}() { - return sampleTexture(${e2}, halfCR); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); - } - const a2 = ` - float ${t2}() { - int offset_${e2} = coordsToOffset(TexCoords, ${r2}, ${o2}); - vec2 uv = uvFromFlat(${r2}, ${o2}, offset_${e2}); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - getUnpackedSampler1D(t2, e2, n2) { - const r2 = n2.width, o2 = n2.height; - if (1 === o2 && 1 === r2) { - const n3 = ` - float ${t2}(int index) { - return sampleTexture(${e2}, halfCR); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); - } - if (1 === o2) { - const n3 = ` - float ${t2}(int index) { - vec2 uv = vec2((float(index) + 0.5) / ${r2}.0, 0.5); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); - } - if (1 === r2) { - const n3 = ` - float ${t2}(int index) { - vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o2}.0); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); - } - const a2 = ` - float ${t2}(int index) { - vec2 uv = uvFromFlat(${r2}, ${o2}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); - } - getUnpackedSampler2D(t2, e2, n2) { - const o2 = n2.unpackedShape, u2 = [n2.height, n2.width]; - if (null != u2 && r.ArrayUtil.arraysEqual(o2, u2)) { - const n3 = ` - float ${t2}(int row, int col) { - vec2 uv = (vec2(row, col) + halfCR) / vec2(${u2[1]}.0, ${u2[0]}.0); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); - } - const { newShape: c, keptDims: l } = (0, a.squeezeShape)(o2), p = c; - if (p.length < o2.length) { - const r2 = (0, s.squeezeInputShape)(o2, p), a2 = JSON.parse(JSON.stringify(n2)); - a2.unpackedShape = r2; - const u3 = ["col", "row"], c2 = ` - ${this.getUnpackedSamplerFromInput(t2, e2, a2).routineBody} - float ${t2}(int row, int col) { - return ${t2}(${(0, s.getSqueezedParams)(u3, l)}); - } - `; - return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture"]); - } - const f = u2[1], d = u2[0]; - if (1 === d) { - const n3 = ` - float ${t2}(int row, int col) { - int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d}); - float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1)); - vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - if (1 === f) { - const n3 = ` - float ${t2}(int row, int col) { - int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d}); - float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1)); - vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - const h = ` - float ${t2}(int row, int col) { - int index = col * ${o2[1]} + row; - vec2 uv = uvFromFlat(${f}, ${d}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - getUnpackedSampler3D(t2, e2, n2) { - const r2 = n2.unpackedShape, o2 = r2[1] * r2[2], u2 = r2[2], { newShape: c, keptDims: l } = (0, a.squeezeShape)(r2), p = c; - if (p.length < r2.length) { - const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["batch", "col", "row"], u3 = JSON.parse(JSON.stringify(n2)); - u3.unpackedShape = o3; - const c2 = this.getUnpackedSamplerFromInput(t2, e2, u3), f2 = l.reverse(), d = ` - ${c2.routineBody} - float ${t2}(int batch, int row, int col) { - return ${t2}(${(0, s.getSqueezedParams)(a2, f2)}); - } - `; - return new i.GlslLibRoutine(d, c2.dependencies); - } - const f = ` - float ${t2}(int depth, int row, int col) { - // Explicitly use integer operations as dot() only works on floats. - int index = depth * ${o2} + col * ${u2} + row; - vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(f, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - getUnpackedSampler4D(t2, e2, n2) { - const r2 = n2.unpackedShape, o2 = r2[3], a2 = r2[2] * o2, s2 = ` - float ${t2}(int row, int col, int depth, int depth2) { - int index = row * ${r2[1] * a2} + col * ${a2} + - depth2 * ${o2} + depth; - vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(s2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); - } - getUnpackedSampler5D(t2, e2, n2) { - const r2 = n2.unpackedShape, o2 = r2[4], u2 = r2[3] * o2, c = r2[2] * u2, l = r2[1] * c, { newShape: p, keptDims: f } = (0, a.squeezeShape)(r2); - if (p.length < r2.length) { - const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["row", "col", "depth", "depth2", "depth3"], u3 = JSON.parse(JSON.stringify(n2)); - u3.unpackedShape = o3; - const c2 = ` - ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody} - float ${t2}(int row, int col, int depth, int depth2, int depth3) { - return ${t2}(${(0, s.getSqueezedParams)(a2, f)}); - } - `; - return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); - } - const d = ` - float ${t2}(int row, int col, int depth, int depth2, int depth3) { - int index = row * ${l} + col * ${c} + depth * ${u2} + - depth3 * ${o2} + depth2; - vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(d, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); - } - getUnpackedSampler6D(t2, e2, n2) { - const r2 = n2.unpackedShape, o2 = r2[5], u2 = r2[4] * o2, c = r2[3] * u2, l = r2[2] * c, p = r2[1] * l, { newShape: f, keptDims: d } = (0, a.squeezeShape)(r2); - if (f.length < r2.length) { - const o3 = (0, s.squeezeInputShape)(r2, f), a2 = ["row", "col", "depth", "depth2", "depth3", "depth4"], u3 = JSON.parse(JSON.stringify(n2)); - u3.unpackedShape = o3; - const c2 = ` - ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody} - float ${t2}(int row, int col, int depth, - int depth2, int depth3, int depth4) { - return ${t2}(${(0, s.getSqueezedParams)(a2, d)}); - } - `; - return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); - } - const h = ` - float ${t2}(int row, int col, int depth, - int depth2, int depth3, int depth4) { - int index = row * ${p} + col * ${l} + depth * ${c} + - depth2 * ${u2} + depth3 * ${o2} + depth4; - vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); - return sampleTexture(${e2}, uv); - } - `; - return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); - } - toVec() { - const t2 = this.context.outputTextureLayout, e2 = t2.shape.length, n2 = t2.strides, r2 = t2.width, o2 = t2.height, a2 = []; - for (let t3 = 0; t3 < e2 - 1; ++t3) - a2.push(` - c[${t3}] = offset / ${n2[t3]};`), a2.push(` - offset -= c[${t3}] * ${n2[t3]};`); - a2.push(` - c[${e2 - 1}] = offset;`); - const s2 = ` - void toVec(vec2 texCoords, out int c[${e2}]) { - int offset = coordsToOffset(texCoords, ${r2}, ${o2}); - ${a2.join("")} - } - void toVec(int offset, out int c[${e2}]) { - ${a2.join("")} - } - `; - return { toVec: new i.GlslLibRoutine(s2, ["coordinates.coordsToOffset"]) }; - } - valueFrom() { - const t2 = {}; - return this.context.programInfo.inputNames.forEach((e2, n2) => { - const r2 = this.context.inputTextureLayouts[n2], o2 = (r2.unpackedShape.length > 0 ? r2.unpackedShape : r2.shape).length; - let a2 = `_${e2}`; - t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, false), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), a2 += "_T", t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, true), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]); - }), t2; - } - getValueFromSingle(t2, e2, n2, r2, i2) { - let a2 = `_${t2}`; - return i2 && (a2 += "_T"), ` - float ${a2}(int m[${e2}]) { - int offset = indicesToOffset${a2}(m); - vec2 coords = offsetToCoords(offset, ${n2}, ${r2}); - float value = getColorAsFloat(${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords)); - return value; - } - `; - } - getPackedValueFrom(t2, e2, n2, r2, i2) { - let a2 = `_${t2}_Pack`; - return i2 && (a2 += "_T"), ` - vec4 ${a2}(int m[${e2}]) { - int offset = indicesToOffset_${t2}(m); - vec2 coords = offsetToCoords(offset, ${n2}, ${r2}); - return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords); - } - `; - } - } - e.CoordsGlslLib = u; - }, 8520: (t, e) => { - "use strict"; - var n; - Object.defineProperty(e, "__esModule", { value: true }), e.TopologicalSortGlslRoutines = e.GlslLibRoutineNode = e.GlslLibRoutine = e.GlslLib = e.GlslContext = e.FunctionType = void 0, (n = e.FunctionType || (e.FunctionType = {}))[n.ValueBased = 0] = "ValueBased", n[n.Positional = 1] = "Positional", e.GlslContext = class { - constructor(t2, e2, n2, r) { - this.glContext = t2, this.programInfo = e2, this.inputTextureLayouts = n2, this.outputTextureLayout = r; - } - }, e.GlslLib = class { - constructor(t2) { - this.context = t2; - } - }, e.GlslLibRoutine = class { - constructor(t2, e2) { - this.routineBody = t2, this.dependencies = e2; - } - }, e.GlslLibRoutineNode = class { - constructor(t2, e2, n2) { - this.name = t2, this.dependencies = n2 || [], e2 && (this.routineBody = e2); - } - addDependency(t2) { - t2 && this.dependencies.push(t2); - } - }, e.TopologicalSortGlslRoutines = class { - static returnOrderedNodes(t2) { - if (!t2 || 0 === t2.length) - return []; - if (1 === t2.length) - return t2; - const e2 = /* @__PURE__ */ new Set(), n2 = /* @__PURE__ */ new Set(), r = new Array(); - return this.createOrderedNodes(t2, e2, n2, r), r; - } - static createOrderedNodes(t2, e2, n2, r) { - for (let i = 0; i < t2.length; ++i) - this.dfsTraverse(t2[i], e2, n2, r); - } - static dfsTraverse(t2, e2, n2, r) { - if (!t2 || n2.has(t2.name)) - return; - if (e2.has(t2.name)) - throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader."); - e2.add(t2.name); - const i = t2.dependencies; - if (i && i.length > 0) - for (let t3 = 0; t3 < i.length; ++t3) - this.dfsTraverse(i[t3], e2, n2, r); - r.push(t2), n2.add(t2.name), e2.delete(t2.name); - } - }; - }, 7341: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.EncodingGlslLib = void 0; - const r = n(8520); - class i extends r.GlslLib { - constructor(t2) { - super(t2); - } - getFunctions() { - return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32()); - } - getCustomTypes() { - return {}; - } - encodeFloat32() { - return { encode: new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ") }; - } - decodeFloat32() { - return { decode: new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ") }; - } - encodeUint8() { - const t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; - return { encode: new r.GlslLibRoutine(` - highp vec4 encode(highp float f) { - highp float F = abs(f); - highp float Sign = step(0.0,-f); - highp float Exponent = floor(log2(F)); - highp float Mantissa = (exp2(- Exponent) * F); - Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); - highp vec4 rgba; - rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); - rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); - rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); - rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); - ${t2} - rgba = rgba / 255.0; // values need to be normalized to [0,1] - return rgba; - } - `) }; - } - decodeUint8() { - const t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; - return { decode: new r.GlslLibRoutine(` - highp float decode(highp vec4 rgba) { - rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] - ${t2} - highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; - highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; - highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); - highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); - return Result; - } - `) }; - } - static isLittleEndian() { - const t2 = new ArrayBuffer(4), e2 = new Uint32Array(t2), n2 = new Uint8Array(t2); - if (e2[0] = 3735928559, 239 === n2[0]) - return true; - if (222 === n2[0]) - return false; - throw new Error("unknown endianness"); - } - } - e.EncodingGlslLib = i; - }, 9894: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.FragColorGlslLib = void 0; - const r = n(8520), i = n(5060); - class o extends r.GlslLib { - constructor(t2) { - super(t2); - } - getFunctions() { - return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat()); - } - getCustomTypes() { - return {}; - } - setFragColor() { - const t2 = (0, i.getGlsl)(this.context.glContext.version); - return { setFragColor: new r.GlslLibRoutine(` - void setFragColor(float value) { - ${t2.output} = encode(value); - } - `, ["encoding.encode"]) }; - } - getColorAsFloat() { - return { getColorAsFloat: new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ", ["encoding.decode"]) }; - } - } - e.FragColorGlslLib = o; - }, 2848: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.replaceInlines = void 0; - const n = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm; - e.replaceInlines = function(t2) { - const e2 = {}; - let r; - for (; null !== (r = n.exec(t2)); ) { - const t3 = r[3].split(",").map((t4) => { - const e3 = t4.trim().split(" "); - return e3 && 2 === e3.length ? { type: e3[0], name: e3[1] } : null; - }).filter((t4) => null !== t4); - e2[r[2]] = { params: t3, body: r[4] }; - } - for (const n2 in e2) { - const i = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__", n2), o = new RegExp(i, "gm"); - for (; null !== (r = o.exec(t2)); ) { - const i2 = r[1], o2 = r[2], a = r[3].split(","), s = i2 ? `${i2} ${o2};` : ""; - let u = e2[n2].body, c = ""; - e2[n2].params.forEach((t3, e3) => { - t3 && (c += `${t3.type} ${t3.name} = ${a[e3]}; -`); - }), u = `${c} - ${u}`, u = u.replace("return", `${o2} = `); - const l = ` - ${s} - { - ${u} - } - `; - t2 = t2.replace(r[0], l); - } - } - return t2.replace(n, ""); - }; - }, 8879: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.GlslPreprocessor = void 0; - const r = n(8520), i = n(2848), o = n(5483), a = n(5060); - e.GlslPreprocessor = class { - constructor(t2, e2, n2, i2) { - this.libs = {}, this.glslLibRoutineDependencyGraph = {}, this.context = new r.GlslContext(t2, e2, n2, i2), Object.keys(o.glslRegistry).forEach((t3) => { - const e3 = new o.glslRegistry[t3](this.context); - this.libs[t3] = e3; - }); - const a2 = this.glslLibRoutineDependencyGraph; - for (const t3 in this.libs) { - const e3 = this.libs[t3].getFunctions(); - for (const n3 in e3) { - const i3 = t3 + "." + n3; - let o2; - a2[i3] ? (o2 = a2[i3], o2.routineBody = e3[n3].routineBody) : (o2 = new r.GlslLibRoutineNode(i3, e3[n3].routineBody), a2[i3] = o2); - const s = e3[n3].dependencies; - if (s) - for (let t4 = 0; t4 < s.length; ++t4) - if (a2[s[t4]]) - o2.addDependency(a2[s[t4]]); - else { - const e4 = new r.GlslLibRoutineNode(s[t4]); - a2[s[t4]] = e4, o2.addDependency(e4); - } - } - } - } - preprocess() { - const t2 = this.context.programInfo; - let e2 = t2.shaderSource; - return this.context.programInfo.hasMain || (e2 = `${e2} - ${(0, a.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), e2 = (0, i.replaceInlines)(e2), `${(0, a.getFragShaderPreamble)(this.context.glContext.version)} - ${this.getUniforms(t2.inputNames, t2.variables)} - ${this.getImports(e2)} - ${e2}`; - } - getImports(t2) { - const e2 = this.selectGlslLibRoutinesToBeIncluded(t2); - if (0 === e2.length) - return ""; - let n2 = ""; - for (let t3 = 0; t3 < e2.length; ++t3) { - if (!e2[t3].routineBody) - throw new Error(`Missing body for the Glsl Library routine: ${e2[t3].name}`); - n2 += e2[t3].routineBody + "\n"; - } - return n2; - } - selectGlslLibRoutinesToBeIncluded(t2) { - const e2 = []; - return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n2) => { - const r2 = n2.split(".")[1]; - -1 !== t2.indexOf(r2) && e2.push(this.glslLibRoutineDependencyGraph[n2]); - }), r.TopologicalSortGlslRoutines.returnOrderedNodes(e2); - } - getUniforms(t2, e2) { - const n2 = []; - if (t2) - for (const e3 of t2) - n2.push(`uniform sampler2D ${e3};`); - if (e2) - for (const t3 of e2) - n2.push(`uniform ${t3.type} ${t3.name}${t3.arrayLength ? `[${t3.arrayLength}]` : ""};`); - return n2.join("\n"); - } - }; - }, 5483: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.glslRegistry = void 0; - const r = n(5107), i = n(7341), o = n(9894), a = n(2655), s = n(3891); - e.glslRegistry = { encoding: i.EncodingGlslLib, fragcolor: o.FragColorGlslLib, vec: s.VecGlslLib, shapeUtils: a.ShapeUtilsGlslLib, coordinates: r.CoordsGlslLib }; - }, 2655: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.ShapeUtilsGlslLib = void 0; - const r = n(8520); - class i extends r.GlslLib { - constructor(t2) { - super(t2); - } - getFunctions() { - return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices()); - } - getCustomTypes() { - return {}; - } - bcastIndex() { - const t2 = this.context.outputTextureLayout.shape.length, e2 = {}; - return this.context.programInfo.inputNames.forEach((n2, i2) => { - const o = this.context.inputTextureLayouts[i2].unpackedShape; - if (o.length <= t2) { - const i3 = o.length, a = t2 - i3, s = `bcastIndices_${n2}`; - let u = ""; - for (let t3 = 0; t3 < i3; ++t3) - u += ` - realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) ); - `; - const c = ` - void ${s} (int bcastedIndices[${t2}], out int realIndices[${i3}]) { - ${u} - } - `; - e2[s] = new r.GlslLibRoutine(c); - } - }), e2; - } - bcastMatmulIndex() { - const t2 = this.context.outputTextureLayout.shape.length, e2 = {}; - return this.context.programInfo.inputNames.forEach((n2, i2) => { - const o = this.context.inputTextureLayouts[i2].shape; - if (!(o.length < 2 || o.length > t2)) { - const i3 = o.length, a = t2 - i3, s = `bcastMatmulIndices_${n2}`; - let u = ""; - for (let t3 = 0; t3 < i3 - 2; ++t3) - u += ` - realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) ); - `; - const c = ` - void ${s}(int bcastedIndices[${t2}], out int realIndices[${i3}]) { - ${u} - realIndices[${i3 - 1}] = bcastedIndices[${t2 - 1}]; - realIndices[${i3 - 2}] = bcastedIndices[${t2 - 2}]; - } - `; - e2[s] = new r.GlslLibRoutine(c); - } - }), e2; - } - indicesToOffset() { - const t2 = {}; - return this.context.programInfo.inputNames.forEach((e2, n2) => { - const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length; - let u = `indicesToOffset_${e2}`; - t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a)), u = `indicesToOffset_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a.slice().reverse())); - }), t2; - } - static indexToOffsetSingle(t2, e2, n2) { - let r2 = ""; - for (let t3 = e2 - 1; t3 >= 0; --t3) - r2 += ` - offset += indices[${t3}] * ${n2[t3]}; - `; - return ` - int ${t2}(int indices[${e2}]) { - int offset = 0; - ${r2} - return offset; - } - `; - } - offsetToIndices() { - const t2 = {}; - return this.context.programInfo.inputNames.forEach((e2, n2) => { - const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length; - let u = `offsetToIndices_${e2}`; - t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a)), u = `offsetToIndices_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a.slice().reverse())); - }), t2; - } - static offsetToIndicesSingle(t2, e2, n2) { - const r2 = []; - for (let t3 = 0; t3 < e2 - 1; ++t3) - r2.push(` - indices[${t3}] = offset / ${n2[t3]};`), r2.push(` - offset -= indices[${t3}] * ${n2[t3]};`); - return r2.push(` - indices[${e2 - 1}] = offset;`), ` - void ${t2}(int offset, out int indices[${e2}]) { - ${r2.join("")} - } - `; - } - incrementIndices() { - const t2 = {}; - return this.context.programInfo.inputNames.forEach((e2, n2) => { - const i2 = this.context.inputTextureLayouts[n2].shape, o = i2.length, a = `incrementIndices_${e2}`; - let s = ""; - for (let t3 = 0; t3 < o; ++t3) - s += ` - shape[${t3}] = ${i2[t3]};`; - const u = ` - void ${a}(int axis, out int indices[${o}]) { - int shape[${o}]; - ${s}; - for(int i = ${o} -1 ; i >= 0; --i) { - if(i > axis) continue; - indices[i] += 1; - if(indices[i] < shape[i]) { - break; - } - indices[i] = 0; - } - } - `; - t2[a] = new r.GlslLibRoutine(u); - }), t2; - } - } - e.ShapeUtilsGlslLib = i; - }, 5060: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.getDefaultFragShaderMain = e.getFragShaderPreamble = e.getVertexShaderSource = e.getGlsl = void 0; - const n = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, r = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" }; - function i(t2) { - return 1 === t2 ? n : r; - } - e.getGlsl = i, e.getVertexShaderSource = function(t2) { - const e2 = i(t2); - return `${e2.version} - precision highp float; - ${e2.attribute} vec3 position; - ${e2.attribute} vec2 textureCoord; - - ${e2.varyingVertex} vec2 TexCoords; - - void main() - { - gl_Position = vec4(position, 1.0); - TexCoords = textureCoord; - }`; - }, e.getFragShaderPreamble = function(t2) { - const e2 = i(t2); - return `${e2.version} - precision highp float; - precision highp int; - precision highp sampler2D; - ${e2.varyingFrag} vec2 TexCoords; - ${e2.outputDeclaration} - const vec2 halfCR = vec2(0.5, 0.5); - - // Custom vector types to handle higher dimenalities. - struct ivec5 - { - int x; - int y; - int z; - int w; - int u; - }; - - struct ivec6 - { - int x; - int y; - int z; - int w; - int u; - int v; - }; - - int imod(int x, int y) { - return x - y * (x / y); - } - - `; - }, e.getDefaultFragShaderMain = function(t2, e2) { - return ` - void main() { - int indices[${e2}]; - toVec(TexCoords, indices); - vec4 result = vec4(process(indices)); - ${i(t2).output} = result; - } - `; - }; - }, 3891: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.VecGlslLib = void 0; - const r = n(8520); - class i extends r.GlslLib { - constructor(t2) { - super(t2); - } - getCustomTypes() { - return {}; - } - getFunctions() { - return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem()); - } - binaryVecFunctions() { - const t2 = this.context.outputTextureLayout.shape.length, e2 = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, n2 = {}; - for (const i2 in e2) { - const o = `${i2}Vec`; - let a = ""; - for (let n3 = 0; n3 < t2; ++n3) - a += ` - dest[${n3}] ${e2[i2]} src[${n3}]; - `; - const s = ` - void ${o}(int src[${t2}], out int dest[${t2}]) { - ${a} - } - `; - n2[o] = new r.GlslLibRoutine(s); - } - return n2; - } - copyVec() { - const t2 = this.context.outputTextureLayout.shape.length; - let e2 = ""; - for (let n3 = 0; n3 < t2; ++n3) - e2 += ` - dest[${n3}] = src[${n3}]; - `; - const n2 = ` - void copyVec(int src[${t2}], out int dest[${t2}]) { - ${e2} - } - `; - return { copyVec: new r.GlslLibRoutine(n2) }; - } - setVecItem() { - const t2 = this.context.outputTextureLayout.shape.length; - let e2 = ` - if(index < 0) - index =${t2} + index; - if (index == 0) - m[0] = value; - `; - for (let n3 = 1; n3 < t2 - 1; ++n3) - e2 += ` - else if (index == ${n3}) - m[${n3}] = value; - `; - e2 += ` - else - m[${t2 - 1}] = value; - `; - const n2 = ` - void setVecItem(out int m[${t2}], int index, int value) { - ${e2} - } - `; - return { setVecItem: new r.GlslLibRoutine(n2) }; - } - getVecItem() { - const t2 = this.context.outputTextureLayout.shape.length; - let e2 = ` - if(index < 0) - index = ${t2} + index; - if (index == 0) - return m[0]; - `; - for (let n3 = 1; n3 < t2 - 1; ++n3) - e2 += ` - else if (index == ${n3}) - return m[${n3}]; - `; - e2 += ` - else - return m[${t2 - 1}]; - `; - const n2 = ` - int getVecItem(int m[${t2}], int index) { - ${e2} - } - `; - return { getVecItem: new r.GlslLibRoutine(n2) }; - } - } - e.VecGlslLib = i; - }, 8316: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.WebGLInferenceHandler = void 0; - const r = n(6231), i = n(9162), o = n(2517), a = n(2403), s = n(7019), u = n(8710), c = n(5611), l = n(4057), p = n(2039); - e.WebGLInferenceHandler = class { - constructor(t2) { - this.session = t2, this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); - } - calculateTextureWidthAndHeight(t2, e2) { - return (0, l.calculateTextureWidthAndHeight)(this.session.layoutStrategy, t2, e2); - } - executeProgram(t2, e2) { - if (e2.length < t2.inputNames.length) - throw new Error(`Input size mustn't be less than ${t2.inputNames.length}.`); - if (t2.inputNames.length !== t2.inputTypes.length) - throw new Error("input names size does not match input types"); - const n2 = []; - for (let r3 = 0; r3 < t2.inputNames.length; ++r3) - n2[r3] = this.getOrCreateTextureData(e2[r3], t2.inputTypes[r3]); - const r2 = ((t3, e3) => { - const n3 = e3.map((t4) => `${t4.unpackedShape.join(",")};${t4.width}x${t4.height}`).join("_"); - let r3 = t3.name; - return t3.cacheHint && (r3 += "[" + t3.cacheHint + "]"), r3 += ":" + n3, r3; - })(t2, n2); - let i2 = this.session.programManager.getArtifact(r2); - const o2 = i2 ? i2.programInfo : "function" == typeof t2.get ? t2.get() : t2, a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2.output.dims, o2.output.textureType), s2 = this.createTextureData(a2, o2.output.type); - return i2 || (i2 = this.session.programManager.build(o2, n2, s2), this.session.programManager.setArtifact(r2, i2)), this.runProgram(i2, n2, s2), s2; - } - run(t2, e2) { - return this.executeProgram(t2, e2).tensor; - } - runProgram(t2, e2, n2) { - for (let n3 = 0; n3 < e2.length; ++n3) - if (!!e2[n3].isPacked != (t2.programInfo.inputTypes[n3] === p.TextureType.packed)) - throw new Error(`input[${n3}] property packed inconsistent`); - if (!!n2.isPacked != (t2.programInfo.output.textureType === p.TextureType.packed)) - throw new Error("output property packed inconsistent"); - this.session.programManager.run(t2, e2, n2); - } - getOrCreateTextureData(t2, e2) { - let n2 = this.getTextureData(t2.dataId, e2 === p.TextureType.packed); - if (!n2 && (n2 = this.getTextureData(t2.dataId, e2 !== p.TextureType.packed), n2)) - return e2 === p.TextureType.packed ? this.pack(n2) : this.unpack(n2); - if (!n2) { - const r2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, t2.dims, e2); - if (e2 === p.TextureType.packedLastDimension) { - const n3 = 1, r3 = 4, i2 = t2.dims; - if (4 === i2.length) { - const o2 = [i2[0], Math.ceil(i2[1] * i2[2] * i2[3] / r3)], a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2, e2); - let s2 = t2.numberData; - if (i2[1] * i2[2] * i2[3] % r3 != 0) { - const e3 = i2[0], o3 = i2[1] * i2[2] * i2[3], a3 = Math.ceil(o3 * n3 / r3) * r3; - s2 = new Float32Array(e3 * a3); - for (let r4 = 0; r4 < e3; ++r4) { - const e4 = r4 * o3, i3 = r4 * a3 + r4 % n3 * o3; - s2.set(t2.numberData.subarray(e4, e4 + o3), i3); - } - } - return this.createTextureData(a2, t2.type, s2, t2, 1); - } - } - if (e2 === p.TextureType.packed) { - const e3 = (0, l.createTextureLayoutFromShape)(this.session.layoutStrategy, t2.dims, 1, [], { reverseWH: true }), r3 = this.createTextureData(e3, t2.type, t2.numberData, t2, 1); - n2 = this.pack(r3); - } else - n2 = this.createTextureData(r2, t2.type, t2.numberData, t2, 1); - } - return n2; - } - createTextureDataFromLayoutBindTensor(t2, e2, n2, r2) { - return this.createTextureData(t2, e2, n2, r2, 1); - } - createTextureData(t2, e2, n2, i2, o2) { - r.Logger.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(t2)}]`); - const a2 = this.session.textureManager.createTextureFromLayout(e2, t2, n2, o2); - return this.createTextureDataFromTexture(t2, e2, a2, i2); - } - reshapeUnpacked(t2, e2) { - const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked), r2 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2 }; - return this.createTextureDataFromTexture(r2, t2.type, n2.texture).tensor; - } - reshapePacked(t2, e2) { - const n2 = this.getOrCreateTextureData(t2, p.TextureType.packed); - if ((0, s.isReshapeCheap)(t2.dims, e2)) { - const r3 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2, isPacked: true }; - return this.createTextureDataFromTexture(r3, t2.type, n2.texture).tensor; - } - const r2 = (0, s.processDims3D)(t2.dims), i2 = (0, s.processDims3D)(e2), a2 = this.reshapePacked(t2, r2), u2 = this.run((0, s.createPackedReshape3DProgramInfoLoader)(this, a2, i2), [a2]); - return this.reshapePacked(u2, e2); - } - cast(t2, e2) { - const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked); - return this.createTextureDataFromTexture(n2, e2, n2.texture).tensor; - } - createTextureDataFromTexture(t2, e2, n2, r2, o2) { - const a2 = Object.assign(Object.assign({}, t2), { tensor: r2 || new i.Tensor(t2.unpackedShape, e2, (t3) => this.readTexture(a2), async (t3) => this.readTextureAsync(a2), void 0, o2), texture: n2 }); - return this.setTextureData(a2.tensor.dataId, a2, t2.isPacked), a2; - } - getTextureData(t2, e2 = false) { - return this.session.isInitializer(t2) ? this.session.getTextureData(t2, e2) : e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2); - } - setTextureData(t2, e2, n2 = false) { - this.session.isInitializer(t2) ? this.session.setTextureData(t2, e2, n2) : (n2 ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(t2, e2); - } - isTextureLayoutCached(t2, e2 = false) { - return !!this.getTextureData(t2.dataId, e2); - } - dispose() { - this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((t2) => this.session.textureManager.releaseTexture(t2)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((t2) => this.session.textureManager.releaseTexture(t2)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); - } - readTexture(t2) { - return t2.isPacked ? this.readTexture(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2)); - } - async readTextureAsync(t2) { - return t2.isPacked ? this.readTextureAsync(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2)); - } - pack(t2) { - return this.executeProgram((0, a.createPackProgramInfoLoader)(this, t2.tensor), [t2.tensor]); - } - unpack(t2) { - return this.executeProgram((0, c.createUnpackProgramInfoLoader)(this, t2.tensor), [t2.tensor]); - } - }; - }, 1640: function(t, e, n) { - "use strict"; - var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2); - var i2 = Object.getOwnPropertyDescriptor(e2, n2); - i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { - return e2[n2]; - } }), Object.defineProperty(t2, r2, i2); - } : function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; - }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { - Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); - } : function(t2, e2) { - t2.default = e2; - }), o = this && this.__importStar || function(t2) { - if (t2 && t2.__esModule) - return t2; - var e2 = {}; - if (null != t2) - for (var n2 in t2) - "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); - return i(e2, t2), e2; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.WEBGL_OP_RESOLVE_RULES = void 0; - const a = n(2898), s = o(n(7839)), u = n(4196), c = n(2069), l = n(8138), p = n(9663), f = n(5193), d = n(7992), h = n(1253), g = n(4776), b = n(6572), m = n(3346), y = n(5623), _ = n(2870), v = n(2143), w = n(4939), x = n(718), T = n(2268), S = n(8117), O = n(2278), A = n(5524), E = n(5975), I = n(3933), P = n(6558), D = n(5723), $ = n(3738), k = o(n(4909)), C = n(8428), F = n(9793); - e.WEBGL_OP_RESOLVE_RULES = [["Abs", "", "6+", k.abs], ["Acos", "", "7+", k.acos], ["Add", "", "7+", s.add], ["And", "", "7+", s.and], ["Asin", "", "7+", k.asin], ["Atan", "", "7+", k.atan], ["AveragePool", "", "7+", v.averagePool, v.parseAveragePoolAttributes], ["BatchNormalization", "", "7+", a.batchNormalization, a.parseBatchNormalizationAttributes], ["Cast", "", "6+", u.cast, u.parseCastAttributes], ["Ceil", "", "6+", k.ceil], ["Clip", "", "6-10", k.clip, k.parseClipAttributes], ["Clip", "", "11+", k.clipV11], ["Concat", "", "4+", c.concat, c.parseConcatAttributes], ["Conv", "", "1+", l.conv, l.parseConvAttributes], ["ConvTranspose", "", "1+", p.convTranspose, p.parseConvTransposeAttributes], ["Cos", "", "7+", k.cos], ["Div", "", "7+", s.div], ["Dropout", "", "7+", k.identity], ["DepthToSpace", "", "1+", f.depthToSpace, f.parseDepthToSpaceAttributes], ["Equal", "", "7+", s.equal], ["Elu", "", "6+", k.elu, k.parseEluAttributes], ["Exp", "", "6+", k.exp], ["Flatten", "", "1+", d.flatten, d.parseFlattenAttributes], ["Floor", "", "6+", k.floor], ["FusedConv", "com.microsoft", "1+", l.conv, l.parseConvAttributes], ["Gather", "", "1+", h.gather, h.parseGatherAttributes], ["Gemm", "", "7-10", g.gemm, g.parseGemmAttributesV7], ["Gemm", "", "11+", g.gemm, g.parseGemmAttributesV11], ["GlobalAveragePool", "", "1+", v.globalAveragePool, v.parseGlobalAveragePoolAttributes], ["GlobalMaxPool", "", "1+", v.globalMaxPool], ["Greater", "", "7+", s.greater], ["Identity", "", "1+", k.identity], ["ImageScaler", "", "1+", b.imageScaler, b.parseImageScalerAttributes], ["InstanceNormalization", "", "6+", m.instanceNormalization, m.parseInstanceNormalizationAttributes], ["LeakyRelu", "", "6+", k.leakyRelu, k.parseLeakyReluAttributes], ["Less", "", "7+", s.less], ["Log", "", "6+", k.log], ["MatMul", "", "1+", y.matMul, y.parseMatMulAttributes], ["MaxPool", "", "1+", v.maxPool, v.parseMaxPoolAttributes], ["Mul", "", "7+", s.mul], ["Neg", "", "6+", k.neg], ["Not", "", "1+", k.not], ["Or", "", "7+", s.or], ["Pad", "", "2-10", _.padV2, _.parsePadAttributesV2], ["Pad", "", "11+", _.padV11, _.parsePadAttributesV11], ["Pow", "", "7+", s.pow], ["PRelu", "", "7+", s.pRelu], ["ReduceLogSum", "", "1+", w.reduceLogSum, w.parseReduceAttributes], ["ReduceMax", "", "1+", w.reduceMax, w.parseReduceAttributes], ["ReduceMean", "", "1+", w.reduceMean, w.parseReduceAttributes], ["ReduceMin", "", "1+", w.reduceMin, w.parseReduceAttributes], ["ReduceProd", "", "1+", w.reduceProd, w.parseReduceAttributes], ["ReduceSum", "", "1-12", w.reduceSum, w.parseReduceAttributes], ["ReduceSumSquare", "", "1+", w.reduceLogSumSquare, w.parseReduceAttributes], ["Relu", "", "6+", k.relu], ["Reshape", "", "5+", x.reshape], ["Resize", "", "10", T.resize, T.parseResizeAttributesV10], ["Resize", "", "11+", T.resize, T.parseResizeAttributesV11], ["Shape", "", "1+", S.shape], ["Sigmoid", "", "6+", k.sigmoid], ["Sin", "", "7+", k.sin], ["Slice", "", "10+", O.sliceV10], ["Slice", "", "1-9", O.slice, O.parseSliceAttributes], ["Softmax", "", "1-12", A.softmax, A.parseSoftmaxAttributes], ["Softmax", "", "13+", A.softmaxV13, A.parseSoftmaxAttributesV13], ["Split", "", "2-12", E.split, E.parseSplitAttributes], ["Sqrt", "", "6+", k.sqrt], ["Squeeze", "", "1-12", I.squeeze, I.parseSqueezeAttributes], ["Squeeze", "", "13+", I.squeezeV13], ["Sub", "", "7+", s.sub], ["Sum", "", "6+", P.sum], ["Tan", "", "7+", k.tan], ["Tanh", "", "6+", k.tanh], ["Tile", "", "6+", D.tile], ["Transpose", "", "1+", $.transpose, $.parseTransposeAttributes], ["Upsample", "", "7-8", F.upsample, F.parseUpsampleAttributesV7], ["Upsample", "", "9", F.upsample, F.parseUpsampleAttributesV9], ["Unsqueeze", "", "1-12", C.unsqueeze, C.parseUnsqueezeAttributes], ["Unsqueeze", "", "13+", C.unsqueezeV13], ["Xor", "", "7+", s.xor]]; - }, 2898: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseBatchNormalizationAttributes = e.batchNormalization = void 0; - const r = n(246), i = n(5060), o = n(2039), a = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] }; - e.batchNormalization = (t2, e2, n2) => (u(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2, n2) }), e2)]), e.parseBatchNormalizationAttributes = (t2) => { - const e2 = t2.attributes.getFloat("epsilon", 1e-5), n2 = t2.attributes.getFloat("momentum", 0.9), i2 = t2.attributes.getInt("spatial", 1); - return (0, r.createAttributeWithCacheKey)({ epsilon: e2, momentum: n2, spatial: i2 }); - }; - const s = (t2, e2, n2) => { - const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), s2 = e2[0].dims.length, [u2, c] = t2.calculateTextureWidthAndHeight(e2[1].dims, o.TextureType.unpacked), l = ` - float process(int[${s2}] indices) { - vec2 position = offsetToCoords(indices[1], ${u2}, ${c}); - float scale = getColorAsFloat(${r2.texture2D}(Scale, position)); - float mean = getColorAsFloat(${r2.texture2D}(Mean, position)); - float variance = getColorAsFloat(${r2.texture2D}(Variance, position)); - float b = getColorAsFloat(${r2.texture2D}(B, position)); - - return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n2.epsilon})) ) + b; - }`; - return Object.assign(Object.assign({}, a), { output: { dims: e2[0].dims, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: l }); - }, u = (t2) => { - if (!t2 || 5 !== t2.length) - throw new Error("BatchNormalization requires 5 inputs."); - const e2 = t2[0], n2 = t2[1], r2 = t2[2], i2 = t2[3], o2 = t2[4]; - if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length || 1 !== i2.dims.length || 1 !== o2.dims.length) - throw new Error("invalid input shape."); - if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1] || i2.dims[0] !== e2.dims[1] || o2.dims[0] !== e2.dims[1]) - throw new Error("invalid input shape."); - if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type || "float32" !== i2.type && "float64" !== i2.type || "float32" !== o2.type && "float64" !== o2.type) - throw new Error("invalid input tensor types."); - }; - }, 7839: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.xor = e.sub = e.pRelu = e.pow = e.or = e.mul = e.less = e.greater = e.equal = e.div = e.and = e.add = e.glslPRelu = e.glslPow = e.glslXor = e.glslOr = e.glslAnd = e.glslLess = e.glslGreater = e.glslEqual = e.glslSub = e.glslMul = e.glslDiv = e.glslAdd = void 0; - const r = n(2517), i = n(8520), o = n(5060), a = n(2039); - function s() { - const t2 = "add_"; - return { body: ` - float ${t2}(float a, float b) { - return a + b; - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return v1 + v2; - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function u() { - const t2 = "div_"; - return { body: ` - float ${t2}(float a, float b) { - return a / b; - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return v1 / v2; - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function c() { - const t2 = "mul_"; - return { body: ` - float ${t2}(float a, float b) { - return a * b; - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return v1 * v2; - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function l() { - const t2 = "sub_"; - return { body: ` - float ${t2}(float a, float b) { - return a - b; - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return v1 - v2; - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function p() { - const t2 = "equal_"; - return { body: ` - float ${t2}(float a, float b) { - return float(a == b); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return vec4(equal(v1, v2)); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function f() { - const t2 = "greater_"; - return { body: ` - float ${t2}(float a, float b) { - return float(a > b); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return vec4( v1.r > v2.r , - v1.g > v2.g, - v1.b > v2.b, - v1.a > v2.a ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function d() { - const t2 = "less_"; - return { body: ` - float ${t2}(float a, float b) { - return float(a < b); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return vec4( v1.r < v2.r , - v1.g < v2.g, - v1.b < v2.b, - v1.a < v2.a ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function h() { - const t2 = "and_"; - return { body: ` - float ${t2}(float a, float b) { - return float( bool(a) && bool(b) ); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r && b2.r , - b1.g && b2.g, - b1.b && b2.b, - b1.a && b2.a ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function g() { - const t2 = "or_"; - return { body: ` - float ${t2}(float a, float b) { - return float( bool(a) || bool(b) ); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r || b2.r , - b1.g || b2.g, - b1.b || b2.b, - b1.a || b2.a ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function b() { - const t2 = "xor_"; - return { body: ` - float ${t2}(float a, float b) { - return float( bool(a) ^^ bool(b) ); - } - vec4 ${t2}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r ^^ b2.r , - b1.g ^^ b2.g, - b1.b ^^ b2.b, - b1.a ^^ b2.a ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - function m() { - return function(t2) { - const e2 = `${t2}_`; - return { body: ` - float ${e2}(float a, float b) { - return ${t2}(a, b); - } - vec4 ${e2}(vec4 v1, vec4 v2) { - return ${t2}(v1, v2); - } - `, name: e2, type: i.FunctionType.ValueBased }; - }("pow"); - } - function y() { - const t2 = "prelu_"; - return { body: ` - float ${t2}(float a, float b) { - return a < 0.0 ? a * b: a; - } - vec4 ${t2}(vec4 v1, vec4 v2) { - return vec4( - v1.r < 0.0 ? v1.r * v2.r: v1.r, - v1.g < 0.0 ? v1.g * v2.g: v1.g, - v1.b < 0.0 ? v1.b * v2.b: v1.b, - v1.a < 0.0 ? v1.a * v2.a: v1.a - ); - } - `, name: t2, type: i.FunctionType.ValueBased }; - } - e.glslAdd = s, e.glslDiv = u, e.glslMul = c, e.glslSub = l, e.glslEqual = p, e.glslGreater = f, e.glslLess = d, e.glslAnd = h, e.glslOr = g, e.glslXor = b, e.glslPow = m, e.glslPRelu = y; - const _ = (t2, e2, n2, r2 = e2[0].type, i2) => { - const o2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked; - return { name: n2.name, inputNames: ["A", "B"], inputTypes: [o2, o2], cacheHint: i2, get: () => v(t2, e2, n2, r2) }; - }, v = (t2, e2, n2, i2 = e2[0].type) => { - const s2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked, u2 = !r.ShapeUtil.areEqual(e2[0].dims, e2[1].dims); - let c2 = e2[0].dims; - const l2 = t2.session.pack; - if (u2) { - const a2 = r.BroadcastUtil.calcShape(e2[0].dims, e2[1].dims, false); - if (!a2) - throw new Error("Can't perform binary op on the given tensors"); - c2 = a2; - const u3 = c2.length, p3 = 0 !== e2[0].dims.length ? e2[0].dims.length : 1, f3 = 0 !== e2[1].dims.length ? e2[1].dims.length : 1, d2 = 0 !== e2[0].dims.length ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", h2 = 0 !== e2[1].dims.length ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", g2 = (0, o.getGlsl)(t2.session.backend.glContext.version), b2 = l2 ? ` - ${n2.body} - void main() { - vec4 a = getAAtOutCoords(); - vec4 b = getBAtOutCoords(); - vec4 result = ${n2.name}(a, b); - ${g2.output} = result; - }` : ` - ${n2.body} - float process(int indices[${u3}]) { - int aindices[${p3}]; - int bindices[${f3}]; - ${d2} - ${h2} - return ${n2.name}(_A(aindices), _B(bindices)); - }`; - return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: c2, type: i2, textureType: s2 }, shaderSource: b2, hasMain: l2 }; - } - const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = ` - ${n2.body} - void main() { - vec4 v1 = ${p2.texture2D}(A, TexCoords); - vec4 v2 = ${p2.texture2D}(B, TexCoords); - vec4 result = ${n2.name}(v1, v2); - ${p2.output} = result; - } - `; - return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: e2[0].dims, type: i2, textureType: s2 }, shaderSource: f2, hasMain: true }; - }; - e.add = (t2, e2) => [t2.run(_(t2, e2, s()), e2)], e.and = (t2, e2) => [t2.run(_(t2, e2, h(), "bool"), e2)], e.div = (t2, e2) => [t2.run(_(t2, e2, u()), e2)], e.equal = (t2, e2) => [t2.run(_(t2, e2, p(), "bool"), e2)], e.greater = (t2, e2) => [t2.run(_(t2, e2, f(), "bool"), e2)], e.less = (t2, e2) => [t2.run(_(t2, e2, d(), "bool"), e2)], e.mul = (t2, e2) => [t2.run(_(t2, e2, c()), e2)], e.or = (t2, e2) => [t2.run(_(t2, e2, g(), "bool"), e2)], e.pow = (t2, e2) => [t2.run(_(t2, e2, m()), e2)], e.pRelu = (t2, e2) => [t2.run(_(t2, e2, y()), e2)], e.sub = (t2, e2) => [t2.run(_(t2, e2, l()), e2)], e.xor = (t2, e2) => [t2.run(_(t2, e2, b(), "bool"), e2)]; - }, 4196: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseCastAttributes = e.cast = void 0; - const r = n(2517); - e.cast = (t2, e2, n2) => (i(e2), [t2.cast(e2[0], n2)]), e.parseCastAttributes = (t2) => r.ProtoUtil.tensorDataTypeFromProto(t2.attributes.getInt("to")); - const i = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Cast requires 1 input."); - if ("string" === t2[0].type) - throw new Error("Invalid input type."); - }; - }, 1163: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createPackedConcatProgramInfoLoader = void 0; - const r = n(5060), i = n(2039), o = n(9390), a = n(2827); - e.createPackedConcatProgramInfoLoader = (t2, e2, n2) => { - const u = (c = e2.length, l = n2.cacheKey, { name: "Concat (packed)", inputNames: Array.from({ length: c }, (t3, e3) => `X${e3}`), inputTypes: Array(c).fill(i.TextureType.packed), cacheHint: l }); - var c, l; - return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => { - const c2 = n3[0].dims.slice(); - if (u2 >= c2.length || u2 < -1 * c2.length) - throw new Error("axis specified for concat doesn't match input dimensionality"); - u2 < 0 && (u2 = c2.length + u2); - const l2 = c2.slice(0); - for (let t4 = 1; t4 < n3.length; t4++) { - const e4 = n3[t4].dims.slice(); - for (let t5 = 0; t5 < c2.length; t5++) - if (t5 === u2) - l2[u2] += e4[t5]; - else if (c2[t5] !== e4[t5]) - throw new Error("non concat dimensions must match"); - } - const p = l2.length, f = (0, a.getChannels)("coords", p), d = (0, o.getCoordsDataType)(p), h = (0, a.unpackFromChannel)(), g = n3.map((t4) => t4.dims), b = (0, o.getGlChannels)(p), m = new Array(g.length - 1); - m[0] = g[0][u2]; - for (let t4 = 1; t4 < m.length; t4++) - m[t4] = m[t4 - 1] + g[t4][u2]; - const y = b[u2], _ = b.slice(-2), v = b.join(); - let w = `if (${y} < ${m[0]}) { - return getChannel( - getX0(${v}), vec2(${_.join()})); - }`; - for (let t4 = 1; t4 < m.length; t4++) { - const e4 = m[t4 - 1]; - w += ` - if (${y} < ${m[t4]} && ${y} >= ${m[t4 - 1]}) { - return getChannel( - getX${t4}(${s(b, y, e4)}), - vec2(${s(_, y, e4)})); - }`; - } - const x = m.length, T = m[m.length - 1]; - w += ` - return getChannel( - getX${x}(${s(b, y, T)}), - vec2(${s(_, y, T)}));`; - const S = (0, r.getGlsl)(t3.session.backend.glContext.version), O = ` - ${h} - float getValue(${b.map((t4) => "int " + t4)}) { - ${w} - } - - void main() { - ${d} coords = getOutputCoords(); - int lastDim = coords.${b[p - 1]}; - coords.${b[p - 1]} = coords.${b[p - 2]}; - coords.${b[p - 2]} = lastDim; - - vec4 result = vec4(getValue(${f}), 0., 0., 0.); - - ${f[p - 1]} = ${f[p - 1]} + 1; - if (${f[p - 1]} < ${l2[p - 1]}) { - result.g = getValue(${f}); - } - - ${f[p - 2]} = ${f[p - 2]} + 1; - if (${f[p - 2]} < ${l2[p - 2]}) { - result.a = getValue(${f}); - } - - ${f[p - 1]} = ${f[p - 1]} - 1; - if (${f[p - 2]} < ${l2[p - 2]} && - ${f[p - 1]} < ${l2[p - 1]}) { - result.b = getValue(${f}); - } - ${S.output} = result; - } - `; - return Object.assign(Object.assign({}, e3), { output: { dims: l2, type: n3[0].type, textureType: i.TextureType.packed }, shaderSource: O, hasMain: true }); - })(t2, u, e2, n2.axis) }); - }; - const s = (t2, e2, n2) => { - const r2 = t2.indexOf(e2); - return t2.map((t3, e3) => e3 === r2 ? `${t3} - ${n2}` : t3).join(); - }; - }, 2069: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseConcatAttributes = e.concat = void 0; - const r = n(246), i = n(2039), o = n(1163); - e.concat = (t2, e2, n2) => (p(e2), t2.session.pack && e2[0].dims.length > 1 ? [t2.run((0, o.createPackedConcatProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(a(t2, e2, n2), e2)]); - const a = (t2, e2, n2) => { - const r2 = (o2 = e2.length, a2 = n2.cacheKey, { name: "Concat", inputNames: Array.from({ length: o2 }, (t3, e3) => `X${e3}`), inputTypes: Array(o2).fill(i.TextureType.unpacked), cacheHint: a2 }); - var o2, a2; - return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { - const o3 = n3[0].dims.slice(); - if (r3 >= o3.length || r3 < -1 * o3.length) - throw new Error("axis specified for concat doesn't match input dimensionality"); - r3 < 0 && (r3 = o3.length + r3); - const a3 = o3.slice(0); - for (let t4 = 1; t4 < n3.length; t4++) { - const e4 = n3[t4].dims.slice(); - for (let t5 = 0; t5 < o3.length; t5++) - if (t5 === r3) - a3[r3] += e4[t5]; - else if (o3[t5] !== e4[t5]) - throw new Error("non concat dimensions must match"); - } - const p2 = a3.length, f = new Array(n3.length); - let d = 0; - for (let t4 = 0; t4 < f.length; ++t4) - d += n3[t4].dims[r3], f[t4] = d; - let h = ""; - h = n3.length < 5 ? s(f) : u(f); - const g = ` - ${c(n3.length, p2)} - ${l(f)} - ${h} - float process(int indices[${p2}]) { - int textureIndex = getTextureWhereDataResides (indices[${r3}]); - - if(textureIndex != 0) { - indices[${r3}] = indices[${r3}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1))); - } - - return fetchDataFromCorrectTexture(textureIndex, indices); - }`; - return Object.assign(Object.assign({}, e3), { output: { dims: a3, type: n3[0].type, textureType: i.TextureType.unpacked }, shaderSource: g }); - })(0, r2, e2, n2.axis) }); - }, s = (t2) => `int getTextureWhereDataResides(int index) { - ${t2.map((t3, e2) => `if(index<${t3}) {return ${e2};} -`).join("")} - }`, u = (t2) => s(t2), c = (t2, e2) => { - const n2 = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e2}]) {`]; - for (let e3 = 0; e3 < t2; ++e3) - 0 === e3 ? n2.push(` if (textureIndex == ${e3}) { return _X${e3}(indices); }`) : e3 === t2 - 1 ? n2.push(` else { return _X${e3}(indices); }`) : n2.push(` else if (textureIndex == ${e3}) { return _X${e3}(indices); }`); - return n2.push(" }"), n2.join("\n"); - }, l = (t2) => { - const e2 = ["int getSizeInConcatAxisValueFromIndex(int index) {"]; - for (let n2 = 0; n2 < t2.length; ++n2) - 0 === n2 ? e2.push(` if (index == ${n2}) { return ${t2[n2]}; }`) : n2 === t2.length - 1 ? e2.push(` else { return ${t2[n2]}; }`) : e2.push(` else if (index == ${n2}) { return ${t2[n2]}; }`); - return e2.push(" }"), e2.join("\n"); - }; - e.parseConcatAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis") }); - const p = (t2) => { - if (!t2 || t2.length < 1) - throw new Error("too few inputs"); - const e2 = t2[0].type, n2 = t2[0].dims.length; - if ("string" === e2) - throw new Error("string tensor is not supported yet"); - for (const r2 of t2) { - if (r2.type !== e2) - throw new Error("input tensors should be one type"); - if (r2.dims.length !== n2) - throw new Error("input tensors should have the same shape"); - } - }; - }, 4770: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackedGroupedConvProgramInfoLoader = void 0; - const r = n(6231), i = n(5060), o = n(2039), a = n(8138), s = n(2823); - e.createUnpackedGroupedConvProgramInfoLoader = (t2, e2, n2) => { - const u = (c = e2.length > 2, l = n2.cacheKey, { name: "GroupedConv", inputNames: c ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: c ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: l }); - var c, l; - return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => { - const c2 = e3.length > 2 ? "value += getBias(output_channel);" : "", l2 = e3[0].dims.slice(), p = e3[1].dims.slice(), f = p[0] / u2.group; - r.Logger.verbose("GroupedConv", `autpPad:${u2.autoPad}, dilations:${u2.dilations}, group:${u2.group}, kernelShape:${u2.kernelShape}, pads:${u2.pads}, strides:${u2.strides}`); - const d = (0, a.calculateOutputShape)(l2, p, u2.dilations, u2.pads, u2.strides), h = (0, i.getGlsl)(t3.session.backend.glContext.version), { activationFunction: g, applyActivation: b } = (0, s.getActivationSnippet)(u2), m = ` - const ivec2 strides = ivec2(${u2.strides[0]}, ${u2.strides[1]}); - const ivec2 pads = ivec2(${u2.pads[0]}, ${u2.pads[1]}); - ${g} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - ivec2 xRCCorner = coords.zw * strides - pads; - int group_id = output_channel / ${f}; - - float value = 0.0; - for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) { - int input_channel = group_id * ${p[1]} + wInChannel; - for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) { - int xHeight = xRCCorner.x + wHeight * ${u2.dilations[0]}; - - if (xHeight < 0 || xHeight >= ${l2[2]}) { - continue; - } - - for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) { - int xWidth = xRCCorner.y + wWidth * ${u2.dilations[1]}; - if (xWidth < 0 || xWidth >= ${l2[3]}) { - continue; - } - - float xVal = getX(batch, input_channel, xWidth, xHeight); - float wVal = getW(output_channel, wInChannel, wWidth, wHeight); - value += xVal*wVal; - } - } - } - ${c2} - ${b} - ${h.output} = vec4(value, .0, .0, .0); - } -`; - return Object.assign(Object.assign({}, n3), { output: { dims: d, type: e3[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, hasMain: true }); - })(t2, e2, u, n2) }); - }; - }, 1386: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.conv2DPacked = e.conv2DPackedPointwise = void 0; - const r = n(8138), i = n(8555), o = n(708); - e.conv2DPackedPointwise = (t2, e2, n2) => { - const i2 = e2[0].dims, a = e2[1].dims, s = (0, r.calculateOutputShape)(i2, a, n2.dilations, n2.pads, n2.strides), u = t2.reshapePacked(e2[0], [i2[1], i2[2] * i2[3]]), c = t2.reshapePacked(e2[1], [a[0], a[1]]), l = e2.length > 2 ? [c, u, e2[2]] : [c, u], p = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, l, n2), l); - return t2.reshapePacked(p, s); - }, e.conv2DPacked = (t2, e2, n2) => { - const a = e2[0].dims, s = e2[1].dims, u = (0, r.calculateOutputShape)(a, s, n2.dilations, n2.pads, n2.strides), c = t2.run((0, i.createPackedIm2ColProgramInfoLoader)(t2, e2[0], e2[1], u, n2), [e2[0]]), l = t2.reshapePacked(e2[1], [s[0], s[1] * s[2] * s[3]]), p = 3 === e2.length ? [l, c, e2[2]] : [l, c], f = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, p, n2), p); - return t2.reshapePacked(f, u); - }; - }, 9663: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseConvTransposeAttributes = e.convTranspose = void 0; - const r = n(246), i = n(5060), o = n(2039), a = n(2823), s = (t2, e2, n2, r2, i2, o2) => (t2 - 1) * e2 + n2 + (r2 - 1) * i2 + 1 - o2, u = (t2, e2, n2, r2, i2) => { - const o2 = Math.floor(t2 / 2); - "SAME_UPPER" === e2 ? (n2[r2] = o2, n2[i2] = t2 - o2) : "SAME_LOWER" === e2 && (n2[r2] = t2 - o2, n2[i2] = o2); - }; - e.convTranspose = (t2, e2, n2) => (f(e2, n2), c(t2, e2, n2)); - const c = (t2, e2, n2) => { - const r2 = p(n2, e2); - return [l(t2, e2, r2)]; - }, l = (t2, e2, n2) => t2.run(((t3, e3, n3) => { - const r2 = (s2 = e3.length > 2, u2 = n3.cacheKey, { name: "ConvTranspose", inputNames: s2 ? ["X", "W", "B"] : ["X", "W"], inputTypes: s2 ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: u2 }); - var s2, u2; - return Object.assign(Object.assign({}, r2), { get: () => ((t4, e4, n4, r3) => { - const s3 = e4.length > 2 ? "getB(output_channel)" : "0.0", u3 = e4[0].dims, c2 = e4[1].dims, l2 = c2[1], p2 = c2[0] / r3.group, f2 = [e4[0].dims[0], e4[1].dims[1] * r3.group, ...r3.outputShape], d = (0, i.getGlsl)(t4.session.backend.glContext.version), { activationFunction: h, applyActivation: g } = (0, a.getActivationSnippet)(r3), b = ` - const ivec2 strides = ivec2(${r3.strides[0]}, ${r3.strides[1]}); - const ivec2 pads = ivec2(${r3.pads[0]}, ${r3.pads[1]}); - ${h} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - - ivec2 loc = coords.zw + pads; - - int group_id = output_channel / ${l2}; - int wOutChannel = output_channel - group_id * ${l2}; - - float value = ${s3}; - for (int inChannelOffset = 0; inChannelOffset < ${p2}; inChannelOffset++) { - int input_channel = group_id * ${p2} + inChannelOffset; - for (int wWOff = 0; wWOff < ${c2[2]}; wWOff++) { - for (int wHOff = 0; wHOff < ${c2[3]}; wHOff++) { - ivec2 wOff = ivec2(wWOff * ${r3.dilations[0]}, wHOff * ${r3.dilations[1]}); - ivec2 wLoc = loc - wOff; - ivec2 wLocIn = wLoc / strides; - if ( - wLocIn * strides == wLoc && - wLocIn.x >= 0 && wLocIn.x < ${u3[2]} && - wLocIn.y >= 0 && wLocIn.y < ${u3[3]} - ) { - float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); - float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); - value += xVal * wVal; - } - } - } - } - ${g} - ${d.output} = vec4(value, .0, .0, .0); - } -`; - return Object.assign(Object.assign({}, n4), { output: { dims: f2, type: e4[0].type, textureType: o.TextureType.unpacked }, shaderSource: b, hasMain: true }); - })(t3, e3, r2, n3) }); - })(t2, e2, n2), e2), p = (t2, e2) => { - const n2 = t2.kernelShape.slice(); - if (0 === t2.kernelShape.length) - for (let t3 = 2; t3 < e2[1].dims.length; ++t3) - n2.push(e2[1].dims[t3]); - const r2 = t2.pads.slice(), i2 = t2.outputShape.slice(); - ((t3, e3, n3, r3, i3, o3, a2, c2) => { - const l2 = t3.length - 2, p2 = 0 === c2.length; - for (let f2 = 0; f2 < l2; ++f2) { - const d = p2 ? t3[f2 + 2] * o3[f2] : c2[f2], h = s(t3[f2 + 2], o3[f2], i3[f2], e3[f2], n3[f2], d); - u(h, r3, i3, f2, f2 + l2), p2 && c2.push(o3[f2] * (t3[f2 + 2] - 1) + a2[f2] + (e3[f2] - 1) * n3[f2] + 1 - i3[f2] - i3[f2 + l2]); - } - })(e2[0].dims, n2, t2.dilations, t2.autoPad, r2, t2.strides, t2.outputPadding, i2); - const o2 = Object.assign({}, t2); - return Object.assign(o2, { kernelShape: n2, pads: r2, outputShape: i2, cacheKey: t2.cacheKey }), o2; - }; - e.parseConvTransposeAttributes = (t2) => { - const e2 = t2.attributes, n2 = (0, a.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), s2 = e2.getInt("group", 1), u2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("output_padding", [0, 0]), l2 = e2.getInts("output_shape", []), p2 = e2.getInts("pads", [0, 0, 0, 0]), f2 = e2.getInts("strides", [1, 1]); - return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: s2, kernelShape: u2, outputPadding: c2, outputShape: l2, pads: p2, strides: f2 }, n2)); - }; - const f = (t2, e2) => { - if (!t2 || 2 !== t2.length && 3 !== t2.length) - throw new Error("Conv requires 2 or 3 inputs"); - if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) - throw new Error("currently only support 2-dimensional conv"); - if (t2[0].dims[1] !== t2[1].dims[0]) - throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); - const n2 = t2[1].dims[1] * e2.group; - if (3 === t2.length && (1 !== t2[2].dims.length || t2[2].dims[0] !== n2)) - throw new Error("invalid bias"); - const r2 = t2[0].dims.length - 2; - if (e2.dilations.length !== r2) - throw new Error(`dilations should be ${r2}D`); - if (e2.strides.length !== r2) - throw new Error(`strides should be ${r2}D`); - if (e2.pads.length !== 2 * r2) - throw new Error(`pads should be ${2 * r2}D`); - if (e2.outputPadding.length !== r2) - throw new Error(`output_padding should be ${r2}D`); - if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) - throw new Error("invalid kernel shape"); - if (0 !== e2.outputShape.length && e2.outputShape.length !== t2[0].dims.length - 2) - throw new Error("invalid output shape"); - if ("float32" !== t2[0].type || "float32" !== t2[1].type) - throw new Error("ConvTranspose input(X,W) should be float tensor"); - if (3 === t2.length && "float32" !== t2[2].type) - throw new Error("ConvTranspose input(bias) should be float tensor"); - }; - }, 8138: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseConvAttributes = e.conv = e.calculateOutputShape = void 0; - const r = n(246), i = n(2517), o = n(4770), a = n(1386), s = n(9828), u = n(2823), c = n(3248), l = n(5623); - e.calculateOutputShape = (t2, e2, n2, r2, i2) => { - const o2 = t2[0], a2 = t2.slice(2), s2 = a2.length, u2 = e2[0], c2 = e2.slice(2).map((t3, e3) => t3 + (t3 - 1) * (n2[e3] - 1)), l2 = a2.map((t3, e3) => t3 + r2[e3] + r2[e3 + s2]).map((t3, e3) => Math.floor((t3 - c2[e3] + i2[e3]) / i2[e3])); - return [o2, u2].concat(...l2); - }, e.conv = (t2, e2, n2) => (g(e2, n2), p(t2, e2, n2)); - const p = (t2, e2, n2) => { - const r2 = h(n2, e2), i2 = t2.session.pack, s2 = 1 === r2.kernelShape[0] && 1 === r2.kernelShape[1]; - return r2.group > 1 ? [t2.run((0, o.createUnpackedGroupedConvProgramInfoLoader)(t2, e2, r2), e2)] : s2 && i2 ? [f(t2, e2, r2)] : i2 && 4 === e2[0].dims.length && 1 === e2[0].dims[0] && !s2 ? [(0, a.conv2DPacked)(t2, e2, r2)] : [d(t2, e2, r2)]; - }, f = (t2, n2, r2) => { - const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), s2 = t2.reshapeUnpacked(n2[0], [i2[1], i2[2] * i2[3]]), u2 = t2.reshapeUnpacked(n2[1], [o2[0], o2[1]]), c2 = n2.length > 2 ? [u2, s2, n2[2]] : [u2, s2], p2 = t2.run((0, l.createMatmulProgramInfoLoader)(c2, r2), c2); - return t2.reshapeUnpacked(p2, a2); - }, d = (t2, n2, r2) => { - const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), u2 = t2.run((0, c.createIm2ColProgramInfoLoader)(t2, n2[0], n2[1], a2, r2), [n2[0]]), l2 = 3 === n2.length ? [u2, n2[1], n2[2]] : [u2, n2[1]]; - return t2.run((0, s.createDotProductProgramInfoLoader)(t2, n2, a2, r2), l2); - }, h = (t2, e2) => { - const n2 = t2.kernelShape.slice(); - if (0 === t2.kernelShape.length) - for (let t3 = 2; t3 < e2[1].dims.length; ++t3) - n2.push(e2[1].dims[t3]); - const r2 = t2.pads.slice(); - i.PoolConvUtil.adjustPadsBasedOnAutoPad(e2[0].dims, t2.strides, t2.dilations, n2, r2, t2.autoPad); - const o2 = Object.assign({}, t2); - return Object.assign(o2, { kernelShape: n2, pads: r2, cacheKey: t2.cacheKey }), o2; - }; - e.parseConvAttributes = (t2) => { - const e2 = t2.attributes, n2 = (0, u.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), a2 = e2.getInt("group", 1), s2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("pads", [0, 0, 0, 0]), l2 = e2.getInts("strides", [1, 1]); - return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: a2, kernelShape: s2, pads: c2, strides: l2 }, n2)); - }; - const g = (t2, e2) => { - if (!t2 || 2 !== t2.length && 3 !== t2.length) - throw new Error("Conv requires 2 or 3 inputs"); - if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) - throw new Error("currently only support 2-dimensional conv"); - if (t2[0].dims[1] !== t2[1].dims[1] * e2.group) - throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); - if (3 === t2.length && (1 !== t2[2].dims.length || t2[1].dims[0] !== t2[2].dims[0])) - throw new Error("invalid bias"); - const n2 = t2[0].dims.length - 2; - if (e2.dilations.length !== n2) - throw new Error(`dilations should be ${n2}D`); - if (e2.strides.length !== n2) - throw new Error(`strides should be ${n2}D`); - if (e2.pads.length !== 2 * n2) - throw new Error(`pads should be ${2 * n2}D`); - if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) - throw new Error("invalid kernel shape"); - if ("float32" !== t2[0].type || "float32" !== t2[1].type) - throw new Error("Conv input(X,W) should be float tensor"); - if (3 === t2.length && "float32" !== t2[2].type) - throw new Error("Conv input(bias) should be float tensor"); - }; - }, 5193: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseDepthToSpaceAttributes = e.depthToSpace = void 0; - const r = n(3738); - e.depthToSpace = (t2, e2, n2) => { - i(e2); - const o = n2.blocksize, a = o * o, s = "DCR" === n2.mode ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], u = "DCR" === n2.mode ? [e2[0].dims[0], o, o, e2[0].dims[1] / a, e2[0].dims[2], e2[0].dims[3]] : [e2[0].dims[0], e2[0].dims[1] / a, o, o, e2[0].dims[2], e2[0].dims[3]], c = t2.reshapeUnpacked(e2[0], u), l = { perm: s, cacheKey: `${s}` }, [p] = (0, r.transpose)(t2, [c], l), f = [e2[0].dims[0], e2[0].dims[1] / a, e2[0].dims[2] * o, e2[0].dims[3] * o]; - return [t2.reshapeUnpacked(p, f)]; - }, e.parseDepthToSpaceAttributes = (t2) => { - const e2 = t2.attributes.getInt("blocksize"); - if (e2 < 1) - throw new Error(`blocksize must be >= 1, but got : ${e2} for DepthToSpace`); - const n2 = t2.attributes.getString("mode", "DCR"); - if ("DCR" !== n2 && "CRD" !== n2) - throw new Error(`unrecognized mode: ${n2} for DepthToSpace`); - return { mode: n2, blocksize: e2 }; - }; - const i = (t2) => { - if (1 !== t2.length) - throw new Error(`DepthToSpace expect 1 inputs, but got ${t2.length}`); - if ("string" === t2[0].type || 4 !== t2[0].dims.length) - throw new TypeError("DepthToSpace input should be a 4-D numeric tensor"); - }; - }, 9828: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createDotProductProgramInfoLoader = void 0; - const r = n(2517), i = n(5060), o = n(2039), a = n(2823), s = n(3248); - e.createDotProductProgramInfoLoader = (t2, e2, n2, u) => { - const c = ((t3, e3) => ({ name: "ConvDotProduct", inputNames: t3 ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: t3 ? [o.TextureType.unpacked, o.TextureType.packedLastDimension, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.packedLastDimension], cacheKey: e3.activationCacheKey }))(e2.length > 2, u); - return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, u2, c2) => { - const l = n3[0].dims, p = n3[1].dims, f = [p[0], Math.ceil(l[1] * p[2] * p[3] / 4)], d = (0, s.calculateIm2ColDims)(l, p, u2), [h, g] = t3.calculateTextureWidthAndHeight(f, o.TextureType.packedLastDimension), b = r.ShapeUtil.computeStrides(d), [m, y] = t3.calculateTextureWidthAndHeight(d, o.TextureType.packedLastDimension), _ = u2.length, v = n3.length < 3 ? "0.0" : "_B(b)", w = Math.ceil(l[1] * p[2] * p[3] / 4), { activationFunction: x, applyActivation: T } = (0, a.getActivationSnippet)(c2), S = (0, i.getGlsl)(t3.session.backend.glContext.version), O = ` -${x} -float process(int indices[${_}]) { - int b[1]; - b[0] = indices[1]; - int im2col[4]; - im2col[0] = indices[0]; - im2col[1] = indices[2]; - im2col[2] = indices[3]; - int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]}; - int kernelOffset = indices[1] * ${f[1]}; - float value = ${v}; - for (int i = 0; i < ${w}; ++i) { - vec2 im2colCoords = offsetToCoords(im2colOffset, ${m}, ${y}); - vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g}); - value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords)); - ++im2colOffset; - ++kernelOffset; - } - ${T} - return value; -}`; - return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: o.TextureType.unpacked }, shaderSource: O }); - })(t2, c, e2, n2, u) }); - }; - }, 7992: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseFlattenAttributes = e.flatten = void 0; - const r = n(2517); - e.flatten = (t2, e2, n2) => { - i(e2, n2); - const o = r.ShapeUtil.flattenShape(e2[0].dims, n2); - return [t2.reshapeUnpacked(e2[0], o)]; - }, e.parseFlattenAttributes = (t2) => t2.attributes.getInt("axis", 1); - const i = (t2, e2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Flatten requires 1 input."); - const n2 = t2[0].dims.length; - if (0 === n2) - throw new Error("scalar tensor is not supported."); - if (e2 < -n2 || e2 > n2) - throw new Error("Invalid axis"); - if ("string" === t2[0].type) - throw new Error("string tensor is not supported."); - }; - }, 2823: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseInternalActivationAttributes = e.getActivationSnippet = void 0; - const r = n(2517), i = n(4909); - e.getActivationSnippet = function(t2) { - let e2; - switch (t2.activation) { - case "Relu": - e2 = (0, i.glslRelu)(); - break; - case "Sigmoid": - e2 = (0, i.glslSigmoid)(); - break; - case "Clip": - e2 = (0, i.glslClip)(t2.clipMin, t2.clipMax); - break; - default: - return { activationFunction: "", applyActivation: "" }; - } - const n2 = e2.name; - return { activationFunction: e2.body, applyActivation: `value = ${n2}_(value);` }; - }, e.parseInternalActivationAttributes = (t2) => { - const e2 = t2.getString("activation", ""); - if ("Clip" === e2) { - const [n2, i2] = t2.getFloats("activation_params", [r.MIN_CLIP, r.MAX_CLIP]); - return { activation: e2, clipMax: i2, clipMin: n2, activationCacheKey: `${e2}:${n2},${i2}` }; - } - return { activation: e2, activationCacheKey: e2 }; - }; - }, 1253: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseGatherAttributes = e.gather = void 0; - const r = n(246), i = n(782), o = n(2517), a = n(2039); - e.gather = (t2, e2, n2) => (c(e2, n2.axis), [t2.run(u(t2, e2, n2), e2)]), e.parseGatherAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 0) }); - const s = { name: "Gather", inputNames: ["A", "B"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, u = (t2, e2, n2) => { - const r2 = Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey }); - return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { - const i2 = n3[0].dims.slice(), s2 = n3[1].dims.slice(), u2 = new Array(i2.length + s2.length - 1); - r3 = o.ShapeUtil.normalizeAxis(r3, i2.length); - const c2 = []; - for (let t4 = 0; t4 < u2.length; t4++) - t4 < r3 ? (u2[t4] = i2[t4], c2.push(`inputIdx[${t4}] = outputIdx[${t4}];`)) : t4 < r3 + s2.length ? (u2[t4] = s2[t4 - r3], c2.push(`indexDataIdx[${t4 - r3}] = outputIdx[${t4}];`)) : (u2[t4] = i2[t4 - s2.length + 1], c2.push(`inputIdx[${t4 - s2.length + 1}] = outputIdx[${t4}];`)); - const l = ` - float process(int outputIdx[${u2.length || 1}]) { - int inputIdx[${i2.length}]; - int indexDataIdx[${s2.length || 1}]; - indexDataIdx[0] = 0; - ${c2.join("\n ")} - int idx = int(_B(indexDataIdx)); - inputIdx[${r3}] = idx < 0 ? idx + ${i2[r3]} : idx; - return _A(inputIdx); - }`; - return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: a.TextureType.unpacked }, shaderSource: l }); - })(0, r2, e2, n2.axis) }); - }, c = (t2, e2) => { - if (!t2 || 2 !== t2.length) - throw new Error("Gather requires 2 inputs."); - const n2 = t2[0].dims.length; - if (n2 < 1) - throw new Error("Invalid input shape."); - if (e2 < -n2 || e2 > n2 - 1) - throw new Error("Invalid axis."); - if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) - throw new Error("Invaid input type."); - if ("int32" !== t2[1].type && "int16" !== t2[1].type) - throw new Error("Invaid input type."); - }; - }, 4776: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseGemmAttributesV11 = e.parseGemmAttributesV7 = e.gemm = void 0; - const r = n(246), i = n(2517), o = n(2039); - e.gemm = (t2, e2, n2) => (c(e2, n2), [t2.run(s(e2, n2), e2)]); - const a = (t2, e2) => { - const n2 = 0 !== t2.attributes.getInt("transA", 0), i2 = 0 !== t2.attributes.getInt("transB", 0), o2 = t2.attributes.getFloat("alpha", 1), a2 = t2.attributes.getFloat("beta", 1); - return (0, r.createAttributeWithCacheKey)({ transA: n2, transB: i2, alpha: o2, beta: a2, isOptionalC: e2 }); - }; - e.parseGemmAttributesV7 = (t2) => a(t2, false), e.parseGemmAttributesV11 = (t2) => a(t2, true); - const s = (t2, e2) => { - const n2 = { name: "Gemm", inputNames: 3 === t2.length ? ["A", "B", "C"] : ["A", "B"], inputTypes: 3 === t2.length ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], key: e2.cacheKey }; - return Object.assign(Object.assign({}, n2), { get: () => u(n2, t2, e2) }); - }, u = (t2, e2, n2) => { - const r2 = e2[0].dims.slice(), a2 = e2[1].dims.slice(), [s2, u2] = i.GemmUtil.getShapeOfGemmResult(r2, n2.transA, a2, n2.transB, 3 === e2.length ? e2[2].dims : void 0), c2 = [s2, u2]; - if (!c2) - throw new Error("Can't use gemm on the given tensors"); - let l = r2[r2.length - 1], p = ""; - n2.transA && (l = r2[0]), n2.transA && n2.transB ? p = "value += _A_T(a) * _B_T(b);" : n2.transA && !n2.transB ? p = "value += _A_T(a) * _B(b);" : !n2.transA && n2.transB ? p = "value += _A(a) * _B_T(b);" : n2.transA || n2.transB || (p = "value += _A(a) * _B(b);"); - const f = c2.length, d = ` - float process(int indices[${f}]) { - int a[${f}]; - int b[${f}]; - ${3 === e2.length ? `int c[${e2[2].dims.length}];` : ""} - - copyVec(indices, a); - copyVec(indices, b); - ${3 === e2.length ? "bcastIndices_C(indices, c);" : ""} - - float value = 0.0; - for (int k=0; k<${l}; ++k) { - a[${f - 1}] = k; - b[${f - 2}] = k; - ${p} - } - - value = value * alpha; - ${3 === e2.length ? "value += beta * _C(c);" : ""} - return value; - }`; - return Object.assign(Object.assign({}, t2), { output: { dims: c2, type: e2[0].type, textureType: o.TextureType.unpacked }, variables: [{ name: "alpha", type: "float", data: n2.alpha }, { name: "beta", type: "float", data: n2.beta }], shaderSource: d }); - }, c = (t2, e2) => { - if (!t2) - throw new Error("Input is missing"); - if (e2.isOptionalC && (t2.length < 2 || t2.length > 3)) - throw new Error("Invaid input shape."); - if (!e2.isOptionalC && 3 !== t2.length) - throw new Error("Gemm requires 3 inputs"); - if (3 === t2.length && 1 !== t2[2].dims.length && 2 !== t2[2].dims.length) - throw new Error("Invalid input shape of C"); - if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type || 3 === t2.length && "float32" !== t2[2].type && "float64" !== t2[2].type) - throw new Error("Invalid input type."); - if (t2[0].type !== t2[1].type || 3 === t2.length && t2[0].type !== t2[2].type) - throw new Error("Input types are mismatched"); - }; - }, 8555: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createPackedIm2ColProgramInfoLoader = void 0; - const r = n(5060), i = n(2039), o = n(2827); - e.createPackedIm2ColProgramInfoLoader = (t2, e2, n2, a, s) => { - const u = (c = s.cacheKey, { name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [i.TextureType.packed], cacheHint: c }); - var c; - return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, a2, s2, u2) => { - const c2 = n3.dims, l = a2.dims, p = s2.length, f = [l[1] * l[2] * l[3], s2[2] * s2[3]], d = l[2] * l[3], h = (0, o.unpackFromChannel)(), g = (0, r.getGlsl)(t3.session.backend.glContext.version); - let b = ""; - for (let t4 = 0; t4 <= 1; t4++) - for (let e4 = 0; e4 <= 1; e4++) - b += ` - blockIndex = rc.x + ${e4}; - pos = rc.y + ${t4}; - - if(blockIndex < ${f[1]} && pos < ${f[0]}) { - offsetY = int(blockIndex / (${s2[p - 1]})) * ${u2.strides[0]} - - ${u2.pads[0]}; - d0 = offsetY + ${u2.dilations[0]} * (imod(pos, ${d}) / ${l[2]}); - - if(d0 < ${c2[2]} && d0 >= 0) { - offsetX = imod(blockIndex, ${s2[p - 1]}) * ${u2.strides[1]} - - ${u2.pads[1]}; - d1 = offsetX + ${u2.dilations[1]} * imod(imod(pos, ${d}), ${l[2]}); - - if(d1 < ${c2[3]} && d1 >= 0) { - - ch = int(float(pos)/ ${d}.); - innerDims = vec2(d0, d1); - result[${2 * t4 + e4}] = getChannel( - getA(0, ch, int(innerDims.x), - int(innerDims.y)), innerDims); - } - } - } - - `; - const m = ` - ${h} - - void main() { - ivec2 rc = getOutputCoords(); - vec4 result = vec4(0.0); - int blockIndex, pos, offsetY, d0, offsetX, d1, ch; - vec2 innerDims; - ${b} - ${g.output} = result; - } - `; - return Object.assign(Object.assign({}, e3), { output: { dims: f, type: n3.type, textureType: i.TextureType.packed }, shaderSource: m, hasMain: true }); - })(t2, u, e2, n2, a, s) }); - }; - }, 3248: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.calculateIm2ColDims = e.createIm2ColProgramInfoLoader = void 0; - const r = n(2039); - e.createIm2ColProgramInfoLoader = (t2, n2, i, o, a) => { - const s = (u = a.cacheKey, { name: "Im2Col", inputNames: ["X"], inputTypes: [r.TextureType.unpacked], cacheHint: u }); - var u; - return Object.assign(Object.assign({}, s), { get: () => ((t3, n3, i2, o2, a2, s2) => { - const u2 = i2.dims, c = o2.dims, l = a2.length, p = (0, e.calculateIm2ColDims)(u2, c, a2, 4), f = ` - const int XC = ${u2[1]}; - const int XH = ${u2[2]}; - const int XW = ${u2[3]}; - const int KH = ${s2.kernelShape[0]}; - const int KW = ${s2.kernelShape[1]}; - const int dilationH = ${s2.dilations[0]}; - const int dilationW = ${s2.dilations[1]}; - const int strideH = ${s2.strides[0]}; - const int strideW = ${s2.strides[1]}; - const int padH = ${s2.pads[0]}; - const int padW = ${s2.pads[1]}; - const int KHKW = KH*KW; - const int XCKHKW = XC * KHKW; - const int outputChannels = 4; - vec4 process(int indices[${l}]) { - int b = indices[0]; // batch size - int oh = indices[1] * strideH - padH; //output height - int ow = indices[2] * strideW - padW; //output width - int p = indices[3] * outputChannels; //patch - vec4 value = vec4(0.0); - for(int i=0; i < outputChannels; ++i) { - if(p < XCKHKW) { - int patchC = p / KHKW; - int patchH = (p - patchC*KHKW) / KW; - int patchW = (p - patchC*KHKW) - patchH * KW; - int xh2 = oh + patchH * dilationH; - int xw2 = ow + patchW * dilationW; - int x[${u2.length}]; - x[0] = b; - x[1] = patchC; - x[2] = xh2; - x[3] = xw2; - if(xh2 >= 0 && - xh2 < XH && - xw2 >= 0 && - xw2 < XW) { - value[i] = _X(x); - } - } - ++p; - } - return value; - } - `; - return Object.assign(Object.assign({}, n3), { output: { dims: p, type: i2.type, textureType: r.TextureType.packedLastDimension }, shaderSource: f }); - })(0, s, n2, i, o, a) }); - }, e.calculateIm2ColDims = (t2, e2, n2, r2 = 4) => [n2[0], n2[2], n2[3], Math.ceil(t2[1] * e2[2] * e2[3] / r2)]; - }, 6572: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseImageScalerAttributes = e.imageScaler = void 0; - const r = n(246), i = n(2039); - e.imageScaler = (t2, e2, n2) => (u(e2), [t2.run(a(t2, e2, n2), e2)]), e.parseImageScalerAttributes = (t2) => { - const e2 = t2.attributes.getFloat("scale"), n2 = t2.attributes.getFloats("bias"); - return (0, r.createAttributeWithCacheKey)({ scale: e2, bias: n2 }); - }; - const o = { name: "ImageScaler", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2, e2, n2) => { - const r2 = Object.assign(Object.assign({}, o), { cacheHint: n2.cacheKey }); - return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { - const o2 = n3[0].dims.slice(), a2 = o2.length, u2 = ` - ${s(r3.bias.length)} - float process(int indices[${a2}]) { - return _X(indices) * scale + getBias(bias, indices[1]); - }`; - return Object.assign(Object.assign({}, e3), { output: { dims: o2, type: n3[0].type, textureType: i.TextureType.unpacked }, variables: [{ name: "bias", type: "float", arrayLength: r3.bias.length, data: r3.bias }, { name: "scale", type: "float", data: r3.scale }], shaderSource: u2 }); - })(0, r2, e2, n2) }); - }, s = (t2) => { - const e2 = [`float getBias(float bias[${t2}], int channel) {`]; - for (let n2 = 0; n2 < t2; ++n2) - 0 === n2 ? e2.push(` if (channel == ${n2}) { return bias[${n2}]; }`) : n2 === t2 - 1 ? e2.push(` else { return bias[${n2}]; }`) : e2.push(` else if (channel == ${n2}) { return bias[${n2}]; }`); - return e2.push(" }"), e2.join("\n"); - }, u = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("ImageScaler requires 1 input."); - if (4 !== t2[0].dims.length) - throw new Error("Invalid input shape."); - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("Invalid input type."); - }; - }, 3346: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseInstanceNormalizationAttributes = e.instanceNormalization = void 0; - const r = n(5060), i = n(2039); - e.instanceNormalization = (t2, e2, n2) => { - c(e2); - const r2 = t2.run(a(e2[0]), e2); - return [t2.run(u(t2, e2[0], n2, r2.dims), [e2[0], r2, e2[1], e2[2]])]; - }, e.parseInstanceNormalizationAttributes = (t2) => t2.attributes.getFloat("epsilon", 1e-5); - const o = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2) => Object.assign(Object.assign({}, o), { get: () => ((t3, e2) => { - const n2 = e2.dims.slice(), r2 = n2[1], o2 = n2[2] * n2[3], a2 = [n2[0], r2], s2 = ` - vec4 process(int[2] indices) { - vec4 v = vec4(0.0); - int a[4]; - a[0] = indices[0]; - a[1] = indices[1]; - float temp = 0.0; - for(int a2=0; a2<${n2[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${n2[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += x; - } - } - float mean = temp / float(${o2}); - temp = 0.0; - for(int a2=0; a2<${n2[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${n2[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += (x - mean) * (x - mean); - } - } - v.r = mean; - v.g = temp / float(${o2}); - - return v; - }`; - return Object.assign(Object.assign({}, t3), { output: { dims: a2, type: e2.type, textureType: i.TextureType.packedLastDimension }, shaderSource: s2 }); - })(o, t2) }), s = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [i.TextureType.unpacked, i.TextureType.packedLastDimension, i.TextureType.unpacked, i.TextureType.unpacked] }, u = (t2, e2, n2, o2) => { - const a2 = Object.assign(Object.assign({}, s), { cacheHint: `${n2}` }); - return Object.assign(Object.assign({}, a2), { get: () => ((t3, e3, n3, o3, a3) => { - const s2 = (0, r.getGlsl)(t3.session.backend.glContext.version), [u2, c2] = t3.calculateTextureWidthAndHeight(a3, i.TextureType.packedLastDimension), [l, p] = [u2 / 4, c2], f = ` - vec4 get_MeanAndVariance(int[2] mv) { - int offset = indicesToOffset_MeanAndVariance(mv); - vec2 coords = offsetToCoords(offset, ${l}, ${p}); - return ${s2.texture2D}(MeanAndVariance, coords); - } - - float process(int[4] indices) { - int mv[2]; - mv[0] = indices[0]; - mv[1] = indices[1]; - vec4 mean_and_variance = get_MeanAndVariance(mv); - float mean = mean_and_variance.r; - float variance = mean_and_variance.g; - - int sb[1]; - sb[0] = indices[1]; - float scale = _Scale(sb); - float b = _B(sb); - - return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; - }`; - return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i.TextureType.unpacked }, variables: [{ name: "epsilon", type: "float", data: o3 }], shaderSource: f }); - })(t2, a2, e2, n2, o2) }); - }, c = (t2) => { - if (!t2 || 3 !== t2.length) - throw new Error("InstanceNormalization requires 3 inputs."); - const e2 = t2[0], n2 = t2[1], r2 = t2[2]; - if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length) - throw new Error("Invalid input shape."); - if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1]) - throw new Error("Input shapes are mismatched."); - if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type) - throw new Error("Invalid input type."); - if (4 !== t2[0].dims.length) - throw new Error("Only support 4-D input shape."); - }; - }, 708: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createPackedMatmulProgramInfoLoader = void 0; - const r = n(2517), i = n(5060), o = n(2039), a = n(9390), s = n(2823), u = n(5623); - e.createPackedMatmulProgramInfoLoader = (t2, e2, n2) => { - const c = (l = e2.length > 2, p = n2.activationCacheKey, { name: "MatMul (packed)", inputNames: l ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: l ? [o.TextureType.packed, o.TextureType.packed, o.TextureType.packed] : [o.TextureType.packed, o.TextureType.packed], cacheHint: p }); - var l, p; - return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, c2) => { - const l2 = n3.length > 2, p2 = l2 ? "value += getBiasForMatmul();" : "", f = n3[0].dims, d = n3[1].dims, h = r.BroadcastUtil.calcShape(f, d, true), g = !r.ShapeUtil.areEqual(n3[0].dims, n3[1].dims); - if (!h) - throw new Error("Can't use matmul on the given tensors"); - const b = f[f.length - 1], m = Math.ceil(b / 2), y = f.length, _ = d.length, v = (0, i.getGlsl)(t3.session.backend.glContext.version), w = (0, a.getCoordsDataType)(h.length), x = h.length, T = (0, a.getGlChannels)(), { activationFunction: S, applyActivation: O } = (0, s.getActivationSnippet)(c2), A = l2 ? `${(0, u.getBiasForMatmul)(w, T, n3[2].dims, h, true)}` : "", E = g ? `${function(t4, e4, n4, i2) { - let o2 = [], a2 = []; - const s2 = n4[0].dims, u2 = n4[1].dims, c3 = s2.length, l3 = u2.length, p3 = i2.length, f2 = p3 - c3, d2 = p3 - l3; - o2 = s2.map((t5, n5) => `coords.${e4[n5 + f2]}`), o2[c3 - 1] = "i*2", o2.join(", "), a2 = u2.map((t5, n5) => `coords.${e4[n5 + d2]}`), a2[l3 - 2] = "i*2", a2.join(", "); - const h2 = r.BroadcastUtil.getBroadcastDims(s2, i2), g2 = r.BroadcastUtil.getBroadcastDims(u2, i2), b2 = h2.map((t5) => `coords.${e4[t5 + f2]} = 0;`).join("\n"), m2 = g2.map((t5) => `coords.${e4[t5 + d2]} = 0;`).join("\n"), y2 = `int lastDim = coords.${e4[p3 - 1]}; - coords.${e4[p3 - 1]} = coords.${e4[p3 - 2]}; - coords.${e4[p3 - 2]} = lastDim;`; - return ` -vec4 getAAtOutCoordsMatmul(int i) { - ${t4} coords = getOutputCoords(); - ${y2} - ${b2} - vec4 outputValue = getA(${o2}); - return outputValue; -} - -vec4 getBAtOutCoordsMatmul(int i) { - ${t4} coords = getOutputCoords(); - ${y2} - ${m2} - vec4 outputValue = getB(${a2}); - return outputValue; -}`; - }(w, T, n3, h)}` : "", I = g ? "getAAtOutCoordsMatmul(i)" : `getA(${function(t4, e4) { - let n4 = ""; - for (let r2 = 0; r2 < e4 - 2; r2++) - n4 += `rc.${t4[r2]}, `; - return n4 += `rc.${t4[e4 - 2]}, i*2`, n4; - }(T, y)})`, P = g ? "getBAtOutCoordsMatmul(i)" : `getB(${function(t4, e4) { - let n4 = ""; - for (let r2 = 0; r2 < e4 - 2; r2++) - n4 += `rc.${t4[r2]}, `; - return n4 += `i*2, rc.${t4[e4 - 1]}`, n4; - }(T, _)})`, D = ` - ${E} - ${A} - ${S} - void main() { - ${g ? "" : `${w} rc = - getOutputCoords(); int lastDim = rc.${T[x - 1]}; rc.${T[x - 1]} = - rc.${T[x - 2]}; rc.${T[x - 2]} = lastDim; - `} - - vec4 value = vec4(0); - for (int i = 0; i < ${m}; i++) { - vec4 a = ${I}; - vec4 b = ${P}; - - value += (a.rrbb * b.rgrg); - value += (a.ggaa * b.baba); - } - ${p2} - ${O} - ${v.output} = value; - }`; - return Object.assign(Object.assign({}, e3), { output: { dims: h, type: n3[0].type, textureType: o.TextureType.packed }, shaderSource: D, hasMain: true }); - })(t2, c, e2, n2) }); - }; - }, 5623: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.getBiasForMatmul = e.createMatmulProgramInfoLoader = e.parseMatMulAttributes = e.matMul = void 0; - const r = n(2517), i = n(2039), o = n(9390), a = n(2823), s = n(708); - function u(t2, e2) { - const n2 = (s2 = t2.length > 2, u2 = e2.activationCacheKey, { name: "MatMul", inputNames: s2 ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: s2 ? [i.TextureType.unpacked, i.TextureType.unpacked, i.TextureType.unpacked] : [i.TextureType.unpacked, i.TextureType.unpacked], cacheHint: u2 }); - var s2, u2; - return Object.assign(Object.assign({}, n2), { get: () => function(t3, e3, n3) { - const s3 = e3[0].dims, u3 = e3[1].dims, c2 = r.BroadcastUtil.calcShape(s3, u3, true); - if (!c2) - throw new Error("Can't use matmul on the given tensors"); - const p = (0, o.getCoordsDataType)(c2.length), f = (0, o.getGlChannels)(), { activationFunction: d, applyActivation: h } = (0, a.getActivationSnippet)(n3), g = e3.length > 2, b = g ? "value += getBiasForMatmul();" : "", m = g ? `${l(p, f, e3[2].dims, c2, false)}` : "", y = c2.length, _ = s3.length, v = u3.length, w = ` - ${d} - ${m} - float process(int indices[${y}]) { - int a[${_}]; - int b[${v}]; - bcastMatmulIndices_A(indices, a); - bcastMatmulIndices_B(indices, b); - - float value; - for (int k=0; k<${s3[s3.length - 1]}; ++k) { - a[${_ - 1}] = k; - b[${v - 2}] = k; - value += _A(a) * _B(b); - } - ${b} - ${h} - return value; - }`; - return Object.assign(Object.assign({}, t3), { output: { dims: c2, type: e3[0].type, textureType: i.TextureType.unpacked }, shaderSource: w }); - }(n2, t2, e2) }); - } - e.matMul = (t2, e2, n2) => (c(e2), t2.session.pack ? [t2.run((0, s.createPackedMatmulProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(u(e2, n2), e2)]), e.parseMatMulAttributes = (t2) => (0, a.parseInternalActivationAttributes)(t2.attributes), e.createMatmulProgramInfoLoader = u; - const c = (t2) => { - if (!t2 || 2 !== t2.length) - throw new Error("MatMul requires 2 inputs."); - if (t2[0].dims[t2[0].dims.length - 1] !== t2[1].dims[t2[1].dims.length - 2]) - throw new Error("shared dimension does not match."); - if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type) - throw new Error("inputs should be float type"); - if (t2[0].type !== t2[1].type) - throw new Error("inputs types should match"); - }; - function l(t2, e2, n2, i2, o2) { - let a2 = ""; - const s2 = n2.length, u2 = i2.length, c2 = u2 - s2; - a2 = u2 < 2 && s2 > 0 ? "coords" : n2.map((t3, n3) => `coords.${e2[n3 + c2]}`).join(", "); - const l2 = r.BroadcastUtil.getBroadcastDims(n2, i2).map((t3) => `coords.${e2[t3 + c2]} = 0;`).join("\n"); - let p = "vec4(outputValue.xx, outputValue.yy)"; - return 1 === r.ShapeUtil.size(n2) && (p = "vec4(outputValue.x)"), o2 ? ` -vec4 getBiasForMatmul() { - ${t2} coords = getOutputCoords(); - ${l2} - vec4 outputValue = getBias(${a2}); - return ${p}; -}` : ` -float getBiasForMatmul() { - ${t2} coords = getOutputCoords(); - ${l2} - return getBias(coords.x); -}`; - } - e.getBiasForMatmul = l; - }, 2403: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createPackProgramInfoLoader = void 0; - const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = { name: "pack", inputNames: ["A"], inputTypes: [i.TextureType.unpackedReversed] }; - e.createPackProgramInfoLoader = (t2, e2) => Object.assign(Object.assign({}, s), { get: () => ((t3, e3) => { - const n2 = (0, r.getGlsl)(t3.session.backend.glContext.version), u = e3.dims, c = u.length, l = e3.dims.length, p = (0, o.getCoordsDataType)(l), f = (0, a.getChannels)("rc", l), d = (h = l, g = f, b = u[u.length - 2], m = u[u.length - 1], 0 === h || 1 === h ? "" : ` - int r = ${g[h - 2]}; - int c = ${g[h - 1]}; - int rp1 = ${g[h - 2]} + 1; - int cp1 = ${g[h - 1]} + 1; - bool rEdge = rp1 >= ${m}; - bool cEdge = cp1 >= ${b}; - `); - var h, g, b, m; - let y; - y = 0 === c ? [1, 1] : 1 === c ? [u[0], 1] : [u[l - 1], u[l - 2]]; - const _ = function(t4, e4, n3) { - if (0 === t4) - return "false"; - if (1 === t4) - return `rc > ${e4[0]}`; - let r2 = ""; - for (let i2 = t4 - 2; i2 < t4; i2++) - r2 += `${n3[i2]} >= ${e4[i2 - t4 + 2]}`, i2 < t4 - 1 && (r2 += "||"); - return r2; - }(l, y, f), v = function(t4, e4) { - const n3 = t4.length; - if (0 === n3) - return "getA(), 0, 0, 0"; - if (1 === n3) - return `getA(rc), - rc + 1 >= ${t4[0]} ? 0. : getA(rc + 1), - 0, 0`; - let r2 = ""; - if (n3 > 2) - for (let t5 = 0; t5 < n3 - 2; ++t5) - r2 += `${e4[t5]},`; - return `getA(${r2}r, c), - rEdge ? 0. : getA(${r2}rp1, c), - cEdge ? 0. : getA(${r2}r, cp1), - rEdge || cEdge ? 0. : getA(${r2}rp1, cp1)`; - }(u, f), w = ` - void main() { - ${p} rc = getOutputCoords(); - - if(${_}) { - ${n2.output} = vec4(0); - } else { - ${d} - - ${n2.output} = vec4(${v}); - } - } - `; - return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e3.dims, type: e3.type, textureType: i.TextureType.packed }, shaderSource: w }); - })(t2, e2) }); - }, 2827: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.unpackFromChannel = e.getChannels = e.getVecChannels = void 0; - const r = n(9390); - function i(t2, e2) { - return (0, r.getGlChannels)(e2).map((e3) => `${t2}.${e3}`); - } - e.getVecChannels = i, e.getChannels = function(t2, e2) { - return 1 === e2 ? [t2] : i(t2, e2); - }, e.unpackFromChannel = function() { - return "\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "; - }; - }, 2870: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parsePadAttributesV11 = e.padV11 = e.parsePadAttributesV2 = e.padV2 = void 0; - const r = n(246), i = n(2517), o = n(5060), a = n(2039), s = { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; - e.padV2 = (t2, e2, n2) => (l(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => c(t2, e2[0], n2) }), e2)]), e.parsePadAttributesV2 = (t2) => { - const e2 = t2.attributes.getString("mode", "constant"), n2 = t2.attributes.getFloat("value", 0), i2 = t2.attributes.getInts("pads"); - return (0, r.createAttributeWithCacheKey)({ mode: e2, value: n2, pads: i2 }); - }, e.padV11 = (t2, n2, r2) => { - p(n2); - const i2 = u(t2, n2, r2); - return (0, e.padV2)(t2, [n2[0]], i2); - }, e.parsePadAttributesV11 = (t2) => t2.attributes.getString("mode", "constant"); - const u = (t2, e2, n2) => { - if (!t2.session.isInitializer(e2[1].dataId) || e2.length >= 3 && !t2.session.isInitializer(e2[2].dataId)) - throw new Error("dynamic pad attributes are not allowed"); - const i2 = Array.from(e2[1].integerData), o2 = e2.length >= 3 ? e2[2].floatData[0] : 0; - return (0, r.createAttributeWithCacheKey)({ mode: n2, pads: i2, value: o2 }); - }, c = (t2, e2, n2) => { - const r2 = i.ShapeUtil.padShape(e2.dims.slice(), n2.pads), o2 = r2.length, s2 = ` - ${f(t2, e2, n2)} - float process(int[${o2}] indices) { - return padA(indices); - }`; - return { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked], output: { dims: r2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: s2 }; - }, l = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Pad requires 1 input"); - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("Invalid input type."); - }, p = (t2) => { - if (!t2 || 2 !== t2.length && 3 !== t2.length) - throw new Error("Pad requires 2 or 3 inputs"); - if ("int32" !== t2[1].type) - throw new Error("Invalid input type."); - if (t2.length >= 3 && "string" === t2[2].type) - throw new Error("Invalid input type."); - }, f = (t2, e2, n2) => { - const r2 = (0, o.getGlsl)(t2.session.backend.glContext.version), [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = i.ShapeUtil.computeStrides(e2.dims); - switch (n2.mode) { - case "constant": - return d(r2, e2.dims, c2, s2, u2, n2.pads, n2.value); - case "reflect": - return h(r2, e2.dims, c2, s2, u2, n2.pads); - case "edge": - return g(r2, e2.dims, c2, s2, u2, n2.pads); - default: - throw new Error("Invalid mode"); - } - }, d = (t2, e2, n2, r2, i2, o2, a2) => { - const s2 = e2.length; - let u2 = ""; - for (let t3 = s2 - 1; t3 >= 0; --t3) - u2 += ` - k = m[${t3}] - ${o2[t3]}; - if (k < 0) return constant; - if (k >= ${e2[t3]}) return constant; - offset += k * ${n2[t3]}; - `; - return ` - float padA(int m[${s2}]) { - const float constant = float(${a2}); - int offset = 0; - int k = 0; - ${u2} - vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); - float value = getColorAsFloat(${t2.texture2D}(A, coords)); - return value; - } - `; - }, h = (t2, e2, n2, r2, i2, o2) => { - const a2 = e2.length; - let s2 = ""; - for (let t3 = a2 - 1; t3 >= 0; --t3) - s2 += ` - k = m[${t3}] - ${o2[t3]}; - if (k < 0) { k = -k; } - { - const int _2n_1 = ${2 * (e2[t3] - 1)}; - k = int( mod( float(k), float(_2n_1) ) ) ; - if(k >= ${e2[t3]}) { k = _2n_1 - k; } - } - offset += k * ${n2[t3]}; - `; - return ` - float padA(int m[${a2}]) { - int offset = 0; - int k = 0; - ${s2} - vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); - float value = getColorAsFloat(${t2.texture2D}(A, coords)); - return value; - } - `; - }, g = (t2, e2, n2, r2, i2, o2) => { - const a2 = e2.length; - let s2 = ""; - for (let t3 = a2 - 1; t3 >= 0; --t3) - s2 += ` - k = m[${t3}] - ${o2[t3]}; - if (k < 0) k = 0; - if (k >= ${e2[t3]}) k = ${e2[t3] - 1}; - offset += k * ${n2[t3]}; - `; - return ` - float padA(int m[${a2}]) { - int offset = 0; - int k = 0; - ${s2} - vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); - float value = getColorAsFloat(${t2.texture2D}(A, coords)); - return value; - } - `; - }; - }, 2143: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.globalMaxPool = e.parseMaxPoolAttributes = e.maxPool = e.parseGlobalAveragePoolAttributes = e.globalAveragePool = e.parseAveragePoolAttributes = e.averagePool = void 0; - const r = n(246), i = n(2517), o = n(2039); - e.averagePool = (t2, e2, n2) => { - p(e2); - const r2 = { name: "AveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey }; - return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, false, n2) }), e2)]; - }, e.parseAveragePoolAttributes = (t2) => { - const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = 0 !== t2.attributes.getInt("count_include_pad", 0), o2 = t2.attributes.getInts("kernel_shape"), a2 = t2.attributes.getInts("strides", []), s2 = t2.attributes.getInts("pads", []); - if (0 !== n2) - throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); - return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: i2, kernelShape: o2, strides: a2, pads: s2 }); - }; - const a = (t2, e2, n2, r2) => { - const [a2, s2] = u(t2, r2, n2), c2 = i.ShapeUtil.size(a2.kernelShape); - let l2 = ""; - a2.countIncludePad ? l2 += `value /= float(${c2});` : l2 += `value /= float(${c2} - pad);`; - const p2 = ` - ${f(t2[0].dims, a2, "value += _X(x);", l2, "0.0")} - `; - return Object.assign(Object.assign({}, e2), { output: { dims: s2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: p2 }); - }; - e.globalAveragePool = (t2, e2, n2) => { - p(e2); - const r2 = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: `${n2.countIncludePad}` }; - return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, true, n2) }), e2)]; - }, e.parseGlobalAveragePoolAttributes = (t2) => { - const e2 = 0 !== t2.attributes.getInt("count_include_pad", 0); - return (0, r.createAttributeWithCacheKey)({ autoPad: "", ceilMode: 0, countIncludePad: e2, kernelShape: [], strides: [], pads: [] }); - }, e.maxPool = (t2, e2, n2) => { - p(e2); - const r2 = { name: "MaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey }; - return [t2.run(Object.assign(Object.assign({}, r2), { get: () => s(e2, r2, false, n2) }), e2)]; - }, e.parseMaxPoolAttributes = (t2) => { - const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = t2.attributes.getInts("kernel_shape"), o2 = t2.attributes.getInts("strides", []), a2 = t2.attributes.getInts("pads", []), s2 = t2.attributes.getInt("storage_order", 0), u2 = t2.attributes.getInts("dilations", []); - if (0 !== s2) - throw new Error("column major storage order is not yet supported for MaxPool"); - if (0 !== n2) - throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); - return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: false, kernelShape: i2, strides: o2, pads: a2, storageOrder: s2, dilations: u2 }); - }; - const s = (t2, e2, n2, r2) => { - const [i2, a2] = u(t2, r2, n2), s2 = ` - ${f(t2[0].dims, i2, "\n value = max(_X(x), value);\n ", "", "-1e5")} - `; - return Object.assign(Object.assign({}, e2), { output: { dims: a2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: s2 }); - }, u = (t2, e2, n2) => { - const r2 = t2[0].dims.slice(), o2 = Object.hasOwnProperty.call(e2, "dilations"), a2 = e2.kernelShape.slice(), s2 = e2.strides.slice(), u2 = o2 ? e2.dilations.slice() : [], c2 = e2.pads.slice(); - i.PoolConvUtil.adjustPoolAttributes(n2, r2, a2, s2, u2, c2); - const l2 = i.PoolConvUtil.computePoolOutputShape(n2, r2, s2, u2, a2, c2, e2.autoPad), p2 = Object.assign({}, e2); - return o2 ? Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, dilations: u2, cacheKey: e2.cacheKey }) : Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, cacheKey: e2.cacheKey }), [p2, l2]; - }, c = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, l = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] }; - e.globalMaxPool = (t2, e2) => (p(e2), [t2.run(Object.assign(Object.assign({}, l), { get: () => s(e2, l, true, c) }), e2)]); - const p = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Pool ops requires 1 input."); - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("Invalid input type."); - }, f = (t2, e2, n2, r2, o2) => { - const a2 = t2.length; - if (e2.kernelShape.length <= 2) { - const i2 = e2.kernelShape[e2.kernelShape.length - 1], s2 = e2.strides[e2.strides.length - 1], u2 = e2.pads[e2.pads.length / 2 - 1], c2 = e2.pads[e2.pads.length - 1], l2 = t2[a2 - 1]; - let p2 = "", f2 = "", d2 = ""; - if (p2 = u2 + c2 !== 0 ? ` - for (int i = 0; i < ${i2}; i++) { - x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i; - if (x[${a2} - 1] < 0 || x[${a2} - 1] >= ${l2}) { - pad++; - continue; - } - ${n2} - }` : ` - for (int i = 0; i < ${i2}; i++) { - x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i; - ${n2} - }`, 2 === e2.kernelShape.length) { - const n3 = e2.kernelShape[e2.kernelShape.length - 2], r3 = e2.strides[e2.strides.length - 2], o3 = e2.pads[e2.pads.length / 2 - 2], s3 = e2.pads[e2.pads.length - 2], u3 = t2[a2 - 2]; - f2 = o3 + s3 !== 0 ? ` - for (int j = 0; j < ${n3}; j++) { - x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j; - if (x[${a2} - 2] < 0 || x[${a2} - 2] >= ${u3}) { - pad+= ${i2}; - continue; - } - ` : ` - for (int j = 0; j < ${n3}; j++) { - x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j; - `, d2 = "\n }\n "; - } - return ` - float process(int indices[${a2}]) { - int x[${a2}]; - copyVec(indices, x); - - float value = ${o2}; - int pad = 0; - ${f2} - ${p2} - ${d2} - ${r2} - return value; - } - `; - } - { - const s2 = i.ShapeUtil.size(e2.kernelShape), u2 = i.ShapeUtil.computeStrides(e2.kernelShape), c2 = u2.length, l2 = e2.pads.length, p2 = h(c2), f2 = d(t2, "inputDims"), g = d(e2.pads, "pads"), b = d(u2, "kernelStrides"), m = d(e2.strides, "strides"); - let y = ""; - return y = e2.pads.reduce((t3, e3) => t3 + e3) ? ` - if (x[j] >= inputDims[j] || x[j] < 0) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - ${n2} - }` : ` - } - ${n2} - `, ` - ${p2} - float process(int indices[${a2}]) { - int x[${a2}]; - copyVec(indices, x); - int offset[${c2}]; - int pads[${l2}]; - int inputDims[${a2}]; - int kernelStrides[${c2}]; - int strides[${c2}]; - ${g} - ${f2} - ${m} - ${b} - - float value = ${o2}; - int pad = 0; - bool isPad = false; - for (int i = 0; i < ${s2}; i++) { - offsetToIndices(i, kernelStrides, offset); - isPad = false; - for (int j = ${a2} - ${c2}; j < ${a2}; j++) { - x[j] = indices[j] * strides[j - ${a2} + ${c2}] - + offset[j - ${a2} + ${c2}] - pads[j - 2]; - ${y} - } - ${r2} - - return value; - } - `; - } - }, d = (t2, e2) => { - let n2 = ""; - for (let r2 = 0; r2 < t2.length; r2++) - n2 += ` - ${e2}[${r2}] = ${t2[r2]}; - `; - return n2; - }, h = (t2) => ` - void offsetToIndices(int offset, int[${t2}] strides, out int[${t2}] indices) { - if (${t2} == 0) { - return; - } - for (int i = 0; i < ${t2} - 1; ++i) { - indices[i] = offset / strides[i]; - offset -= indices[i] * strides[i]; - } - indices[${t2} - 1] = offset; - }`; - }, 4939: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.reduceLogSumSquare = e.reduceLogSum = e.reduceProd = e.reduceMin = e.reduceMax = e.reduceMean = e.reduceSum = e.parseReduceAttributes = void 0; - const r = n(246), i = n(782), o = n(2517), a = n(2039), s = (t2, e2, n2, r2, i2) => { - c(e2); - const o2 = { name: r2, inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; - return [t2.run(Object.assign(Object.assign({}, o2), { cacheHint: n2.cacheKey, get: () => u(t2, e2, n2, r2, i2, o2) }), e2)]; - }; - e.parseReduceAttributes = (t2) => { - const e2 = t2.attributes.getInts("axes", []), n2 = 1 === t2.attributes.getInt("keepdims", 1); - return (0, r.createAttributeWithCacheKey)({ axes: e2, keepDims: n2 }); - }; - const u = (t2, e2, n2, r2, i2, s2) => { - const u2 = [], c2 = e2[0].dims.length || 1, l = [], p = o.ShapeUtil.normalizeAxes(n2.axes, e2[0].dims.length), f = i2(e2, p); - let d = f[1]; - for (let t3 = 0; t3 < e2[0].dims.length; t3++) - p.indexOf(t3) >= 0 || 0 === p.length ? (n2.keepDims && u2.push(1), d = ` - for(int j${t3} = 0; j${t3} < ${e2[0].dims[t3]}; j${t3}++) { - inputIdx[${t3}] = j${t3}; - ${d} - }`) : (l.push(`inputIdx[${t3}] = outputIdx[${u2.length}];`), u2.push(e2[0].dims[t3])); - const h = ` - float process(int outputIdx[${u2.length || 1}]) { - float value; // final result - int inputIdx[${c2}]; // addressing input data - ${l.join("\n")} - ${f[0]} // init ops for reduce max/min - ${d} - ${f[2]} // final computation for reduce mean - return value; - }`; - return Object.assign(Object.assign({}, s2), { output: { dims: u2, type: e2[0].type, textureType: a.TextureType.unpacked }, shaderSource: h }); - }, c = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Reduce op requires 1 input."); - if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) - throw new Error("Invalid input type."); - }; - e.reduceSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceSum", () => ["value = 0.0;", "value += _A(inputIdx);", ""]), e.reduceMean = (t2, e2, n2) => s(t2, e2, n2, "ReduceMean", (t3, e3) => { - let n3 = 1; - for (let r2 = 0; r2 < t3[0].dims.length; r2++) - (e3.indexOf(r2) >= 0 || 0 === e3.length) && (n3 *= t3[0].dims[r2]); - return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${n3}.;`]; - }), e.reduceMax = (t2, e2, n2) => s(t2, e2, n2, "ReduceMax", (t3, e3) => { - const n3 = []; - for (let r2 = 0; r2 < t3[0].dims.length; r2++) - (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`); - return [`${n3.join("\n")} -value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""]; - }), e.reduceMin = (t2, e2, n2) => s(t2, e2, n2, "ReduceMin", (t3, e3) => { - const n3 = []; - for (let r2 = 0; r2 < t3[0].dims.length; r2++) - (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`); - return [`${n3.join("\n")} -value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""]; - }), e.reduceProd = (t2, e2, n2) => s(t2, e2, n2, "ReduceProd", () => ["value = 1.0;", "value *= _A(inputIdx);", ""]), e.reduceLogSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSum", () => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"]), e.reduceLogSumSquare = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSumSquare", () => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]); - }, 7019: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.isReshapeCheap = e.processDims3D = e.createPackedReshape3DProgramInfoLoader = void 0; - const r = n(2517), i = n(5060), o = n(2039), a = n(2827); - e.createPackedReshape3DProgramInfoLoader = (t2, e2, n2) => { - const s = ((t3) => ({ name: "Reshape (packed)", inputTypes: [o.TextureType.packed], inputNames: ["A"], cacheHint: `${t3}` }))(n2); - return Object.assign(Object.assign({}, s), { get: () => ((t3, e3, n3, s2) => { - const u = e3.dims, c = s2; - let l = ""; - for (let t4 = 0; t4 < 4; t4++) { - let e4 = ""; - switch (t4) { - case 0: - e4 = "outputCoords = rc;"; - break; - case 1: - e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);"; - break; - case 2: - e4 = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);"; - break; - case 3: - e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);"; - break; - default: - throw new Error(); - } - l += ` - ${e4} - ${t4 > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""} - int flattenedIndex = getFlattenedIndex(outputCoords); - - ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); - vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); - - result[${t4}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); - - ${t4 > 0 ? "}" : ""} - `; - } - const p = (0, i.getGlsl)(t3.session.backend.glContext.version), f = ` - ${function(t4) { - const e4 = r.ShapeUtil.computeStrides(t4), n4 = ["b", "r", "c"], i2 = "index"; - return ` - ivec3 inputCoordsFromReshapedOutCoords(int index) { - ${e4.map((t5, r2) => `int ${n4[r2]} = ${i2} / ${t5}; ${r2 === e4.length - 1 ? `int ${n4[r2 + 1]} = ${i2} - ${n4[r2]} * ${t5}` : `index -= ${n4[r2]} * ${t5}`};`).join("")} - return ivec3(b, r, c); - } - `; - }(u)} - ${function(t4) { - const e4 = r.ShapeUtil.computeStrides(t4); - return ` - int getFlattenedIndex(ivec3 coords) { - // reverse y, z order - return coords.x * ${e4[0]} + coords.z * ${e4[1]} + coords.y; - } -`; - }(c)} - ${(0, a.unpackFromChannel)()} - - void main() { - ivec3 rc = getOutputCoords(); - - vec4 result = vec4(0.0); - - ivec3 outputCoords; - int rows = ${c[2]}; - int cols = ${c[1]}; - - ${l} - ${p.output} = result; - } - `; - return Object.assign(Object.assign({}, n3), { output: { dims: c, type: e3.type, textureType: o.TextureType.packed }, shaderSource: f, hasMain: true }); - })(t2, e2, s, n2) }); - }, e.processDims3D = function(t2) { - if (0 === t2.length) - return [1, 1, 1]; - let e2 = 1; - for (let n2 = 0; n2 < t2.length - 2; ++n2) - e2 *= t2[n2]; - return [e2, t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]]; - }, e.isReshapeCheap = function(t2, e2) { - let n2 = false; - return n2 = 0 === t2.length || 0 === e2.length || (t2.length < 2 || e2.length < 2 ? t2[t2.length - 1] === e2[e2.length - 1] : t2[t2.length - 1] === e2[e2.length - 1] && t2[t2.length - 2] === e2[e2.length - 2]), n2; - }; - }, 718: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.reshape = void 0; - const r = n(2517); - e.reshape = (t2, e2) => { - const n2 = r.ShapeUtil.calculateReshapedDims(e2[0].dims, e2[1].integerData); - return t2.session.pack ? [t2.reshapePacked(e2[0], n2)] : [t2.reshapeUnpacked(e2[0], n2)]; - }; - }, 2268: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseResizeAttributesV11 = e.parseResizeAttributesV10 = e.resize = void 0; - const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = n(9793), u = { name: "Resize", inputNames: ["A"], inputTypes: [i.TextureType.packed] }; - e.resize = (t2, e2, n2) => ((0, s.validateInputs)(e2, n2), [t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => c(t2, e2, n2) }), e2)]), e.parseResizeAttributesV10 = (t2) => (0, s.parseUpsampleAttributes)(t2, 10), e.parseResizeAttributesV11 = (t2) => (0, s.parseUpsampleAttributes)(t2, 11); - const c = (t2, e2, n2) => { - const s2 = (0, r.getGlsl)(t2.session.backend.glContext.version), [c2, p2] = l(e2, n2); - if (c2.every((t3) => 1 === t3) && "tf_crop_and_resize" !== n2.coordinateTransformMode) - return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: `void main() { - vec4 v = ${s2.texture2D}(X, TexCoords); - ${s2.output} = v; - }` }); - const f2 = p2.length; - if (f2 < 2) - throw new Error(`output dimension should be at least 2, but got ${f2}`); - const d = p2[f2 - 2], h = p2[f2 - 1], g = e2[0].dims; - if (f2 !== g.length) - throw new Error(`output dimension should match input ${g.length}, but got ${f2}`); - const b = g[f2 - 2], m = g[f2 - 1], y = c2[f2 - 2], _ = c2[f2 - 1]; - let v = ""; - if ("linear" !== n2.mode) - throw new Error(`resize (packed) does not support mode: '${n2.mode}'`); - switch (n2.coordinateTransformMode) { - case "asymmetric": - v = "\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n "; - break; - case "half_pixel": - v = "\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n "; - break; - case "pytorch_half_pixel": - v = ` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 fcoords = vec4(coords); - return vec4( - ${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, - ${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, - ${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, - ${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 - ); - } - `; - break; - case "align_corners": - v = ` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0, - ${d}.0 - 1.0); - vec4 original = vec4(${m}.0 - 1.0, ${b}.0 - 1.0, ${m}.0 - 1.0, - ${b}.0 - 1.0); - vec4 new_scale = original / resized; - return vec4(coords) * new_scale; - } - `; - break; - default: - throw new Error(`resize (packed) does not support coordinateTransformMode: '${n2.coordinateTransformMode}'`); - } - const w = (0, o.getCoordsDataType)(f2), x = ` - const vec2 inputWH = vec2(${b}.0, ${m}.0); - const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_})); - ${(0, a.unpackFromChannel)()} - ${v} - float getAValue(int x10, int r, int c, int d) { - return getChannel(getA(x10, r, c, d), vec2(c, d)); - } - void main() { - ${w} rc = getOutputCoords(); - - int batch = rc[0]; - int depth = rc[1]; - - // retrieve the 4 coordinates that is used in the 4 packed output values. - ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); - - // calculate the source index in fraction - vec4 sourceFrac = getSourceFracIndex(coords); - - // get the lower and upper bound of the 4 values that will be packed into one texel. - ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); - ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); - ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); - ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); - - bool hasNextRow = rc.w < ${d - 1}; - bool hasNextCol = rc.z < ${h - 1}; - - // pack x00, x01, x10, x11's top-left corner into one vec4 structure - vec4 topLeft = vec4( - getAValue(batch, depth, x00.x, x00.y), - hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); - - // pack x00, x01, x10, x11's top-right corner into one vec4 structure - vec4 topRight = vec4( - getAValue(batch, depth, x00.x, x00.w), - hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); - - // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure - vec4 bottomLeft = vec4( - getAValue(batch, depth, x00.z, x00.y), - hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); - - // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure - vec4 bottomRight = vec4( - getAValue(batch, depth, x00.z, x00.w), - hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); - - // calculate the interpolation fraction on u and v direction - vec4 frac = vec4(sourceFrac) - floor(sourceFrac); - vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); - - vec4 top = mix(topLeft, topRight, clampFrac.ywyw); - vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); - vec4 newValue = mix(top, bottom, clampFrac.xxzz); - - ${s2.output} = vec4(newValue); - } - `; - return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: x }); - }, l = (t2, e2) => { - const n2 = t2[0].dims; - let r2, i2 = e2.scales; - if (0 === i2.length) { - const o3 = t2[e2.scalesInputIdx]; - if (o3 && 0 !== o3.size) { - if (t2[e2.sizesInputIdx]) - throw new Error("Only one of scales or sizes must be provided as input."); - i2 = p(o3, e2.mode, e2.isResize); - } else { - const o4 = t2[e2.sizesInputIdx]; - if (!o4 || 0 === o4.size) - throw new Error("Either scales or sizes MUST be provided as input."); - r2 = Array.from(o4.integerData), i2 = f(r2, n2, e2.mode, e2.isResize); - } - } else if (t2[e2.sizesInputIdx]) - throw new Error("Only one of scales or sizes must be provided as input."); - const o2 = r2 || n2.map((t3, e3) => Math.floor(t3 * i2[e3])); - return [i2, o2]; - }, p = (t2, e2, n2) => { - const r2 = Array.from(t2.floatData); - return (0, s.scalesValidation)(r2, e2, n2), r2; - }, f = (t2, e2, n2, r2) => { - const i2 = e2.length, o2 = new Array(i2); - for (let n3 = 0, r3 = i2; n3 < r3; n3++) - if (0 === e2[n3]) { - if (0 !== t2[n3]) - throw new Error("Input dim is zero but required output dim is non-zero."); - o2[n3] = 1; - } else - o2[n3] = t2[n3] / e2[n3]; - return (0, s.scalesValidation)(o2, n2, r2), o2; - }; - }, 8117: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.shape = void 0; - const r = n(9162); - e.shape = (t2, e2) => (i(e2), [new r.Tensor([e2[0].dims.length], "int32", void 0, void 0, new Int32Array(e2[0].dims))]); - const i = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Shape requires 1 input."); - }; - }, 2278: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.sliceV10 = e.parseSliceAttributes = e.slice = void 0; - const r = n(246), i = n(782), o = n(2517), a = n(2039), s = { name: "Slice", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; - e.slice = (t2, e2, n2) => (c(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), e2)]), e.parseSliceAttributes = (t2) => { - const e2 = t2.attributes.getInts("starts"), n2 = t2.attributes.getInts("ends"), i2 = t2.attributes.getInts("axes", []); - return (0, r.createAttributeWithCacheKey)({ starts: e2, ends: n2, axes: i2 }); - }; - const u = (t2, e2, n2) => { - const r2 = 0 === n2.axes.length ? e2.dims.slice(0).map((t3, e3) => e3) : n2.axes, i2 = o.ShapeUtil.normalizeAxes(r2, e2.dims.length), u2 = n2.starts.map((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]])), c2 = n2.ends.map((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]])), l2 = e2.dims.slice(), p2 = []; - for (let t3 = 0; t3 < i2.length; t3++) - l2[i2[t3]] = c2[t3] - u2[t3], u2[t3] > 0 && p2.push(`outputIdx[${i2[t3]}] += ${u2[t3]};`); - const f = ` - float process(int outputIdx[${l2.length}]) { - ${p2.join("\n ")} - return _A(outputIdx); - }`; - return Object.assign(Object.assign({}, s), { output: { dims: l2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f }); - }, c = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Slice requires 1 input."); - if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) - throw new Error("Invalid input type."); - }; - e.sliceV10 = (t2, e2) => { - p(e2); - const n2 = l(t2, e2); - return [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), [e2[0]])]; - }; - const l = (t2, e2) => { - if (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId) || e2.length >= 4 && !t2.session.isInitializer(e2[3].dataId) || e2.length >= 5 && !t2.session.isInitializer(e2[4].dataId)) - throw new Error("dynamic slice attributes are not allowed"); - if (e2.length >= 5 && e2[4].integerData.some((t3) => 1 !== t3)) - throw new Error("currently non-1 steps is not supported for Slice"); - const n2 = Array.from(e2[1].integerData), r2 = Array.from(e2[2].integerData), i2 = e2.length >= 4 ? Array.from(e2[3].integerData) : []; - return { starts: n2, ends: r2, axes: i2, cacheKey: `${i2};${n2};${r2}` }; - }, p = (t2) => { - if (!t2 || t2.length < 3 || t2.length > 5) - throw new Error("Invalid input number."); - if ("int32" !== t2[1].type || 1 !== t2[1].dims.length) - throw new Error("Invalid input type."); - if ("int32" !== t2[2].type || 1 !== t2[2].dims.length) - throw new Error("Invalid input type."); - if (t2.length >= 4 && ("int32" !== t2[3].type || 1 !== t2[3].dims.length)) - throw new Error("Invalid input type."); - if (t2.length >= 5 && ("int32" !== t2[4].type || 1 !== t2[4].dims.length)) - throw new Error("Invalid input type."); - }; - }, 5524: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.softmaxV13 = e.parseSoftmaxAttributesV13 = e.parseSoftmaxAttributes = e.softmax = void 0; - const r = n(246), i = n(2517), o = n(5060), a = n(2039), s = n(3738), u = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }, c = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, l = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked, a.TextureType.unpacked] }; - e.softmax = (t2, e2, n2) => { - g(e2); - const r2 = e2[0].dims.slice(), o2 = i.ShapeUtil.normalizeAxis(n2.axis, r2.length), a2 = i.ShapeUtil.sizeToDimension(r2, o2), s2 = i.ShapeUtil.sizeFromDimension(r2, o2); - return p(t2, e2, n2, a2, s2); - }, e.parseSoftmaxAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 1) }), e.parseSoftmaxAttributesV13 = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", -1) }), e.softmaxV13 = (t2, e2, n2) => { - g(e2); - const o2 = e2[0].dims.slice(), a2 = i.ShapeUtil.normalizeAxis(n2.axis, o2.length), u2 = o2.length, c2 = a2 !== u2 - 1, l2 = []; - let f2, d2 = [], h2 = []; - c2 && (d2 = Array.from({ length: u2 }).map((t3, e3) => e3), d2[a2] = u2 - 1, d2[u2 - 1] = a2, d2.map((t3) => l2.push(o2[t3])), f2 = (0, r.createAttributeWithCacheKey)({ perm: d2 }), h2 = (0, s.transpose)(t2, e2, f2)); - const b = c2 ? i.ShapeUtil.sizeToDimension(l2, u2 - 1) : i.ShapeUtil.sizeToDimension(o2, u2 - 1), m = c2 ? i.ShapeUtil.sizeFromDimension(l2, u2 - 1) : i.ShapeUtil.sizeFromDimension(o2, u2 - 1), y = p(t2, c2 ? h2 : e2, n2, b, m); - return c2 ? (0, s.transpose)(t2, y, f2) : y; - }; - const p = (t2, e2, n2, r2, i2) => { - const o2 = f(t2, e2[0], r2, i2, [r2]), a2 = t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => o2 }), e2), s2 = d(t2, e2[0], r2, i2, o2.output.dims, [r2]), p2 = t2.run(Object.assign(Object.assign({}, c), { cacheHint: n2.cacheKey, get: () => s2 }), [e2[0], a2]), g2 = h(t2, e2[0], r2, i2, o2.output.dims, s2.output.dims); - return [t2.run(Object.assign(Object.assign({}, l), { cacheHint: n2.cacheKey, get: () => g2 }), [e2[0], a2, p2])]; - }, f = (t2, e2, n2, r2, i2) => { - const [s2, c2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), l2 = i2.length; - if (n2 < 1 || r2 < 1) - throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); - if (1 !== i2.length) - throw new Error("Dimensionality of the output should be 1"); - if (i2[0] !== n2) - throw new Error("Shape of the output should be equal to logical row count"); - const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = ` - float process(int[${l2}] indices) { - int logical_row_start_offset = indices[0] * ${r2}; - - float max = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s2}, - ${c2} ))); - for(int i=1; i<${r2}; ++i) - { - float current = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${s2}, ${c2}))); - if(current > max) - max = current; - } - - return max; - }`; - return Object.assign(Object.assign({}, u), { output: { dims: i2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 }); - }, d = (t2, e2, n2, r2, i2, s2) => { - const [u2, l2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), p2 = s2.length; - if (n2 < 1 || r2 < 1) - throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); - if (1 !== s2.length) - throw new Error("Dimensionality of the output should be 1"); - if (s2[0] !== n2) - throw new Error("Shape of the output should be equal to logical row count"); - if (1 !== i2.length) - throw new Error("Dimensionality of the intermediate results should be 1"); - if (i2[0] !== n2) - throw new Error("Shape of the intermediate results should be equal to logical row count"); - const f2 = ` - float process(int[${p2}] indices) { - int logical_row_start_offset = indices[0] * ${r2}; - - float norm_factor = 0.0; - float max = _Max(indices); - for(int i=0; i<${r2}; ++i) - { - norm_factor += exp(getColorAsFloat(${(0, o.getGlsl)(t2.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${u2}, ${l2}))) - max); - } - - return norm_factor; - }`; - return Object.assign(Object.assign({}, c), { output: { dims: s2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 }); - }, h = (t2, e2, n2, r2, i2, o2) => { - const [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = e2.dims.length; - if (n2 < 1 || r2 < 1) - throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); - if (1 !== i2.length || 1 !== o2.length) - throw new Error("Dimensionality of the intermediate results should be 1"); - if (i2[0] !== n2 || o2[0] !== n2) - throw new Error("Shape of the intermediate results should be equal to logical row count"); - const p2 = ` - float process(int[${c2}] indices) { - - // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) - int offset = coordsToOffset(TexCoords, ${s2}, ${u2}); - - //determine the logical row for this index - int logical_row_index[1]; - logical_row_index[0] = offset / ${r2}; - - float norm_factor = _Norm(logical_row_index); - - // avoid possible division by 0 - // if norm_facor is 0, all elements are zero - // if so, return 0 - if(norm_factor == 0.0) - return 0.0; - - return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; - }`; - return Object.assign(Object.assign({}, l), { output: { dims: e2.dims, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: p2 }); - }, g = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Softmax requires 1 input."); - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("Invalid input type"); - }; - }, 5975: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseSplitAttributes = e.split = void 0; - const r = n(246), i = n(2517), o = n(2039), a = { name: "Split", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] }; - e.split = (t2, e2, n2) => { - c(e2); - const r2 = i.ShapeUtil.normalizeAxis(n2.axis, e2[0].dims.length), o2 = s(t2, e2, r2, n2), l = []; - for (let i2 = 0; i2 < o2; ++i2) - l.push(t2.run(Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey};${i2}`, get: () => u(t2, e2[0], n2, r2, i2) }), e2)); - return l; - }, e.parseSplitAttributes = (t2) => { - const e2 = t2.attributes.getInt("axis", 0), n2 = t2.attributes.getInts("split", []), i2 = t2.outputs.length; - return (0, r.createAttributeWithCacheKey)({ axis: e2, split: n2, numOutputs: i2 }); - }; - const s = (t2, e2, n2, r2) => { - const [, o2] = i.SplitUtil.splitShape(e2[0].dims, n2, r2.split, r2.numOutputs); - return o2.length; - }, u = (t2, e2, n2, r2, s2) => { - const [u2, c2] = i.SplitUtil.splitShape(e2.dims, r2, n2.split, n2.numOutputs), l = c2[s2], p = u2[s2], f = ` - float process(int indices[${p.length}]) { - indices[${r2}] += ${l}; - return _A(indices); - } - `; - return Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey}:${s2}`, output: { dims: p, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: f }); - }, c = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Split requires one input."); - if ("int8" !== t2[0].type && "uint8" !== t2[0].type && "int16" !== t2[0].type && "uint16" !== t2[0].type && "int32" !== t2[0].type && "uint32" !== t2[0].type && "float32" !== t2[0].type && "float64" !== t2[0].type && "bool" !== t2[0].type) - throw new Error("Invalid input type."); - }; - }, 3933: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseSqueezeAttributes = e.squeezeV13 = e.squeeze = void 0; - const r = n(2517); - e.squeeze = (t2, e2, n2) => { - i(e2); - const o2 = r.ShapeUtil.squeezeShape(e2[0].dims, n2); - return [t2.reshapeUnpacked(e2[0], o2)]; - }, e.squeezeV13 = (t2, n2) => (o(n2), (0, e.squeeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseSqueezeAttributes = (t2) => t2.attributes.getInts("axes"); - const i = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Squeeze requires 1 input."); - if ("string" === t2[0].type) - throw new Error("invalid input tensor types."); - }, o = (t2) => { - if (!t2 || 2 !== t2.length) - throw new Error("Squeeze requires 2 inputs."); - if ("int32" !== t2[1].type) - throw new Error("Invalid input type."); - }; - }, 6558: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.sum = void 0; - const r = n(5060), i = n(2039); - e.sum = (t2, e2) => { - a(e2); - const n2 = { name: "Sum", inputNames: e2.map((t3, e3) => `X${e3}`), inputTypes: new Array(e2.length).fill(i.TextureType.unpacked) }; - return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)]; - }; - const o = (t2, e2, n2) => { - const o2 = (0, r.getGlsl)(t2.session.backend.glContext.version), a2 = e2[0].dims.slice(), s = ` - void main() { - vec4 result = ${e2.map((t3, e3) => `${o2.texture2D}(X${e3},TexCoords)`).join(" + ")}; - ${o2.output} = result; - } - `; - return Object.assign(Object.assign({}, n2), { output: { dims: a2, type: e2[0].type, textureType: i.TextureType.unpacked }, hasMain: true, shaderSource: s }); - }, a = (t2) => { - if (!t2 || 0 === t2.length) - throw new Error("Sum requires inputs."); - const e2 = t2[0].dims.length; - for (let n2 = 1; n2 < t2.length; n2++) { - if (e2 !== t2[n2].dims.length) - throw new Error("Input shapes are mismatched."); - for (let r2 = 0; r2 < e2; r2++) - if (t2[0].dims[r2] !== t2[n2].dims[r2]) - throw new Error("Input shapes are not matched."); - } - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("Invalid input type."); - for (let e3 = 1; e3 < t2.length; e3++) - if (t2[0].type !== t2[e3].type) - throw new Error("Input types are not matched."); - }; - }, 5723: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.tile = void 0; - const r = n(782), i = n(2039); - e.tile = (t2, e2) => { - a(e2); - const n2 = { name: "Tile", inputNames: ["A"], inputTypes: [i.TextureType.unpacked] }; - return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)]; - }; - const o = (t2, e2, n2) => { - const r2 = e2[0].dims.slice(), o2 = new Array(r2.length), a2 = []; - for (let t3 = 0; t3 < r2.length; t3++) - o2[t3] = r2[t3] * e2[1].numberData[t3], a2.push(`inputIdx[${t3}] = int(mod(float(outputIdx[${t3}]), ${r2[t3]}.));`); - const s = o2.length, u = ` - float process(int outputIdx[${s}]) { - int inputIdx[${s}]; - ${a2.join("\n")} - return _A(inputIdx); - } - `; - return Object.assign(Object.assign({}, n2), { output: { dims: o2, type: e2[0].type, textureType: i.TextureType.unpacked }, shaderSource: u }); - }, a = (t2) => { - if (!t2 || 2 !== t2.length) - throw new Error("Tile requires 2 input."); - if (1 !== t2[1].dims.length) - throw new Error("The second input shape must 1 dimension."); - if (t2[1].dims[0] !== t2[0].dims.length) - throw new Error("Invalid input shape."); - if (-1 === r.NUMBER_TYPES.indexOf(t2[0].type)) - throw new Error("Invalid input type."); - if ("int32" !== t2[1].type && "int16" !== t2[1].type) - throw new Error("Invalid repeat type."); - }; - }, 3738: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseTransposeAttributes = e.transpose = void 0; - const r = n(246), i = n(2517), o = n(2039), a = { name: "Transpose", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] }; - e.transpose = (t2, e2, n2) => (p(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2[0], n2.perm) }), e2)]), e.parseTransposeAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ perm: t2.attributes.getInts("perm", []) }); - const s = (t2, e2, n2) => { - const r2 = e2.dims; - n2 = u(r2, n2); - const i2 = c(r2, n2), s2 = r2.length, p2 = ` - ${l("perm", n2, s2)} - float process(int indices[${s2}]) { - int a[${s2}]; - perm(a, indices); - return _A(a); - }`; - return Object.assign(Object.assign({}, a), { output: { dims: i2, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: p2 }); - }, u = (t2, e2) => (e2 && e2.length !== t2.length && (e2 = [...t2.keys()].reverse()), e2), c = (t2, e2) => (e2 = u(t2, e2), i.ShapeUtil.sortBasedOnPerm(t2, e2)), l = (t2, e2, n2) => { - const r2 = []; - r2.push(`void ${t2}(out int a[${n2}], int src[${n2}]) {`); - for (let t3 = 0; t3 < n2; ++t3) - r2.push(` a[${e2[t3]}]=src[${t3}];`); - return r2.push(" }"), r2.join("\n"); - }, p = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Transpose requires 1 input."); - if ("float32" !== t2[0].type && "float64" !== t2[0].type) - throw new Error("input should be float tensor"); - }; - }, 8710: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.encodeAsUint8 = void 0; - const r = n(5060), i = n(2039); - e.encodeAsUint8 = (t2, e2) => { - const n2 = e2.shape, o = (0, r.getGlsl)(t2.session.backend.glContext.version), a = ` - const float FLOAT_MAX = 1.70141184e38; - const float FLOAT_MIN = 1.17549435e-38; - - bool isNaN(float val) { - return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; - } - - highp vec4 encodeAsUint8(highp float v) { - if (isNaN(v)) { - return vec4(255, 255, 255, 255); - } - - highp float av = abs(v); - - if(av < FLOAT_MIN) { - return vec4(0.0, 0.0, 0.0, 0.0); - } else if(v > FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; - } else if(v < -FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; - } - - highp vec4 c = vec4(0,0,0,0); - - highp float e = floor(log2(av)); - highp float m = exp2(fract(log2(av))) - 1.0; - - c[2] = floor(128.0 * m); - m -= c[2] / 128.0; - c[1] = floor(32768.0 * m); - m -= c[1] / 32768.0; - c[0] = floor(8388608.0 * m); - - highp float ebias = e + 127.0; - c[3] = floor(ebias / 2.0); - ebias -= c[3] * 2.0; - c[2] += floor(ebias) * 128.0; - - c[3] += 128.0 * step(0.0, -v); - - return c / 255.0; - } - - void main() { - float value = ${o.texture2D}(X,TexCoords).r; - ${o.output} = encodeAsUint8(value); - }`, s = { name: "Uint8Encode", inputTypes: [i.TextureType.unpacked], inputNames: ["X"], output: { dims: n2, type: e2.tensor.type, textureType: i.TextureType.downloadUint8AsFloat }, shaderSource: a, hasMain: true }; - return t2.executeProgram(s, [e2.tensor]); - }; - }, 4909: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.tanh = e.tan = e.sqrt = e.sin = e.sigmoid = e.relu = e.not = e.neg = e.log = e.parseLeakyReluAttributes = e.leakyRelu = e.identity = e.floor = e.exp = e.parseEluAttributes = e.elu = e.cos = e.ceil = e.clipV11 = e.parseClipAttributes = e.clip = e.atan = e.asin = e.acos = e.abs = e.glslTanh = e.glslTan = e.glslSqrt = e.glslSigmoid = e.glslRelu = e.glslSin = e.glslNot = e.glslNeg = e.glslLog = e.glslLeakyRelu = e.glslIdentity = e.glslClip = e.glslFloor = e.glslExp = e.glslElu = e.glslCos = e.glslCeil = e.glslAtan = e.glslAsin = e.glslAcos = e.glslAbs = void 0; - const r = n(246), i = n(2517), o = n(8520), a = n(5060), s = n(2039); - function u() { - return P("abs"); - } - function c() { - return P("acos"); - } - function l() { - return P("asin"); - } - function p() { - return P("atan"); - } - function f() { - return P("ceil"); - } - function d() { - return P("cos"); - } - function h(t2) { - const e2 = "elu"; - return { body: ` - const float alpha = float(${t2}); - - float ${e2}_(float a) { - return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; - } - vec4 ${e2}_(vec4 v) { - return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w)); - } - `, name: e2, type: o.FunctionType.ValueBased }; - } - function g() { - return P("exp"); - } - function b() { - return P("floor"); - } - function m(t2, e2) { - const n2 = "clip"; - return { body: ` - const float min = float(${t2}); - const float max = float(${e2}); - - float ${n2}_(float a) { - return clamp(a, min, max); - } - vec4 ${n2}_(vec4 v) { - return clamp(v, min, max); - } - `, name: n2, type: o.FunctionType.ValueBased }; - } - function y() { - const t2 = "indentity"; - return { body: ` - float ${t2}_(float a) { - return a; - } - vec4 ${t2}_(vec4 v) { - return v; - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function _(t2) { - const e2 = "leakyRelu"; - return { body: ` - const float alpha = float(${t2}); - - float ${e2}_(float a) { - return a < 0.0 ? a * alpha : a; - } - vec4 ${e2}_(vec4 v) { - return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w)); - } - `, name: e2, type: o.FunctionType.ValueBased }; - } - function v() { - return P("log"); - } - function w() { - const t2 = "neg"; - return { body: ` - float ${t2}_(float a) { - return -a; - } - vec4 ${t2}_(vec4 v) { - return -v; - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function x() { - const t2 = "not"; - return { body: ` - float ${t2}_(float a) { - return float( ! bool(a) ); - } - bool ${t2}_(bool a) { - return !a; - } - vec4 ${t2}_(vec4 v) { - return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); - } - bvec4 ${t2}_(bvec4 v) { - return bvec4(!v.x, !v.y, !v.z, !v.w); - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function T() { - return P("sin"); - } - function S() { - const t2 = "relu"; - return { body: ` - float ${t2}_(float a) { - return max( a, 0.0 ); - } - vec4 ${t2}_(vec4 v) { - return max( v, 0.0 ); - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function O() { - const t2 = "sigmoid"; - return { body: ` - float ${t2}_(float a) { - return 1.0 / (1.0 + exp(-a)); - } - vec4 ${t2}_(vec4 v) { - return 1.0 / (1.0 + exp(-v)); - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function A() { - return P("sqrt"); - } - function E() { - return P("tan"); - } - function I() { - const t2 = "tanh"; - return { body: ` - float ${t2}_(float a) { - a = clamp(a, -10., 10.); - a = exp(2.*a); - return (a - 1.) / (a + 1.); - } - vec4 ${t2}_(vec4 v) { - v = clamp(v, -10., 10.); - v = exp(2.*v); - return (v - 1.) / (v + 1.); - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - function P(t2) { - return { body: ` - float ${t2}_(float a) { - return ${t2}(a); - } - vec4 ${t2}_(vec4 v) { - return ${t2}(v); - } - `, name: t2, type: o.FunctionType.ValueBased }; - } - e.glslAbs = u, e.glslAcos = c, e.glslAsin = l, e.glslAtan = p, e.glslCeil = f, e.glslCos = d, e.glslElu = h, e.glslExp = g, e.glslFloor = b, e.glslClip = m, e.glslIdentity = y, e.glslLeakyRelu = _, e.glslLog = v, e.glslNeg = w, e.glslNot = x, e.glslSin = T, e.glslRelu = S, e.glslSigmoid = O, e.glslSqrt = A, e.glslTan = E, e.glslTanh = I; - const D = (t2, e2, n2, r2) => { - const i2 = t2.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o2 = { name: n2.name, inputTypes: [i2], inputNames: ["A"], cacheHint: r2 }; - return Object.assign(Object.assign({}, o2), { get: () => ((t3, e3, n3, r3) => { - const i3 = t3.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o3 = (0, a.getGlsl)(t3.session.backend.glContext.version); - return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i3 }, shaderSource: ` - ${r3.body} - void main() { - vec4 v = ${o3.texture2D}(A, TexCoords); - v = ${r3.name}_(v); - ${o3.output} = v; - } - `, hasMain: true }); - })(t2, o2, e2, n2) }); - }; - e.abs = (t2, e2) => [t2.run(D(t2, e2[0], u()), e2)], e.acos = (t2, e2) => [t2.run(D(t2, e2[0], c()), e2)], e.asin = (t2, e2) => [t2.run(D(t2, e2[0], l()), e2)], e.atan = (t2, e2) => [t2.run(D(t2, e2[0], p()), e2)], e.clip = (t2, e2, n2) => [t2.run(D(t2, e2[0], m(n2.min, n2.max), n2.cacheKey), e2)], e.parseClipAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ min: t2.attributes.getFloat("min", i.MIN_CLIP), max: t2.attributes.getFloat("max", i.MAX_CLIP) }), e.clipV11 = (t2, n2) => { - const r2 = $(t2, n2); - return (0, e.clip)(t2, [n2[0]], r2); - }; - const $ = (t2, e2) => { - if (e2.length >= 3 && (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId))) - throw new Error("dynamic clip attributes are not allowed"); - const n2 = e2.length >= 3 ? e2[1].numberData[0] : i.MIN_CLIP, o2 = e2.length >= 3 ? e2[2].numberData[0] : i.MAX_CLIP; - return (0, r.createAttributeWithCacheKey)({ min: n2, max: o2 }); - }; - e.ceil = (t2, e2) => [t2.run(D(t2, e2[0], f()), e2)], e.cos = (t2, e2) => [t2.run(D(t2, e2[0], d()), e2)], e.elu = (t2, e2, n2) => [t2.run(D(t2, e2[0], h(n2.alpha), n2.cacheKey), e2)], e.parseEluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 1) }), e.exp = (t2, e2) => [t2.run(D(t2, e2[0], g()), e2)], e.floor = (t2, e2) => [t2.run(D(t2, e2[0], b()), e2)], e.identity = (t2, e2) => [t2.run(D(t2, e2[0], y()), e2)], e.leakyRelu = (t2, e2, n2) => [t2.run(D(t2, e2[0], _(n2.alpha), n2.cacheKey), e2)], e.parseLeakyReluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 0.01) }), e.log = (t2, e2) => [t2.run(D(t2, e2[0], v()), e2)], e.neg = (t2, e2) => [t2.run(D(t2, e2[0], w()), e2)], e.not = (t2, e2) => [t2.run(D(t2, e2[0], x()), e2)], e.relu = (t2, e2) => [t2.run(D(t2, e2[0], S()), e2)], e.sigmoid = (t2, e2) => [t2.run(D(t2, e2[0], O()), e2)], e.sin = (t2, e2) => [t2.run(D(t2, e2[0], T()), e2)], e.sqrt = (t2, e2) => [t2.run(D(t2, e2[0], A()), e2)], e.tan = (t2, e2) => [t2.run(D(t2, e2[0], E()), e2)], e.tanh = (t2, e2) => [t2.run(D(t2, e2[0], I()), e2)]; - }, 5611: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackProgramInfoLoader = e.createUnpackProgramInfo = void 0; - const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = { name: "unpack", inputNames: ["A"], inputTypes: [i.TextureType.packed] }; - e.createUnpackProgramInfo = (t2, e2) => { - const n2 = e2.dims.length, u = (0, a.getChannels)("rc", n2), c = u.slice(-2), l = (0, o.getCoordsDataType)(n2), p = (0, a.unpackFromChannel)(), f = 0 === e2.dims.length ? "" : function(t3, e3) { - if (1 === t3) - return "rc"; - let n3 = ""; - for (let r2 = 0; r2 < t3; r2++) - n3 += e3[r2], r2 < t3 - 1 && (n3 += ","); - return n3; - }(n2, u), d = n2 <= 1 ? "rc" : `vec2(${c.join(",")})`, h = ` - ${p} - void main() { - ${l} rc = getOutputCoords(); - - // Sample the texture with the coords to get the rgba channel value. - vec4 packedInput = getA(${f}); - - ${(0, r.getGlsl)(t2.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0); - } - `; - return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e2.dims, type: e2.type, textureType: i.TextureType.unpacked }, shaderSource: h }); - }, e.createUnpackProgramInfoLoader = (t2, n2) => Object.assign(Object.assign({}, s), { get: () => (0, e.createUnpackProgramInfo)(t2, n2) }); - }, 8428: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.parseUnsqueezeAttributes = e.unsqueezeV13 = e.unsqueeze = void 0; - const r = n(2517); - e.unsqueeze = (t2, e2, n2) => { - i(e2); - const o2 = r.ShapeUtil.unsqueezeShape(e2[0].dims, n2); - return [t2.reshapeUnpacked(e2[0], o2)]; - }, e.unsqueezeV13 = (t2, n2) => (o(n2), (0, e.unsqueeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseUnsqueezeAttributes = (t2) => t2.attributes.getInts("axes"); - const i = (t2) => { - if (!t2 || 1 !== t2.length) - throw new Error("Unsqueeze requires 1 input."); - if ("string" === t2[0].type) - throw new Error("invalid input tensor types."); - }, o = (t2) => { - if (!t2 || 2 !== t2.length) - throw new Error("Unsqueeze requires 2 inputs."); - if ("int32" !== t2[1].type) - throw new Error("Invalid input type."); - }; - }, 9793: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.scalesValidation = e.validateInputs = e.parseUpsampleAttributes = e.parseUpsampleAttributesV9 = e.parseUpsampleAttributesV7 = e.upsample = void 0; - const r = n(246), i = n(5060), o = n(2039), a = { name: "Upsample", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] }; - e.upsample = (t2, n2, r2) => ((0, e.validateInputs)(n2, r2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: r2.cacheKey, get: () => s(t2, n2, r2) }), n2)]), e.parseUpsampleAttributesV7 = (t2) => (0, e.parseUpsampleAttributes)(t2, 7), e.parseUpsampleAttributesV9 = (t2) => (0, e.parseUpsampleAttributes)(t2, 9), e.parseUpsampleAttributes = (t2, n2) => { - const i2 = n2 >= 10, o2 = t2.attributes.getString("mode", "nearest"); - if ("nearest" !== o2 && "linear" !== o2 && (n2 < 11 || "cubic" !== o2)) - throw new Error(`unrecognized mode: ${o2}`); - let a2 = []; - n2 < 9 && (a2 = t2.attributes.getFloats("scales"), (0, e.scalesValidation)(a2, o2, i2)); - const s2 = t2.attributes.getFloat("extrapolation_value", 0), u = n2 > 10 ? t2.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric"; - if (-1 === ["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(u)) - throw new Error(`coordinate_transform_mode '${u}' is not supported`); - const c = "tf_crop_and_resize" === u, l = c, p = "nearest" === o2 && n2 >= 11 ? t2.attributes.getString("nearest_mode", "round_prefer_floor") : ""; - if (-1 === ["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(p)) - throw new Error(`nearest_mode '${p}' is not supported`); - const f = t2.attributes.getFloat("cubic_coeff_a", -0.75), d = 0 !== t2.attributes.getInt("exclude_outside", 0); - if (d && "cubic" !== o2) - throw new Error("exclude_outside can be set to 1 only when mode is CUBIC."); - const h = n2 < 11 || "nearest" === o2 && "asymmetric" === u && "floor" === p; - let g = 0, b = 0, m = 0; - return n2 > 10 ? t2.inputs.length > 2 ? (g = 1, b = 2, m = 3) : (b = 1, m = 2) : 9 === n2 && (b = 1), (0, r.createAttributeWithCacheKey)({ opset: n2, isResize: i2, mode: o2, scales: a2, extrapolationValue: s2, coordinateTransformMode: u, useExtrapolation: l, needRoiInput: c, nearestMode: p, cubicCoefficientA: f, excludeOutside: d, useNearest2xOptimization: h, roiInputIdx: g, scalesInputIdx: b, sizesInputIdx: m }); - }; - const s = (t2, e2, n2) => { - const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), [s2, u] = t2.calculateTextureWidthAndHeight(e2[0].dims, o.TextureType.unpacked), c = e2[0].dims.map((t3, e3) => Math.floor(t3 * n2.scales[e3])), [l, p] = t2.calculateTextureWidthAndHeight(c, o.TextureType.unpacked), f = c.length, d = new Array(f), h = new Array(f); - let g = ` - int output_pitches[${f}]; - int input_pitches[${f}]; - `; - for (let t3 = f - 1; t3 >= 0; t3--) - d[t3] = t3 === f - 1 ? 1 : d[t3 + 1] * c[t3 + 1], h[t3] = t3 === f - 1 ? 1 : h[t3 + 1] * e2[0].dims[t3 + 1], g += ` - output_pitches[${t3}] = ${d[t3]}; - input_pitches[${t3}] = ${h[t3]}; - `; - const b = ` - float getInputFloat(int index) { - vec2 coords = offsetToCoords(index, ${s2}, ${u}); - float value = getColorAsFloat(${r2.texture2D}(X, coords)); - return value; - } - `, m = "nearest" === n2.mode ? ` - ${b} - float process(int indices[${f}]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${l}, ${p}); - - ${g} - - int d, m; - for (int dim = 0; dim < ${f}; ++dim) { - d = output_index / output_pitches[dim]; - m = output_index - d * output_pitches[dim]; - output_index = m; - - if (scales[dim] != 1 && d > 0) { - int d2 = d / scales[dim]; - m = d - d2 * scales[dim]; - d = d2; - } - input_index += input_pitches[dim] * d; - } - - return getInputFloat(input_index); - }` : 4 === f ? ` - ${b} - float process(int indices[4]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${l}, ${p}); - - ${g} - - int m; - int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m / output_pitches[1]; - m = m - index_of_dim1 * output_pitches[1]; - index_of_dim2 = m / output_pitches[2]; - m = m - index_of_dim2 * output_pitches[2]; - index_of_dim3 = m; - - int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; - index_of_input_dim2 = index_of_dim2 / scales[2]; - y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; - index_of_input_dim3 = index_of_dim3 / scales[3]; - x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; - - input_index = index_of_dim0 * input_pitches[0] + - index_of_dim1 * input_pitches[1] + - index_of_input_dim2 * input_pitches[2] + - index_of_input_dim3; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim2 = false; - if (index_of_input_dim2 == (${e2[0].dims[2]} - 1)) { - // It's the end in dimension 2 - x01 = x00; - end_of_dim2 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[2]); - } - - if (index_of_input_dim3 == (input_pitches[2] - 1)) { - // It's the end in dimension 3 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); - }` : ` - ${b} - float process(int indices[2]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${l}, ${p}); - - ${g} - - int m; - int index_of_dim0, index_of_dim1; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m; - - int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; - index_of_input_dim0 = index_of_dim0 / scales[0]; - y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; - index_of_input_dim1 = index_of_dim1 / scales[1]; - x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; - - input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim0 = false; - if (index_of_input_dim0 == (${e2[0].dims[0]} - 1)) { - // It's the end in dimension 0 - x01 = x00; - end_of_dim0 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[0]); - } - - if (index_of_input_dim1 == (input_pitches[0] - 1)) { - // It's the end in dimension 1 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); - }`; - return Object.assign(Object.assign({}, a), { output: { dims: c, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, variables: [{ name: "scales", type: "int", arrayLength: n2.scales.length, data: n2.scales.map((t3) => Math.ceil(t3)) }] }); - }; - e.validateInputs = (t2, e2) => { - if (!t2 || e2.opset < 9 && 1 !== t2.length || e2.opset >= 9 && e2.opset < 11 && 2 !== t2.length || e2.opset >= 11 && t2.length < 2) - throw new Error("invalid inputs."); - if (e2.scales.length > 0 && t2[0].dims.length !== e2.scales.length) - throw new Error("Invalid input shape."); - if ("string" === t2[0].type) - throw new Error("Invalid input tensor types."); - }, e.scalesValidation = (t2, e2, n2) => { - if (n2) { - for (const e3 of t2) - if (e3 <= 0) - throw new Error("Scale value should be greater than 0."); - } else - for (const e3 of t2) - if (e3 < 1) - throw new Error("Scale value should be greater than or equal to 1."); - if (!("linear" !== e2 && "cubic" !== e2 || 2 === t2.length || 4 === t2.length && 1 === t2[0] && 1 === t2[1])) - throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n2 ? "Resize" : "Upsample"} opeartor.`); - }; - }, 1958: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.ProgramManager = void 0; - const r = n(1670), i = n(6231), o = n(8879), a = n(5060); - e.ProgramManager = class { - constructor(t2, e2, n2) { - this.profiler = t2, this.glContext = e2, this.textureLayoutStrategy = n2, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; - } - getArtifact(t2) { - return this.repo.get(t2); - } - setArtifact(t2, e2) { - this.repo.set(t2, e2); - } - run(t2, e2, n2) { - var r2; - this.profiler.event("op", `ProgramManager.run ${null !== (r2 = t2.programInfo.name) && void 0 !== r2 ? r2 : "unknown kernel"}`, () => { - var r3; - const o2 = this.glContext.gl, a2 = t2.program; - o2.useProgram(a2); - try { - this.bindOutput(n2), this.attributesBound || this.bindAttributes(t2.attribLocations), this.bindUniforms(t2.uniformLocations, null !== (r3 = t2.programInfo.variables) && void 0 !== r3 ? r3 : [], e2); - } catch (e3) { - throw i.Logger.error("ProgramManager", t2.programInfo.shaderSource), e3; - } - this.profiler.event("backend", "GlContext.draw()", () => { - this.glContext.draw(); - }); - }, this.glContext); - } - dispose() { - this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach((t2) => this.glContext.deleteProgram(t2.program)); - } - build(t2, e2, n2) { - return this.profiler.event("backend", "ProgramManager.build", () => { - const r2 = new o.GlslPreprocessor(this.glContext, t2, e2, n2), i2 = r2.preprocess(), a2 = this.compile(i2); - return { programInfo: t2, program: a2, uniformLocations: this.getUniformLocations(a2, r2.context.programInfo.inputNames, r2.context.programInfo.variables), attribLocations: this.getAttribLocations(a2) }; - }); - } - compile(t2) { - if (!this.vertexShader) { - i.Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time"); - const t3 = (0, a.getVertexShaderSource)(this.glContext.version); - this.vertexShader = this.glContext.compileShader(t3, this.glContext.gl.VERTEX_SHADER); - } - r.env.debug && i.Logger.verbose("ProrgramManager", `FragShader: -${t2} -`); - const e2 = this.glContext.compileShader(t2, this.glContext.gl.FRAGMENT_SHADER), n2 = this.glContext.createProgram(this.vertexShader, e2); - return this.glContext.deleteShader(e2), n2; - } - bindOutput(t2) { - const e2 = t2.width, n2 = t2.height; - i.Logger.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${e2}/${n2}, shape=${t2.shape}, type=${t2.tensor.type}`), this.glContext.attachFramebuffer(t2.texture, e2, n2); - } - bindAttributes(t2) { - const e2 = t2.position, n2 = t2.textureCoord; - this.glContext.setVertexAttributes(e2, n2), this.attributesBound = true; - } - bindUniforms(t2, e2, n2) { - var r2; - const i2 = this.glContext.gl; - let o2 = 0; - for (const { name: a2, type: s, location: u, arrayLength: c } of t2) { - const t3 = null === (r2 = e2.find((t4) => t4.name === a2)) || void 0 === r2 ? void 0 : r2.data; - if ("sampler2D" !== s && !t3) - throw new Error(`variable '${a2}' does not have data defined in program info`); - switch (s) { - case "sampler2D": - this.bindTexture(n2[o2], u, o2), o2++; - break; - case "float": - c ? i2.uniform1fv(u, t3) : i2.uniform1f(u, t3); - break; - case "int": - c ? i2.uniform1iv(u, t3) : i2.uniform1i(u, t3); - break; - default: - throw new Error(`Uniform not implemented: ${s}`); - } - } - } - bindTexture(t2, e2, n2) { - this.glContext.bindTextureToUniform(t2.texture, n2, e2); - } - getAttribLocations(t2) { - return { position: this.getAttribLocation(t2, "position"), textureCoord: this.getAttribLocation(t2, "textureCoord") }; - } - getUniformLocations(t2, e2, n2) { - const r2 = []; - if (e2) - for (const n3 of e2) - r2.push({ name: n3, type: "sampler2D", location: this.getUniformLocation(t2, n3) }); - if (n2) - for (const e3 of n2) - r2.push(Object.assign(Object.assign({}, e3), { location: this.getUniformLocation(t2, e3.name) })); - return r2; - } - getUniformLocation(t2, e2) { - const n2 = this.glContext.gl.getUniformLocation(t2, e2); - if (null === n2) - throw new Error(`Uniform ${e2} not found.`); - return n2; - } - getAttribLocation(t2, e2) { - return this.glContext.gl.getAttribLocation(t2, e2); - } - }; - }, 6416: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.WebGLSessionHandler = void 0; - const r = n(6231), i = n(1047), o = n(8316), a = n(1640), s = n(1958), u = n(7859), c = n(5702); - e.WebGLSessionHandler = class { - constructor(t2, e2) { - this.backend = t2, this.context = e2, this.layoutStrategy = new u.PreferLogicalStrategy(t2.glContext.maxTextureSize), this.programManager = new s.ProgramManager(this.context.profiler, t2.glContext, this.layoutStrategy), this.textureManager = new c.TextureManager(t2.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: "full" === t2.textureCacheMode }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = t2.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map(); - } - createInferenceHandler() { - return new o.WebGLInferenceHandler(this); - } - onGraphInitialized(t2) { - const e2 = t2.getValues().filter((t3) => -1 === t3.from && t3.tensor).map((t3) => t3.tensor.dataId); - this.initializers = new Set(e2); - } - isInitializer(t2) { - return !!this.initializers && this.initializers.has(t2); - } - addInitializer(t2) { - this.initializers.add(t2); - } - getTextureData(t2, e2) { - return e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2); - } - setTextureData(t2, e2, n2 = false) { - r.Logger.verbose("WebGLSessionHandler", "Storing Texture data in cache"), n2 ? this.packedTextureDataCache.set(t2, e2) : this.unpackedTextureDataCache.set(t2, e2); - } - dispose() { - this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((t2) => this.textureManager.releaseTexture(t2, true)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((t2) => this.textureManager.releaseTexture(t2, true)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); - } - resolve(t2, e2, n2) { - const r2 = (0, i.resolveOperator)(t2, e2, a.WEBGL_OP_RESOLVE_RULES); - return { impl: r2.opImpl, context: r2.opInit ? r2.opInit(t2, n2) : t2 }; - } - }; - }, 7769: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.Uint8DataEncoder = e.RGBAFloatDataEncoder = e.RedFloat32DataEncoder = void 0; - const r = n(6231); - e.RedFloat32DataEncoder = class { - constructor(t2, e2 = 1) { - if (1 === e2) - this.internalFormat = t2.R32F, this.format = t2.RED, this.textureType = t2.FLOAT, this.channelSize = e2; - else { - if (4 !== e2) - throw new Error(`Invalid number of channels: ${e2}`); - this.internalFormat = t2.RGBA32F, this.format = t2.RGBA, this.textureType = t2.FLOAT, this.channelSize = e2; - } - } - encode(t2, e2) { - let n2, i; - return t2.constructor !== Float32Array && (r.Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array"), i = new Float32Array(t2)), e2 * this.channelSize > t2.length ? (r.Logger.warning("Encoder", "Source data too small. Allocating larger array"), i = t2, n2 = this.allocate(e2 * this.channelSize), i.forEach((t3, e3) => n2[e3] = t3)) : (i = t2, n2 = i), n2; - } - allocate(t2) { - return new Float32Array(4 * t2); - } - decode(t2, e2) { - return 1 === this.channelSize ? t2.filter((t3, e3) => e3 % 4 == 0).subarray(0, e2) : t2.subarray(0, e2); - } - }, e.RGBAFloatDataEncoder = class { - constructor(t2, e2 = 1, n2) { - if (1 !== e2 && 4 !== e2) - throw new Error(`Invalid number of channels: ${e2}`); - this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.channelSize = e2, this.textureType = n2 || t2.FLOAT; - } - encode(t2, e2) { - let n2 = t2; - return 1 === this.channelSize && (r.Logger.verbose("Encoder", "Exploding into a larger array"), n2 = this.allocate(e2), t2.forEach((t3, e3) => n2[4 * e3] = t3)), n2; - } - allocate(t2) { - return new Float32Array(4 * t2); - } - decode(t2, e2) { - return 1 === this.channelSize ? t2.filter((t3, e3) => e3 % 4 == 0).subarray(0, e2) : t2.subarray(0, e2); - } - }, e.Uint8DataEncoder = class { - constructor(t2, e2 = 1) { - if (this.channelSize = 4, 1 === e2) - this.internalFormat = t2.ALPHA, this.format = t2.ALPHA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2; - else { - if (4 !== e2) - throw new Error(`Invalid number of channels: ${e2}`); - this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2; - } - } - encode(t2, e2) { - return new Uint8Array(t2.buffer, t2.byteOffset, t2.byteLength); - } - allocate(t2) { - return new Uint8Array(t2 * this.channelSize); - } - decode(t2, e2) { - if (t2 instanceof Uint8Array) - return t2.subarray(0, e2); - throw new Error(`Invalid array type: ${t2.constructor}`); - } - }; - }, 7859: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.getBatchDim = e.sizeToSquarishShape = e.getRowsCols = e.sizeFromShape = e.isInt = e.parseAxisParam = e.squeezeShape = e.PreferLogicalStrategy = e.AlwaysKeepOriginalSizeStrategy = void 0; - const r = n(6231), i = n(2517); - function o(t2, e2) { - const n2 = [], r2 = [], i2 = null != e2 && Array.isArray(e2) && 0 === e2.length, o2 = null == e2 || i2 ? null : a(e2, t2).sort(); - let s2 = 0; - for (let e3 = 0; e3 < t2.length; ++e3) { - if (null != o2) { - if (o2[s2] === e3 && 1 !== t2[e3]) - throw new Error(`Can't squeeze axis ${e3} since its dim '${t2[e3]}' is not 1`); - (null == o2[s2] || o2[s2] > e3) && 1 === t2[e3] && (n2.push(t2[e3]), r2.push(e3)), o2[s2] <= e3 && s2++; - } - 1 !== t2[e3] && (n2.push(t2[e3]), r2.push(e3)); - } - return { newShape: n2, keptDims: r2 }; - } - function a(t2, e2) { - const n2 = e2.length; - return t2 = null == t2 ? e2.map((t3, e3) => e3) : [].concat(t2), (0, i.assert)(t2.every((t3) => t3 >= -n2 && t3 < n2), () => `All values in axis param must be in range [-${n2}, ${n2}) but got axis ${t2}`), (0, i.assert)(t2.every(s), () => `All values in axis param must be integers but got axis ${t2}`), t2.map((t3) => t3 < 0 ? n2 + t3 : t3); - } - function s(t2) { - return t2 % 1 == 0; - } - function u(t2) { - if (0 === t2.length) - return 1; - let e2 = t2[0]; - for (let n2 = 1; n2 < t2.length; n2++) - e2 *= t2[n2]; - return e2; - } - function c(t2) { - const e2 = Math.ceil(Math.sqrt(t2)); - return [e2, Math.ceil(t2 / e2)]; - } - e.AlwaysKeepOriginalSizeStrategy = class { - constructor(t2) { - this.maxTextureSize = t2; - } - computeTextureWH(t2, e2) { - if (0 === t2.length) - return [1, 1]; - const n2 = this.maxTextureSize; - if (e2 && void 0 !== e2.breakAxis) { - const i3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce((t3, e3) => t3 * e3), o3 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce((t3, e3) => t3 * e3); - if (!(i3 > n2 || o3 > n2)) - return [i3, o3]; - r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`); - } - const i2 = t2.reduce((t3, e3) => t3 * e3); - let o2 = Math.floor(Math.sqrt(i2)); - for (; o2 < n2 && o2 < i2 && i2 % o2 != 0; o2++) - ; - if (o2 >= n2 || i2 % o2 != 0) - throw new Error(`The given dimensions are outside this GPU's boundaries: ${t2}`); - return [o2, i2 / o2]; - } - }, e.PreferLogicalStrategy = class { - constructor(t2) { - this.maxTextureSize = t2; - } - computeTextureWH(t2, e2) { - const n2 = this.computeTexture(t2, e2); - return e2 && e2.isPacked && (n2[0] /= 2, n2[1] /= 2), e2 && e2.reverseWH ? [n2[1], n2[0]] : n2; - } - computeTexture(t2, e2) { - const n2 = e2 && e2.isPacked; - if (0 === t2.length) - return n2 ? [2, 2] : [1, 1]; - let i2 = this.maxTextureSize; - if (e2 && void 0 !== e2.breakAxis) { - const n3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce((t3, e3) => t3 * e3), o2 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce((t3, e3) => t3 * e3); - if (!(n3 > i2 || o2 > i2)) - return [n3, o2]; - r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`); - } - let a2 = t2.slice(0); - if (n2 && (i2 *= 2, a2 = a2.map((t3, e3) => e3 >= a2.length - 2 ? a2[e3] % 2 == 0 ? a2[e3] : a2[e3] + 1 : a2[e3]), 1 === a2.length && (a2 = [2, a2[0]])), 2 !== a2.length) { - const t3 = o(a2); - a2 = t3.newShape; - } - const s2 = u(a2); - return a2.length <= 1 && s2 <= i2 ? [1, s2] : 2 === a2.length && a2[0] <= i2 && a2[1] <= i2 ? a2 : 3 === a2.length && a2[0] * a2[1] <= i2 && a2[2] <= i2 ? [a2[0] * a2[1], a2[2]] : 3 === a2.length && a2[0] <= i2 && a2[1] * a2[2] <= i2 ? [a2[0], a2[1] * a2[2]] : 4 === a2.length && a2[0] * a2[1] * a2[2] <= i2 && a2[3] <= i2 ? [a2[0] * a2[1] * a2[2], a2[3]] : 4 === a2.length && a2[0] <= i2 && a2[1] * a2[2] * a2[3] <= i2 ? [a2[0], a2[1] * a2[2] * a2[3]] : n2 ? c(s2 / 4).map((t3) => 2 * t3) : c(s2); - } - }, e.squeezeShape = o, e.parseAxisParam = a, e.isInt = s, e.sizeFromShape = u, e.getRowsCols = function(t2) { - if (0 === t2.length) - throw Error("Cannot get rows and columns of an empty shape array."); - return [t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]]; - }, e.sizeToSquarishShape = c, e.getBatchDim = function(t2, e2 = 2) { - return u(t2.slice(0, t2.length - e2)); - }; - }, 4057: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createTextureLayoutFromShape = e.calculateTextureWidthAndHeight = e.createTextureLayoutFromTextureType = void 0; - const r = n(2517), i = n(2039); - e.createTextureLayoutFromTextureType = (t2, n2, r2) => { - const o = r2 === i.TextureType.unpacked || r2 === i.TextureType.unpackedReversed ? 1 : 4, a = r2 === i.TextureType.packed, s = r2 === i.TextureType.unpackedReversed || r2 === i.TextureType.packed, u = r2 === i.TextureType.packedLastDimension ? n2.length - 1 : void 0, c = r2 === i.TextureType.packedLastDimension ? n2.map((t3, e2) => e2 === n2.length - 1 ? 4 * t3 : t3) : void 0; - return (0, e.createTextureLayoutFromShape)(t2, n2, o, c, { isPacked: a, reverseWH: s, breakAxis: u }); - }, e.calculateTextureWidthAndHeight = (t2, n2, r2) => { - const i2 = (0, e.createTextureLayoutFromTextureType)(t2, n2, r2); - return [i2.width, i2.height]; - }, e.createTextureLayoutFromShape = (t2, e2, n2 = 1, i2, o) => { - const a = !(!o || !o.isPacked), [s, u] = t2.computeTextureWH(a && i2 || e2, o), c = e2.length; - let l = e2.slice(0); - if (0 === c && (l = [1]), 1 === n2) - i2 = e2; - else if (a) { - if (4 !== n2) - throw new Error("a packed texture must be 4-channel"); - i2 = e2, c > 0 && (l[c - 1] = Math.ceil(l[c - 1] / 2)), c > 1 && (l[c - 2] = Math.ceil(l[c - 2] / 2)); - } else if (!i2) - throw new Error("Unpacked shape is needed when using channels > 1"); - return { width: s, height: u, channels: n2, isPacked: a, shape: l, strides: r.ShapeUtil.computeStrides(l), unpackedShape: i2, reversedWH: o && o.reverseWH }; - }; - }, 5702: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.TextureManager = void 0; - const r = n(6231); - e.TextureManager = class { - constructor(t2, e2, n2, r2) { - this.glContext = t2, this.layoutStrategy = e2, this.profiler = n2, this.config = r2, this.pendingRead = /* @__PURE__ */ new Map(), r2.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map()); - } - createTextureFromLayout(t2, e2, n2, i) { - const o = this.toEncoderType(t2), a = this.glContext.getEncoder(o, e2.channels || 1, i); - if (e2.isPacked && 1 === i) - throw new Error("not implemented"); - const s = e2.width, u = e2.height; - let c, l; - if (this.config.reuseTextures) { - c = `${s}x${u}_${a.format}_${a.internalFormat}_${a.textureType}`, l = this.inUseTextures.get(c), l || (l = [], this.inUseTextures.set(c, l)); - const e3 = this.idleTextures.get(c); - if (e3 && e3.length > 0) { - const r2 = e3.pop(); - return l.push(r2), 1 === i && this.glContext.updateTexture(r2, s, u, a, this.toTextureData(t2, n2)), r2; - } - } - r.Logger.verbose("TextureManager", `Creating new texture of size ${e2.width}x${e2.height}`); - const p = this.glContext.allocateTexture(s, u, a, this.toTextureData(t2, n2)); - return this.config.reuseTextures && (l.push(p), this.textureLookup.set(p, c)), p; - } - readTexture(t2, e2, n2) { - return n2 || (n2 = 1), this.profiler.event("backend", "TextureManager.readTexture", () => { - const r2 = t2.shape.reduce((t3, e3) => t3 * e3) * n2, i = this.glContext.readTexture(t2.texture, t2.width, t2.height, r2, this.toEncoderType(e2), n2); - return this.toTensorData(e2, i); - }); - } - async readTextureAsync(t2, e2, n2) { - const r2 = t2.tensor.dataId; - if (n2 || (n2 = 1), this.pendingRead.has(r2)) { - const t3 = this.pendingRead.get(r2); - return new Promise((e3) => null == t3 ? void 0 : t3.push(e3)); - } - return this.profiler.event("backend", "TextureManager.readTextureAsync", async () => { - this.pendingRead.set(r2, []); - const i = t2.shape.reduce((t3, e3) => t3 * e3) * n2; - await this.glContext.createAndWaitForFence(); - const o = this.glContext.readTexture(t2.texture, t2.width, t2.height, i, this.toEncoderType(e2), n2), a = this.toTensorData(e2, o), s = this.pendingRead.get(r2); - return this.pendingRead.delete(r2), null == s || s.forEach((t3) => t3(a)), a; - }); - } - readUint8TextureAsFloat(t2) { - return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", () => { - const e2 = t2.shape.reduce((t3, e3) => t3 * e3), n2 = this.glContext.readTexture(t2.texture, t2.width, t2.height, 4 * e2, "byte", 4); - return new Float32Array(n2.buffer, n2.byteOffset, e2); - }); - } - releaseTexture(t2, e2) { - let n2; - if (this.config.reuseTextures && (n2 = this.textureLookup.get(t2.texture), n2)) { - e2 && this.textureLookup.delete(n2); - const r2 = this.inUseTextures.get(n2); - if (r2) { - const e3 = r2.indexOf(t2.texture); - if (-1 !== e3) { - r2.splice(e3, 1); - let i = this.idleTextures.get(n2); - i || (i = [], this.idleTextures.set(n2, i)), i.push(t2.texture); - } - } - } - n2 && !e2 || (r.Logger.verbose("TextureManager", `Deleting texture of size ${t2.width}x${t2.height}`), this.glContext.deleteTexture(t2.texture)); - } - toTensorData(t2, e2) { - switch (t2) { - case "int16": - return e2 instanceof Int16Array ? e2 : Int16Array.from(e2); - case "int32": - return e2 instanceof Int32Array ? e2 : Int32Array.from(e2); - case "int8": - return e2 instanceof Int8Array ? e2 : Int8Array.from(e2); - case "uint16": - return e2 instanceof Uint16Array ? e2 : Uint16Array.from(e2); - case "uint32": - return e2 instanceof Uint32Array ? e2 : Uint32Array.from(e2); - case "uint8": - case "bool": - return e2 instanceof Uint8Array ? e2 : Uint8Array.from(e2); - case "float32": - return e2 instanceof Float32Array ? e2 : Float32Array.from(e2); - case "float64": - return e2 instanceof Float64Array ? e2 : Float64Array.from(e2); - default: - throw new Error(`TensorData type ${t2} is not supported`); - } - } - toTextureData(t2, e2) { - if (e2) - return e2 instanceof Float32Array ? e2 : new Float32Array(e2); - } - toEncoderType(t2) { - return "float"; - } - clearActiveTextures() { - this.glContext.clearActiveTextures(); - } - }; - }, 2039: (t, e) => { - "use strict"; - var n; - Object.defineProperty(e, "__esModule", { value: true }), e.TextureType = void 0, (n = e.TextureType || (e.TextureType = {}))[n.unpacked = 0] = "unpacked", n[n.unpackedReversed = 1] = "unpackedReversed", n[n.packed = 2] = "packed", n[n.downloadUint8AsFloat = 3] = "downloadUint8AsFloat", n[n.packedLastDimension = 4] = "packedLastDimension"; - }, 9390: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.getGlChannels = e.getCoordsDataType = e.getSqueezedParams = e.squeezeInputShape = e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = e.generateShaderFuncNameFromInputSamplerName = e.repeatedTry = e.getPackedShape = void 0; - const r = n(2517); - e.getPackedShape = function(t2) { - const e2 = t2.length; - return t2.slice(0, e2 - 1).concat(t2[e2 - 1] / 4); - }, e.repeatedTry = async function(t2, e2 = (t3) => 0, n2) { - return new Promise((r2, i) => { - let o = 0; - const a = () => { - if (t2()) - return void r2(); - o++; - const s = e2(o); - null != n2 && o >= n2 ? i() : setTimeout(a, s); - }; - a(); - }); - }, e.generateShaderFuncNameFromInputSamplerName = function(t2) { - return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, () => "empty string found for sampler name"), "get" + t2.charAt(0).toUpperCase() + t2.slice(1); - }, e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = function(t2) { - return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, () => "empty string found for sampler name"), "get" + t2.charAt(0).toUpperCase() + t2.slice(1) + "AtOutCoords"; - }, e.squeezeInputShape = function(t2, e2) { - let n2 = JSON.parse(JSON.stringify(t2)); - return n2 = e2, n2; - }, e.getSqueezedParams = function(t2, e2) { - return e2.map((e3) => t2[e3]).join(", "); - }, e.getCoordsDataType = function(t2) { - if (t2 <= 1) - return "int"; - if (2 === t2) - return "ivec2"; - if (3 === t2) - return "ivec3"; - if (4 === t2) - return "ivec4"; - if (5 === t2) - return "ivec5"; - if (6 === t2) - return "ivec6"; - throw Error(`GPU for rank ${t2} is not yet supported`); - }, e.getGlChannels = function(t2 = 6) { - return ["x", "y", "z", "w", "u", "v"].slice(0, t2); - }; - }, 7305: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.createNewWebGLContext = e.createWebGLContext = void 0; - const r = n(6231), i = n(1713), o = {}; - function a(t2) { - const e2 = function() { - if ("undefined" == typeof document) { - if ("undefined" == typeof OffscreenCanvas) - throw new TypeError("failed to create canvas: OffscreenCanvas is not supported"); - return new OffscreenCanvas(1, 1); - } - const t3 = document.createElement("canvas"); - return t3.width = 1, t3.height = 1, t3; - }(); - let n2; - const o2 = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false }; - if ((!t2 || "webgl2" === t2) && (n2 = e2.getContext("webgl2", o2), n2)) - try { - return new i.WebGLContext(n2, 2); - } catch (t3) { - r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${t3}`); - } - if ((!t2 || "webgl" === t2) && (n2 = e2.getContext("webgl", o2) || e2.getContext("experimental-webgl", o2), n2)) - try { - return new i.WebGLContext(n2, 1); - } catch (t3) { - r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t3}`); - } - throw new Error("WebGL is not supported"); - } - e.createWebGLContext = function t2(e2) { - let n2; - e2 && "webgl2" !== e2 || !("webgl2" in o) ? e2 && "webgl" !== e2 || !("webgl" in o) || (n2 = o.webgl) : n2 = o.webgl2, n2 = n2 || a(e2), e2 = e2 || 1 === n2.version ? "webgl" : "webgl2"; - const r2 = n2.gl; - return o[e2] = n2, r2.isContextLost() ? (delete o[e2], t2(e2)) : (r2.disable(r2.DEPTH_TEST), r2.disable(r2.STENCIL_TEST), r2.disable(r2.BLEND), r2.disable(r2.DITHER), r2.disable(r2.POLYGON_OFFSET_FILL), r2.disable(r2.SAMPLE_COVERAGE), r2.enable(r2.SCISSOR_TEST), r2.enable(r2.CULL_FACE), r2.cullFace(r2.BACK), n2); - }, e.createNewWebGLContext = a; - }, 1713: function(t, e, n) { - "use strict"; - var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2); - var i2 = Object.getOwnPropertyDescriptor(e2, n2); - i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { - return e2[n2]; - } }), Object.defineProperty(t2, r2, i2); - } : function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; - }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { - Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); - } : function(t2, e2) { - t2.default = e2; - }), o = this && this.__importStar || function(t2) { - if (t2 && t2.__esModule) - return t2; - var e2 = {}; - if (null != t2) - for (var n2 in t2) - "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); - return i(e2, t2), e2; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.WebGLContext = e.linearSearchLastTrue = void 0; - const a = n(1670), s = o(n(7769)), u = n(9390); - function c(t2) { - let e2 = 0; - for (; e2 < t2.length && t2[e2](); ++e2) - ; - return e2 - 1; - } - e.linearSearchLastTrue = c, e.WebGLContext = class { - constructor(t2, e2) { - this.frameBufferBound = false, this.itemsToPoll = [], this.gl = t2, this.version = e2, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters(); - } - allocateTexture(t2, e2, n2, r2) { - const i2 = this.gl, o2 = i2.createTexture(); - i2.bindTexture(i2.TEXTURE_2D, o2), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MIN_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MAG_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_S, i2.CLAMP_TO_EDGE), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_T, i2.CLAMP_TO_EDGE); - const a2 = r2 ? n2.encode(r2, t2 * e2) : null; - return i2.texImage2D(i2.TEXTURE_2D, 0, n2.internalFormat, t2, e2, 0, n2.format, n2.textureType, a2), this.checkError(), o2; - } - updateTexture(t2, e2, n2, r2, i2) { - const o2 = this.gl; - o2.bindTexture(o2.TEXTURE_2D, t2); - const a2 = r2.encode(i2, e2 * n2); - o2.texSubImage2D(o2.TEXTURE_2D, 0, 0, 0, e2, n2, r2.format, r2.textureType, a2), this.checkError(); - } - attachFramebuffer(t2, e2, n2) { - const r2 = this.gl; - r2.bindTexture(r2.TEXTURE_2D, t2), r2.bindFramebuffer(r2.FRAMEBUFFER, this.framebuffer), r2.framebufferTexture2D(r2.FRAMEBUFFER, r2.COLOR_ATTACHMENT0, r2.TEXTURE_2D, t2, 0), this.checkError(), r2.viewport(0, 0, e2, n2), r2.scissor(0, 0, e2, n2); - } - readTexture(t2, e2, n2, r2, i2, o2) { - const a2 = this.gl; - o2 || (o2 = 1), this.frameBufferBound || this.attachFramebuffer(t2, e2, n2); - const s2 = this.getEncoder(i2, o2), u2 = s2.allocate(e2 * n2); - return a2.bindTexture(a2.TEXTURE_2D, t2), a2.framebufferTexture2D(a2.FRAMEBUFFER, a2.COLOR_ATTACHMENT0, a2.TEXTURE_2D, t2, 0), a2.readPixels(0, 0, e2, n2, a2.RGBA, s2.textureType, u2), this.checkError(), s2.decode(u2, r2); - } - isFramebufferReady() { - return true; - } - getActiveTexture() { - const t2 = this.gl; - return "TEXTURE" + (t2.getParameter(this.gl.ACTIVE_TEXTURE) - t2.TEXTURE0); - } - getTextureBinding() { - return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); - } - getFramebufferBinding() { - return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); - } - setVertexAttributes(t2, e2) { - const n2 = this.gl; - n2.vertexAttribPointer(t2, 3, n2.FLOAT, false, 20, 0), n2.enableVertexAttribArray(t2), -1 !== e2 && (n2.vertexAttribPointer(e2, 2, n2.FLOAT, false, 20, 12), n2.enableVertexAttribArray(e2)), this.checkError(); - } - createProgram(t2, e2) { - const n2 = this.gl, r2 = n2.createProgram(); - return n2.attachShader(r2, t2), n2.attachShader(r2, e2), n2.linkProgram(r2), r2; - } - compileShader(t2, e2) { - const n2 = this.gl, r2 = n2.createShader(e2); - if (!r2) - throw new Error(`createShader() returned null with type ${e2}`); - if (n2.shaderSource(r2, t2), n2.compileShader(r2), false === n2.getShaderParameter(r2, n2.COMPILE_STATUS)) - throw new Error(`Failed to compile shader: ${n2.getShaderInfoLog(r2)} -Shader source: -${t2}`); - return r2; - } - deleteShader(t2) { - this.gl.deleteShader(t2); - } - bindTextureToUniform(t2, e2, n2) { - const r2 = this.gl; - r2.activeTexture(r2.TEXTURE0 + e2), this.checkError(), r2.bindTexture(r2.TEXTURE_2D, t2), this.checkError(), r2.uniform1i(n2, e2), this.checkError(); - } - draw() { - this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError(); - } - checkError() { - if (a.env.debug) { - const t2 = this.gl, e2 = t2.getError(); - let n2 = ""; - switch (e2) { - case t2.NO_ERROR: - return; - case t2.INVALID_ENUM: - n2 = "INVALID_ENUM"; - break; - case t2.INVALID_VALUE: - n2 = "INVALID_VALUE"; - break; - case t2.INVALID_OPERATION: - n2 = "INVALID_OPERATION"; - break; - case t2.INVALID_FRAMEBUFFER_OPERATION: - n2 = "INVALID_FRAMEBUFFER_OPERATION"; - break; - case t2.OUT_OF_MEMORY: - n2 = "OUT_OF_MEMORY"; - break; - case t2.CONTEXT_LOST_WEBGL: - n2 = "CONTEXT_LOST_WEBGL"; - break; - default: - n2 = `Unknown WebGL Error: ${e2.toString(16)}`; - } - throw new Error(n2); - } - } - deleteTexture(t2) { - this.gl.deleteTexture(t2); - } - deleteProgram(t2) { - this.gl.deleteProgram(t2); - } - getEncoder(t2, e2, n2 = 0) { - if (2 === this.version) - return new s.RedFloat32DataEncoder(this.gl, e2); - switch (t2) { - case "float": - return 1 === n2 || this.isRenderFloat32Supported ? new s.RGBAFloatDataEncoder(this.gl, e2) : new s.RGBAFloatDataEncoder(this.gl, e2, this.textureHalfFloatExtension.HALF_FLOAT_OES); - case "int": - throw new Error("not implemented"); - case "byte": - return new s.Uint8DataEncoder(this.gl, e2); - default: - throw new Error(`Invalid dataType: ${t2}`); - } - } - clearActiveTextures() { - const t2 = this.gl; - for (let e2 = 0; e2 < this.maxTextureImageUnits; ++e2) - t2.activeTexture(t2.TEXTURE0 + e2), t2.bindTexture(t2.TEXTURE_2D, null); - } - dispose() { - if (this.disposed) - return; - const t2 = this.gl; - t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(this.framebuffer), t2.bindBuffer(t2.ARRAY_BUFFER, null), t2.deleteBuffer(this.vertexbuffer), t2.bindBuffer(t2.ELEMENT_ARRAY_BUFFER, null), t2.finish(), this.disposed = true; - } - createDefaultGeometry() { - return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]); - } - createVertexbuffer() { - const t2 = this.gl, e2 = t2.createBuffer(); - if (!e2) - throw new Error("createBuffer() returned null"); - const n2 = this.createDefaultGeometry(); - return t2.bindBuffer(t2.ARRAY_BUFFER, e2), t2.bufferData(t2.ARRAY_BUFFER, n2, t2.STATIC_DRAW), this.checkError(), e2; - } - createFramebuffer() { - const t2 = this.gl.createFramebuffer(); - if (!t2) - throw new Error("createFramebuffer returned null"); - return t2; - } - queryVitalParameters() { - const t2 = this.gl; - if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), 1 === this.version && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) - throw new Error("both float32 and float16 TextureType are not supported"); - this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = t2.getParameter(t2.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = t2.getParameter(t2.MAX_TEXTURE_IMAGE_UNITS), this.version; - } - getExtensions() { - 2 === this.version ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float")); - } - checkFloatTextureAttachableToFrameBuffer() { - const t2 = this.gl, e2 = t2.createTexture(); - t2.bindTexture(t2.TEXTURE_2D, e2); - const n2 = 2 === this.version ? t2.RGBA32F : t2.RGBA; - t2.texImage2D(t2.TEXTURE_2D, 0, n2, 1, 1, 0, t2.RGBA, t2.FLOAT, null); - const r2 = t2.createFramebuffer(); - t2.bindFramebuffer(t2.FRAMEBUFFER, r2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0); - const i2 = t2.checkFramebufferStatus(t2.FRAMEBUFFER) === t2.FRAMEBUFFER_COMPLETE; - return t2.bindTexture(t2.TEXTURE_2D, null), t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteTexture(e2), t2.deleteFramebuffer(r2), i2; - } - checkRenderFloat32() { - if (2 === this.version) { - if (!this.colorBufferFloatExtension) - return false; - } else if (!this.textureFloatExtension) - return false; - return this.isFloatTextureAttachableToFrameBuffer; - } - checkFloat32Download() { - if (2 === this.version) { - if (!this.colorBufferFloatExtension) - return false; - } else { - if (!this.textureFloatExtension) - return false; - if (!this.gl.getExtension("WEBGL_color_buffer_float")) - return false; - } - return this.isFloatTextureAttachableToFrameBuffer; - } - checkFloat32Blend() { - const t2 = this.gl; - let e2, n2, r2, i2, o2; - try { - e2 = t2.createTexture(), n2 = t2.createFramebuffer(), t2.bindTexture(t2.TEXTURE_2D, e2); - const a2 = 2 === this.version ? t2.RGBA32F : t2.RGBA; - return t2.texImage2D(t2.TEXTURE_2D, 0, a2, 1, 1, 0, t2.RGBA, t2.FLOAT, null), t2.bindFramebuffer(t2.FRAMEBUFFER, n2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0), t2.enable(t2.BLEND), r2 = t2.createShader(t2.VERTEX_SHADER), !!r2 && (t2.shaderSource(r2, "void main(){}"), t2.compileShader(r2), i2 = t2.createShader(t2.FRAGMENT_SHADER), !!i2 && (t2.shaderSource(i2, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), t2.compileShader(i2), o2 = t2.createProgram(), !!o2 && (t2.attachShader(o2, r2), t2.attachShader(o2, i2), t2.linkProgram(o2), t2.useProgram(o2), t2.drawArrays(t2.POINTS, 0, 1), t2.getError() === t2.NO_ERROR))); - } finally { - t2.disable(t2.BLEND), o2 && t2.deleteProgram(o2), r2 && t2.deleteShader(r2), i2 && t2.deleteShader(i2), n2 && (t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(n2)), e2 && (t2.bindTexture(t2.TEXTURE_2D, null), t2.deleteTexture(e2)); - } - } - beginTimer() { - if (2 === this.version && this.disjointTimerQueryWebgl2Extension) { - const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension, n2 = t2.createQuery(); - return t2.beginQuery(e2.TIME_ELAPSED_EXT, n2), n2; - } - throw new Error("WebGL1 profiling currently not supported."); - } - endTimer() { - if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) - throw new Error("WebGL1 profiling currently not supported"); - { - const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension; - t2.endQuery(e2.TIME_ELAPSED_EXT); - } - } - isTimerResultAvailable(t2) { - let e2 = false, n2 = false; - if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) - throw new Error("WebGL1 profiling currently not supported"); - { - const r2 = this.gl, i2 = this.disjointTimerQueryWebgl2Extension; - e2 = r2.getQueryParameter(t2, r2.QUERY_RESULT_AVAILABLE), n2 = r2.getParameter(i2.GPU_DISJOINT_EXT); - } - return e2 && !n2; - } - getTimerResult(t2) { - let e2 = 0; - if (2 !== this.version) - throw new Error("WebGL1 profiling currently not supported"); - { - const n2 = this.gl; - e2 = n2.getQueryParameter(t2, n2.QUERY_RESULT), n2.deleteQuery(t2); - } - return e2 / 1e6; - } - async waitForQueryAndGetTime(t2) { - return await (0, u.repeatedTry)(() => this.isTimerResultAvailable(t2)), this.getTimerResult(t2); - } - async createAndWaitForFence() { - const t2 = this.createFence(this.gl); - return this.pollFence(t2); - } - createFence(t2) { - let e2; - const n2 = t2, r2 = n2.fenceSync(n2.SYNC_GPU_COMMANDS_COMPLETE, 0); - return t2.flush(), e2 = null === r2 ? () => true : () => { - const t3 = n2.clientWaitSync(r2, 0, 0); - return t3 === n2.ALREADY_SIGNALED || t3 === n2.CONDITION_SATISFIED; - }, { query: r2, isFencePassed: e2 }; - } - async pollFence(t2) { - return new Promise((e2) => { - this.addItemToPoll(() => t2.isFencePassed(), () => e2()); - }); - } - pollItems() { - const t2 = c(this.itemsToPoll.map((t3) => t3.isDoneFn)); - for (let e2 = 0; e2 <= t2; ++e2) { - const { resolveFn: t3 } = this.itemsToPoll[e2]; - t3(); - } - this.itemsToPoll = this.itemsToPoll.slice(t2 + 1); - } - async addItemToPoll(t2, e2) { - this.itemsToPoll.push({ isDoneFn: t2, resolveFn: e2 }), this.itemsToPoll.length > 1 || await (0, u.repeatedTry)(() => (this.pollItems(), 0 === this.itemsToPoll.length)); - } - }; - }, 1036: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.ExecutionPlan = void 0; - const r = n(6231); - class i { - constructor(t2, e2) { - this.op = t2, this.node = e2; - } - } - e.ExecutionPlan = class { - constructor(t2, e2, n2) { - this.graph = t2, this.profiler = n2, this.initialize(e2); - } - initialize(t2) { - this.profiler.event("session", "ExecutionPlan.initialize", () => { - const e2 = this.graph.getNodes(); - if (e2.length !== t2.length) - throw new Error("The size of nodes and OPs do not match."); - this._ops = t2.map((t3, n2) => new i(t3, e2[n2])), this.reset(), this._starter = [], this._ops.forEach((t3, e3) => { - let n2 = true; - for (const e4 of t3.node.inputs) - if (!this._values[e4] && -1 === this.graph.getInputIndices().indexOf(e4)) { - n2 = false; - break; - } - n2 && this._starter.push(e3); - }); - }); - } - reset() { - this._values = this.graph.getValues().map((t2) => t2.tensor); - } - async execute(t2, e2) { - return this.profiler.event("session", "ExecutionPlan.execute", async () => { - this.reset(); - const n2 = t2.createInferenceHandler(), i2 = this.graph.getInputIndices(); - if (e2.length !== i2.length) - throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e2.length} expected: ${i2.length}`); - e2.forEach((t3, e3) => { - const n3 = i2[e3]; - this._values[n3] = t3; - }); - const o = this._starter.slice(0), a = this.graph.getValues(), s = this.graph.getNodes(); - let u = 0; - for (; u < o.length; ) { - const t3 = o[u++], e3 = this._ops[t3], i3 = e3.node.inputs.map((t4) => this._values[t4]); - if (-1 !== i3.indexOf(void 0)) - throw new Error(`unresolved input detected: op: ${e3.node}`); - const c2 = i3; - r.Logger.verbose("ExecPlan", `Runing op:${e3.node.name} (${c2.map((t4, n3) => `'${e3.node.inputs[n3]}': ${t4.type}[${t4.dims.join(",")}]`).join(", ")})`); - const l = await this.profiler.event("node", e3.node.name, async () => e3.op.impl(n2, c2, e3.op.context)); - if (l.length !== e3.node.outputs.length) - throw new Error("the size of output does not match model definition."); - l.forEach((t4, n3) => { - const r2 = e3.node.outputs[n3]; - if (this._values[r2]) - throw new Error(`output [${r2}] already has value: op:${e3.node.name}`); - this._values[r2] = t4; - }); - const p = /* @__PURE__ */ new Set(); - l.forEach((t4, n3) => { - const r2 = e3.node.outputs[n3]; - for (const t5 of a[r2].to) { - const e4 = s[t5]; - let n4 = true; - for (const t6 of e4.inputs) - if (!this._values[t6]) { - n4 = false; - break; - } - n4 && p.add(t5); - } - }), o.push(...p); - } - const c = []; - for (let t3 = 0; t3 < this.graph.getOutputIndices().length; t3++) { - const e3 = this.graph.getOutputIndices()[t3], n3 = this._values[e3]; - if (void 0 === n3) - throw new Error(`required output [${e3}] does not have value`); - 0 === e3 ? await n3.getData() : n3.data, c.push(n3); - } - return r.Logger.verbose("ExecPlan", "disposing of inferenceHandler"), n2.dispose(), c; - }); - } - }; - }, 7070: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.Graph = void 0; - const r = n(1446), i = n(7778), o = n(9395), a = n(9162), s = n(2517); - var u = o.onnxruntime.experimental.fbs; - e.Graph = { from: (t2, e2) => new p(t2, e2) }; - class c { - constructor(t2) { - this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, t2 && (this.type = s.ProtoUtil.tensorValueTypeFromProto(t2.type.tensorType)); - } - get from() { - return this._from; - } - get to() { - return this._to; - } - } - class l { - constructor(t2, e2) { - t2 instanceof r.onnx.NodeProto ? (this.name = t2.name, this.opType = t2.opType, this.attributes = new i.Attribute(t2.attribute)) : t2 instanceof u.Node && (this.name = null != e2 ? e2 : t2.name(), this.opType = t2.opType(), this.attributes = new i.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t2))), this.inputs = [], this.outputs = [], this.executeNode = true; - } - } - class p { - constructor(t2, e2) { - if (!t2) - throw new TypeError("graph is empty"); - this.buildGraph(t2), this.transformGraph(e2), this.checkIsAcyclic(); - } - getInputIndices() { - return this._allInputIndices; - } - getInputNames() { - return this._allInputNames; - } - getOutputIndices() { - return this._allOutputIndices; - } - getOutputNames() { - return this._allOutputNames; - } - getValues() { - return this._allData; - } - getNodes() { - return this._nodes; - } - buildGraph(t2) { - if (t2 instanceof r.onnx.GraphProto) - this.buildGraphFromOnnxFormat(t2); - else { - if (!(t2 instanceof u.Graph)) - throw new TypeError("Graph type is not supported."); - this.buildGraphFromOrtFormat(t2); - } - } - buildGraphFromOnnxFormat(t2) { - const e2 = /* @__PURE__ */ new Map(); - this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; - const n2 = /* @__PURE__ */ new Map(); - if (!t2.input) - throw new Error("missing information in graph: input"); - const r2 = []; - for (const n3 of t2.input) { - if (e2.has(n3.name)) - throw new Error(`duplicated input name: ${n3.name}`); - const t3 = this._allData.push(new c(n3)) - 1; - e2.set(n3.name, t3), r2.push(n3.name); - } - if (!t2.initializer) - throw new Error("missing information in graph: initializer"); - for (const n3 of t2.initializer) { - let t3 = e2.get(n3.name); - if (void 0 === t3) { - const r3 = new c(); - r3.type = { shape: { dims: s.ProtoUtil.tensorDimsFromProto(n3.dims) }, tensorType: s.ProtoUtil.tensorDataTypeFromProto(n3.dataType) }, t3 = this._allData.push(r3) - 1, e2.set(n3.name, t3); - } - this._allData[t3]._from = -1, this._allData[t3].tensor = a.Tensor.fromProto(n3); - } - for (let t3 = 0; t3 < this._allData.length; t3++) - this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(r2[t3])); - if (!t2.output) - throw new Error("missing information in graph: output"); - for (const n3 of t2.output) { - if (e2.has(n3.name)) - throw new Error(`duplicated output name: ${n3.name}`); - const t3 = this._allData.push(new c(n3)) - 1; - e2.set(n3.name, t3), this._allOutputIndices.push(t3), this._allOutputNames.push(n3.name); - } - if (!t2.node) - throw new Error("missing information in graph: node"); - for (const e3 of t2.node) { - if (!e3.name) - for (let t4 = 0; ; t4++) { - const r3 = `unnamed_${e3.opType}_${t4}`; - if (!n2.has(r3)) { - e3.name = r3; - break; - } - } - if (n2.has(e3.name)) - throw new Error(`duplicated node name: ${e3.name}`); - const t3 = this._nodes.push(new l(e3)) - 1; - n2.set(e3.name, t3); - } - for (let n3 = 0; n3 < this._nodes.length; n3++) { - const r3 = this._nodes[n3], i2 = t2.node[n3]; - if (!i2.output) - throw new Error(`missing output for node: ${i2.name}`); - for (const t3 of i2.output) { - let o2 = e2.get(t3); - if (void 0 === o2 && (o2 = this._allData.push(new c()) - 1, e2.set(t3, o2)), r3.outputs.push(o2), void 0 !== this._allData[o2]._from) - throw new Error(`multiple nodes output to one data value: ${o2}`); - if (this._allData[o2]._from = n3, "Constant" === i2.opType) { - if (!i2.attribute || 1 !== i2.attribute.length || !i2.attribute[0].t) - throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); - if (!i2.output || 1 !== i2.output.length) - throw new Error("missing output or incorrect number of outputs for this Constant operator"); - r3.outputs.pop(), r3.executeNode = false, this._allData[o2]._from = -1, this._allData[o2].tensor = a.Tensor.fromProto(i2.attribute[0].t); - } - } - } - for (let n3 = 0; n3 < this._nodes.length; n3++) { - const r3 = this._nodes[n3], i2 = t2.node[n3]; - if (!i2.input) - throw new Error(`missing input for node: ${i2.name}`); - for (const t3 of i2.input) { - const o2 = e2.get(t3); - if (void 0 === o2) { - if ("" === t3 && 3 === i2.input.length && "Resize" === i2.opType) - continue; - throw new Error(`unrecognized input '${t3}' for node: ${i2.name}`); - } - r3.inputs.push(o2), this._allData[o2]._to.push(n3); - } - } - return true; - } - buildGraphFromOrtFormat(t2) { - var e2, n2, r2; - const i2 = /* @__PURE__ */ new Map(); - this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; - const o2 = /* @__PURE__ */ new Map(), p2 = []; - for (let o3 = 0; o3 < t2.inputsLength(); o3++) { - const a2 = t2.inputs(o3); - if (i2.has(a2)) - throw new Error(`duplicated input name: ${a2}`); - for (let o4 = 0; o4 < t2.nodeArgsLength(); o4++) - if ((null === (e2 = t2.nodeArgs(o4)) || void 0 === e2 ? void 0 : e2.name()) === a2) { - const e3 = new c(); - if ((null === (r2 = null === (n2 = t2.nodeArgs(o4)) || void 0 === n2 ? void 0 : n2.type()) || void 0 === r2 ? void 0 : r2.valueType()) !== u.TypeInfoValue.tensor_type) - throw new Error("Unexpected value type for the nodeArg."); - const l2 = t2.nodeArgs(o4).type().value(new u.TensorTypeAndShape()), f = s.ProtoUtil.tensorDataTypeFromProto(l2.elemType()), d = l2.shape(), h = []; - for (let t3 = 0; t3 < d.dimLength(); t3++) - h.push(s.LongUtil.longToNumber(d.dim(t3).value().dimValue())); - e3.type = { shape: { dims: h }, tensorType: f }; - const g = this._allData.push(e3) - 1; - i2.set(a2, g), p2.push(a2); - } - } - for (let e3 = 0; e3 < t2.initializersLength(); e3++) { - const n3 = t2.initializers(e3); - let r3 = i2.get(n3.name()); - if (void 0 === r3) { - const t3 = new c(), e4 = s.ProtoUtil.tensorDimsFromORTFormat(n3), o3 = s.ProtoUtil.tensorDataTypeFromProto(n3.dataType()); - t3.type = { shape: { dims: e4 }, tensorType: o3 }, r3 = this._allData.push(t3) - 1, i2.set(n3.name(), r3); - } - this._allData[r3]._from = -1, this._allData[r3].tensor = a.Tensor.fromOrtTensor(n3); - } - for (let t3 = 0; t3 < this._allData.length; t3++) - this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(p2[t3])); - for (let e3 = 0; e3 < t2.outputsLength(); e3++) { - const n3 = t2.outputs(e3); - if (i2.has(n3)) - throw new Error(`duplicated output name: ${n3}`); - const r3 = this._allData.push(new c()) - 1; - i2.set(n3, r3), this._allOutputIndices.push(r3), this._allOutputNames.push(n3); - } - if (!t2.nodes) - throw new Error("missing information in graph: node"); - for (let e3 = 0; e3 < t2.nodesLength(); e3++) { - const n3 = t2.nodes(e3); - let r3 = n3.name(); - if (!r3) - for (let t3 = 0; r3 = `unnamed_${n3.opType()}_${t3}`, o2.has(r3); t3++) - ; - if (o2.has(r3)) - throw new Error(`duplicated node name: ${r3}`); - const i3 = this._nodes.push(new l(n3, r3)) - 1; - o2.set(r3, i3); - } - for (let e3 = 0; e3 < this._nodes.length; e3++) { - const n3 = this._nodes[e3], r3 = t2.nodes(e3); - if (null == r3) - throw new Error(`No node exists at index ${e3}`); - if (0 === (null == r3 ? void 0 : r3.outputsLength())) - throw new Error(`missing output for node: ${r3.name}`); - for (let t3 = 0; t3 < (null == r3 ? void 0 : r3.outputsLength()); t3++) { - const o3 = null == r3 ? void 0 : r3.outputs(t3); - let s2 = i2.get(o3); - if (void 0 === s2 && (s2 = this._allData.push(new c()) - 1, i2.set(o3, s2)), n3.outputs.push(s2), void 0 !== this._allData[s2]._from) - throw new Error(`multiple nodes output to one data value: ${s2}`); - if (this._allData[s2]._from = e3, "Constant" === r3.opType()) { - if (1 !== r3.attributesLength() || !r3.attributes(0).t()) - throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); - if (1 !== r3.outputsLength()) - throw new Error("missing output or incorrect number of outputs for this Constant operator"); - n3.outputs.pop(), n3.executeNode = false, this._allData[s2]._from = -1, this._allData[s2].tensor = a.Tensor.fromOrtTensor(r3.attributes(0).t()); - } - } - } - for (let e3 = 0; e3 < this._nodes.length; e3++) { - const n3 = this._nodes[e3], r3 = t2.nodes(e3); - if (0 === r3.inputsLength()) - throw new Error(`missing input for node: ${r3.name}`); - for (let t3 = 0; t3 < r3.inputsLength(); t3++) { - const o3 = r3.inputs(t3), a2 = i2.get(o3); - if (void 0 === a2) - throw new Error(`unrecognized input '${o3}' for node: ${r3.name()}`); - n3.inputs.push(a2), this._allData[a2]._to.push(e3); - } - } - } - checkIsAcyclic() { - const t2 = /* @__PURE__ */ new Set(); - this._allInputIndices.forEach((e3) => { - this._allData[e3]._to.forEach((e4) => { - t2.add(e4); - }); - }); - const e2 = Array.from(t2), n2 = new Array(this._nodes.length).fill("white"); - for (; e2.length > 0; ) { - const t3 = e2.pop(); - "gray" === n2[t3] ? n2[t3] = "black" : (e2.push(t3), n2[t3] = "gray", this._nodes[t3].outputs.forEach((r2) => { - const i2 = this._allData[r2]; - if (void 0 !== i2.tensor) - throw new Error("node outputs should not be initialized"); - if (i2._from !== t3) - throw new Error("from property of the Value object doesn't match index of Node being processed"); - i2._to.forEach((t4) => { - if ("gray" === n2[t4]) - throw new Error("model graph is cyclic"); - "white" === n2[t4] && e2.push(t4); - }); - })); - } - } - transformGraph(t2) { - this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), t2 && t2.transformGraph(this), this.finalizeGraph(); - } - finalizeGraph() { - let t2 = 0; - for (let e2 = 0; e2 < this._nodes.length; e2++) - this._nodes[e2].executeNode ? t2 > 0 && (this._nodes[e2].inputs.forEach((n2) => { - const r2 = this._allData[n2]._to.indexOf(e2 + t2); - -1 !== r2 && (this._allData[n2]._to[r2] = e2); - }), this._nodes[e2].outputs.forEach((n2) => { - this._allData[n2]._from && this._allData[n2]._from === e2 + t2 && (this._allData[n2]._from = e2); - })) : (t2++, this._nodes[e2].outputs.forEach((t3) => { - this._allData[t3]._from = -2; - }), this._nodes.splice(e2, 1), e2--); - t2 = 0; - for (let e2 = 0; e2 < this._allData.length; e2++) - if (-2 !== this._allData[e2].from || -1 !== this._allOutputIndices.indexOf(e2 + t2)) { - if (t2 > 0) { - let n2 = -1; - void 0 !== this._allData[e2].from && -1 !== this._allData[e2].from ? (n2 = this._nodes[this._allData[e2].from].outputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[this._allData[e2].from].outputs[n2] = e2)) : (n2 = this._allInputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allInputIndices[n2] = e2)), this._allData[e2].to.forEach((r2) => { - n2 = this._nodes[r2].inputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[r2].inputs[n2] = e2); - }), 0 === this._allData[e2].to.length && (n2 = this._allOutputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allOutputIndices[n2] = e2)); - } - } else - t2++, this._allData.splice(e2, 1), e2--; - } - deleteNode(t2) { - const e2 = this._nodes[t2]; - if (e2.outputs.length > 1) { - for (let t3 = 1; t3 < e2.outputs.length; t3++) - if (this._allData[e2.outputs[t3]].to.length > 0) - throw new Error("Node deletion with more than one output connected to other nodes is not supported. "); - } - e2.executeNode = false; - const n2 = e2.inputs[0], r2 = e2.outputs[0], i2 = this._allData[r2].to, o2 = this._allData[n2].to.indexOf(t2); - if (-1 === o2) - throw new Error("The Value object doesn't have the current Node in it's 'to' property "); - this._allData[n2].to.splice(o2, 1), this._allData[r2]._to = []; - const a2 = this._allOutputIndices.indexOf(r2); - if (-1 !== a2 && (this._allOutputIndices[a2] = n2), i2 && i2.length > 0) - for (const t3 of i2) { - const e3 = this._nodes[t3].inputs.indexOf(r2); - if (-1 === e3) - throw new Error("The Node object doesn't have the output Value in it's 'inputs' property "); - this._nodes[t3].inputs[e3] = n2, this._allData[n2].to.push(t3); - } - } - removeAllDropoutNodes() { - let t2 = 0; - for (const e2 of this._nodes) { - if ("Dropout" === e2.opType) { - if (1 !== e2.inputs.length) - throw new Error("Dropout nodes should only contain one input. "); - if (1 !== e2.outputs.length && 2 !== e2.outputs.length) - throw new Error("Dropout nodes should contain either 1 or 2 output(s)"); - if (2 === e2.outputs.length && 0 !== this._allData[e2.outputs[1]]._to.length) - throw new Error("Dropout nodes's second output should not be referenced by other nodes"); - this.deleteNode(t2); - } - t2++; - } - } - removeAllIdentityNodes() { - let t2 = 0; - for (const e2 of this._nodes) - "Identity" === e2.opType && this.deleteNode(t2), t2++; - } - isActivation(t2) { - switch (t2.opType) { - case "Relu": - case "Sigmoid": - case "Clip": - return true; - default: - return false; - } - } - fuseConvActivationNodes() { - for (const t2 of this._nodes) - if ("Conv" === t2.opType) { - const e2 = this._allData[t2.outputs[0]]._to; - if (1 === e2.length && this.isActivation(this._nodes[e2[0]])) { - const n2 = this._nodes[e2[0]]; - if ("Clip" === n2.opType) - if (1 === n2.inputs.length) - try { - t2.attributes.set("activation_params", "floats", [n2.attributes.getFloat("min"), n2.attributes.getFloat("max")]); - } catch (e3) { - t2.attributes.set("activation_params", "floats", [s.MIN_CLIP, s.MAX_CLIP]); - } - else { - if (!(n2.inputs.length >= 3 && void 0 !== this._allData[n2.inputs[1]].tensor && void 0 !== this._allData[n2.inputs[2]].tensor)) - continue; - t2.attributes.set("activation_params", "floats", [this._allData[n2.inputs[1]].tensor.floatData[0], this._allData[n2.inputs[2]].tensor.floatData[0]]); - } - t2.attributes.set("activation", "string", n2.opType), this.deleteNode(e2[0]); - } - } - } - } - }, 6231: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.now = e.Profiler = e.Logger = void 0; - const n = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, r = { none: new class { - log(t2, e2, n2) { - } - }(), console: new class { - log(t2, e2, n2) { - console.log(`${this.color(t2)} ${n2 ? "\x1B[35m" + n2 + "\x1B[0m " : ""}${e2}`); - } - color(t2) { - switch (t2) { - case "verbose": - return "\x1B[34;40mv\x1B[0m"; - case "info": - return "\x1B[32mi\x1B[0m"; - case "warning": - return "\x1B[30;43mw\x1B[0m"; - case "error": - return "\x1B[31;40me\x1B[0m"; - case "fatal": - return "\x1B[101mf\x1B[0m"; - default: - throw new Error(`unsupported severity: ${t2}`); - } - } - }() }, i = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false }; - let o = { "": i }; - function a(t2, e2, n2, r2) { - if (void 0 === e2) - return i2 = t2, { verbose: a.verbose.bind(null, i2), info: a.info.bind(null, i2), warning: a.warning.bind(null, i2), error: a.error.bind(null, i2), fatal: a.fatal.bind(null, i2) }; - if (void 0 === n2) - s(t2, e2); - else if ("number" == typeof n2 && void 0 === r2) - s(t2, e2); - else if ("string" == typeof n2 && void 0 === r2) - s(t2, n2, 0, e2); - else { - if ("string" != typeof n2 || "number" != typeof r2) - throw new TypeError("input is valid"); - s(t2, n2, 0, e2); - } - var i2; - } - function s(t2, e2, i2, a2) { - const s2 = o[a2 || ""] || o[""]; - n[t2] < n[s2.minimalSeverity] || (s2.logDateTime && (e2 = `${(/* @__PURE__ */ new Date()).toISOString()}|${e2}`), s2.logSourceLocation, r[s2.provider].log(t2, e2, a2)); - } - !function(t2) { - function e2(t3) { - o = {}, n2("", t3 || {}); - } - function n2(t3, n3) { - if ("*" === t3) - e2(n3); - else { - const e3 = o[t3] || i; - o[t3] = { provider: n3.provider || e3.provider, minimalSeverity: n3.minimalSeverity || e3.minimalSeverity, logDateTime: void 0 === n3.logDateTime ? e3.logDateTime : n3.logDateTime, logSourceLocation: void 0 === n3.logSourceLocation ? e3.logSourceLocation : n3.logSourceLocation }; - } - } - t2.verbose = function(e3, n3) { - t2("verbose", e3, n3); - }, t2.info = function(e3, n3) { - t2("info", e3, n3); - }, t2.warning = function(e3, n3) { - t2("warning", e3, n3); - }, t2.error = function(e3, n3) { - t2("error", e3, n3); - }, t2.fatal = function(e3, n3) { - t2("fatal", e3, n3); - }, t2.reset = e2, t2.set = n2, t2.setWithEnv = function(t3) { - const e3 = {}; - t3.logLevel && (e3.minimalSeverity = t3.logLevel), n2("", e3); - }; - }(a || (a = {})), e.Logger = a; - class u { - constructor(t2, e2, n2, r2, i2, o2) { - this.category = t2, this.name = e2, this.startTime = n2, this.endCallback = r2, this.timer = i2, this.ctx = o2; - } - end() { - return this.endCallback(this); - } - async checkTimer() { - if (void 0 === this.ctx || void 0 === this.timer) - throw new Error("No webgl timer found"); - return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer); - } - } - class c { - constructor(t2, e2, n2, r2) { - this.category = t2, this.name = e2, this.startTime = n2, this.endTime = r2; - } - } - e.Profiler = class { - static create(t2) { - return void 0 === t2 ? new this() : new this(t2.maxNumberEvents, t2.flushBatchSize, t2.flushIntervalInMilliseconds); - } - constructor(t2, e2, n2) { - this._started = false, this._flushPointer = 0, this._started = false, this._maxNumberEvents = void 0 === t2 ? 1e4 : t2, this._flushBatchSize = void 0 === e2 ? 10 : e2, this._flushIntervalInMilliseconds = void 0 === n2 ? 5e3 : n2; - } - start() { - this._started = true, this._timingEvents = [], this._flushTime = (0, e.now)(), this._flushPointer = 0; - } - stop() { - for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++) - this.logOneEvent(this._timingEvents[this._flushPointer]); - } - event(t2, e2, n2, r2) { - const i2 = this._started ? this.begin(t2, e2, r2) : void 0; - let o2 = false; - const a2 = n2(); - if (a2 && "function" == typeof a2.then) - return o2 = true, new Promise((t3, e3) => { - a2.then(async (e4) => { - i2 && await i2.end(), t3(e4); - }, async (t4) => { - i2 && await i2.end(), e3(t4); - }); - }); - if (!o2 && i2) { - const t3 = i2.end(); - if (t3 && "function" == typeof t3.then) - return new Promise((e3, n3) => { - t3.then(() => { - e3(a2); - }, (t4) => { - n3(t4); - }); - }); - } - return a2; - } - begin(t2, n2, r2) { - if (!this._started) - throw new Error("profiler is not started yet"); - if (void 0 === r2) { - const r3 = (0, e.now)(); - return this.flush(r3), new u(t2, n2, r3, (t3) => this.endSync(t3)); - } - { - const e2 = r2.beginTimer(); - return new u(t2, n2, 0, async (t3) => this.end(t3), e2, r2); - } - } - async end(t2) { - const e2 = await t2.checkTimer(); - this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, e2)), this.flush(e2)); - } - endSync(t2) { - const n2 = (0, e.now)(); - this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, n2)), this.flush(n2)); - } - logOneEvent(t2) { - e.Logger.verbose(`Profiler.${t2.category}`, `${(t2.endTime - t2.startTime).toFixed(2)}ms on event '${t2.name}' at ${t2.endTime.toFixed(2)}`); - } - flush(t2) { - if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || t2 - this._flushTime >= this._flushIntervalInMilliseconds) { - for (const t3 = this._flushPointer; this._flushPointer < t3 + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) - this.logOneEvent(this._timingEvents[this._flushPointer]); - this._flushTime = (0, e.now)(); - } - } - get started() { - return this._started; - } - }, e.now = "undefined" != typeof performance && performance.now ? () => performance.now() : Date.now; - }, 2644: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.Model = void 0; - const r = n(5686), i = n(1446), o = n(7070), a = n(9395), s = n(2517); - var u = a.onnxruntime.experimental.fbs; - e.Model = class { - constructor() { - } - load(t2, e2, n2) { - if (!n2) - try { - return void this.loadFromOnnxFormat(t2, e2); - } catch (t3) { - if (void 0 !== n2) - throw t3; - } - this.loadFromOrtFormat(t2, e2); - } - loadFromOnnxFormat(t2, e2) { - const n2 = i.onnx.ModelProto.decode(t2); - if (s.LongUtil.longToNumber(n2.irVersion) < 3) - throw new Error("only support ONNX model with IR_VERSION>=3"); - this._opsets = n2.opsetImport.map((t3) => ({ domain: t3.domain, version: s.LongUtil.longToNumber(t3.version) })), this._graph = o.Graph.from(n2.graph, e2); - } - loadFromOrtFormat(t2, e2) { - const n2 = new r.flatbuffers.ByteBuffer(t2), i2 = u.InferenceSession.getRootAsInferenceSession(n2).model(); - if (s.LongUtil.longToNumber(i2.irVersion()) < 3) - throw new Error("only support ONNX model with IR_VERSION>=3"); - this._opsets = []; - for (let t3 = 0; t3 < i2.opsetImportLength(); t3++) { - const e3 = i2.opsetImport(t3); - this._opsets.push({ domain: null == e3 ? void 0 : e3.domain(), version: s.LongUtil.longToNumber(e3.version()) }); - } - this._graph = o.Graph.from(i2.graph(), e2); - } - get graph() { - return this._graph; - } - get opsets() { - return this._opsets; - } - }; - }, 782: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.FLOAT_TYPES = e.INT_TYPES = e.NUMBER_TYPES = void 0, e.NUMBER_TYPES = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"], e.INT_TYPES = ["int32", "int16", "int8", "uint16", "uint32", "uint8"], e.FLOAT_TYPES = ["float32", "float64"]; - }, 1047: (t, e) => { - "use strict"; - function n(t2, e2) { - if (e2.endsWith("+")) { - const n2 = Number.parseInt(e2.substring(0, e2.length - 1), 10); - return !isNaN(n2) && n2 <= t2; - } - if (2 === e2.split("-").length) { - const n2 = e2.split("-"), r = Number.parseInt(n2[0], 10), i = Number.parseInt(n2[1], 10); - return !isNaN(r) && !isNaN(i) && r <= t2 && t2 <= i; - } - return Number.parseInt(e2, 10) === t2; - } - Object.defineProperty(e, "__esModule", { value: true }), e.resolveOperator = void 0, e.resolveOperator = function(t2, e2, r) { - for (const i of r) { - const r2 = i[0], o = i[1], a = i[2], s = i[3], u = i[4]; - if (t2.opType === r2) { - for (const t3 of e2) - if ((t3.domain === o || "ai.onnx" === t3.domain && "" === o) && n(t3.version, a)) - return { opImpl: s, opInit: u }; - } - } - throw new TypeError(`cannot resolve operator '${t2.opType}' with opsets: ${e2.map((t3) => `${t3.domain || "ai.onnx"} v${t3.version}`).join(", ")}`); - }; - }, 9395: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.onnxruntime = void 0; - const r = n(5686); - var i, o; - i = e.onnxruntime || (e.onnxruntime = {}), function(t2) { - let e2; - !function(t3) { - t3[t3.UNDEFINED = 0] = "UNDEFINED", t3[t3.FLOAT = 1] = "FLOAT", t3[t3.INT = 2] = "INT", t3[t3.STRING = 3] = "STRING", t3[t3.TENSOR = 4] = "TENSOR", t3[t3.GRAPH = 5] = "GRAPH", t3[t3.FLOATS = 6] = "FLOATS", t3[t3.INTS = 7] = "INTS", t3[t3.STRINGS = 8] = "STRINGS", t3[t3.TENSORS = 9] = "TENSORS", t3[t3.GRAPHS = 10] = "GRAPHS", t3[t3.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", t3[t3.SPARSE_TENSORS = 12] = "SPARSE_TENSORS"; - }(e2 = t2.AttributeType || (t2.AttributeType = {})); - }((o = i.experimental || (i.experimental = {})).fbs || (o.fbs = {})), function(t2) { - !function(t3) { - !function(t4) { - let e2; - !function(t5) { - t5[t5.UNKNOWN = 0] = "UNKNOWN", t5[t5.VALUE = 1] = "VALUE", t5[t5.PARAM = 2] = "PARAM"; - }(e2 = t4.DimensionValueType || (t4.DimensionValueType = {})); - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - !function(t4) { - let e2; - !function(t5) { - t5[t5.UNDEFINED = 0] = "UNDEFINED", t5[t5.FLOAT = 1] = "FLOAT", t5[t5.UINT8 = 2] = "UINT8", t5[t5.INT8 = 3] = "INT8", t5[t5.UINT16 = 4] = "UINT16", t5[t5.INT16 = 5] = "INT16", t5[t5.INT32 = 6] = "INT32", t5[t5.INT64 = 7] = "INT64", t5[t5.STRING = 8] = "STRING", t5[t5.BOOL = 9] = "BOOL", t5[t5.FLOAT16 = 10] = "FLOAT16", t5[t5.DOUBLE = 11] = "DOUBLE", t5[t5.UINT32 = 12] = "UINT32", t5[t5.UINT64 = 13] = "UINT64", t5[t5.COMPLEX64 = 14] = "COMPLEX64", t5[t5.COMPLEX128 = 15] = "COMPLEX128", t5[t5.BFLOAT16 = 16] = "BFLOAT16"; - }(e2 = t4.TensorDataType || (t4.TensorDataType = {})); - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - !function(t4) { - let e2; - !function(t5) { - t5[t5.Primitive = 0] = "Primitive", t5[t5.Fused = 1] = "Fused"; - }(e2 = t4.NodeType || (t4.NodeType = {})); - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - !function(t4) { - let e2; - !function(t5) { - t5[t5.NONE = 0] = "NONE", t5[t5.tensor_type = 1] = "tensor_type", t5[t5.sequence_type = 2] = "sequence_type", t5[t5.map_type = 3] = "map_type"; - }(e2 = t4.TypeInfoValue || (t4.TypeInfoValue = {})); - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsShape(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsShape(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - dim(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 4); - return r2 ? (n3 || new t2.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - dimLength() { - let t3 = this.bb.__offset(this.bb_pos, 4); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startShape(t3) { - t3.startObject(1); - } - static addDim(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static createDimVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startDimVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endShape(t3) { - return t3.endObject(); - } - static createShape(t3, e4) { - return n2.startShape(t3), n2.addDim(t3, e4), n2.endShape(t3); - } - } - e3.Shape = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsDimension(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsDimension(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - value(e4) { - let n3 = this.bb.__offset(this.bb_pos, 4); - return n3 ? (e4 || new t2.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - denotation(t3) { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - static startDimension(t3) { - t3.startObject(2); - } - static addValue(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addDenotation(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static endDimension(t3) { - return t3.endObject(); - } - static createDimension(t3, e4, r2) { - return n2.startDimension(t3), n2.addValue(t3, e4), n2.addDenotation(t3, r2), n2.endDimension(t3); - } - } - e3.Dimension = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsDimensionValue(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsDimensionValue(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - dimType() { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.readInt8(this.bb_pos + e4) : t2.experimental.fbs.DimensionValueType.UNKNOWN; - } - dimValue() { - let t3 = this.bb.__offset(this.bb_pos, 6); - return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); - } - dimParam(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - static startDimensionValue(t3) { - t3.startObject(3); - } - static addDimType(e4, n3) { - e4.addFieldInt8(0, n3, t2.experimental.fbs.DimensionValueType.UNKNOWN); - } - static addDimValue(t3, e4) { - t3.addFieldInt64(1, e4, t3.createLong(0, 0)); - } - static addDimParam(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static endDimensionValue(t3) { - return t3.endObject(); - } - static createDimensionValue(t3, e4, r2, i2) { - return n2.startDimensionValue(t3), n2.addDimType(t3, e4), n2.addDimValue(t3, r2), n2.addDimParam(t3, i2), n2.endDimensionValue(t3); - } - } - e3.DimensionValue = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsTensorTypeAndShape(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsTensorTypeAndShape(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - elemType() { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; - } - shape(e4) { - let n3 = this.bb.__offset(this.bb_pos, 6); - return n3 ? (e4 || new t2.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startTensorTypeAndShape(t3) { - t3.startObject(2); - } - static addElemType(e4, n3) { - e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); - } - static addShape(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static endTensorTypeAndShape(t3) { - return t3.endObject(); - } - static createTensorTypeAndShape(t3, e4, r2) { - return n2.startTensorTypeAndShape(t3), n2.addElemType(t3, e4), n2.addShape(t3, r2), n2.endTensorTypeAndShape(t3); - } - } - e3.TensorTypeAndShape = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsMapType(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsMapType(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - keyType() { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; - } - valueType(e4) { - let n3 = this.bb.__offset(this.bb_pos, 6); - return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startMapType(t3) { - t3.startObject(2); - } - static addKeyType(e4, n3) { - e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); - } - static addValueType(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static endMapType(t3) { - return t3.endObject(); - } - static createMapType(t3, e4, r2) { - return n2.startMapType(t3), n2.addKeyType(t3, e4), n2.addValueType(t3, r2), n2.endMapType(t3); - } - } - e3.MapType = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsSequenceType(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsSequenceType(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - elemType(e4) { - let n3 = this.bb.__offset(this.bb_pos, 4); - return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startSequenceType(t3) { - t3.startObject(1); - } - static addElemType(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static endSequenceType(t3) { - return t3.endObject(); - } - static createSequenceType(t3, e4) { - return n2.startSequenceType(t3), n2.addElemType(t3, e4), n2.endSequenceType(t3); - } - } - e3.SequenceType = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - (t3.fbs || (t3.fbs = {})).EdgeEnd = class { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t4, e2) { - return this.bb_pos = t4, this.bb = e2, this; - } - nodeIndex() { - return this.bb.readUint32(this.bb_pos); - } - srcArgIndex() { - return this.bb.readInt32(this.bb_pos + 4); - } - dstArgIndex() { - return this.bb.readInt32(this.bb_pos + 8); - } - static createEdgeEnd(t4, e2, n2, r2) { - return t4.prep(4, 12), t4.writeInt32(r2), t4.writeInt32(n2), t4.writeInt32(e2), t4.offset(); - } - }; - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsNodeEdge(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsNodeEdge(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - nodeIndex() { - let t3 = this.bb.__offset(this.bb_pos, 4); - return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; - } - inputEdges(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 6); - return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null; - } - inputEdgesLength() { - let t3 = this.bb.__offset(this.bb_pos, 6); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - outputEdges(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 8); - return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null; - } - outputEdgesLength() { - let t3 = this.bb.__offset(this.bb_pos, 8); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startNodeEdge(t3) { - t3.startObject(3); - } - static addNodeIndex(t3, e4) { - t3.addFieldInt32(0, e4, 0); - } - static addInputEdges(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static startInputEdgesVector(t3, e4) { - t3.startVector(12, e4, 4); - } - static addOutputEdges(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static startOutputEdgesVector(t3, e4) { - t3.startVector(12, e4, 4); - } - static endNodeEdge(t3) { - return t3.endObject(); - } - static createNodeEdge(t3, e4, r2, i2) { - return n2.startNodeEdge(t3), n2.addNodeIndex(t3, e4), n2.addInputEdges(t3, r2), n2.addOutputEdges(t3, i2), n2.endNodeEdge(t3); - } - } - e3.NodeEdge = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsNode(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsNode(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - name(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - docString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - domain(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - sinceVersion() { - let t3 = this.bb.__offset(this.bb_pos, 10); - return t3 ? this.bb.readInt32(this.bb_pos + t3) : 0; - } - index() { - let t3 = this.bb.__offset(this.bb_pos, 12); - return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; - } - opType(t3) { - let e4 = this.bb.__offset(this.bb_pos, 14); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - type() { - let e4 = this.bb.__offset(this.bb_pos, 16); - return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.NodeType.Primitive; - } - executionProviderType(t3) { - let e4 = this.bb.__offset(this.bb_pos, 18); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - inputs(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 20); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - inputsLength() { - let t3 = this.bb.__offset(this.bb_pos, 20); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - outputs(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 22); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - outputsLength() { - let t3 = this.bb.__offset(this.bb_pos, 22); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - attributes(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 24); - return r2 ? (n3 || new t2.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - attributesLength() { - let t3 = this.bb.__offset(this.bb_pos, 24); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - inputArgCounts(t3) { - let e4 = this.bb.__offset(this.bb_pos, 26); - return e4 ? this.bb.readInt32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0; - } - inputArgCountsLength() { - let t3 = this.bb.__offset(this.bb_pos, 26); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - inputArgCountsArray() { - let t3 = this.bb.__offset(this.bb_pos, 26); - return t3 ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; - } - implicitInputs(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 28); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - implicitInputsLength() { - let t3 = this.bb.__offset(this.bb_pos, 28); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startNode(t3) { - t3.startObject(13); - } - static addName(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addDocString(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addDomain(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static addSinceVersion(t3, e4) { - t3.addFieldInt32(3, e4, 0); - } - static addIndex(t3, e4) { - t3.addFieldInt32(4, e4, 0); - } - static addOpType(t3, e4) { - t3.addFieldOffset(5, e4, 0); - } - static addType(e4, n3) { - e4.addFieldInt32(6, n3, t2.experimental.fbs.NodeType.Primitive); - } - static addExecutionProviderType(t3, e4) { - t3.addFieldOffset(7, e4, 0); - } - static addInputs(t3, e4) { - t3.addFieldOffset(8, e4, 0); - } - static createInputsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startInputsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addOutputs(t3, e4) { - t3.addFieldOffset(9, e4, 0); - } - static createOutputsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startOutputsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addAttributes(t3, e4) { - t3.addFieldOffset(10, e4, 0); - } - static createAttributesVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startAttributesVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addInputArgCounts(t3, e4) { - t3.addFieldOffset(11, e4, 0); - } - static createInputArgCountsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addInt32(e4[n3]); - return t3.endVector(); - } - static startInputArgCountsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addImplicitInputs(t3, e4) { - t3.addFieldOffset(12, e4, 0); - } - static createImplicitInputsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startImplicitInputsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endNode(t3) { - return t3.endObject(); - } - static createNode(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) { - return n2.startNode(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDomain(t3, i2), n2.addSinceVersion(t3, o2), n2.addIndex(t3, a), n2.addOpType(t3, s), n2.addType(t3, u), n2.addExecutionProviderType(t3, c), n2.addInputs(t3, l), n2.addOutputs(t3, p), n2.addAttributes(t3, f), n2.addInputArgCounts(t3, d), n2.addImplicitInputs(t3, h), n2.endNode(t3); - } - } - e3.Node = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsValueInfo(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsValueInfo(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - name(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - docString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - type(e4) { - let n3 = this.bb.__offset(this.bb_pos, 8); - return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startValueInfo(t3) { - t3.startObject(3); - } - static addName(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addDocString(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addType(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static endValueInfo(t3) { - return t3.endObject(); - } - static createValueInfo(t3, e4, r2, i2) { - return n2.startValueInfo(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.endValueInfo(t3); - } - } - e3.ValueInfo = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsTypeInfo(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsTypeInfo(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - denotation(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - valueType() { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.readUint8(this.bb_pos + e4) : t2.experimental.fbs.TypeInfoValue.NONE; - } - value(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.__union(t3, this.bb_pos + e4) : null; - } - static startTypeInfo(t3) { - t3.startObject(3); - } - static addDenotation(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addValueType(e4, n3) { - e4.addFieldInt8(1, n3, t2.experimental.fbs.TypeInfoValue.NONE); - } - static addValue(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static endTypeInfo(t3) { - return t3.endObject(); - } - static createTypeInfo(t3, e4, r2, i2) { - return n2.startTypeInfo(t3), n2.addDenotation(t3, e4), n2.addValueType(t3, r2), n2.addValue(t3, i2), n2.endTypeInfo(t3); - } - } - e3.TypeInfo = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - !function(t4) { - class e2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t5, e3) { - return this.bb_pos = t5, this.bb = e3, this; - } - static getRootAsOperatorSetId(t5, n2) { - return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); - } - static getSizePrefixedRootAsOperatorSetId(t5, n2) { - return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); - } - domain(t5) { - let e3 = this.bb.__offset(this.bb_pos, 4); - return e3 ? this.bb.__string(this.bb_pos + e3, t5) : null; - } - version() { - let t5 = this.bb.__offset(this.bb_pos, 6); - return t5 ? this.bb.readInt64(this.bb_pos + t5) : this.bb.createLong(0, 0); - } - static startOperatorSetId(t5) { - t5.startObject(2); - } - static addDomain(t5, e3) { - t5.addFieldOffset(0, e3, 0); - } - static addVersion(t5, e3) { - t5.addFieldInt64(1, e3, t5.createLong(0, 0)); - } - static endOperatorSetId(t5) { - return t5.endObject(); - } - static createOperatorSetId(t5, n2, r2) { - return e2.startOperatorSetId(t5), e2.addDomain(t5, n2), e2.addVersion(t5, r2), e2.endOperatorSetId(t5); - } - } - t4.OperatorSetId = e2; - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsTensor(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsTensor(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - name(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - docString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - dims(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); - } - dimsLength() { - let t3 = this.bb.__offset(this.bb_pos, 8); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - dataType() { - let e4 = this.bb.__offset(this.bb_pos, 10); - return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; - } - rawData(t3) { - let e4 = this.bb.__offset(this.bb_pos, 12); - return e4 ? this.bb.readUint8(this.bb.__vector(this.bb_pos + e4) + t3) : 0; - } - rawDataLength() { - let t3 = this.bb.__offset(this.bb_pos, 12); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - rawDataArray() { - let t3 = this.bb.__offset(this.bb_pos, 12); - return t3 ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; - } - stringData(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 14); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - stringDataLength() { - let t3 = this.bb.__offset(this.bb_pos, 14); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startTensor(t3) { - t3.startObject(6); - } - static addName(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addDocString(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addDims(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static createDimsVector(t3, e4) { - t3.startVector(8, e4.length, 8); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addInt64(e4[n3]); - return t3.endVector(); - } - static startDimsVector(t3, e4) { - t3.startVector(8, e4, 8); - } - static addDataType(e4, n3) { - e4.addFieldInt32(3, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); - } - static addRawData(t3, e4) { - t3.addFieldOffset(4, e4, 0); - } - static createRawDataVector(t3, e4) { - t3.startVector(1, e4.length, 1); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addInt8(e4[n3]); - return t3.endVector(); - } - static startRawDataVector(t3, e4) { - t3.startVector(1, e4, 1); - } - static addStringData(t3, e4) { - t3.addFieldOffset(5, e4, 0); - } - static createStringDataVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startStringDataVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endTensor(t3) { - return t3.endObject(); - } - static createTensor(t3, e4, r2, i2, o2, a, s) { - return n2.startTensor(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDims(t3, i2), n2.addDataType(t3, o2), n2.addRawData(t3, a), n2.addStringData(t3, s), n2.endTensor(t3); - } - } - e3.Tensor = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsSparseTensor(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsSparseTensor(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - values(e4) { - let n3 = this.bb.__offset(this.bb_pos, 4); - return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - indices(e4) { - let n3 = this.bb.__offset(this.bb_pos, 6); - return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - dims(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); - } - dimsLength() { - let t3 = this.bb.__offset(this.bb_pos, 8); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startSparseTensor(t3) { - t3.startObject(3); - } - static addValues(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addIndices(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addDims(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static createDimsVector(t3, e4) { - t3.startVector(8, e4.length, 8); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addInt64(e4[n3]); - return t3.endVector(); - } - static startDimsVector(t3, e4) { - t3.startVector(8, e4, 8); - } - static endSparseTensor(t3) { - return t3.endObject(); - } - static createSparseTensor(t3, e4, r2, i2) { - return n2.startSparseTensor(t3), n2.addValues(t3, e4), n2.addIndices(t3, r2), n2.addDims(t3, i2), n2.endSparseTensor(t3); - } - } - e3.SparseTensor = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsAttribute(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsAttribute(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - name(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - docString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 6); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - type() { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.AttributeType.UNDEFINED; - } - f() { - let t3 = this.bb.__offset(this.bb_pos, 10); - return t3 ? this.bb.readFloat32(this.bb_pos + t3) : 0; - } - i() { - let t3 = this.bb.__offset(this.bb_pos, 12); - return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); - } - s(t3) { - let e4 = this.bb.__offset(this.bb_pos, 14); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - t(e4) { - let n3 = this.bb.__offset(this.bb_pos, 16); - return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - g(e4) { - let n3 = this.bb.__offset(this.bb_pos, 18); - return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - floats(t3) { - let e4 = this.bb.__offset(this.bb_pos, 20); - return e4 ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0; - } - floatsLength() { - let t3 = this.bb.__offset(this.bb_pos, 20); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - floatsArray() { - let t3 = this.bb.__offset(this.bb_pos, 20); - return t3 ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; - } - ints(t3) { - let e4 = this.bb.__offset(this.bb_pos, 22); - return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); - } - intsLength() { - let t3 = this.bb.__offset(this.bb_pos, 22); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - strings(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 24); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - stringsLength() { - let t3 = this.bb.__offset(this.bb_pos, 24); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - tensors(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 26); - return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - tensorsLength() { - let t3 = this.bb.__offset(this.bb_pos, 26); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - graphs(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 28); - return r2 ? (n3 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - graphsLength() { - let t3 = this.bb.__offset(this.bb_pos, 28); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startAttribute(t3) { - t3.startObject(13); - } - static addName(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addDocString(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addType(e4, n3) { - e4.addFieldInt32(2, n3, t2.experimental.fbs.AttributeType.UNDEFINED); - } - static addF(t3, e4) { - t3.addFieldFloat32(3, e4, 0); - } - static addI(t3, e4) { - t3.addFieldInt64(4, e4, t3.createLong(0, 0)); - } - static addS(t3, e4) { - t3.addFieldOffset(5, e4, 0); - } - static addT(t3, e4) { - t3.addFieldOffset(6, e4, 0); - } - static addG(t3, e4) { - t3.addFieldOffset(7, e4, 0); - } - static addFloats(t3, e4) { - t3.addFieldOffset(8, e4, 0); - } - static createFloatsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addFloat32(e4[n3]); - return t3.endVector(); - } - static startFloatsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addInts(t3, e4) { - t3.addFieldOffset(9, e4, 0); - } - static createIntsVector(t3, e4) { - t3.startVector(8, e4.length, 8); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addInt64(e4[n3]); - return t3.endVector(); - } - static startIntsVector(t3, e4) { - t3.startVector(8, e4, 8); - } - static addStrings(t3, e4) { - t3.addFieldOffset(10, e4, 0); - } - static createStringsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startStringsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addTensors(t3, e4) { - t3.addFieldOffset(11, e4, 0); - } - static createTensorsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startTensorsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addGraphs(t3, e4) { - t3.addFieldOffset(12, e4, 0); - } - static createGraphsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startGraphsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endAttribute(t3) { - return t3.endObject(); - } - static createAttribute(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) { - return n2.startAttribute(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.addF(t3, o2), n2.addI(t3, a), n2.addS(t3, s), n2.addT(t3, u), n2.addG(t3, c), n2.addFloats(t3, l), n2.addInts(t3, p), n2.addStrings(t3, f), n2.addTensors(t3, d), n2.addGraphs(t3, h), n2.endAttribute(t3); - } - } - e3.Attribute = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsGraph(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsGraph(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - initializers(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 4); - return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - initializersLength() { - let t3 = this.bb.__offset(this.bb_pos, 4); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - nodeArgs(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 6); - return r2 ? (n3 || new t2.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - nodeArgsLength() { - let t3 = this.bb.__offset(this.bb_pos, 6); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - nodes(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 8); - return r2 ? (n3 || new t2.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - nodesLength() { - let t3 = this.bb.__offset(this.bb_pos, 8); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - maxNodeIndex() { - let t3 = this.bb.__offset(this.bb_pos, 10); - return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; - } - nodeEdges(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 12); - return r2 ? (n3 || new t2.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - nodeEdgesLength() { - let t3 = this.bb.__offset(this.bb_pos, 12); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - inputs(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 14); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - inputsLength() { - let t3 = this.bb.__offset(this.bb_pos, 14); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - outputs(t3, e4) { - let n3 = this.bb.__offset(this.bb_pos, 16); - return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; - } - outputsLength() { - let t3 = this.bb.__offset(this.bb_pos, 16); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - sparseInitializers(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 18); - return r2 ? (n3 || new t2.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - sparseInitializersLength() { - let t3 = this.bb.__offset(this.bb_pos, 18); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startGraph(t3) { - t3.startObject(8); - } - static addInitializers(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static createInitializersVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startInitializersVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addNodeArgs(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static createNodeArgsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startNodeArgsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addNodes(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static createNodesVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startNodesVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addMaxNodeIndex(t3, e4) { - t3.addFieldInt32(3, e4, 0); - } - static addNodeEdges(t3, e4) { - t3.addFieldOffset(4, e4, 0); - } - static createNodeEdgesVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startNodeEdgesVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addInputs(t3, e4) { - t3.addFieldOffset(5, e4, 0); - } - static createInputsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startInputsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addOutputs(t3, e4) { - t3.addFieldOffset(6, e4, 0); - } - static createOutputsVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startOutputsVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addSparseInitializers(t3, e4) { - t3.addFieldOffset(7, e4, 0); - } - static createSparseInitializersVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startSparseInitializersVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endGraph(t3) { - return t3.endObject(); - } - static createGraph(t3, e4, r2, i2, o2, a, s, u, c) { - return n2.startGraph(t3), n2.addInitializers(t3, e4), n2.addNodeArgs(t3, r2), n2.addNodes(t3, i2), n2.addMaxNodeIndex(t3, o2), n2.addNodeEdges(t3, a), n2.addInputs(t3, s), n2.addOutputs(t3, u), n2.addSparseInitializers(t3, c), n2.endGraph(t3); - } - } - e3.Graph = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsModel(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsModel(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - irVersion() { - let t3 = this.bb.__offset(this.bb_pos, 4); - return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); - } - opsetImport(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 6); - return r2 ? (n3 || new t2.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - opsetImportLength() { - let t3 = this.bb.__offset(this.bb_pos, 6); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - producerName(t3) { - let e4 = this.bb.__offset(this.bb_pos, 8); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - producerVersion(t3) { - let e4 = this.bb.__offset(this.bb_pos, 10); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - domain(t3) { - let e4 = this.bb.__offset(this.bb_pos, 12); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - modelVersion() { - let t3 = this.bb.__offset(this.bb_pos, 14); - return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); - } - docString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 16); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - graph(e4) { - let n3 = this.bb.__offset(this.bb_pos, 18); - return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - graphDocString(t3) { - let e4 = this.bb.__offset(this.bb_pos, 20); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - static startModel(t3) { - t3.startObject(9); - } - static addIrVersion(t3, e4) { - t3.addFieldInt64(0, e4, t3.createLong(0, 0)); - } - static addOpsetImport(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static createOpsetImportVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startOpsetImportVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static addProducerName(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static addProducerVersion(t3, e4) { - t3.addFieldOffset(3, e4, 0); - } - static addDomain(t3, e4) { - t3.addFieldOffset(4, e4, 0); - } - static addModelVersion(t3, e4) { - t3.addFieldInt64(5, e4, t3.createLong(0, 0)); - } - static addDocString(t3, e4) { - t3.addFieldOffset(6, e4, 0); - } - static addGraph(t3, e4) { - t3.addFieldOffset(7, e4, 0); - } - static addGraphDocString(t3, e4) { - t3.addFieldOffset(8, e4, 0); - } - static endModel(t3) { - return t3.endObject(); - } - static createModel(t3, e4, r2, i2, o2, a, s, u, c, l) { - return n2.startModel(t3), n2.addIrVersion(t3, e4), n2.addOpsetImport(t3, r2), n2.addProducerName(t3, i2), n2.addProducerVersion(t3, o2), n2.addDomain(t3, a), n2.addModelVersion(t3, s), n2.addDocString(t3, u), n2.addGraph(t3, c), n2.addGraphDocString(t3, l), n2.endModel(t3); - } - } - e3.Model = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(t3) { - !function(t4) { - class e2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t5, e3) { - return this.bb_pos = t5, this.bb = e3, this; - } - static getRootAsKernelCreateInfos(t5, n2) { - return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); - } - static getSizePrefixedRootAsKernelCreateInfos(t5, n2) { - return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); - } - nodeIndices(t5) { - let e3 = this.bb.__offset(this.bb_pos, 4); - return e3 ? this.bb.readUint32(this.bb.__vector(this.bb_pos + e3) + 4 * t5) : 0; - } - nodeIndicesLength() { - let t5 = this.bb.__offset(this.bb_pos, 4); - return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0; - } - nodeIndicesArray() { - let t5 = this.bb.__offset(this.bb_pos, 4); - return t5 ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t5), this.bb.__vector_len(this.bb_pos + t5)) : null; - } - kernelDefHashes(t5) { - let e3 = this.bb.__offset(this.bb_pos, 6); - return e3 ? this.bb.readUint64(this.bb.__vector(this.bb_pos + e3) + 8 * t5) : this.bb.createLong(0, 0); - } - kernelDefHashesLength() { - let t5 = this.bb.__offset(this.bb_pos, 6); - return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0; - } - static startKernelCreateInfos(t5) { - t5.startObject(2); - } - static addNodeIndices(t5, e3) { - t5.addFieldOffset(0, e3, 0); - } - static createNodeIndicesVector(t5, e3) { - t5.startVector(4, e3.length, 4); - for (let n2 = e3.length - 1; n2 >= 0; n2--) - t5.addInt32(e3[n2]); - return t5.endVector(); - } - static startNodeIndicesVector(t5, e3) { - t5.startVector(4, e3, 4); - } - static addKernelDefHashes(t5, e3) { - t5.addFieldOffset(1, e3, 0); - } - static createKernelDefHashesVector(t5, e3) { - t5.startVector(8, e3.length, 8); - for (let n2 = e3.length - 1; n2 >= 0; n2--) - t5.addInt64(e3[n2]); - return t5.endVector(); - } - static startKernelDefHashesVector(t5, e3) { - t5.startVector(8, e3, 8); - } - static endKernelCreateInfos(t5) { - return t5.endObject(); - } - static createKernelCreateInfos(t5, n2, r2) { - return e2.startKernelCreateInfos(t5), e2.addNodeIndices(t5, n2), e2.addKernelDefHashes(t5, r2), e2.endKernelCreateInfos(t5); - } - } - t4.KernelCreateInfos = e2; - }(t3.fbs || (t3.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsSubGraphSessionState(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsSubGraphSessionState(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - graphId(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - sessionState(e4) { - let n3 = this.bb.__offset(this.bb_pos, 6); - return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startSubGraphSessionState(t3) { - t3.startObject(2); - } - static addGraphId(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addSessionState(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static endSubGraphSessionState(t3) { - let e4 = t3.endObject(); - return t3.requiredField(e4, 4), e4; - } - static createSubGraphSessionState(t3, e4, r2) { - return n2.startSubGraphSessionState(t3), n2.addGraphId(t3, e4), n2.addSessionState(t3, r2), n2.endSubGraphSessionState(t3); - } - } - e3.SubGraphSessionState = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsSessionState(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsSessionState(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - kernels(e4) { - let n3 = this.bb.__offset(this.bb_pos, 4); - return n3 ? (e4 || new t2.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - subGraphSessionStates(e4, n3) { - let r2 = this.bb.__offset(this.bb_pos, 6); - return r2 ? (n3 || new t2.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; - } - subGraphSessionStatesLength() { - let t3 = this.bb.__offset(this.bb_pos, 6); - return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; - } - static startSessionState(t3) { - t3.startObject(2); - } - static addKernels(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addSubGraphSessionStates(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static createSubGraphSessionStatesVector(t3, e4) { - t3.startVector(4, e4.length, 4); - for (let n3 = e4.length - 1; n3 >= 0; n3--) - t3.addOffset(e4[n3]); - return t3.endVector(); - } - static startSubGraphSessionStatesVector(t3, e4) { - t3.startVector(4, e4, 4); - } - static endSessionState(t3) { - return t3.endObject(); - } - static createSessionState(t3, e4, r2) { - return n2.startSessionState(t3), n2.addKernels(t3, e4), n2.addSubGraphSessionStates(t3, r2), n2.endSessionState(t3); - } - } - e3.SessionState = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})), function(t2) { - !function(e2) { - !function(e3) { - class n2 { - constructor() { - this.bb = null, this.bb_pos = 0; - } - __init(t3, e4) { - return this.bb_pos = t3, this.bb = e4, this; - } - static getRootAsInferenceSession(t3, e4) { - return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static getSizePrefixedRootAsInferenceSession(t3, e4) { - return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); - } - static bufferHasIdentifier(t3) { - return t3.__has_identifier("ORTM"); - } - ortVersion(t3) { - let e4 = this.bb.__offset(this.bb_pos, 4); - return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; - } - model(e4) { - let n3 = this.bb.__offset(this.bb_pos, 6); - return n3 ? (e4 || new t2.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - sessionState(e4) { - let n3 = this.bb.__offset(this.bb_pos, 8); - return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; - } - static startInferenceSession(t3) { - t3.startObject(3); - } - static addOrtVersion(t3, e4) { - t3.addFieldOffset(0, e4, 0); - } - static addModel(t3, e4) { - t3.addFieldOffset(1, e4, 0); - } - static addSessionState(t3, e4) { - t3.addFieldOffset(2, e4, 0); - } - static endInferenceSession(t3) { - return t3.endObject(); - } - static finishInferenceSessionBuffer(t3, e4) { - t3.finish(e4, "ORTM"); - } - static finishSizePrefixedInferenceSessionBuffer(t3, e4) { - t3.finish(e4, "ORTM", true); - } - static createInferenceSession(t3, e4, r2, i2) { - return n2.startInferenceSession(t3), n2.addOrtVersion(t3, e4), n2.addModel(t3, r2), n2.addSessionState(t3, i2), n2.endInferenceSession(t3); - } - } - e3.InferenceSession = n2; - }(e2.fbs || (e2.fbs = {})); - }(t2.experimental || (t2.experimental = {})); - }(e.onnxruntime || (e.onnxruntime = {})); - }, 7448: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.OnnxjsSessionHandler = void 0; - const r = n(1670), i = n(9162); - e.OnnxjsSessionHandler = class { - constructor(t2) { - this.session = t2, this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames; - } - async dispose() { - } - async run(t2, e2, n2) { - const o = /* @__PURE__ */ new Map(); - for (const e3 in t2) - if (Object.hasOwnProperty.call(t2, e3)) { - const n3 = t2[e3]; - o.set(e3, new i.Tensor(n3.dims, n3.type, void 0, void 0, n3.data)); - } - const a = await this.session.run(o), s = {}; - return a.forEach((t3, e3) => { - s[e3] = new r.Tensor(t3.type, t3.data, t3.dims); - }), s; - } - startProfiling() { - this.session.startProfiling(); - } - endProfiling() { - this.session.endProfiling(); - } - }; - }, 6919: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.Session = void 0; - const r = n(7067), i = n(1296), o = n(7091), a = n(1036), s = n(6231), u = n(2644); - e.Session = class { - constructor(t2 = {}) { - this._initialized = false, this.backendHint = t2.backendHint, this.profiler = s.Profiler.create(t2.profiler), this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] }; - } - get inputNames() { - return this._model.graph.getInputNames(); - } - get outputNames() { - return this._model.graph.getOutputNames(); - } - startProfiling() { - this.profiler.start(); - } - endProfiling() { - this.profiler.stop(); - } - async loadModel(t2, e2, n2) { - await this.profiler.event("session", "Session.loadModel", async () => { - const a2 = await (0, o.resolveBackend)(this.backendHint); - if (this.sessionHandler = a2.createSessionHandler(this.context), this._model = new u.Model(), "string" == typeof t2) { - const e3 = t2.endsWith(".ort"); - if ("undefined" == typeof fetch) { - const n3 = await (0, i.promisify)(r.readFile)(t2); - this.initialize(n3, e3); - } else { - const n3 = await fetch(t2), r2 = await n3.arrayBuffer(); - this.initialize(new Uint8Array(r2), e3); - } - } else if (ArrayBuffer.isView(t2)) - this.initialize(t2); - else { - const r2 = new Uint8Array(t2, e2 || 0, n2 || t2.byteLength); - this.initialize(r2); - } - }); - } - initialize(t2, e2) { - if (this._initialized) - throw new Error("already initialized"); - this.profiler.event("session", "Session.initialize", () => { - const n2 = this.sessionHandler.transformGraph ? this.sessionHandler : void 0; - this._model.load(t2, n2, e2), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new a.ExecutionPlan(this._model.graph, this._ops, this.profiler); - }), this._initialized = true; - } - async run(t2) { - if (!this._initialized) - throw new Error("session not initialized yet"); - return this.profiler.event("session", "Session.run", async () => { - const e2 = this.normalizeAndValidateInputs(t2), n2 = await this._executionPlan.execute(this.sessionHandler, e2); - return this.createOutput(n2); - }); - } - normalizeAndValidateInputs(t2) { - const e2 = this._model.graph.getInputNames(); - if (Array.isArray(t2)) { - if (t2.length !== e2.length) - throw new Error(`incorrect input array length: expected ${e2.length} but got ${t2.length}`); - } else { - if (t2.size !== e2.length) - throw new Error(`incorrect input map size: expected ${e2.length} but got ${t2.size}`); - const n2 = new Array(t2.size); - let r2 = 0; - for (let i2 = 0; i2 < e2.length; ++i2) { - const o2 = t2.get(e2[i2]); - if (!o2) - throw new Error(`missing input tensor for: '${name}'`); - n2[r2++] = o2; - } - t2 = n2; - } - if (this.context.graphInputTypes && 0 !== this.context.graphInputTypes.length && this.context.graphInputDims && 0 !== this.context.graphInputDims.length) - this.validateInputTensorDims(this.context.graphInputDims, t2, false); - else { - const e3 = this._model.graph.getInputIndices(), n2 = this._model.graph.getValues(), r2 = new Array(e3.length); - for (let i2 = 0; i2 < e3.length; ++i2) { - const o2 = n2[e3[i2]]; - r2[i2] = o2.type.shape.dims, this.context.graphInputTypes.push(o2.type.tensorType), this.context.graphInputDims.push(t2[i2].dims); - } - this.validateInputTensorDims(r2, t2, true); - } - return this.validateInputTensorTypes(this.context.graphInputTypes, t2), t2; - } - validateInputTensorTypes(t2, e2) { - for (let n2 = 0; n2 < e2.length; n2++) { - const r2 = t2[n2], i2 = e2[n2].type; - if (r2 !== i2) - throw new Error(`input tensor[${n2}] check failed: expected type '${r2}' but got ${i2}`); - } - } - validateInputTensorDims(t2, e2, n2) { - for (let r2 = 0; r2 < e2.length; r2++) { - const i2 = t2[r2], o2 = e2[r2].dims; - if (!this.compareTensorDims(i2, o2, n2)) - throw new Error(`input tensor[${r2}] check failed: expected shape '[${i2.join(",")}]' but got [${o2.join(",")}]`); - } - } - compareTensorDims(t2, e2, n2) { - if (t2.length !== e2.length) - return false; - for (let r2 = 0; r2 < t2.length; ++r2) - if (t2[r2] !== e2[r2] && (!n2 || 0 !== t2[r2])) - return false; - return true; - } - createOutput(t2) { - const e2 = this._model.graph.getOutputNames(); - if (t2.length !== e2.length) - throw new Error("expected number of outputs do not match number of generated outputs"); - const n2 = /* @__PURE__ */ new Map(); - for (let r2 = 0; r2 < e2.length; ++r2) - n2.set(e2[r2], t2[r2]); - return n2; - } - initializeOps(t2) { - const e2 = t2.getNodes(); - this._ops = new Array(e2.length); - for (let n2 = 0; n2 < e2.length; n2++) - this._ops[n2] = this.sessionHandler.resolve(e2[n2], this._model.opsets, t2); - } - }; - }, 9162: function(t, e, n) { - "use strict"; - var r = this && this.__importDefault || function(t2) { - return t2 && t2.__esModule ? t2 : { default: t2 }; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.Tensor = void 0; - const i = n(3442), o = r(n(3720)), a = n(1446), s = n(9395), u = n(2517); - var c = s.onnxruntime.experimental.fbs; - class l { - get data() { - if (void 0 === this.cache) { - const t2 = this.dataProvider(this.dataId); - if (t2.length !== this.size) - throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor."); - this.cache = t2; - } - return this.cache; - } - get stringData() { - if ("string" !== this.type) - throw new TypeError("data type is not string"); - return this.data; - } - get integerData() { - switch (this.type) { - case "uint8": - case "int8": - case "uint16": - case "int16": - case "int32": - case "uint32": - case "bool": - return this.data; - default: - throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)"); - } - } - get floatData() { - switch (this.type) { - case "float32": - case "float64": - return this.data; - default: - throw new TypeError("data type is not float (float32, float64)"); - } - } - get numberData() { - if ("string" !== this.type) - return this.data; - throw new TypeError("type cannot be non-number (string)"); - } - get(t2) { - return this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)]; - } - set(t2, e2) { - this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)] = e2; - } - async getData() { - return void 0 === this.cache && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache; - } - get strides() { - return this._strides || (this._strides = u.ShapeUtil.computeStrides(this.dims)), this._strides; - } - constructor(t2, e2, n2, r2, o2, a2 = i.Guid.create()) { - this.dims = t2, this.type = e2, this.dataProvider = n2, this.asyncDataProvider = r2, this.cache = o2, this.dataId = a2, this.size = u.ShapeUtil.validateDimsAndCalcSize(t2); - const s2 = this.size, c2 = void 0 === n2 && void 0 === r2 && void 0 === o2; - if (void 0 !== o2 && o2.length !== s2) - throw new RangeError("Input dims doesn't match data length."); - if ("string" === e2) { - if (!(void 0 === o2 || Array.isArray(o2) && o2.every((t3) => "string" == typeof t3))) - throw new TypeError("cache should be a string array"); - c2 && (this.cache = new Array(s2)); - } else { - if (void 0 !== o2) { - const t3 = f(e2); - if (!(o2 instanceof t3)) - throw new TypeError(`cache should be type ${t3.name}`); - } - if (c2) { - const t3 = new ArrayBuffer(s2 * function(t4) { - switch (t4) { - case "bool": - case "int8": - case "uint8": - return 1; - case "int16": - case "uint16": - return 2; - case "int32": - case "uint32": - case "float32": - return 4; - case "float64": - return 8; - default: - throw new Error(`cannot calculate sizeof() on type ${t4}`); - } - }(e2)); - this.cache = function(t4, e3) { - return new (f(e3))(t4); - }(t3, e2); - } - } - } - static fromProto(t2) { - if (!t2) - throw new Error("cannot construct Value from an empty tensor"); - const e2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType), n2 = u.ProtoUtil.tensorDimsFromProto(t2.dims), r2 = new l(n2, e2); - if ("string" === e2) - t2.stringData.forEach((t3, e3) => { - r2.data[e3] = (0, u.decodeUtf8String)(t3); - }); - else if (t2.rawData && "number" == typeof t2.rawData.byteLength && t2.rawData.byteLength > 0) { - const e3 = r2.data, n3 = new DataView(t2.rawData.buffer, t2.rawData.byteOffset, t2.rawData.byteLength), i2 = p(t2.dataType), o2 = t2.rawData.byteLength / i2; - if (t2.rawData.byteLength % i2 != 0) - throw new Error("invalid buffer length"); - if (e3.length !== o2) - throw new Error("buffer length mismatch"); - for (let r3 = 0; r3 < o2; r3++) { - const o3 = h(n3, t2.dataType, r3 * i2); - e3[r3] = o3; - } - } else { - let e3; - switch (t2.dataType) { - case a.onnx.TensorProto.DataType.FLOAT: - e3 = t2.floatData; - break; - case a.onnx.TensorProto.DataType.INT32: - case a.onnx.TensorProto.DataType.INT16: - case a.onnx.TensorProto.DataType.UINT16: - case a.onnx.TensorProto.DataType.INT8: - case a.onnx.TensorProto.DataType.UINT8: - case a.onnx.TensorProto.DataType.BOOL: - e3 = t2.int32Data; - break; - case a.onnx.TensorProto.DataType.INT64: - e3 = t2.int64Data; - break; - case a.onnx.TensorProto.DataType.DOUBLE: - e3 = t2.doubleData; - break; - case a.onnx.TensorProto.DataType.UINT32: - case a.onnx.TensorProto.DataType.UINT64: - e3 = t2.uint64Data; - break; - default: - throw new Error("unspecific error"); - } - if (null == e3) - throw new Error("failed to populate data from a tensorproto value"); - const n3 = r2.data; - if (n3.length !== e3.length) - throw new Error("array length mismatch"); - for (let r3 = 0; r3 < e3.length; r3++) { - const i2 = e3[r3]; - o.default.isLong(i2) ? n3[r3] = d(i2, t2.dataType) : n3[r3] = i2; - } - } - return r2; - } - static fromData(t2, e2, n2) { - return new l(e2, n2, void 0, void 0, t2); - } - static fromOrtTensor(t2) { - if (!t2) - throw new Error("cannot construct Value from an empty tensor"); - const e2 = u.ProtoUtil.tensorDimsFromORTFormat(t2), n2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType()), r2 = new l(e2, n2); - if ("string" === n2) - for (let e3 = 0; e3 < t2.stringDataLength(); e3++) - r2.data[e3] = t2.stringData(e3); - else if (t2.rawDataArray() && "number" == typeof t2.rawDataLength() && t2.rawDataLength() > 0) { - const e3 = r2.data, n3 = new DataView(t2.rawDataArray().buffer, t2.rawDataArray().byteOffset, t2.rawDataLength()), i2 = p(t2.dataType()), o2 = t2.rawDataLength() / i2; - if (t2.rawDataLength() % i2 != 0) - throw new Error("invalid buffer length"); - if (e3.length !== o2) - throw new Error("buffer length mismatch"); - for (let r3 = 0; r3 < o2; r3++) { - const o3 = h(n3, t2.dataType(), r3 * i2); - e3[r3] = o3; - } - } - return r2; - } - } - function p(t2) { - switch (t2) { - case a.onnx.TensorProto.DataType.UINT8: - case a.onnx.TensorProto.DataType.INT8: - case a.onnx.TensorProto.DataType.BOOL: - return 1; - case a.onnx.TensorProto.DataType.UINT16: - case a.onnx.TensorProto.DataType.INT16: - return 2; - case a.onnx.TensorProto.DataType.FLOAT: - case a.onnx.TensorProto.DataType.INT32: - case a.onnx.TensorProto.DataType.UINT32: - return 4; - case a.onnx.TensorProto.DataType.INT64: - case a.onnx.TensorProto.DataType.DOUBLE: - case a.onnx.TensorProto.DataType.UINT64: - return 8; - default: - throw new Error(`cannot calculate sizeof() on type ${a.onnx.TensorProto.DataType[t2]}`); - } - } - function f(t2) { - switch (t2) { - case "bool": - case "uint8": - return Uint8Array; - case "int8": - return Int8Array; - case "int16": - return Int16Array; - case "uint16": - return Uint16Array; - case "int32": - return Int32Array; - case "uint32": - return Uint32Array; - case "float32": - return Float32Array; - case "float64": - return Float64Array; - default: - throw new Error("unspecified error"); - } - } - function d(t2, e2) { - if (e2 === a.onnx.TensorProto.DataType.INT64 || e2 === c.TensorDataType.INT64) { - if (t2.greaterThanOrEqual(2147483648) || t2.lessThan(-2147483648)) - throw new TypeError("int64 is not supported"); - } else { - if (e2 !== a.onnx.TensorProto.DataType.UINT32 && e2 !== c.TensorDataType.UINT32 && e2 !== a.onnx.TensorProto.DataType.UINT64 && e2 !== c.TensorDataType.UINT64) - throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[e2]}`); - if (t2.greaterThanOrEqual(4294967296) || t2.lessThan(0)) - throw new TypeError("uint64 is not supported"); - } - return t2.toNumber(); - } - function h(t2, e2, n2) { - switch (e2) { - case a.onnx.TensorProto.DataType.BOOL: - case a.onnx.TensorProto.DataType.UINT8: - return t2.getUint8(n2); - case a.onnx.TensorProto.DataType.INT8: - return t2.getInt8(n2); - case a.onnx.TensorProto.DataType.UINT16: - return t2.getUint16(n2, true); - case a.onnx.TensorProto.DataType.INT16: - return t2.getInt16(n2, true); - case a.onnx.TensorProto.DataType.FLOAT: - return t2.getFloat32(n2, true); - case a.onnx.TensorProto.DataType.INT32: - return t2.getInt32(n2, true); - case a.onnx.TensorProto.DataType.UINT32: - return t2.getUint32(n2, true); - case a.onnx.TensorProto.DataType.INT64: - return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), false), e2); - case a.onnx.TensorProto.DataType.DOUBLE: - return t2.getFloat64(n2, true); - case a.onnx.TensorProto.DataType.UINT64: - return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), true), e2); - default: - throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[e2]}`); - } - } - e.Tensor = l; - }, 2517: function(t, e, n) { - "use strict"; - var r = this && this.__importDefault || function(t2) { - return t2 && t2.__esModule ? t2 : { default: t2 }; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.decodeUtf8String = e.MAX_CLIP = e.MIN_CLIP = e.PoolConvUtil = e.ReduceUtil = e.SplitUtil = e.MathUtil = e.ShapeUtil = e.LongUtil = e.ProtoUtil = e.GemmUtil = e.arrayCopyHelper = e.BroadcastUtil = e.MatMulUtil = e.ArrayUtil = e.assert = e.checkInputsShape = void 0; - const i = n(5686), o = r(n(3720)), a = n(1446), s = n(9162); - e.checkInputsShape = function(t2, ...e2) { - if (!t2 || t2.length !== e2.length) - return false; - for (let n2 = 0; n2 < t2.length; n2++) - if (!t2[n2].dims || t2[n2].dims.length !== e2[n2]) - return false; - return true; - }, e.assert = function(t2, e2) { - if (!t2) - throw new Error("string" == typeof e2 ? e2 : e2()); - }, e.ArrayUtil = class { - static arraysEqual(t2, e2) { - if (t2.length !== e2.length) - return false; - for (let n2 = 0; n2 < t2.length; n2++) - if (t2[n2] !== e2[n2]) - return false; - return true; - } - }; - class u { - static preprocessInputShapes(t2, e2) { - return [1 === t2.length ? [1, t2[0]] : t2, 1 === e2.length ? [e2[0], 1] : e2]; - } - static postprocessOutputShape(t2, e2, n2) { - 1 === e2 && t2.splice(t2.length - 2, 1), 1 === n2 && t2.pop(); - } - static calcMatMulShape(t2, e2) { - return t2[1] !== e2[0] ? void 0 : [t2[0], e2[1]]; - } - } - e.MatMulUtil = u; - class c { - static calcShape(t2, e2, n2 = false) { - const r2 = t2.length, i2 = e2.length; - if (0 === r2) - return e2; - if (0 === i2) - return t2; - const o2 = Math.max(t2.length, e2.length), a2 = new Array(o2); - if (n2) { - if (r2 < 2 || i2 < 2) - return; - const n3 = u.calcMatMulShape([t2[r2 - 2], t2[r2 - 1]], [e2[i2 - 2], e2[i2 - 1]]); - if (void 0 === n3) - return; - [a2[o2 - 2], a2[o2 - 1]] = n3; - } - for (let s2 = n2 ? 3 : 1; s2 <= o2; s2++) { - const n3 = r2 - s2 < 0 ? 1 : t2[r2 - s2], u2 = i2 - s2 < 0 ? 1 : e2[i2 - s2]; - if (n3 !== u2 && n3 > 1 && u2 > 1) - return; - a2[o2 - s2] = Math.max(n3, u2); - } - return a2; - } - static index(t2, e2) { - const n2 = new Array(e2.length); - return c.fillIndex(t2, e2, n2), n2; - } - static fillIndex(t2, e2, n2) { - const r2 = t2.length - e2.length; - for (let i2 = 0; i2 < e2.length; i2++) - n2[i2] = t2[r2 + i2] % e2[i2]; - } - static calc(t2, e2, n2, r2, i2) { - const o2 = c.calcShape(t2.dims, e2.dims); - if (o2) { - if (r2 && !f.areEqual(o2, t2.dims)) - return; - const a2 = f.size(o2), u2 = r2 ? t2 : new s.Tensor(o2, i2 || t2.type); - if (0 === o2.length) - u2.set([], n2(t2.get([]), e2.get([]))); - else { - const r3 = new Array(o2.length), i3 = new Array(t2.dims.length), s2 = new Array(e2.dims.length); - let l2, p2 = 0, f2 = 0, d2 = false, h2 = false; - 0 === t2.dims.length && (p2 = t2.get([]), d2 = true), 0 === e2.dims.length && (f2 = e2.get([]), h2 = true); - for (let g2 = 0; g2 < a2; g2++) { - l2 = g2; - for (let t3 = o2.length - 1; t3 >= 0; t3--) - r3[t3] = l2 % o2[t3], l2 = Math.floor(l2 / o2[t3]); - d2 || (c.fillIndex(r3, t2.dims, i3), p2 = t2.get(i3)), h2 || (c.fillIndex(r3, e2.dims, s2), f2 = e2.get(s2)), u2.set(r3, n2(p2, f2)); - } - } - return u2; - } - } - static isValidBroadcast(t2, e2) { - const n2 = t2.length, r2 = e2.length; - if (n2 > r2) - return false; - for (let i2 = 1; i2 <= n2; i2++) - if (1 !== t2[n2 - i2] && t2[n2 - i2] !== e2[r2 - i2]) - return false; - return true; - } - static getBroadcastDims(t2, e2) { - const n2 = t2.length, r2 = []; - for (let i2 = 0; i2 < n2; i2++) { - const o2 = n2 - 1 - i2, a2 = t2[o2] || 1; - (e2[e2.length - 1 - i2] || 1) > 1 && 1 === a2 && r2.unshift(o2); - } - return r2; - } - } - e.BroadcastUtil = c, e.arrayCopyHelper = function(t2, e2, n2, r2, i2) { - if (r2 < 0 || r2 >= e2.length) - throw new Error("sourceIndex out of bounds"); - if (n2 < 0 || n2 >= t2.length) - throw new Error("targetIndex out of bounds"); - if (r2 + i2 > e2.length) - throw new Error("source indices to be copied are outside bounds"); - if (n2 + i2 > t2.length) - throw new Error("target array is too small to hold result"); - for (let o2 = 0; o2 < i2; o2++) - t2[n2 + o2] = e2[r2 + o2]; - }, e.GemmUtil = class { - static getShapeOfGemmResult(t2, e2, n2, r2, i2) { - if (2 !== t2.length || 2 !== n2.length) - throw new Error("shape need to be of size 2"); - let o2, a2, s2; - e2 ? (o2 = t2[1], a2 = t2[0]) : (o2 = t2[0], a2 = t2[1]); - let u2 = -1; - if (r2 ? (s2 = n2[0], u2 = 1) : (s2 = n2[1], u2 = 0), n2[u2] !== a2) - throw new Error("dimension mismatch"); - if (o2 <= 0 || s2 <= 0 || a2 <= 0) - throw new Error("invalid shape specified"); - if (i2 && !c.isValidBroadcast(i2, [o2, s2])) - throw new Error("gemm: invalid bias shape for broadcast"); - return [o2, s2, a2]; - } - }; - class l { - static tensorDataTypeFromProto(t2) { - switch (t2) { - case a.onnx.TensorProto.DataType.INT8: - return "int8"; - case a.onnx.TensorProto.DataType.UINT8: - return "uint8"; - case a.onnx.TensorProto.DataType.BOOL: - return "bool"; - case a.onnx.TensorProto.DataType.INT16: - return "int16"; - case a.onnx.TensorProto.DataType.UINT16: - return "uint16"; - case a.onnx.TensorProto.DataType.INT32: - return "int32"; - case a.onnx.TensorProto.DataType.UINT32: - return "uint32"; - case a.onnx.TensorProto.DataType.FLOAT: - return "float32"; - case a.onnx.TensorProto.DataType.DOUBLE: - return "float64"; - case a.onnx.TensorProto.DataType.STRING: - return "string"; - case a.onnx.TensorProto.DataType.INT64: - return "int32"; - case a.onnx.TensorProto.DataType.UINT64: - return "uint32"; - default: - throw new Error(`unsupported data type: ${a.onnx.TensorProto.DataType[t2]}`); - } - } - static tensorDataTypeStringToEnum(t2) { - switch (t2) { - case "int8": - return a.onnx.TensorProto.DataType.INT8; - case "uint8": - return a.onnx.TensorProto.DataType.UINT8; - case "bool": - return a.onnx.TensorProto.DataType.BOOL; - case "int16": - return a.onnx.TensorProto.DataType.INT16; - case "uint16": - return a.onnx.TensorProto.DataType.UINT16; - case "int32": - return a.onnx.TensorProto.DataType.INT32; - case "uint32": - return a.onnx.TensorProto.DataType.UINT32; - case "float32": - return a.onnx.TensorProto.DataType.FLOAT; - case "float64": - return a.onnx.TensorProto.DataType.DOUBLE; - case "string": - return a.onnx.TensorProto.DataType.STRING; - case "int64": - return a.onnx.TensorProto.DataType.INT64; - case "uint64": - return a.onnx.TensorProto.DataType.UINT64; - default: - throw new Error(`unsupported data type: ${t2}`); - } - } - static tensorDimsFromProto(t2) { - return t2.map((t3) => o.default.isLong(t3) ? t3.toNumber() : t3); - } - static tensorValueTypeFromProto(t2) { - return { tensorType: l.tensorDataTypeFromProto(t2.elemType), shape: { dims: l.tensorDimsFromProto(t2.shape.dim.map((t3) => t3.dimValue)) } }; - } - static tensorDimsFromORTFormat(t2) { - const e2 = []; - for (let n2 = 0; n2 < t2.dimsLength(); n2++) - e2.push(p.longToNumber(t2.dims(n2))); - return e2; - } - static tensorAttributesFromORTFormat(t2) { - const e2 = []; - for (let n2 = 0; n2 < t2.attributesLength(); n2++) - e2.push(t2.attributes(n2)); - return e2; - } - } - e.ProtoUtil = l; - class p { - static longToNumber(t2, e2) { - return o.default.isLong(t2) ? t2.toNumber() : t2 instanceof i.flatbuffers.Long ? o.default.fromValue({ low: t2.low, high: t2.high, unsigned: null != e2 && e2 }).toNumber() : t2; - } - static isLong(t2) { - return o.default.isLong(t2) || t2 instanceof i.flatbuffers.Long; - } - } - e.LongUtil = p; - class f { - static size(t2) { - return f.getSizeFromDimensionRange(t2, 0, t2.length); - } - static sizeFromDimension(t2, e2) { - if (e2 < 0 || e2 > t2.length) - throw new Error(`invalid dimension of ${e2} for sizeFromDimension as Tensor has ${t2.length} dimensions.`); - return f.getSizeFromDimensionRange(t2, e2, t2.length); - } - static sizeToDimension(t2, e2) { - if (e2 < 0 || e2 > t2.length) - throw new Error(`invalid dimension of ${e2} for sizeToDimension as Tensor has ${t2.length} dimensions.`); - return f.getSizeFromDimensionRange(t2, 0, e2); - } - static getSizeFromDimensionRange(t2, e2, n2) { - let r2 = 1; - for (let i2 = e2; i2 < n2; i2++) { - if (t2[i2] <= 0) - throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them."); - r2 *= t2[i2]; - } - return r2; - } - static computeStrides(t2) { - const e2 = t2.length; - if (0 === e2) - return []; - if (1 === e2) - return [1]; - const n2 = new Array(e2); - n2[e2 - 1] = 1, n2[e2 - 2] = t2[e2 - 1]; - for (let r2 = e2 - 3; r2 >= 0; --r2) - n2[r2] = n2[r2 + 1] * t2[r2 + 1]; - return n2; - } - static transpose(t2) { - return t2.slice().reverse(); - } - static indicesToOffset(t2, e2, n2) { - void 0 === n2 && (n2 = t2.length); - let r2 = 0; - for (let i2 = 0; i2 < n2; ++i2) - r2 += e2[i2] * t2[i2]; - return r2; - } - static offsetToIndices(t2, e2) { - const n2 = e2.length; - if (0 === n2) - return []; - if (1 === n2) - return [t2 * e2[0]]; - const r2 = new Array(e2.length); - for (let n3 = 0; n3 < r2.length - 1; ++n3) - r2[n3] = Math.floor(t2 / e2[n3]), t2 -= r2[n3] * e2[n3]; - return r2[r2.length - 1] = t2, r2; - } - static normalizeAxis(t2, e2) { - if (t2 < -e2 && t2 >= e2) - throw new Error("unsupported axis for this operation."); - return t2 < 0 ? t2 + e2 : t2; - } - static normalizeAxes(t2, e2) { - return t2.map((t3) => this.normalizeAxis(t3, e2)); - } - static incrementIndex(t2, e2, n2) { - if (0 === e2.length || 0 === t2.length) - throw new Error("Index incrementing unsupported for scalar Tensor"); - if (void 0 === n2) - n2 = e2.length; - else if (n2 <= 0 || n2 > e2.length) - throw new Error("Incorrect axis to increment on"); - for (let r2 = n2 - 1; r2 >= 0 && (t2[r2]++, !(t2[r2] < e2[r2])); --r2) - t2[r2] = 0; - } - static calculateReshapedDims(t2, e2) { - if (0 === e2.length) { - if (0 === t2.length || 1 === f.size(t2)) - return []; - throw new Error("cannot reshape to a scalar Tensor"); - } - const n2 = e2.length, r2 = new Array(n2); - let i2 = -1, o2 = 1; - for (let a3 = 0; a3 < n2; a3++) { - if (e2[a3] < -1) - throw new Error("a dimension in shape hints cannot be less than -1"); - if (-1 === e2[a3]) { - if (-1 !== i2) - throw new Error("at most one dimension in shape hints can be -1"); - i2 = a3; - } else { - if (0 === e2[a3]) { - if (a3 >= t2.length) - throw new Error("the dimension with value zero exceeds the dimension size of the input tensor"); - r2[a3] = t2[a3]; - } else - r2[a3] = e2[a3]; - o2 *= r2[a3]; - } - } - const a2 = f.size(t2); - if (-1 !== i2) { - if (a2 % o2 != 0) - throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t2}] Output shape: [${e2}]`); - r2[i2] = a2 / o2; - } else if (o2 !== a2) - throw new Error("reshapedDims and originalDims don't have matching sizes"); - return r2; - } - static sortBasedOnPerm(t2, e2) { - return e2 ? e2.map((e3) => t2[e3]) : t2.slice().reverse(); - } - static padShape(t2, e2) { - const n2 = t2.length; - return t2.map((t3, r2) => t3 + e2[r2] + e2[r2 + n2]); - } - static areEqual(t2, e2) { - return t2.length === e2.length && t2.every((t3, n2) => t3 === e2[n2]); - } - static validateDimsAndCalcSize(t2) { - if (t2.length > 6) - throw new TypeError("Only rank 0 to 6 is supported for tensor shape."); - let e2 = 1; - for (const n2 of t2) { - if (!Number.isInteger(n2)) - throw new TypeError(`Invalid shape: ${n2} is not an integer`); - if (n2 < 0 || n2 > 2147483647) - throw new TypeError(`Invalid shape: length ${n2} is not allowed`); - e2 *= n2; - } - return e2; - } - static flattenShape(t2, e2) { - e2 < 0 && (e2 += t2.length); - const n2 = t2.reduce((t3, e3) => t3 * e3, 1), r2 = t2.slice(e2).reduce((t3, e3) => t3 * e3, 1); - return [n2 / r2, r2]; - } - static squeezeShape(t2, e2) { - const n2 = new Array(); - e2 = f.normalizeAxes(e2, t2.length); - for (let r2 = 0; r2 < t2.length; r2++) { - const i2 = e2.indexOf(r2) >= 0; - if (i2 && 1 !== t2[r2]) - throw new Error("squeeze an axis of size different than 1"); - (0 === e2.length && t2[r2] > 1 || e2.length > 0 && !i2) && n2.push(t2[r2]); - } - return n2; - } - static unsqueezeShape(t2, e2) { - const n2 = new Array(t2.length + e2.length); - n2.fill(0); - for (let t3 = 0; t3 < e2.length; t3++) { - const r3 = f.normalizeAxis(e2[t3], n2.length); - if (r3 >= n2.length) - throw new Error("'axes' has an out of range axis"); - if (0 !== n2[r3]) - throw new Error("'axes' has a duplicate axis"); - n2[r3] = 1; - } - let r2 = 0; - for (let e3 = 0; e3 < n2.length; e3++) - 0 === n2[e3] && (n2[e3] = t2[r2++]); - if (r2 !== t2.length) - throw new Error("the unsqueezed dimension could not be established"); - return n2; - } - } - e.ShapeUtil = f, e.MathUtil = class { - static sqr(t2, e2, n2, r2, i2) { - if (r2 < 0 || r2 >= e2.length) - throw new Error("sourceIndex out of bounds"); - if (n2 < 0 || n2 >= t2.length) - throw new Error("targetIndex out of bounds"); - if (r2 + i2 > e2.length) - throw new Error("source indices to be copied are outside bounds"); - if (n2 + i2 > t2.length) - throw new Error("target array is too small to hold result"); - for (let o2 = 0; o2 < i2; o2++) - t2[n2 + o2] += Math.pow(e2[r2 + o2], 2); - } - static axpy(t2, e2, n2, r2, i2, o2) { - if (r2 < 0 || r2 >= e2.length) - throw new Error("sourceIndex out of bounds"); - if (n2 < 0 || n2 >= t2.length) - throw new Error("targetIndex out of bounds"); - if (r2 + i2 > e2.length) - throw new Error("source indices to be copied are outside bounds"); - if (n2 + i2 > t2.length) - throw new Error("target array is too small to hold result"); - for (let a2 = 0; a2 < i2; a2++) - t2[n2 + a2] += o2 * e2[r2 + a2]; - } - static powx(t2, e2, n2, r2, i2, o2) { - if (r2 < 0 || r2 >= e2.length) - throw new Error("sourceIndex out of bounds"); - if (n2 < 0 || n2 >= t2.length) - throw new Error("targetIndex out of bounds"); - if (r2 + i2 > e2.length) - throw new Error("source indices to be copied are outside bounds"); - if (n2 + i2 > t2.length) - throw new Error("target array is too small to hold result"); - for (let a2 = 0; a2 < i2; a2++) - t2[n2 + a2] = Math.pow(e2[r2 + a2], o2); - } - static mul(t2, e2, n2, r2, i2) { - if (r2 < 0 || r2 >= e2.length) - throw new Error("sourceIndex out of bounds"); - if (n2 < 0 || n2 >= t2.length) - throw new Error("targetIndex out of bounds"); - if (r2 + i2 > e2.length) - throw new Error("source indices to be copied are outside bounds"); - if (n2 + i2 > t2.length) - throw new Error("target array is too small to hold result"); - for (let o2 = 0; o2 < i2; o2++) - t2[n2 + o2] = e2[r2 + o2] * t2[n2 + o2]; - } - }; - class d { - static splitShape(t2, e2, n2, r2) { - if (0 === n2.length) { - if (!r2) - throw new Error("need to know number of outputs when the 'split' attribute is not specified"); - d.determineSplit(t2[e2], r2, n2); - } - const i2 = [], o2 = [0]; - for (let r3 = 0; r3 < n2.length; ++r3) { - 0 !== r3 && o2.push(o2[r3 - 1] + n2[r3 - 1]); - const a2 = t2.slice(); - a2[e2] = n2[r3], i2.push(a2); - } - return [i2, o2]; - } - static determineSplit(t2, e2, n2) { - if (t2 % e2 != 0) - throw new Error("cannot split tensor to equal sized parts"); - for (let r2 = 0; r2 < e2; ++r2) - n2.push(t2 / e2); - } - } - e.SplitUtil = d; - class h { - static calcReduce(t2, e2, n2, r2, i2) { - const o2 = t2.dims.slice(0); - 0 === e2.length && o2.forEach((t3, n3) => e2.push(n3)); - const a2 = h.calcReduceShape(o2, e2, true), u2 = f.size(a2), l2 = new s.Tensor(a2, t2.type), p2 = f.computeStrides(a2), d2 = f.computeStrides(o2), g2 = new Array(o2.length); - for (let n3 = 0; n3 < u2; n3++) { - const a3 = f.offsetToIndices(n3, p2); - c.fillIndex(a3, o2, g2), l2.set(a3, h.calcReduceByAxis(t2.numberData, e2, o2, 0, f.indicesToOffset(g2, d2), r2, i2)); - } - return n2 ? l2 : new s.Tensor(h.calcReduceShape(o2, e2, n2), l2.type, void 0, void 0, l2.data, l2.dataId); - } - static calcReduceByAxis(t2, e2, n2, r2, i2, o2, a2) { - let s2 = 0; - if (r2 >= e2.length) - return o2(t2[i2]); - const u2 = e2[r2], c2 = u2 >= n2.length ? 1 : f.size(n2.slice(u2 + 1)); - for (let l2 = 0; l2 < n2[u2]; l2++) - s2 = 0 === l2 ? h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2) : a2(s2, h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2)), i2 += c2; - return s2; - } - static calcReduceShape(t2, e2, n2) { - const r2 = t2.slice(); - for (let t3 = 0; t3 < e2.length; t3++) - r2[e2[t3]] = n2 ? 1 : 0; - return r2.filter((t3) => 0 !== t3); - } - } - e.ReduceUtil = h; - class g { - static adjustPoolAttributes(t2, e2, n2, r2, i2, o2) { - if (!t2 && n2.length !== e2.length - 2) - throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); - if (t2) - for (let t3 = 0; t3 < e2.length - 2; t3++) - t3 >= n2.length ? n2.push(e2[t3 + 2]) : n2[t3] = e2[t3 + 2]; - for (let t3 = 0; t3 < n2.length; t3++) - if (t3 < r2.length) { - if (r2[t3] < 0) - throw new Error("strides should be greater than or equal to 1"); - } else - r2.push(1); - for (let t3 = 0; t3 < n2.length; t3++) - if (t3 < i2.length) { - if (i2[t3] < 0) - throw new Error("dilations should be greater than or equal to 1"); - } else - i2.push(1); - for (let t3 = 0; t3 < 2 * n2.length; t3++) - if (t3 < o2.length) { - if (o2[t3] < 0) - throw new Error("pad should be greater than or equal to 1"); - } else - o2.push(0); - for (let t3 = 0; t3 < n2.length; t3++) { - if (n2[t3] <= 0) - throw new Error("kernel shapes need to be greater than 0"); - if (o2[t3] >= n2[t3] || o2[t3 + n2.length] >= n2[t3]) - throw new Error("pads should be smaller than kernel"); - } - } - static adjustPadsBasedOnAutoPad(t2, e2, n2, r2, i2, o2) { - if (o2) { - if (i2.length !== 2 * (t2.length - 2)) - throw new Error("length of pads should be twice the length of data dimensions"); - if (e2.length !== t2.length - 2) - throw new Error("length of strides should be the length of data dimensions"); - if (r2.length !== t2.length - 2) - throw new Error("length of kernel shapes should be the length of data dimensions"); - for (let a2 = 0; a2 < t2.length - 2; a2++) - g.adjustPadAndReturnShape(t2[a2 + 2], e2[a2], n2[a2], r2[a2], i2, a2, a2 + t2.length - 2, o2); - } - } - static computePoolOutputShape(t2, e2, n2, r2, i2, o2, a2) { - if (e2.length <= 0) - throw new Error("input shape must be of size greater than 0"); - const s2 = [e2[0], e2[1]]; - return g.computeShapeHelper(t2, e2, s2, n2, r2, i2, o2, a2), s2; - } - static computeConvOutputShape(t2, e2, n2, r2, i2, o2, a2) { - if (t2.length <= 0 || e2.length <= 0) - throw new Error("invalid input tensor dims or invalid filter tensor dims"); - const s2 = [t2[0], e2[0]]; - return g.computeShapeHelper(false, t2, s2, n2, r2, i2, o2, a2), s2; - } - static computeShapeHelper(t2, e2, n2, r2, i2, o2, a2, s2) { - if (t2) - for (let t3 = 0; t3 < e2.length - 2; t3++) - n2.push(1); - else - for (let t3 = 0; t3 < e2.length - 2; t3++) - n2.push(g.adjustPadAndReturnShape(e2[t3 + 2], r2[t3], i2[t3], o2[t3], a2, t3, t3 + e2.length - 2, s2)); - } - static adjustPadAndReturnShape(t2, e2, n2, r2, i2, o2, a2, s2) { - const u2 = n2 * (r2 - 1) + 1; - if (!s2 || "NOTSET" === s2) - return Math.floor((t2 + i2[o2] + i2[a2] - u2) / e2 + 1); - switch (s2) { - case "VALID": - return i2[o2] = 0, i2[a2] = 0, Math.floor((t2 - u2) / e2 + 1); - case "SAME_LOWER": - case "SAME_UPPER": - if (1 !== n2) - throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); - { - const n3 = ((t2 + e2 - 1) / e2 - 1) * e2 + r2 - t2; - return i2[o2] = "SAME_LOWER" === s2 ? Math.floor((n3 + 1) / 2) : Math.floor(n3 / 2), i2[a2] = n3 - i2[o2], Math.floor((t2 + n3 - r2) / e2 + 1); - } - default: - throw new Error("Unsupported AutoPad type"); - } - } - } - e.PoolConvUtil = g, e.MIN_CLIP = -34028234663852886e22, e.MAX_CLIP = 34028234663852886e22, e.decodeUtf8String = function(t2) { - return new TextDecoder().decode(t2); - }; - }, 7967: (t, e) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.iterateExtraOptions = void 0, e.iterateExtraOptions = (t2, n, r, i) => { - if ("object" == typeof t2 && null !== t2) { - if (r.has(t2)) - throw new Error("Circular reference in options"); - r.add(t2); - } - Object.entries(t2).forEach(([t3, o]) => { - const a = n ? n + t3 : t3; - if ("object" == typeof o) - (0, e.iterateExtraOptions)(o, a + ".", r, i); - else if ("string" == typeof o || "number" == typeof o) - i(a, o.toString()); - else { - if ("boolean" != typeof o) - throw new Error("Can't handle extra config type: " + typeof o); - i(a, o ? "1" : "0"); - } - }); - }; - }, 2157: function(t, e, n) { - "use strict"; - var r, i = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2); - var i2 = Object.getOwnPropertyDescriptor(e2, n2); - i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { - return e2[n2]; - } }), Object.defineProperty(t2, r2, i2); - } : function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; - }), o = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { - Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); - } : function(t2, e2) { - t2.default = e2; - }), a = this && this.__importStar || function(t2) { - if (t2 && t2.__esModule) - return t2; - var e2 = {}; - if (null != t2) - for (var n2 in t2) - "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && i(e2, t2, n2); - return o(e2, t2), e2; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = e.initWasm = void 0; - const s = n(1670), u = a(n(349)), c = n(6361), l = () => !!s.env.wasm.proxy && "undefined" != typeof document; - let p, f, d, h = false, g = false, b = false; - const m = [], y = [], _ = [], v = [], w = [], x = [], T = () => { - if (h || !g || b || !p) - throw new Error("worker not ready"); - }, S = (t2) => { - switch (t2.data.type) { - case "init-wasm": - h = false, t2.data.err ? (b = true, f[1](t2.data.err)) : (g = true, f[0]()); - break; - case "init-ort": - t2.data.err ? d[1](t2.data.err) : d[0](); - break; - case "create_allocate": - t2.data.err ? m.shift()[1](t2.data.err) : m.shift()[0](t2.data.out); - break; - case "create_finalize": - t2.data.err ? y.shift()[1](t2.data.err) : y.shift()[0](t2.data.out); - break; - case "create": - t2.data.err ? _.shift()[1](t2.data.err) : _.shift()[0](t2.data.out); - break; - case "release": - t2.data.err ? v.shift()[1](t2.data.err) : v.shift()[0](); - break; - case "run": - t2.data.err ? w.shift()[1](t2.data.err) : w.shift()[0](t2.data.out); - break; - case "end-profiling": - t2.data.err ? x.shift()[1](t2.data.err) : x.shift()[0](); - } - }, O = "undefined" != typeof document ? null === (r = null === document || void 0 === document ? void 0 : document.currentScript) || void 0 === r ? void 0 : r.src : void 0; - e.initWasm = async () => { - if (l()) { - if (g) - return; - if (h) - throw new Error("multiple calls to 'initWasm()' detected."); - if (b) - throw new Error("previous call to 'initWasm()' failed."); - return h = true, void 0 === s.env.wasm.wasmPaths && O && 0 !== O.indexOf("blob:") && (s.env.wasm.wasmPaths = O.substr(0, +O.lastIndexOf("/") + 1)), new Promise((t2, e2) => { - null == p || p.terminate(), p = n(9710).Z(), p.onmessage = S, f = [t2, e2]; - const r2 = { type: "init-wasm", in: s.env.wasm }; - p.postMessage(r2); - }); - } - return (0, c.initializeWebAssembly)(s.env.wasm); - }, e.initOrt = async (t2, e2) => { - if (l()) - return T(), new Promise((n2, r2) => { - d = [n2, r2]; - const i2 = { type: "init-ort", in: { numThreads: t2, loggingLevel: e2 } }; - p.postMessage(i2); - }); - u.initOrt(t2, e2); - }, e.createSessionAllocate = async (t2) => l() ? (T(), new Promise((e2, n2) => { - m.push([e2, n2]); - const r2 = { type: "create_allocate", in: { model: t2 } }; - p.postMessage(r2, [t2.buffer]); - })) : u.createSessionAllocate(t2), e.createSessionFinalize = async (t2, e2) => l() ? (T(), new Promise((n2, r2) => { - y.push([n2, r2]); - const i2 = { type: "create_finalize", in: { modeldata: t2, options: e2 } }; - p.postMessage(i2); - })) : u.createSessionFinalize(t2, e2), e.createSession = async (t2, e2) => l() ? (T(), new Promise((n2, r2) => { - _.push([n2, r2]); - const i2 = { type: "create", in: { model: t2, options: e2 } }; - p.postMessage(i2, [t2.buffer]); - })) : u.createSession(t2, e2), e.releaseSession = async (t2) => { - if (l()) - return T(), new Promise((e2, n2) => { - v.push([e2, n2]); - const r2 = { type: "release", in: t2 }; - p.postMessage(r2); - }); - u.releaseSession(t2); - }, e.run = async (t2, e2, n2, r2, i2) => l() ? (T(), new Promise((o2, a2) => { - w.push([o2, a2]); - const s2 = { type: "run", in: { sessionId: t2, inputIndices: e2, inputs: n2, outputIndices: r2, options: i2 } }; - p.postMessage(s2, u.extractTransferableBuffers(n2)); - })) : u.run(t2, e2, n2, r2, i2), e.endProfiling = async (t2) => { - if (l()) - return T(), new Promise((e2, n2) => { - x.push([e2, n2]); - const r2 = { type: "end-profiling", in: t2 }; - p.postMessage(r2); - }); - u.endProfiling(t2); - }; - }, 586: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.setRunOptions = void 0; - const r = n(7967), i = n(4983), o = n(6361); - e.setRunOptions = (t2) => { - const e2 = (0, o.getInstance)(); - let n2 = 0; - const a = [], s = t2 || {}; - try { - if (void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) - s.logSeverityLevel = 2; - else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) - throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`); - if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) - s.logVerbosityLevel = 0; - else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) - throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`); - void 0 === (null == t2 ? void 0 : t2.terminate) && (s.terminate = false); - let o2 = 0; - if (void 0 !== (null == t2 ? void 0 : t2.tag) && (o2 = (0, i.allocWasmString)(t2.tag, a)), n2 = e2._OrtCreateRunOptions(s.logSeverityLevel, s.logVerbosityLevel, !!s.terminate, o2), 0 === n2) - throw new Error("Can't create run options"); - return void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), (t3, r2) => { - const o3 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a); - if (0 !== e2._OrtAddRunConfigEntry(n2, o3, s2)) - throw new Error(`Can't set a run config entry: ${t3} - ${r2}`); - }), [n2, a]; - } catch (t3) { - throw 0 !== n2 && e2._OrtReleaseRunOptions(n2), a.forEach(e2._free), t3; - } - }; - }, 2306: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.OnnxruntimeWebAssemblySessionHandler = void 0; - const r = n(2806), i = n(1670), o = n(2850), a = n(2157); - let s; - e.OnnxruntimeWebAssemblySessionHandler = class { - async createSessionAllocate(t2) { - const e2 = await fetch(t2), n2 = await e2.arrayBuffer(); - return (0, a.createSessionAllocate)(new Uint8Array(n2)); - } - async loadModel(t2, e2) { - if (s || (await (0, a.initOrt)(i.env.wasm.numThreads, ((t3) => { - switch (t3) { - case "verbose": - return 0; - case "info": - return 1; - case "warning": - return 2; - case "error": - return 3; - case "fatal": - return 4; - default: - throw new Error(`unsupported logging level: ${t3}`); - } - })(i.env.logLevel)), s = true), "string" == typeof t2) - if ("undefined" == typeof fetch) { - const n2 = await (0, o.promisify)(r.readFile)(t2); - [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(n2, e2); - } else { - const n2 = await this.createSessionAllocate(t2); - [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSessionFinalize)(n2, e2); - } - else - [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(t2, e2); - } - async dispose() { - return (0, a.releaseSession)(this.sessionId); - } - async run(t2, e2, n2) { - const r2 = [], o2 = []; - Object.entries(t2).forEach((t3) => { - const e3 = t3[0], n3 = t3[1], i2 = this.inputNames.indexOf(e3); - if (-1 === i2) - throw new Error(`invalid input '${e3}'`); - r2.push(n3), o2.push(i2); - }); - const s2 = []; - Object.entries(e2).forEach((t3) => { - const e3 = t3[0], n3 = this.outputNames.indexOf(e3); - if (-1 === n3) - throw new Error(`invalid output '${e3}'`); - s2.push(n3); - }); - const u = await (0, a.run)(this.sessionId, o2, r2.map((t3) => [t3.type, t3.dims, t3.data]), s2, n2), c = {}; - for (let t3 = 0; t3 < u.length; t3++) - c[this.outputNames[s2[t3]]] = new i.Tensor(u[t3][0], u[t3][2], u[t3][1]); - return c; - } - startProfiling() { - } - endProfiling() { - (0, a.endProfiling)(this.sessionId); - } - }; - }, 4919: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.setSessionOptions = void 0; - const r = n(7967), i = n(4983), o = n(6361); - e.setSessionOptions = (t2) => { - const e2 = (0, o.getInstance)(); - let n2 = 0; - const a = [], s = t2 || {}; - ((t3) => { - t3.extra || (t3.extra = {}), t3.extra.session || (t3.extra.session = {}); - const e3 = t3.extra.session; - e3.use_ort_model_bytes_directly || (e3.use_ort_model_bytes_directly = "1"); - })(s); - try { - void 0 === (null == t2 ? void 0 : t2.graphOptimizationLevel) && (s.graphOptimizationLevel = "all"); - const u = ((t3) => { - switch (t3) { - case "disabled": - return 0; - case "basic": - return 1; - case "extended": - return 2; - case "all": - return 99; - default: - throw new Error(`unsupported graph optimization level: ${t3}`); - } - })(s.graphOptimizationLevel); - void 0 === (null == t2 ? void 0 : t2.enableCpuMemArena) && (s.enableCpuMemArena = true), void 0 === (null == t2 ? void 0 : t2.enableMemPattern) && (s.enableMemPattern = true), void 0 === (null == t2 ? void 0 : t2.executionMode) && (s.executionMode = "sequential"); - const c = ((t3) => { - switch (t3) { - case "sequential": - return 0; - case "parallel": - return 1; - default: - throw new Error(`unsupported execution mode: ${t3}`); - } - })(s.executionMode); - let l = 0; - if (void 0 !== (null == t2 ? void 0 : t2.logId) && (l = (0, i.allocWasmString)(t2.logId, a)), void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) - s.logSeverityLevel = 2; - else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) - throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`); - if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) - s.logVerbosityLevel = 0; - else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) - throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`); - if (void 0 === (null == t2 ? void 0 : t2.enableProfiling) && (s.enableProfiling = false), n2 = e2._OrtCreateSessionOptions(u, !!s.enableCpuMemArena, !!s.enableMemPattern, c, !!s.enableProfiling, 0, l, s.logSeverityLevel, s.logVerbosityLevel), 0 === n2) - throw new Error("Can't create session options"); - return (null == t2 ? void 0 : t2.executionProviders) && ((t3, e3, n3) => { - for (const r2 of e3) { - let e4 = "string" == typeof r2 ? r2 : r2.name; - switch (e4) { - case "xnnpack": - e4 = "XNNPACK"; - break; - case "wasm": - case "cpu": - continue; - default: - throw new Error(`not supported EP: ${e4}`); - } - const a2 = (0, i.allocWasmString)(e4, n3); - if (0 !== (0, o.getInstance)()._OrtAppendExecutionProvider(t3, a2)) - throw new Error(`Can't append execution provider: ${e4}`); - } - })(n2, t2.executionProviders, a), void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), (t3, r2) => { - const o2 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a); - if (0 !== e2._OrtAddSessionConfigEntry(n2, o2, s2)) - throw new Error(`Can't set a session config entry: ${t3} - ${r2}`); - }), [n2, a]; - } catch (t3) { - throw 0 !== n2 && e2._OrtReleaseSessionOptions(n2), a.forEach(e2._free), t3; - } - }; - }, 4983: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.allocWasmString = void 0; - const r = n(6361); - e.allocWasmString = (t2, e2) => { - const n2 = (0, r.getInstance)(), i = n2.lengthBytesUTF8(t2) + 1, o = n2._malloc(i); - return n2.stringToUTF8(t2, o, i), e2.push(o), o; - }; - }, 349: (t, e, n) => { - "use strict"; - Object.defineProperty(e, "__esModule", { value: true }), e.extractTransferableBuffers = e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = void 0; - const r = n(586), i = n(4919), o = n(4983), a = n(6361); - e.initOrt = (t2, e2) => { - const n2 = (0, a.getInstance)()._OrtInit(t2, e2); - if (0 !== n2) - throw new Error(`Can't initialize onnxruntime. error code = ${n2}`); - }; - const s = /* @__PURE__ */ new Map(); - e.createSessionAllocate = (t2) => { - const e2 = (0, a.getInstance)(), n2 = e2._malloc(t2.byteLength); - return e2.HEAPU8.set(t2, n2), [n2, t2.byteLength]; - }, e.createSessionFinalize = (t2, e2) => { - const n2 = (0, a.getInstance)(); - let r2 = 0, o2 = 0, u2 = []; - try { - if ([o2, u2] = (0, i.setSessionOptions)(e2), r2 = n2._OrtCreateSession(t2[0], t2[1], o2), 0 === r2) - throw new Error("Can't create a session"); - } finally { - n2._free(t2[0]), n2._OrtReleaseSessionOptions(o2), u2.forEach(n2._free); - } - const c2 = n2._OrtGetInputCount(r2), l2 = n2._OrtGetOutputCount(r2), p = [], f = [], d = [], h = []; - for (let t3 = 0; t3 < c2; t3++) { - const e3 = n2._OrtGetInputName(r2, t3); - if (0 === e3) - throw new Error("Can't get an input name"); - f.push(e3), p.push(n2.UTF8ToString(e3)); - } - for (let t3 = 0; t3 < l2; t3++) { - const e3 = n2._OrtGetOutputName(r2, t3); - if (0 === e3) - throw new Error("Can't get an output name"); - h.push(e3), d.push(n2.UTF8ToString(e3)); - } - return s.set(r2, [r2, f, h]), [r2, p, d]; - }, e.createSession = (t2, n2) => { - const r2 = (0, e.createSessionAllocate)(t2); - return (0, e.createSessionFinalize)(r2, n2); - }, e.releaseSession = (t2) => { - const e2 = (0, a.getInstance)(), n2 = s.get(t2); - if (!n2) - throw new Error("invalid session id"); - const r2 = n2[0], i2 = n2[1], o2 = n2[2]; - i2.forEach(e2._OrtFree), o2.forEach(e2._OrtFree), e2._OrtReleaseSession(r2), s.delete(t2); - }; - const u = (t2) => { - switch (t2) { - case "int8": - return 3; - case "uint8": - return 2; - case "bool": - return 9; - case "int16": - return 5; - case "uint16": - return 4; - case "int32": - return 6; - case "uint32": - return 12; - case "float32": - return 1; - case "float64": - return 11; - case "string": - return 8; - case "int64": - return 7; - case "uint64": - return 13; - default: - throw new Error(`unsupported data type: ${t2}`); - } - }, c = (t2) => { - switch (t2) { - case 3: - return "int8"; - case 2: - return "uint8"; - case 9: - return "bool"; - case 5: - return "int16"; - case 4: - return "uint16"; - case 6: - return "int32"; - case 12: - return "uint32"; - case 1: - return "float32"; - case 11: - return "float64"; - case 8: - return "string"; - case 7: - return "int64"; - case 13: - return "uint64"; - default: - throw new Error(`unsupported data type: ${t2}`); - } - }, l = (t2) => { - switch (t2) { - case "float32": - return Float32Array; - case "uint8": - case "bool": - return Uint8Array; - case "int8": - return Int8Array; - case "uint16": - return Uint16Array; - case "int16": - return Int16Array; - case "int32": - return Int32Array; - case "float64": - return Float64Array; - case "uint32": - return Uint32Array; - case "int64": - return BigInt64Array; - case "uint64": - return BigUint64Array; - default: - throw new Error(`unsupported type: ${t2}`); - } - }; - e.run = (t2, e2, n2, i2, p) => { - const f = (0, a.getInstance)(), d = s.get(t2); - if (!d) - throw new Error("invalid session id"); - const h = d[0], g = d[1], b = d[2], m = e2.length, y = i2.length; - let _ = 0, v = []; - const w = [], x = []; - try { - [_, v] = (0, r.setRunOptions)(p); - for (let t4 = 0; t4 < m; t4++) { - const e3 = n2[t4][0], r2 = n2[t4][1], i3 = n2[t4][2]; - let a3, s3; - if (Array.isArray(i3)) { - s3 = 4 * i3.length, a3 = f._malloc(s3), x.push(a3); - let t5 = a3 / 4; - for (let e4 = 0; e4 < i3.length; e4++) { - if ("string" != typeof i3[e4]) - throw new TypeError(`tensor data at index ${e4} is not a string`); - f.HEAPU32[t5++] = (0, o.allocWasmString)(i3[e4], x); - } - } else - s3 = i3.byteLength, a3 = f._malloc(s3), x.push(a3), f.HEAPU8.set(new Uint8Array(i3.buffer, i3.byteOffset, s3), a3); - const c2 = f.stackSave(), l2 = f.stackAlloc(4 * r2.length); - try { - let t5 = l2 / 4; - r2.forEach((e4) => f.HEAP32[t5++] = e4); - const n3 = f._OrtCreateTensor(u(e3), a3, s3, l2, r2.length); - if (0 === n3) - throw new Error("Can't create a tensor"); - w.push(n3); - } finally { - f.stackRestore(c2); - } - } - const t3 = f.stackSave(), a2 = f.stackAlloc(4 * m), s2 = f.stackAlloc(4 * m), d2 = f.stackAlloc(4 * y), T = f.stackAlloc(4 * y); - try { - let n3 = a2 / 4, r2 = s2 / 4, o2 = d2 / 4, u2 = T / 4; - for (let t4 = 0; t4 < m; t4++) - f.HEAPU32[n3++] = w[t4], f.HEAPU32[r2++] = g[e2[t4]]; - for (let t4 = 0; t4 < y; t4++) - f.HEAPU32[o2++] = 0, f.HEAPU32[u2++] = b[i2[t4]]; - let p2 = f._OrtRun(h, s2, a2, m, T, y, d2, _); - const v2 = []; - if (0 === p2) - for (let t4 = 0; t4 < y; t4++) { - const e3 = f.HEAPU32[d2 / 4 + t4], n4 = f.stackSave(), r3 = f.stackAlloc(16); - let i3, o3 = 0; - try { - if (p2 = f._OrtGetTensorData(e3, r3, r3 + 4, r3 + 8, r3 + 12), 0 !== p2) - throw new Error(`Can't access output tensor data. error code = ${p2}`); - let t5 = r3 / 4; - const a3 = f.HEAPU32[t5++]; - o3 = f.HEAPU32[t5++]; - const s3 = f.HEAPU32[t5++], u3 = f.HEAPU32[t5++], d3 = []; - for (let t6 = 0; t6 < u3; t6++) - d3.push(f.HEAPU32[s3 / 4 + t6]); - f._OrtFree(s3); - const h2 = 0 === d3.length ? 1 : d3.reduce((t6, e4) => t6 * e4); - if (i3 = c(a3), "string" === i3) { - const t6 = []; - let e4 = o3 / 4; - for (let n5 = 0; n5 < h2; n5++) { - const r4 = f.HEAPU32[e4++], i4 = n5 === h2 - 1 ? void 0 : f.HEAPU32[e4] - r4; - t6.push(f.UTF8ToString(r4, i4)); - } - v2.push([i3, d3, t6]); - } else { - const t6 = new (l(i3))(h2); - new Uint8Array(t6.buffer, t6.byteOffset, t6.byteLength).set(f.HEAPU8.subarray(o3, o3 + t6.byteLength)), v2.push([i3, d3, t6]); - } - } finally { - f.stackRestore(n4), "string" === i3 && o3 && f._free(o3), f._OrtReleaseTensor(e3); - } - } - if (0 === p2) - return v2; - throw new Error(`failed to call OrtRun(). error code = ${p2}.`); - } finally { - f.stackRestore(t3); - } - } finally { - w.forEach(f._OrtReleaseTensor), x.forEach(f._free), f._OrtReleaseRunOptions(_), v.forEach(f._free); - } - }, e.endProfiling = (t2) => { - const e2 = (0, a.getInstance)(), n2 = s.get(t2); - if (!n2) - throw new Error("invalid session id"); - const r2 = n2[0], i2 = e2._OrtEndProfiling(r2); - if (0 === i2) - throw new Error("Can't get an profile file name"); - e2._OrtFree(i2); - }, e.extractTransferableBuffers = (t2) => { - const e2 = []; - for (const n2 of t2) { - const t3 = n2[2]; - !Array.isArray(t3) && t3.buffer && e2.push(t3.buffer); - } - return e2; - }; - }, 6361: function(t, e, n) { - "use strict"; - var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2); - var i2 = Object.getOwnPropertyDescriptor(e2, n2); - i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { - return e2[n2]; - } }), Object.defineProperty(t2, r2, i2); - } : function(t2, e2, n2, r2) { - void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; - }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { - Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); - } : function(t2, e2) { - t2.default = e2; - }), o = this && this.__importStar || function(t2) { - if (t2 && t2.__esModule) - return t2; - var e2 = {}; - if (null != t2) - for (var n2 in t2) - "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); - return i(e2, t2), e2; - }, a = this && this.__importDefault || function(t2) { - return t2 && t2.__esModule ? t2 : { default: t2 }; - }; - Object.defineProperty(e, "__esModule", { value: true }), e.dispose = e.getInstance = e.initializeWebAssembly = void 0; - const s = o(n(6449)), u = a(n(932)), c = n(3474); - let l, p = false, f = false, d = false; - const h = (t2, e2) => e2 ? t2 ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-threaded.wasm" : t2 ? "ort-wasm-simd.wasm" : "ort-wasm.wasm"; - e.initializeWebAssembly = async (t2) => { - if (p) - return Promise.resolve(); - if (f) - throw new Error("multiple calls to 'initializeWebAssembly()' detected."); - if (d) - throw new Error("previous call to 'initializeWebAssembly()' failed."); - f = true; - const e2 = t2.initTimeout, r2 = t2.numThreads, i2 = t2.simd, o2 = r2 > 1 && (() => { - try { - return "undefined" != typeof SharedArrayBuffer && ("undefined" != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]))); - } catch (t3) { - return false; - } - })(), a2 = i2 && (() => { - try { - return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11])); - } catch (t3) { - return false; - } - })(), g = "string" == typeof t2.wasmPaths ? t2.wasmPaths : void 0, b = h(false, o2), m = h(a2, o2), y = "object" == typeof t2.wasmPaths ? t2.wasmPaths[m] : void 0; - let _ = false; - const v = []; - if (e2 > 0 && v.push(new Promise((t3) => { - setTimeout(() => { - _ = true, t3(); - }, e2); - })), v.push(new Promise((t3, e3) => { - const r3 = o2 ? c : u.default, i3 = { locateFile: (t4, e4) => o2 && t4.endsWith(".worker.js") && "undefined" != typeof Blob ? URL.createObjectURL(new Blob([n(4154)], { type: "text/javascript" })) : t4 === b ? null != y ? y : (null != g ? g : e4) + m : e4 + t4 }; - if (o2) - if ("undefined" == typeof Blob) - i3.mainScriptUrlOrBlob = s.join("/", "ort-wasm-threaded.js"); - else { - const t4 = `var ortWasmThreaded=(function(){var _scriptDir;return ${r3.toString()}})();`; - i3.mainScriptUrlOrBlob = new Blob([t4], { type: "text/javascript" }); - } - r3(i3).then((e4) => { - f = false, p = true, l = e4, t3(); - }, (t4) => { - f = false, d = true, e3(t4); - }); - })), await Promise.race(v), _) - throw new Error(`WebAssembly backend initializing failed due to timeout: ${e2}ms`); - }, e.getInstance = () => { - if (p && l) - return l; - throw new Error("WebAssembly is not initialized yet."); - }, e.dispose = () => { - var t2; - !p || f || d || (f = true, null === (t2 = l.PThread) || void 0 === t2 || t2.terminateAllThreads(), l = void 0, f = false, p = false, d = true); - }; - }, 9710: (t, e, n) => { - "use strict"; - n.d(e, { Z: () => o }); - var r = n(477), i = n.n(r); - function o() { - return i()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n', "Worker", void 0, void 0); - } - }, 477: (t) => { - "use strict"; - t.exports = function(t2, e, n, r) { - var i = self || window; - try { - try { - var o; - try { - o = new i.Blob([t2]); - } catch (e2) { - (o = new (i.BlobBuilder || i.WebKitBlobBuilder || i.MozBlobBuilder || i.MSBlobBuilder)()).append(t2), o = o.getBlob(); - } - var a = i.URL || i.webkitURL, s = a.createObjectURL(o), u = new i[e](s, n); - return a.revokeObjectURL(s), u; - } catch (r2) { - return new i[e]("data:application/javascript,".concat(encodeURIComponent(t2)), n); - } - } catch (t3) { - if (!r) - throw Error("Inline worker is not supported"); - return new i[e](r, n); - } - }; - }, 4154: (t) => { - "use strict"; - t.exports = '"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'; - }, 1670: (t) => { - "use strict"; - t.exports = __WEBPACK_EXTERNAL_MODULE__1670__; - }, 7067: () => { - }, 1296: () => { - }, 1384: () => { - }, 3993: () => { - }, 908: () => { - }, 6953: () => { - }, 9925: () => { - }, 2806: () => { - }, 6449: () => { - }, 2850: () => { - }, 5381: () => { - }, 5686: (t, e, n) => { - "use strict"; - n.r(e), n.d(e, { flatbuffers: () => r }); - var r = {}; - r.Offset, r.Table, r.SIZEOF_SHORT = 2, r.SIZEOF_INT = 4, r.FILE_IDENTIFIER_LENGTH = 4, r.SIZE_PREFIX_LENGTH = 4, r.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }, r.int32 = new Int32Array(2), r.float32 = new Float32Array(r.int32.buffer), r.float64 = new Float64Array(r.int32.buffer), r.isLittleEndian = 1 === new Uint16Array(new Uint8Array([1, 0]).buffer)[0], r.Long = function(t2, e2) { - this.low = 0 | t2, this.high = 0 | e2; - }, r.Long.create = function(t2, e2) { - return 0 == t2 && 0 == e2 ? r.Long.ZERO : new r.Long(t2, e2); - }, r.Long.prototype.toFloat64 = function() { - return (this.low >>> 0) + 4294967296 * this.high; - }, r.Long.prototype.equals = function(t2) { - return this.low == t2.low && this.high == t2.high; - }, r.Long.ZERO = new r.Long(0, 0), r.Builder = function(t2) { - if (t2) - e2 = t2; - else - var e2 = 1024; - this.bb = r.ByteBuffer.allocate(e2), this.space = e2, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; - }, r.Builder.prototype.clear = function() { - this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; - }, r.Builder.prototype.forceDefaults = function(t2) { - this.force_defaults = t2; - }, r.Builder.prototype.dataBuffer = function() { - return this.bb; - }, r.Builder.prototype.asUint8Array = function() { - return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); - }, r.Builder.prototype.prep = function(t2, e2) { - t2 > this.minalign && (this.minalign = t2); - for (var n2 = 1 + ~(this.bb.capacity() - this.space + e2) & t2 - 1; this.space < n2 + t2 + e2; ) { - var i = this.bb.capacity(); - this.bb = r.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - i; - } - this.pad(n2); - }, r.Builder.prototype.pad = function(t2) { - for (var e2 = 0; e2 < t2; e2++) - this.bb.writeInt8(--this.space, 0); - }, r.Builder.prototype.writeInt8 = function(t2) { - this.bb.writeInt8(this.space -= 1, t2); - }, r.Builder.prototype.writeInt16 = function(t2) { - this.bb.writeInt16(this.space -= 2, t2); - }, r.Builder.prototype.writeInt32 = function(t2) { - this.bb.writeInt32(this.space -= 4, t2); - }, r.Builder.prototype.writeInt64 = function(t2) { - this.bb.writeInt64(this.space -= 8, t2); - }, r.Builder.prototype.writeFloat32 = function(t2) { - this.bb.writeFloat32(this.space -= 4, t2); - }, r.Builder.prototype.writeFloat64 = function(t2) { - this.bb.writeFloat64(this.space -= 8, t2); - }, r.Builder.prototype.addInt8 = function(t2) { - this.prep(1, 0), this.writeInt8(t2); - }, r.Builder.prototype.addInt16 = function(t2) { - this.prep(2, 0), this.writeInt16(t2); - }, r.Builder.prototype.addInt32 = function(t2) { - this.prep(4, 0), this.writeInt32(t2); - }, r.Builder.prototype.addInt64 = function(t2) { - this.prep(8, 0), this.writeInt64(t2); - }, r.Builder.prototype.addFloat32 = function(t2) { - this.prep(4, 0), this.writeFloat32(t2); - }, r.Builder.prototype.addFloat64 = function(t2) { - this.prep(8, 0), this.writeFloat64(t2); - }, r.Builder.prototype.addFieldInt8 = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addInt8(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldInt16 = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addInt16(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldInt32 = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addInt32(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldInt64 = function(t2, e2, n2) { - !this.force_defaults && e2.equals(n2) || (this.addInt64(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldFloat32 = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addFloat32(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldFloat64 = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addFloat64(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldOffset = function(t2, e2, n2) { - (this.force_defaults || e2 != n2) && (this.addOffset(e2), this.slot(t2)); - }, r.Builder.prototype.addFieldStruct = function(t2, e2, n2) { - e2 != n2 && (this.nested(e2), this.slot(t2)); - }, r.Builder.prototype.nested = function(t2) { - if (t2 != this.offset()) - throw new Error("FlatBuffers: struct must be serialized inline."); - }, r.Builder.prototype.notNested = function() { - if (this.isNested) - throw new Error("FlatBuffers: object serialization must not be nested."); - }, r.Builder.prototype.slot = function(t2) { - this.vtable[t2] = this.offset(); - }, r.Builder.prototype.offset = function() { - return this.bb.capacity() - this.space; - }, r.Builder.growByteBuffer = function(t2) { - var e2 = t2.capacity(); - if (3221225472 & e2) - throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); - var n2 = e2 << 1, i = r.ByteBuffer.allocate(n2); - return i.setPosition(n2 - e2), i.bytes().set(t2.bytes(), n2 - e2), i; - }, r.Builder.prototype.addOffset = function(t2) { - this.prep(r.SIZEOF_INT, 0), this.writeInt32(this.offset() - t2 + r.SIZEOF_INT); - }, r.Builder.prototype.startObject = function(t2) { - this.notNested(), null == this.vtable && (this.vtable = []), this.vtable_in_use = t2; - for (var e2 = 0; e2 < t2; e2++) - this.vtable[e2] = 0; - this.isNested = true, this.object_start = this.offset(); - }, r.Builder.prototype.endObject = function() { - if (null == this.vtable || !this.isNested) - throw new Error("FlatBuffers: endObject called without startObject"); - this.addInt32(0); - for (var t2 = this.offset(), e2 = this.vtable_in_use - 1; e2 >= 0 && 0 == this.vtable[e2]; e2--) - ; - for (var n2 = e2 + 1; e2 >= 0; e2--) - this.addInt16(0 != this.vtable[e2] ? t2 - this.vtable[e2] : 0); - this.addInt16(t2 - this.object_start); - var i = (n2 + 2) * r.SIZEOF_SHORT; - this.addInt16(i); - var o = 0, a = this.space; - t: - for (e2 = 0; e2 < this.vtables.length; e2++) { - var s = this.bb.capacity() - this.vtables[e2]; - if (i == this.bb.readInt16(s)) { - for (var u = r.SIZEOF_SHORT; u < i; u += r.SIZEOF_SHORT) - if (this.bb.readInt16(a + u) != this.bb.readInt16(s + u)) - continue t; - o = this.vtables[e2]; - break; - } - } - return o ? (this.space = this.bb.capacity() - t2, this.bb.writeInt32(this.space, o - t2)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - t2, this.offset() - t2)), this.isNested = false, t2; - }, r.Builder.prototype.finish = function(t2, e2, n2) { - var i = n2 ? r.SIZE_PREFIX_LENGTH : 0; - if (e2) { - var o = e2; - if (this.prep(this.minalign, r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH + i), o.length != r.FILE_IDENTIFIER_LENGTH) - throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH); - for (var a = r.FILE_IDENTIFIER_LENGTH - 1; a >= 0; a--) - this.writeInt8(o.charCodeAt(a)); - } - this.prep(this.minalign, r.SIZEOF_INT + i), this.addOffset(t2), i && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space); - }, r.Builder.prototype.finishSizePrefixed = function(t2, e2) { - this.finish(t2, e2, true); - }, r.Builder.prototype.requiredField = function(t2, e2) { - var n2 = this.bb.capacity() - t2, r2 = n2 - this.bb.readInt32(n2); - if (0 == this.bb.readInt16(r2 + e2)) - throw new Error("FlatBuffers: field " + e2 + " must be set"); - }, r.Builder.prototype.startVector = function(t2, e2, n2) { - this.notNested(), this.vector_num_elems = e2, this.prep(r.SIZEOF_INT, t2 * e2), this.prep(n2, t2 * e2); - }, r.Builder.prototype.endVector = function() { - return this.writeInt32(this.vector_num_elems), this.offset(); - }, r.Builder.prototype.createString = function(t2) { - if (t2 instanceof Uint8Array) - var e2 = t2; - else { - e2 = []; - for (var n2 = 0; n2 < t2.length; ) { - var r2, i = t2.charCodeAt(n2++); - (r2 = i < 55296 || i >= 56320 ? i : (i << 10) + t2.charCodeAt(n2++) + -56613888) < 128 ? e2.push(r2) : (r2 < 2048 ? e2.push(r2 >> 6 & 31 | 192) : (r2 < 65536 ? e2.push(r2 >> 12 & 15 | 224) : e2.push(r2 >> 18 & 7 | 240, r2 >> 12 & 63 | 128), e2.push(r2 >> 6 & 63 | 128)), e2.push(63 & r2 | 128)); - } - } - this.addInt8(0), this.startVector(1, e2.length, 1), this.bb.setPosition(this.space -= e2.length), n2 = 0; - for (var o = this.space, a = this.bb.bytes(); n2 < e2.length; n2++) - a[o++] = e2[n2]; - return this.endVector(); - }, r.Builder.prototype.createLong = function(t2, e2) { - return r.Long.create(t2, e2); - }, r.ByteBuffer = function(t2) { - this.bytes_ = t2, this.position_ = 0; - }, r.ByteBuffer.allocate = function(t2) { - return new r.ByteBuffer(new Uint8Array(t2)); - }, r.ByteBuffer.prototype.clear = function() { - this.position_ = 0; - }, r.ByteBuffer.prototype.bytes = function() { - return this.bytes_; - }, r.ByteBuffer.prototype.position = function() { - return this.position_; - }, r.ByteBuffer.prototype.setPosition = function(t2) { - this.position_ = t2; - }, r.ByteBuffer.prototype.capacity = function() { - return this.bytes_.length; - }, r.ByteBuffer.prototype.readInt8 = function(t2) { - return this.readUint8(t2) << 24 >> 24; - }, r.ByteBuffer.prototype.readUint8 = function(t2) { - return this.bytes_[t2]; - }, r.ByteBuffer.prototype.readInt16 = function(t2) { - return this.readUint16(t2) << 16 >> 16; - }, r.ByteBuffer.prototype.readUint16 = function(t2) { - return this.bytes_[t2] | this.bytes_[t2 + 1] << 8; - }, r.ByteBuffer.prototype.readInt32 = function(t2) { - return this.bytes_[t2] | this.bytes_[t2 + 1] << 8 | this.bytes_[t2 + 2] << 16 | this.bytes_[t2 + 3] << 24; - }, r.ByteBuffer.prototype.readUint32 = function(t2) { - return this.readInt32(t2) >>> 0; - }, r.ByteBuffer.prototype.readInt64 = function(t2) { - return new r.Long(this.readInt32(t2), this.readInt32(t2 + 4)); - }, r.ByteBuffer.prototype.readUint64 = function(t2) { - return new r.Long(this.readUint32(t2), this.readUint32(t2 + 4)); - }, r.ByteBuffer.prototype.readFloat32 = function(t2) { - return r.int32[0] = this.readInt32(t2), r.float32[0]; - }, r.ByteBuffer.prototype.readFloat64 = function(t2) { - return r.int32[r.isLittleEndian ? 0 : 1] = this.readInt32(t2), r.int32[r.isLittleEndian ? 1 : 0] = this.readInt32(t2 + 4), r.float64[0]; - }, r.ByteBuffer.prototype.writeInt8 = function(t2, e2) { - this.bytes_[t2] = e2; - }, r.ByteBuffer.prototype.writeUint8 = function(t2, e2) { - this.bytes_[t2] = e2; - }, r.ByteBuffer.prototype.writeInt16 = function(t2, e2) { - this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8; - }, r.ByteBuffer.prototype.writeUint16 = function(t2, e2) { - this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8; - }, r.ByteBuffer.prototype.writeInt32 = function(t2, e2) { - this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24; - }, r.ByteBuffer.prototype.writeUint32 = function(t2, e2) { - this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24; - }, r.ByteBuffer.prototype.writeInt64 = function(t2, e2) { - this.writeInt32(t2, e2.low), this.writeInt32(t2 + 4, e2.high); - }, r.ByteBuffer.prototype.writeUint64 = function(t2, e2) { - this.writeUint32(t2, e2.low), this.writeUint32(t2 + 4, e2.high); - }, r.ByteBuffer.prototype.writeFloat32 = function(t2, e2) { - r.float32[0] = e2, this.writeInt32(t2, r.int32[0]); - }, r.ByteBuffer.prototype.writeFloat64 = function(t2, e2) { - r.float64[0] = e2, this.writeInt32(t2, r.int32[r.isLittleEndian ? 0 : 1]), this.writeInt32(t2 + 4, r.int32[r.isLittleEndian ? 1 : 0]); - }, r.ByteBuffer.prototype.getBufferIdentifier = function() { - if (this.bytes_.length < this.position_ + r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH) - throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier."); - for (var t2 = "", e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) - t2 += String.fromCharCode(this.readInt8(this.position_ + r.SIZEOF_INT + e2)); - return t2; - }, r.ByteBuffer.prototype.__offset = function(t2, e2) { - var n2 = t2 - this.readInt32(t2); - return e2 < this.readInt16(n2) ? this.readInt16(n2 + e2) : 0; - }, r.ByteBuffer.prototype.__union = function(t2, e2) { - return t2.bb_pos = e2 + this.readInt32(e2), t2.bb = this, t2; - }, r.ByteBuffer.prototype.__string = function(t2, e2) { - t2 += this.readInt32(t2); - var n2 = this.readInt32(t2), i = "", o = 0; - if (t2 += r.SIZEOF_INT, e2 === r.Encoding.UTF8_BYTES) - return this.bytes_.subarray(t2, t2 + n2); - for (; o < n2; ) { - var a, s = this.readUint8(t2 + o++); - if (s < 192) - a = s; - else { - var u = this.readUint8(t2 + o++); - if (s < 224) - a = (31 & s) << 6 | 63 & u; - else { - var c = this.readUint8(t2 + o++); - a = s < 240 ? (15 & s) << 12 | (63 & u) << 6 | 63 & c : (7 & s) << 18 | (63 & u) << 12 | (63 & c) << 6 | 63 & this.readUint8(t2 + o++); - } - } - a < 65536 ? i += String.fromCharCode(a) : (a -= 65536, i += String.fromCharCode(55296 + (a >> 10), 56320 + (1023 & a))); - } - return i; - }, r.ByteBuffer.prototype.__indirect = function(t2) { - return t2 + this.readInt32(t2); - }, r.ByteBuffer.prototype.__vector = function(t2) { - return t2 + this.readInt32(t2) + r.SIZEOF_INT; - }, r.ByteBuffer.prototype.__vector_len = function(t2) { - return this.readInt32(t2 + this.readInt32(t2)); - }, r.ByteBuffer.prototype.__has_identifier = function(t2) { - if (t2.length != r.FILE_IDENTIFIER_LENGTH) - throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH); - for (var e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) - if (t2.charCodeAt(e2) != this.readInt8(this.position_ + r.SIZEOF_INT + e2)) - return false; - return true; - }, r.ByteBuffer.prototype.createLong = function(t2, e2) { - return r.Long.create(t2, e2); - }; - } }, __webpack_module_cache__ = {}; - function __webpack_require__(t) { - var e = __webpack_module_cache__[t]; - if (void 0 !== e) - return e.exports; - var n = __webpack_module_cache__[t] = { exports: {} }; - return __webpack_modules__[t].call(n.exports, n, n.exports, __webpack_require__), n.exports; - } - __webpack_require__.n = (t) => { - var e = t && t.__esModule ? () => t.default : () => t; - return __webpack_require__.d(e, { a: e }), e; - }, __webpack_require__.d = (t, e) => { - for (var n in e) - __webpack_require__.o(e, n) && !__webpack_require__.o(t, n) && Object.defineProperty(t, n, { enumerable: true, get: e[n] }); - }, __webpack_require__.g = function() { - if ("object" == typeof globalThis) - return globalThis; - try { - return this || new Function("return this")(); - } catch (t) { - if ("object" == typeof window) - return window; - } - }(), __webpack_require__.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), __webpack_require__.r = (t) => { - "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: true }); - }; - var __webpack_exports__ = __webpack_require__(6018); - return __webpack_exports__; - })()); - } - }); - - // (disabled):node_modules/sharp/lib/index.js - var require_lib = __commonJS({ - "(disabled):node_modules/sharp/lib/index.js"() { - } - }); - - // node_modules/@xenova/transformers/src/utils/core.js - function dispatchCallback(progress_callback, data) { - if (progress_callback) - progress_callback(data); - } - function reverseDictionary(data) { - return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); - } - function escapeRegExp(string) { - return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - } - var Callable = ( - /** @type {any} */ - class { - /** - * Creates a new instance of the Callable class. - */ - constructor() { - let closure = function(...args) { - return closure._call(...args); - }; - return Object.setPrototypeOf(closure, new.target.prototype); - } - /** - * This method should be implemented in subclasses to provide the - * functionality of the callable object. - * - * @param {any[]} args - * @throws {Error} If the subclass does not implement the `_call` method. - */ - _call(...args) { - throw Error("Must implement _call method in subclass"); - } - } - ); - function isTypedArray(val) { - return val?.prototype?.__proto__?.constructor?.name === "TypedArray"; - } - function isIntegralNumber(x) { - return Number.isInteger(x) || typeof x === "bigint"; - } - function exists(x) { - return x !== void 0 && x !== null; - } - function calculateDimensions(arr) { - const dimensions = []; - let current = arr; - while (Array.isArray(current)) { - dimensions.push(current.length); - current = current[0]; - } - return dimensions; - } - function pop(obj, key, defaultValue = void 0) { - const value = obj[key]; - if (value !== void 0) { - delete obj[key]; - return value; - } - if (defaultValue === void 0) { - throw Error(`Key ${key} does not exist in object.`); - } - return defaultValue; - } - function mergeArrays(...arrs) { - return Array.prototype.concat.apply([], arrs); - } - function product(...a) { - return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e]))); - } - function calculateReflectOffset(i, w) { - return Math.abs((i + w) % (2 * w) - w); - } - - // node_modules/@xenova/transformers/src/utils/hub.js - var import_fs2 = __toESM(require_fs(), 1); - var import_path2 = __toESM(require_path(), 1); - var import_web = __toESM(require_web(), 1); - - // node_modules/@xenova/transformers/src/env.js - var import_fs = __toESM(require_fs(), 1); - var import_path = __toESM(require_path(), 1); - var import_url = __toESM(require_url(), 1); - - // node_modules/@xenova/transformers/src/backends/onnx.js - var ONNX_NODE = __toESM(require_dist(), 1); - var ONNX_WEB = __toESM(require_ort_web_min(), 1); - var ONNX; - var executionProviders = [ - // 'webgpu', - "wasm" - ]; - if (typeof process !== "undefined" && process?.release?.name === "node") { - ONNX = ONNX_NODE.default ?? ONNX_NODE; - executionProviders.unshift("cpu"); - } else { - ONNX = ONNX_WEB.default ?? ONNX_WEB; - const isIOS = typeof navigator !== "undefined" && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent); - if (isIOS) { - ONNX.env.wasm.simd = false; - } - } - - // node_modules/@xenova/transformers/src/env.js - var import_meta = {}; - var { env: onnx_env } = ONNX; - var VERSION = "2.13.4"; - var WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self; - var FS_AVAILABLE = !isEmpty(import_fs.default); - var PATH_AVAILABLE = !isEmpty(import_path.default); - var RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE; - var __dirname = RUNNING_LOCALLY ? import_path.default.dirname(import_path.default.dirname(import_url.default.fileURLToPath(import_meta.url))) : "./"; - var DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/.cache/") : null; - var DEFAULT_LOCAL_MODEL_PATH = "/models/"; - var localModelPath = RUNNING_LOCALLY ? import_path.default.join(__dirname, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH; - onnx_env.wasm.wasmPaths = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/dist/") : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`; - var env = { - /////////////////// Backends settings /////////////////// - backends: { - // onnxruntime-web/onnxruntime-node - onnx: onnx_env, - // TensorFlow.js - tfjs: {} - }, - __dirname, - version: VERSION, - /////////////////// Model settings /////////////////// - allowRemoteModels: true, - remoteHost: "https://huggingface.co/", - remotePathTemplate: "{model}/resolve/{revision}/", - allowLocalModels: true, - localModelPath, - useFS: FS_AVAILABLE, - /////////////////// Cache settings /////////////////// - useBrowserCache: WEB_CACHE_AVAILABLE, - useFSCache: FS_AVAILABLE, - cacheDir: DEFAULT_CACHE_DIR, - useCustomCache: false, - customCache: null - ////////////////////////////////////////////////////// - }; - function isEmpty(obj) { - return Object.keys(obj).length === 0; - } - - // node_modules/@xenova/transformers/src/utils/hub.js - if (!globalThis.ReadableStream) { - globalThis.ReadableStream = import_web.default.ReadableStream; - } - var FileResponse = class _FileResponse { - /** - * Mapping from file extensions to MIME types. - */ - _CONTENT_TYPE_MAP = { - "txt": "text/plain", - "html": "text/html", - "css": "text/css", - "js": "text/javascript", - "json": "application/json", - "png": "image/png", - "jpg": "image/jpeg", - "jpeg": "image/jpeg", - "gif": "image/gif" - }; - /** - * Creates a new `FileResponse` object. - * @param {string|URL} filePath - */ - constructor(filePath) { - this.filePath = filePath; - this.headers = new Headers(); - this.exists = import_fs2.default.existsSync(filePath); - if (this.exists) { - this.status = 200; - this.statusText = "OK"; - let stats = import_fs2.default.statSync(filePath); - this.headers.set("content-length", stats.size.toString()); - this.updateContentType(); - let self2 = this; - this.body = new ReadableStream({ - start(controller) { - self2.arrayBuffer().then((buffer) => { - controller.enqueue(new Uint8Array(buffer)); - controller.close(); - }); - } - }); - } else { - this.status = 404; - this.statusText = "Not Found"; - this.body = null; - } - } - /** - * Updates the 'content-type' header property of the response based on the extension of - * the file specified by the filePath property of the current object. - * @returns {void} - */ - updateContentType() { - const extension = this.filePath.toString().split(".").pop().toLowerCase(); - this.headers.set("content-type", this._CONTENT_TYPE_MAP[extension] ?? "application/octet-stream"); - } - /** - * Clone the current FileResponse object. - * @returns {FileResponse} A new FileResponse object with the same properties as the current object. - */ - clone() { - let response = new _FileResponse(this.filePath); - response.exists = this.exists; - response.status = this.status; - response.statusText = this.statusText; - response.headers = new Headers(this.headers); - return response; - } - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with an ArrayBuffer containing the file's contents. - * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async arrayBuffer() { - const data = await import_fs2.default.promises.readFile(this.filePath); - return data.buffer; - } - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a Blob containing the file's contents. - * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async blob() { - const data = await import_fs2.default.promises.readFile(this.filePath); - return new Blob([data], { type: this.headers.get("content-type") }); - } - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a string containing the file's contents. - * @returns {Promise} A Promise that resolves with a string containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async text() { - const data = await import_fs2.default.promises.readFile(this.filePath, "utf8"); - return data; - } - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a parsed JavaScript object containing the file's contents. - * - * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async json() { - return JSON.parse(await this.text()); - } - }; - function isValidHttpUrl(string, validHosts = null) { - let url2; - try { - url2 = new URL(string); - } catch (_) { - return false; - } - if (validHosts && !validHosts.includes(url2.hostname)) { - return false; - } - return url2.protocol === "http:" || url2.protocol === "https:"; - } - async function getFile(urlOrPath) { - if (env.useFS && !isValidHttpUrl(urlOrPath)) { - return new FileResponse(urlOrPath); - } else if (typeof process !== "undefined" && process?.release?.name === "node") { - const IS_CI = !!process.env?.TESTING_REMOTELY; - const version = env.version; - const headers = new Headers(); - headers.set("User-Agent", `transformers.js/${version}; is_ci/${IS_CI};`); - const isHFURL = isValidHttpUrl(urlOrPath, ["huggingface.co", "hf.co"]); - if (isHFURL) { - const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; - if (token) { - headers.set("Authorization", `Bearer ${token}`); - } - } - return fetch(urlOrPath, { headers }); - } else { - return fetch(urlOrPath); - } - } - var ERROR_MAPPING = { - // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) - 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", - // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) - 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" - }; - function handleError(status, remoteURL, fatal) { - if (!fatal) { - return null; - } - const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; - throw Error(`${message}: "${remoteURL}".`); - } - var FileCache = class { - /** - * Instantiate a `FileCache` object. - * @param {string} path - */ - constructor(path3) { - this.path = path3; - } - /** - * Checks whether the given request is in the cache. - * @param {string} request - * @returns {Promise} - */ - async match(request) { - let filePath = import_path2.default.join(this.path, request); - let file = new FileResponse(filePath); - if (file.exists) { - return file; - } else { - return void 0; - } - } - /** - * Adds the given response to the cache. - * @param {string} request - * @param {Response|FileResponse} response - * @returns {Promise} - */ - async put(request, response) { - const buffer = Buffer.from(await response.arrayBuffer()); - let outputPath = import_path2.default.join(this.path, request); - try { - await import_fs2.default.promises.mkdir(import_path2.default.dirname(outputPath), { recursive: true }); - await import_fs2.default.promises.writeFile(outputPath, buffer); - } catch (err) { - console.warn("An error occurred while writing the file to cache:", err); - } - } - // TODO add the rest? - // addAll(requests: RequestInfo[]): Promise; - // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; - // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; - }; - async function tryCache(cache, ...names) { - for (let name2 of names) { - try { - let result = await cache.match(name2); - if (result) - return result; - } catch (e) { - continue; - } - } - return void 0; - } - async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) { - if (!env.allowLocalModels) { - if (options.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`)."); - } else if (!env.allowRemoteModels) { - throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`."); - } - } - dispatchCallback(options.progress_callback, { - status: "initiate", - name: path_or_repo_id, - file: filename - }); - let cache; - if (!cache && env.useBrowserCache) { - if (typeof caches === "undefined") { - throw Error("Browser cache is not available in this environment."); - } - try { - cache = await caches.open("transformers-cache"); - } catch (e) { - console.warn("An error occurred while opening the browser cache:", e); - } - } - if (!cache && env.useFSCache) { - cache = new FileCache(options.cache_dir ?? env.cacheDir); - } - if (!cache && env.useCustomCache) { - if (!env.customCache) { - throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined."); - } - if (!env.customCache.match || !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" - ); - } - cache = env.customCache; - } - const revision = options.revision ?? "main"; - let requestURL = pathJoin(path_or_repo_id, filename); - let localPath = pathJoin(env.localModelPath, requestURL); - let remoteURL = pathJoin( - env.remoteHost, - env.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", revision), - filename - ); - let fsCacheKey = revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename); - let cacheKey; - let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL; - let toCacheResponse = false; - let response; - if (cache) { - response = await tryCache(cache, localPath, proposedCacheKey); - } - const cacheHit = response !== void 0; - if (response === void 0) { - if (env.allowLocalModels) { - const isURL = isValidHttpUrl(requestURL); - if (!isURL) { - try { - response = await getFile(localPath); - cacheKey = localPath; - } catch (e) { - console.warn(`Unable to load from local path "${localPath}": "${e}"`); - } - } else if (options.local_files_only) { - throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); - } else if (!env.allowRemoteModels) { - throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`); - } - } - if (response === void 0 || response.status === 404) { - if (options.local_files_only || !env.allowRemoteModels) { - if (fatal) { - throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`); - } else { - return null; - } - } - response = await getFile(remoteURL); - if (response.status !== 200) { - return handleError(response.status, remoteURL, fatal); - } - cacheKey = proposedCacheKey; - } - toCacheResponse = cache && typeof Response !== "undefined" && response instanceof Response && response.status === 200; - } - dispatchCallback(options.progress_callback, { - status: "download", - name: path_or_repo_id, - file: filename - }); - const progressInfo = { - status: "progress", - name: path_or_repo_id, - file: filename - }; - let buffer; - if (!options.progress_callback) { - buffer = new Uint8Array(await response.arrayBuffer()); - } else if (cacheHit && typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) { - buffer = new Uint8Array(await response.arrayBuffer()); - dispatchCallback(options.progress_callback, { - ...progressInfo, - progress: 100, - loaded: buffer.length, - total: buffer.length - }); - } else { - buffer = await readResponse(response, (data) => { - dispatchCallback(options.progress_callback, { - ...progressInfo, - ...data - }); - }); - } - if ( - // Only cache web responses - // i.e., do not cache FileResponses (prevents duplication) - toCacheResponse && cacheKey && // Check again whether request is in cache. If not, we add the response to the cache - await cache.match(cacheKey) === void 0 - ) { - await cache.put(cacheKey, new Response(buffer, { - headers: response.headers - })).catch((err) => { - console.warn(`Unable to add response to browser cache: ${err}.`); - }); - } - dispatchCallback(options.progress_callback, { - status: "done", - name: path_or_repo_id, - file: filename - }); - return buffer; - } - async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { - let buffer = await getModelFile(modelPath, fileName, fatal, options); - if (buffer === null) { - return {}; - } - let decoder = new TextDecoder("utf-8"); - let jsonData = decoder.decode(buffer); - return JSON.parse(jsonData); - } - async function readResponse(response, progress_callback) { - const contentLength = response.headers.get("Content-Length"); - if (contentLength === null) { - console.warn("Unable to determine content-length from response headers. Will expand buffer when needed."); - } - let total = parseInt(contentLength ?? "0"); - let buffer = new Uint8Array(total); - let loaded = 0; - const reader = response.body.getReader(); - async function read() { - const { done, value } = await reader.read(); - if (done) - return; - let newLoaded = loaded + value.length; - if (newLoaded > total) { - total = newLoaded; - let newBuffer = new Uint8Array(total); - newBuffer.set(buffer); - buffer = newBuffer; - } - buffer.set(value, loaded); - loaded = newLoaded; - const progress = loaded / total * 100; - progress_callback({ - progress, - loaded, - total - }); - return read(); - } - await read(); - return buffer; - } - function pathJoin(...parts) { - parts = parts.map((part, index) => { - if (index) { - part = part.replace(new RegExp("^/"), ""); - } - if (index !== parts.length - 1) { - part = part.replace(new RegExp("/$"), ""); - } - return part; - }); - return parts.join("/"); - } - - // node_modules/@xenova/transformers/src/utils/maths.js - function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = "bilinear", align_corners = false) { - const x_scale = out_width / in_width; - const y_scale = out_height / in_height; - const out_img = new input.constructor(out_height * out_width * in_channels); - const inStride = in_height * in_width; - const outStride = out_height * out_width; - for (let i = 0; i < out_height; ++i) { - for (let j = 0; j < out_width; ++j) { - const outOffset = i * out_width + j; - const x = (j + 0.5) / x_scale - 0.5; - const y = (i + 0.5) / y_scale - 0.5; - let x1 = Math.floor(x); - let y1 = Math.floor(y); - const x2 = Math.min(x1 + 1, in_width - 1); - const y2 = Math.min(y1 + 1, in_height - 1); - x1 = Math.max(x1, 0); - y1 = Math.max(y1, 0); - const s = x - x1; - const t = y - y1; - const w1 = (1 - s) * (1 - t); - const w2 = s * (1 - t); - const w3 = (1 - s) * t; - const w4 = s * t; - const yStride = y1 * in_width; - const xStride = y2 * in_width; - const idx1 = yStride + x1; - const idx2 = yStride + x2; - const idx3 = xStride + x1; - const idx4 = xStride + x2; - for (let k = 0; k < in_channels; ++k) { - const cOffset = k * inStride; - out_img[k * outStride + outOffset] = w1 * input[cOffset + idx1] + w2 * input[cOffset + idx2] + w3 * input[cOffset + idx3] + w4 * input[cOffset + idx4]; - } - } - } - return out_img; - } - function transpose_data(array, dims, axes) { - const shape = new Array(axes.length); - const stride = new Array(axes.length); - for (let i = axes.length - 1, s = 1; i >= 0; --i) { - stride[i] = s; - shape[i] = dims[axes[i]]; - s *= shape[i]; - } - const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); - const transposedData = new array.constructor(array.length); - for (let i = 0; i < array.length; ++i) { - let newIndex = 0; - for (let j = dims.length - 1, k = i; j >= 0; --j) { - newIndex += k % dims[j] * invStride[j]; - k = Math.floor(k / dims[j]); - } - transposedData[newIndex] = array[i]; - } - return [transposedData, shape]; - } - function softmax(arr) { - const maxVal = max(arr)[0]; - const exps = arr.map((x) => Math.exp(x - maxVal)); - const sumExps = exps.reduce((acc, val) => acc + val, 0); - const softmaxArr = exps.map((x) => x / sumExps); - return ( - /** @type {T} */ - softmaxArr - ); - } - function log_softmax(arr) { - const softmaxArr = softmax(arr); - const logSoftmaxArr = softmaxArr.map((x) => Math.log(x)); - return ( - /** @type {T} */ - logSoftmaxArr - ); - } - function getTopItems(items, top_k = 0) { - items = Array.from(items).map((x, i) => [i, x]).sort((a, b) => b[1] - a[1]); - if (top_k !== null && top_k > 0) { - items = items.slice(0, top_k); - } - return items; - } - function min(arr) { - if (arr.length === 0) - throw Error("Array must not be empty"); - let min2 = arr[0]; - let indexOfMin = 0; - for (let i = 1; i < arr.length; ++i) { - if (arr[i] < min2) { - min2 = arr[i]; - indexOfMin = i; - } - } - return [min2, indexOfMin]; - } - function max(arr) { - if (arr.length === 0) - throw Error("Array must not be empty"); - let max2 = arr[0]; - let indexOfMax = 0; - for (let i = 1; i < arr.length; ++i) { - if (arr[i] > max2) { - max2 = arr[i]; - indexOfMax = i; - } - } - return [Number(max2), indexOfMax]; - } - function isPowerOfTwo(number) { - return number > 0 && (number & number - 1) === 0; - } - var P2FFT = class { - /** - * @param {number} size The size of the input array. Must be a power of two larger than 1. - * @throws {Error} FFT size must be a power of two larger than 1. - */ - constructor(size) { - this.size = size | 0; - if (this.size <= 1 || !isPowerOfTwo(this.size)) - throw new Error("FFT size must be a power of two larger than 1"); - this._csize = size << 1; - this.table = new Float64Array(this.size * 2); - for (let i = 0; i < this.table.length; i += 2) { - const angle = Math.PI * i / this.size; - this.table[i] = Math.cos(angle); - this.table[i + 1] = -Math.sin(angle); - } - let power = 0; - for (let t = 1; this.size > t; t <<= 1) - ++power; - this._width = power % 2 === 0 ? power - 1 : power; - this._bitrev = new Int32Array(1 << this._width); - for (let j = 0; j < this._bitrev.length; ++j) { - this._bitrev[j] = 0; - for (let shift = 0; shift < this._width; shift += 2) { - const revShift = this._width - shift - 2; - this._bitrev[j] |= (j >>> shift & 3) << revShift; - } - } - } - /** - * Create a complex number array with size `2 * size` - * - * @returns {Float64Array} A complex number array with size `2 * size` - */ - createComplexArray() { - return new Float64Array(this._csize); - } - /** - * Converts a complex number representation stored in a Float64Array to an array of real numbers. - * - * @param {Float64Array} complex The complex number representation to be converted. - * @param {number[]} [storage] An optional array to store the result in. - * @returns {number[]} An array of real numbers representing the input complex number representation. - */ - fromComplexArray(complex, storage) { - const res = storage || new Array(complex.length >>> 1); - for (let i = 0; i < complex.length; i += 2) - res[i >>> 1] = complex[i]; - return res; - } - /** - * Convert a real-valued input array to a complex-valued output array. - * @param {Float64Array} input The real-valued input array. - * @param {Float64Array} [storage] Optional buffer to store the output array. - * @returns {Float64Array} The complex-valued output array. - */ - toComplexArray(input, storage) { - const res = storage || this.createComplexArray(); - for (let i = 0; i < res.length; i += 2) { - res[i] = input[i >>> 1]; - res[i + 1] = 0; - } - return res; - } - /** - * Completes the spectrum by adding its mirrored negative frequency components. - * @param {Float64Array} spectrum The input spectrum. - * @returns {void} - */ - completeSpectrum(spectrum) { - const size = this._csize; - const half = size >>> 1; - for (let i = 2; i < half; i += 2) { - spectrum[size - i] = spectrum[i]; - spectrum[size - i + 1] = -spectrum[i + 1]; - } - } - /** - * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. - * - * @param {Float64Array} out The output buffer to store the result. - * @param {Float64Array} data The input data to transform. - * - * @throws {Error} Input and output buffers must be different. - * - * @returns {void} - */ - transform(out, data) { - if (out === data) - throw new Error("Input and output buffers must be different"); - this._transform4( - out, - data, - 1 - /* DONE */ - ); - } - /** - * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. - * The input buffer must contain real values only, while the output buffer will contain complex values. The input and - * output buffers must be different. - * - * @param {Float64Array} out The output buffer. - * @param {Float64Array} data The input buffer containing real values. - * - * @throws {Error} If the input and output buffers are the same. - */ - realTransform(out, data) { - if (out === data) - throw new Error("Input and output buffers must be different"); - this._realTransform4( - out, - data, - 1 - /* DONE */ - ); - } - /** - * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. - * The `out` array must be a different buffer than the `data` array. The `out` array will contain the - * result of the transformation. The `data` array will not be modified. - * - * @param {Float64Array} out The output buffer for the transformed data. - * @param {Float64Array} data The input data to transform. - * @throws {Error} If `out` and `data` refer to the same buffer. - * @returns {void} - */ - inverseTransform(out, data) { - if (out === data) - throw new Error("Input and output buffers must be different"); - this._transform4( - out, - data, - -1 - /* DONE */ - ); - for (let i = 0; i < out.length; ++i) - out[i] /= this.size; - } - /** - * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. - * - * @param {Float64Array} out The output buffer for the transformed data. - * @param {Float64Array} data The input buffer of data to be transformed. - * @param {number} inv A scaling factor to apply to the transform. - * @returns {void} - */ - _transform4(out, data, inv) { - const size = this._csize; - const width = this._width; - let step = 1 << width; - let len = size / step << 1; - let outOff; - let t; - const bitrev = this._bitrev; - if (len === 4) { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleTransform2(data, out, outOff, off, step); - } - } else { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleTransform4(data, out, outOff, off, step, inv); - } - } - for (step >>= 2; step >= 2; step >>= 2) { - len = size / step << 1; - const quarterLen = len >>> 2; - for (outOff = 0; outOff < size; outOff += len) { - const limit = outOff + quarterLen - 1; - for (let i = outOff, k = 0; i < limit; i += 2, k += step) { - const A = i; - const B = A + quarterLen; - const C = B + quarterLen; - const D = C + quarterLen; - const Ar = out[A]; - const Ai = out[A + 1]; - const Br = out[B]; - const Bi = out[B + 1]; - const Cr = out[C]; - const Ci = out[C + 1]; - const Dr = out[D]; - const Di = out[D + 1]; - const tableBr = this.table[k]; - const tableBi = inv * this.table[k + 1]; - const MBr = Br * tableBr - Bi * tableBi; - const MBi = Br * tableBi + Bi * tableBr; - const tableCr = this.table[2 * k]; - const tableCi = inv * this.table[2 * k + 1]; - const MCr = Cr * tableCr - Ci * tableCi; - const MCi = Cr * tableCi + Ci * tableCr; - const tableDr = this.table[3 * k]; - const tableDi = inv * this.table[3 * k + 1]; - const MDr = Dr * tableDr - Di * tableDi; - const MDi = Dr * tableDi + Di * tableDr; - const T0r = Ar + MCr; - const T0i = Ai + MCi; - const T1r = Ar - MCr; - const T1i = Ai - MCi; - const T2r = MBr + MDr; - const T2i = MBi + MDi; - const T3r = inv * (MBr - MDr); - const T3i = inv * (MBi - MDi); - out[A] = T0r + T2r; - out[A + 1] = T0i + T2i; - out[B] = T1r + T3i; - out[B + 1] = T1i - T3r; - out[C] = T0r - T2r; - out[C + 1] = T0i - T2i; - out[D] = T1r - T3i; - out[D + 1] = T1i + T3r; - } - } - } - } - /** - * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. - * - * @param {Float64Array} data The input buffer of data to be transformed. - * @param {Float64Array} out The output buffer for the transformed data. - * @param {number} outOff The offset at which to write the output data. - * @param {number} off The offset at which to begin reading the input data. - * @param {number} step The step size for indexing the input data. - * @returns {void} - */ - _singleTransform2(data, out, outOff, off, step) { - const evenR = data[off]; - const evenI = data[off + 1]; - const oddR = data[off + step]; - const oddI = data[off + step + 1]; - out[outOff] = evenR + oddR; - out[outOff + 1] = evenI + oddI; - out[outOff + 2] = evenR - oddR; - out[outOff + 3] = evenI - oddI; - } - /** - * Performs radix-4 transformation on input data of length 8 - * - * @param {Float64Array} data Input data array of length 8 - * @param {Float64Array} out Output data array of length 8 - * @param {number} outOff Index of output array to start writing from - * @param {number} off Index of input array to start reading from - * @param {number} step Step size between elements in input array - * @param {number} inv Scaling factor for inverse transform - * - * @returns {void} - */ - _singleTransform4(data, out, outOff, off, step, inv) { - const step2 = step * 2; - const step3 = step * 3; - const Ar = data[off]; - const Ai = data[off + 1]; - const Br = data[off + step]; - const Bi = data[off + step + 1]; - const Cr = data[off + step2]; - const Ci = data[off + step2 + 1]; - const Dr = data[off + step3]; - const Di = data[off + step3 + 1]; - const T0r = Ar + Cr; - const T0i = Ai + Ci; - const T1r = Ar - Cr; - const T1i = Ai - Ci; - const T2r = Br + Dr; - const T2i = Bi + Di; - const T3r = inv * (Br - Dr); - const T3i = inv * (Bi - Di); - out[outOff] = T0r + T2r; - out[outOff + 1] = T0i + T2i; - out[outOff + 2] = T1r + T3i; - out[outOff + 3] = T1i - T3r; - out[outOff + 4] = T0r - T2r; - out[outOff + 5] = T0i - T2i; - out[outOff + 6] = T1r - T3i; - out[outOff + 7] = T1i + T3r; - } - /** - * Real input radix-4 implementation - * @param {Float64Array} out Output array for the transformed data - * @param {Float64Array} data Input array of real data to be transformed - * @param {number} inv The scale factor used to normalize the inverse transform - */ - _realTransform4(out, data, inv) { - const size = this._csize; - const width = this._width; - let step = 1 << width; - let len = size / step << 1; - let outOff; - let t; - const bitrev = this._bitrev; - if (len === 4) { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); - } - } else { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); - } - } - for (step >>= 2; step >= 2; step >>= 2) { - len = size / step << 1; - const quarterLen = len >>> 2; - for (outOff = 0; outOff < size; outOff += len) { - const limit = outOff + quarterLen - 1; - for (let i = outOff, k = 0; i < limit; i += 2, k += step) { - const A = i; - const B = A + quarterLen; - const C = B + quarterLen; - const D = C + quarterLen; - const Ar = out[A]; - const Ai = out[A + 1]; - const Br = out[B]; - const Bi = out[B + 1]; - const Cr = out[C]; - const Ci = out[C + 1]; - const Dr = out[D]; - const Di = out[D + 1]; - const tableBr = this.table[k]; - const tableBi = inv * this.table[k + 1]; - const MBr = Br * tableBr - Bi * tableBi; - const MBi = Br * tableBi + Bi * tableBr; - const tableCr = this.table[2 * k]; - const tableCi = inv * this.table[2 * k + 1]; - const MCr = Cr * tableCr - Ci * tableCi; - const MCi = Cr * tableCi + Ci * tableCr; - const tableDr = this.table[3 * k]; - const tableDi = inv * this.table[3 * k + 1]; - const MDr = Dr * tableDr - Di * tableDi; - const MDi = Dr * tableDi + Di * tableDr; - const T0r = Ar + MCr; - const T0i = Ai + MCi; - const T1r = Ar - MCr; - const T1i = Ai - MCi; - const T2r = MBr + MDr; - const T2i = MBi + MDi; - const T3r = inv * (MBr - MDr); - const T3i = inv * (MBi - MDi); - out[A] = T0r + T2r; - out[A + 1] = T0i + T2i; - out[B] = T1r + T3i; - out[B + 1] = T1i - T3r; - out[C] = T0r - T2r; - out[C + 1] = T0i - T2i; - out[D] = T1r - T3i; - out[D + 1] = T1i + T3r; - } - } - } - } - /** - * Performs a single real input radix-2 transformation on the provided data - * - * @param {Float64Array} data The input data array - * @param {Float64Array} out The output data array - * @param {number} outOff The output offset - * @param {number} off The input offset - * @param {number} step The step - * - * @returns {void} - */ - _singleRealTransform2(data, out, outOff, off, step) { - const evenR = data[off]; - const oddR = data[off + step]; - out[outOff] = evenR + oddR; - out[outOff + 1] = 0; - out[outOff + 2] = evenR - oddR; - out[outOff + 3] = 0; - } - /** - * Computes a single real-valued transform using radix-4 algorithm. - * This method is only called for len=8. - * - * @param {Float64Array} data The input data array. - * @param {Float64Array} out The output data array. - * @param {number} outOff The offset into the output array. - * @param {number} off The offset into the input array. - * @param {number} step The step size for the input array. - * @param {number} inv The value of inverse. - */ - _singleRealTransform4(data, out, outOff, off, step, inv) { - const step2 = step * 2; - const step3 = step * 3; - const Ar = data[off]; - const Br = data[off + step]; - const Cr = data[off + step2]; - const Dr = data[off + step3]; - const T0r = Ar + Cr; - const T1r = Ar - Cr; - const T2r = Br + Dr; - const T3r = inv * (Br - Dr); - out[outOff] = T0r + T2r; - out[outOff + 1] = 0; - out[outOff + 2] = T1r; - out[outOff + 3] = -T3r; - out[outOff + 4] = T0r - T2r; - out[outOff + 5] = 0; - out[outOff + 6] = T1r; - out[outOff + 7] = T3r; - } - }; - var NP2FFT = class { - /** - * Constructs a new NP2FFT object. - * @param {number} fft_length The length of the FFT - */ - constructor(fft_length) { - const a = 2 * (fft_length - 1); - const b = 2 * (2 * fft_length - 1); - const nextP2 = 2 ** Math.ceil(Math.log2(b)); - this.bufferSize = nextP2; - this._a = a; - const chirp = new Float64Array(b); - const ichirp = new Float64Array(nextP2); - this._chirpBuffer = new Float64Array(nextP2); - this._buffer1 = new Float64Array(nextP2); - this._buffer2 = new Float64Array(nextP2); - this._outBuffer1 = new Float64Array(nextP2); - this._outBuffer2 = new Float64Array(nextP2); - const theta = -2 * Math.PI / fft_length; - const baseR = Math.cos(theta); - const baseI = Math.sin(theta); - for (let i = 0; i < b >> 1; ++i) { - const e = (i + 1 - fft_length) ** 2 / 2; - const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; - const result_arg = e * Math.atan2(baseI, baseR); - const i2 = 2 * i; - chirp[i2] = result_mod * Math.cos(result_arg); - chirp[i2 + 1] = result_mod * Math.sin(result_arg); - ichirp[i2] = chirp[i2]; - ichirp[i2 + 1] = -chirp[i2 + 1]; - } - this._slicedChirpBuffer = chirp.subarray(a, b); - this._f = new P2FFT(nextP2 >> 1); - this._f.transform(this._chirpBuffer, ichirp); - } - _transform(output, input, real) { - const ib1 = this._buffer1; - const ib2 = this._buffer2; - const ob2 = this._outBuffer1; - const ob3 = this._outBuffer2; - const cb = this._chirpBuffer; - const sb = this._slicedChirpBuffer; - const a = this._a; - if (real) { - for (let j = 0; j < sb.length; j += 2) { - const j2 = j + 1; - const j3 = j >> 1; - const a_real = input[j3]; - ib1[j] = a_real * sb[j]; - ib1[j2] = a_real * sb[j2]; - } - } else { - for (let j = 0; j < sb.length; j += 2) { - const j2 = j + 1; - ib1[j] = input[j] * sb[j] - input[j2] * sb[j2]; - ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j]; - } - } - this._f.transform(ob2, ib1); - for (let j = 0; j < cb.length; j += 2) { - const j2 = j + 1; - ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2]; - ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j]; - } - this._f.inverseTransform(ob3, ib2); - for (let j = 0; j < ob3.length; j += 2) { - const a_real = ob3[j + a]; - const a_imag = ob3[j + a + 1]; - const b_real = sb[j]; - const b_imag = sb[j + 1]; - output[j] = a_real * b_real - a_imag * b_imag; - output[j + 1] = a_real * b_imag + a_imag * b_real; - } - } - transform(output, input) { - this._transform(output, input, false); - } - realTransform(output, input) { - this._transform(output, input, true); - } - }; - var FFT = class { - constructor(fft_length) { - this.fft_length = fft_length; - this.isPowerOfTwo = isPowerOfTwo(fft_length); - if (this.isPowerOfTwo) { - this.fft = new P2FFT(fft_length); - this.outputBufferSize = 2 * fft_length; - } else { - this.fft = new NP2FFT(fft_length); - this.outputBufferSize = this.fft.bufferSize; - } - } - realTransform(out, input) { - this.fft.realTransform(out, input); - } - transform(out, input) { - this.fft.transform(out, input); - } - }; - function medianFilter(data, windowSize) { - if (windowSize % 2 === 0 || windowSize <= 0) { - throw new Error("Window size must be a positive odd number"); - } - const outputArray = new data.constructor(data.length); - const buffer = new data.constructor(windowSize); - const halfWindowSize = Math.floor(windowSize / 2); - for (let i = 0; i < data.length; ++i) { - let valuesIndex = 0; - for (let j = -halfWindowSize; j <= halfWindowSize; ++j) { - let index = i + j; - if (index < 0) { - index = Math.abs(index); - } else if (index >= data.length) { - index = 2 * (data.length - 1) - index; - } - buffer[valuesIndex++] = data[index]; - } - buffer.sort(); - outputArray[i] = buffer[halfWindowSize]; - } - return outputArray; - } - function round(num, decimals) { - const pow = Math.pow(10, decimals); - return Math.round(num * pow) / pow; - } - - // node_modules/@xenova/transformers/src/utils/tensor.js - var DataTypeMap = Object.freeze({ - float32: Float32Array, - float64: Float64Array, - string: Array, - // string[] - int8: Int8Array, - uint8: Uint8Array, - int16: Int16Array, - uint16: Uint16Array, - int32: Int32Array, - uint32: Uint32Array, - int64: BigInt64Array, - uint64: BigUint64Array, - bool: Uint8Array - }); - var ONNXTensor = ONNX.Tensor; - var Tensor = class _Tensor { - /** @type {number[]} Dimensions of the tensor. */ - dims; - /** @type {DataType} Type of the tensor. */ - type; - /** @type {DataArray} The data stored in the tensor. */ - data; - /** @type {number} The number of elements in the tensor. */ - size; - /** - * Create a new Tensor or copy an existing Tensor. - * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args - */ - constructor(...args) { - if (args[0] instanceof ONNXTensor) { - Object.assign(this, args[0]); - } else { - Object.assign(this, new ONNXTensor( - /** @type {DataType} */ - args[0], - /** @type {Exclude} */ - args[1], - args[2] - )); - } - return new Proxy(this, { - get: (obj, key) => { - if (typeof key === "string") { - let index = Number(key); - if (Number.isInteger(index)) { - return obj._getitem(index); - } - } - return obj[key]; - }, - set: (obj, key, value) => { - return obj[key] = value; - } - }); - } - /** - * Returns an iterator object for iterating over the tensor data in row-major order. - * If the tensor has more than one dimension, the iterator will yield subarrays. - * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. - */ - *[Symbol.iterator]() { - const [iterLength, ...iterDims] = this.dims; - if (iterDims.length > 0) { - const iterSize = iterDims.reduce((a, b) => a * b); - for (let i = 0; i < iterLength; ++i) { - yield this._subarray(i, iterSize, iterDims); - } - } else { - yield* this.data; - } - } - /** - * Index into a Tensor object. - * @param {number} index The index to access. - * @returns {Tensor} The data at the specified index. - */ - _getitem(index) { - const [iterLength, ...iterDims] = this.dims; - index = safeIndex(index, iterLength); - if (iterDims.length > 0) { - const iterSize = iterDims.reduce((a, b) => a * b); - return this._subarray(index, iterSize, iterDims); - } else { - return new _Tensor(this.type, [this.data[index]], iterDims); - } - } - /** - * @param {number|bigint} item The item to search for in the tensor - * @returns {number} The index of the first occurrence of item in the tensor data. - */ - indexOf(item) { - for (let index = 0; index < this.data.length; ++index) { - if (this.data[index] == item) { - return index; - } - } - return -1; - } - /** - * @param {number} index - * @param {number} iterSize - * @param {any} iterDims - * @returns {Tensor} - */ - _subarray(index, iterSize, iterDims) { - const o1 = index * iterSize; - const o2 = (index + 1) * iterSize; - const data = "subarray" in this.data ? this.data.subarray(o1, o2) : this.data.slice(o1, o2); - return new _Tensor(this.type, data, iterDims); - } - /** - * Returns the value of this tensor as a standard JavaScript Number. This only works - * for tensors with one element. For other cases, see `Tensor.tolist()`. - * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. - * @throws {Error} If the tensor has more than one element. - */ - item() { - if (this.data.length !== 1) { - throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`); - } - return this.data[0]; - } - /** - * Convert tensor data to a n-dimensional JS list - * @returns {Array} - */ - tolist() { - return reshape(this.data, this.dims); - } - /** - * Return a new Tensor with the sigmoid function applied to each element. - * @returns {Tensor} The tensor with the sigmoid function applied. - */ - sigmoid() { - return this.clone().sigmoid_(); - } - /** - * Applies the sigmoid function to the tensor in place. - * @returns {Tensor} Returns `this`. - */ - sigmoid_() { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] = 1 / (1 + Math.exp(-this.data[i])); - } - return this; - } - /** - * Return a new Tensor with every element multiplied by a constant. - * @param {number} val The value to multiply by. - * @returns {Tensor} The new tensor. - */ - mul(val) { - return this.clone().mul_(val); - } - /** - * Multiply the tensor by a constant in place. - * @param {number} val The value to multiply by. - * @returns {Tensor} Returns `this`. - */ - mul_(val) { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] *= val; - } - return this; - } - /** - * Return a new Tensor with every element added by a constant. - * @param {number} val The value to add by. - * @returns {Tensor} The new tensor. - */ - add(val) { - return this.clone().add_(val); - } - /** - * Add the tensor by a constant in place. - * @param {number} val The value to add by. - * @returns {Tensor} Returns `this`. - */ - add_(val) { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] += val; - } - return this; - } - clone() { - return new _Tensor(this.type, this.data.slice(), this.dims.slice()); - } - slice(...slices) { - let newTensorDims = []; - let newOffsets = []; - for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { - let slice2 = slices[sliceIndex]; - if (slice2 === null || slice2 === void 0) { - newOffsets.push([0, this.dims[sliceIndex]]); - newTensorDims.push(this.dims[sliceIndex]); - } else if (typeof slice2 === "number") { - slice2 = safeIndex(slice2, this.dims[sliceIndex], sliceIndex); - newOffsets.push([slice2, slice2 + 1]); - } else if (Array.isArray(slice2) && slice2.length === 2) { - if (slice2[0] > slice2[1]) { - throw new Error(`Invalid slice: ${slice2}`); - } - let offsets = [ - Math.max(slice2[0], 0), - Math.min(slice2[1], this.dims[sliceIndex]) - ]; - newOffsets.push(offsets); - newTensorDims.push(offsets[1] - offsets[0]); - } else { - throw new Error(`Invalid slice: ${slice2}`); - } - } - let newDims = newOffsets.map(([start, end]) => end - start); - let newBufferSize = newDims.reduce((a, b) => a * b); - let data = new this.data.constructor(newBufferSize); - const stride = this.stride(); - for (let i = 0; i < newBufferSize; ++i) { - let originalIndex = 0; - for (let j = newDims.length - 1, num = i; j >= 0; --j) { - const size = newDims[j]; - originalIndex += (num % size + newOffsets[j][0]) * stride[j]; - num = Math.floor(num / size); - } - data[i] = this.data[originalIndex]; - } - return new _Tensor(this.type, data, newTensorDims); - } - /** - * Return a transposed version of this Tensor, according to the provided dimensions. - * @param {...number} dims Dimensions to transpose. - * @returns {Tensor} The transposed tensor. - */ - transpose(...dims) { - return transpose(this, dims); - } - // TODO: rename transpose to permute - // TODO: implement transpose - // TODO add .max() and .min() methods - /** - * Returns the sum of each row of the input tensor in the given dimension dim. - * - * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. - * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. - * @returns The summed tensor - */ - sum(dim = null, keepdim = false) { - return this.norm(1, dim, keepdim); - } - /** - * Returns the matrix norm or vector norm of a given tensor. - * @param {number|string} [p='fro'] The order of norm - * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. - * If dim is None, the norm will be calculated across all dimensions of input. - * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. - * @returns {Tensor} The norm of the tensor. - */ - norm(p = "fro", dim = null, keepdim = false) { - if (p === "fro") { - p = 2; - } else if (typeof p === "string") { - throw Error(`Unsupported norm: ${p}`); - } - if (dim === null) { - let val = this.data.reduce((a, b) => a + b ** p, 0) ** (1 / p); - return new _Tensor(this.type, [val], []); - } - dim = safeIndex(dim, this.dims.length); - const resultDims = this.dims.slice(); - resultDims[dim] = 1; - const result = new this.data.constructor(this.data.length / this.dims[dim]); - for (let i = 0; i < this.data.length; ++i) { - let resultIndex = 0; - for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = this.dims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - } - num = Math.floor(num / size); - } - result[resultIndex] += this.data[i] ** p; - } - if (p !== 1) { - for (let i = 0; i < result.length; ++i) { - result[i] = result[i] ** (1 / p); - } - } - if (!keepdim) { - resultDims.splice(dim, 1); - } - return new _Tensor(this.type, result, resultDims); - } - /** - * Performs `L_p` normalization of inputs over specified dimension. Operates in place. - * @param {number} [p=2] The exponent value in the norm formulation - * @param {number} [dim=1] The dimension to reduce - * @returns {Tensor} `this` for operation chaining. - */ - normalize_(p = 2, dim = 1) { - dim = safeIndex(dim, this.dims.length); - const norm = this.norm(p, dim, true); - for (let i = 0; i < this.data.length; ++i) { - let resultIndex = 0; - for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = this.dims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= this.dims[j]; - } - num = Math.floor(num / size); - } - this.data[i] /= norm.data[resultIndex]; - } - return this; - } - /** - * Performs `L_p` normalization of inputs over specified dimension. - * @param {number} [p=2] The exponent value in the norm formulation - * @param {number} [dim=1] The dimension to reduce - * @returns {Tensor} The normalized tensor. - */ - normalize(p = 2, dim = 1) { - return this.clone().normalize_(p, dim); - } - /** - * Compute and return the stride of this tensor. - * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. - * @returns {number[]} The stride of this tensor. - */ - stride() { - return dimsToStride(this.dims); - } - /** - * Returns a tensor with all specified dimensions of input of size 1 removed. - * - * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. - * If you would like a copy, use `tensor.clone()` before squeezing. - * - * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions. - * @returns The squeezed tensor - */ - squeeze(dim = null) { - return new _Tensor( - this.type, - this.data, - calc_squeeze_dims(this.dims, dim) - ); - } - /** - * In-place version of @see {@link Tensor.squeeze} - */ - squeeze_(dim = null) { - this.dims = calc_squeeze_dims(this.dims, dim); - return this; - } - /** - * Returns a new tensor with a dimension of size one inserted at the specified position. - * - * NOTE: The returned tensor shares the same underlying data with this tensor. - * - * @param {number} dim The index at which to insert the singleton dimension - * @returns The unsqueezed tensor - */ - unsqueeze(dim = null) { - return new _Tensor( - this.type, - this.data, - calc_unsqueeze_dims(this.dims, dim) - ); - } - /** - * In-place version of @see {@link Tensor.unsqueeze} - */ - unsqueeze_(dim = null) { - this.dims = calc_unsqueeze_dims(this.dims, dim); - return this; - } - /** - * In-place version of @see {@link Tensor.flatten} - */ - flatten_(start_dim = 0, end_dim = -1) { - end_dim = (end_dim + this.dims.length) % this.dims.length; - let dimsToKeepBefore = this.dims.slice(0, start_dim); - let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); - let dimsToKeepAfter = this.dims.slice(end_dim + 1); - this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]; - return this; - } - /** - * Flattens input by reshaping it into a one-dimensional tensor. - * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` - * and ending with `end_dim` are flattened. The order of elements in input is unchanged. - * @param {number} start_dim the first dim to flatten - * @param {number} end_dim the last dim to flatten - * @returns The flattened tensor. - */ - flatten(start_dim = 0, end_dim = -1) { - return this.clone().flatten_(start_dim, end_dim); - } - /** - * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. - * @param {...number} dims the desired size - * @returns {Tensor} The tensor with the same data but different shape - */ - view(...dims) { - let inferredIndex = -1; - for (let i = 0; i < dims.length; ++i) { - if (dims[i] === -1) { - if (inferredIndex !== -1) { - throw new Error("Only one dimension can be inferred"); - } - inferredIndex = i; - } - } - if (inferredIndex !== -1) { - const productOther = dims.reduce((product2, curr, index) => { - return index !== inferredIndex ? product2 * curr : product2; - }, 1); - dims[inferredIndex] = this.data.length / productOther; - } - return new _Tensor(this.type, this.data, dims); - } - neg_() { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] = -this.data[i]; - } - return this; - } - neg() { - return this.clone().neg_(); - } - /** - * In-place version of @see {@link Tensor.clamp} - */ - clamp_(min2, max2) { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] = Math.min(Math.max(this.data[i], min2), max2); - } - return this; - } - /** - * Clamps all elements in input into the range [ min, max ] - * @param {number} min lower-bound of the range to be clamped to - * @param {number} max upper-bound of the range to be clamped to - * @returns the output tensor. - */ - clamp(min2, max2) { - return this.clone().clamp_(min2, max2); - } - /** - * In-place version of @see {@link Tensor.round} - */ - round_() { - for (let i = 0; i < this.data.length; ++i) { - this.data[i] = Math.round(this.data[i]); - } - return this; - } - /** - * Rounds elements of input to the nearest integer. - * @returns the output tensor. - */ - round() { - return this.clone().round_(); - } - /** - * Performs Tensor dtype conversion. - * @param {DataType} type The desired data type. - * @returns {Tensor} The converted tensor. - */ - to(type) { - if (this.type === type) - return this; - if (!DataTypeMap.hasOwnProperty(type)) { - throw new Error(`Unsupported type: ${type}`); - } - return new _Tensor(type, DataTypeMap[type].from(this.data), this.dims); - } - }; - function reshape(data, dimensions) { - const totalElements = data.length; - const dimensionSize = dimensions.reduce((a, b) => a * b); - if (totalElements !== dimensionSize) { - throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); - } - let reshapedArray = data; - for (let i = dimensions.length - 1; i >= 0; i--) { - reshapedArray = reshapedArray.reduce((acc, val) => { - let lastArray = acc[acc.length - 1]; - if (lastArray.length < dimensions[i]) { - lastArray.push(val); - } else { - acc.push([val]); - } - return acc; - }, [[]]); - } - return reshapedArray[0]; - } - function transpose(tensor, axes) { - const [transposedData, shape] = transpose_data(tensor.data, tensor.dims, axes); - return new Tensor(tensor.type, transposedData, shape); - } - function interpolate(input, [out_height, out_width], mode = "bilinear", align_corners = false) { - const in_channels = input.dims.at(-3) ?? 1; - const in_height = input.dims.at(-2); - const in_width = input.dims.at(-1); - let output = interpolate_data( - /** @type {import('./maths.js').TypedArray}*/ - input.data, - [in_channels, in_height, in_width], - [out_height, out_width], - mode, - align_corners - ); - return new Tensor(input.type, output, [in_channels, out_height, out_width]); - } - function mean_pooling(last_hidden_state, attention_mask) { - let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; - let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]); - let [batchSize, seqLength, embedDim] = last_hidden_state.dims; - let outIndex = 0; - for (let i = 0; i < batchSize; ++i) { - let offset = i * embedDim * seqLength; - for (let k = 0; k < embedDim; ++k) { - let sum = 0; - let count = 0; - let attnMaskOffset = i * seqLength; - let offset2 = offset + k; - for (let j = 0; j < seqLength; ++j) { - let attn = Number(attention_mask.data[attnMaskOffset + j]); - count += attn; - sum += last_hidden_state.data[offset2 + j * embedDim] * attn; - } - let avg = sum / count; - returnedData[outIndex++] = avg; - } - } - return new Tensor( - last_hidden_state.type, - returnedData, - shape - ); - } - function calc_squeeze_dims(dims, dim) { - dims = dims.slice(); - if (dim === null) { - dims = dims.filter((d) => d !== 1); - } else if (typeof dim === "number") { - if (dims[dim] === 1) { - dims.splice(dim, 1); - } - } else if (Array.isArray(dim)) { - dims = dims.filter((x, i) => { - return x !== 1 || !dim.includes(i); - }); - } - return dims; - } - function calc_unsqueeze_dims(dims, dim) { - dim = safeIndex(dim, dims.length + 1); - dims = dims.slice(); - dims.splice(dim, 0, 1); - return dims; - } - function safeIndex(index, size, dimension = null) { - if (index < -size || index >= size) { - throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}`); - } - if (index < 0) { - index = (index % size + size) % size; - } - return index; - } - function cat(tensors, dim = 0) { - dim = safeIndex(dim, tensors[0].dims.length); - const resultDims = tensors[0].dims.slice(); - resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); - const resultSize = resultDims.reduce((a, b) => a * b, 1); - const result = new tensors[0].data.constructor(resultSize); - const resultType = tensors[0].type; - if (dim === 0) { - let offset = 0; - for (let t of tensors) { - result.set(t.data, offset); - offset += t.data.length; - } - } else { - let currentDim = 0; - for (let t = 0; t < tensors.length; ++t) { - let tensor = tensors[t]; - for (let i = 0; i < tensor.data.length; ++i) { - let resultIndex = 0; - for (let j = tensor.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = tensor.dims[j]; - let index = num % size; - if (j === dim) { - index += currentDim; - } - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - num = Math.floor(num / size); - } - result[resultIndex] = tensor.data[i]; - } - currentDim += tensor.dims[dim]; - } - } - return new Tensor(resultType, result, resultDims); - } - function stack(tensors, dim = 0) { - return cat(tensors.map((t) => t.unsqueeze(dim)), dim); - } - function std_mean(input, dim = null, correction = 1, keepdim = false) { - if (dim === null) { - const sum = input.data.reduce((a, b) => a + b, 0); - const mean2 = sum / input.data.length; - const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean2) ** 2, 0) / (input.data.length - correction)); - const meanTensor2 = new Tensor(input.type, [mean2], [ - /* scalar */ - ]); - const stdTensor2 = new Tensor(input.type, [std], [ - /* scalar */ - ]); - return [stdTensor2, meanTensor2]; - } - dim = safeIndex(dim, input.dims.length); - const meanTensor = mean(input, dim, keepdim); - const resultDims = input.dims.slice(); - resultDims[dim] = 1; - const result = new input.data.constructor(input.data.length / input.dims[dim]); - for (let i = 0; i < input.data.length; ++i) { - let resultIndex = 0; - for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = input.dims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - } - num = Math.floor(num / size); - } - result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2; - } - for (let i = 0; i < result.length; ++i) { - result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction)); - } - if (!keepdim) { - resultDims.splice(dim, 1); - } - const stdTensor = new Tensor(input.type, result, resultDims); - return [stdTensor, meanTensor]; - } - function mean(input, dim = null, keepdim = false) { - if (dim === null) { - let val = input.data.reduce((a, b) => a + b, 0); - return new Tensor(input.type, [val / input.data.length], [ - /* scalar */ - ]); - } - dim = safeIndex(dim, input.dims.length); - const resultDims = input.dims.slice(); - resultDims[dim] = 1; - const result = new input.data.constructor(input.data.length / input.dims[dim]); - for (let i = 0; i < input.data.length; ++i) { - let resultIndex = 0; - for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = input.dims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - } - num = Math.floor(num / size); - } - result[resultIndex] += input.data[i]; - } - if (input.dims[dim] !== 1) { - for (let i = 0; i < result.length; ++i) { - result[i] = result[i] / input.dims[dim]; - } - } - if (!keepdim) { - resultDims.splice(dim, 1); - } - return new Tensor(input.type, result, resultDims); - } - function dynamicTimeWarping(matrix) { - const [output_length, input_length] = matrix.dims; - const outputShape = [output_length + 1, input_length + 1]; - const cost = new Tensor( - "float32", - new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity), - outputShape - ); - const trace = new Tensor( - "float32", - new Float32Array(outputShape[0] * outputShape[1]).fill(-1), - outputShape - ); - cost[0].data[0] = 0; - for (let j2 = 1; j2 < input_length + 1; ++j2) { - for (let i2 = 1; i2 < output_length + 1; ++i2) { - const c0 = cost[i2 - 1][j2 - 1].item(); - const c1 = cost[i2 - 1][j2].item(); - const c2 = cost[i2][j2 - 1].item(); - let c, t; - if (c0 < c1 && c0 < c2) { - c = c0; - t = 0; - } else if (c1 < c0 && c1 < c2) { - c = c1; - t = 1; - } else { - c = c2; - t = 2; - } - cost[i2].data[j2] = matrix[i2 - 1][j2 - 1].item() + c; - trace[i2].data[j2] = t; - } - } - let i = output_length; - let j = input_length; - trace.data.fill(2, 0, outputShape[1]); - for (let i2 = 0; i2 < outputShape[0]; ++i2) { - trace[i2].data[0] = 1; - } - let text_indices = []; - let time_indices = []; - while (i > 0 || j > 0) { - text_indices.push(i - 1); - time_indices.push(j - 1); - const t = trace[i][j].item(); - switch (t) { - case 0: - --i; - --j; - break; - case 1: - --i; - break; - case 2: - --j; - break; - default: - throw new Error( - `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.` - ); - } - } - text_indices.reverse(); - time_indices.reverse(); - return [text_indices, time_indices]; - } - function dimsToStride(dims) { - const stride = new Array(dims.length); - for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { - stride[i] = s2; - s2 *= dims[i]; - } - return stride; - } - function ones(size) { - const numElements = size.reduce((a, b) => a * b, 1); - return new Tensor( - "int64", - new BigInt64Array(numElements).fill(1n), - size - ); - } - function ones_like(tensor) { - return ones(tensor.dims); - } - - // node_modules/@xenova/transformers/src/utils/data-structures.js - var PriorityQueue = class { - /** - * Create a new PriorityQueue. - * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap. - */ - constructor(comparator = (a, b) => a > b) { - this._heap = []; - this._comparator = comparator; - } - /** - * The size of the queue - */ - get size() { - return this._heap.length; - } - /** - * Check if the queue is empty. - * @returns {boolean} `true` if the queue is empty, `false` otherwise. - */ - isEmpty() { - return this.size === 0; - } - /** - * Return the element with the highest priority in the queue. - * @returns {any} The highest priority element in the queue. - */ - peek() { - return this._heap[0]; - } - /** - * Add one or more elements to the queue. - * @param {...any} values The values to push into the queue. - * @returns {number} The new size of the queue. - */ - push(...values) { - return this.extend(values); - } - /** - * Add multiple elements to the queue. - * @param {any[]} values The values to push into the queue. - * @returns {number} The new size of the queue. - */ - extend(values) { - for (const value of values) { - this._heap.push(value); - this._siftUp(); - } - return this.size; - } - /** - * Remove and return the element with the highest priority in the queue. - * @returns {any} The element with the highest priority in the queue. - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size - 1; - if (bottom > 0) { - this._swap(0, bottom); - } - this._heap.pop(); - this._siftDown(); - return poppedValue; - } - /** - * Replace the element with the highest priority in the queue with a new value. - * @param {*} value The new value. - * @returns {*} The replaced value. - */ - replace(value) { - const replacedValue = this.peek(); - this._heap[0] = value; - this._siftDown(); - return replacedValue; - } - /** - * Compute the index for the parent of the node at index `i`. - * @param {number} i The index of the node to get the parent of. - * @returns {number} The index of the parent node. - * @private - */ - _parent(i) { - return (i + 1 >>> 1) - 1; - } - /** - * Compute the index for the left child of the node at index `i`. - * @param {number} i The index of the node to get the left child of. - * @returns {number} The index of the left child. - * @private - */ - _left(i) { - return (i << 1) + 1; - } - /** - * Compute the index for the right child of the node at index `i`. - * @param {number} i The index of the node to get the right child of. - * @returns {number} The index of the right child. - * @private - */ - _right(i) { - return i + 1 << 1; - } - /** - * Check if the element at index `i` is greater than the element at index `j`. - * @param {number} i The index of the first element to compare. - * @param {number} j The index of the second element to compare. - * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. - * @private - */ - _greater(i, j) { - return this._comparator(this._heap[i], this._heap[j]); - } - /** - * Swap the elements at indices `i` and `j`. - * @param {number} i The index of the first element to swap. - * @param {number} j The index of the second element to swap. - * @private - */ - _swap(i, j) { - const temp = this._heap[i]; - this._heap[i] = this._heap[j]; - this._heap[j] = temp; - } - /** - * Maintain the heap property by updating positions in the heap, - * starting at the last element and moving up the heap. - * @private - */ - _siftUp() { - let node = this.size - 1; - while (node > 0 && this._greater(node, this._parent(node))) { - this._swap(node, this._parent(node)); - node = this._parent(node); - } - } - /** - * Maintain the heap property by updating positions in the heap, - * starting at the first element and moving down the heap. - * @private - */ - _siftDown() { - let node = 0; - while (this._left(node) < this.size && this._greater(this._left(node), node) || this._right(node) < this.size && this._greater(this._right(node), node)) { - const maxChild = this._right(node) < this.size && this._greater(this._right(node), this._left(node)) ? this._right(node) : this._left(node); - this._swap(node, maxChild); - node = maxChild; - } - } - }; - var CharTrie = class { - constructor() { - this.root = CharTrieNode.default(); - } - /** - * Adds one or more `texts` to the trie. - * @param {string[]} texts The strings to add to the trie. - */ - extend(texts) { - for (let text of texts) { - this.push(text); - } - } - /** - * Adds text to the trie. - * @param {string} text The string to add to the trie. - */ - push(text) { - let node = this.root; - for (let ch of text) { - let child = node.children.get(ch); - if (child === void 0) { - child = CharTrieNode.default(); - node.children.set(ch, child); - } - node = child; - } - node.isLeaf = true; - } - /** - * Searches the trie for all strings with a common prefix of `text`. - * @param {string} text The common prefix to search for. - * @yields {string} Each string in the trie that has `text` as a prefix. - */ - *commonPrefixSearch(text) { - let node = this.root; - let prefix = ""; - for (let i = 0; i < text.length && node !== void 0; ++i) { - const ch = text[i]; - prefix += ch; - node = node.children.get(ch); - if (node !== void 0 && node.isLeaf) { - yield prefix; - } - } - } - }; - var CharTrieNode = class _CharTrieNode { - /** - * Create a new CharTrieNode. - * @param {boolean} isLeaf Whether the node is a leaf node or not. - * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. - */ - constructor(isLeaf, children) { - this.isLeaf = isLeaf; - this.children = children; - } - /** - * Returns a new `CharTrieNode` instance with default values. - * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. - */ - static default() { - return new _CharTrieNode(false, /* @__PURE__ */ new Map()); - } - }; - var TokenLattice = class { - /** - * Creates a new TokenLattice instance. - * - * @param {string} sentence The input sentence to be tokenized. - * @param {number} bosTokenId The beginning-of-sequence token ID. - * @param {number} eosTokenId The end-of-sequence token ID. - */ - constructor(sentence, bosTokenId, eosTokenId) { - this.sentence = sentence; - this.len = sentence.length; - this.bosTokenId = bosTokenId; - this.eosTokenId = eosTokenId; - this.nodes = []; - this.beginNodes = Array.from({ length: this.len + 1 }, () => []); - this.endNodes = Array.from({ length: this.len + 1 }, () => []); - const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0); - const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0); - this.nodes.push(bos.clone()); - this.nodes.push(eos.clone()); - this.beginNodes[this.len].push(eos); - this.endNodes[0].push(bos); - } - /** - * Inserts a new token node into the token lattice. - * - * @param {number} pos The starting position of the token. - * @param {number} length The length of the token. - * @param {number} score The score of the token. - * @param {number} tokenId The token ID of the token. - */ - insert(pos, length, score, tokenId) { - const nodeId = this.nodes.length; - const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score); - this.beginNodes[pos].push(node); - this.endNodes[pos + length].push(node); - this.nodes.push(node); - } - /** - * Implements the Viterbi algorithm to compute the most likely sequence of tokens. - * - * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens. - */ - viterbi() { - const len = this.len; - let pos = 0; - while (pos <= len) { - if (this.beginNodes[pos].length == 0) { - return []; - } - for (let rnode of this.beginNodes[pos]) { - rnode.prev = null; - let bestScore = 0; - let bestNode = null; - for (let lnode of this.endNodes[pos]) { - const score = lnode.backtraceScore + rnode.score; - if (bestNode === null || score > bestScore) { - bestNode = lnode.clone(); - bestScore = score; - } - } - if (bestNode !== null) { - rnode.prev = bestNode; - rnode.backtraceScore = bestScore; - } else { - return []; - } - } - ++pos; - } - const results = []; - const root = this.beginNodes[len][0]; - const prev = root.prev; - if (prev === null) { - return []; - } - let node = prev.clone(); - while (node.prev !== null) { - results.push(node.clone()); - const n = node.clone(); - node = n.prev.clone(); - } - results.reverse(); - return results; - } - /** - * @param {TokenLatticeNode} node - * @returns {string} The array of nodes representing the most likely sequence of tokens. - */ - piece(node) { - return this.sentence.slice(node.pos, node.pos + node.length); - } - /** - * @returns {Array} The array of nodes representing the most likely sequence of tokens. - */ - tokens() { - const nodes = this.viterbi(); - return nodes.map((x) => this.piece(x)); - } - /** - * @returns {Array} The array of nodes representing the most likely sequence of tokens. - */ - tokenIds() { - const nodes = this.viterbi(); - return nodes.map((x) => x.tokenId); - } - }; - var TokenLatticeNode = class _TokenLatticeNode { - /** - * Represents a node in a token lattice for a given sentence. - * @param {number} tokenId The ID of the token associated with this node. - * @param {number} nodeId The ID of this node. - * @param {number} pos The starting position of the token in the sentence. - * @param {number} length The length of the token. - * @param {number} score The score associated with the token. - */ - constructor(tokenId, nodeId, pos, length, score) { - this.tokenId = tokenId; - this.nodeId = nodeId; - this.pos = pos; - this.length = length; - this.score = score; - this.prev = null; - this.backtraceScore = 0; - } - /** - * Returns a clone of this node. - * @returns {TokenLatticeNode} A clone of this node. - */ - clone() { - const n = new _TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score); - n.prev = this.prev; - n.backtraceScore = this.backtraceScore; - return n; - } - }; - - // node_modules/@huggingface/jinja/dist/index.js - var TOKEN_TYPES = Object.freeze({ - Text: "Text", - // The text between Jinja statements or expressions - NumericLiteral: "NumericLiteral", - // e.g., 123 - BooleanLiteral: "BooleanLiteral", - // true or false - StringLiteral: "StringLiteral", - // 'string' - Identifier: "Identifier", - // Variables, functions, etc. - Equals: "Equals", - // = - OpenParen: "OpenParen", - // ( - CloseParen: "CloseParen", - // ) - OpenStatement: "OpenStatement", - // {% - CloseStatement: "CloseStatement", - // %} - OpenExpression: "OpenExpression", - // {{ - CloseExpression: "CloseExpression", - // }} - OpenSquareBracket: "OpenSquareBracket", - // [ - CloseSquareBracket: "CloseSquareBracket", - // ] - Comma: "Comma", - // , - Dot: "Dot", - // . - Colon: "Colon", - // : - Pipe: "Pipe", - // | - CallOperator: "CallOperator", - // () - AdditiveBinaryOperator: "AdditiveBinaryOperator", - // + - - MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator", - // * / % - ComparisonBinaryOperator: "ComparisonBinaryOperator", - // < > <= >= == != - UnaryOperator: "UnaryOperator", - // ! - + - // Keywords - Set: "Set", - If: "If", - For: "For", - In: "In", - NotIn: "NotIn", - Else: "Else", - EndIf: "EndIf", - ElseIf: "ElseIf", - EndFor: "EndFor", - And: "And", - Or: "Or", - Not: "UnaryOperator" - }); - var KEYWORDS = Object.freeze({ - set: TOKEN_TYPES.Set, - for: TOKEN_TYPES.For, - in: TOKEN_TYPES.In, - if: TOKEN_TYPES.If, - else: TOKEN_TYPES.Else, - endif: TOKEN_TYPES.EndIf, - elif: TOKEN_TYPES.ElseIf, - endfor: TOKEN_TYPES.EndFor, - and: TOKEN_TYPES.And, - or: TOKEN_TYPES.Or, - not: TOKEN_TYPES.Not, - "not in": TOKEN_TYPES.NotIn, - // Literals - true: TOKEN_TYPES.BooleanLiteral, - false: TOKEN_TYPES.BooleanLiteral - }); - var Token = class { - /** - * Constructs a new Token. - * @param {string} value The raw value as seen inside the source code. - * @param {TokenType} type The type of token. - */ - constructor(value, type) { - this.value = value; - this.type = type; - } - }; - function isWord(char) { - return /\w/.test(char); - } - function isInteger(char) { - return /[0-9]/.test(char); - } - var ORDERED_MAPPING_TABLE = [ - // Control sequences - ["{%", TOKEN_TYPES.OpenStatement], - ["%}", TOKEN_TYPES.CloseStatement], - ["{{", TOKEN_TYPES.OpenExpression], - ["}}", TOKEN_TYPES.CloseExpression], - // Single character tokens - ["(", TOKEN_TYPES.OpenParen], - [")", TOKEN_TYPES.CloseParen], - ["[", TOKEN_TYPES.OpenSquareBracket], - ["]", TOKEN_TYPES.CloseSquareBracket], - [",", TOKEN_TYPES.Comma], - [".", TOKEN_TYPES.Dot], - [":", TOKEN_TYPES.Colon], - ["|", TOKEN_TYPES.Pipe], - // Comparison operators - ["<=", TOKEN_TYPES.ComparisonBinaryOperator], - [">=", TOKEN_TYPES.ComparisonBinaryOperator], - ["==", TOKEN_TYPES.ComparisonBinaryOperator], - ["!=", TOKEN_TYPES.ComparisonBinaryOperator], - ["<", TOKEN_TYPES.ComparisonBinaryOperator], - [">", TOKEN_TYPES.ComparisonBinaryOperator], - // Arithmetic operators - ["+", TOKEN_TYPES.AdditiveBinaryOperator], - ["-", TOKEN_TYPES.AdditiveBinaryOperator], - ["*", TOKEN_TYPES.MultiplicativeBinaryOperator], - ["/", TOKEN_TYPES.MultiplicativeBinaryOperator], - ["%", TOKEN_TYPES.MultiplicativeBinaryOperator], - // Assignment operator - ["=", TOKEN_TYPES.Equals] - ]; - var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([ - ["n", "\n"], - // New line - ["t", " "], - // Horizontal tab - ["r", "\r"], - // Carriage return - ["b", "\b"], - // Backspace - ["f", "\f"], - // Form feed - ["v", "\v"], - // Vertical tab - ["'", "'"], - // Single quote - ['"', '"'], - // Double quote - ["\\", "\\"] - // Backslash - ]); - function tokenize(source) { - const tokens = []; - const src = source; - let cursorPosition = 0; - const consumeWhile = (predicate) => { - let str = ""; - while (predicate(src[cursorPosition])) { - if (src[cursorPosition] === "\\") { - ++cursorPosition; - if (cursorPosition >= src.length) - throw new SyntaxError("Unexpected end of input"); - const escaped = src[cursorPosition++]; - const unescaped = ESCAPE_CHARACTERS.get(escaped); - if (unescaped === void 0) { - throw new SyntaxError(`Unexpected escaped character: ${escaped}`); - } - str += unescaped; - continue; - } - str += src[cursorPosition++]; - if (cursorPosition >= src.length) - throw new SyntaxError("Unexpected end of input"); - } - return str; - }; - main: - while (cursorPosition < src.length) { - const lastTokenType = tokens.at(-1)?.type; - if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) { - let text = ""; - while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression - !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{"))) { - text += src[cursorPosition++]; - } - if (text.length > 0) { - tokens.push(new Token(text, TOKEN_TYPES.Text)); - continue; - } - } - consumeWhile((char2) => /\s/.test(char2)); - const char = src[cursorPosition]; - if (char === "-" || char === "+") { - const lastTokenType2 = tokens.at(-1)?.type; - if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) { - throw new SyntaxError(`Unexpected character: ${char}`); - } - switch (lastTokenType2) { - case TOKEN_TYPES.Identifier: - case TOKEN_TYPES.NumericLiteral: - case TOKEN_TYPES.BooleanLiteral: - case TOKEN_TYPES.StringLiteral: - case TOKEN_TYPES.CloseParen: - case TOKEN_TYPES.CloseSquareBracket: - break; - default: { - ++cursorPosition; - const num = consumeWhile(isInteger); - tokens.push( - new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator) - ); - continue; - } - } - } - for (const [char2, token] of ORDERED_MAPPING_TABLE) { - const slice2 = src.slice(cursorPosition, cursorPosition + char2.length); - if (slice2 === char2) { - tokens.push(new Token(char2, token)); - cursorPosition += char2.length; - continue main; - } - } - if (char === "'") { - ++cursorPosition; - const str = consumeWhile((char2) => char2 !== "'"); - tokens.push(new Token(str, TOKEN_TYPES.StringLiteral)); - ++cursorPosition; - continue; - } - if (isInteger(char)) { - const num = consumeWhile(isInteger); - tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral)); - continue; - } - if (isWord(char)) { - const word = consumeWhile(isWord); - const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier; - if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) { - tokens.pop(); - tokens.push(new Token("not in", TOKEN_TYPES.NotIn)); - } else { - tokens.push(new Token(word, type)); - } - continue; - } - throw new SyntaxError(`Unexpected character: ${char}`); - } - return tokens; - } - var Statement = class { - type = "Statement"; - }; - var Program = class extends Statement { - constructor(body) { - super(); - this.body = body; - } - type = "Program"; - }; - var If = class extends Statement { - constructor(test, body, alternate) { - super(); - this.test = test; - this.body = body; - this.alternate = alternate; - } - type = "If"; - }; - var For = class extends Statement { - constructor(loopvar, iterable, body) { - super(); - this.loopvar = loopvar; - this.iterable = iterable; - this.body = body; - } - type = "For"; - }; - var SetStatement = class extends Statement { - constructor(assignee, value) { - super(); - this.assignee = assignee; - this.value = value; - } - type = "Set"; - }; - var Expression = class extends Statement { - type = "Expression"; - }; - var MemberExpression = class extends Expression { - constructor(object, property, computed) { - super(); - this.object = object; - this.property = property; - this.computed = computed; - } - type = "MemberExpression"; - }; - var CallExpression = class extends Expression { - constructor(callee, args) { - super(); - this.callee = callee; - this.args = args; - } - type = "CallExpression"; - }; - var Identifier = class extends Expression { - /** - * @param {string} value The name of the identifier - */ - constructor(value) { - super(); - this.value = value; - } - type = "Identifier"; - }; - var Literal = class extends Expression { - constructor(value) { - super(); - this.value = value; - } - type = "Literal"; - }; - var NumericLiteral = class extends Literal { - type = "NumericLiteral"; - }; - var StringLiteral = class extends Literal { - type = "StringLiteral"; - constructor(value) { - super(value); - } - }; - var BooleanLiteral = class extends Literal { - type = "BooleanLiteral"; - }; - var BinaryExpression = class extends Expression { - constructor(operator, left, right) { - super(); - this.operator = operator; - this.left = left; - this.right = right; - } - type = "BinaryExpression"; - }; - var FilterExpression = class extends Expression { - constructor(operand, filter) { - super(); - this.operand = operand; - this.filter = filter; - } - type = "FilterExpression"; - }; - var UnaryExpression = class extends Expression { - constructor(operator, argument) { - super(); - this.operator = operator; - this.argument = argument; - } - type = "UnaryExpression"; - }; - var SliceExpression = class extends Expression { - constructor(start = void 0, stop = void 0, step = void 0) { - super(); - this.start = start; - this.stop = stop; - this.step = step; - } - type = "SliceExpression"; - }; - function parse(tokens) { - const program = new Program([]); - let current = 0; - function expect(type, error) { - const prev = tokens[current++]; - if (!prev || prev.type !== type) { - throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`); - } - return prev; - } - function parseAny() { - switch (tokens[current].type) { - case TOKEN_TYPES.Text: - return parseText(); - case TOKEN_TYPES.OpenStatement: - return parseJinjaStatement(); - case TOKEN_TYPES.OpenExpression: - return parseJinjaExpression(); - default: - throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`); - } - } - function not(...types) { - return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type); - } - function is(...types) { - return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type); - } - function parseText() { - return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value); - } - function parseJinjaStatement() { - expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token"); - let result; - switch (tokens[current].type) { - case TOKEN_TYPES.Set: - ++current; - result = parseSetStatement(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - break; - case TOKEN_TYPES.If: - ++current; - result = parseIfStatement(); - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expect(TOKEN_TYPES.EndIf, "Expected endif token"); - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - break; - case TOKEN_TYPES.For: - ++current; - result = parseForStatement(); - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expect(TOKEN_TYPES.EndFor, "Expected endfor token"); - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - break; - default: - throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`); - } - return result; - } - function parseJinjaExpression() { - expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token"); - const result = parseExpression(); - expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token"); - return result; - } - function parseSetStatement() { - const left = parseExpression(); - if (is(TOKEN_TYPES.Equals)) { - ++current; - const value = parseSetStatement(); - return new SetStatement(left, value); - } - return left; - } - function parseIfStatement() { - const test = parseExpression(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - const alternate = []; - while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) { - body.push(parseAny()); - } - if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) { - ++current; - if (is(TOKEN_TYPES.ElseIf)) { - expect(TOKEN_TYPES.ElseIf, "Expected elseif token"); - alternate.push(parseIfStatement()); - } else { - expect(TOKEN_TYPES.Else, "Expected else token"); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) { - alternate.push(parseAny()); - } - } - } - return new If(test, body, alternate); - } - function parseForStatement() { - const loopVariable = parsePrimaryExpression(); - if (!(loopVariable instanceof Identifier)) { - throw new SyntaxError(`Expected identifier for the loop variable`); - } - expect(TOKEN_TYPES.In, "Expected `in` keyword following loop variable"); - const iterable = parseExpression(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) { - body.push(parseAny()); - } - return new For(loopVariable, iterable, body); - } - function parseExpression() { - return parseLogicalOrExpression(); - } - function parseLogicalOrExpression() { - let left = parseLogicalAndExpression(); - while (is(TOKEN_TYPES.Or)) { - const operator = tokens[current]; - ++current; - const right = parseLogicalAndExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; - } - function parseLogicalAndExpression() { - let left = parseLogicalNegationExpression(); - while (is(TOKEN_TYPES.And)) { - const operator = tokens[current]; - ++current; - const right = parseLogicalNegationExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; - } - function parseLogicalNegationExpression() { - let right; - while (is(TOKEN_TYPES.Not)) { - const operator = tokens[current]; - ++current; - const arg = parseLogicalNegationExpression(); - right = new UnaryExpression(operator, arg); - } - return right ?? parseComparisonExpression(); - } - function parseComparisonExpression() { - let left = parseAdditiveExpression(); - while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) { - const operator = tokens[current]; - ++current; - const right = parseAdditiveExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; - } - function parseAdditiveExpression() { - let left = parseMultiplicativeExpression(); - while (is(TOKEN_TYPES.AdditiveBinaryOperator)) { - const operator = tokens[current]; - ++current; - const right = parseMultiplicativeExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; - } - function parseCallMemberExpression() { - const member = parseMemberExpression(); - if (is(TOKEN_TYPES.OpenParen)) { - return parseCallExpression(member); - } - return member; - } - function parseCallExpression(callee) { - let callExpression = new CallExpression(callee, parseArgs()); - if (is(TOKEN_TYPES.OpenParen)) { - callExpression = parseCallExpression(callExpression); - } - return callExpression; - } - function parseArgs() { - expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list"); - const args = is(TOKEN_TYPES.CloseParen) ? [] : parseArgumentsList(); - expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"); - return args; - } - function parseArgumentsList() { - const args = [parseExpression()]; - while (is(TOKEN_TYPES.Comma)) { - ++current; - args.push(parseExpression()); - } - return args; - } - function parseMemberExpressionArgumentsList() { - const slices = []; - let isSlice = false; - while (!is(TOKEN_TYPES.CloseSquareBracket)) { - if (is(TOKEN_TYPES.Colon)) { - slices.push(void 0); - ++current; - isSlice = true; - } else { - slices.push(parseExpression()); - if (is(TOKEN_TYPES.Colon)) { - ++current; - isSlice = true; - } - } - } - if (slices.length === 0) { - throw new SyntaxError(`Expected at least one argument for member/slice expression`); - } - if (isSlice) { - if (slices.length > 3) { - throw new SyntaxError(`Expected 0-3 arguments for slice expression`); - } - return new SliceExpression(...slices); - } - return slices[0]; - } - function parseMemberExpression() { - let object = parsePrimaryExpression(); - while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) { - const operator = tokens[current]; - ++current; - let property; - const computed = operator.type !== TOKEN_TYPES.Dot; - if (computed) { - property = parseMemberExpressionArgumentsList(); - expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket"); - } else { - property = parsePrimaryExpression(); - if (property.type !== "Identifier") { - throw new SyntaxError(`Expected identifier following dot operator`); - } - } - object = new MemberExpression(object, property, computed); - } - return object; - } - function parseMultiplicativeExpression() { - let left = parseFilterExpression(); - while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) { - const operator = tokens[current]; - ++current; - const right = parseFilterExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; - } - function parseFilterExpression() { - let operand = parseCallMemberExpression(); - while (is(TOKEN_TYPES.Pipe)) { - ++current; - const filter = parsePrimaryExpression(); - if (!(filter instanceof Identifier)) { - throw new SyntaxError(`Expected identifier for the filter`); - } - operand = new FilterExpression(operand, filter); - } - return operand; - } - function parsePrimaryExpression() { - const token = tokens[current]; - switch (token.type) { - case TOKEN_TYPES.NumericLiteral: - ++current; - return new NumericLiteral(Number(token.value)); - case TOKEN_TYPES.StringLiteral: - ++current; - return new StringLiteral(token.value); - case TOKEN_TYPES.BooleanLiteral: - ++current; - return new BooleanLiteral(token.value === "true"); - case TOKEN_TYPES.Identifier: - ++current; - return new Identifier(token.value); - case TOKEN_TYPES.OpenParen: { - ++current; - const expression = parseExpression(); - if (tokens[current].type !== TOKEN_TYPES.CloseParen) { - throw new SyntaxError("Expected closing parenthesis"); - } - ++current; - return expression; - } - default: - throw new SyntaxError(`Unexpected token: ${token.type}`); - } - } - while (current < tokens.length) { - program.body.push(parseAny()); - } - return program; - } - function slice(array, start, stop, step = 1) { - const direction = Math.sign(step); - if (direction >= 0) { - start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length); - stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length); - } else { - start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1); - stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1); - } - const result = []; - for (let i = start; direction * i < direction * stop; i += step) { - result.push(array[i]); - } - return result; - } - var RuntimeValue = class { - type = "RuntimeValue"; - value; - /** - * A collection of built-in functions for this type. - */ - builtins = /* @__PURE__ */ new Map(); - /** - * Creates a new RuntimeValue. - */ - constructor(value = void 0) { - this.value = value; - } - /** - * Determines truthiness or falsiness of the runtime value. - * This function should be overridden by subclasses if it has custom truthiness criteria. - * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise. - */ - __bool__() { - return new BooleanValue(!!this.value); - } - }; - var NumericValue = class extends RuntimeValue { - type = "NumericValue"; - }; - var StringValue = class extends RuntimeValue { - type = "StringValue"; - builtins = /* @__PURE__ */ new Map([ - [ - "upper", - new FunctionValue(() => { - return new StringValue(this.value.toUpperCase()); - }) - ], - [ - "lower", - new FunctionValue(() => { - return new StringValue(this.value.toLowerCase()); - }) - ], - [ - "strip", - new FunctionValue(() => { - return new StringValue(this.value.trim()); - }) - ], - ["length", new NumericValue(this.value.length)] - ]); - }; - var BooleanValue = class extends RuntimeValue { - type = "BooleanValue"; - }; - var ObjectValue = class extends RuntimeValue { - type = "ObjectValue"; - /** - * NOTE: necessary to override since all JavaScript arrays are considered truthy, - * while only non-empty Python arrays are consider truthy. - * - * e.g., - * - JavaScript: {} && 5 -> 5 - * - Python: {} and 5 -> {} - */ - __bool__() { - return new BooleanValue(this.value.size > 0); - } - }; - var ArrayValue = class extends RuntimeValue { - type = "ArrayValue"; - builtins = /* @__PURE__ */ new Map([["length", new NumericValue(this.value.length)]]); - /** - * NOTE: necessary to override since all JavaScript arrays are considered truthy, - * while only non-empty Python arrays are consider truthy. - * - * e.g., - * - JavaScript: [] && 5 -> 5 - * - Python: [] and 5 -> [] - */ - __bool__() { - return new BooleanValue(this.value.length > 0); - } - }; - var FunctionValue = class extends RuntimeValue { - type = "FunctionValue"; - }; - var NullValue = class extends RuntimeValue { - type = "NullValue"; - }; - var UndefinedValue = class extends RuntimeValue { - type = "UndefinedValue"; - }; - var Environment = class { - constructor(parent) { - this.parent = parent; - } - /** - * The variables declared in this environment. - */ - variables = /* @__PURE__ */ new Map(); - /** - * Set the value of a variable in the current environment. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - set(name2, value) { - return this.declareVariable(name2, convertToRuntimeValues(value)); - } - declareVariable(name2, value) { - if (this.variables.has(name2)) { - throw new SyntaxError(`Variable already declared: ${name2}`); - } - this.variables.set(name2, value); - return value; - } - // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue { - // const env = this.resolve(name); - // env.variables.set(name, value); - // return value; - // } - /** - * Declare if doesn't exist, assign otherwise. - */ - setVariable(name2, value) { - let env3; - try { - env3 = this.resolve(name2); - } catch { - } - (env3 ?? this).variables.set(name2, value); - return value; - } - /** - * Resolve the environment in which the variable is declared. - * @param {string} name The name of the variable. - * @returns {Environment} The environment in which the variable is declared. - */ - resolve(name2) { - if (this.variables.has(name2)) { - return this; - } - if (this.parent) { - return this.parent.resolve(name2); - } - throw new Error(`Unknown variable: ${name2}`); - } - lookupVariable(name2) { - return this.resolve(name2).variables.get(name2) ?? new NullValue(); - } - }; - var Interpreter = class { - global; - constructor(env3) { - this.global = env3 ?? new Environment(); - } - /** - * Run the program. - */ - run(program) { - return this.evaluate(program, this.global); - } - /** - * Evaulates expressions following the binary operation type. - */ - evaluateBinaryExpression(node, environment) { - const left = this.evaluate(node.left, environment); - const right = this.evaluate(node.right, environment); - switch (node.operator.value) { - case "==": - return new BooleanValue(left.value == right.value); - case "!=": - return new BooleanValue(left.value != right.value); - case "and": - return left.__bool__().value ? right : left; - case "or": - return left.__bool__().value ? left : right; - } - if (left instanceof UndefinedValue || right instanceof UndefinedValue) { - throw new Error("Cannot perform operation on undefined values"); - } else if (left instanceof NullValue || right instanceof NullValue) { - throw new Error("Cannot perform operation on null values"); - } else if (left instanceof NumericValue && right instanceof NumericValue) { - switch (node.operator.value) { - case "+": - return new NumericValue(left.value + right.value); - case "-": - return new NumericValue(left.value - right.value); - case "*": - return new NumericValue(left.value * right.value); - case "/": - return new NumericValue(left.value / right.value); - case "%": - return new NumericValue(left.value % right.value); - case "<": - return new BooleanValue(left.value < right.value); - case ">": - return new BooleanValue(left.value > right.value); - case ">=": - return new BooleanValue(left.value >= right.value); - case "<=": - return new BooleanValue(left.value <= right.value); - } - } else if (right instanceof ArrayValue) { - const member = right.value.find((x) => x.value === left.value) !== void 0; - switch (node.operator.value) { - case "in": - return new BooleanValue(member); - case "not in": - return new BooleanValue(!member); - } - } - if (left instanceof StringValue || right instanceof StringValue) { - switch (node.operator.value) { - case "+": - return new StringValue(left.value.toString() + right.value.toString()); - } - } - if (left instanceof StringValue && right instanceof StringValue) { - switch (node.operator.value) { - case "in": - return new BooleanValue(right.value.includes(left.value)); - case "not in": - return new BooleanValue(!right.value.includes(left.value)); - } - } - throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`); - } - /** - * Evaulates expressions following the filter operation type. - */ - evaluateFilterExpression(node, environment) { - const operand = this.evaluate(node.operand, environment); - if (operand instanceof ArrayValue) { - switch (node.filter.value) { - case "first": - return operand.value[0]; - case "last": - return operand.value[operand.value.length - 1]; - case "length": - return new NumericValue(operand.value.length); - case "reverse": - return new ArrayValue(operand.value.reverse()); - case "sort": - return new ArrayValue( - operand.value.sort((a, b) => { - if (a.type !== b.type) { - throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`); - } - switch (a.type) { - case "NumericValue": - return a.value - b.value; - case "StringValue": - return a.value.localeCompare(b.value); - default: - throw new Error(`Cannot compare type: ${a.type}`); - } - }) - ); - default: - throw new Error(`Unknown filter: ${node.filter.value}`); - } - } - throw new Error(`Cannot apply filter to type: ${operand.type}`); - } - /** - * Evaulates expressions following the unary operation type. - */ - evaluateUnaryExpression(node, environment) { - const argument = this.evaluate(node.argument, environment); - switch (node.operator.value) { - case "not": - return new BooleanValue(!argument.value); - default: - throw new SyntaxError(`Unknown operator: ${node.operator.value}`); - } - } - evalProgram(program, environment) { - return this.evaluateBlock(program.body, environment); - } - evaluateBlock(statements, environment) { - let result = ""; - for (const statement of statements) { - const lastEvaluated = this.evaluate(statement, environment); - if (lastEvaluated.type !== "NullValue") { - result += lastEvaluated.value; - } - } - result = result.replace(/^\n/, ""); - return new StringValue(result); - } - evaluateIdentifier(node, environment) { - return environment.lookupVariable(node.value); - } - evaluateCallExpression(expr, environment) { - const args = expr.args.map((arg) => this.evaluate(arg, environment)); - const fn = this.evaluate(expr.callee, environment); - if (fn.type !== "FunctionValue") { - throw new Error(`Cannot call something that is not a function: got ${fn.type}`); - } - return fn.value(args, environment); - } - evaluateSliceExpression(object, expr, environment) { - if (!(object instanceof ArrayValue || object instanceof StringValue)) { - throw new Error("Slice object must be an array or string"); - } - const start = this.evaluate(expr.start, environment); - const stop = this.evaluate(expr.stop, environment); - const step = this.evaluate(expr.step, environment); - if (!(start instanceof NumericValue || start instanceof UndefinedValue)) { - throw new Error("Slice start must be numeric or undefined"); - } - if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) { - throw new Error("Slice stop must be numeric or undefined"); - } - if (!(step instanceof NumericValue || step instanceof UndefinedValue)) { - throw new Error("Slice step must be numeric or undefined"); - } - if (object instanceof ArrayValue) { - return new ArrayValue(slice(object.value, start.value, stop.value, step.value)); - } else { - return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join("")); - } - } - evaluateMemberExpression(expr, environment) { - const object = this.evaluate(expr.object, environment); - let property; - if (expr.computed) { - if (expr.property.type === "SliceExpression") { - return this.evaluateSliceExpression(object, expr.property, environment); - } else { - property = this.evaluate(expr.property, environment); - } - } else { - property = new StringValue(expr.property.value); - } - let value; - if (object instanceof ObjectValue) { - if (!(property instanceof StringValue)) { - throw new Error(`Cannot access property with non-string: got ${property.type}`); - } - value = object.value.get(property.value) ?? object.builtins.get(property.value); - } else if (object instanceof ArrayValue || object instanceof StringValue) { - if (property instanceof NumericValue) { - value = object.value.at(property.value); - if (object instanceof StringValue) { - value = new StringValue(object.value.at(property.value)); - } - } else if (property instanceof StringValue) { - value = object.builtins.get(property.value); - } else { - throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`); - } - } else { - if (!(property instanceof StringValue)) { - throw new Error(`Cannot access property with non-string: got ${property.type}`); - } - value = object.builtins.get(property.value); - } - if (!(value instanceof RuntimeValue)) { - throw new Error(`${object.type} has no property '${property.value}'`); - } - return value; - } - evaluateSet(node, environment) { - if (node.assignee.type !== "Identifier") { - throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`); - } - const variableName = node.assignee.value; - environment.setVariable(variableName, this.evaluate(node.value, environment)); - return new NullValue(); - } - evaluateIf(node, environment) { - const test = this.evaluate(node.test, environment); - return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment); - } - evaluateFor(node, environment) { - const scope = new Environment(environment); - const iterable = this.evaluate(node.iterable, scope); - if (!(iterable instanceof ArrayValue)) { - throw new Error(`Expected iterable type in for loop: got ${iterable.type}`); - } - let result = ""; - for (let i = 0; i < iterable.value.length; ++i) { - scope.setVariable( - "loop", - new ObjectValue( - new Map( - [ - ["index", new NumericValue(i + 1)], - ["index0", new NumericValue(i)], - ["first", new BooleanValue(i === 0)], - ["last", new BooleanValue(i === iterable.value.length - 1)], - ["length", new NumericValue(iterable.value.length)] - ].map(([key, value]) => [key, value]) - ) - ) - ); - scope.setVariable(node.loopvar.value, iterable.value[i]); - const evaluated = this.evaluateBlock(node.body, scope); - result += evaluated.value; - } - return new StringValue(result); - } - evaluate(statement, environment) { - if (statement === void 0) - return new UndefinedValue(); - switch (statement.type) { - case "Program": - return this.evalProgram(statement, environment); - case "Set": - return this.evaluateSet(statement, environment); - case "If": - return this.evaluateIf(statement, environment); - case "For": - return this.evaluateFor(statement, environment); - case "NumericLiteral": - return new NumericValue(Number(statement.value)); - case "StringLiteral": - return new StringValue(statement.value); - case "BooleanLiteral": - return new BooleanValue(statement.value); - case "Identifier": - return this.evaluateIdentifier(statement, environment); - case "CallExpression": - return this.evaluateCallExpression(statement, environment); - case "MemberExpression": - return this.evaluateMemberExpression(statement, environment); - case "UnaryExpression": - return this.evaluateUnaryExpression(statement, environment); - case "BinaryExpression": - return this.evaluateBinaryExpression(statement, environment); - case "FilterExpression": - return this.evaluateFilterExpression(statement, environment); - default: - throw new SyntaxError(`Unknown node type: ${statement.type}`); - } - } - }; - function convertToRuntimeValues(input) { - switch (typeof input) { - case "number": - return new NumericValue(input); - case "string": - return new StringValue(input); - case "boolean": - return new BooleanValue(input); - case "object": - if (input === null) { - return new NullValue(); - } else if (Array.isArray(input)) { - return new ArrayValue(input.map(convertToRuntimeValues)); - } else { - return new ObjectValue( - new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])) - ); - } - case "function": - return new FunctionValue((args, _scope) => { - const result = input(...args.map((x) => x.value)) ?? null; - return convertToRuntimeValues(result); - }); - default: - throw new Error(`Cannot convert to runtime value: ${input}`); - } - } - var Template = class { - parsed; - /** - * @param {string} template The template string - */ - constructor(template) { - template = template.replace(/%}\s+{%/g, "%}{%"); - const tokens = tokenize(template); - this.parsed = parse(tokens); - } - render(items) { - const env3 = new Environment(); - env3.set("false", false); - env3.set("true", true); - env3.set("raise_exception", (args) => { - throw new Error(args); - }); - for (const [key, value] of Object.entries(items)) { - env3.set(key, value); - } - const interpreter = new Interpreter(env3); - const result = interpreter.run(this.parsed); - return result.value; - } - }; - - // node_modules/@xenova/transformers/src/tokenizers.js - async function loadTokenizer(pretrained_model_name_or_path, options) { - const info = await Promise.all([ - getModelJSON(pretrained_model_name_or_path, "tokenizer.json", true, options), - getModelJSON(pretrained_model_name_or_path, "tokenizer_config.json", true, options) - ]); - if (options.legacy !== null) { - info[1].legacy = options.legacy; - } - return info; - } - function regexSplit(text, regex) { - const result = []; - let prev = 0; - for (const match of text.matchAll(regex)) { - const fullMatch = match[0]; - if (prev < match.index) { - result.push(text.slice(prev, match.index)); - } - if (fullMatch.length > 0) { - result.push(fullMatch); - } - prev = match.index + fullMatch.length; - } - if (prev < text.length) { - result.push(text.slice(prev)); - } - return result; - } - function createPattern(pattern, invert = true) { - if (pattern.Regex !== void 0) { - const regex = pattern.Regex.replace(/\\([#&~])/g, "$1"); - return new RegExp(regex, "gu"); - } else if (pattern.String !== void 0) { - const escaped = escapeRegExp(pattern.String); - return new RegExp(invert ? escaped : `(${escaped})`, "gu"); - } else { - console.warn("Unknown pattern type:", pattern); - return null; - } - } - function objectToMap(obj) { - return new Map(Object.entries(obj)); - } - function prepareTensorForDecode(tensor) { - const dims = tensor.dims; - switch (dims.length) { - case 1: - return tensor.tolist(); - case 2: - if (dims[0] !== 1) { - throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs."); - } - return tensor.tolist()[0]; - default: - throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`); - } - } - function clean_up_tokenization(text) { - return text.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 remove_accents(text) { - return text.replace(/[\u0300-\u036f]/g, ""); - } - function lowercase_and_remove_accent(text) { - return remove_accents(text.toLowerCase()); - } - function fuse(arr, value, mapping) { - const fused = []; - let i = 0; - while (i < arr.length) { - fused.push(arr[i]); - if ((mapping.get(arr[i]) ?? value) !== value) { - ++i; - continue; - } - while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) { - ++i; - } - } - return fused; - } - function whitespace_split(text) { - return text.match(/\S+/g) || []; - } - var PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E"; - var AddedToken = class { - /** - * Creates a new instance of AddedToken. - * @param {Object} config Added token configuration object. - * @param {string} config.content The content of the added token. - * @param {number} config.id The id of the added token. - * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. - * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. - * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. - * @param {boolean} [config.normalized=false] Whether this token should be normalized. - * @param {boolean} [config.special=false] Whether this token is special. - */ - constructor(config) { - this.content = config.content; - this.id = config.id; - this.single_word = config.single_word ?? false; - this.lstrip = config.lstrip ?? false; - this.rstrip = config.rstrip ?? false; - this.special = config.special ?? false; - this.normalized = config.normalized ?? null; - } - }; - var TokenizerModel = class extends Callable { - /** - * Creates a new instance of TokenizerModel. - * @param {Object} config The configuration object for the TokenizerModel. - */ - constructor(config) { - super(); - this.config = config; - this.vocab = []; - this.tokens_to_ids = /* @__PURE__ */ 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 ?? false; - } - /** - * Instantiates a new TokenizerModel instance based on the configuration object provided. - * @param {Object} config The configuration object for the TokenizerModel. - * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. - * @returns {TokenizerModel} A new instance of a TokenizerModel. - * @throws Will throw an error if the TokenizerModel type in the config is not recognized. - */ - static fromConfig(config, ...args) { - switch (config.type) { - case "WordPiece": - return new WordPieceTokenizer(config); - case "Unigram": - return new Unigram(config, ...args); - case "BPE": - return new BPE(config); - default: - if (config.vocab) { - return new LegacyTokenizerModel(config, ...args); - } - throw new Error(`Unknown TokenizerModel type: ${config.type}`); - } - } - /** - * Internal function to call the TokenizerModel instance. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} The encoded token IDs. - */ - _call(tokens) { - let ids = this.encode(tokens); - if (this.fuse_unk) { - ids = fuse(ids, this.unk_token_id, this.tokens_to_ids); - } - return ids; - } - /** - * Encodes a list of tokens into a list of token IDs. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} The encoded tokens. - * @throws Will throw an error if not implemented in a subclass. - */ - encode(tokens) { - throw Error("encode should be implemented in subclass."); - } - /** - * Converts a list of tokens into a list of token IDs. - * @param {string[]} tokens The tokens to convert. - * @returns {number[]} The converted token IDs. - */ - convert_tokens_to_ids(tokens) { - return tokens.map((t) => this.tokens_to_ids.get(t) ?? this.unk_token_id); - } - /** - * Converts a list of token IDs into a list of tokens. - * @param {number[]} ids The token IDs to convert. - * @returns {string[]} The converted tokens. - */ - convert_ids_to_tokens(ids) { - return ids.map((i) => this.vocab[i] ?? this.unk_token); - } - }; - var WordPieceTokenizer = class extends TokenizerModel { - /** - * @param {Object} config The configuration object. - * @param {Object} config.vocab A mapping of tokens to ids. - * @param {string} config.unk_token The unknown token string. - * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords. - * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word. - */ - constructor(config) { - super(config); - this.tokens_to_ids = objectToMap(config.vocab); - this.unk_token_id = this.tokens_to_ids.get(config.unk_token); - this.unk_token = config.unk_token; - this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; - this.vocab = new Array(this.tokens_to_ids.size); - for (const [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } - } - /** - * Encodes an array of tokens using WordPiece encoding. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} An array of encoded tokens. - */ - encode(tokens) { - const outputTokens = []; - for (const token of tokens) { - const chars = [...token]; - if (chars.length > this.max_input_chars_per_word) { - outputTokens.push(this.unk_token); - continue; - } - let isUnknown = false; - let start = 0; - const subTokens = []; - while (start < chars.length) { - let end = chars.length; - let currentSubstring = null; - while (start < end) { - let substr = chars.slice(start, end).join(""); - if (start > 0) { - substr = this.config.continuing_subword_prefix + substr; - } - if (this.tokens_to_ids.has(substr)) { - currentSubstring = substr; - break; - } - --end; - } - if (currentSubstring === null) { - isUnknown = true; - break; - } - subTokens.push(currentSubstring); - start = end; - } - if (isUnknown) { - outputTokens.push(this.unk_token); - } else { - outputTokens.push(...subTokens); - } - } - return outputTokens; - } - }; - var Unigram = class extends TokenizerModel { - /** - * Create a new Unigram tokenizer model. - * @param {Object} config The configuration object for the Unigram model. - * @param {number} config.unk_id The ID of the unknown token - * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores. - * @param {Object} moreConfig Additional configuration object for the Unigram model. - */ - constructor(config, moreConfig) { - super(config); - const vocabSize = config.vocab.length; - this.vocab = new Array(vocabSize); - this.scores = new Array(vocabSize); - for (let i = 0; i < vocabSize; ++i) { - const piece = config.vocab[i]; - this.vocab[i] = piece[0]; - this.scores[i] = piece[1]; - } - this.unk_token_id = config.unk_id; - this.unk_token = this.vocab[config.unk_id]; - this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i])); - this.bosToken = " "; - this.bosTokenId = this.tokens_to_ids.get(this.bosToken); - this.eosToken = moreConfig.eos_token; - this.eosTokenId = this.tokens_to_ids.get(this.eosToken); - this.unkToken = this.vocab[this.unk_token_id]; - this.minScore = min(this.scores)[0]; - this.unkScore = this.minScore - 10; - this.scores[this.unk_token_id] = this.unkScore; - this.trie = new CharTrie(); - this.trie.extend(this.vocab); - this.fuse_unk = true; - } - /** - * Populates lattice nodes. - * @param {TokenLattice} lattice The token lattice to populate with nodes. - */ - populateNodes(lattice) { - const sentence = lattice.sentence; - const len = sentence.length; - let beginPos = 0; - while (beginPos < len) { - const mblen = 1; - let hasSingleNode = false; - const tokens = []; - for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) { - tokens.push(token); - const tokenId = this.tokens_to_ids.get(token); - const tokenScore = this.scores[tokenId]; - const n = token.length; - lattice.insert(beginPos, n, tokenScore, tokenId); - if (!hasSingleNode && n === mblen) { - hasSingleNode = true; - } - } - if (!hasSingleNode) { - lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id); - } - beginPos += mblen; - } - } - /** - * Encodes an array of tokens into an array of subtokens using the unigram model. - * - * @param {string} normalized The normalized string. - * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model. - */ - tokenize(normalized) { - const lattice = new TokenLattice(normalized, this.bosTokenId, this.eosTokenId); - this.populateNodes(lattice); - return lattice.tokens(); - } - /** - * Encodes an array of tokens using Unigram encoding. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} An array of encoded tokens. - */ - encode(tokens) { - const toReturn = []; - for (const token of tokens) { - const tokenized = this.tokenize(token); - toReturn.push(...tokenized); - } - return toReturn; - } - }; - var BYTES_TO_UNICODE = (() => { - const bs = [ - ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)), - ...Array.from({ length: "\xAC".charCodeAt(0) - "\xA1".charCodeAt(0) + 1 }, (_, i) => i + "\xA1".charCodeAt(0)), - ...Array.from({ length: "\xFF".charCodeAt(0) - "\xAE".charCodeAt(0) + 1 }, (_, i) => i + "\xAE".charCodeAt(0)) - ]; - const cs = bs.slice(); - let n = 0; - for (let b = 0; b < 256; ++b) { - if (!bs.includes(b)) { - bs.push(b); - cs.push(256 + n); - n += 1; - } - } - const ccs = cs.map((n2) => String.fromCharCode(n2)); - return Object.fromEntries(bs.map((b, i) => [b, ccs[i]])); - })(); - var UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE); - var BPE = class extends TokenizerModel { - /** - * Create a BPE instance. - * @param {Object} config The configuration object for BPE. - * @param {Object} config.vocab A mapping of tokens to ids. - * @param {string} config.unk_token The unknown token used for out of vocabulary words. - * @param {string} config.end_of_word_suffix The suffix to place at the end of each word. - * @param {string} [config.continuing_subword_suffix] The suffix to insert between words. - * @param {Array} config.merges An array of BPE merges as strings. - */ - constructor(config) { - super(config); - this.BPE_SPLIT_TOKEN = " "; - this.tokens_to_ids = objectToMap(config.vocab); - this.unk_token_id = this.tokens_to_ids.get(config.unk_token); - this.unk_token = config.unk_token; - this.vocab = new Array(this.tokens_to_ids.size); - for (const [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } - this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i])); - this.merges = config.merges.map((x) => x.split(this.BPE_SPLIT_TOKEN)); - this.end_of_word_suffix = config.end_of_word_suffix; - this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; - this.byte_fallback = this.config.byte_fallback ?? false; - if (this.byte_fallback) { - this.text_encoder = new TextEncoder(); - } - this.cache = /* @__PURE__ */ new Map(); - } - /** - * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority - * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. - * @param {string} token The token to encode. - * @returns {string[]} The BPE encoded tokens. - */ - bpe(token) { - if (token.length === 0) { - return []; - } - const cached = this.cache.get(token); - if (cached !== void 0) { - return cached; - } - const word = Array.from(token); - if (this.end_of_word_suffix) { - word[word.length - 1] += this.end_of_word_suffix; - } - let result = []; - if (word.length > 1) { - const queue = new PriorityQueue((a, b) => a.score < b.score); - let startingNode = { - token: word[0], - bias: 0, - prev: null, - next: null - }; - let previousNode = startingNode; - for (let i = 1; i < word.length; ++i) { - const currentNode = { - bias: i / word.length, - // Add fractional component to break ties - token: word[i], - prev: previousNode, - next: null - }; - previousNode.next = currentNode; - this._add_node(queue, previousNode); - previousNode = currentNode; - } - while (!queue.isEmpty()) { - const node = queue.pop(); - if (node.deleted || !node.next || node.next.deleted) - continue; - node.deleted = true; - node.next.deleted = true; - if (node.prev) { - const newPreviousNode = { ...node.prev }; - node.prev.deleted = true; - node.prev = newPreviousNode; - if (newPreviousNode.prev) { - newPreviousNode.prev.next = newPreviousNode; - } else { - startingNode = newPreviousNode; - } - } - const merged = { - token: node.token + node.next.token, - bias: node.bias, - prev: node.prev, - next: node.next.next - }; - if (merged.prev) { - merged.prev.next = merged; - this._add_node(queue, merged.prev); - } else { - startingNode = merged; - } - if (merged.next) { - merged.next.prev = merged; - this._add_node(queue, merged); - } - } - for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) { - result.push(currentNode.token); - } - } else { - result = word; - } - if (this.continuing_subword_suffix) { - for (let i = 0; i < result.length - 1; ++i) { - result[i] += this.continuing_subword_suffix; - } - } - this.cache.set(token, result); - return result; - } - /** - * Helper function to add a node to the priority queue. - * @param {PriorityQueue} queue - * @param {BPENode} node - * @private - */ - _add_node(queue, node) { - const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token); - if (rank !== void 0) { - node.score = rank + node.bias; - queue.push(node); - } - } - /** - * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. - * @param {string[]} tokens The input sequence of tokens to encode. - * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. - */ - encode(tokens) { - const outputTokens = []; - for (const token of tokens) { - const bpe_token_list = this.bpe(token); - for (const t of bpe_token_list) { - if (this.tokens_to_ids.has(t)) { - outputTokens.push(t); - } else { - if (this.byte_fallback) { - outputTokens.push( - ...Array.from(this.text_encoder.encode(t)).map((x) => `<0x${x.toString(16).toUpperCase().padStart(2, "0")}>`) - ); - } else { - outputTokens.push(this.unk_token); - } - } - } - } - return outputTokens; - } - }; - var LegacyTokenizerModel = class extends TokenizerModel { - /** - * Create a LegacyTokenizerModel instance. - * @param {Object} config The configuration object for LegacyTokenizerModel. - * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids. - * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model. - */ - constructor(config, moreConfig) { - super(config); - this.tokens_to_ids = objectToMap( - moreConfig.target_lang ? config.vocab[moreConfig.target_lang] : config.vocab - ); - this.bos_token = moreConfig.bos_token; - this.bos_token_id = this.tokens_to_ids.get(this.bos_token); - this.eos_token = moreConfig.eos_token; - this.eos_token_id = this.tokens_to_ids.get(this.eos_token); - this.pad_token = moreConfig.pad_token; - this.pad_token_id = this.tokens_to_ids.get(this.pad_token); - this.unk_token = moreConfig.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 [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } - } - encode(tokens) { - return tokens; - } - }; - var Normalizer = class extends Callable { - /** - * @param {Object} config The configuration object for the normalizer. - */ - constructor(config) { - super(); - this.config = config; - } - /** - * Factory method for creating normalizers from config objects. - * @static - * @param {Object} config The configuration object for the normalizer. - * @returns {Normalizer} A Normalizer object. - * @throws {Error} If an unknown Normalizer type is specified in the config. - */ - static fromConfig(config) { - if (config === null) - return null; - switch (config.type) { - case "BertNormalizer": - return new BertNormalizer(config); - case "Precompiled": - return new Precompiled(config); - case "Sequence": - return new NormalizerSequence(config); - case "Replace": - return new Replace(config); - case "NFC": - return new NFC(config); - case "NFKC": - return new NFKC(config); - case "NFKD": - return new NFKD(config); - case "Strip": - return new StripNormalizer(config); - case "StripAccents": - return new StripAccents(config); - case "Lowercase": - return new Lowercase(config); - case "Prepend": - return new Prepend(config); - default: - throw new Error(`Unknown Normalizer type: ${config.type}`); - } - } - /** - * Normalize the input text. - * @abstract - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - * @throws {Error} If this method is not implemented in a subclass. - */ - normalize(text) { - throw Error("normalize should be implemented in subclass."); - } - /** - * Alias for {@link Normalizer#normalize}. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - _call(text) { - return this.normalize(text); - } - }; - var Replace = class extends Normalizer { - /** - * Normalize the input text by replacing the pattern with the content. - * @param {string} text The input text to be normalized. - * @returns {string} The normalized text after replacing the pattern with the content. - */ - normalize(text) { - const pattern = createPattern(this.config.pattern); - return pattern === null ? text : text.replaceAll(pattern, this.config.content); - } - }; - var NFC = class extends Normalizer { - /** - * Normalize the input text by applying Unicode normalization form C (NFC). - * @param {string} text The input text to be normalized. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.normalize("NFC"); - return text; - } - }; - var NFKC = class extends Normalizer { - /** - * Normalize text using NFKC normalization. - * @param {string} text The text to be normalized. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.normalize("NFKC"); - return text; - } - }; - var NFKD = class extends Normalizer { - /** - * Normalize text using NFKD normalization. - * @param {string} text The text to be normalized. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.normalize("NFKD"); - return text; - } - }; - var StripNormalizer = class extends Normalizer { - /** - * Strip leading and/or trailing whitespace from the input text. - * @param {string} text The input text. - * @returns {string} The normalized text. - */ - normalize(text) { - if (this.config.strip_left && this.config.strip_right) { - text = text.trim(); - } else { - if (this.config.strip_left) { - text = text.trimStart(); - } - if (this.config.strip_right) { - text = text.trimEnd(); - } - } - return text; - } - }; - var StripAccents = class extends Normalizer { - /** - * Remove all accents from the text. - * @param {string} text The input text. - * @returns {string} The normalized text without accents. - */ - normalize(text) { - text = remove_accents(text); - return text; - } - }; - var Lowercase = class extends Normalizer { - /** - * Lowercases the input string. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.toLowerCase(); - return text; - } - }; - var Prepend = class extends Normalizer { - /** - * Prepends the input string. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - text = this.config.prepend + text; - return text; - } - }; - var NormalizerSequence = class extends Normalizer { - /** - * Create a new instance of NormalizerSequence. - * @param {Object} config The configuration object. - * @param {Object[]} config.normalizers An array of Normalizer configuration objects. - */ - constructor(config) { - super(config); - this.normalizers = config.normalizers.map((x) => Normalizer.fromConfig(x)); - } - /** - * Apply a sequence of Normalizers to the input text. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - return this.normalizers.reduce((t, normalizer) => { - return normalizer.normalize(t); - }, text); - } - }; - var BertNormalizer = class extends Normalizer { - /** - * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. - * - * @param {string} text The input text to tokenize. - * @returns {string} The tokenized text with whitespace added around CJK characters. - */ - _tokenize_chinese_chars(text) { - const output = []; - for (let i = 0; i < text.length; ++i) { - const char = text[i]; - const cp = char.charCodeAt(0); - if (this._is_chinese_char(cp)) { - output.push(" "); - output.push(char); - output.push(" "); - } else { - output.push(char); - } - } - return output.join(""); - } - /** - * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character. - * - * A "chinese character" is defined as anything in the CJK Unicode block: - * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) - * - * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name. - * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana. - * Those alphabets are used to write space-separated words, so they are not treated specially - * and are handled like all other languages. - * - * @param {number} cp The Unicode codepoint to check. - * @returns {boolean} True if the codepoint represents a CJK character, false otherwise. - */ - _is_chinese_char(cp) { - return cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103; - } - /** - * Strips accents from the given text. - * @param {string} text The text to strip accents from. - * @returns {string} The text with accents removed. - */ - stripAccents(text) { - return text.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); - } - /** - * Checks whether `char` is a control character. - * @param {string} char The character to check. - * @returns {boolean} Whether `char` is a control character. - * @private - */ - _is_control(char) { - switch (char) { - case " ": - case "\n": - case "\r": - return false; - default: - return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); - } - } - /** - * Performs invalid character removal and whitespace cleanup on text. - * @param {string} text The text to clean. - * @returns {string} The cleaned text. - * @private - */ - _clean_text(text) { - const output = []; - for (const char of text) { - const cp = char.charCodeAt(0); - if (cp === 0 || cp === 65533 || this._is_control(char)) { - continue; - } - if (/^\s$/.test(char)) { - output.push(" "); - } else { - output.push(char); - } - } - return output.join(""); - } - /** - * Normalizes the given text based on the configuration. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - if (this.config.clean_text) { - text = this._clean_text(text); - } - if (this.config.handle_chinese_chars) { - text = this._tokenize_chinese_chars(text); - } - if (this.config.lowercase) { - text = text.toLowerCase(); - if (this.config.strip_accents !== false) { - text = this.stripAccents(text); - } - } else if (this.config.strip_accents) { - text = this.stripAccents(text); - } - return text; - } - }; - var PreTokenizer = class extends Callable { - /** - * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. - * - * @static - * @param {Object} config A configuration object for the pre-tokenizer. - * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. - * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. - */ - static fromConfig(config) { - if (config === null) - return null; - switch (config.type) { - case "BertPreTokenizer": - return new BertPreTokenizer(config); - case "Sequence": - return new PreTokenizerSequence(config); - case "WhitespaceSplit": - return new WhitespaceSplit(config); - case "Metaspace": - return new MetaspacePreTokenizer(config); - case "ByteLevel": - return new ByteLevelPreTokenizer(config); - case "Split": - return new SplitPreTokenizer(config); - case "Punctuation": - return new PunctuationPreTokenizer(config); - case "Digits": - return new DigitsPreTokenizer(config); - case "Replace": - return new ReplacePreTokenizer(config); - default: - throw new Error(`Unknown PreTokenizer type: ${config.type}`); - } - } - /** - * Method that should be implemented by subclasses to define the specific pre-tokenization logic. - * - * @abstract - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} The pre-tokenized text. - * @throws {Error} If the method is not implemented in the subclass. - */ - pre_tokenize_text(text, options) { - throw Error("pre_tokenize_text should be implemented in subclass."); - } - /** - * Tokenizes the given text into pre-tokens. - * @param {string|string[]} text The text or array of texts to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of pre-tokens. - */ - pre_tokenize(text, options) { - return (Array.isArray(text) ? text.map((x) => this.pre_tokenize_text(x, options)) : this.pre_tokenize_text(text, options)).flat(); - } - /** - * Alias for {@link PreTokenizer#pre_tokenize}. - * @param {string|string[]} text The text or array of texts to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of pre-tokens. - */ - _call(text, options) { - return this.pre_tokenize(text, options); - } - }; - var BertPreTokenizer = class extends PreTokenizer { - /** - * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme - * similar to that used in the original implementation of BERT. - * - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, "gu"); - } - /** - * Tokenizes a single text using the BERT pre-tokenization scheme. - * - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.trim().match(this.pattern) || []; - } - }; - var ByteLevelPreTokenizer = class extends PreTokenizer { - /** - * Creates a new instance of the `ByteLevelPreTokenizer` class. - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - this.config = config; - this.add_prefix_space = this.config.add_prefix_space; - this.trim_offsets = this.config.trim_offsets; - this.use_regex = this.config.use_regex ?? true; - 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 = BYTES_TO_UNICODE; - this.text_encoder = new TextEncoder(); - } - /** - * Tokenizes a single piece of text using byte-level tokenization. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - if (this.add_prefix_space && !text.startsWith(" ")) { - text = " " + text; - } - const tokens = this.use_regex ? text.match(this.pattern) || [] : [text]; - return tokens.map( - (token) => Array.from(this.text_encoder.encode(token), (byte) => this.byte_encoder[byte]).join("") - ); - } - }; - var SplitPreTokenizer = class extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. - * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string. - * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex. - * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. - * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern. - */ - constructor(config) { - super(); - this.config = config; - this.pattern = createPattern(this.config.pattern, this.config.invert); - } - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - if (this.pattern === null) { - return []; - } - if (this.config.invert) { - return text.match(this.pattern) || []; - } else { - return regexSplit(text, this.pattern); - } - } - }; - var PunctuationPreTokenizer = class extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. - */ - constructor(config) { - super(); - this.config = config; - this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, "gu"); - } - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.match(this.pattern) || []; - } - }; - var DigitsPreTokenizer = class extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {boolean} config.individual_digits Whether to split on individual digits. - */ - constructor(config) { - super(); - this.config = config; - const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`; - this.pattern = new RegExp(digit_pattern, "gu"); - } - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.match(this.pattern) || []; - } - }; - var PostProcessor = class extends Callable { - /** - * @param {Object} config The configuration for the post-processor. - */ - constructor(config) { - super(); - this.config = config; - } - /** - * Factory method to create a PostProcessor object from a configuration object. - * - * @param {Object} config Configuration object representing a PostProcessor. - * @returns {PostProcessor} A PostProcessor object created from the given configuration. - * @throws {Error} If an unknown PostProcessor type is encountered. - */ - static fromConfig(config) { - if (config === null) - return null; - switch (config.type) { - case "TemplateProcessing": - return new TemplateProcessing(config); - case "ByteLevel": - return new ByteLevelPostProcessor(config); - case "RobertaProcessing": - return new RobertaProcessing(config); - case "BertProcessing": - return new BertProcessing(config); - default: - throw new Error(`Unknown PostProcessor type: ${config.type}`); - } - } - /** - * Method to be implemented in subclass to apply post-processing on the given tokens. - * - * @param {Array} tokens The input tokens to be post-processed. - * @param {...*} args Additional arguments required by the post-processing logic. - * @returns {PostProcessedOutput} The post-processed tokens. - * @throws {Error} If the method is not implemented in subclass. - */ - post_process(tokens, ...args) { - throw Error("post_process should be implemented in subclass."); - } - /** - * Alias for {@link PostProcessor#post_process}. - * @param {Array} tokens The text or array of texts to post-process. - * @param {...*} args Additional arguments required by the post-processing logic. - * @returns {PostProcessedOutput} The post-processed tokens. - */ - _call(tokens, ...args) { - return this.post_process(tokens, ...args); - } - }; - var BertProcessing = class extends PostProcessor { - /** - * @param {Object} config The configuration for the post-processor. - * @param {string[]} config.cls The special tokens to add to the beginning of the input. - * @param {string[]} config.sep The special tokens to add to the end of the input. - */ - constructor(config) { - super(config); - this.cls = config.cls[0]; - this.sep = config.sep[0]; - } - /** - * Adds the special tokens to the beginning and end of the input. - * @param {string[]} tokens The input tokens. - * @param {string[]} [tokens_pair=null] An optional second set of input tokens. - * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end. - */ - post_process(tokens, tokens_pair = null, { - add_special_tokens = true - } = {}) { - if (add_special_tokens) { - tokens = mergeArrays([this.cls], tokens, [this.sep]); - } - let token_type_ids = new Array(tokens.length).fill(0); - if (tokens_pair !== null) { - const middle = add_special_tokens && this instanceof RobertaProcessing ? [this.sep] : []; - const after = add_special_tokens ? [this.sep] : []; - tokens = mergeArrays(tokens, middle, tokens_pair, after); - token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1)); - } - return { tokens, token_type_ids }; - } - }; - var RobertaProcessing = class extends BertProcessing { - }; - var TemplateProcessing = class extends PostProcessor { - /** - * Creates a new instance of `TemplateProcessing`. - * @param {Object} config The configuration options for the post processor. - * @param {Array} config.single The template for a single sequence of tokens. - * @param {Array} config.pair The template for a pair of sequences of tokens. - */ - constructor(config) { - super(config); - this.single = config.single; - this.pair = config.pair; - } - /** - * Replaces special tokens in the template with actual tokens. - * @param {string[]} tokens The list of tokens for the first sequence. - * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). - * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens. - */ - post_process(tokens, tokens_pair = null, { - add_special_tokens = true - } = {}) { - const type = tokens_pair === null ? this.single : this.pair; - let processedTokens = []; - let types = []; - for (const item of type) { - if ("SpecialToken" in item) { - if (add_special_tokens) { - processedTokens.push(item.SpecialToken.id); - types.push(item.SpecialToken.type_id); - } - } else if ("Sequence" in item) { - if (item.Sequence.id === "A") { - processedTokens = mergeArrays(processedTokens, tokens); - types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id)); - } else if (item.Sequence.id === "B") { - processedTokens = mergeArrays(processedTokens, tokens_pair); - types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id)); - } - } - } - return { tokens: processedTokens, token_type_ids: types }; - } - }; - var ByteLevelPostProcessor = class extends PostProcessor { - /** - * Post process the given tokens. - * @param {string[]} tokens The list of tokens for the first sequence. - * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). - * @returns {PostProcessedOutput} An object containing the post-processed tokens. - */ - post_process(tokens, tokens_pair = null) { - if (tokens_pair) { - tokens = mergeArrays(tokens, tokens_pair); - } - return { tokens }; - } - }; - var Decoder = class extends Callable { - /** - * Creates an instance of `Decoder`. - * - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - this.config = config; - this.added_tokens = []; - this.end_of_word_suffix = null; - this.trim_offsets = config.trim_offsets; - } - /** - * Creates a decoder instance based on the provided configuration. - * - * @param {Object} config The configuration object. - * @returns {Decoder} A decoder instance. - * @throws {Error} If an unknown decoder type is provided. - */ - static fromConfig(config) { - if (config === null) - return null; - switch (config.type) { - case "WordPiece": - return new WordPieceDecoder(config); - case "Metaspace": - return new MetaspaceDecoder(config); - case "ByteLevel": - return new ByteLevelDecoder(config); - case "Replace": - return new ReplaceDecoder(config); - case "ByteFallback": - return new ByteFallback(config); - case "Fuse": - return new FuseDecoder(config); - case "Strip": - return new StripDecoder(config); - case "Sequence": - return new DecoderSequence(config); - case "CTC": - return new CTCDecoder(config); - case "BPEDecoder": - return new BPEDecoder(config); - default: - throw new Error(`Unknown Decoder type: ${config.type}`); - } - } - /** - * Calls the `decode` method. - * - * @param {string[]} tokens The list of tokens. - * @returns {string} The decoded string. - */ - _call(tokens) { - return this.decode(tokens); - } - /** - * Decodes a list of tokens. - * @param {string[]} tokens The list of tokens. - * @returns {string} The decoded string. - */ - decode(tokens) { - return this.decode_chain(tokens).join(""); - } - /** - * Apply the decoder to a list of tokens. - * - * @param {string[]} tokens The list of tokens. - * @returns {string[]} The decoded list of tokens. - * @throws {Error} If the `decode_chain` method is not implemented in the subclass. - */ - decode_chain(tokens) { - throw Error("`decode_chain` should be implemented in subclass."); - } - }; - var ReplaceDecoder = class extends Decoder { - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const pattern = createPattern(this.config.pattern); - return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, this.config.content)); - } - }; - var ByteFallback = class extends Decoder { - constructor(config) { - super(config); - this.text_decoder = new TextDecoder(); - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const new_tokens = []; - let previous_byte_tokens = []; - for (const token of tokens) { - let bytes = null; - if (token.length === 6 && token.startsWith("<0x") && token.endsWith(">")) { - const byte = parseInt(token.slice(3, 5), 16); - if (!isNaN(byte)) { - bytes = byte; - } - } - if (bytes !== null) { - previous_byte_tokens.push(bytes); - } else { - if (previous_byte_tokens.length > 0) { - const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); - new_tokens.push(string); - previous_byte_tokens = []; - } - new_tokens.push(token); - } - } - if (previous_byte_tokens.length > 0) { - const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); - new_tokens.push(string); - previous_byte_tokens = []; - } - return new_tokens; - } - }; - var FuseDecoder = class extends Decoder { - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return [tokens.join("")]; - } - }; - var StripDecoder = class extends Decoder { - constructor(config) { - super(config); - this.content = this.config.content; - this.start = this.config.start; - this.stop = this.config.stop; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map((token) => { - let start_cut = 0; - for (let i = 0; i < this.start; ++i) { - if (token[i] === this.content) { - start_cut = i + 1; - continue; - } else { - break; - } - } - let stop_cut = token.length; - for (let i = 0; i < this.stop; ++i) { - const index = token.length - i - 1; - if (token[index] === this.content) { - stop_cut = index; - continue; - } else { - break; - } - } - return token.slice(start_cut, stop_cut); - }); - } - }; - var WordPieceDecoder = class extends Decoder { - /** - * Creates a new instance of WordPieceDecoder. - * @param {Object} config The configuration object. - * @param {string} config.prefix The prefix used for WordPiece encoding. - * @param {boolean} config.cleanup Whether to cleanup the decoded string. - */ - constructor(config) { - super(config); - this.cleanup = config.cleanup; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map((token, i) => { - if (i !== 0) { - if (token.startsWith(this.config.prefix)) { - token = token.replace(this.config.prefix, ""); - } else { - token = " " + token; - } - } - if (this.cleanup) { - token = clean_up_tokenization(token); - } - return token; - }); - } - }; - var ByteLevelDecoder = class extends Decoder { - /** - * Create a `ByteLevelDecoder` object. - * @param {Object} config Configuration object. - */ - constructor(config) { - super(config); - this.byte_decoder = UNICODE_TO_BYTES; - this.text_decoder = new TextDecoder("utf-8", { - fatal: false, - ignoreBOM: true - }); - this.end_of_word_suffix = null; - } - /** - * Convert an array of tokens to string by decoding each byte. - * @param {string[]} tokens Array of tokens to be decoded. - * @returns {string} The decoded string. - */ - convert_tokens_to_string(tokens) { - const text = tokens.join(""); - const byteArray = new Uint8Array([...text].map((c) => this.byte_decoder[c])); - const decoded_text = this.text_decoder.decode(byteArray); - return decoded_text; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const sub_texts = []; - let current_sub_text = []; - for (const token of tokens) { - if (this.added_tokens.find((x) => x.content === token) !== void 0) { - if (current_sub_text.length > 0) { - sub_texts.push(this.convert_tokens_to_string(current_sub_text)); - current_sub_text = []; - } - sub_texts.push(token); - } else { - current_sub_text.push(token); - } - } - if (current_sub_text.length > 0) { - sub_texts.push(this.convert_tokens_to_string(current_sub_text)); - } - return sub_texts; - } - }; - var CTCDecoder = class extends Decoder { - constructor(config) { - super(config); - this.pad_token = this.config.pad_token; - this.word_delimiter_token = this.config.word_delimiter_token; - this.cleanup = this.config.cleanup; - } - /** - * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. - * @param {string[]} tokens Array of tokens to be decoded. - * @returns {string} The decoded string. - */ - convert_tokens_to_string(tokens) { - if (tokens.length === 0) - return ""; - const grouped_tokens = [tokens[0]]; - for (let i = 1; i < tokens.length; ++i) { - if (tokens[i] !== grouped_tokens.at(-1)) { - grouped_tokens.push(tokens[i]); - } - } - const filtered_tokens = grouped_tokens.filter((token) => token !== this.pad_token); - let text = filtered_tokens.join(""); - if (this.cleanup) { - text = clean_up_tokenization(text).replaceAll(this.word_delimiter_token, " ").trim(); - } - return text; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return [this.convert_tokens_to_string(tokens)]; - } - }; - var DecoderSequence = class extends Decoder { - /** - * Creates a new instance of DecoderSequence. - * @param {Object} config The configuration object. - * @param {Decoder[]} config.decoders The list of decoders to apply. - */ - constructor(config) { - super(config); - this.decoders = config.decoders.map((x) => Decoder.fromConfig(x)); - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return this.decoders.reduce((toks, decoder) => { - return decoder.decode_chain(toks); - }, tokens); - } - }; - var BPEDecoder = class extends Decoder { - constructor(config) { - super(config); - this.suffix = this.config.suffix; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map((token, i) => { - return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " "); - }); - } - }; - var VitsDecoder = class extends Decoder { - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - let decoded = ""; - for (let i = 1; i < tokens.length; i += 2) { - decoded += tokens[i]; - } - return [decoded]; - } - }; - var MetaspacePreTokenizer = class extends PreTokenizer { - /** - * @param {Object} config The configuration object for the MetaspacePreTokenizer. - * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token. - * @param {string} config.replacement The character to replace spaces with. - * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character. - * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme. - */ - constructor(config) { - super(); - this.addPrefixSpace = config.add_prefix_space; - this.replacement = config.replacement; - this.strRep = config.str_rep || this.replacement; - this.prepend_scheme = config.prepend_scheme ?? "always"; - } - /** - * This method takes a string, replaces spaces with the replacement character, - * adds a prefix space if requested, and returns a new list of tokens. - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] The options for the pre-tokenization. - * @param {number} [options.section_index] The index of the section to pre-tokenize. - * @returns {string[]} A new list of pre-tokenized tokens. - */ - pre_tokenize_text(text, { - section_index = void 0 - } = {}) { - let normalized = text.replaceAll(" ", this.strRep); - if ( - // We add a prefix space if: - // (1) The addPrefixSpace option is enabled and the normalized - // token does not already start with the replacement character. - this.addPrefixSpace && !normalized.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0) - ) { - normalized = this.strRep + normalized; - } - return [normalized]; - } - }; - var MetaspaceDecoder = class extends Decoder { - /** - * Constructs a new MetaspaceDecoder object. - * @param {Object} config The configuration object for the MetaspaceDecoder. - * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string. - * @param {string} config.replacement The string to replace spaces with. - */ - constructor(config) { - super(config); - this.addPrefixSpace = config.add_prefix_space; - this.replacement = config.replacement; - } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const result = []; - for (let i = 0; i < tokens.length; ++i) { - let normalized = tokens[i].replaceAll(this.replacement, " "); - if (this.addPrefixSpace && i == 0 && normalized.startsWith(" ")) { - normalized = normalized.substring(1); - } - result.push(normalized); - } - return result; - } - }; - var Precompiled = class extends Normalizer { - /** - * Create a new instance of Precompiled normalizer. - * @param {Object} config The configuration object. - * @param {any} config.precompiled_charsmap Precompiled chars mapping. - */ - constructor(config) { - super(config); - this.charsmap = config.precompiled_charsmap; - } - /** - * Normalizes the given text by applying the precompiled charsmap. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ""); - text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, " "); - if (text.includes("\uFF5E")) { - const parts = text.split("\uFF5E"); - text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E"); - } else { - text = text.normalize("NFKC"); - } - return text; - } - }; - var PreTokenizerSequence = class extends PreTokenizer { - /** - * Creates an instance of PreTokenizerSequence. - * @param {Object} config The configuration object for the pre-tokenizer sequence. - * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations. - */ - constructor(config) { - super(); - this.tokenizers = config.pretokenizers.map((x) => PreTokenizer.fromConfig(x)); - } - /** - * Applies each pre-tokenizer in the sequence to the input text in turn. - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} The pre-tokenized text. - */ - pre_tokenize_text(text, options) { - return this.tokenizers.reduce((preTokenizedText, tokenizer) => { - return tokenizer.pre_tokenize(preTokenizedText, options); - }, [text]); - } - }; - var WhitespaceSplit = class extends PreTokenizer { - /** - * Creates an instance of WhitespaceSplit. - * @param {Object} config The configuration object for the pre-tokenizer sequence. - */ - constructor(config) { - super(); - } - /** - * Pre-tokenizes the input text by splitting it on whitespace characters. - * @param {string} text The text to be pre-tokenized. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. - */ - pre_tokenize_text(text, options) { - return whitespace_split(text); - } - }; - var ReplacePreTokenizer = class extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. - * @param {string} config.content What to replace the pattern with. - */ - constructor(config) { - super(); - this.config = config; - this.pattern = createPattern(this.config.pattern); - this.content = this.config.content; - } - /** - * Pre-tokenizes the input text by replacing certain characters. - * @param {string} text The text to be pre-tokenized. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens produced by replacing certain characters. - */ - pre_tokenize_text(text, options) { - if (this.pattern === null) { - return [text]; - } - return [text.replaceAll(this.pattern, this.config.content)]; - } - }; - var SPECIAL_TOKEN_ATTRIBUTES = [ - "bos_token", - "eos_token", - "unk_token", - "sep_token", - "pad_token", - "cls_token", - "mask_token" - // additional_special_tokens (TODO) - ]; - function padHelper(item, length, value_fn, side) { - for (const key of Object.keys(item)) { - const diff = length - item[key].length; - const value = value_fn(key); - const padData = new Array(diff).fill(value); - item[key] = side === "right" ? mergeArrays(item[key], padData) : mergeArrays(padData, item[key]); - } - } - function truncateHelper(item, length) { - for (const key of Object.keys(item)) { - item[key].length = length; - } - } - var PreTrainedTokenizer = class extends Callable { - return_token_type_ids = false; - _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + ' -' + message['content'] + '<|im_end|>' + ' -'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant -' }}{% endif %}`; - /** - * Create a new PreTrainedTokenizer instance. - * @param {Object} tokenizerJSON The JSON of the tokenizer. - * @param {Object} tokenizerConfig The config of the tokenizer. - */ - constructor(tokenizerJSON, tokenizerConfig) { - super(); - this._tokenizer_config = tokenizerConfig; - this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer); - this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer); - this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig); - this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor); - this.decoder = Decoder.fromConfig(tokenizerJSON.decoder); - this.special_tokens = []; - this.all_special_ids = []; - this.added_tokens = []; - for (const addedToken of tokenizerJSON.added_tokens) { - const token = new AddedToken(addedToken); - this.added_tokens.push(token); - this.model.tokens_to_ids.set(token.content, token.id); - this.model.vocab[token.id] = token.content; - if (token.special) { - this.special_tokens.push(token.content); - this.all_special_ids.push(token.id); - } - } - this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? []; - this.special_tokens.push(...this.additional_special_tokens); - this.special_tokens = [...new Set(this.special_tokens)]; - if (this.decoder) { - this.decoder.added_tokens = this.added_tokens; - this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; - } - this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp( - this.added_tokens.map((x) => `${x.lstrip ? "\\s*" : ""}(${escapeRegExp(x.content)})${x.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(tokenizerConfig, "unk_token"); - this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token); - this.model_max_length = tokenizerConfig.model_max_length; - this.remove_space = tokenizerConfig.remove_space; - this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true; - this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false; - this.padding_side = "right"; - this.legacy = false; - this.chat_template = tokenizerConfig.chat_template ?? null; - this._compiled_template_cache = /* @__PURE__ */ new Map(); - } - /** - * Returns the value of the first matching key in the tokenizer config object. - * @param {...string} keys One or more keys to search for in the tokenizer config object. - * @returns {string|null} The value associated with the first matching key, or null if no match is found. - * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". - */ - getToken(...keys) { - for (const key of keys) { - const item = this._tokenizer_config[key]; - if (!item) - continue; - if (typeof item === "object") { - if (item.__type === "AddedToken") { - return item.content; - } else { - throw Error(`Unknown token: ${item}`); - } - } else { - return item; - } - } - return null; - } - /** - * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. - * - * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. - * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. - * - * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. - * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main", - legacy = null - } = {}) { - const info = await loadTokenizer(pretrained_model_name_or_path, { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - legacy - }); - return new this(...info); - } - /** - * @typedef {number[]|number[][]|Tensor} BatchEncodingItem - * - * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. - * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. - * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. - * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. - */ - /** - * Encode/tokenize the given text(s). - * @param {string|string[]} text The text to tokenize. - * @param {Object} options An optional object containing the following properties: - * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. - * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. - * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. - * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. - * @returns {BatchEncoding} Object to be passed to the model. - */ - _call(text, { - text_pair = null, - add_special_tokens = true, - padding = false, - truncation = null, - max_length = null, - return_tensor = true - // Different to HF - } = {}) { - const isBatched = Array.isArray(text); - let encodedTokens; - if (isBatched) { - if (text.length === 0) { - throw Error("text array must be non-empty"); - } - if (text_pair !== null) { - if (!Array.isArray(text_pair)) { - throw Error("text_pair must also be an array"); - } else if (text.length !== text_pair.length) { - throw Error("text and text_pair must have the same length"); - } - encodedTokens = text.map( - (t, i) => this._encode_plus(t, text_pair[i], { add_special_tokens }) - ); - } else { - encodedTokens = text.map((x) => this._encode_plus(x, null, { add_special_tokens })); - } - } else { - if (text === null) { - throw Error("text may not be null"); - } - if (Array.isArray(text_pair)) { - throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array)."); - } - encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens })]; - } - if (max_length === null) { - if (padding === "max_length") { - max_length = this.model_max_length; - } else { - max_length = max(encodedTokens.map((x) => x.input_ids.length))[0]; - } - } else { - if (!truncation) { - 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.`); - } - } - max_length = Math.min(max_length, this.model_max_length); - if (padding || truncation) { - for (let i = 0; i < encodedTokens.length; ++i) { - if (encodedTokens[i].input_ids.length === max_length) { - continue; - } else if (encodedTokens[i].input_ids.length > max_length) { - if (truncation) { - truncateHelper(encodedTokens[i], max_length); - } - } else { - if (padding) { - padHelper( - encodedTokens[i], - max_length, - (key) => key === "input_ids" ? this.pad_token_id : 0, - this.padding_side - ); - } - } - } - } - const result = {}; - if (return_tensor) { - if (!(padding && truncation)) { - if (encodedTokens.some((x) => { - for (const key of Object.keys(x)) { - if (x[key].length !== encodedTokens[0][key]?.length) { - return true; - } - } - return false; - })) { - 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 dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; - for (const key of Object.keys(encodedTokens[0])) { - result[key] = new Tensor( - "int64", - BigInt64Array.from(encodedTokens.flatMap((x) => x[key]).map(BigInt)), - dims - ); - } - } else { - for (const key of Object.keys(encodedTokens[0])) { - result[key] = encodedTokens.map((x) => x[key]); - } - if (!isBatched) { - for (const key of Object.keys(result)) { - result[key] = result[key][0]; - } - } - } - return ( - /** @type {BatchEncoding} */ - result - ); - } - /** - * Encodes a single text using the preprocessor pipeline of the tokenizer. - * - * @param {string|null} text The text to encode. - * @returns {string[]|null} The encoded tokens. - */ - _encode_text(text) { - if (text === null) - return null; - const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter((x) => x) : [text]; - const tokens = sections.map((x, section_index) => { - const addedToken = this.added_tokens.find((t) => t.content === x); - if (addedToken !== void 0) { - return x; - } else { - if (this.remove_space === true) { - x = x.trim().split(/\s+/).join(" "); - } - if (this.do_lowercase_and_remove_accent) { - x = lowercase_and_remove_accent(x); - } - if (this.normalizer !== null) { - x = this.normalizer(x); - } - const sectionTokens = this.pre_tokenizer !== null ? this.pre_tokenizer(x, { - section_index - }) : [x]; - const tokens2 = this.model(sectionTokens); - return tokens2; - } - }).flat(); - return tokens; - } - /** - * Encodes a single text or a pair of texts using the model's tokenizer. - * - * @param {string} text The text to encode. - * @param {string|null} text_pair The optional second text to encode. - * @param {Object} options An optional object containing the following properties: - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @returns {EncodingSingle} An object containing the encoded text. - * @private - */ - _encode_plus(text, text_pair = null, { - add_special_tokens = true - } = {}) { - const tokens = this._encode_text(text); - const tokens2 = this._encode_text(text_pair); - const combinedTokens = this.post_processor ? this.post_processor(tokens, tokens2, { add_special_tokens }) : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) }; - const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens); - const result = { - input_ids, - attention_mask: new Array(input_ids.length).fill(1) - }; - if (this.return_token_type_ids && combinedTokens.token_type_ids) { - result.token_type_ids = combinedTokens.token_type_ids; - } - return result; - } - /** - * Encodes a single text or a pair of texts using the model's tokenizer. - * - * @param {string} text The text to encode. - * @param {string|null} text_pair The optional second text to encode. - * @param {Object} options An optional object containing the following properties: - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @returns {number[]} An array of token IDs representing the encoded text(s). - */ - encode(text, text_pair = null, { - add_special_tokens = true - } = {}) { - const { input_ids } = this._encode_plus(text, text_pair, { - add_special_tokens - }); - return input_ids; - } - /** - * Decode a batch of tokenized sequences. - * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. - * @param {Object} decode_args (Optional) Object with decoding arguments. - * @returns {string[]} List of decoded sequences. - */ - batch_decode(batch, decode_args = {}) { - if (batch instanceof Tensor) { - batch = batch.tolist(); - } - return batch.map((x) => this.decode(x, decode_args)); - } - /** - * Decodes a sequence of token IDs back to a string. - * - * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode. - * @param {Object} [decode_args={}] - * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. - * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. - * - * @returns {string} The decoded string. - * @throws {Error} If `token_ids` is not a non-empty array of integers. - */ - decode(token_ids, decode_args = {}) { - if (token_ids instanceof Tensor) { - token_ids = prepareTensorForDecode(token_ids); - } - if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) { - throw Error("token_ids must be a non-empty array of integers."); - } - return this.decode_single(token_ids, decode_args); - } - /** - * Decode a single list of token ids to a string. - * @param {number[]} token_ids List of token ids to decode - * @param {Object} decode_args Optional arguments for decoding - * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding - * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. - * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. - * @returns {string} The decoded string - */ - decode_single(token_ids, { - skip_special_tokens = false, - clean_up_tokenization_spaces = null - }) { - let tokens = this.model.convert_ids_to_tokens(token_ids); - if (skip_special_tokens) { - tokens = tokens.filter((x) => !this.special_tokens.includes(x)); - } - let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" "); - if (this.decoder && this.decoder.end_of_word_suffix) { - decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, " "); - if (skip_special_tokens) { - decoded = decoded.trim(); - } - } - if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { - decoded = clean_up_tokenization(decoded); - } - return decoded; - } - get default_chat_template() { - if (!this._warned_about_chat_template) { - console.warn( - "No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information." - ); - this._warned_about_chat_template = true; - } - return this._default_chat_template; - } - /** - * @typedef {Object} Message - * @property {string} role The role of the message (e.g., "user" or "assistant" or "system"). - * @property {string} content The content of the message. - */ - /** - * Converts a list of message objects with `"role"` and `"content"` keys to a list of token - * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to - * determine the format and control tokens to use when converting. When chat_template is None, it will fall back - * to the default_chat_template specified at the class level. - * - * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. - * - * **Example:** Applying a chat template to a conversation. - * - * ```javascript - * import { AutoTokenizer } from "@xenova/transformers"; - * - * const tokenizer = await AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1"); - * - * const chat = [ - * { "role": "user", "content": "Hello, how are you?" }, - * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, - * { "role": "user", "content": "I'd like to show off how chat templating works!" }, - * ] - * - * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); - * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" - * - * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); - * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] - * ``` - * - * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If - * this is not passed, the model's default chat template will be used instead. - * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate - * the start of an assistant message. This is useful when you want to generate a response from the model. - * Note that this argument will be passed to the chat template, and so it must be supported in the - * template for this argument to have any effect. - * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. - * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. - * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. - * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. - * If not specified, the tokenizer's `max_length` attribute will be used as a default. - * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. - * @returns {string | Tensor | number[]| number[][]} The tokenized output. - */ - apply_chat_template(conversation, { - chat_template = null, - add_generation_prompt = false, - tokenize: tokenize2 = true, - padding = false, - truncation = false, - max_length = null, - return_tensor = true - } = {}) { - chat_template ??= this.chat_template ?? this.default_chat_template; - let compiledTemplate = this._compiled_template_cache.get(chat_template); - if (compiledTemplate === void 0) { - compiledTemplate = new Template(chat_template); - this._compiled_template_cache.set(chat_template, compiledTemplate); - } - const special_tokens_map = /* @__PURE__ */ Object.create(null); - for (const key of SPECIAL_TOKEN_ATTRIBUTES) { - const value = this.getToken(key); - if (value) { - special_tokens_map[key] = value; - } - } - const rendered = compiledTemplate.render({ - messages: conversation, - add_generation_prompt, - ...special_tokens_map - }); - if (tokenize2) { - return this._call(rendered, { - add_special_tokens: false, - padding, - truncation, - max_length, - return_tensor - }).input_ids; - } - return rendered; - } - }; - var BertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var AlbertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var MobileBertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var SqueezeBertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var DebertaTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var DebertaV2Tokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var HerbertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var ConvBertTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var RoFormerTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var DistilBertTokenizer = class extends PreTrainedTokenizer { - }; - var CamembertTokenizer = class extends PreTrainedTokenizer { - }; - var XLMTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); - } - }; - var ElectraTokenizer = class extends PreTrainedTokenizer { - return_token_type_ids = true; - }; - var T5Tokenizer = class extends PreTrainedTokenizer { - }; - var GPT2Tokenizer = class extends PreTrainedTokenizer { - _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`; - }; - var BartTokenizer = class extends PreTrainedTokenizer { - }; - var MBartTokenizer = class extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; - this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)); - this.lang_to_token = (x) => x; - } - /** - * Helper function to build translation inputs for an `MBartTokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); - } - }; - var MBart50Tokenizer = class extends MBartTokenizer { - }; - var RobertaTokenizer = class extends PreTrainedTokenizer { - }; - var BloomTokenizer = class extends GPT2Tokenizer { - // NOTE: `GPT2Tokenizer` to get the correct chat template - constructor(tokenizerJSON, tokenizerConfig) { - const splitChars = ".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C"; - const patternObject = tokenizerJSON.pre_tokenizer?.pretokenizers[0]?.pattern; - if (patternObject && patternObject.Regex === ` ?[^(\\s|[${splitChars}])]+`) { - patternObject.Regex = ` ?[^\\s${splitChars}]+`; - } - super(tokenizerJSON, tokenizerConfig); - } - }; - var SPIECE_UNDERLINE = "\u2581"; - var LlamaTokenizer = class extends PreTrainedTokenizer { - _default_chat_template = `{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> -' + system_message + ' -<> - -' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> -' + content.strip() + ' -<> - -' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`; - DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."; - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.use_default_system_prompt = tokenizerConfig.use_default_system_prompt ?? false; - this.legacy = tokenizerConfig.legacy ?? true; - if (!this.legacy) { - this.normalizer = null; - this.pre_tokenizer = new MetaspacePreTokenizer({ - replacement: SPIECE_UNDERLINE, - add_prefix_space: true, - prepend_scheme: "first" - }); - } - } - /** - * Helper function to handle legacy encoding of SPM tokenizers. - * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387 - * @param {string} text The text to encode. - * @returns {string[]} The encoded tokens. - */ - _encode_text(text) { - if (text === null) - return null; - if (this.legacy || text.length === 0) { - return super._encode_text(text); - } - let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " ")); - if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) { - tokens = tokens.slice(1); - } - return tokens; - } - get default_chat_template() { - return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT", this.use_default_system_prompt ? "true" : "false").replaceAll("DEFAULT_SYSTEM_MESSAGE", this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n", "\\n").replaceAll("'", "\\'")); - } - }; - var CodeLlamaTokenizer = class extends LlamaTokenizer { - }; - var XLMRobertaTokenizer = class extends PreTrainedTokenizer { - }; - var MPNetTokenizer = class extends PreTrainedTokenizer { - }; - var FalconTokenizer = class extends PreTrainedTokenizer { - }; - var GPTNeoXTokenizer = class extends PreTrainedTokenizer { - }; - var EsmTokenizer = class extends PreTrainedTokenizer { - }; - function _build_translation_inputs(self2, raw_inputs, tokenizer_options, generate_kwargs) { - if (!("language_codes" in self2) || !Array.isArray(self2.language_codes)) { - throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids."); - } - if (!("languageRegex" in self2) || !(self2.languageRegex instanceof RegExp)) { - throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression."); - } - if (!("lang_to_token" in self2) || typeof self2.lang_to_token !== "function") { - throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function."); - } - const src_lang_token = generate_kwargs.src_lang; - const tgt_lang_token = generate_kwargs.tgt_lang; - if (!self2.language_codes.includes(tgt_lang_token)) { - throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); - } - if (src_lang_token !== void 0) { - if (!self2.language_codes.includes(src_lang_token)) { - throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); - } - for (const item of self2.post_processor.config.single) { - if ("SpecialToken" in item && self2.languageRegex.test(item.SpecialToken.id)) { - item.SpecialToken.id = self2.lang_to_token(src_lang_token); - break; - } - } - } - generate_kwargs.forced_bos_token_id = self2.model.convert_tokens_to_ids([self2.lang_to_token(tgt_lang_token)])[0]; - return self2._call(raw_inputs, tokenizer_options); - } - var NllbTokenizer = class extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; - this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)); - this.lang_to_token = (x) => x; - } - /** - * Helper function to build translation inputs for an `NllbTokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); - } - }; - var M2M100Tokenizer = class extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.languageRegex = /^__[a-z]{2,3}__$/; - this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)).map((x) => x.slice(2, -2)); - this.lang_to_token = (x) => `__${x}__`; - } - /** - * Helper function to build translation inputs for an `M2M100Tokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); - } - }; - var WHISPER_LANGUAGES = [ - ["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"] - ]; - var WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); - var WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ - ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]), - ...[ - ["burmese", "my"], - ["valencian", "ca"], - ["flemish", "nl"], - ["haitian", "ht"], - ["letzeburgesch", "lb"], - ["pushto", "ps"], - ["panjabi", "pa"], - ["moldavian", "ro"], - ["moldovan", "ro"], - ["sinhalese", "si"], - ["castilian", "es"] - ] - ]); - var WhisperTokenizer = class extends PreTrainedTokenizer { - _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`; - /** - * Decodes automatic speech recognition (ASR) sequences. - * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. - * @param {Object} options The options to use for decoding. - * @returns {Array, text: string}>}>} The decoded sequences. - */ - _decode_asr(sequences, { - return_timestamps = false, - return_language = false, - time_precision = null, - force_full_sequences = true - } = {}) { - if (time_precision === null) { - throw Error("Must specify time_precision"); - } - let last_language = null; - const returnWordTimestamps = return_timestamps === "word"; - function new_chunk() { - return { "language": last_language, "timestamp": [null, null], "text": "" }; - } - const chunks = []; - let chunk = new_chunk(); - let time_offset = 0; - const timestamp_begin = this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; - let previous_tokens = []; - let previous_token_timestamps = []; - let skip = false; - let right_stride_start = null; - const all_special_ids = new Set(this.all_special_ids); - for (const output of sequences) { - const token_ids = output.tokens; - const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; - let last_timestamp = null; - let first_timestamp = timestamp_begin; - if ("stride" in output) { - const [chunk_len, stride_left, stride_right] = output.stride; - time_offset -= stride_left; - right_stride_start = chunk_len - stride_right; - if (stride_left) { - first_timestamp = stride_left / time_precision + timestamp_begin; - } - if (stride_right) { - for (let i = token_ids.length - 1; i >= 0; --i) { - const token = token_ids[i]; - if (token >= timestamp_begin) { - if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { - break; - } - last_timestamp = token; - } - } - } - } - let current_tokens = []; - let current_token_timestamps = []; - for (let i = 0; i < token_ids.length; ++i) { - const token = token_ids[i]; - if (all_special_ids.has(token)) { - const text = this.decode([token]); - const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); - if (language !== void 0) { - if (last_language !== null && language !== last_language && !return_timestamps) { - previous_tokens.push(current_tokens); - const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; - const resolved_text = this.decode(resolved_tokens); - chunk.text = resolved_text; - chunks.push(chunk); - previous_tokens = []; - current_tokens = []; - chunk = new_chunk(); - } - last_language = chunk.language = language; - } else { - } - } else if (token >= timestamp_begin) { - const time = (token - timestamp_begin) * time_precision + time_offset; - const rounded_time = round(time, 2); - if (last_timestamp !== null && token >= last_timestamp) { - skip = true; - } else if (skip || previous_tokens.length > 0 && token < first_timestamp) { - skip = false; - } else if (chunk.timestamp[0] === null) { - chunk.timestamp[0] = rounded_time; - } else { - if (rounded_time === chunk.timestamp[0]) { - } else { - chunk.timestamp[1] = rounded_time; - previous_tokens.push(current_tokens); - if (returnWordTimestamps) { - previous_token_timestamps.push(current_token_timestamps); - } - const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( - previous_tokens, - previous_token_timestamps - ); - const resolved_text = this.decode(resolved_tokens); - chunk.text = resolved_text; - if (returnWordTimestamps) { - chunk.words = this.collateWordTimestamps( - resolved_tokens, - resolved_token_timestamps, - last_language - ); - } - chunks.push(chunk); - previous_tokens = []; - current_tokens = []; - previous_token_timestamps = []; - current_token_timestamps = []; - chunk = new_chunk(); - } - } - } else { - current_tokens.push(token); - if (returnWordTimestamps) { - let start_time = round(token_timestamps[i] + time_offset, 2); - let end_time; - if (i + 1 < token_timestamps.length) { - end_time = round(token_timestamps[i + 1] + time_offset, 2); - } else { - end_time = null; - } - current_token_timestamps.push([start_time, end_time]); - } - } - } - if ("stride" in output) { - const [chunk_len, stride_left, stride_right] = output.stride; - time_offset += chunk_len - stride_right; - } - if (current_tokens.length > 0) { - previous_tokens.push(current_tokens); - if (returnWordTimestamps) { - previous_token_timestamps.push(current_token_timestamps); - } - } else if (previous_tokens.every((p) => p.length === 0)) { - chunk = new_chunk(); - previous_tokens = []; - current_tokens = []; - previous_token_timestamps = []; - current_token_timestamps = []; - } - } - if (previous_tokens.length > 0) { - if (force_full_sequences && return_timestamps) { - 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 [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps); - const resolved_text = this.decode(resolved_tokens); - chunk.text = resolved_text; - if (returnWordTimestamps) { - chunk.words = this.collateWordTimestamps( - resolved_tokens, - resolved_token_timestamps, - last_language - ); - } - chunks.push(chunk); - } - let optional = /* @__PURE__ */ Object.create(null); - const full_text = chunks.map((chunk2) => chunk2.text).join(""); - if (return_timestamps || return_language) { - for (let i = 0; i < chunks.length; ++i) { - const chunk2 = chunks[i]; - if (!return_timestamps) { - delete chunk2["timestamp"]; - } - if (!return_language) { - delete chunk2["language"]; - } - } - if (returnWordTimestamps) { - const new_chunks = []; - for (const chunk2 of chunks) { - for (const word of chunk2.words) { - new_chunks.push(word); - } - } - optional = { "chunks": new_chunks }; - } else { - optional = { "chunks": chunks }; - } - } - return [full_text, optional]; - } - /** - * Finds the longest common sequence among the provided sequences. - * @param {number[][]} sequences An array of sequences of token ids to compare. - * @returns {number[][]} The longest common sequence found. - * @throws {Error} If there is a bug within the function. - * @private - */ - findLongestCommonSequence(sequences, token_timestamp_sequences = null) { - let leftSequence = sequences[0]; - let leftLength = leftSequence.length; - let totalSequence = []; - const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; - let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; - let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; - for (let i = 1; i < sequences.length; ++i) { - const rightSequence = sequences[i]; - let max2 = 0; - let maxIndices = [leftLength, leftLength, 0, 0]; - const rightLength = rightSequence.length; - for (let j = 1; j < leftLength + rightLength; ++j) { - const eps = j / 1e4; - const leftStart2 = Math.max(0, leftLength - j); - const leftStop2 = Math.min(leftLength, leftLength + rightLength - j); - const left = leftSequence.slice(leftStart2, leftStop2); - const rightStart2 = Math.max(0, j - leftLength); - const rightStop2 = Math.min(rightLength, j); - const right = rightSequence.slice(rightStart2, rightStop2); - if (left.length !== right.length) { - throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); - } - const matches = left.filter((elem, idx) => elem === right[idx]).length; - const matching = matches / j + eps; - if (matches > 1 && matching > max2) { - max2 = matching; - maxIndices = [leftStart2, leftStop2, rightStart2, rightStop2]; - } - } - const [leftStart, leftStop, rightStart, rightStop] = maxIndices; - const leftMid = Math.floor((leftStop + leftStart) / 2); - const rightMid = Math.floor((rightStop + rightStart) / 2); - totalSequence.push(...leftSequence.slice(0, leftMid)); - leftSequence = rightSequence.slice(rightMid); - leftLength = leftSequence.length; - if (use_token_timestamp_sequences) { - total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); - left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); - } - } - totalSequence.push(...leftSequence); - if (use_token_timestamp_sequences) { - total_token_timestamp_sequence.push(...left_token_timestamp_sequence); - return [totalSequence, total_token_timestamp_sequence]; - } else { - return [totalSequence, []]; - } - } - /** @private */ - collateWordTimestamps(tokens, token_timestamps, language) { - const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); - const timings = []; - for (let i = 0; i < words.length; ++i) { - const indices = token_indices[i]; - timings.push({ - text: words[i], - timestamp: [ - token_timestamps[indices.at(0)][0], - token_timestamps[indices.at(-1)][1] - ] - }); - } - return timings; - } - /** - * Groups tokens by word. Returns a tuple containing a list of strings with the words, - * and a list of `token_id` sequences with the tokens making up each word. - * @param {number[]} tokens - * @param {string} [language] - * @param {string} prepend_punctionations - * @param {string} append_punctuations - * - * @private - */ - combineTokensIntoWords(tokens, language, prepend_punctionations = `"'\u201C\xA1\xBF([{-`, append_punctuations = `"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`) { - language = language ?? "english"; - let words, word_tokens, token_indices; - if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { - [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens); - } else { - [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens); - } - return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); - } - /** @type {PreTrainedTokenizer['decode']} */ - decode(token_ids, decode_args) { - let text; - if (decode_args && decode_args.decode_with_timestamps) { - if (token_ids instanceof Tensor) { - token_ids = prepareTensorForDecode(token_ids); - } - text = this.decodeWithTimestamps(token_ids, decode_args); - } else { - text = super.decode(token_ids, decode_args); - } - return text; - } - /** - * @param {number[]} token_ids List of token IDs to decode. - * @param {Object} decode_args Optional arguments for decoding - * @private - */ - decodeWithTimestamps(token_ids, decode_args) { - const time_precision = decode_args?.time_precision ?? 0.02; - const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1; - let outputs = [[]]; - for (const token of token_ids) { - if (token >= timestamp_begin) { - const timestamp = round((token - timestamp_begin) * time_precision, 2); - outputs.push(`<|${timestamp}|>`); - outputs.push([]); - } else { - outputs[outputs.length - 1].push(token); - } - } - outputs = outputs.map( - (s) => { - if (typeof s === "string") { - return s; - } else { - return super.decode(s, decode_args); - } - } - ); - return outputs.join(""); - } - /** - * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. - * @param {number[]} tokens - * @returns {*} - * @private - */ - splitTokensOnUnicode(tokens) { - const decoded_full = this.decode(tokens, { - // @ts-ignore - decode_with_timestamps: true - }); - const replacement_char = "\uFFFD"; - const words = []; - const word_tokens = []; - const token_indices = []; - let current_tokens = []; - let current_indices = []; - let unicode_offset = 0; - for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { - const token = tokens[token_idx]; - current_tokens.push(token); - current_indices.push(token_idx); - const decoded = this.decode(current_tokens, { - // @ts-ignore - decode_with_timestamps: true - }); - if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { - words.push(decoded); - word_tokens.push(current_tokens); - token_indices.push(current_indices); - current_tokens = []; - current_indices = []; - unicode_offset += decoded.length; - } - } - return [words, word_tokens, token_indices]; - } - /** - * Combine tokens into words by splitting at whitespace and punctuation tokens. - * @param {number[]} tokens - * @private - */ - splitTokensOnSpaces(tokens) { - const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); - const words = []; - const word_tokens = []; - const token_indices = []; - const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, "gu"); - for (let i = 0; i < subwords.length; ++i) { - const subword = subwords[i]; - const subword_tokens = subword_tokens_list[i]; - const subword_indices = subword_indices_list[i]; - const special = subword_tokens[0] >= this.model.tokens_to_ids.get("<|endoftext|>"); - const with_space = subword.startsWith(" "); - const trimmed = subword.trim(); - const punctuation = punctuationRegex.test(trimmed); - if (special || with_space || punctuation || words.length === 0) { - words.push(subword); - word_tokens.push(subword_tokens); - token_indices.push(subword_indices); - } else { - const ix = words.length - 1; - words[ix] += subword; - word_tokens[ix].push(...subword_tokens); - token_indices[ix].push(...subword_indices); - } - } - return [words, word_tokens, token_indices]; - } - /** - * Merges punctuation tokens with neighboring words. - * @param {string[]} words - * @param {number[][]} tokens - * @param {number[][]} indices - * @param {string} prepended - * @param {string} appended - * @private - */ - mergePunctuations(words, tokens, indices, prepended, appended) { - const newWords = structuredClone(words); - const newTokens = structuredClone(tokens); - const newIndices = structuredClone(indices); - let i = newWords.length - 2; - let j = newWords.length - 1; - while (i >= 0) { - if (newWords[i].startsWith(" ") && prepended.includes(newWords[i].trim())) { - newWords[j] = newWords[i] + newWords[j]; - newTokens[j] = mergeArrays(newTokens[i], newTokens[j]); - newIndices[j] = mergeArrays(newIndices[i], newIndices[j]); - newWords[i] = ""; - newTokens[i] = []; - newIndices[i] = []; - } else { - j = i; - } - --i; - } - i = 0; - j = 1; - while (j < newWords.length) { - if (!newWords[i].endsWith(" ") && appended.includes(newWords[j])) { - newWords[i] += newWords[j]; - newTokens[i] = mergeArrays(newTokens[i], newTokens[j]); - newIndices[i] = mergeArrays(newIndices[i], newIndices[j]); - newWords[j] = ""; - newTokens[j] = []; - newIndices[j] = []; - } else { - i = j; - } - ++j; - } - return [ - newWords.filter((x) => x), - newTokens.filter((x) => x.length > 0), - newIndices.filter((x) => x.length > 0) - ]; - } - /** - * Helper function to build translation inputs for a `WhisperTokenizer`, - * depending on the language, task, and whether to predict timestamp tokens. - * - * Used to override the prefix tokens appended to the start of the label sequence. - * - * **Example: Get ids for a language** - * ```javascript - * // instantiate the tokenizer and set the prefix token to Spanish - * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny'); - * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' }); - * // [(1, 50262), (2, 50363)] - * ``` - * - * @param {Object} options Options to generate the decoder prompt. - * @param {string} [options.language] The language of the transcription text. - * The corresponding language id token is appended to the start of the sequence for multilingual - * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended - * to the start of sequence. - * @param {string} [options.task] Task identifier to append at the start of sequence (if any). - * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and - * "translate" for speech translation. - * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence. - * @returns {number[][]} The decoder prompt ids. - */ - get_decoder_prompt_ids({ - language = null, - task = null, - no_timestamps = true - } = {}) { - const forced_decoder_ids = []; - if (language) { - language = language.toLowerCase(); - let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); - if (language_code === void 0) { - if (WHISPER_LANGUAGE_MAPPING.has(language)) { - language_code = language; - } else { - const is_language_code = language.length === 2; - const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); - throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(langs)}`); - } - } - const language_token_id = this.model.tokens_to_ids.get(`<|${language_code}|>`); - if (language_token_id === void 0) { - throw new Error(`Unable to find language "${language_code}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`); - } - forced_decoder_ids.push(language_token_id); - } else { - forced_decoder_ids.push(null); - } - if (task) { - task = task.toLowerCase(); - if (task !== "transcribe" && task !== "translate") { - throw new Error(`Task "${task}" is not supported. Must be one of: ["transcribe", "translate"]`); - } - const task_token_id = this.model.tokens_to_ids.get(`<|${task}|>`); - if (task_token_id === void 0) { - throw new Error(`Unable to find task "${task}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`); - } - forced_decoder_ids.push(task_token_id); - } else { - forced_decoder_ids.push(null); - } - if (no_timestamps) { - const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`); - if (no_timestamps_id === void 0) { - throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.'); - } - forced_decoder_ids.push(no_timestamps_id); - } - return forced_decoder_ids.map((x, i) => [i + 1, x]).filter((x) => x[1] !== null); - } - }; - var CodeGenTokenizer = class extends PreTrainedTokenizer { - }; - var CLIPTokenizer = class extends PreTrainedTokenizer { - }; - var SiglipTokenizer = class extends PreTrainedTokenizer { - }; - var MarianTokenizer = class extends PreTrainedTokenizer { - /** - * Create a new MarianTokenizer instance. - * @param {Object} tokenizerJSON The JSON of the tokenizer. - * @param {Object} tokenizerConfig The config of the tokenizer. - */ - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.languageRegex = /^(>>\w+<<)\s*/g; - this.supported_language_codes = this.model.vocab.filter( - (x) => this.languageRegex.test(x) - ); - console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); - } - /** - * Encodes a single text. Overriding this method is necessary since the language codes - * must be removed before encoding with sentencepiece model. - * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 - * - * @param {string|null} text The text to encode. - * @returns {Array} The encoded tokens. - */ - _encode_text(text) { - if (text === null) - return null; - const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); - if (remainder.length === 0) { - return super._encode_text(matchInfo); - } else if (remainder.length === 2) { - const [language, text2] = remainder; - if (!this.supported_language_codes.includes(language)) { - console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`); - } - return mergeArrays([language], super._encode_text(text2)); - } - } - }; - var Wav2Vec2CTCTokenizer = class extends PreTrainedTokenizer { - }; - var BlenderbotTokenizer = class extends PreTrainedTokenizer { - _default_chat_template = `{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}`; - }; - var BlenderbotSmallTokenizer = class extends BlenderbotTokenizer { - }; - var SpeechT5Tokenizer = class extends PreTrainedTokenizer { - }; - var NougatTokenizer = class extends PreTrainedTokenizer { - }; - var VitsTokenizer = class extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - this.decoder = new VitsDecoder({}); - } - }; - var AutoTokenizer = class { - static TOKENIZER_CLASS_MAPPING = { - T5Tokenizer, - DistilBertTokenizer, - CamembertTokenizer, - DebertaTokenizer, - DebertaV2Tokenizer, - BertTokenizer, - HerbertTokenizer, - ConvBertTokenizer, - RoFormerTokenizer, - XLMTokenizer, - ElectraTokenizer, - MobileBertTokenizer, - SqueezeBertTokenizer, - AlbertTokenizer, - GPT2Tokenizer, - BartTokenizer, - MBartTokenizer, - MBart50Tokenizer, - RobertaTokenizer, - WhisperTokenizer, - CodeGenTokenizer, - CLIPTokenizer, - SiglipTokenizer, - MarianTokenizer, - BloomTokenizer, - NllbTokenizer, - M2M100Tokenizer, - LlamaTokenizer, - CodeLlamaTokenizer, - XLMRobertaTokenizer, - MPNetTokenizer, - FalconTokenizer, - GPTNeoXTokenizer, - EsmTokenizer, - Wav2Vec2CTCTokenizer, - BlenderbotTokenizer, - BlenderbotSmallTokenizer, - SpeechT5Tokenizer, - NougatTokenizer, - VitsTokenizer, - // Base case: - PreTrainedTokenizer - }; - /** - * Instantiate one of the tokenizer classes of the library from a pretrained model. - * - * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object - * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. - * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. - * - * @returns {Promise} A new instance of the PreTrainedTokenizer class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - quantized = true, - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main", - legacy = null - } = {}) { - const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { - quantized, - progress_callback, - config, - cache_dir, - local_files_only, - revision, - legacy - }); - const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer"; - let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName]; - if (!cls) { - console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); - cls = PreTrainedTokenizer; - } - return new cls(tokenizerJSON, tokenizerConfig); - } - }; - - // node_modules/@xenova/transformers/src/configs.js - async function loadConfig(pretrained_model_name_or_path, options) { - let info = await getModelJSON(pretrained_model_name_or_path, "config.json", true, options); - return info; - } - var PretrainedConfig = class { - // NOTE: Typo in original - /** - * Create a new PreTrainedTokenizer instance. - * @param {Object} configJSON The JSON of the config. - */ - constructor(configJSON) { - this.model_type = null; - this.is_encoder_decoder = false; - Object.assign(this, configJSON); - } - /** - * Loads a pre-trained config from the given `pretrained_model_name_or_path`. - * - * @param {string} pretrained_model_name_or_path The path to the pre-trained config. - * @param {PretrainedOptions} options Additional options for loading the config. - * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. - * - * @returns {Promise} A new instance of the `PretrainedConfig` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main" - } = {}) { - let data = config ?? await loadConfig(pretrained_model_name_or_path, { - progress_callback, - config, - cache_dir, - local_files_only, - revision - }); - return new this(data); - } - }; - var AutoConfig = class { - /** @type {PretrainedConfig.from_pretrained} */ - static async from_pretrained(...args) { - return PretrainedConfig.from_pretrained(...args); - } - }; - - // node_modules/@xenova/transformers/src/utils/generation.js - var LogitsProcessorList = class extends Callable { - /** - * Constructs a new instance of `LogitsProcessorList`. - */ - constructor() { - super(); - this.processors = []; - } - /** - * Adds a new logits processor to the list. - * - * @param {LogitsProcessor} item The logits processor function to add. - */ - push(item) { - this.processors.push(item); - } - /** - * Adds multiple logits processors to the list. - * - * @param {LogitsProcessor[]} items The logits processor functions to add. - */ - extend(items) { - this.processors.push(...items); - } - /** - * Applies all logits processors in the list to a batch of logits, modifying them in-place. - * - * @param {number[]} input_ids The input IDs for the language model. - * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single - * input sequence in the batch. - */ - _call(input_ids, batchedLogits) { - for (let logits of batchedLogits) { - this.processors.forEach( - (func) => func(input_ids, logits) - ); - } - } - [Symbol.iterator]() { - return this.processors.values(); - } - }; - var LogitsProcessor = class extends Callable { - /** - * Apply the processor to the input logits. - * - * @abstract - * @param {Array} input_ids The input ids. - * @param {Tensor} logits The logits to process. - * @throws {Error} Throws an error if `_call` is not implemented in the subclass. - */ - _call(input_ids, logits) { - throw Error("`_call` should be implemented in a subclass"); - } - }; - var ForceTokensLogitsProcessor = class extends LogitsProcessor { - /** - * Constructs a new instance of `ForceTokensLogitsProcessor`. - * - * @param {Array} forced_decoder_ids The ids of tokens that should be forced. - */ - constructor(forced_decoder_ids) { - super(); - this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []); - } - /** - * Apply the processor to the input logits. - * - * @param {Array} input_ids The input ids. - * @param {Tensor} logits The logits to process. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - let map = this.force_token_map[input_ids.length]; - if (exists(map)) { - logits.data.fill(-Infinity); - logits.data[map] = 0; - } - return logits; - } - }; - var ForcedBOSTokenLogitsProcessor = class extends LogitsProcessor { - /** - * Create a ForcedBOSTokenLogitsProcessor. - * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. - */ - constructor(bos_token_id) { - super(); - this.bos_token_id = bos_token_id; - } - /** - * Apply the BOS token forcing to the logits. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The logits with BOS token forcing. - */ - _call(input_ids, logits) { - if (input_ids.length === 1) { - logits.data.fill(-Infinity); - logits.data[this.bos_token_id] = 0; - } - return logits; - } - }; - var ForcedEOSTokenLogitsProcessor = class extends LogitsProcessor { - /** - * Create a ForcedEOSTokenLogitsProcessor. - * @param {number} max_length Max length of the sequence. - * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced. - */ - constructor(max_length, forced_eos_token_id) { - super(); - this.max_length = max_length; - this.forced_eos_token_id = forced_eos_token_id; - } - /** - * Apply the processor to input_ids and logits. - * - * @param {number[]} input_ids The input ids. - * @param {Tensor} logits The logits tensor. - */ - _call(input_ids, logits) { - } - }; - var SuppressTokensAtBeginLogitsProcessor = class extends LogitsProcessor { - /** - * Create a SuppressTokensAtBeginLogitsProcessor. - * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. - * @param {number} begin_index The number of tokens to generate before suppressing tokens. - */ - constructor(begin_suppress_tokens, begin_index) { - super(); - this.begin_suppress_tokens = begin_suppress_tokens; - this.begin_index = begin_index; - } - /** - * Apply the BOS token forcing to the logits. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The logits with BOS token forcing. - */ - _call(input_ids, logits) { - if (input_ids.length === this.begin_index) { - for (let token_id of this.begin_suppress_tokens) { - logits.data[token_id] = -Infinity; - } - } - return logits; - } - }; - var WhisperTimeStampLogitsProcessor = class extends LogitsProcessor { - /** - * Constructs a new WhisperTimeStampLogitsProcessor. - * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model. - * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token. - * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp. - * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp. - * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear. - */ - constructor(generate_config) { - super(); - this.eos_token_id = generate_config.eos_token_id; - this.no_timestamps_token_id = generate_config.no_timestamps_token_id; - this.timestamp_begin = this.no_timestamps_token_id + 1; - this.begin_index = (generate_config.forced_decoder_ids || []).length + 2; - if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) { - this.begin_index -= 1; - } - this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; - } - /** - * Modify the logits to handle timestamp tokens. - * @param {Array} input_ids The input sequence of tokens. - * @param {Tensor} logits The logits output by the model. - * @returns {Tensor} The modified logits. - */ - _call(input_ids, logits) { - const logitsData = ( - /** @type {Float32Array} */ - logits.data - ); - logitsData[this.no_timestamps_token_id] = -Infinity; - if (input_ids.length === this.begin_index - 1) { - logitsData.fill(-Infinity); - logitsData[this.timestamp_begin] = 0; - return logits; - } - const seq = input_ids.slice(this.begin_index); - const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; - const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; - if (last_was_timestamp) { - if (penultimate_was_timestamp) { - logitsData.subarray(this.timestamp_begin).fill(-Infinity); - } else { - logitsData.subarray(0, this.eos_token_id).fill(-Infinity); - } - } - if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) { - const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; - logitsData.subarray(last_allowed + 1).fill(-Infinity); - } - const logprobs = log_softmax(logitsData); - const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); - const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0]; - if (timestamp_logprob > max_text_token_logprob) { - logitsData.subarray(0, this.timestamp_begin).fill(-Infinity); - } - return logits; - } - }; - var NoRepeatNGramLogitsProcessor = class extends LogitsProcessor { - /** - * Create a NoRepeatNGramLogitsProcessor. - * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. - */ - constructor(no_repeat_ngram_size) { - super(); - this.no_repeat_ngram_size = no_repeat_ngram_size; - } - /** - * Generate n-grams from a sequence of token ids. - * @param {number[]} prevInputIds List of previous input ids - * @returns {Map} Map of generated n-grams - */ - getNgrams(prevInputIds) { - const curLen = prevInputIds.length; - const ngrams = []; - for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) { - const ngram = []; - for (let k = 0; k < this.no_repeat_ngram_size; ++k) { - ngram.push(prevInputIds[j + k]); - } - ngrams.push(ngram); - } - const generatedNgram = /* @__PURE__ */ new Map(); - for (const ngram of ngrams) { - const prevNgram = ngram.slice(0, ngram.length - 1); - const prevNgramKey = JSON.stringify(prevNgram); - const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; - prevNgramValue.push(ngram[ngram.length - 1]); - generatedNgram.set(prevNgramKey, prevNgramValue); - } - return generatedNgram; - } - /** - * Generate n-grams from a sequence of token ids. - * @param {Map} bannedNgrams Map of banned n-grams - * @param {number[]} prevInputIds List of previous input ids - * @returns {number[]} Map of generated n-grams - */ - getGeneratedNgrams(bannedNgrams, prevInputIds) { - const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); - const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? []; - return banned; - } - /** - * Calculate banned n-gram tokens - * @param {number[]} prevInputIds List of previous input ids - * @returns {number[]} Map of generated n-grams - */ - calcBannedNgramTokens(prevInputIds) { - const bannedTokens = []; - if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { - return bannedTokens; - } else { - const generatedNgrams = this.getNgrams(prevInputIds); - const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds); - return bannedTokens2; - } - } - /** - * Apply the no-repeat-ngram processor to the logits. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The logits with no-repeat-ngram processing. - */ - _call(input_ids, logits) { - const bannedTokens = this.calcBannedNgramTokens(input_ids); - for (const token of bannedTokens) { - logits.data[token] = -Infinity; - } - return logits; - } - }; - var RepetitionPenaltyLogitsProcessor = class extends LogitsProcessor { - /** - * Create a RepetitionPenaltyLogitsProcessor. - * @param {number} penalty The penalty to apply for repeated tokens. - */ - constructor(penalty) { - super(); - this.penalty = penalty; - } - /** - * Apply the repetition penalty to the logits. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The logits with repetition penalty processing. - */ - _call(input_ids, logits) { - for (const input_id of input_ids) { - if (logits.data[input_id] < 0) { - logits.data[input_id] *= this.penalty; - } else { - logits.data[input_id] /= this.penalty; - } - } - return logits; - } - }; - var MinLengthLogitsProcessor = class extends LogitsProcessor { - /** - * Create a MinLengthLogitsProcessor. - * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. - * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. - */ - constructor(min_length, eos_token_id) { - super(); - this.min_length = min_length; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - /** - * Apply logit processor. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The processed logits. - */ - _call(input_ids, logits) { - if (input_ids.length < this.min_length) { - for (const eos_token of this.eos_token_id) { - logits.data[eos_token] = -Infinity; - } - } - return logits; - } - }; - var MinNewTokensLengthLogitsProcessor = class extends LogitsProcessor { - /** - * Create a MinNewTokensLengthLogitsProcessor. - * @param {number} prompt_length_to_skip The input tokens length. - * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. - * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. - */ - constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { - super(); - this.prompt_length_to_skip = prompt_length_to_skip; - this.min_new_tokens = min_new_tokens; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - /** - * Apply logit processor. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The processed logits. - */ - _call(input_ids, logits) { - const new_tokens_length = input_ids.length - this.prompt_length_to_skip; - if (new_tokens_length < this.min_new_tokens) { - for (const eos_token of this.eos_token_id) { - logits.data[eos_token] = -Infinity; - } - } - return logits; - } - }; - var NoBadWordsLogitsProcessor = class extends LogitsProcessor { - /** - * Create a `NoBadWordsLogitsProcessor`. - * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. - * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. - */ - constructor(bad_words_ids, eos_token_id) { - super(); - this.bad_words_ids = bad_words_ids; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - /** - * Apply logit processor. - * @param {Array} input_ids The input IDs. - * @param {Object} logits The logits. - * @returns {Object} The processed logits. - */ - _call(input_ids, logits) { - for (const bad_word_ids of this.bad_words_ids) { - let mark = true; - for (let i = 1; i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i) { - if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) { - mark = false; - break; - } - } - if (mark) { - logits.data[bad_word_ids.at(-1)] = -Infinity; - } - } - return logits; - } - }; - var GenerationConfig = ( - /** @type {any} */ - class { - /** - * Create a new GenerationConfig object. - * @param {GenerationConfigType} kwargs - */ - constructor(kwargs = {}) { - this.max_length = kwargs.max_length ?? 20; - this.max_new_tokens = kwargs.max_new_tokens ?? null; - this.min_length = kwargs.min_length ?? 0; - this.min_new_tokens = kwargs.min_new_tokens ?? null; - this.early_stopping = kwargs.early_stopping ?? false; - this.max_time = kwargs.max_time ?? null; - this.do_sample = kwargs.do_sample ?? false; - this.num_beams = kwargs.num_beams ?? 1; - this.num_beam_groups = kwargs.num_beam_groups ?? 1; - this.penalty_alpha = kwargs.penalty_alpha ?? null; - this.use_cache = kwargs.use_cache ?? true; - this.temperature = kwargs.temperature ?? 1; - this.top_k = kwargs.top_k ?? 50; - this.top_p = kwargs.top_p ?? 1; - this.typical_p = kwargs.typical_p ?? 1; - this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0; - this.eta_cutoff = kwargs.eta_cutoff ?? 0; - this.diversity_penalty = kwargs.diversity_penalty ?? 0; - this.repetition_penalty = kwargs.repetition_penalty ?? 1; - this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1; - this.length_penalty = kwargs.length_penalty ?? 1; - this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0; - this.bad_words_ids = kwargs.bad_words_ids ?? null; - this.force_words_ids = kwargs.force_words_ids ?? null; - this.renormalize_logits = kwargs.renormalize_logits ?? false; - this.constraints = kwargs.constraints ?? null; - this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null; - this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null; - this.remove_invalid_values = kwargs.remove_invalid_values ?? false; - this.exponential_decay_length_penalty = kwargs.exponential_decay_length_penalty ?? null; - this.suppress_tokens = kwargs.suppress_tokens ?? null; - this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null; - this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null; - this.num_return_sequences = kwargs.num_return_sequences ?? 1; - this.output_attentions = kwargs.output_attentions ?? false; - this.output_hidden_states = kwargs.output_hidden_states ?? false; - this.output_scores = kwargs.output_scores ?? false; - this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false; - this.pad_token_id = kwargs.pad_token_id ?? null; - this.bos_token_id = kwargs.bos_token_id ?? null; - this.eos_token_id = kwargs.eos_token_id ?? null; - this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0; - this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null; - this.generation_kwargs = kwargs.generation_kwargs ?? {}; - } - } - ); - var Sampler = class extends Callable { - /** - * Creates a new Sampler object with the specified generation config. - * @param {GenerationConfigType} generation_config The generation config. - */ - constructor(generation_config) { - super(); - this.generation_config = generation_config; - } - /** - * Executes the sampler, using the specified logits. - * @param {Tensor} logits - * @param {number} index - * @returns {void} - */ - _call(logits, index = -1) { - return this.sample(logits, index); - } - /** - * Abstract method for sampling the logits. - * @param {Tensor} logits - * @param {number} index - * @throws {Error} - */ - sample(logits, index) { - throw Error("sample should be implemented in subclasses."); - } - /** - * Returns the specified logits as an array, with temperature applied. - * @param {Tensor} logits - * @param {number} index - * @returns {Float32Array} - */ - getLogits(logits, index) { - let vocabSize = logits.dims.at(-1); - let logs = ( - /** @type {Float32Array} */ - logits.data - ); - if (index === -1) { - logs = logs.slice(-vocabSize); - } else { - let startIndex = index * vocabSize; - logs = logs.slice(startIndex, startIndex + vocabSize); - } - if (this.generation_config.temperature > 0) { - logs = logs.map((x) => x / this.generation_config.temperature); - } - return logs; - } - /** - * Selects an item randomly based on the specified probabilities. - * @param {Array} probabilities An array of probabilities to use for selection. - * @returns {number} The index of the selected item. - */ - randomSelect(probabilities) { - let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0); - let r = Math.random() * sumProbabilities; - for (let i = 0; i < probabilities.length; ++i) { - r -= probabilities[i]; - if (r <= 0) { - return i; - } - } - return 0; - } - /** - * Returns a Sampler object based on the specified options. - * @param {GenerationConfigType} generation_config An object containing options for the sampler. - * @returns {Sampler} A Sampler object. - */ - static getSampler(generation_config) { - if (generation_config.do_sample) { - return new MultinomialSampler(generation_config); - } else if (generation_config.num_beams > 1) { - return new BeamSearchSampler(generation_config); - } else { - if (generation_config.num_return_sequences > 1) { - throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`); - } - return new GreedySampler(generation_config); - } - } - }; - var GreedySampler = class extends Sampler { - /** - * Sample the maximum probability of a given logits tensor. - * @param {Tensor} logits - * @param {number} [index=-1] - * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). - */ - sample(logits, index = -1) { - let logs = this.getLogits(logits, index); - let argmax = max(logs)[1]; - return [ - [argmax, 0] - ]; - } - }; - var MultinomialSampler = class extends Sampler { - /** - * Sample from the logits. - * @param {Tensor} logits - * @param {number} index - * @returns {Array} - */ - sample(logits, index = -1) { - let k = logits.dims.at(-1); - if (this.generation_config.top_k > 0) { - k = Math.min(this.generation_config.top_k, k); - } - const logs = this.getLogits(logits, index); - const topLogits = getTopItems(logs, k); - const probabilities = softmax(topLogits.map((x) => x[1])); - return Array.from({ length: this.generation_config.num_beams }, () => { - const sampledIndex = this.randomSelect(probabilities); - return [ - topLogits[sampledIndex][0], - // token id - Math.log(probabilities[sampledIndex]) - // score - ]; - }); - } - }; - var BeamSearchSampler = class extends Sampler { - /** - * Sample from the logits. - * @param {Tensor} logits - * @param {number} index - * @returns {Array} - */ - sample(logits, index = -1) { - let k = logits.dims.at(-1); - if (this.generation_config.top_k > 0) { - k = Math.min(this.generation_config.top_k, k); - } - const logs = this.getLogits(logits, index); - const topLogits = getTopItems(logs, k); - const probabilities = softmax(topLogits.map((x) => x[1])); - return Array.from({ length: this.generation_config.num_beams }, (_, i) => { - return [ - topLogits[i][0], - // token id - Math.log(probabilities[i]) - // score - ]; - }); - } - }; - - // node_modules/@xenova/transformers/src/models.js - var { InferenceSession, Tensor: ONNXTensor2, env: env2 } = ONNX; - var MODEL_TYPES = { - EncoderOnly: 0, - EncoderDecoder: 1, - Seq2Seq: 2, - Vision2Seq: 3, - DecoderOnly: 4 - }; - var MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map(); - var MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map(); - var MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map(); - async function constructSession(pretrained_model_name_or_path, fileName, options) { - let modelFileName = `onnx/${fileName}${options.quantized ? "_quantized" : ""}.onnx`; - let buffer = await getModelFile(pretrained_model_name_or_path, modelFileName, true, options); - try { - return await InferenceSession.create(buffer, { - executionProviders - }); - } catch (err) { - if (executionProviders.length === 1 && executionProviders[0] === "wasm") { - throw err; - } - console.warn(err); - console.warn( - "Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. " - ); - return await InferenceSession.create(buffer, { - executionProviders: ["wasm"] - }); - } - } - function validateInputs(session, inputs) { - const checkedInputs = /* @__PURE__ */ Object.create(null); - const missingInputs = []; - for (const inputName of session.inputNames) { - const tensor = inputs[inputName]; - if (!(tensor instanceof Tensor)) { - missingInputs.push(inputName); - continue; - } - checkedInputs[inputName] = env2.wasm.proxy ? tensor.clone() : tensor; - } - if (missingInputs.length > 0) { - throw new Error( - `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.` - ); - } - const numInputsProvided = Object.keys(inputs).length; - const numInputsNeeded = session.inputNames.length; - if (numInputsProvided > numInputsNeeded) { - let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName)); - console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`); - } - return checkedInputs; - } - async function sessionRun(session, inputs) { - const checkedInputs = validateInputs(session, inputs); - try { - let output = await session.run(checkedInputs); - output = replaceTensors(output); - return output; - } catch (e) { - console.error(`An error occurred during model execution: "${e}".`); - console.error("Inputs given to model:", checkedInputs); - throw e; - } - } - function replaceTensors(obj) { - for (let prop in obj) { - if (obj[prop] instanceof ONNXTensor2) { - obj[prop] = new Tensor(obj[prop]); - } else if (typeof obj[prop] === "object") { - replaceTensors(obj[prop]); - } - } - return obj; - } - function toI64Tensor(items) { - if (items instanceof Tensor) { - return items; - } - if (items.length === 0) { - throw Error("items must be non-empty"); - } - if (Array.isArray(items[0])) { - if (items.some((x) => x.length !== items[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 Tensor( - "int64", - BigInt64Array.from(items.flat().map((x) => BigInt(x))), - [items.length, items[0].length] - ); - } else { - return new Tensor( - "int64", - BigInt64Array.from(items.map((x) => BigInt(x))), - [1, items.length] - ); - } - } - function prepareAttentionMask(self2, tokens) { - let pad_token_id = self2.config.pad_token_id ?? null; - let eos_token_id = self2.config.eos_token_id ?? null; - if (isIntegralNumber(eos_token_id)) { - eos_token_id = [eos_token_id]; - } - let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1; - let is_pad_token_not_equal_to_eos_token_id = eos_token_id === null || !eos_token_id.includes(pad_token_id); - if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) { - let data = BigInt64Array.from( - // Note: != so that int matches bigint - // @ts-ignore - tokens.data.map((x) => x != pad_token_id) - ); - return new Tensor("int64", data, tokens.dims); - } else { - return ones_like(tokens); - } - } - function preparePositionIds(session, feeds, use_cache_branch) { - if (!session.inputNames.includes("position_ids")) - return; - const data = new BigInt64Array(feeds.attention_mask.data.length); - for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) { - let start = i * feeds.attention_mask.dims[1]; - let sum = BigInt(0); - for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) { - const index = start + j; - if (feeds.attention_mask.data[index] === 0n) { - data[index] = BigInt(1); - } else { - data[index] = sum; - sum += feeds.attention_mask.data[index]; - } - } - } - feeds.position_ids = new Tensor("int64", data, feeds.attention_mask.dims); - if (use_cache_branch) { - feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1); - } - } - function boolTensor(value) { - return new Tensor("bool", [value], [1]); - } - async function seq2seqForward(self2, model_inputs) { - let { encoder_outputs, past_key_values } = model_inputs; - if (!encoder_outputs) { - encoder_outputs = (await encoderForward(self2, model_inputs)).last_hidden_state; - } - let decoderFeeds = { - input_ids: model_inputs.decoder_input_ids, - encoder_hidden_states: encoder_outputs - }; - const use_cache_branch = !!past_key_values; - if (self2.decoder_merged_session.inputNames.includes("use_cache_branch")) { - decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); - } - if (self2.decoder_merged_session.inputNames.includes("encoder_attention_mask")) { - decoderFeeds.encoder_attention_mask = model_inputs.attention_mask; - } - preparePositionIds(self2.decoder_merged_session, decoderFeeds, use_cache_branch); - self2.addPastKeyValues(decoderFeeds, past_key_values); - const decoderResults = await sessionRun(self2.decoder_merged_session, decoderFeeds); - let logits = decoderResults.logits; - past_key_values = self2.getPastKeyValues(decoderResults, past_key_values); - const attns = self2.getAttentions(decoderResults); - return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns }); - } - function seq2seqStartBeams(self2, inputTokenIds, generation_config, numOutputTokens) { - let beams = []; - let beamId = 0; - const requires_attention_mask = self2.requires_attention_mask ?? true; - let decoder_input_ids = generation_config.decoder_input_ids ?? generation_config.decoder_start_token_id ?? generation_config.bos_token_id ?? generation_config.eos_token_id; - if (decoder_input_ids instanceof Tensor) { - decoder_input_ids = decoder_input_ids.tolist().flat(); - } else if (!Array.isArray(decoder_input_ids)) { - decoder_input_ids = [decoder_input_ids]; - } - for (let tokens of inputTokenIds) { - tokens.dims = [1, ...tokens.dims]; - let start = { - inputs: tokens, - encoder_outputs: null, - prev_model_outputs: null, - output_token_ids: decoder_input_ids, - done: false, - score: 0, - id: beamId++ - // assign unique id to beams - }; - if (requires_attention_mask) { - start.attention_mask = prepareAttentionMask(self2, tokens); - } - beams.push(start); - } - return beams; - } - async function seq2seqRunBeam(self2, beam) { - const input_name = self2.main_input_name; - let decoder_input_ids = beam.output_token_ids; - if (beam.prev_model_outputs) { - decoder_input_ids = decoder_input_ids.slice(-1); - } - let model_inputs = { - [input_name]: beam.inputs, - decoder_input_ids: toI64Tensor(decoder_input_ids), - encoder_outputs: beam.encoder_outputs, - past_key_values: beam.prev_model_outputs?.past_key_values - }; - if (beam.attention_mask) { - model_inputs.attention_mask = beam.attention_mask; - } - let output = await self2.forward(model_inputs); - beam.prev_model_outputs = output; - beam.encoder_outputs = output.encoder_outputs; - return output; - } - function seq2seqUpdatebeam(beam, newTokenId) { - beam.output_token_ids = [...beam.output_token_ids, newTokenId]; - } - async function encoderForward(self2, model_inputs) { - const encoderFeeds = /* @__PURE__ */ Object.create(null); - for (const key of self2.session.inputNames) { - encoderFeeds[key] = model_inputs[key]; - } - if (self2.session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) { - encoderFeeds.token_type_ids = new Tensor( - "int64", - new BigInt64Array(encoderFeeds.input_ids.data.length), - encoderFeeds.input_ids.dims - ); - } - return await sessionRun(self2.session, encoderFeeds); - } - async function decoderForward(self2, model_inputs) { - let { input_ids, past_key_values, attention_mask } = model_inputs; - let decoderFeeds = { - input_ids, - attention_mask: attention_mask ?? prepareAttentionMask(self2, input_ids) - }; - const use_cache_branch = !!past_key_values; - if (self2.session.inputNames.includes("use_cache_branch")) { - decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); - } - preparePositionIds(self2.session, decoderFeeds, use_cache_branch); - self2.addPastKeyValues(decoderFeeds, past_key_values); - let decoderResults = await sessionRun(self2.session, decoderFeeds); - let logits = decoderResults.logits; - past_key_values = self2.getPastKeyValues(decoderResults, past_key_values); - return { logits, past_key_values }; - } - function decoderStartBeams(self2, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { - let beams = []; - let beamId = 0; - for (let tokens of inputTokenIds) { - let output_token_ids = tokens.tolist().map(Number); - tokens.dims = [1, ...tokens.dims]; - let attn_mask; - if (inputs_attention_mask) { - attn_mask = inputs_attention_mask[beamId]; - attn_mask.dims = [1, ...attn_mask.dims]; - } else { - attn_mask = prepareAttentionMask(self2, tokens); - } - let start = { - input: tokens, - model_input_ids: tokens, - attention_mask: attn_mask, - prev_model_outputs: null, - output_token_ids, - num_output_tokens: numOutputTokens, - done: false, - score: 0, - id: beamId++ - // assign unique id to beams - }; - beams.push(start); - } - return beams; - } - async function decoderRunBeam(self2, beam) { - let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n); - let model_inputs = { - input_ids: beam.model_input_ids, - attention_mask: new Tensor( - "int64", - attnMaskData, - [1, attnMaskData.length] - ), - past_key_values: beam.prev_model_outputs?.past_key_values - }; - let output = await self2.forward(model_inputs); - beam.prev_model_outputs = output; - return output; - } - function decoderUpdatebeam(beam, newTokenId) { - beam.output_token_ids = [...beam.output_token_ids, newTokenId]; - beam.model_input_ids = new Tensor("int64", [BigInt(newTokenId)], [1, 1]); - } - var PreTrainedModel = class extends Callable { - main_input_name = "input_ids"; - /** - * Creates a new instance of the `PreTrainedModel` class. - * @param {Object} config The model configuration. - * @param {any} session session for the model. - */ - constructor(config, session) { - super(); - this.config = config; - this.session = session; - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); - const modelType = MODEL_TYPE_MAPPING.get(modelName); - this.can_generate = false; - this._runBeam = null; - this._getStartBeams = null; - this._updateBeam = null; - this._forward = null; - if (modelType === MODEL_TYPES.DecoderOnly) { - this.can_generate = true; - this._runBeam = decoderRunBeam; - this._getStartBeams = decoderStartBeams; - this._updateBeam = decoderUpdatebeam; - this._forward = decoderForward; - } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { - this.can_generate = true; - this._runBeam = seq2seqRunBeam; - this._getStartBeams = seq2seqStartBeams; - this._updateBeam = seq2seqUpdatebeam; - this._forward = seq2seqForward; - } else if (modelType === MODEL_TYPES.EncoderDecoder) { - this._forward = encoderForward; - } else { - this._forward = encoderForward; - } - } - /** - * Disposes of all the ONNX sessions that were created during inference. - * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. - * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry - */ - async dispose() { - const promises = []; - for (let key of Object.keys(this)) { - const item = this[key]; - if (item instanceof InferenceSession) { - promises.push(item.handler.dispose()); - } - } - return await Promise.all(promises); - } - /** - * Instantiate one of the model classes of the library from a pretrained model. - * - * The model class to instantiate is selected based on the `model_type` property of the config object - * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. - * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. - * - * @returns {Promise} A new instance of the `PreTrainedModel` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - quantized = true, - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main", - model_file_name = null - } = {}) { - let options = { - quantized, - progress_callback, - config, - cache_dir, - local_files_only, - revision, - model_file_name - }; - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); - const modelType = MODEL_TYPE_MAPPING.get(modelName); - let info; - if (modelType === MODEL_TYPES.DecoderOnly) { - info = await Promise.all([ - AutoConfig.from_pretrained(pretrained_model_name_or_path, options), - constructSession(pretrained_model_name_or_path, options.model_file_name ?? "decoder_model_merged", options), - getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options) - ]); - } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { - info = await Promise.all([ - AutoConfig.from_pretrained(pretrained_model_name_or_path, options), - constructSession(pretrained_model_name_or_path, "encoder_model", options), - constructSession(pretrained_model_name_or_path, "decoder_model_merged", options), - getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options) - ]); - } else if (modelType === MODEL_TYPES.EncoderDecoder) { - info = await Promise.all([ - AutoConfig.from_pretrained(pretrained_model_name_or_path, options), - constructSession(pretrained_model_name_or_path, "encoder_model", options), - constructSession(pretrained_model_name_or_path, "decoder_model_merged", options) - ]); - } else { - if (modelType !== MODEL_TYPES.EncoderOnly) { - console.warn(`Model type for '${modelName}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`); - } - info = await Promise.all([ - AutoConfig.from_pretrained(pretrained_model_name_or_path, options), - constructSession(pretrained_model_name_or_path, options.model_file_name ?? "model", options) - ]); - } - return new this(...info); - } - /** - * Runs the model with the provided inputs - * @param {Object} model_inputs Object containing input tensors - * @returns {Promise} Object containing output tensors - */ - async _call(model_inputs) { - return await this.forward(model_inputs); - } - /** - * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method - * will be chosen based on the model type. - * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. - * @returns {Promise} The output data from the model in the format specified in the ONNX model. - * @throws {Error} This method must be implemented in subclasses. - */ - async forward(model_inputs) { - return await this._forward(this, model_inputs); - } - /** - * @param {import('./utils/generation.js').GenerationConfigType} generation_config - * @param {number} input_ids_seq_length The starting sequence length for the input ids. - * @returns {LogitsProcessorList} - * @private - */ - _get_logits_processor(generation_config, input_ids_seq_length, logits_processor = null) { - const processors = new LogitsProcessorList(); - if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) { - processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); - } - if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { - processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); - } - if (generation_config.bad_words_ids !== null) { - processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)); - } - if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { - processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); - } - if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { - processors.push(new MinNewTokensLengthLogitsProcessor( - input_ids_seq_length, - generation_config.min_new_tokens, - generation_config.eos_token_id - )); - } - if (generation_config.forced_bos_token_id !== null) { - processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); - } - if (generation_config.forced_eos_token_id !== null) { - processors.push(new ForcedEOSTokenLogitsProcessor( - generation_config.max_length, - generation_config.forced_eos_token_id - )); - } - if (generation_config.begin_suppress_tokens !== null) { - let begin_index = input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null ? input_ids_seq_length : input_ids_seq_length + 1; - if (generation_config.forced_decoder_ids !== null) { - begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0]; - } - processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)); - } - if (generation_config.forced_decoder_ids !== null) { - processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids)); - } - if (logits_processor !== null) { - processors.extend(logits_processor); - } - return processors; - } - /** - * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. - * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. - * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters. - * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation. - */ - _get_generation_config(generation_config) { - let gen_config = new GenerationConfig(this.config); - if ("generation_config" in this) { - Object.assign(gen_config, this.generation_config); - } - if (generation_config !== null) { - Object.assign(gen_config, generation_config); - } - return gen_config; - } - /** - * @typedef {import('./utils/maths.js').TypedArray} TypedArray - */ - /** - * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput - * @typedef {Object} DecoderOutput - * - * Generates text based on the given inputs and generation configuration using the model. - * @param {Tensor|Array|TypedArray} inputs An array of input token IDs. - * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used. - * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created. - * @param {Object} options options - * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs. - * @returns {Promise} An array of generated output sequences, where each sequence is an array of token IDs. - * @throws {Error} Throws an error if the inputs array is empty. - */ - async generate(inputs, generation_config = null, logits_processor = null, { - inputs_attention_mask = null - } = {}) { - if (!this.can_generate) { - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); - let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; - const modelType = this.config.model_type; - const possibleInfo = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType); - if (possibleInfo) { - errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`; - } - throw Error(errorMessage); - } - if (!(inputs instanceof Tensor) && !isTypedArray(inputs) && !Array.isArray(inputs)) { - throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`); - } - let input_ids_seq_length; - if (this.config.is_encoder_decoder) { - input_ids_seq_length = 0; - } else { - input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length; - if (input_ids_seq_length === 0) { - throw Error("Must supply a non-empty array of input token ids."); - } - } - generation_config = this._get_generation_config(generation_config); - logits_processor = logits_processor ?? new LogitsProcessorList(); - logits_processor = this._get_logits_processor( - generation_config, - input_ids_seq_length, - logits_processor - ); - let eos_token_ids = generation_config.eos_token_id; - if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) { - eos_token_ids = [eos_token_ids]; - } - let numOutputTokens = 1; - const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity); - const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null; - let sampler = Sampler.getSampler(generation_config); - let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask); - while (beams.some((x) => !x.done) && numOutputTokens < maxOutputTokens) { - let newest_beams = []; - for (let beam of beams) { - if (beam.done) { - newest_beams.push(beam); - continue; - } - if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) { - beam.done = true; - newest_beams.push(beam); - continue; - } - let output = await this.runBeam(beam); - if (generation_config.output_attentions) { - this.addAttentionsToBeam(beam, output); - } - if (generation_config.output_scores) { - } - let logits = output.logits.slice(null, -1, null); - logits_processor(beam.output_token_ids, logits); - let sampledTokens = sampler(logits); - for (let [newTokenId, logProb] of sampledTokens) { - let newBeam = { ...beam }; - this.updateBeam(newBeam, newTokenId); - newBeam.score += logProb; - if (eos_token_ids && eos_token_ids.includes(newTokenId)) { - newBeam.done = true; - } - newest_beams.push(newBeam); - } - } - ++numOutputTokens; - newest_beams = this.groupBeams(newest_beams).map( - (group) => group.sort((a, b) => b.score - a.score).slice(0, generation_config.num_beams) - // remove outside beam width - ); - beams = newest_beams.flat(); - if (generation_config.callback_function) { - generation_config.callback_function(beams); - } - } - const groupedBeams = this.groupBeams(beams); - const getFlattened = (key) => groupedBeams.map( - (batch) => { - if (generation_config.num_return_sequences > 1) { - return batch.slice(0, generation_config.num_return_sequences).map((x) => x[key]); - } else { - return [batch[0][key]]; - } - } - ).flat(); - const sequences = getFlattened("output_token_ids"); - if (generation_config.return_dict_in_generate) { - const decoder_attentions = getFlattened("decoder_attentions"); - const cross_attentions = getFlattened("cross_attentions"); - return { - sequences, - decoder_attentions, - cross_attentions - }; - } else { - return sequences; - } - } - /** - * Helper function to add attentions to beam - * @param {Object} beam - * @param {Object} output - * @private - */ - addAttentionsToBeam(beam, output) { - if (this.config.is_encoder_decoder) { - if (!output.cross_attentions || output.cross_attentions.length === 0) { - throw Error( - "`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`." - ); - } - if (!beam.cross_attentions) { - beam.cross_attentions = []; - } - beam.cross_attentions.push(output.cross_attentions); - } - if (!output.decoder_attentions || output.decoder_attentions.length === 0) { - throw Error( - "`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`." - ); - } - if (!beam.decoder_attentions) { - beam.decoder_attentions = []; - } - beam.decoder_attentions.push(output.decoder_attentions); - } - /** - * Groups an array of beam objects by their ids. - * - * @param {Array} beams The array of beam objects to group. - * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id. - */ - groupBeams(beams) { - const groups = /* @__PURE__ */ Object.create(null); - for (const obj of beams) { - if (groups[obj.id] === void 0) { - groups[obj.id] = [obj]; - } else { - groups[obj.id].push(obj); - } - } - return Object.values(groups); - } - /** - * Returns an object containing past key values from the given decoder results object. - * - * @param {Object} decoderResults The decoder results object. - * @param {Object} pastKeyValues The previous past key values. - * @returns {Object} An object containing past key values. - */ - getPastKeyValues(decoderResults, pastKeyValues) { - const pkvs = /* @__PURE__ */ Object.create(null); - for (const name2 in decoderResults) { - if (name2.startsWith("present")) { - let newName = name2.replace("present", "past_key_values"); - if (pastKeyValues && name2.includes("encoder")) { - pkvs[newName] = pastKeyValues[newName]; - } else { - pkvs[newName] = decoderResults[name2]; - } - } - } - return pkvs; - } - /** - * Returns an object containing attentions from the given decoder results object. - * - * @param {Object} decoderResults The decoder results object. - * @returns {Object} An object containing attentions. - */ - getAttentions(decoderResults) { - const attns = /* @__PURE__ */ Object.create(null); - for (const attnName of ["cross_attentions", "decoder_attentions"]) { - const result = []; - for (const name2 in decoderResults) { - if (name2.startsWith(attnName)) { - const index = name2.split(".").pop(); - result[index] = decoderResults[name2]; - } - } - attns[attnName] = result; - } - return attns; - } - /** - * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. - * - * @param {Object} decoderFeeds The decoder feeds object to add past key values to. - * @param {Object} pastKeyValues An object containing past key values. - */ - addPastKeyValues(decoderFeeds, pastKeyValues) { - if (pastKeyValues) { - Object.assign(decoderFeeds, pastKeyValues); - } else { - const batch_size = 1; - if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) { - let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv]; - let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv]; - for (let i = 0; i < this.num_decoder_layers; ++i) { - decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor("float32", [], encoder_dims); - decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor("float32", [], encoder_dims); - decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor("float32", [], decoder_dims); - decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor("float32", [], decoder_dims); - } - } else if (this.config.model_type === "falcon") { - let dims = [batch_size * this.num_heads, 0, this.dim_kv]; - for (let i = 0; i < this.num_layers; ++i) { - decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims); - decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], dims); - } - } else if (this.config.multi_query) { - let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv]; - for (let i = 0; i < this.num_layers; ++i) { - decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor("float32", [], dims); - } - } else if (this.config.model_type === "bloom") { - let keyDims = [batch_size * this.num_heads, this.dim_kv, 0]; - let valueDims = [batch_size * this.num_heads, 0, this.dim_kv]; - for (let i = 0; i < this.num_layers; ++i) { - decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], keyDims); - decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], valueDims); - } - } else { - let dims = [batch_size, this.num_heads, 0, this.dim_kv]; - for (let i = 0; i < this.num_layers; ++i) { - decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims); - decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], dims); - } - } - } - } - /** - * Initializes and returns the beam for text generation task - * @param {Tensor} inputTokenIds The input token ids. - * @param {Object} generation_config The generation config. - * @param {number} numOutputTokens The number of tokens to be generated. - * @param {Tensor} inputs_attention_mask Optional input attention mask. - * @returns {any} A Beam object representing the initialized beam. - * @private - */ - getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { - return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask); - } - /** - * Runs a single step of the beam search generation algorithm. - * @param {any} beam The current beam being generated. - * @returns {Promise} The updated beam after a single generation step. - * @private - */ - async runBeam(beam) { - return await this._runBeam(this, beam); - } - /** - * Update a beam with a new token ID. - * @param {Object} beam The beam to update. - * @param {number} newTokenId The new token ID to add to the beam's output. - * @private - */ - updateBeam(beam, newTokenId) { - return this._updateBeam(beam, newTokenId); - } - }; - var ModelOutput = class { - }; - var BertPreTrainedModel = class extends PreTrainedModel { - }; - var BertModel = class extends BertPreTrainedModel { - }; - var BertForMaskedLM = class extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var BertForSequenceClassification = class extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var BertForTokenClassification = class extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var BertForQuestionAnswering = class extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var RoFormerPreTrainedModel = class extends PreTrainedModel { - }; - var RoFormerModel = class extends RoFormerPreTrainedModel { - }; - var RoFormerForMaskedLM = class extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var RoFormerForSequenceClassification = class extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var RoFormerForTokenClassification = class extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var RoFormerForQuestionAnswering = class extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var ConvBertPreTrainedModel = class extends PreTrainedModel { - }; - var ConvBertModel = class extends ConvBertPreTrainedModel { - }; - var ConvBertForMaskedLM = class extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var ConvBertForSequenceClassification = class extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var ConvBertForTokenClassification = class extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var ConvBertForQuestionAnswering = class extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var ElectraPreTrainedModel = class extends PreTrainedModel { - }; - var ElectraModel = class extends ElectraPreTrainedModel { - }; - var ElectraForMaskedLM = class extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var ElectraForSequenceClassification = class extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var ElectraForTokenClassification = class extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var ElectraForQuestionAnswering = class extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var CamembertPreTrainedModel = class extends PreTrainedModel { - }; - var CamembertModel = class extends CamembertPreTrainedModel { - }; - var CamembertForMaskedLM = class extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var CamembertForSequenceClassification = class extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var CamembertForTokenClassification = class extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var CamembertForQuestionAnswering = class extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var DebertaPreTrainedModel = class extends PreTrainedModel { - }; - var DebertaModel = class extends DebertaPreTrainedModel { - }; - var DebertaForMaskedLM = class extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var DebertaForSequenceClassification = class extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var DebertaForTokenClassification = class extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var DebertaForQuestionAnswering = class extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var DebertaV2PreTrainedModel = class extends PreTrainedModel { - }; - var DebertaV2Model = class extends DebertaV2PreTrainedModel { - }; - var DebertaV2ForMaskedLM = class extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var DebertaV2ForSequenceClassification = class extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var DebertaV2ForTokenClassification = class extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var DebertaV2ForQuestionAnswering = class extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var DistilBertPreTrainedModel = class extends PreTrainedModel { - }; - var DistilBertModel = class extends DistilBertPreTrainedModel { - }; - var DistilBertForSequenceClassification = class extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var DistilBertForTokenClassification = class extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var DistilBertForQuestionAnswering = class extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var DistilBertForMaskedLM = class extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var EsmPreTrainedModel = class extends PreTrainedModel { - }; - var EsmModel = class extends EsmPreTrainedModel { - }; - var EsmForMaskedLM = class extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var EsmForSequenceClassification = class extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var EsmForTokenClassification = class extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var MobileBertPreTrainedModel = class extends PreTrainedModel { - }; - var MobileBertModel = class extends MobileBertPreTrainedModel { - }; - var MobileBertForMaskedLM = class extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var MobileBertForSequenceClassification = class extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var MobileBertForQuestionAnswering = class extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var MPNetPreTrainedModel = class extends PreTrainedModel { - }; - var MPNetModel = class extends MPNetPreTrainedModel { - }; - var MPNetForMaskedLM = class extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var MPNetForSequenceClassification = class extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var MPNetForTokenClassification = class extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var MPNetForQuestionAnswering = class extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var SqueezeBertPreTrainedModel = class extends PreTrainedModel { - }; - var SqueezeBertModel = class extends SqueezeBertPreTrainedModel { - }; - var SqueezeBertForMaskedLM = class extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var SqueezeBertForSequenceClassification = class extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var SqueezeBertForQuestionAnswering = class extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var AlbertPreTrainedModel = class extends PreTrainedModel { - }; - var AlbertModel = class extends AlbertPreTrainedModel { - }; - var AlbertForSequenceClassification = class extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var AlbertForQuestionAnswering = class extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var AlbertForMaskedLM = class extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var T5PreTrainedModel = class extends PreTrainedModel { - }; - var T5Model = class extends T5PreTrainedModel { - }; - var T5ForConditionalGeneration = class extends T5PreTrainedModel { - /** - * Creates a new instance of the `T5ForConditionalGeneration` class. - * @param {Object} config The model configuration. - * @param {any} session session for the model. - * @param {any} decoder_merged_session session for the decoder. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.num_decoder_layers; - this.num_decoder_heads = this.config.num_heads; - this.decoder_dim_kv = this.config.d_kv; - this.num_encoder_layers = this.config.num_layers; - this.num_encoder_heads = this.config.num_heads; - this.encoder_dim_kv = this.config.d_kv; - } - }; - var LongT5PreTrainedModel = class extends PreTrainedModel { - }; - var LongT5Model = class extends LongT5PreTrainedModel { - }; - var LongT5ForConditionalGeneration = class extends LongT5PreTrainedModel { - /** - * Creates a new instance of the `LongT5ForConditionalGeneration` class. - * @param {Object} config The model configuration. - * @param {any} session session for the model. - * @param {any} decoder_merged_session session for the decoder. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.num_decoder_layers; - this.num_decoder_heads = this.config.num_heads; - this.decoder_dim_kv = this.config.d_kv; - this.num_encoder_layers = this.config.num_layers; - this.num_encoder_heads = this.config.num_heads; - this.encoder_dim_kv = this.config.d_kv; - } - }; - var MT5PreTrainedModel = class extends PreTrainedModel { - }; - var MT5Model = class extends MT5PreTrainedModel { - }; - var MT5ForConditionalGeneration = class extends MT5PreTrainedModel { - /** - * Creates a new instance of the `MT5ForConditionalGeneration` class. - * @param {any} config The model configuration. - * @param {any} session The ONNX session containing the encoder weights. - * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.num_decoder_layers; - this.num_decoder_heads = this.config.num_heads; - this.decoder_dim_kv = this.config.d_kv; - this.num_encoder_layers = this.config.num_layers; - this.num_encoder_heads = this.config.num_heads; - this.encoder_dim_kv = this.config.d_kv; - } - }; - var BartPretrainedModel = class extends PreTrainedModel { - }; - var BartModel = class extends BartPretrainedModel { - }; - var BartForConditionalGeneration = class extends BartPretrainedModel { - /** - * Creates a new instance of the `BartForConditionalGeneration` class. - * @param {Object} config The configuration object for the Bart model. - * @param {Object} session The ONNX session used to execute the model. - * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. - * @param {Object} generation_config The generation configuration object. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var BartForSequenceClassification = class extends BartPretrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var MBartPreTrainedModel = class extends PreTrainedModel { - }; - var MBartModel = class extends MBartPreTrainedModel { - }; - var MBartForConditionalGeneration = class extends MBartPreTrainedModel { - /** - * Creates a new instance of the `MBartForConditionalGeneration` class. - * @param {Object} config The configuration object for the Bart model. - * @param {Object} session The ONNX session used to execute the model. - * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. - * @param {Object} generation_config The generation configuration object. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var MBartForSequenceClassification = class extends MBartPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var MBartForCausalLM = class extends MBartPreTrainedModel { - /** - * Creates a new instance of the `MBartForCausalLM` class. - * @param {Object} config Configuration object for the model. - * @param {Object} decoder_merged_session ONNX Session object for the decoder. - * @param {Object} generation_config Configuration object for the generation process. - */ - constructor(config, decoder_merged_session, generation_config) { - super(config, decoder_merged_session); - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var BlenderbotPreTrainedModel = class extends PreTrainedModel { - }; - var BlenderbotModel = class extends BlenderbotPreTrainedModel { - }; - var BlenderbotForConditionalGeneration = class extends BlenderbotPreTrainedModel { - /** - * Creates a new instance of the `BlenderbotForConditionalGeneration` class. - * @param {any} config The model configuration. - * @param {any} session The ONNX session containing the encoder weights. - * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var BlenderbotSmallPreTrainedModel = class extends PreTrainedModel { - }; - var BlenderbotSmallModel = class extends BlenderbotSmallPreTrainedModel { - }; - var BlenderbotSmallForConditionalGeneration = class extends BlenderbotSmallPreTrainedModel { - /** - * Creates a new instance of the `BlenderbotForConditionalGeneration` class. - * @param {any} config The model configuration. - * @param {any} session The ONNX session containing the encoder weights. - * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var RobertaPreTrainedModel = class extends PreTrainedModel { - }; - var RobertaModel = class extends RobertaPreTrainedModel { - }; - var RobertaForMaskedLM = class extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var RobertaForSequenceClassification = class extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var RobertaForTokenClassification = class extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var RobertaForQuestionAnswering = class extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var XLMPreTrainedModel = class extends PreTrainedModel { - }; - var XLMModel = class extends XLMPreTrainedModel { - }; - var XLMWithLMHeadModel = class extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var XLMForSequenceClassification = class extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var XLMForTokenClassification = class extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var XLMForQuestionAnswering = class extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var XLMRobertaPreTrainedModel = class extends PreTrainedModel { - }; - var XLMRobertaModel = class extends XLMRobertaPreTrainedModel { - }; - var XLMRobertaForMaskedLM = class extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } - }; - var XLMRobertaForSequenceClassification = class extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var XLMRobertaForTokenClassification = class extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } - }; - var XLMRobertaForQuestionAnswering = class extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } - }; - var ASTPreTrainedModel = class extends PreTrainedModel { - }; - var ASTModel = class extends ASTPreTrainedModel { - }; - var ASTForAudioClassification = class extends ASTPreTrainedModel { - }; - var WhisperPreTrainedModel = class extends PreTrainedModel { - }; - var WhisperModel = class extends WhisperPreTrainedModel { - }; - var WhisperForConditionalGeneration = class extends WhisperPreTrainedModel { - requires_attention_mask = false; - main_input_name = "input_features"; - /** - * Creates a new instance of the `WhisperForConditionalGeneration` class. - * @param {Object} config Configuration object for the model. - * @param {Object} session ONNX Session object for the model. - * @param {Object} decoder_merged_session ONNX Session object for the decoder. - * @param {Object} generation_config Configuration object for the generation process. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - /** - * @typedef {Object} WhisperGenerationConfig - * @extends GenerationConfig - * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. - * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps - * with the text. This can be used with or without the `return_timestamps` option. To get word-level - * timestamps, use the tokenizer to group the tokens into words. - * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps. - */ - /** - * Generates outputs based on input and generation configuration. - * @param {Object} inputs Input data for the model. - * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process. - * @param {Object} logits_processor Optional logits processor object. - * @returns {Promise} Promise object represents the generated outputs. - */ - async generate(inputs, generation_config = null, logits_processor = null) { - generation_config = this._get_generation_config(generation_config); - generation_config.return_timestamps ??= false; - if (generation_config.return_timestamps) { - logits_processor = [new WhisperTimeStampLogitsProcessor(generation_config)]; - } - if (generation_config.return_token_timestamps) { - generation_config.output_attentions = true; - generation_config.return_dict_in_generate = true; - if (generation_config.task === "translate") { - console.warn("Token-level timestamps may not be reliable for task 'translate'."); - } - if (!generation_config.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." - ); - } - } - const outputs = await super.generate(inputs, generation_config, logits_processor); - if (generation_config.return_token_timestamps && generation_config.alignment_heads) { - outputs["token_timestamps"] = this._extract_token_timestamps( - outputs, - generation_config.alignment_heads, - generation_config.num_frames - ); - } - return outputs; - } - /** - * Calculates token-level timestamps using the encoder-decoder cross-attentions and - * dynamic time-warping (DTW) to map each output token to a position in the input audio. - * @param {Object} generate_outputs Outputs generated by the model - * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model - * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model - * @param {number[][]} generate_outputs.sequences The sequences output by the model - * @param {number[][]} alignment_heads Alignment heads of the model - * @param {number} [num_frames=null] Number of frames in the input audio. - * @param {number} [time_precision=0.02] Precision of the timestamps in seconds - * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token - */ - _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) { - if (!generate_outputs.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`." - ); - } - let median_filter_width = this.config.median_filter_width; - if (median_filter_width === void 0) { - console.warn("Model config has no `median_filter_width`, using default value of 7."); - median_filter_width = 7; - } - const batchedMatrices = generate_outputs.cross_attentions.map((batch) => { - let cross_attentions = Array.from( - { length: this.config.decoder_layers }, - (_, i) => cat(batch.map((x) => x[i]), 2) - ); - let weights = stack(alignment_heads.map(([l, h]) => { - return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h); - })); - weights = weights.transpose(1, 0, 2, 3); - let [std, calculatedMean] = std_mean(weights, -2, 0, true); - let smoothedWeights = weights.clone(); - for (let a = 0; a < smoothedWeights.dims[0]; ++a) { - let aTensor = smoothedWeights[a]; - for (let b = 0; b < aTensor.dims[0]; ++b) { - let bTensor = aTensor[b]; - const stdTensor = std[a][b][0]; - const meanTensor = calculatedMean[a][b][0]; - for (let c = 0; c < bTensor.dims[0]; ++c) { - let cTensor = bTensor[c]; - for (let d = 0; d < cTensor.data.length; ++d) { - cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d]; - } - cTensor.data.set(medianFilter(cTensor.data, median_filter_width)); - } - } - } - const matrix = mean(smoothedWeights, 1); - return matrix; - }); - const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length]; - const timestamps = new Tensor( - "float32", - new Float32Array(timestampsShape[0] * timestampsShape[1]), - timestampsShape - ); - for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { - const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); - let [text_indices, time_indices] = dynamicTimeWarping(matrix); - let diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]); - let jumps = mergeArrays([1], diffs).map((x) => !!x); - let jump_times = []; - for (let i = 0; i < jumps.length; ++i) { - if (jumps[i]) { - jump_times.push(time_indices[i] * time_precision); - } - } - timestamps[batch_idx].data.set(jump_times, 1); - } - return timestamps; - } - }; - var VisionEncoderDecoderModel = class extends PreTrainedModel { - main_input_name = "pixel_values"; - /** - * Creates a new instance of the `VisionEncoderDecoderModel` class. - * @param {Object} config The configuration object specifying the hyperparameters and other model settings. - * @param {Object} session The ONNX session containing the encoder model. - * @param {any} decoder_merged_session The ONNX session containing the merged decoder model. - * @param {Object} generation_config Configuration object for the generation process. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - const encoderConfig = this.config.encoder; - const decoderConfig = this.config.decoder; - const encoderModelType = encoderConfig.model_type; - const encoderModel = MODEL_MAPPING_NAMES_ENCODER_ONLY.get(encoderModelType) ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(encoderModelType); - if (!encoderModel) { - console.warn(`Model type for encoder '${encoderModelType}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`); - } - const decoderModel = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(decoderConfig.model_type); - if (!decoderModel) { - throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`); - } - const decoderModelClass = decoderModel[1]; - const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config); - this.add_encoder_pkv = "num_decoder_layers" in decoder; - if (this.add_encoder_pkv) { - this.num_decoder_layers = decoder.num_decoder_layers; - this.num_decoder_heads = decoder.num_decoder_heads; - this.decoder_dim_kv = decoder.decoder_dim_kv; - this.num_encoder_layers = decoder.num_encoder_layers; - this.num_encoder_heads = decoder.num_encoder_heads; - this.encoder_dim_kv = decoder.encoder_dim_kv; - } else { - this.num_layers = decoder.num_layers; - this.num_heads = decoder.num_heads; - this.dim_kv = decoder.dim_kv; - } - } - }; - var CLIPPreTrainedModel = class extends PreTrainedModel { - }; - var CLIPModel = class extends CLIPPreTrainedModel { - }; - var CLIPTextModelWithProjection = class extends CLIPPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "text_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var CLIPVisionModelWithProjection = class extends CLIPPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "vision_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var SiglipPreTrainedModel = class extends PreTrainedModel { - }; - var SiglipModel = class extends SiglipPreTrainedModel { - }; - var SiglipTextModel = class extends SiglipPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "text_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var SiglipVisionModel = class extends CLIPPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "vision_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var ChineseCLIPPreTrainedModel = class extends PreTrainedModel { - }; - var ChineseCLIPModel = class extends ChineseCLIPPreTrainedModel { - }; - var CLIPSegPreTrainedModel = class extends PreTrainedModel { - }; - var CLIPSegModel = class extends CLIPSegPreTrainedModel { - }; - var CLIPSegForImageSegmentation = class extends CLIPSegPreTrainedModel { - }; - var GPT2PreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `GPT2PreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_head; - this.num_layers = this.config.n_layer; - this.dim_kv = this.config.n_embd / this.num_heads; - } - }; - var GPT2Model = class extends GPT2PreTrainedModel { - }; - var GPT2LMHeadModel = class extends GPT2PreTrainedModel { - }; - var GPTNeoPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `GPTNeoPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_heads; - this.num_layers = this.config.num_layers; - this.dim_kv = this.config.hidden_size / this.num_heads; - } - }; - var GPTNeoModel = class extends GPTNeoPreTrainedModel { - }; - var GPTNeoForCausalLM = class extends GPTNeoPreTrainedModel { - }; - var GPTNeoXPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `GPTNeoXPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_attention_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.num_heads; - } - }; - var GPTNeoXModel = class extends GPTNeoXPreTrainedModel { - }; - var GPTNeoXForCausalLM = class extends GPTNeoXPreTrainedModel { - }; - var GPTJPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `GPTJPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_head; - this.num_layers = this.config.n_layer; - this.dim_kv = this.config.n_embd / this.num_heads; - } - }; - var GPTJModel = class extends GPTJPreTrainedModel { - }; - var GPTJForCausalLM = class extends GPTJPreTrainedModel { - }; - var GPTBigCodePreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `GPTBigCodePreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_head; - this.num_layers = this.config.n_layer; - this.dim_kv = this.config.n_embd / this.num_heads; - } - }; - var GPTBigCodeModel = class extends GPTBigCodePreTrainedModel { - }; - var GPTBigCodeForCausalLM = class extends GPTBigCodePreTrainedModel { - }; - var CodeGenPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `CodeGenPreTrainedModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_head; - this.num_layers = this.config.n_layer; - this.dim_kv = this.config.n_embd / this.num_heads; - } - }; - var CodeGenModel = class extends CodeGenPreTrainedModel { - }; - var CodeGenForCausalLM = class extends CodeGenPreTrainedModel { - }; - var LlamaPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `LlamaPreTrainedModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; - } - }; - var LlamaModel = class extends LlamaPreTrainedModel { - }; - var LlamaForCausalLM = class extends LlamaPreTrainedModel { - }; - var PhiPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `PhiPreTrainedModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_attention_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.num_heads; - } - }; - var PhiModel = class extends PhiPreTrainedModel { - }; - var PhiForCausalLM = class extends PhiPreTrainedModel { - }; - var BloomPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `BloomPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_head; - this.num_layers = this.config.n_layer; - this.dim_kv = this.config.hidden_size / this.num_heads; - } - }; - var BloomModel = class extends BloomPreTrainedModel { - }; - var BloomForCausalLM = class extends BloomPreTrainedModel { - }; - var MptPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `MptPreTrainedModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.n_heads; - this.num_layers = this.config.n_layers; - this.dim_kv = this.config.d_model / this.num_heads; - } - }; - var MptModel = class extends MptPreTrainedModel { - }; - var MptForCausalLM = class extends MptPreTrainedModel { - }; - var OPTPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `OPTPreTrainedModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_attention_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.num_heads; - } - }; - var OPTModel = class extends OPTPreTrainedModel { - }; - var OPTForCausalLM = class extends OPTPreTrainedModel { - }; - var ViTPreTrainedModel = class extends PreTrainedModel { - }; - var ViTModel = class extends ViTPreTrainedModel { - }; - var ViTForImageClassification = class extends ViTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var VitMattePreTrainedModel = class extends PreTrainedModel { - }; - var VitMatteForImageMatting = class extends VitMattePreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new ImageMattingOutput(await super._call(model_inputs)); - } - }; - var MobileViTPreTrainedModel = class extends PreTrainedModel { - }; - var MobileViTModel = class extends MobileViTPreTrainedModel { - }; - var MobileViTForImageClassification = class extends MobileViTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var OwlViTPreTrainedModel = class extends PreTrainedModel { - }; - var OwlViTModel = class extends OwlViTPreTrainedModel { - }; - var OwlViTForObjectDetection = class extends OwlViTPreTrainedModel { - }; - var BeitPreTrainedModel = class extends PreTrainedModel { - }; - var BeitModel = class extends BeitPreTrainedModel { - }; - var BeitForImageClassification = class extends BeitPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var DetrPreTrainedModel = class extends PreTrainedModel { - }; - var DetrModel = class extends DetrPreTrainedModel { - }; - var DetrForObjectDetection = class extends DetrPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new DetrObjectDetectionOutput(await super._call(model_inputs)); - } - }; - var DetrForSegmentation = class extends DetrPreTrainedModel { - /** - * Runs the model with the provided inputs - * @param {Object} model_inputs Model inputs - * @returns {Promise} Object containing segmentation outputs - */ - async _call(model_inputs) { - return new DetrSegmentationOutput(await super._call(model_inputs)); - } - }; - var DetrObjectDetectionOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification logits (including no-object) for all queries. - * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). - * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). - */ - constructor({ logits, pred_boxes }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - } - }; - var DetrSegmentationOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits The output logits of the model. - * @param {Tensor} output.pred_boxes Predicted boxes. - * @param {Tensor} output.pred_masks Predicted masks. - */ - constructor({ logits, pred_boxes, pred_masks }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - this.pred_masks = pred_masks; - } - }; - var TableTransformerPreTrainedModel = class extends PreTrainedModel { - }; - var TableTransformerModel = class extends TableTransformerPreTrainedModel { - }; - var TableTransformerForObjectDetection = class extends TableTransformerPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); - } - }; - var TableTransformerObjectDetectionOutput = class extends DetrObjectDetectionOutput { - }; - var DeiTPreTrainedModel = class extends PreTrainedModel { - }; - var DeiTModel = class extends DeiTPreTrainedModel { - }; - var DeiTForImageClassification = class extends DeiTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var ResNetPreTrainedModel = class extends PreTrainedModel { - }; - var ResNetModel = class extends ResNetPreTrainedModel { - }; - var ResNetForImageClassification = class extends ResNetPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var SwinPreTrainedModel = class extends PreTrainedModel { - }; - var SwinModel = class extends SwinPreTrainedModel { - }; - var SwinForImageClassification = class extends SwinPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var Swin2SRPreTrainedModel = class extends PreTrainedModel { - }; - var Swin2SRModel = class extends Swin2SRPreTrainedModel { - }; - var Swin2SRForImageSuperResolution = class extends Swin2SRPreTrainedModel { - }; - var DPTPreTrainedModel = class extends PreTrainedModel { - }; - var DPTModel = class extends DPTPreTrainedModel { - }; - var DPTForDepthEstimation = class extends DPTPreTrainedModel { - }; - var GLPNPreTrainedModel = class extends PreTrainedModel { - }; - var GLPNModel = class extends GLPNPreTrainedModel { - }; - var GLPNForDepthEstimation = class extends GLPNPreTrainedModel { - }; - var DonutSwinPreTrainedModel = class extends PreTrainedModel { - }; - var DonutSwinModel = class extends DonutSwinPreTrainedModel { - }; - var ConvNextPreTrainedModel = class extends PreTrainedModel { - }; - var ConvNextModel = class extends ConvNextPreTrainedModel { - }; - var ConvNextForImageClassification = class extends ConvNextPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var ConvNextV2PreTrainedModel = class extends PreTrainedModel { - }; - var ConvNextV2Model = class extends ConvNextV2PreTrainedModel { - }; - var ConvNextV2ForImageClassification = class extends ConvNextV2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var Dinov2PreTrainedModel = class extends PreTrainedModel { - }; - var Dinov2Model = class extends Dinov2PreTrainedModel { - }; - var Dinov2ForImageClassification = class extends Dinov2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var YolosPreTrainedModel = class extends PreTrainedModel { - }; - var YolosModel = class extends YolosPreTrainedModel { - }; - var YolosForObjectDetection = class extends YolosPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new YolosObjectDetectionOutput(await super._call(model_inputs)); - } - }; - var YolosObjectDetectionOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification logits (including no-object) for all queries. - * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). - * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). - */ - constructor({ logits, pred_boxes }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - } - }; - var SamPreTrainedModel = class extends PreTrainedModel { - }; - var SamModel = class extends SamPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. - * @param {Tensor} model_inputs.input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`. This is used by the prompt encoder to encode the prompt. - * @todo Add support for `input_labels`, `input_boxes`, `input_masks`, and `image_embeddings`. - */ - async _call(model_inputs) { - return new SamImageSegmentationOutput(await super._call(model_inputs)); - } - }; - var SamImageSegmentationOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.iou_scores The output logits of the model. - * @param {Tensor} output.pred_masks Predicted boxes. - */ - constructor({ iou_scores, pred_masks }) { - super(); - this.iou_scores = iou_scores; - this.pred_masks = pred_masks; - } - }; - var MarianPreTrainedModel = class extends PreTrainedModel { - }; - var MarianModel = class extends MarianPreTrainedModel { - }; - var MarianMTModel = class extends MarianPreTrainedModel { - /** - * Creates a new instance of the `MarianMTModel` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {any} decoder_merged_session - * @param {any} generation_config - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var M2M100PreTrainedModel = class extends PreTrainedModel { - }; - var M2M100Model = class extends M2M100PreTrainedModel { - }; - var M2M100ForConditionalGeneration = class extends M2M100PreTrainedModel { - /** - * Creates a new instance of the `M2M100ForConditionalGeneration` class. - * @param {Object} config The model configuration object. - * @param {Object} session The ONNX session object. - * @param {any} decoder_merged_session - * @param {any} generation_config - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; - } - }; - var Wav2Vec2PreTrainedModel = class extends PreTrainedModel { - }; - var Wav2Vec2Model = class extends Wav2Vec2PreTrainedModel { - }; - var Wav2Vec2ForCTC = class extends Wav2Vec2PreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); - } - }; - var Wav2Vec2ForSequenceClassification = class extends Wav2Vec2PreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var HubertModel = class extends Wav2Vec2PreTrainedModel { - }; - var HubertForCTC = class extends Wav2Vec2PreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); - } - }; - var HubertForSequenceClassification = class extends Wav2Vec2PreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var WavLMPreTrainedModel = class extends PreTrainedModel { - }; - var WavLMModel = class extends WavLMPreTrainedModel { - }; - var WavLMForCTC = class extends WavLMPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); - } - }; - var WavLMForSequenceClassification = class extends WavLMPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } - }; - var SpeechT5PreTrainedModel = class extends PreTrainedModel { - }; - var SpeechT5ForSpeechToText = class extends SpeechT5PreTrainedModel { - }; - var SpeechT5ForTextToSpeech = class extends SpeechT5PreTrainedModel { - /** - * Creates a new instance of the `SpeechT5ForTextToSpeech` class. - * @param {Object} config The model configuration. - * @param {any} session session for the model. - * @param {any} decoder_merged_session session for the decoder. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, decoder_merged_session, generation_config) { - super(config, session); - this.decoder_merged_session = decoder_merged_session; - this.generation_config = generation_config; - this.num_decoder_layers = this.config.decoder_layers; - this.num_decoder_heads = this.config.decoder_attention_heads; - this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads; - this.num_encoder_layers = this.config.encoder_layers; - this.num_encoder_heads = this.config.encoder_attention_heads; - this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads; - } - /** - * @typedef {Object} SpeechOutput - * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape - * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided - * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. - * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape - * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. - */ - /** - * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. - * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. - * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. - * @param {Object} options Optional parameters for generating speech. - * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. - * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. - * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. - * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. - * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. - * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. - */ - async generate_speech(input_values, speaker_embeddings, { - threshold = 0.5, - minlenratio = 0, - maxlenratio = 20, - vocoder = null - // output_cross_attentions = false, // TODO add - } = {}) { - const model_inputs = { - input_ids: input_values - }; - const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs); - const r = encoder_outputs.dims[1] / this.config.reduction_factor; - const maxlen = Math.floor(r * maxlenratio); - const minlen = Math.floor(r * minlenratio); - const num_mel_bins = this.config.num_mel_bins; - let spectrogramParts = []; - let past_key_values = null; - let decoder_outputs = null; - let idx = 0; - while (true) { - ++idx; - const use_cache_branch = boolTensor(!!decoder_outputs); - let output_sequence; - if (decoder_outputs) { - output_sequence = decoder_outputs.output_sequence_out; - } else { - output_sequence = new Tensor( - "float32", - new Float32Array(num_mel_bins), - [1, 1, num_mel_bins] - ); - } - let decoderFeeds = { - use_cache_branch, - output_sequence, - encoder_attention_mask, - speaker_embeddings, - encoder_hidden_states: encoder_outputs - }; - this.addPastKeyValues(decoderFeeds, past_key_values); - decoder_outputs = await sessionRun(this.decoder_merged_session, decoderFeeds); - past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values); - const { prob, spectrum } = decoder_outputs; - spectrogramParts.push(spectrum); - if (idx >= minlen && // Finished when stop token or maximum length is reached. - (Array.from(prob.data).filter((p) => p >= threshold).length > 0 || idx >= maxlen)) { - break; - } - } - const spectrogram2 = cat(spectrogramParts); - const { waveform } = await sessionRun(vocoder.session, { spectrogram: spectrogram2 }); - return { - spectrogram: spectrogram2, - waveform - // cross_attentions: null, // TODO add - }; - } - }; - var SpeechT5HifiGan = class extends PreTrainedModel { - main_input_name = "spectrogram"; - }; - var TrOCRPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `TrOCRPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers; - this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads; - this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; - } - }; - var TrOCRForCausalLM = class extends TrOCRPreTrainedModel { - }; - var MistralPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `MistralPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_key_value_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; - } - }; - var MistralModel = class extends MistralPreTrainedModel { - }; - var MistralForCausalLM = class extends MistralPreTrainedModel { - }; - var FalconPreTrainedModel = class extends PreTrainedModel { - /** - * Creates a new instance of the `FalconPreTrainedModel` class. - * @param {Object} config The configuration of the model. - * @param {any} session The ONNX session containing the model weights. - * @param {GenerationConfig} generation_config The generation configuration. - */ - constructor(config, session, generation_config) { - super(config, session); - this.generation_config = generation_config; - this.config.pad_token_id = this.config.eos_token_id; - this.num_heads = this.config.num_attention_heads; - this.num_layers = this.config.num_hidden_layers; - this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; - } - }; - var FalconModel = class extends FalconPreTrainedModel { - }; - var FalconForCausalLM = class extends FalconPreTrainedModel { - }; - var ClapPreTrainedModel = class extends PreTrainedModel { - }; - var ClapModel = class extends ClapPreTrainedModel { - }; - var ClapTextModelWithProjection = class extends ClapPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "text_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var ClapAudioModelWithProjection = class extends ClapPreTrainedModel { - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - options.model_file_name ??= "audio_model"; - return super.from_pretrained(pretrained_model_name_or_path, options); - } - }; - var VitsPreTrainedModel = class extends PreTrainedModel { - }; - var VitsModel = class extends VitsPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} The outputs for the VITS model. - */ - async _call(model_inputs) { - return new VitsModelOutput(await super._call(model_inputs)); - } - }; - var SegformerPreTrainedModel = class extends PreTrainedModel { - }; - var SegformerForImageClassification = class extends SegformerPreTrainedModel { - }; - var SegformerForSemanticSegmentation = class extends SegformerPreTrainedModel { - }; - var PretrainedMixin = class { - /** - * Mapping from model type to model class. - * @type {Map[]} - */ - static MODEL_CLASS_MAPPINGS = null; - /** - * Whether to attempt to instantiate the base class (`PretrainedModel`) if - * the model type is not found in the mapping. - */ - static BASE_IF_FAIL = false; - /** @type {PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, { - quantized = true, - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main", - model_file_name = null - } = {}) { - let options = { - quantized, - progress_callback, - config, - cache_dir, - local_files_only, - revision, - model_file_name - }; - config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options); - if (!options.config) { - options.config = config; - } - if (!this.MODEL_CLASS_MAPPINGS) { - throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); - } - for (let MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { - const modelInfo = MODEL_CLASS_MAPPING.get(config.model_type); - if (!modelInfo) { - continue; - } - return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options); - } - if (this.BASE_IF_FAIL) { - console.warn(`Unknown model class "${config.model_type}", attempting to construct from base class.`); - return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); - } else { - throw Error(`Unsupported model type: ${config.model_type}`); - } - } - }; - var MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([ - ["bert", ["BertModel", BertModel]], - ["roformer", ["RoFormerModel", RoFormerModel]], - ["electra", ["ElectraModel", ElectraModel]], - ["esm", ["EsmModel", EsmModel]], - ["convbert", ["ConvBertModel", ConvBertModel]], - ["camembert", ["CamembertModel", CamembertModel]], - ["deberta", ["DebertaModel", DebertaModel]], - ["deberta-v2", ["DebertaV2Model", DebertaV2Model]], - ["mpnet", ["MPNetModel", MPNetModel]], - ["albert", ["AlbertModel", AlbertModel]], - ["distilbert", ["DistilBertModel", DistilBertModel]], - ["roberta", ["RobertaModel", RobertaModel]], - ["xlm", ["XLMModel", XLMModel]], - ["xlm-roberta", ["XLMRobertaModel", XLMRobertaModel]], - ["clap", ["ClapModel", ClapModel]], - ["clip", ["CLIPModel", CLIPModel]], - ["clipseg", ["CLIPSegModel", CLIPSegModel]], - ["chinese_clip", ["ChineseCLIPModel", ChineseCLIPModel]], - ["siglip", ["SiglipModel", SiglipModel]], - ["mobilebert", ["MobileBertModel", MobileBertModel]], - ["squeezebert", ["SqueezeBertModel", SqueezeBertModel]], - ["wav2vec2", ["Wav2Vec2Model", Wav2Vec2Model]], - ["hubert", ["HubertModel", HubertModel]], - ["wavlm", ["WavLMModel", WavLMModel]], - ["audio-spectrogram-transformer", ["ASTModel", ASTModel]], - ["vits", ["VitsModel", VitsModel]], - ["detr", ["DetrModel", DetrModel]], - ["table-transformer", ["TableTransformerModel", TableTransformerModel]], - ["vit", ["ViTModel", ViTModel]], - ["mobilevit", ["MobileViTModel", MobileViTModel]], - ["owlvit", ["OwlViTModel", OwlViTModel]], - ["beit", ["BeitModel", BeitModel]], - ["deit", ["DeiTModel", DeiTModel]], - ["convnext", ["ConvNextModel", ConvNextModel]], - ["convnextv2", ["ConvNextV2Model", ConvNextV2Model]], - ["dinov2", ["Dinov2Model", Dinov2Model]], - ["resnet", ["ResNetModel", ResNetModel]], - ["swin", ["SwinModel", SwinModel]], - ["swin2sr", ["Swin2SRModel", Swin2SRModel]], - ["donut-swin", ["DonutSwinModel", DonutSwinModel]], - ["yolos", ["YolosModel", YolosModel]], - ["dpt", ["DPTModel", DPTModel]], - ["glpn", ["GLPNModel", GLPNModel]], - ["hifigan", ["SpeechT5HifiGan", SpeechT5HifiGan]], - ["sam", ["SamModel", SamModel]] - // TODO change to encoder-decoder when model is split correctly - ]); - var MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([ - ["t5", ["T5Model", T5Model]], - ["longt5", ["LongT5Model", LongT5Model]], - ["mt5", ["MT5Model", MT5Model]], - ["bart", ["BartModel", BartModel]], - ["mbart", ["MBartModel", MBartModel]], - ["marian", ["MarianModel", MarianModel]], - ["whisper", ["WhisperModel", WhisperModel]], - ["m2m_100", ["M2M100Model", M2M100Model]], - ["blenderbot", ["BlenderbotModel", BlenderbotModel]], - ["blenderbot-small", ["BlenderbotSmallModel", BlenderbotSmallModel]] - ]); - var MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([ - ["bloom", ["BloomModel", BloomModel]], - ["gpt2", ["GPT2Model", GPT2Model]], - ["gptj", ["GPTJModel", GPTJModel]], - ["gpt_bigcode", ["GPTBigCodeModel", GPTBigCodeModel]], - ["gpt_neo", ["GPTNeoModel", GPTNeoModel]], - ["gpt_neox", ["GPTNeoXModel", GPTNeoXModel]], - ["codegen", ["CodeGenModel", CodeGenModel]], - ["llama", ["LlamaModel", LlamaModel]], - ["phi", ["PhiModel", PhiModel]], - ["mpt", ["MptModel", MptModel]], - ["opt", ["OPTModel", OPTModel]], - ["mistral", ["MistralModel", MistralModel]], - ["falcon", ["FalconModel", FalconModel]] - ]); - var MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]], - ["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]] - ]); - var MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]] - ]); - var MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["vits", ["VitsModel", VitsModel]] - ]); - var MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["bert", ["BertForSequenceClassification", BertForSequenceClassification]], - ["roformer", ["RoFormerForSequenceClassification", RoFormerForSequenceClassification]], - ["electra", ["ElectraForSequenceClassification", ElectraForSequenceClassification]], - ["esm", ["EsmForSequenceClassification", EsmForSequenceClassification]], - ["convbert", ["ConvBertForSequenceClassification", ConvBertForSequenceClassification]], - ["camembert", ["CamembertForSequenceClassification", CamembertForSequenceClassification]], - ["deberta", ["DebertaForSequenceClassification", DebertaForSequenceClassification]], - ["deberta-v2", ["DebertaV2ForSequenceClassification", DebertaV2ForSequenceClassification]], - ["mpnet", ["MPNetForSequenceClassification", MPNetForSequenceClassification]], - ["albert", ["AlbertForSequenceClassification", AlbertForSequenceClassification]], - ["distilbert", ["DistilBertForSequenceClassification", DistilBertForSequenceClassification]], - ["roberta", ["RobertaForSequenceClassification", RobertaForSequenceClassification]], - ["xlm", ["XLMForSequenceClassification", XLMForSequenceClassification]], - ["xlm-roberta", ["XLMRobertaForSequenceClassification", XLMRobertaForSequenceClassification]], - ["bart", ["BartForSequenceClassification", BartForSequenceClassification]], - ["mbart", ["MBartForSequenceClassification", MBartForSequenceClassification]], - ["mobilebert", ["MobileBertForSequenceClassification", MobileBertForSequenceClassification]], - ["squeezebert", ["SqueezeBertForSequenceClassification", SqueezeBertForSequenceClassification]] - ]); - var MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["bert", ["BertForTokenClassification", BertForTokenClassification]], - ["roformer", ["RoFormerForTokenClassification", RoFormerForTokenClassification]], - ["electra", ["ElectraForTokenClassification", ElectraForTokenClassification]], - ["esm", ["EsmForTokenClassification", EsmForTokenClassification]], - ["convbert", ["ConvBertForTokenClassification", ConvBertForTokenClassification]], - ["camembert", ["CamembertForTokenClassification", CamembertForTokenClassification]], - ["deberta", ["DebertaForTokenClassification", DebertaForTokenClassification]], - ["deberta-v2", ["DebertaV2ForTokenClassification", DebertaV2ForTokenClassification]], - ["mpnet", ["MPNetForTokenClassification", MPNetForTokenClassification]], - ["distilbert", ["DistilBertForTokenClassification", DistilBertForTokenClassification]], - ["roberta", ["RobertaForTokenClassification", RobertaForTokenClassification]], - ["xlm", ["XLMForTokenClassification", XLMForTokenClassification]], - ["xlm-roberta", ["XLMRobertaForTokenClassification", XLMRobertaForTokenClassification]] - ]); - var MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["t5", ["T5ForConditionalGeneration", T5ForConditionalGeneration]], - ["longt5", ["LongT5ForConditionalGeneration", LongT5ForConditionalGeneration]], - ["mt5", ["MT5ForConditionalGeneration", MT5ForConditionalGeneration]], - ["bart", ["BartForConditionalGeneration", BartForConditionalGeneration]], - ["mbart", ["MBartForConditionalGeneration", MBartForConditionalGeneration]], - ["marian", ["MarianMTModel", MarianMTModel]], - ["m2m_100", ["M2M100ForConditionalGeneration", M2M100ForConditionalGeneration]], - ["blenderbot", ["BlenderbotForConditionalGeneration", BlenderbotForConditionalGeneration]], - ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", BlenderbotSmallForConditionalGeneration]] - ]); - var MODEL_WITH_LM_HEAD_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["bloom", ["BloomForCausalLM", BloomForCausalLM]], - ["gpt2", ["GPT2LMHeadModel", GPT2LMHeadModel]], - ["gptj", ["GPTJForCausalLM", GPTJForCausalLM]], - ["gpt_bigcode", ["GPTBigCodeForCausalLM", GPTBigCodeForCausalLM]], - ["gpt_neo", ["GPTNeoForCausalLM", GPTNeoForCausalLM]], - ["gpt_neox", ["GPTNeoXForCausalLM", GPTNeoXForCausalLM]], - ["codegen", ["CodeGenForCausalLM", CodeGenForCausalLM]], - ["llama", ["LlamaForCausalLM", LlamaForCausalLM]], - ["phi", ["PhiForCausalLM", PhiForCausalLM]], - ["mpt", ["MptForCausalLM", MptForCausalLM]], - ["opt", ["OPTForCausalLM", OPTForCausalLM]], - ["mbart", ["MBartForCausalLM", MBartForCausalLM]], - ["mistral", ["MistralForCausalLM", MistralForCausalLM]], - ["falcon", ["FalconForCausalLM", FalconForCausalLM]], - ["trocr", ["TrOCRForCausalLM", TrOCRForCausalLM]] - ]); - var MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["bert", ["BertForMaskedLM", BertForMaskedLM]], - ["roformer", ["RoFormerForMaskedLM", RoFormerForMaskedLM]], - ["electra", ["ElectraForMaskedLM", ElectraForMaskedLM]], - ["esm", ["EsmForMaskedLM", EsmForMaskedLM]], - ["convbert", ["ConvBertForMaskedLM", ConvBertForMaskedLM]], - ["camembert", ["CamembertForMaskedLM", CamembertForMaskedLM]], - ["deberta", ["DebertaForMaskedLM", DebertaForMaskedLM]], - ["deberta-v2", ["DebertaV2ForMaskedLM", DebertaV2ForMaskedLM]], - ["mpnet", ["MPNetForMaskedLM", MPNetForMaskedLM]], - ["albert", ["AlbertForMaskedLM", AlbertForMaskedLM]], - ["distilbert", ["DistilBertForMaskedLM", DistilBertForMaskedLM]], - ["roberta", ["RobertaForMaskedLM", RobertaForMaskedLM]], - ["xlm", ["XLMWithLMHeadModel", XLMWithLMHeadModel]], - ["xlm-roberta", ["XLMRobertaForMaskedLM", XLMRobertaForMaskedLM]], - ["mobilebert", ["MobileBertForMaskedLM", MobileBertForMaskedLM]], - ["squeezebert", ["SqueezeBertForMaskedLM", SqueezeBertForMaskedLM]] - ]); - var MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["bert", ["BertForQuestionAnswering", BertForQuestionAnswering]], - ["roformer", ["RoFormerForQuestionAnswering", RoFormerForQuestionAnswering]], - ["electra", ["ElectraForQuestionAnswering", ElectraForQuestionAnswering]], - ["convbert", ["ConvBertForQuestionAnswering", ConvBertForQuestionAnswering]], - ["camembert", ["CamembertForQuestionAnswering", CamembertForQuestionAnswering]], - ["deberta", ["DebertaForQuestionAnswering", DebertaForQuestionAnswering]], - ["deberta-v2", ["DebertaV2ForQuestionAnswering", DebertaV2ForQuestionAnswering]], - ["mpnet", ["MPNetForQuestionAnswering", MPNetForQuestionAnswering]], - ["albert", ["AlbertForQuestionAnswering", AlbertForQuestionAnswering]], - ["distilbert", ["DistilBertForQuestionAnswering", DistilBertForQuestionAnswering]], - ["roberta", ["RobertaForQuestionAnswering", RobertaForQuestionAnswering]], - ["xlm", ["XLMForQuestionAnswering", XLMForQuestionAnswering]], - ["xlm-roberta", ["XLMRobertaForQuestionAnswering", XLMRobertaForQuestionAnswering]], - ["mobilebert", ["MobileBertForQuestionAnswering", MobileBertForQuestionAnswering]], - ["squeezebert", ["SqueezeBertForQuestionAnswering", SqueezeBertForQuestionAnswering]] - ]); - var MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]] - ]); - var MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]] - ]); - var MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["vit", ["ViTForImageClassification", ViTForImageClassification]], - ["mobilevit", ["MobileViTForImageClassification", MobileViTForImageClassification]], - ["beit", ["BeitForImageClassification", BeitForImageClassification]], - ["deit", ["DeiTForImageClassification", DeiTForImageClassification]], - ["convnext", ["ConvNextForImageClassification", ConvNextForImageClassification]], - ["convnextv2", ["ConvNextV2ForImageClassification", ConvNextV2ForImageClassification]], - ["dinov2", ["Dinov2ForImageClassification", Dinov2ForImageClassification]], - ["resnet", ["ResNetForImageClassification", ResNetForImageClassification]], - ["swin", ["SwinForImageClassification", SwinForImageClassification]], - ["segformer", ["SegformerForImageClassification", SegformerForImageClassification]] - ]); - var MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["detr", ["DetrForObjectDetection", DetrForObjectDetection]], - ["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]], - ["yolos", ["YolosForObjectDetection", YolosForObjectDetection]] - ]); - var MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]] - ]); - var MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["detr", ["DetrForSegmentation", DetrForSegmentation]], - ["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]] - ]); - var MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]] - ]); - var MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["sam", ["SamModel", SamModel]] - ]); - var MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]], - ["wavlm", ["WavLMForCTC", WavLMForCTC]], - ["hubert", ["HubertForCTC", HubertForCTC]] - ]); - var MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Wav2Vec2ForSequenceClassification]], - ["wavlm", ["WavLMForSequenceClassification", WavLMForSequenceClassification]], - ["hubert", ["HubertForSequenceClassification", HubertForSequenceClassification]], - ["audio-spectrogram-transformer", ["ASTForAudioClassification", ASTForAudioClassification]] - ]); - var MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]] - ]); - var MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]] - ]); - var MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ - ["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]], - ["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]] - ]); - var MODEL_CLASS_TYPE_MAPPING = [ - [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], - [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], - [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly], - [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], - [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], - [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly] - ]; - for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { - for (const [name2, model] of mappings.values()) { - MODEL_TYPE_MAPPING.set(name2, type); - MODEL_CLASS_TO_NAME_MAPPING.set(model, name2); - MODEL_NAME_TO_CLASS_MAPPING.set(name2, model); - } - } - var CUSTOM_MAPPING = [ - ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection, MODEL_TYPES.EncoderOnly], - ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly], - ["SiglipVisionModel", SiglipVisionModel, MODEL_TYPES.EncoderOnly], - ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly] - ]; - for (const [name2, model, type] of CUSTOM_MAPPING) { - MODEL_TYPE_MAPPING.set(name2, type); - MODEL_CLASS_TO_NAME_MAPPING.set(model, name2); - MODEL_NAME_TO_CLASS_MAPPING.set(name2, model); - } - var AutoModel = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_MAPPING_NAMES_DECODER_ONLY]; - static BASE_IF_FAIL = true; - }; - var AutoModelForSequenceClassification = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; - }; - var AutoModelForTokenClassification = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; - }; - var AutoModelForSeq2SeqLM = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; - }; - var AutoModelForSpeechSeq2Seq = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; - }; - var AutoModelForTextToSpectrogram = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; - }; - var AutoModelForTextToWaveform = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; - }; - var AutoModelForCausalLM = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_WITH_LM_HEAD_MAPPING_NAMES]; - }; - var AutoModelForMaskedLM = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES]; - }; - var AutoModelForQuestionAnswering = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; - }; - var AutoModelForVision2Seq = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; - }; - var AutoModelForImageClassification = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; - }; - var AutoModelForImageSegmentation = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; - }; - var AutoModelForSemanticSegmentation = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; - }; - var AutoModelForObjectDetection = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; - }; - var AutoModelForZeroShotObjectDetection = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; - }; - var AutoModelForCTC = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES]; - }; - var AutoModelForAudioClassification = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; - }; - var AutoModelForDocumentQuestionAnswering = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; - }; - var AutoModelForImageToImage = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; - }; - var AutoModelForDepthEstimation = class extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; - }; - var Seq2SeqLMOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits The output logits of the model. - * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. - * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. - * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. - */ - constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { - super(); - this.logits = logits; - this.past_key_values = past_key_values; - this.encoder_outputs = encoder_outputs; - this.decoder_attentions = decoder_attentions; - this.cross_attentions = cross_attentions; - } - }; - var SequenceClassifierOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). - */ - constructor({ logits }) { - super(); - this.logits = logits; - } - }; - var TokenClassifierOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification scores (before SoftMax). - */ - constructor({ logits }) { - super(); - this.logits = logits; - } - }; - var MaskedLMOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - */ - constructor({ logits }) { - super(); - this.logits = logits; - } - }; - var QuestionAnsweringModelOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.start_logits Span-start scores (before SoftMax). - * @param {Tensor} output.end_logits Span-end scores (before SoftMax). - */ - constructor({ start_logits, end_logits }) { - super(); - this.start_logits = start_logits; - this.end_logits = end_logits; - } - }; - var CausalLMOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). - */ - constructor({ logits }) { - super(); - this.logits = logits; - } - }; - var ImageMattingOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. - */ - constructor({ alphas }) { - super(); - this.alphas = alphas; - } - }; - var VitsModelOutput = class extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. - * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. - * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. - */ - constructor({ waveform, spectrogram: spectrogram2 }) { - super(); - this.waveform = waveform; - this.spectrogram = spectrogram2; - } - }; - - // node_modules/@xenova/transformers/src/utils/image.js - var import_sharp = __toESM(require_lib(), 1); - var BROWSER_ENV = typeof self !== "undefined"; - var WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === "DedicatedWorkerGlobalScope"; - var createCanvasFunction; - var ImageDataClass; - var loadImageFunction; - if (BROWSER_ENV) { - createCanvasFunction = (width, height) => { - if (!self.OffscreenCanvas) { - throw new Error("OffscreenCanvas not supported by this browser."); - } - return new self.OffscreenCanvas(width, height); - }; - loadImageFunction = self.createImageBitmap; - ImageDataClass = self.ImageData; - } else if (import_sharp.default) { - loadImageFunction = async (img) => { - const metadata = await img.metadata(); - const rawChannels = metadata.channels; - let { data, info } = await img.raw().toBuffer({ resolveWithObject: true }); - const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); - if (rawChannels !== void 0 && rawChannels !== info.channels) { - newImage.convert(rawChannels); - } - return newImage; - }; - } else { - throw new Error("Unable to load image processing library."); - } - var RESAMPLING_MAPPING = { - 0: "nearest", - 1: "lanczos", - 2: "bilinear", - 3: "bicubic", - 4: "box", - 5: "hamming" - }; - var CONTENT_TYPE_MAP = /* @__PURE__ */ new Map([ - ["png", "image/png"], - ["jpg", "image/jpeg"], - ["jpeg", "image/jpeg"], - ["gif", "image/gif"] - ]); - var RawImage = class _RawImage { - /** - * Create a new `RawImage` object. - * @param {Uint8ClampedArray|Uint8Array} data The pixel data. - * @param {number} width The width of the image. - * @param {number} height The height of the image. - * @param {1|2|3|4} channels The number of channels. - */ - constructor(data, width, height, channels) { - this.data = data; - this.width = width; - this.height = height; - this.channels = channels; - } - get size() { - return [this.width, this.height]; - } - /** - * Helper method for reading an image from a variety of input types. - * @param {RawImage|string|URL} input - * @returns The image object. - * - * **Example:** Read image from a URL. - * ```javascript - * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * // RawImage { - * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], - * // "width": 800, - * // "height": 533, - * // "channels": 3 - * // } - * ``` - */ - static async read(input) { - if (input instanceof _RawImage) { - return input; - } else if (typeof input === "string" || input instanceof URL) { - return await this.fromURL(input); - } else { - throw new Error(`Unsupported input type: ${typeof input}`); - } - } - /** - * Read an image from a URL or file path. - * @param {string|URL} url The URL or file path to read the image from. - * @returns {Promise} The image object. - */ - static async fromURL(url2) { - let response = await getFile(url2); - if (response.status !== 200) { - throw new Error(`Unable to read image from "${url2}" (${response.status} ${response.statusText})`); - } - let blob = await response.blob(); - return this.fromBlob(blob); - } - /** - * Helper method to create a new Image from a blob. - * @param {Blob} blob The blob to read the image from. - * @returns {Promise} The image object. - */ - static async fromBlob(blob) { - if (BROWSER_ENV) { - let img = await loadImageFunction(blob); - const ctx = createCanvasFunction(img.width, img.height).getContext("2d"); - ctx.drawImage(img, 0, 0); - return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); - } else { - let img = (0, import_sharp.default)(await blob.arrayBuffer()); - return await loadImageFunction(img); - } - } - /** - * Helper method to create a new Image from a tensor - * @param {import('./tensor.js').Tensor} tensor - */ - static fromTensor(tensor, channel_format = "CHW") { - if (channel_format === "CHW") { - tensor = tensor.transpose(1, 2, 0); - } else if (channel_format === "HWC") { - } else { - throw new Error(`Unsupported channel format: ${channel_format}`); - } - if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { - throw new Error(`Unsupported tensor type: ${tensor.type}`); - } - switch (tensor.dims[2]) { - case 1: - case 2: - case 3: - case 4: - return new _RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); - default: - throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); - } - } - /** - * Convert the image to grayscale format. - * @returns {RawImage} `this` to support chaining. - */ - grayscale() { - if (this.channels === 1) { - return this; - } - let newData = new Uint8ClampedArray(this.width * this.height * 1); - switch (this.channels) { - case 3: - case 4: - for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { - const red = this.data[i]; - const green = this.data[i + 1]; - const blue = this.data[i + 2]; - newData[offset++] = Math.round(0.2989 * red + 0.587 * green + 0.114 * blue); - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(newData, this.width, this.height, 1); - } - /** - * Convert the image to RGB format. - * @returns {RawImage} `this` to support chaining. - */ - rgb() { - if (this.channels === 3) { - return this; - } - let newData = new Uint8ClampedArray(this.width * this.height * 3); - switch (this.channels) { - case 1: - for (let i = 0, offset = 0; i < this.data.length; ++i) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - } - break; - case 4: - for (let i = 0, offset = 0; i < this.data.length; i += 4) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i + 1]; - newData[offset++] = this.data[i + 2]; - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(newData, this.width, this.height, 3); - } - /** - * Convert the image to RGBA format. - * @returns {RawImage} `this` to support chaining. - */ - rgba() { - if (this.channels === 4) { - return this; - } - let newData = new Uint8ClampedArray(this.width * this.height * 4); - switch (this.channels) { - case 1: - for (let i = 0, offset = 0; i < this.data.length; ++i) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = 255; - } - break; - case 3: - for (let i = 0, offset = 0; i < this.data.length; i += 3) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i + 1]; - newData[offset++] = this.data[i + 2]; - newData[offset++] = 255; - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(newData, this.width, this.height, 4); - } - /** - * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. - * @param {number} width The width of the new image. - * @param {number} height The height of the new image. - * @param {Object} options Additional options for resizing. - * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. - * @returns {Promise} `this` to support chaining. - */ - async resize(width, height, { - resample = 2 - } = {}) { - let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; - if (BROWSER_ENV) { - let numChannels = this.channels; - let canvas = this.toCanvas(); - const ctx = createCanvasFunction(width, height).getContext("2d"); - ctx.drawImage(canvas, 0, 0, width, height); - let resizedImage = new _RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); - return resizedImage.convert(numChannels); - } else { - let img = this.toSharp(); - switch (resampleMethod) { - case "box": - case "hamming": - if (resampleMethod === "box" || resampleMethod === "hamming") { - console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`); - resampleMethod = "bilinear"; - } - case "nearest": - case "bilinear": - case "bicubic": - img = img.affine([width / this.width, 0, 0, height / this.height], { - interpolator: resampleMethod - }); - break; - case "lanczos": - img = img.resize({ - width, - height, - fit: "fill", - kernel: "lanczos3" - // PIL Lanczos uses a kernel size of 3 - }); - break; - default: - throw new Error(`Resampling method ${resampleMethod} is not supported.`); - } - return await loadImageFunction(img); - } - } - async pad([left, right, top, bottom]) { - left = Math.max(left, 0); - right = Math.max(right, 0); - top = Math.max(top, 0); - bottom = Math.max(bottom, 0); - if (left === 0 && right === 0 && top === 0 && bottom === 0) { - return this; - } - if (BROWSER_ENV) { - let numChannels = this.channels; - let canvas = this.toCanvas(); - let newWidth = this.width + left + right; - let newHeight = this.height + top + bottom; - const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d"); - ctx.drawImage( - canvas, - 0, - 0, - this.width, - this.height, - left, - top, - newWidth, - newHeight - ); - let paddedImage = new _RawImage( - ctx.getImageData(0, 0, newWidth, newHeight).data, - newWidth, - newHeight, - 4 - ); - return paddedImage.convert(numChannels); - } else { - let img = this.toSharp().extend({ left, right, top, bottom }); - return await loadImageFunction(img); - } - } - async crop([x_min, y_min, x_max, y_max]) { - x_min = Math.max(x_min, 0); - y_min = Math.max(y_min, 0); - x_max = Math.min(x_max, this.width - 1); - y_max = Math.min(y_max, this.height - 1); - if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { - return this; - } - const crop_width = x_max - x_min + 1; - const crop_height = y_max - y_min + 1; - if (BROWSER_ENV) { - const numChannels = this.channels; - const canvas = this.toCanvas(); - const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); - ctx.drawImage( - canvas, - x_min, - y_min, - crop_width, - crop_height, - 0, - 0, - crop_width, - crop_height - ); - const resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); - return resizedImage.convert(numChannels); - } else { - const img = this.toSharp().extract({ - left: x_min, - top: y_min, - width: crop_width, - height: crop_height - }); - return await loadImageFunction(img); - } - } - async center_crop(crop_width, crop_height) { - if (this.width === crop_width && this.height === crop_height) { - return this; - } - let width_offset = (this.width - crop_width) / 2; - let height_offset = (this.height - crop_height) / 2; - if (BROWSER_ENV) { - let numChannels = this.channels; - let canvas = this.toCanvas(); - const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); - let sourceX = 0; - let sourceY = 0; - let destX = 0; - let destY = 0; - if (width_offset >= 0) { - sourceX = width_offset; - } else { - destX = -width_offset; - } - if (height_offset >= 0) { - sourceY = height_offset; - } else { - destY = -height_offset; - } - ctx.drawImage( - canvas, - sourceX, - sourceY, - crop_width, - crop_height, - destX, - destY, - crop_width, - crop_height - ); - let resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); - return resizedImage.convert(numChannels); - } else { - let img = this.toSharp(); - if (width_offset >= 0 && height_offset >= 0) { - img = img.extract({ - left: Math.floor(width_offset), - top: Math.floor(height_offset), - width: crop_width, - height: crop_height - }); - } else if (width_offset <= 0 && height_offset <= 0) { - let top = Math.floor(-height_offset); - let left = Math.floor(-width_offset); - img = img.extend({ - top, - left, - // Ensures the resulting image has the desired dimensions - right: crop_width - this.width - left, - bottom: crop_height - this.height - top - }); - } else { - let y_padding = [0, 0]; - let y_extract = 0; - if (height_offset < 0) { - y_padding[0] = Math.floor(-height_offset); - y_padding[1] = crop_height - this.height - y_padding[0]; - } else { - y_extract = Math.floor(height_offset); - } - let x_padding = [0, 0]; - let x_extract = 0; - if (width_offset < 0) { - x_padding[0] = Math.floor(-width_offset); - x_padding[1] = crop_width - this.width - x_padding[0]; - } else { - x_extract = Math.floor(width_offset); - } - img = img.extend({ - top: y_padding[0], - bottom: y_padding[1], - left: x_padding[0], - right: x_padding[1] - }).extract({ - left: x_extract, - top: y_extract, - width: crop_width, - height: crop_height - }); - } - return await loadImageFunction(img); - } - } - async toBlob(type = "image/png", quality = 1) { - if (!BROWSER_ENV) { - throw new Error("toBlob() is only supported in browser environments."); - } - const canvas = this.toCanvas(); - return await canvas.convertToBlob({ type, quality }); - } - toCanvas() { - if (!BROWSER_ENV) { - throw new Error("toCanvas() is only supported in browser environments."); - } - let cloned = this.clone().rgba(); - let clonedCanvas = createCanvasFunction(cloned.width, cloned.height); - let data = new ImageDataClass(cloned.data, cloned.width, cloned.height); - clonedCanvas.getContext("2d").putImageData(data, 0, 0); - return clonedCanvas; - } - /** - * Helper method to update the image data. - * @param {Uint8ClampedArray} data The new image data. - * @param {number} width The new width of the image. - * @param {number} height The new height of the image. - * @param {1|2|3|4|null} [channels] The new number of channels of the image. - * @private - */ - _update(data, width, height, channels = null) { - this.data = data; - this.width = width; - this.height = height; - if (channels !== null) { - this.channels = channels; - } - return this; - } - /** - * Clone the image - * @returns {RawImage} The cloned image - */ - clone() { - return new _RawImage(this.data.slice(), this.width, this.height, this.channels); - } - /** - * Helper method for converting image to have a certain number of channels - * @param {number} numChannels The number of channels. Must be 1, 3, or 4. - * @returns {RawImage} `this` to support chaining. - */ - convert(numChannels) { - if (this.channels === numChannels) - return this; - switch (numChannels) { - 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; - } - /** - * Save the image to the given path. - * @param {string} path The path to save the image to. - */ - async save(path3) { - if (BROWSER_ENV) { - if (WEBWORKER_ENV) { - throw new Error("Unable to save an image from a Web Worker."); - } - const extension = path3.split(".").pop().toLowerCase(); - const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png"; - const blob = await this.toBlob(mime); - const dataURL = URL.createObjectURL(blob); - const downloadLink = document.createElement("a"); - downloadLink.href = dataURL; - downloadLink.download = path3; - downloadLink.click(); - downloadLink.remove(); - } else if (!env.useFS) { - throw new Error("Unable to save the image because filesystem is disabled in this environment."); - } else { - const img = this.toSharp(); - return await img.toFile(path3); - } - } - toSharp() { - if (BROWSER_ENV) { - throw new Error("toSharp() is only supported in server-side environments."); - } - return (0, import_sharp.default)(this.data, { - raw: { - width: this.width, - height: this.height, - channels: this.channels - } - }); - } - }; - - // node_modules/@xenova/transformers/src/utils/audio.js - async function read_audio(url2, sampling_rate) { - if (typeof AudioContext === "undefined") { - 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 response = await (await getFile(url2)).arrayBuffer(); - const audioCTX = new AudioContext({ sampleRate: sampling_rate }); - if (typeof sampling_rate === "undefined") { - console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`); - } - const decoded = await audioCTX.decodeAudioData(response); - let audio; - if (decoded.numberOfChannels === 2) { - const SCALING_FACTOR = Math.sqrt(2); - const left = decoded.getChannelData(0); - const right = decoded.getChannelData(1); - audio = new Float32Array(left.length); - for (let i = 0; i < decoded.length; ++i) { - audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; - } - } else { - audio = decoded.getChannelData(0); - } - return audio; - } - function hanning(M) { - if (M < 1) { - return new Float64Array(); - } - if (M === 1) { - return new Float64Array([1]); - } - const denom = M - 1; - const factor = Math.PI / denom; - const cos_vals = new Float64Array(M); - for (let i = 0; i < M; ++i) { - const n = 2 * i - denom; - cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n); - } - return cos_vals; - } - var HERTZ_TO_MEL_MAPPING = { - "htk": (freq) => 2595 * Math.log10(1 + freq / 700), - "kaldi": (freq) => 1127 * Math.log(1 + freq / 700), - "slaney": (freq, min_log_hertz = 1e3, min_log_mel = 15, logstep = 27 / Math.log(6.4)) => freq >= min_log_hertz ? min_log_mel + Math.log(freq / min_log_hertz) * logstep : 3 * freq / 200 - }; - function hertz_to_mel(freq, mel_scale = "htk") { - const fn = HERTZ_TO_MEL_MAPPING[mel_scale]; - if (!fn) { - throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); - } - return typeof freq === "number" ? fn(freq) : freq.map((x) => fn(x)); - } - var MEL_TO_HERTZ_MAPPING = { - "htk": (mels) => 700 * (10 ** (mels / 2595) - 1), - "kaldi": (mels) => 700 * (Math.exp(mels / 1127) - 1), - "slaney": (mels, min_log_hertz = 1e3, min_log_mel = 15, logstep = Math.log(6.4) / 27) => mels >= min_log_mel ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) : 200 * mels / 3 - }; - function mel_to_hertz(mels, mel_scale = "htk") { - const fn = MEL_TO_HERTZ_MAPPING[mel_scale]; - if (!fn) { - throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); - } - return typeof mels === "number" ? fn(mels) : mels.map((x) => fn(x)); - } - function _create_triangular_filter_bank(fft_freqs, filter_freqs) { - const filter_diff = Float64Array.from( - { length: filter_freqs.length - 1 }, - (_, i) => filter_freqs[i + 1] - filter_freqs[i] - ); - const slopes = Array.from({ - length: fft_freqs.length - }, () => new Array(filter_freqs.length)); - for (let j = 0; j < fft_freqs.length; ++j) { - const slope = slopes[j]; - for (let i = 0; i < filter_freqs.length; ++i) { - slope[i] = filter_freqs[i] - fft_freqs[j]; - } - } - const numFreqs = filter_freqs.length - 2; - const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); - for (let j = 0; j < fft_freqs.length; ++j) { - const slope = slopes[j]; - for (let i = 0; i < numFreqs; ++i) { - const down = -slope[i] / filter_diff[i]; - const up = slope[i + 2] / filter_diff[i + 1]; - ret[i][j] = Math.max(0, Math.min(down, up)); - } - } - return ret; - } - function linspace(start, end, num) { - const step = (end - start) / (num - 1); - return Float64Array.from({ length: num }, (_, i) => start + step * i); - } - function mel_filter_bank(num_frequency_bins, num_mel_filters, min_frequency, max_frequency, sampling_rate, norm = null, mel_scale = "htk", triangularize_in_mel_space = false) { - if (norm !== null && norm !== "slaney") { - throw new Error('norm must be one of null or "slaney"'); - } - const mel_min = hertz_to_mel(min_frequency, mel_scale); - const mel_max = hertz_to_mel(max_frequency, mel_scale); - const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); - let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); - let fft_freqs; - if (triangularize_in_mel_space) { - const fft_bin_width = sampling_rate / (num_frequency_bins * 2); - fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale); - filter_freqs = mel_freqs; - } else { - fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); - } - const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); - if (norm !== null && norm === "slaney") { - for (let i = 0; i < num_mel_filters; ++i) { - const filter = mel_filters[i]; - const enorm = 2 / (filter_freqs[i + 2] - filter_freqs[i]); - for (let j = 0; j < num_frequency_bins; ++j) { - filter[j] *= enorm; - } - } - } - return mel_filters; - } - function padReflect(array, left, right) { - const padded = new array.constructor(array.length + left + right); - const w = array.length - 1; - for (let i = 0; i < array.length; ++i) { - padded[left + i] = array[i]; - } - for (let i = 1; i <= left; ++i) { - padded[left - i] = array[calculateReflectOffset(i, w)]; - } - for (let i = 1; i <= right; ++i) { - padded[w + left + i] = array[calculateReflectOffset(w - i, w)]; - } - return padded; - } - function _db_conversion_helper(spectrogram2, factor, reference, min_value, db_range) { - if (reference <= 0) { - throw new Error("reference must be greater than zero"); - } - if (min_value <= 0) { - throw new Error("min_value must be greater than zero"); - } - reference = Math.max(min_value, reference); - const logReference = Math.log10(reference); - for (let i = 0; i < spectrogram2.length; ++i) { - spectrogram2[i] = factor * Math.log10(Math.max(min_value, spectrogram2[i]) - logReference); - } - if (db_range !== null) { - if (db_range <= 0) { - throw new Error("db_range must be greater than zero"); - } - const maxValue = max(spectrogram2)[0] - db_range; - for (let i = 0; i < spectrogram2.length; ++i) { - spectrogram2[i] = Math.max(spectrogram2[i], maxValue); - } - } - return spectrogram2; - } - function amplitude_to_db(spectrogram2, reference = 1, min_value = 1e-5, db_range = null) { - return _db_conversion_helper(spectrogram2, 20, reference, min_value, db_range); - } - function power_to_db(spectrogram2, reference = 1, min_value = 1e-10, db_range = null) { - return _db_conversion_helper(spectrogram2, 10, reference, min_value, db_range); - } - function spectrogram(waveform, window2, frame_length, hop_length, { - fft_length = null, - power = 1, - center = true, - pad_mode = "reflect", - onesided = true, - preemphasis = null, - mel_filters = null, - mel_floor = 1e-10, - log_mel = null, - reference = 1, - min_value = 1e-10, - db_range = null, - remove_dc_offset = null, - // Custom parameters for efficiency reasons - max_num_frames = null, - do_pad = true, - transpose: transpose2 = false - } = {}) { - const window_length = window2.length; - if (fft_length === null) { - fft_length = frame_length; - } - if (frame_length > fft_length) { - throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`); - } - if (window_length !== frame_length) { - throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); - } - if (hop_length <= 0) { - throw new Error("hop_length must be greater than zero"); - } - if (center) { - if (pad_mode !== "reflect") { - throw new Error(`pad_mode="${pad_mode}" not implemented yet.`); - } - const half_window = Math.floor((fft_length - 1) / 2) + 1; - waveform = padReflect(waveform, half_window, half_window); - } - const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)); - const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length; - let d1 = num_frames; - let d1Max = num_frames; - if (max_num_frames !== null) { - if (max_num_frames > num_frames) { - if (do_pad) { - d1Max = max_num_frames; - } - } else { - d1Max = d1 = max_num_frames; - } - } - const fft = new FFT(fft_length); - const inputBuffer = new Float64Array(fft_length); - const outputBuffer = new Float64Array(fft.outputBufferSize); - const magnitudes = new Array(d1); - for (let i = 0; i < d1; ++i) { - const offset = i * hop_length; - for (let j = 0; j < frame_length; ++j) { - inputBuffer[j] = waveform[offset + j]; - } - if (remove_dc_offset) { - let sum = 0; - for (let j = 0; j < frame_length; ++j) { - sum += inputBuffer[j]; - } - const mean2 = sum / frame_length; - for (let j = 0; j < frame_length; ++j) { - inputBuffer[j] -= mean2; - } - } - if (preemphasis !== null) { - for (let j = frame_length - 1; j >= 1; --j) { - inputBuffer[j] -= preemphasis * inputBuffer[j - 1]; - } - inputBuffer[0] *= 1 - preemphasis; - } - for (let j = 0; j < window2.length; ++j) { - inputBuffer[j] *= window2[j]; - } - fft.realTransform(outputBuffer, inputBuffer); - const row = new Array(num_frequency_bins); - for (let j = 0; j < row.length; ++j) { - const j2 = j << 1; - row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2; - } - magnitudes[i] = row; - } - if (power !== null && power !== 2) { - const pow = 2 / power; - for (let i = 0; i < magnitudes.length; ++i) { - const magnitude = magnitudes[i]; - for (let j = 0; j < magnitude.length; ++j) { - magnitude[j] **= pow; - } - } - } - const num_mel_filters = mel_filters.length; - const mel_spec = new Float32Array(num_mel_filters * d1Max); - const dims = transpose2 ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max]; - for (let i = 0; i < num_mel_filters; ++i) { - const filter = mel_filters[i]; - for (let j = 0; j < d1; ++j) { - const magnitude = magnitudes[j]; - let sum = 0; - for (let k = 0; k < num_frequency_bins; ++k) { - sum += filter[k] * magnitude[k]; - } - mel_spec[transpose2 ? j * num_mel_filters + i : i * d1 + j] = Math.max(mel_floor, sum); - } - } - if (power !== null && log_mel !== null) { - const o = Math.min(mel_spec.length, d1 * num_mel_filters); - switch (log_mel) { - case "log": - for (let i = 0; i < o; ++i) { - mel_spec[i] = Math.log(mel_spec[i]); - } - break; - case "log10": - for (let i = 0; i < o; ++i) { - mel_spec[i] = Math.log10(mel_spec[i]); - } - break; - case "dB": - if (power === 1) { - amplitude_to_db(mel_spec, reference, min_value, db_range); - } else if (power === 2) { - power_to_db(mel_spec, reference, min_value, db_range); - } else { - throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`); - } - break; - default: - throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`); - } - } - return { data: mel_spec, dims }; - } - function window_function(window_length, name2, { - periodic = true, - frame_length = null, - center = true - } = {}) { - const length = periodic ? window_length + 1 : window_length; - let window2; - switch (name2) { - case "boxcar": - window2 = new Float64Array(length).fill(1); - break; - case "hann": - case "hann_window": - window2 = hanning(length); - break; - default: - throw new Error(`Unknown window type ${name2}.`); - } - if (periodic) { - window2 = window2.subarray(0, window_length); - } - if (frame_length === null) { - return window2; - } - if (window_length > frame_length) { - throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`); - } - return window2; - } - - // node_modules/@xenova/transformers/src/processors.js - function center_to_corners_format([centerX, centerY, width, height]) { - return [ - centerX - width / 2, - centerY - height / 2, - centerX + width / 2, - centerY + height / 2 - ]; - } - function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { - const out_logits = outputs.logits; - const out_bbox = outputs.pred_boxes; - const [batch_size, num_boxes, num_classes] = out_logits.dims; - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); - } - let toReturn = []; - for (let i = 0; i < batch_size; ++i) { - let target_size = target_sizes !== null ? target_sizes[i] : null; - let info = { - boxes: [], - classes: [], - scores: [] - }; - let logits = out_logits[i]; - let bbox = out_bbox[i]; - for (let j = 0; j < num_boxes; ++j) { - let logit = logits[j]; - let indices = []; - let probs; - if (is_zero_shot) { - probs = logit.sigmoid().data; - for (let k = 0; k < probs.length; ++k) { - if (probs[k] > threshold) { - indices.push(k); - } - } - } else { - let maxIndex = max(logit.data)[1]; - if (maxIndex === num_classes - 1) { - continue; - } - indices.push(maxIndex); - probs = softmax(logit.data); - } - for (const index of indices) { - let box = bbox[j].data; - box = center_to_corners_format(box); - if (target_size !== null) { - box = box.map((x, i2) => x * target_size[(i2 + 1) % 2]); - } - info.boxes.push(box); - info.classes.push(index); - info.scores.push(probs[index]); - } - } - toReturn.push(info); - } - return toReturn; - } - function validate_audio_inputs(audio, feature_extractor) { - if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { - throw new Error( - `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} 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.` - ); - } - } - var FeatureExtractor = class extends Callable { - /** - * Constructs a new FeatureExtractor instance. - * - * @param {Object} config The configuration for the feature extractor. - */ - constructor(config) { - super(); - this.config = config; - } - }; - var ImageFeatureExtractor = class extends FeatureExtractor { - /** - * Constructs a new ImageFeatureExtractor instance. - * - * @param {Object} config The configuration for the feature extractor. - * @param {number[]} config.image_mean The mean values for image normalization. - * @param {number[]} config.image_std The standard deviation values for image normalization. - * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range. - * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values. - * @param {boolean} config.do_normalize Whether to normalize the image pixel values. - * @param {boolean} config.do_resize Whether to resize the image. - * @param {number} config.resample What method to use for resampling. - * @param {number} config.size The size to resize the image to. - */ - constructor(config) { - super(config); - this.image_mean = this.config.image_mean ?? this.config.mean; - this.image_std = this.config.image_std ?? this.config.std; - this.resample = this.config.resample ?? 2; - this.do_rescale = this.config.do_rescale ?? true; - this.rescale_factor = this.config.rescale_factor ?? 1 / 255; - this.do_normalize = this.config.do_normalize; - this.do_resize = this.config.do_resize; - this.do_thumbnail = this.config.do_thumbnail; - this.size = this.config.size; - this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor; - this.do_center_crop = this.config.do_center_crop; - this.crop_size = this.config.crop_size; - this.do_convert_rgb = this.config.do_convert_rgb ?? true; - this.do_crop_margin = this.config.do_crop_margin; - this.pad_size = this.config.pad_size; - this.do_pad = this.config.do_pad; - if (this.do_pad && !this.pad_size && this.size && this.size.width !== void 0 && this.size.height !== void 0) { - this.pad_size = this.size; - } - } - /** - * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any - * corresponding dimension of the specified size. - * @param {RawImage} image The image to be resized. - * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. - * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. - * @returns {Promise} The resized image. - */ - async thumbnail(image, size, resample = 2) { - const input_height = image.height; - const input_width = image.width; - const output_height = size.height; - const output_width = size.width; - let height = Math.min(input_height, output_height); - let width = Math.min(input_width, output_width); - if (height === input_height && width === input_width) { - return image; - } - if (input_height > input_width) { - width = Math.floor(input_width * height / input_height); - } else if (input_width > input_height) { - height = Math.floor(input_height * width / input_width); - } - return await image.resize(width, height, { resample }); - } - /** - * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). - * @param {RawImage} image The image to be cropped. - * @param {number} gray_threshold Value below which pixels are considered to be gray. - * @returns {Promise} The cropped image. - */ - async crop_margin(image, gray_threshold = 200) { - const gray_image = image.clone().grayscale(); - const minValue = min(gray_image.data)[0]; - const maxValue = max(gray_image.data)[0]; - const diff = maxValue - minValue; - if (diff === 0) { - return image; - } - const threshold = gray_threshold / 255; - let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; - for (let j = 0; j < gray_image.height; ++j) { - const row = j * gray_image.width; - for (let i = 0; i < gray_image.width; ++i) { - if ((gray_image.data[row + i] - minValue) / diff < threshold) { - x_min = Math.min(x_min, i); - y_min = Math.min(y_min, j); - x_max = Math.max(x_max, i); - y_max = Math.max(y_max, j); - } - } - } - image = await image.crop([x_min, y_min, x_max, y_max]); - return image; - } - /** - * Pad the image by a certain amount. - * @param {Float32Array} pixelData The pixel data to pad. - * @param {number[]} imgDims The dimensions of the image. - * @param {{width:number; height:number}|number} padSize The dimensions of the padded image. - * @param {Object} options The options for padding. - * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. - * @param {boolean} [options.center=false] Whether to center the image. - * @param {number} [options.constant_values=0] The constant value to use for padding. - * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. - */ - pad_image(pixelData, imgDims, padSize, { - mode = "constant", - center = false, - constant_values = 0 - } = {}) { - const [imageWidth, imageHeight, imageChannels] = imgDims; - let paddedImageWidth, paddedImageHeight; - if (typeof padSize === "number") { - paddedImageWidth = padSize; - paddedImageHeight = padSize; - } else { - paddedImageWidth = padSize.width; - paddedImageHeight = padSize.height; - } - if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { - const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); - if (Array.isArray(constant_values)) { - for (let i = 0; i < paddedPixelData.length; ++i) { - paddedPixelData[i] = constant_values[i % imageChannels]; - } - } else if (constant_values !== 0) { - paddedPixelData.fill(constant_values); - } - const [left, top] = center ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] : [0, 0]; - for (let i = 0; i < imageHeight; ++i) { - const a = (i + top) * paddedImageWidth; - const b = i * imageWidth; - for (let j = 0; j < imageWidth; ++j) { - const c = (a + j + left) * imageChannels; - const d = (b + j) * imageChannels; - for (let k = 0; k < imageChannels; ++k) { - paddedPixelData[c + k] = pixelData[d + k]; - } - } - } - if (mode === "symmetric") { - if (center) { - throw new Error("`center` padding is not supported when `mode` is set to `symmetric`."); - } - const h1 = imageHeight - 1; - const w1 = imageWidth - 1; - for (let i = 0; i < paddedImageHeight; ++i) { - const a = i * paddedImageWidth; - const b = calculateReflectOffset(i, h1) * imageWidth; - for (let j = 0; j < paddedImageWidth; ++j) { - if (i < imageHeight && j < imageWidth) - continue; - const c = (a + j) * imageChannels; - const d = (b + calculateReflectOffset(j, w1)) * imageChannels; - for (let k = 0; k < imageChannels; ++k) { - paddedPixelData[c + k] = pixelData[d + k]; - } - } - } - } - pixelData = paddedPixelData; - imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]; - } - return [pixelData, imgDims]; - } - /** - * Rescale the image' pixel values by `this.rescale_factor`. - * @param {Float32Array} pixelData The pixel data to rescale. - * @returns {void} - */ - rescale(pixelData) { - for (let i = 0; i < pixelData.length; ++i) { - pixelData[i] = this.rescale_factor * pixelData[i]; - } - } - /** - * @typedef {object} PreprocessedImage - * @property {HeightWidth} original_size The original size of the image. - * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. - * @property {Tensor} pixel_values The pixel values of the preprocessed image. - */ - /** - * Preprocesses the given image. - * - * @param {RawImage} image The image to preprocess. - * @param {Object} overrides The overrides for the preprocessing options. - * @returns {Promise} The preprocessed image. - */ - async preprocess(image, { - do_normalize = null, - do_pad = null, - do_convert_rgb = null, - do_convert_grayscale = null - } = {}) { - if (this.do_crop_margin) { - image = await this.crop_margin(image); - } - const srcWidth = image.width; - const srcHeight = image.height; - if (do_convert_rgb ?? this.do_convert_rgb) { - image = image.rgb(); - } else if (do_convert_grayscale) { - image = image.grayscale(); - } - if (this.do_resize) { - let shortest_edge; - let longest_edge; - if (this.do_thumbnail) { - const { height, width } = this.size; - shortest_edge = Math.min(height, width); - } else if (Number.isInteger(this.size)) { - shortest_edge = this.size; - longest_edge = this.config.max_size ?? shortest_edge; - } else if (this.size !== void 0) { - shortest_edge = this.size.shortest_edge; - longest_edge = this.size.longest_edge; - } - if (shortest_edge !== void 0 || longest_edge !== void 0) { - const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); - const newWidth = srcWidth * shortResizeFactor; - const newHeight = srcHeight * shortResizeFactor; - const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight); - const finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); - const finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); - image = await image.resize(finalWidth, finalHeight, { - resample: this.resample - }); - } else if (this.size !== void 0 && this.size.width !== void 0 && this.size.height !== void 0) { - image = await image.resize(this.size.width, this.size.height, { - resample: this.resample - }); - } else if (this.size_divisibility !== void 0) { - const newWidth = Math.floor(srcWidth / this.size_divisibility) * this.size_divisibility; - const newHeight = Math.floor(srcHeight / this.size_divisibility) * this.size_divisibility; - image = await image.resize(newWidth, newHeight, { - resample: this.resample - }); - } else { - throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(this.size)}`); - } - } - if (this.do_thumbnail) { - image = await this.thumbnail(image, this.size, this.resample); - } - if (this.do_center_crop) { - let crop_width; - let crop_height; - if (Number.isInteger(this.crop_size)) { - crop_width = this.crop_size; - crop_height = this.crop_size; - } else { - crop_width = this.crop_size.width; - crop_height = this.crop_size.height; - } - image = await image.center_crop(crop_width, crop_height); - } - let reshaped_input_size = [image.height, image.width]; - let pixelData = Float32Array.from(image.data); - let imgDims = [image.height, image.width, image.channels]; - if (this.do_rescale) { - this.rescale(pixelData); - } - if (do_normalize ?? this.do_normalize) { - let image_mean = this.image_mean; - if (!Array.isArray(this.image_mean)) { - image_mean = new Array(image.channels).fill(image_mean); - } - let image_std = this.image_std; - if (!Array.isArray(this.image_std)) { - image_std = new Array(image.channels).fill(image_mean); - } - if (image_mean.length !== image.channels || image_std.length !== image.channels) { - throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`); - } - for (let i = 0; i < pixelData.length; i += image.channels) { - for (let j = 0; j < image.channels; ++j) { - pixelData[i + j] = (pixelData[i + j] - this.image_mean[j]) / this.image_std[j]; - } - } - } - if (do_pad ?? (this.do_pad && this.pad_size)) { - const padded = this.pad_image(pixelData, [image.width, image.height, image.channels], this.pad_size); - [pixelData, imgDims] = padded; - } - const img = new Tensor("float32", pixelData, imgDims); - const transposed = transpose(img, [2, 0, 1]); - return { - original_size: [srcHeight, srcWidth], - reshaped_input_size, - pixel_values: transposed - }; - } - /** - * Calls the feature extraction process on an array of images, - * preprocesses each image, and concatenates the resulting - * features into a single Tensor. - * @param {RawImage[]} images The image(s) to extract features from. - * @param {...any} args Additional arguments. - * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. - */ - async _call(images, ...args) { - if (!Array.isArray(images)) { - images = [images]; - } - const imageData = await Promise.all(images.map((x) => this.preprocess(x))); - const pixel_values = stack(imageData.map((x) => x.pixel_values), 0); - return { - pixel_values, - // Original sizes of images - original_sizes: imageData.map((x) => x.original_size), - // Reshaped sizes of images, before padding or cropping - reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) - }; - } - }; - var SegformerFeatureExtractor = class extends ImageFeatureExtractor { - /** - * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps. - * @param {*} outputs Raw outputs of the model. - * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size - * (height, width) of each prediction. If unset, predictions will not be resized. - * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps. - */ - post_process_semantic_segmentation(outputs, target_sizes = null) { - const logits = outputs.logits; - const batch_size = logits.dims[0]; - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); - } - const toReturn = []; - for (let i = 0; i < batch_size; ++i) { - const target_size = target_sizes !== null ? target_sizes[i] : null; - let data = logits[i]; - if (target_size !== null) { - data = interpolate(data, target_size, "bilinear", false); - } - const [height, width] = target_size ?? data.dims.slice(-2); - const segmentation = new Tensor( - "int32", - new Int32Array(height * width), - [height, width] - ); - const buffer = data[0].data; - for (let j = 1; j < data.dims[0]; ++j) { - const row = data[j].data; - for (let k = 0; k < row.length; ++k) { - if (row[k] > buffer[k]) { - buffer[k] = row[k]; - segmentation.data[k] = j; - } - } - } - const hasLabel = new Array(data.dims[0]); - const out = segmentation.data; - for (let j = 0; j < out.length; ++j) { - const index = out[j]; - hasLabel[index] = index; - } - const labels = hasLabel.filter((x) => x !== void 0); - toReturn.push({ segmentation, labels }); - } - return toReturn; - } - }; - var BitImageProcessor = class extends ImageFeatureExtractor { - }; - var DPTFeatureExtractor = class extends ImageFeatureExtractor { - }; - var GLPNFeatureExtractor = class extends ImageFeatureExtractor { - }; - var CLIPFeatureExtractor = class extends ImageFeatureExtractor { - }; - var ChineseCLIPFeatureExtractor = class extends ImageFeatureExtractor { - }; - var SiglipImageProcessor = class extends ImageFeatureExtractor { - }; - var ConvNextFeatureExtractor = class extends ImageFeatureExtractor { - }; - var ConvNextImageProcessor = class extends ConvNextFeatureExtractor { - }; - var ViTFeatureExtractor = class extends ImageFeatureExtractor { - }; - var ViTImageProcessor = class extends ImageFeatureExtractor { - }; - var MobileViTFeatureExtractor = class extends ImageFeatureExtractor { - }; - var OwlViTFeatureExtractor = class extends ImageFeatureExtractor { - /** @type {post_process_object_detection} */ - post_process_object_detection(...args) { - return post_process_object_detection(...args); - } - }; - var DeiTFeatureExtractor = class extends ImageFeatureExtractor { - }; - var BeitFeatureExtractor = class extends ImageFeatureExtractor { - }; - var DonutFeatureExtractor = class extends ImageFeatureExtractor { - pad_image(pixelData, imgDims, padSize, options = {}) { - const [imageWidth, imageHeight, imageChannels] = imgDims; - let image_mean = this.image_mean; - if (!Array.isArray(this.image_mean)) { - image_mean = new Array(imageChannels).fill(image_mean); - } - let image_std = this.image_std; - if (!Array.isArray(image_std)) { - image_std = new Array(imageChannels).fill(image_mean); - } - const constant_values = image_mean.map((x, i) => -x / this.image_std[i]); - return super.pad_image(pixelData, imgDims, padSize, { - center: true, - // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. - // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 - constant_values, - ...options - }); - } - }; - var NougatImageProcessor = class extends DonutFeatureExtractor { - }; - var DetrFeatureExtractor = class extends ImageFeatureExtractor { - /** - * Calls the feature extraction process on an array of images, preprocesses - * each image, and concatenates the resulting features into a single Tensor. - * @param {RawImage[]} images The image(s) to extract features from. - * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. - */ - async _call(images) { - const result = await super._call(images); - const maskSize = [result.pixel_values.dims[0], 64, 64]; - const pixel_mask = new Tensor( - "int64", - new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n), - maskSize - ); - return { ...result, pixel_mask }; - } - /** - * Post-processes the outputs of the model (for object detection). - * @param {Object} outputs The outputs of the model that must be post-processed - * @param {Tensor} outputs.logits The logits - * @param {Tensor} outputs.pred_boxes The predicted boxes. - * @return {Object[]} An array of objects containing the post-processed outputs. - */ - /** @type {post_process_object_detection} */ - post_process_object_detection(...args) { - return post_process_object_detection(...args); - } - /** - * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. - * @param {Tensor} class_logits The class logits. - * @param {Tensor} mask_logits The mask logits. - * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks. - * @param {number} num_labels The number of labels. - * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels. - */ - remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { - let mask_probs_item = []; - let pred_scores_item = []; - let pred_labels_item = []; - for (let j = 0; j < class_logits.dims[0]; ++j) { - let cls = class_logits[j]; - let mask = mask_logits[j]; - let pred_label = max(cls.data)[1]; - if (pred_label === num_labels) { - continue; - } - let scores = softmax(cls.data); - let pred_score = scores[pred_label]; - if (pred_score > object_mask_threshold) { - mask_probs_item.push(mask); - pred_scores_item.push(pred_score); - pred_labels_item.push(pred_label); - } - } - return [mask_probs_item, pred_scores_item, pred_labels_item]; - } - /** - * Checks whether the segment is valid or not. - * @param {Int32Array} mask_labels Labels for each pixel in the mask. - * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks. - * @param {number} k The class id of the segment. - * @param {number} mask_threshold The mask threshold. - * @param {number} overlap_mask_area_threshold The overlap mask area threshold. - * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels. - */ - check_segment_validity(mask_labels, mask_probs, k, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8) { - let mask_k = []; - let mask_k_area = 0; - let original_area = 0; - for (let i = 0; i < mask_labels.length; ++i) { - if (mask_labels[i] === k) { - mask_k.push(i); - ++mask_k_area; - } - if (mask_probs[k].data[i] >= mask_threshold) { - ++original_area; - } - } - let mask_exists = mask_k_area > 0 && original_area > 0; - if (mask_exists) { - let area_ratio = mask_k_area / original_area; - mask_exists = area_ratio > overlap_mask_area_threshold; - } - return [mask_exists, mask_k]; - } - /** - * Computes the segments. - * @param {Tensor[]} mask_probs The mask probabilities. - * @param {number[]} pred_scores The predicted scores. - * @param {number[]} pred_labels The predicted labels. - * @param {number} mask_threshold The mask threshold. - * @param {number} overlap_mask_area_threshold The overlap mask area threshold. - * @param {Set} label_ids_to_fuse The label ids to fuse. - * @param {number[]} target_size The target size of the image. - * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments. - */ - compute_segments(mask_probs, pred_scores, pred_labels, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse = null, target_size = null) { - let [height, width] = target_size ?? mask_probs[0].dims; - let segmentation = new Tensor( - "int32", - new Int32Array(height * width), - [height, width] - ); - let segments = []; - if (target_size !== null) { - for (let i = 0; i < mask_probs.length; ++i) { - mask_probs[i] = interpolate(mask_probs[i], target_size, "bilinear", false); - } - } - let mask_labels = new Int32Array(mask_probs[0].data.length); - let bestScores = new Float32Array(mask_probs[0].data.length); - for (let i = 0; i < mask_probs.length; ++i) { - let score = pred_scores[i]; - for (let j = 0; j < mask_probs[i].data.length; ++j) { - mask_probs[i].data[j] *= score; - if (mask_probs[i].data[j] > bestScores[j]) { - mask_labels[j] = i; - bestScores[j] = mask_probs[i].data[j]; - } - } - } - let current_segment_id = 0; - for (let k = 0; k < pred_labels.length; ++k) { - let pred_class = pred_labels[k]; - let [mask_exists, mask_k] = this.check_segment_validity( - mask_labels, - mask_probs, - k, - mask_threshold, - overlap_mask_area_threshold - ); - if (!mask_exists) { - continue; - } - ++current_segment_id; - for (let index of mask_k) { - segmentation.data[index] = current_segment_id; - } - segments.push({ - id: current_segment_id, - label_id: pred_class, - // was_fused: should_fuse, TODO - score: pred_scores[k] - }); - } - return [segmentation, segments]; - } - /** - * Post-process the model output to generate the final panoptic segmentation. - * @param {*} outputs The model output to post process - * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. - * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. - * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask. - * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together. - * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to. - * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} - */ - post_process_panoptic_segmentation(outputs, threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null) { - if (label_ids_to_fuse === null) { - console.warn("`label_ids_to_fuse` unset. No instance will be fused."); - label_ids_to_fuse = /* @__PURE__ */ new Set(); - } - const class_queries_logits = outputs.logits; - const masks_queries_logits = outputs.pred_masks; - const mask_probs = masks_queries_logits.sigmoid(); - let [batch_size, num_queries, num_labels] = class_queries_logits.dims; - num_labels -= 1; - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); - } - let toReturn = []; - for (let i = 0; i < batch_size; ++i) { - let target_size = target_sizes !== null ? target_sizes[i] : null; - let class_logits = class_queries_logits[i]; - let mask_logits = mask_probs[i]; - let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels); - if (pred_labels_item.length === 0) { - let [height, width] = target_size ?? mask_logits.dims.slice(-2); - let segmentation2 = new Tensor( - "int32", - new Int32Array(height * width).fill(-1), - [height, width] - ); - toReturn.push({ - segmentation: segmentation2, - segments_info: [] - }); - continue; - } - let [segmentation, segments] = this.compute_segments( - mask_probs_item, - pred_scores_item, - pred_labels_item, - mask_threshold, - overlap_mask_area_threshold, - label_ids_to_fuse, - target_size - ); - toReturn.push({ - segmentation, - segments_info: segments - }); - } - return toReturn; - } - post_process_instance_segmentation() { - throw Error("Not implemented yet"); - } - }; - var YolosFeatureExtractor = class extends ImageFeatureExtractor { - /** @type {post_process_object_detection} */ - post_process_object_detection(...args) { - return post_process_object_detection(...args); - } - }; - var SamImageProcessor = class extends ImageFeatureExtractor { - /** - * @param {RawImage[]} images The image(s) to extract features from. - * @param {*} input_points A 3D or 4D array, representing the input points provided by the user. - * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. - * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. - * @returns {Promise} - */ - async _call(images, input_points) { - let { - pixel_values, - original_sizes, - reshaped_input_sizes - } = await super._call(images); - let shape = calculateDimensions(input_points); - if (shape.length === 3) { - shape = [1, ...shape]; - input_points = [input_points]; - } else if (shape.length !== 4) { - throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."); - } - for (let i = 0; i < input_points.length; ++i) { - let originalImageSize = original_sizes[i]; - let reshapedImageSize = reshaped_input_sizes[i]; - let resizeFactors = [ - reshapedImageSize[0] / originalImageSize[0], - reshapedImageSize[1] / originalImageSize[1] - ]; - for (let j = 0; j < input_points[i].length; ++j) { - for (let k = 0; k < input_points[i][j].length; ++k) { - for (let w = 0; w < input_points[i][j][k].length; ++w) { - input_points[i][j][k][w] *= resizeFactors[w]; - } - } - } - } - let input_points_tensor = new Tensor( - "int64", - BigInt64Array.from(input_points.flat(Infinity).map((x) => BigInt(Math.round(x)))), - shape - ); - return { - pixel_values, - original_sizes, - reshaped_input_sizes, - input_points: input_points_tensor - }; - } - /** - * Remove padding and upscale masks to the original image size. - * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. - * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. - * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. - * @param {Object} options Optional parameters for post-processing. - * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. - * @param {boolean} [options.binarize] Whether to binarize the masks. - * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. - * @param {number} [options.pad_size.height] The height the images were padded to. - * @param {number} [options.pad_size.width] The width the images were padded to. - * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. - */ - post_process_masks(masks, original_sizes, reshaped_input_sizes, { - mask_threshold = 0, - binarize = true, - pad_size = null - } = {}) { - let output_masks = []; - pad_size = pad_size ?? this.pad_size; - let target_image_size = [pad_size.height, pad_size.width]; - for (let i = 0; i < original_sizes.length; ++i) { - let original_size = original_sizes[i]; - let reshaped_input_size = reshaped_input_sizes[i]; - let mask = masks[i]; - let interpolated_masks = []; - for (let j = 0; j < mask.dims[0]; ++j) { - let m = mask[j]; - let interpolated_mask = interpolate(m, target_image_size, "bilinear", false); - interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); - interpolated_mask = interpolate(mask, original_size, "bilinear", false); - if (binarize) { - interpolated_mask = new Tensor( - "bool", - Array.from(interpolated_mask.data).map((x) => x > mask_threshold), - interpolated_mask.dims - ); - } - interpolated_mask.dims = [1, ...interpolated_mask.dims]; - interpolated_masks.push(interpolated_mask); - } - let concatenated = cat(interpolated_masks); - output_masks.push(concatenated); - } - return output_masks; - } - }; - var Swin2SRImageProcessor = class extends ImageFeatureExtractor { - pad_image(pixelData, imgDims, padSize, options = {}) { - const [imageWidth, imageHeight, imageChannels] = imgDims; - return super.pad_image(pixelData, imgDims, { - // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already - // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). - // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. - width: imageWidth + (padSize - imageWidth % padSize) % padSize, - height: imageHeight + (padSize - imageHeight % padSize) % padSize - }, { - mode: "symmetric", - center: false, - constant_values: -1, - ...options - }); - } - }; - var VitMatteImageProcessor = class extends ImageFeatureExtractor { - /** - * Calls the feature extraction process on an array of images, preprocesses - * each image, and concatenates the resulting features into a single Tensor. - * @param {RawImage[]} images The image(s) to extract features from. - * @param {RawImage[]} trimaps The trimaps(s) to extract features from. - * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. - */ - async _call(images, trimaps) { - if (!Array.isArray(images)) { - images = [images]; - } - if (!Array.isArray(trimaps)) { - trimaps = [trimaps]; - } - const imageData = await Promise.all(images.map((x) => this.preprocess(x))); - const trimapData = await Promise.all(trimaps.map((x) => this.preprocess(x, { - do_normalize: false, - do_convert_rgb: false, - do_convert_grayscale: true - }))); - const pixel_values = stack(imageData.map( - // Concatenate images and trimaps - (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0) - ), 0); - return { - pixel_values, - // Original sizes of images - original_sizes: imageData.map((x) => x.original_size), - // Reshaped sizes of images, before padding or cropping - reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) - }; - } - }; - var WhisperFeatureExtractor = class extends FeatureExtractor { - constructor(config) { - super(config); - this.config.mel_filters ??= mel_filter_bank( - Math.floor(1 + this.config.n_fft / 2), - // num_frequency_bins - this.config.feature_size, - // num_mel_filters - 0, - // min_frequency - 8e3, - // max_frequency - this.config.sampling_rate, - // sampling_rate - "slaney", - // norm - "slaney" - // mel_scale - ); - this.window = window_function(this.config.n_fft, "hann"); - } - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - _extract_fbank_features(waveform) { - const { data, dims } = spectrogram( - waveform, - this.window, - // window - this.config.n_fft, - // frame_length - this.config.hop_length, - // hop_length - { - power: 2, - mel_filters: this.config.mel_filters, - log_mel: "log10", - // Custom - max_num_frames: this.config.nb_max_frames - // 3000 - } - ); - const maxValue = max(data)[0]; - for (let i = 0; i < data.length; ++i) { - data[i] = (Math.max(data[i], maxValue - 8) + 4) / 4; - } - return { data, dims }; - } - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio) { - validate_audio_inputs(audio, "WhisperFeatureExtractor"); - let waveform; - if (audio.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`." - ); - waveform = audio.slice(0, this.config.n_samples); - } else { - waveform = new Float32Array(this.config.n_samples); - waveform.set(audio); - } - const { data, dims } = this._extract_fbank_features(waveform); - return { - input_features: new Tensor( - "float32", - data, - [1, ...dims] - ) - }; - } - }; - var Wav2Vec2FeatureExtractor = class extends FeatureExtractor { - /** - * @param {Float32Array} input_values - * @returns {Float32Array} - */ - _zero_mean_unit_var_norm(input_values) { - const sum = input_values.reduce((a, b) => a + b, 0); - const mean2 = sum / input_values.length; - const variance = input_values.reduce((a, b) => a + (b - mean2) ** 2, 0) / input_values.length; - return input_values.map((x) => (x - mean2) / Math.sqrt(variance + 1e-7)); - } - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. - */ - async _call(audio) { - validate_audio_inputs(audio, "Wav2Vec2FeatureExtractor"); - if (audio instanceof Float64Array) { - audio = new Float32Array(audio); - } - let input_values = audio; - if (this.config.do_normalize) { - input_values = this._zero_mean_unit_var_norm(input_values); - } - const shape = [1, input_values.length]; - return { - input_values: new Tensor("float32", input_values, shape), - attention_mask: new Tensor("int64", new BigInt64Array(input_values.length).fill(1n), shape) - }; - } - }; - var ASTFeatureExtractor = class extends FeatureExtractor { - constructor(config) { - super(config); - const sampling_rate = this.config.sampling_rate; - const mel_filters = mel_filter_bank( - 256, - // num_frequency_bins - this.config.num_mel_bins, - // num_mel_filters - 20, - // min_frequency - Math.floor(sampling_rate / 2), - // max_frequency - sampling_rate, - // sampling_rate - null, - // norm - "kaldi", - // mel_scale - true - // triangularize_in_mel_space - ); - for (let i = 0; i < mel_filters.length; ++i) { - mel_filters[i].push(0); - } - this.mel_filters = mel_filters; - this.window = window_function(400, "hann", { - periodic: false - }); - this.mean = this.config.mean; - this.std = this.config.std; - } - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number} max_length The maximum number of frames to return. - * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - _extract_fbank_features(waveform, max_length) { - return spectrogram( - waveform, - this.window, - // window - 400, - // frame_length - 160, - // hop_length - { - fft_length: 512, - power: 2, - center: false, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: "log", - mel_floor: 1192092955078125e-22, - remove_dc_offset: true, - // Custom - max_num_frames: max_length, - transpose: true - } - ); - } - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio) { - validate_audio_inputs(audio, "ASTFeatureExtractor"); - const features = this._extract_fbank_features(audio, this.config.max_length); - if (this.config.do_normalize) { - const denom = this.std * 2; - for (let i = 0; i < features.data.length; ++i) { - features.data[i] = (features.data[i] - this.mean) / denom; - } - } - return { - input_values: new Tensor( - "float32", - features.data, - [1, ...features.dims] - ) - }; - } - }; - var ClapFeatureExtractor = class extends FeatureExtractor { - constructor(config) { - super(config); - this.mel_filters = mel_filter_bank( - this.config.nb_frequency_bins, - // num_frequency_bins - this.config.feature_size, - // num_mel_filters - this.config.frequency_min, - // min_frequency - this.config.frequency_max, - // max_frequency - this.config.sampling_rate, - // sampling_rate - null, - // norm - "htk" - // mel_scale - ); - this.mel_filters_slaney = mel_filter_bank( - this.config.nb_frequency_bins, - // num_frequency_bins - this.config.feature_size, - // num_mel_filters - this.config.frequency_min, - // min_frequency - this.config.frequency_max, - // max_frequency - this.config.sampling_rate, - // sampling_rate - "slaney", - // norm - "slaney" - // mel_scale - ); - this.window = window_function(this.config.fft_window_size, "hann"); - } - /** - * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. - * - * Four different path are possible: - * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram - * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram - * are then stacked together. They will later be used for `feature_fusion`. - * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is - * padded based on `padding`. - * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded - * based on `padding`, and is repeated `4` times. - * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel - * spectrogram will be computed on a random crop of the waveform. - * - * @param {Float32Array|Float64Array} waveform The input waveform. - * @param {number} max_length The maximum length of the waveform. - * @param {string} truncation The truncation strategy to use. - * @param {string} padding The padding strategy to use. - * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. - */ - _get_input_mel(waveform, max_length, truncation, padding) { - let input_mel; - let longer = false; - const diff = waveform.length - max_length; - if (diff > 0) { - if (truncation === "rand_trunc") { - longer = true; - const idx = Math.floor(Math.random() * (diff + 1)); - waveform = waveform.subarray(idx, idx + max_length); - input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); - input_mel.dims = [1, ...input_mel.dims]; - } else { - throw new Error(`Truncation strategy "${truncation}" not implemented`); - } - } else { - if (diff < 0) { - let padded = new Float64Array(max_length); - padded.set(waveform); - if (padding === "repeat") { - for (let i = waveform.length; i < max_length; i += waveform.length) { - padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); - } - } else if (padding === "repeatpad") { - for (let i = waveform.length; i < -diff; i += waveform.length) { - padded.set(waveform, i); - } - } - waveform = padded; - } - if (truncation === "fusion") { - throw new Error(`Truncation strategy "${truncation}" not implemented`); - } - input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); - input_mel.dims = [1, ...input_mel.dims]; - } - return { - ...input_mel, - longer - }; - } - /** - * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. - * In CLAP, two different filter banks are used depending on the truncation pattern: - * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from - * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` - * is set to `"fusion"`. - * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used - * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original - * implementation when the truncation mode is not `"fusion"`. - * - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number[][]} mel_filters The mel filters to use. - * @param {number} [max_length=null] The maximum number of frames to return. - * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - _extract_fbank_features(waveform, mel_filters, max_length = null) { - return spectrogram( - waveform, - this.window, - // window - this.config.fft_window_size, - // frame_length - this.config.hop_length, - // hop_length - { - power: 2, - mel_filters, - log_mel: "dB", - // Custom - max_num_frames: max_length, - do_pad: false, - transpose: true - } - ); - } - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio, { - max_length = null - } = {}) { - validate_audio_inputs(audio, "ClapFeatureExtractor"); - const padded_inputs = this._get_input_mel( - audio, - max_length ?? this.config.nb_max_samples, - this.config.truncation, - this.config.padding - ); - return { - input_features: new Tensor( - "float32", - padded_inputs.data, - [1, ...padded_inputs.dims] - ) - }; - } - }; - var SpeechT5FeatureExtractor = class extends FeatureExtractor { - }; - var Processor = class extends Callable { - /** - * Creates a new Processor with the given feature extractor. - * @param {FeatureExtractor} feature_extractor The function used to extract features from the input. - */ - constructor(feature_extractor) { - super(); - this.feature_extractor = feature_extractor; - } - /** - * Calls the feature_extractor function with the given input. - * @param {any} input The input to extract features from. - * @param {...any} args Additional arguments. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(input, ...args) { - return await this.feature_extractor(input, ...args); - } - }; - var SamProcessor = class extends Processor { - /** - * @param {*} images - * @param {*} input_points - * @returns {Promise} - */ - async _call(images, input_points) { - return await this.feature_extractor(images, input_points); - } - /** - * @borrows SamImageProcessor#post_process_masks as post_process_masks - */ - post_process_masks(...args) { - return this.feature_extractor.post_process_masks(...args); - } - }; - var WhisperProcessor = class extends Processor { - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio); - } - }; - var Wav2Vec2ProcessorWithLM = class extends Processor { - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio); - } - }; - var SpeechT5Processor = class extends Processor { - /** - * Calls the feature_extractor function with the given input. - * @param {any} input The input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(input) { - return await this.feature_extractor(input); - } - }; - var OwlViTProcessor = class extends Processor { - }; - var AutoProcessor = class { - static FEATURE_EXTRACTOR_CLASS_MAPPING = { - WhisperFeatureExtractor, - ViTFeatureExtractor, - MobileViTFeatureExtractor, - OwlViTFeatureExtractor, - CLIPFeatureExtractor, - ChineseCLIPFeatureExtractor, - SiglipImageProcessor, - ConvNextFeatureExtractor, - ConvNextImageProcessor, - SegformerFeatureExtractor, - BitImageProcessor, - DPTFeatureExtractor, - GLPNFeatureExtractor, - BeitFeatureExtractor, - DeiTFeatureExtractor, - DetrFeatureExtractor, - YolosFeatureExtractor, - DonutFeatureExtractor, - NougatImageProcessor, - ViTImageProcessor, - VitMatteImageProcessor, - SamImageProcessor, - Swin2SRImageProcessor, - Wav2Vec2FeatureExtractor, - SpeechT5FeatureExtractor, - ASTFeatureExtractor, - ClapFeatureExtractor - }; - static PROCESSOR_CLASS_MAPPING = { - WhisperProcessor, - Wav2Vec2ProcessorWithLM, - SamProcessor, - SpeechT5Processor, - OwlViTProcessor - }; - /** - * Instantiate one of the processor classes of the library from a pretrained model. - * - * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object - * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. - * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor. - * - * @returns {Promise} A new instance of the Processor class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main" - } = {}) { - let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, "preprocessor_config.json", true, { - progress_callback, - config, - cache_dir, - local_files_only, - revision - }); - let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type; - let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key]; - if (!feature_extractor_class) { - if (preprocessorConfig.size !== void 0) { - console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`); - feature_extractor_class = ImageFeatureExtractor; - } else { - throw new Error(`Unknown Feature Extractor type: ${key}`); - } - } - let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor; - let feature_extractor = new feature_extractor_class(preprocessorConfig); - return new processor_class(feature_extractor); - } - }; - - // node_modules/@xenova/transformers/src/pipelines.js - async function prepareImages(images) { - if (!Array.isArray(images)) { - images = [images]; - } - return await Promise.all(images.map((x) => RawImage.read(x))); - } - async function prepareAudios(audios, sampling_rate) { - if (!Array.isArray(audios)) { - audios = [audios]; - } - return await Promise.all(audios.map((x) => { - if (typeof x === "string" || x instanceof URL) { - return read_audio(x, sampling_rate); - } else if (x instanceof Float64Array) { - return new Float32Array(x); - } - return x; - })); - } - function get_bounding_box(box, asInteger) { - if (asInteger) { - box = box.map((x) => x | 0); - } - const [xmin, ymin, xmax, ymax] = box; - return { xmin, ymin, xmax, ymax }; - } - var Pipeline = class extends Callable { - /** - * Create a new Pipeline. - * @param {Object} options An object containing the following properties: - * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. - * @param {PreTrainedModel} [options.model] The model used by the pipeline. - * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). - * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). - */ - constructor({ task, model, tokenizer = null, processor = null }) { - super(); - this.task = task; - this.model = model; - this.tokenizer = tokenizer; - this.processor = processor; - } - /** @type {DisposeType} */ - async dispose() { - await this.model.dispose(); - } - }; - var TextClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ - Pipeline { - /** - * Create a new TextClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {TextClassificationPipelineCallback} */ - async _call(texts, { - topk = 1 - } = {}) { - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true - }); - const outputs = await this.model(model_inputs); - const function_to_apply = this.model.config.problem_type === "multi_label_classification" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data); - const id2label = this.model.config.id2label; - const toReturn = []; - for (const batch of outputs.logits) { - const output = function_to_apply(batch); - const scores = getTopItems(output, topk); - const vals = scores.map((x) => ({ - label: id2label[x[0]], - score: x[1] - })); - if (topk === 1) { - toReturn.push(...vals); - } else { - toReturn.push(vals); - } - } - return Array.isArray(texts) || topk === 1 ? ( - /** @type {TextClassificationOutput} */ - toReturn - ) : ( - /** @type {TextClassificationOutput[]} */ - toReturn[0] - ); - } - }; - var TokenClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ - Pipeline { - /** - * Create a new TokenClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {TokenClassificationPipelineCallback} */ - async _call(texts, { - ignore_labels = ["O"] - } = {}) { - const isBatched = Array.isArray(texts); - const model_inputs = this.tokenizer(isBatched ? texts : [texts], { - padding: true, - truncation: true - }); - const outputs = await this.model(model_inputs); - const logits = outputs.logits; - const id2label = this.model.config.id2label; - const toReturn = []; - for (let i = 0; i < logits.dims[0]; ++i) { - const ids = model_inputs.input_ids[i]; - const batch = logits[i]; - const tokens = []; - for (let j = 0; j < batch.dims[0]; ++j) { - const tokenData = batch[j]; - const topScoreIndex = max(tokenData.data)[1]; - const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; - if (ignore_labels.includes(entity)) { - continue; - } - const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true }); - if (word === "") { - continue; - } - const scores = softmax(tokenData.data); - tokens.push({ - entity, - score: scores[topScoreIndex], - index: j, - word, - // TODO: null for now, but will add - start: null, - end: null - }); - } - toReturn.push(tokens); - } - return isBatched ? toReturn : toReturn[0]; - } - }; - var QuestionAnsweringPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ - Pipeline { - /** - * Create a new QuestionAnsweringPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {QuestionAnsweringPipelineCallback} */ - async _call(question, context, { - topk = 1 - } = {}) { - const inputs = this.tokenizer(question, { - text_pair: context, - padding: true, - truncation: true - }); - const output = await this.model(inputs); - const toReturn = []; - for (let j = 0; j < output.start_logits.dims[0]; ++j) { - const ids = inputs.input_ids[j]; - const sepIndex = ids.indexOf(this.tokenizer.sep_token_id); - const s1 = Array.from(softmax(output.start_logits[j].data)).map((x, i) => [x, i]).filter((x) => x[1] > sepIndex); - const e1 = Array.from(softmax(output.end_logits[j].data)).map((x, i) => [x, i]).filter((x) => x[1] > sepIndex); - const options = product(s1, e1).filter((x) => x[0][1] <= x[1][1]).map((x) => [x[0][1], x[1][1], x[0][0] * x[1][0]]).sort((a, b) => b[2] - a[2]); - for (let k = 0; k < Math.min(options.length, topk); ++k) { - const [start, end, score] = options[k]; - const answer_tokens = [...ids].slice(start, end + 1); - const answer = this.tokenizer.decode(answer_tokens, { - skip_special_tokens: true - }); - toReturn.push({ - answer, - score - }); - } - } - return topk === 1 ? toReturn[0] : toReturn; - } - }; - var FillMaskPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ - Pipeline { - /** - * Create a new FillMaskPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {FillMaskPipelineCallback} */ - async _call(texts, { - topk = 5 - } = {}) { - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true - }); - const outputs = await this.model(model_inputs); - const toReturn = []; - for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) { - const ids = model_inputs.input_ids[i]; - const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id); - if (mask_token_index === -1) { - throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`); - } - const logits = outputs.logits[i]; - const itemLogits = logits[mask_token_index]; - const scores = getTopItems(softmax(itemLogits.data), topk); - toReturn.push(scores.map((x) => { - const sequence = [...ids]; - sequence[mask_token_index] = x[0]; - return { - score: x[1], - token: x[0], - token_str: this.tokenizer.model.vocab[x[0]], - sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }) - }; - })); - } - return Array.isArray(texts) ? toReturn : toReturn[0]; - } - }; - var Text2TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ - Pipeline { - /** @type {'generated_text'} */ - _key = "generated_text"; - /** - * Create a new Text2TextGenerationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {Text2TextGenerationPipelineCallback} */ - async _call(texts, generate_kwargs = {}) { - if (!Array.isArray(texts)) { - texts = [texts]; - } - if (this.model.config.prefix) { - texts = texts.map((x) => this.model.config.prefix + x); - } - const task_specific_params = this.model.config.task_specific_params; - if (task_specific_params && task_specific_params[this.task]) { - if (task_specific_params[this.task].prefix) { - texts = texts.map((x) => task_specific_params[this.task].prefix + x); - } - } - const tokenizer = this.tokenizer; - const tokenizer_options = { - padding: true, - truncation: true - }; - let input_ids; - if (this instanceof TranslationPipeline && "_build_translation_inputs" in tokenizer) { - input_ids = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs).input_ids; - } else { - input_ids = tokenizer(texts, tokenizer_options).input_ids; - } - const outputTokenIds = await this.model.generate(input_ids, generate_kwargs); - return tokenizer.batch_decode(outputTokenIds, { - skip_special_tokens: true - }).map((text) => ({ [this._key]: text })); - } - }; - var SummarizationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ - /** @type {any} */ - Text2TextGenerationPipeline { - /** @type {'summary_text'} */ - _key = "summary_text"; - /** - * Create a new SummarizationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - }; - var TranslationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ - /** @type {any} */ - Text2TextGenerationPipeline { - /** @type {'translation_text'} */ - _key = "translation_text"; - /** - * Create a new TranslationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - }; - var TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ - Pipeline { - /** - * Create a new TextGenerationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {TextGenerationPipelineCallback} */ - async _call(texts, generate_kwargs = {}) { - const isBatched = Array.isArray(texts); - if (!isBatched) { - texts = [ - /** @type {string}*/ - texts - ]; - } - const add_special_tokens = generate_kwargs.add_special_tokens ?? false; - this.tokenizer.padding_side = "left"; - const { input_ids, attention_mask } = this.tokenizer(texts, { - add_special_tokens, - padding: true, - truncation: true - }); - const outputTokenIds = await this.model.generate(input_ids, generate_kwargs, null, { - inputs_attention_mask: attention_mask - }); - const decoded = this.tokenizer.batch_decode(outputTokenIds, { - skip_special_tokens: true - }); - const toReturn = Array.from({ length: texts.length }, (_) => []); - for (let i = 0; i < decoded.length; ++i) { - const textIndex = Math.floor(i / outputTokenIds.length * texts.length); - toReturn[textIndex].push({ - generated_text: decoded[i] - }); - } - return !isBatched && toReturn.length === 1 ? toReturn[0] : toReturn; - } - }; - var ZeroShotClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ - Pipeline { - /** - * Create a new ZeroShotClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - this.label2id = Object.fromEntries( - Object.entries( - /** @type {any} */ - this.model.config.label2id - ).map( - ([k, v]) => [k.toLowerCase(), v] - ) - ); - this.entailment_id = this.label2id["entailment"]; - if (this.entailment_id === void 0) { - 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"]; - if (this.contradiction_id === void 0) { - console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); - this.contradiction_id = 0; - } - } - /** @type {ZeroShotClassificationPipelineCallback} */ - async _call(texts, candidate_labels, { - hypothesis_template = "This example is {}.", - multi_label = false - } = {}) { - const isBatched = Array.isArray(texts); - if (!isBatched) { - texts = [ - /** @type {string} */ - texts - ]; - } - if (!Array.isArray(candidate_labels)) { - candidate_labels = [candidate_labels]; - } - const hypotheses = candidate_labels.map( - (x) => hypothesis_template.replace("{}", x) - ); - const softmaxEach = multi_label || candidate_labels.length === 1; - const toReturn = []; - for (const premise of texts) { - const entails_logits = []; - for (const hypothesis of hypotheses) { - const inputs = this.tokenizer(premise, { - text_pair: hypothesis, - padding: true, - truncation: true - }); - const outputs = await this.model(inputs); - if (softmaxEach) { - entails_logits.push([ - outputs.logits.data[this.contradiction_id], - outputs.logits.data[this.entailment_id] - ]); - } else { - entails_logits.push(outputs.logits.data[this.entailment_id]); - } - } - const scores = softmaxEach ? entails_logits.map((x) => softmax(x)[1]) : softmax(entails_logits); - const scores_sorted = scores.map((x, i) => [x, i]).sort((a, b) => b[0] - a[0]); - toReturn.push({ - sequence: premise, - labels: scores_sorted.map((x) => candidate_labels[x[1]]), - scores: scores_sorted.map((x) => x[0]) - }); - } - return isBatched ? toReturn : toReturn[0]; - } - }; - var FeatureExtractionPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ - Pipeline { - /** - * Create a new FeatureExtractionPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {FeatureExtractionPipelineCallback} */ - async _call(texts, { - pooling = ( - /** @type {'none'} */ - "none" - ), - normalize = false - } = {}) { - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true - }); - const outputs = await this.model(model_inputs); - let result = outputs.last_hidden_state ?? outputs.logits; - if (pooling === "none") { - } else if (pooling === "mean") { - result = mean_pooling(result, model_inputs.attention_mask); - } else if (pooling === "cls") { - result = result.slice(null, 0); - } else { - throw Error(`Pooling method '${pooling}' not supported.`); - } - if (normalize) { - result = result.normalize(2, -1); - } - return result; - } - }; - var AudioClassificationPipeline = class extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ - Pipeline { - /** - * Create a new AudioClassificationPipeline. - * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {AudioClassificationPipelineCallback} */ - async _call(audio, { - topk = null - } = {}) { - const single = !Array.isArray(audio); - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - const id2label = this.model.config.id2label; - const toReturn = []; - for (const aud of preparedAudios) { - const inputs = await this.processor(aud); - const output = await this.model(inputs); - const logits = output.logits[0]; - const scores = getTopItems(softmax(logits.data), topk); - const vals = scores.map((x) => ({ - label: ( - /** @type {string} */ - id2label[x[0]] - ), - score: ( - /** @type {number} */ - x[1] - ) - })); - if (topk === 1) { - toReturn.push(...vals); - } else { - toReturn.push(vals); - } - } - return !single || topk === 1 ? ( - /** @type {AudioClassificationOutput} */ - toReturn - ) : ( - /** @type {AudioClassificationOutput[]} */ - toReturn[0] - ); - } - }; - var ZeroShotAudioClassificationPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ - Pipeline { - /** - * Create a new ZeroShotAudioClassificationPipeline. - * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ZeroShotAudioClassificationPipelineCallback} */ - async _call(audio, candidate_labels, { - hypothesis_template = "This is a sound of {}." - } = {}) { - const single = !Array.isArray(audio); - if (single) { - audio = [ - /** @type {AudioInput} */ - audio - ]; - } - const texts = candidate_labels.map( - (x) => hypothesis_template.replace("{}", x) - ); - const text_inputs = this.tokenizer(texts, { - padding: true, - truncation: true - }); - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - const toReturn = []; - for (const aud of preparedAudios) { - const audio_inputs = await this.processor(aud); - const output = await this.model({ ...text_inputs, ...audio_inputs }); - const probs = softmax(output.logits_per_audio.data); - toReturn.push([...probs].map((x, i) => ({ - score: x, - label: candidate_labels[i] - }))); - } - return single ? toReturn[0] : toReturn; - } - }; - var AutomaticSpeechRecognitionPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ - Pipeline { - /** - * Create a new AutomaticSpeechRecognitionPipeline. - * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {AutomaticSpeechRecognitionPipelineCallback} */ - async _call(audio, kwargs = {}) { - switch (this.model.config.model_type) { - case "whisper": - return this._call_whisper(audio, kwargs); - case "wav2vec2": - case "hubert": - return this._call_wav2vec2(audio, kwargs); - default: - throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`); - } - } - /** - * @type {AutomaticSpeechRecognitionPipelineCallback} - * @private - */ - async _call_wav2vec2(audio, kwargs = {}) { - if (kwargs.language) { - console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); - } - if (kwargs.task) { - console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); - } - const single = !Array.isArray(audio); - if (single) { - audio = [ - /** @type {AudioInput} */ - audio - ]; - } - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - const toReturn = []; - for (const aud of preparedAudios) { - const inputs = await this.processor(aud); - const output = await this.model(inputs); - const logits = output.logits[0]; - const predicted_ids = []; - for (const item of logits) { - predicted_ids.push(max(item.data)[1]); - } - const predicted_sentences = this.tokenizer.decode(predicted_ids); - toReturn.push({ text: predicted_sentences }); - } - return single ? toReturn[0] : toReturn; - } - /** - * @type {AutomaticSpeechRecognitionPipelineCallback} - * @private - */ - async _call_whisper(audio, kwargs = {}) { - const return_timestamps = kwargs.return_timestamps ?? false; - const chunk_length_s = kwargs.chunk_length_s ?? 0; - const chunk_callback = kwargs.chunk_callback ?? null; - const force_full_sequences = kwargs.force_full_sequences ?? false; - let stride_length_s = kwargs.stride_length_s ?? null; - if (return_timestamps === "word") { - kwargs["return_token_timestamps"] = true; - } - const language = pop(kwargs, "language", null); - const task = pop(kwargs, "task", null); - if (language || task || return_timestamps) { - if (kwargs.forced_decoder_ids) { - throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time."); - } - const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({ language, task, no_timestamps: !return_timestamps }); - if (decoder_prompt_ids.length > 0) { - kwargs.forced_decoder_ids = decoder_prompt_ids; - } - } - const single = !Array.isArray(audio); - if (single) { - audio = [ - /** @type {AudioInput} */ - audio - ]; - } - const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions; - const hop_length = this.processor.feature_extractor.config.hop_length; - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - const toReturn = []; - for (const aud of preparedAudios) { - let chunks = []; - if (chunk_length_s > 0) { - if (stride_length_s === null) { - stride_length_s = chunk_length_s / 6; - } else if (chunk_length_s <= stride_length_s) { - throw Error("`chunk_length_s` must be larger than `stride_length_s`."); - } - const window2 = sampling_rate * chunk_length_s; - const stride = sampling_rate * stride_length_s; - const jump = window2 - 2 * stride; - let offset = 0; - while (offset < aud.length) { - const subarr = aud.subarray(offset, offset + window2); - const feature = await this.processor(subarr); - const isFirst = offset === 0; - const isLast = offset + jump >= aud.length; - chunks.push({ - stride: [ - subarr.length, - isFirst ? 0 : stride, - isLast ? 0 : stride - ], - input_features: feature.input_features, - is_last: isLast - }); - offset += jump; - } - } else { - chunks = [{ - stride: [aud.length, 0, 0], - input_features: (await this.processor(aud)).input_features, - is_last: true - }]; - } - for (const chunk of chunks) { - kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length); - const data = await this.model.generate(chunk.input_features, kwargs); - if (return_timestamps === "word") { - chunk.tokens = data.sequences[0]; - chunk.token_timestamps = data.token_timestamps.tolist()[0].map( - (x) => round(x, 2) - ); - } else { - chunk.tokens = data[0]; - } - chunk.stride = chunk.stride.map((x) => x / sampling_rate); - if (chunk_callback !== null) { - chunk_callback(chunk); - } - } - const [full_text, optional] = this.tokenizer._decode_asr(chunks, { - time_precision, - return_timestamps, - force_full_sequences - }); - toReturn.push({ text: full_text, ...optional }); - } - return single ? toReturn[0] : toReturn; - } - }; - var ImageToTextPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ - Pipeline { - /** - * Create a new ImageToTextPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ImageToTextPipelineCallback} */ - async _call(images, generate_kwargs = {}) { - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - const { pixel_values } = await this.processor(preparedImages); - const toReturn = []; - for (const batch of pixel_values) { - batch.dims = [1, ...batch.dims]; - const output = await this.model.generate(batch, generate_kwargs); - const decoded = this.tokenizer.batch_decode(output, { - skip_special_tokens: true - }).map((x) => ({ generated_text: x.trim() })); - toReturn.push(decoded); - } - return isBatched ? toReturn : toReturn[0]; - } - }; - var ImageClassificationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ - Pipeline { - /** - * Create a new ImageClassificationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ImageClassificationPipelineCallback} */ - async _call(images, { - topk = 1 - } = {}) { - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - const { pixel_values } = await this.processor(preparedImages); - const output = await this.model({ pixel_values }); - const id2label = this.model.config.id2label; - const toReturn = []; - for (const batch of output.logits) { - const scores = getTopItems(softmax(batch.data), topk); - const vals = scores.map((x) => ({ - label: id2label[x[0]], - score: x[1] - })); - if (topk === 1) { - toReturn.push(...vals); - } else { - toReturn.push(vals); - } - } - return isBatched || topk === 1 ? ( - /** @type {ImageClassificationOutput} */ - toReturn - ) : ( - /** @type {ImageClassificationOutput[]} */ - toReturn[0] - ); - } - }; - var ImageSegmentationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ - Pipeline { - /** - * Create a new ImageSegmentationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - this.subtasks_mapping = { - // Mapping of subtasks to their corresponding post-processing function names. - panoptic: "post_process_panoptic_segmentation", - instance: "post_process_instance_segmentation", - semantic: "post_process_semantic_segmentation" - }; - } - /** @type {ImageSegmentationPipelineCallback} */ - async _call(images, { - threshold = 0.5, - mask_threshold = 0.5, - overlap_mask_area_threshold = 0.8, - label_ids_to_fuse = null, - target_sizes = null, - subtask = null - } = {}) { - const isBatched = Array.isArray(images); - if (isBatched && images.length !== 1) { - throw Error("Image segmentation pipeline currently only supports a batch size of 1."); - } - const preparedImages = await prepareImages(images); - const imageSizes = preparedImages.map((x) => [x.height, x.width]); - const { pixel_values, pixel_mask } = await this.processor(preparedImages); - const output = await this.model({ pixel_values, pixel_mask }); - let fn = null; - if (subtask !== null) { - fn = this.subtasks_mapping[subtask]; - } else { - for (let [task, func] of Object.entries(this.subtasks_mapping)) { - if (func in this.processor.feature_extractor) { - fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor); - subtask = task; - break; - } - } - } - const id2label = this.model.config.id2label; - const annotation = []; - if (subtask === "panoptic" || subtask === "instance") { - const processed = fn( - output, - threshold, - mask_threshold, - overlap_mask_area_threshold, - label_ids_to_fuse, - target_sizes ?? imageSizes - // TODO FIX? - )[0]; - const segmentation = processed.segmentation; - for (const segment of processed.segments_info) { - const maskData = new Uint8ClampedArray(segmentation.data.length); - for (let i = 0; i < segmentation.data.length; ++i) { - if (segmentation.data[i] === segment.id) { - maskData[i] = 255; - } - } - const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); - annotation.push({ - score: segment.score, - label: id2label[segment.label_id], - mask - }); - } - } else if (subtask === "semantic") { - const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0]; - for (const label of labels) { - const maskData = new Uint8ClampedArray(segmentation.data.length); - for (let i = 0; i < segmentation.data.length; ++i) { - if (segmentation.data[i] === label) { - maskData[i] = 255; - } - } - const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); - annotation.push({ - score: null, - label: id2label[label], - mask - }); - } - } else { - throw Error(`Subtask ${subtask} not supported.`); - } - return annotation; - } - }; - var ZeroShotImageClassificationPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ - Pipeline { - /** - * Create a new ZeroShotImageClassificationPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ZeroShotImageClassificationPipelineCallback} */ - async _call(images, candidate_labels, { - hypothesis_template = "This is a photo of {}" - } = {}) { - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - const texts = candidate_labels.map( - (x) => hypothesis_template.replace("{}", x) - ); - const text_inputs = this.tokenizer(texts, { - padding: this.model.config.model_type === "siglip" ? "max_length" : true, - truncation: true - }); - const { pixel_values } = await this.processor(preparedImages); - const output = await this.model({ ...text_inputs, pixel_values }); - const function_to_apply = this.model.config.model_type === "siglip" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data); - const toReturn = []; - for (const batch of output.logits_per_image) { - const probs = function_to_apply(batch); - const result = [...probs].map((x, i) => ({ - score: x, - label: candidate_labels[i] - })); - result.sort((a, b) => b.score - a.score); - toReturn.push(result); - } - return isBatched ? toReturn : toReturn[0]; - } - }; - var ObjectDetectionPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ - Pipeline { - /** - * Create a new ObjectDetectionPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ObjectDetectionPipelineCallback} */ - async _call(images, { - threshold = 0.9, - percentage = false - } = {}) { - const isBatched = Array.isArray(images); - if (isBatched && images.length !== 1) { - throw Error("Object detection pipeline currently only supports a batch size of 1."); - } - const preparedImages = await prepareImages(images); - const imageSizes = percentage ? null : preparedImages.map((x) => [x.height, x.width]); - const { pixel_values, pixel_mask } = await this.processor(preparedImages); - const output = await this.model({ pixel_values, pixel_mask }); - const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes); - const id2label = this.model.config.id2label; - const result = processed.map((batch) => batch.boxes.map((box, i) => ({ - score: batch.scores[i], - label: id2label[batch.classes[i]], - box: get_bounding_box(box, !percentage) - }))); - return isBatched ? result : result[0]; - } - }; - var ZeroShotObjectDetectionPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ - Pipeline { - /** - * Create a new ZeroShotObjectDetectionPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ZeroShotObjectDetectionPipelineCallback} */ - async _call(images, candidate_labels, { - threshold = 0.1, - topk = null, - percentage = false - } = {}) { - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - const text_inputs = this.tokenizer(candidate_labels, { - padding: true, - truncation: true - }); - const model_inputs = await this.processor(preparedImages); - const toReturn = []; - for (let i = 0; i < preparedImages.length; ++i) { - const image = preparedImages[i]; - const imageSize = percentage ? null : [[image.height, image.width]]; - const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); - const output = await this.model({ ...text_inputs, pixel_values }); - const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0]; - let result = processed.boxes.map((box, i2) => ({ - score: processed.scores[i2], - label: candidate_labels[processed.classes[i2]], - box: get_bounding_box(box, !percentage) - })).sort((a, b) => b.score - a.score); - if (topk !== null) { - result = result.slice(0, topk); - } - toReturn.push(result); - } - return isBatched ? toReturn : toReturn[0]; - } - }; - var DocumentQuestionAnsweringPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ - Pipeline { - /** - * Create a new DocumentQuestionAnsweringPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {DocumentQuestionAnsweringPipelineCallback} */ - async _call(image, question, generate_kwargs = {}) { - const preparedImage = (await prepareImages(image))[0]; - const { pixel_values } = await this.processor(preparedImage); - const task_prompt = `${question}`; - const decoder_input_ids = this.tokenizer(task_prompt, { - add_special_tokens: false, - padding: true, - truncation: true - }).input_ids; - const output = await this.model.generate( - pixel_values, - { - ...generate_kwargs, - decoder_input_ids, - max_length: this.model.config.decoder.max_position_embeddings - } - ); - const decoded = this.tokenizer.batch_decode(output)[0]; - const match = decoded.match(/(.*?)<\/s_answer>/); - let answer = null; - if (match && match.length >= 2) { - answer = match[1].trim(); - } - return [{ answer }]; - } - }; - var TextToAudioPipeline = class extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ - Pipeline { - DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"; - /** - * Create a new TextToAudioPipeline. - * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - this.vocoder = options.vocoder ?? null; - } - /** @type {TextToAudioPipelineCallback} */ - async _call(text_inputs, { - speaker_embeddings = null - } = {}) { - if (this.processor) { - return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings }); - } else { - return this._call_text_to_waveform(text_inputs); - } - } - async _call_text_to_waveform(text_inputs) { - const inputs = this.tokenizer(text_inputs, { - padding: true, - truncation: true - }); - const { waveform } = await this.model(inputs); - const sampling_rate = this.model.config.sampling_rate; - return { - audio: waveform.data, - sampling_rate - }; - } - async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { - if (!this.vocoder) { - console.log("No vocoder specified, using default HifiGan vocoder."); - this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false }); - } - if (typeof speaker_embeddings === "string" || speaker_embeddings instanceof URL) { - speaker_embeddings = new Float32Array( - await (await fetch(speaker_embeddings)).arrayBuffer() - ); - } - if (speaker_embeddings instanceof Float32Array) { - speaker_embeddings = new Tensor( - "float32", - speaker_embeddings, - [1, speaker_embeddings.length] - ); - } else if (!(speaker_embeddings instanceof Tensor)) { - throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`."); - } - const { input_ids } = this.tokenizer(text_inputs, { - padding: true, - truncation: true - }); - const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - return { - audio: waveform.data, - sampling_rate - }; - } - }; - var ImageToImagePipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ - Pipeline { - /** - * Create a new ImageToImagePipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {ImageToImagePipelineCallback} */ - async _call(images) { - const preparedImages = await prepareImages(images); - const inputs = await this.processor(preparedImages); - const outputs = await this.model(inputs); - const toReturn = []; - for (const batch of outputs.reconstruction) { - const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8"); - toReturn.push(RawImage.fromTensor(output)); - } - return toReturn.length > 1 ? toReturn : toReturn[0]; - } - }; - var DepthEstimationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ - Pipeline { - /** - * Create a new DepthEstimationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - /** @type {DepthEstimationPipelineCallback} */ - async _call(images) { - const preparedImages = await prepareImages(images); - const inputs = await this.processor(preparedImages); - const { predicted_depth } = await this.model(inputs); - const toReturn = []; - for (let i = 0; i < preparedImages.length; ++i) { - const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), "bilinear", false); - const formatted = prediction.mul_(255 / max(prediction.data)[0]).to("uint8"); - toReturn.push({ - predicted_depth: predicted_depth[i], - depth: RawImage.fromTensor(formatted) - }); - } - return toReturn.length > 1 ? toReturn : toReturn[0]; - } - }; - var SUPPORTED_TASKS = Object.freeze({ - "text-classification": { - "tokenizer": AutoTokenizer, - "pipeline": TextClassificationPipeline, - "model": AutoModelForSequenceClassification, - "default": { - // TODO: replace with original - // "model": "distilbert-base-uncased-finetuned-sst-2-english", - "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english" - }, - "type": "text" - }, - "token-classification": { - "tokenizer": AutoTokenizer, - "pipeline": TokenClassificationPipeline, - "model": AutoModelForTokenClassification, - "default": { - // TODO: replace with original - // "model": "Davlan/bert-base-multilingual-cased-ner-hrl", - "model": "Xenova/bert-base-multilingual-cased-ner-hrl" - }, - "type": "text" - }, - "question-answering": { - "tokenizer": AutoTokenizer, - "pipeline": QuestionAnsweringPipeline, - "model": AutoModelForQuestionAnswering, - "default": { - // TODO: replace with original - // "model": "distilbert-base-cased-distilled-squad", - "model": "Xenova/distilbert-base-cased-distilled-squad" - }, - "type": "text" - }, - "fill-mask": { - "tokenizer": AutoTokenizer, - "pipeline": FillMaskPipeline, - "model": AutoModelForMaskedLM, - "default": { - // TODO: replace with original - // "model": "bert-base-uncased", - "model": "Xenova/bert-base-uncased" - }, - "type": "text" - }, - "summarization": { - "tokenizer": AutoTokenizer, - "pipeline": SummarizationPipeline, - "model": AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "sshleifer/distilbart-cnn-6-6", - "model": "Xenova/distilbart-cnn-6-6" - }, - "type": "text" - }, - "translation": { - "tokenizer": AutoTokenizer, - "pipeline": TranslationPipeline, - "model": AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "t5-small", - "model": "Xenova/t5-small" - }, - "type": "text" - }, - "text2text-generation": { - "tokenizer": AutoTokenizer, - "pipeline": Text2TextGenerationPipeline, - "model": AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "google/flan-t5-small", - "model": "Xenova/flan-t5-small" - }, - "type": "text" - }, - "text-generation": { - "tokenizer": AutoTokenizer, - "pipeline": TextGenerationPipeline, - "model": AutoModelForCausalLM, - "default": { - // TODO: replace with original - // "model": "gpt2", - "model": "Xenova/gpt2" - }, - "type": "text" - }, - "zero-shot-classification": { - "tokenizer": AutoTokenizer, - "pipeline": ZeroShotClassificationPipeline, - "model": AutoModelForSequenceClassification, - "default": { - // TODO: replace with original - // "model": "typeform/distilbert-base-uncased-mnli", - "model": "Xenova/distilbert-base-uncased-mnli" - }, - "type": "text" - }, - "audio-classification": { - "pipeline": AudioClassificationPipeline, - "model": AutoModelForAudioClassification, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "superb/wav2vec2-base-superb-ks", - "model": "Xenova/wav2vec2-base-superb-ks" - }, - "type": "audio" - }, - "zero-shot-audio-classification": { - "tokenizer": AutoTokenizer, - "pipeline": ZeroShotAudioClassificationPipeline, - "model": AutoModel, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "laion/clap-htsat-fused", - "model": "Xenova/clap-htsat-unfused" - }, - "type": "multimodal" - }, - "automatic-speech-recognition": { - "tokenizer": AutoTokenizer, - "pipeline": AutomaticSpeechRecognitionPipeline, - "model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC], - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "openai/whisper-tiny.en", - "model": "Xenova/whisper-tiny.en" - }, - "type": "multimodal" - }, - "text-to-audio": { - "tokenizer": AutoTokenizer, - "pipeline": TextToAudioPipeline, - "model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram], - "processor": [ - AutoProcessor, - /* Some don't use a processor */ - null - ], - "default": { - // TODO: replace with original - // "model": "microsoft/speecht5_tts", - "model": "Xenova/speecht5_tts" - }, - "type": "text" - }, - "image-to-text": { - "tokenizer": AutoTokenizer, - "pipeline": ImageToTextPipeline, - "model": AutoModelForVision2Seq, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "nlpconnect/vit-gpt2-image-captioning", - "model": "Xenova/vit-gpt2-image-captioning" - }, - "type": "multimodal" - }, - "image-classification": { - // no tokenizer - "pipeline": ImageClassificationPipeline, - "model": AutoModelForImageClassification, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "google/vit-base-patch16-224", - "model": "Xenova/vit-base-patch16-224" - }, - "type": "multimodal" - }, - "image-segmentation": { - // no tokenizer - "pipeline": ImageSegmentationPipeline, - "model": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation], - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "facebook/detr-resnet-50-panoptic", - "model": "Xenova/detr-resnet-50-panoptic" - }, - "type": "multimodal" - }, - "zero-shot-image-classification": { - "tokenizer": AutoTokenizer, - "pipeline": ZeroShotImageClassificationPipeline, - "model": AutoModel, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "openai/clip-vit-base-patch32", - "model": "Xenova/clip-vit-base-patch32" - }, - "type": "multimodal" - }, - "object-detection": { - // no tokenizer - "pipeline": ObjectDetectionPipeline, - "model": AutoModelForObjectDetection, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "facebook/detr-resnet-50", - "model": "Xenova/detr-resnet-50" - }, - "type": "multimodal" - }, - "zero-shot-object-detection": { - "tokenizer": AutoTokenizer, - "pipeline": ZeroShotObjectDetectionPipeline, - "model": AutoModelForZeroShotObjectDetection, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "google/owlvit-base-patch32", - "model": "Xenova/owlvit-base-patch32" - }, - "type": "multimodal" - }, - "document-question-answering": { - "tokenizer": AutoTokenizer, - "pipeline": DocumentQuestionAnsweringPipeline, - "model": AutoModelForDocumentQuestionAnswering, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "naver-clova-ix/donut-base-finetuned-docvqa", - "model": "Xenova/donut-base-finetuned-docvqa" - }, - "type": "multimodal" - }, - "image-to-image": { - // no tokenizer - "pipeline": ImageToImagePipeline, - "model": AutoModelForImageToImage, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "caidas/swin2SR-classical-sr-x2-64", - "model": "Xenova/swin2SR-classical-sr-x2-64" - }, - "type": "image" - }, - "depth-estimation": { - // no tokenizer - "pipeline": DepthEstimationPipeline, - "model": AutoModelForDepthEstimation, - "processor": AutoProcessor, - "default": { - // TODO: replace with original - // "model": "Intel/dpt-large", - "model": "Xenova/dpt-large" - }, - "type": "image" - }, - // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers). - "feature-extraction": { - "tokenizer": AutoTokenizer, - "pipeline": FeatureExtractionPipeline, - "model": AutoModel, - "default": { - // TODO: replace with original - // "model": "sentence-transformers/all-MiniLM-L6-v2", - "model": "Xenova/all-MiniLM-L6-v2" - }, - "type": "text" - } - }); - var TASK_ALIASES = Object.freeze({ - "sentiment-analysis": "text-classification", - "ner": "token-classification", - // "vqa": "visual-question-answering", // TODO: Add - "asr": "automatic-speech-recognition", - "text-to-speech": "text-to-audio", - // Add for backwards compatibility - "embeddings": "feature-extraction" - }); - async function pipeline(task, model = null, { - quantized = true, - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = "main" - } = {}) { - task = TASK_ALIASES[task] ?? task; - const pipelineInfo = SUPPORTED_TASKS[task.split("_", 1)[0]]; - if (!pipelineInfo) { - throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`); - } - if (!model) { - model = pipelineInfo.default.model; - console.log(`No model specified. Using default model: "${model}".`); - } - const pretrainedOptions = { - quantized, - progress_callback, - config, - cache_dir, - local_files_only, - revision - }; - const classes = /* @__PURE__ */ new Map([ - ["tokenizer", pipelineInfo.tokenizer], - ["model", pipelineInfo.model], - ["processor", pipelineInfo.processor] - ]); - const results = await loadItems(classes, model, pretrainedOptions); - results.task = task; - dispatchCallback(progress_callback, { - "status": "ready", - "task": task, - "model": model - }); - const pipelineClass = pipelineInfo.pipeline; - return new pipelineClass(results); - } - async function loadItems(mapping, model, pretrainedOptions) { - const result = /* @__PURE__ */ Object.create(null); - const promises = []; - for (let [name2, cls] of mapping.entries()) { - if (!cls) - continue; - let promise; - if (Array.isArray(cls)) { - promise = new Promise(async (resolve, reject) => { - let e; - for (let c of cls) { - if (c === null) { - resolve(null); - return; - } - try { - resolve(await c.from_pretrained(model, pretrainedOptions)); - return; - } catch (err) { - e = err; - } - } - reject(e); - }); - } else { - promise = cls.from_pretrained(model, pretrainedOptions); - } - result[name2] = promise; - promises.push(promise); - } - await Promise.all(promises); - for (let [name2, promise] of Object.entries(result)) { - result[name2] = await promise; - } - return result; - } - - // worker.ts - var _fetch = self.fetch; - function handleInit(e) { - const data = JSON.parse(e.data); - if (data.type === "init") { - self.fetch = function proxyFetch(url2, init) { - if (!(url2.startsWith("http://") || url2.startsWith("https://"))) { - const fullUrl = `${data.vscMediaUrl}/${url2}`; - return _fetch(fullUrl, init); - } - return _fetch(url2, init); - }; - self.removeEventListener("message", handleInit); - } - } - self.addEventListener("message", handleInit); - env.allowLocalModels = true; - env.allowRemoteModels = false; - env.useBrowserCache = false; - env.backends.onnx.wasm.wasmPaths = "ort-wasm/"; - var EmbeddingsPipeline = class { - static task = "feature-extraction"; - static model = "all-MiniLM-L6-v2"; - static instance = null; - static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); - } - return this.instance; - } - }; - self.addEventListener("message", async (event) => { - const data = JSON.parse(event.data); - if (data.type !== "embeddings") { - return; - } - let extractor = await EmbeddingsPipeline.getInstance(); - let output = await extractor(data.chunks, { - pooling: "mean", - normalize: true - }); - self.postMessage({ - embeddings: output.tolist(), - id: data.id, - type: "embeddings" - }); - }); -})(); -/*! Bundled license information: - -onnxruntime-common/dist/ort-common.node.js: - (*! - * ONNX Runtime Common v1.14.0 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - *) - -onnxruntime-web/dist/ort-web.min.js: - (*! - * ONNX Runtime Web v1.14.0 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - *) -*/ -//# sourceMappingURL=worker.js.map diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 78dc0abd1..49a2bb398 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -14,6 +14,7 @@ import MonacoPage from "./pages/monaco"; import SettingsPage from "./pages/settings"; import { ExtensionIde } from "core/ide"; +import { getBasename } from "core/util"; import MiniSearch from "minisearch"; const router = createMemoryRouter([ @@ -66,14 +67,21 @@ const router = createMemoryRouter([ }, ]); -const miniSearch = new MiniSearch({ +const filesMiniSearch = new MiniSearch({ fields: ["id", "basename"], storeFields: ["id", "basename"], }); -export const SearchContext = createContext<[MiniSearch, MiniSearchResult[]]>([ - miniSearch, - [], -]); +export const FilesSearchContext = createContext< + [MiniSearch, MiniSearchResult[]] +>([filesMiniSearch, []]); + +const foldersMiniSearch = new MiniSearch({ + fields: ["id", "basename"], + storeFields: ["id", "basename"], +}); +export const FoldersSearchContext = createContext< + [MiniSearch, MiniSearchResult[]] +>([foldersMiniSearch, []]); export interface MiniSearchResult { id: string; @@ -85,23 +93,43 @@ function App() { useSetup(dispatch); - const [firstResults, setFirstResults] = useState([]); + const [filesFirstResults, setFilesFirstResults] = useState< + MiniSearchResult[] + >([]); + const [foldersFirstResults, setFoldersFirstResults] = useState< + MiniSearchResult[] + >([]); useEffect(() => { (async () => { const files = await new ExtensionIde().listWorkspaceContents(); const results = files.map((filepath) => { - return { id: filepath, basename: filepath.split(/[\\/]/).pop() }; + return { id: filepath, basename: getBasename(filepath) }; }); - miniSearch.addAll(results); - setFirstResults(results); + filesMiniSearch.addAll(results); + setFilesFirstResults(results); + })(); + }, []); + + useEffect(() => { + (async () => { + const folders = await new ExtensionIde().listFolders(); + const results = folders.map((path) => { + return { id: path, basename: getBasename(path) }; + }); + foldersMiniSearch.addAll(results); + setFoldersFirstResults(results); })(); }, []); return ( - - - + + + + + ); } diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 52bab08ff..541a8f376 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -4,7 +4,7 @@ import { SparklesIcon, } from "@heroicons/react/24/outline"; import { postToIde } from "core/ide/messaging"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; @@ -14,7 +14,6 @@ import { vscBackground, vscForeground, } from "."; -import useLoadEmbeddings from "../hooks/useLoadEmbeddings"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { setBottomMessage, @@ -162,6 +161,8 @@ const Layout = () => { } else { navigate("/history"); } + } else if (event.data.type === "indexProgress") { + setIndexingProgress(event.data.progress); } }; window.addEventListener("message", handler); @@ -170,7 +171,7 @@ const Layout = () => { }; }, [location, navigate]); - const { progress: indexingProgress, currentlyIndexing } = useLoadEmbeddings(); + const [indexingProgress, setIndexingProgress] = useState(1); return ( @@ -240,7 +241,7 @@ const Layout = () => { {indexingProgress < 1 && ( diff --git a/gui/src/components/mainInput/MentionExtension.ts b/gui/src/components/mainInput/MentionExtension.ts index 0dbba69d3..88fbda1ee 100644 --- a/gui/src/components/mainInput/MentionExtension.ts +++ b/gui/src/components/mainInput/MentionExtension.ts @@ -126,6 +126,20 @@ export const Mention = Node.create({ }; }, }, + + itemType: { + default: null, + parseHTML: (element) => element.getAttribute("data-itemType"), + renderHTML: (attributes) => { + if (!attributes.itemType) { + return {}; + } + + return { + "data-itemType": attributes.itemType, + }; + }, + }, }; }, diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index dbdd73049..16ee7be9b 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -46,6 +46,7 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { open: FolderOpenIcon, codebase: SparklesIcon, problems: ExclamationTriangleIcon, + folder: FolderIcon, "/edit": PaintBrushIcon, "/clear": TrashIcon, "/test": BeakerIcon, @@ -129,10 +130,10 @@ const QueryInput = styled.textarea` interface MentionListProps { items: ComboBoxItem[]; - command: (item: ComboBoxItem) => void; + command: (item: any) => void; editor: Editor; - enterSubmenu?: (editor: Editor) => void; + enterSubmenu?: (editor: Editor, providerId: string) => void; } const MentionList = forwardRef((props: MentionListProps, ref) => { @@ -156,9 +157,13 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { const selectItem = (index) => { const item = props.items[index]; - if (item.id === "file") { + if (item.type === "contextProvider" && item.id === "file") { setSubMenuTitle("Files - Type to search"); - props.enterSubmenu(props.editor); + props.enterSubmenu(props.editor, "file"); + return; + } else if (item.type === "contextProvider" && item.id === "folder") { + setSubMenuTitle("Folder - Type to search"); + props.enterSubmenu(props.editor, "folder"); return; } @@ -169,7 +174,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { } if (item) { - props.command(item); + props.command({ ...item, itemType: item.type }); } }; @@ -272,7 +277,10 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { filename={item.title} > )} - {item.type !== "file" && ( + {item.type === "folder" && ( + + )} + {item.type !== "file" && item.type !== "folder" && ( { className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2 flex items-center" > {item.description} - {item.id === "file" && ( - - )} + {item.type === "contextProvider" && + (item.id === "file" || item.id === "folder") && ( + + )} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index cf85e8586..2ec2756bc 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -15,7 +15,7 @@ import { secondaryDark, vscForeground, } from ".."; -import { SearchContext } from "../../App"; +import { FilesSearchContext, FoldersSearchContext } from "../../App"; import useHistory from "../../hooks/useHistory"; import useUpdatingRef from "../../hooks/useUpdatingRef"; import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice"; @@ -71,7 +71,9 @@ interface TipTapEditorProps { function TipTapEditor(props: TipTapEditorProps) { const dispatch = useDispatch(); - const [miniSearch, firstResults] = useContext(SearchContext); + const [filesMiniSearch, filesFirstResults] = useContext(FilesSearchContext); + const [foldersMiniSearch, foldersFirstResults] = + useContext(FoldersSearchContext); const historyLength = useSelector( (store: RootStore) => store.state.history.length @@ -81,10 +83,10 @@ function TipTapEditor(props: TipTapEditorProps) { const { saveSession } = useHistory(dispatch); - const inSubmenuRef = useRef(false); + const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); - const enterSubmenu = async (editor: Editor) => { + const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); if (indexOfAt === -1) { @@ -95,7 +97,7 @@ function TipTapEditor(props: TipTapEditorProps) { from: indexOfAt + 2, to: contents.length + 1, }); - inSubmenuRef.current = true; + inSubmenuRef.current = providerId; // to trigger refresh of suggestions editor.commands.insertContent(" "); @@ -106,7 +108,7 @@ function TipTapEditor(props: TipTapEditorProps) { }; const onClose = () => { - inSubmenuRef.current = false; + inSubmenuRef.current = undefined; inDropdownRef.current = false; }; @@ -118,11 +120,13 @@ function TipTapEditor(props: TipTapEditorProps) { (store: RootStore) => store.state.contextItems ); - const miniSearchRef = useUpdatingRef(miniSearch); + const filesMiniSearchRef = useUpdatingRef(filesMiniSearch); + const foldersMiniSearchRef = useUpdatingRef(foldersMiniSearch); const availableContextProvidersRef = useUpdatingRef( props.availableContextProviders ); - const firstResultsRef = useUpdatingRef(firstResults); + const filesFirstResultsRef = useUpdatingRef(filesFirstResults); + const foldersFirstResultsRef = useUpdatingRef(foldersFirstResults); const historyLengthRef = useUpdatingRef(historyLength); const onEnterRef = useUpdatingRef(props.onEnter); const availableSlashCommandsRef = useUpdatingRef( @@ -177,8 +181,10 @@ function TipTapEditor(props: TipTapEditorProps) { }, suggestion: getMentionSuggestion( availableContextProvidersRef, - miniSearchRef, - firstResultsRef, + filesMiniSearchRef, + filesFirstResultsRef, + foldersMiniSearchRef, + foldersFirstResultsRef, enterSubmenu, onClose, onOpen, diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 934c0999a..87d97a296 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -10,7 +10,7 @@ import { ComboBoxItem, ComboBoxItemType } from "./types"; function getSuggestion( items: (props: { query: string }) => ComboBoxItem[], - enterSubmenu: (editor: Editor) => void = (editor) => {}, + enterSubmenu: (editor: Editor, providerId: string) => void = (editor) => {}, onClose: () => void = () => {}, onOpen: () => void = () => {} ) { @@ -99,6 +99,26 @@ function refreshOpenFiles() { } refreshOpenFiles(); +let folders: ComboBoxItem[] = []; +function refreshFolders() { + new ExtensionIde().listFolders().then((f) => { + folders = f.map((folder) => { + const baseName = getBasename(folder); + const lastTwoParts = folder.split(/[\\/]/).slice(-2).join("/"); + return { + title: baseName, + description: lastTwoParts, + id: "folder", + content: folder, + label: baseName, + type: "folder" as ComboBoxItemType, + query: folder, + }; + }); + }); +} +refreshFolders(); + function getFileItems( query: string, miniSearch: MiniSearch, @@ -109,7 +129,7 @@ function getFileItems( fuzzy: 5, }); if (res.length === 0) { - return openFiles; + return openFiles.length > 0 ? openFiles : firstResults; } return ( res?.slice(0, 10).map((hit) => { @@ -127,21 +147,59 @@ function getFileItems( ); } +function getFolderItems( + query: string, + miniSearch: MiniSearch, + firstResults: any[] +): ComboBoxItem[] { + let res: any[] = miniSearch.search(query.trim() === "" ? "/" : query, { + prefix: true, + fuzzy: 5, + }); + + if (res.length === 0) { + return folders.slice(0, 10); + } + return ( + res?.slice(0, 10).map((hit) => { + const lastTwoParts = hit.id.split(/[\\/]/).slice(-2).join("/"); + const item = { + title: hit.basename, + description: lastTwoParts, + id: "folder", + content: hit.id, + label: hit.basename, + query: hit.id, + type: "folder" as ComboBoxItemType, + }; + return item; + }) || [] + ); +} + export function getMentionSuggestion( availableContextProvidersRef: MutableRefObject, - miniSearchRef: MutableRefObject, - firstResultsRef: MutableRefObject, - enterSubmenu: (editor: Editor) => void, + filesMiniSearchRef: MutableRefObject, + filesFirstResultsRef: MutableRefObject, + foldersMiniSearchRef: MutableRefObject, + foldersFirstResultsRef: MutableRefObject, + enterSubmenu: (editor: Editor, providerId: string) => void, onClose: () => void, onOpen: () => void, - inSubmenu: MutableRefObject + inSubmenu: MutableRefObject ) { const items = ({ query }) => { - if (inSubmenu.current) { + if (inSubmenu.current === "file") { return getFileItems( query, - miniSearchRef.current, - firstResultsRef.current + filesMiniSearchRef.current, + filesFirstResultsRef.current + ); + } else if (inSubmenu.current === "folder") { + return getFolderItems( + query, + foldersMiniSearchRef.current, + filesFirstResultsRef.current ); } @@ -170,8 +228,8 @@ export function getMentionSuggestion( if (mainResults.length === 0) { return getFileItems( query, - miniSearchRef.current, - firstResultsRef.current + filesMiniSearchRef.current, + filesFirstResultsRef.current ); } return mainResults; diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index ec0492c89..621539b41 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -12,6 +12,7 @@ import { getContextItems } from "../../hooks/useContextProviders"; interface MentionAttrs { label: string; id: string; + itemType?: string; query?: string; } @@ -57,11 +58,7 @@ async function resolveEditorContent( let contextItems: ContextItemWithId[] = []; const ide = new ExtensionIde(); for (const item of contextItemAttrs) { - if ( - item.id.startsWith("/") || - item.id.startsWith("\\") || - (item.id.length > 2 && item.id[1] === ":" && item.id[2] === "\\") - ) { + if (item.itemType === "file") { // This is a quick way to resolve @file references const basename = getBasename(item.id); const content = await ide.readFile(item.id); @@ -97,7 +94,7 @@ async function resolveEditorContent( contextItemsText += "\n"; } - let finalText = contextItemsText + paragraphs.join("\n"); + let finalText = paragraphs.join("\n").trim(); if (slashCommand) { finalText = `${slashCommand} ${finalText}`; } diff --git a/gui/src/components/mainInput/types.d.ts b/gui/src/components/mainInput/types.d.ts index b43bcdd0f..33158ae1b 100644 --- a/gui/src/components/mainInput/types.d.ts +++ b/gui/src/components/mainInput/types.d.ts @@ -4,7 +4,8 @@ export type ComboBoxItemType = | "contextProvider" | "slashCommand" | "file" - | "query"; + | "query" + | "folder"; export interface ComboBoxItem { title: string; diff --git a/gui/src/hooks/useLoadEmbeddings.tsx b/gui/src/hooks/useLoadEmbeddings.tsx index 991caf4df..32113b7f1 100644 --- a/gui/src/hooks/useLoadEmbeddings.tsx +++ b/gui/src/hooks/useLoadEmbeddings.tsx @@ -1,6 +1,6 @@ import { Chunk } from "core"; import { ExtensionIde } from "core/ide"; -import { chunkDocument } from "core/index/chunk/chunk"; +import { chunkDocument } from "core/indexing/chunk/chunk"; import { getBasename } from "core/util"; import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; @@ -22,6 +22,8 @@ function useLoadEmbeddings() { ); async function loadEmbeddings() { + return; + if (!embeddingsProvider || disableIndexing) { return; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 831444b56..5d108be84 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -13,7 +13,6 @@ import { VSC_THEME_COLOR_VARS } from "../components"; import { setVscMachineId } from "../redux/slices/configSlice"; import { setConfig, setInactive } from "../redux/slices/stateSlice"; import { RootStore } from "../redux/store"; -import TransformersJsEmbeddingsProvider from "../util/TransformersJsEmbeddingsProvider"; import useChatHandler from "./useChatHandler"; function useSetup(dispatch: Dispatch) { @@ -46,14 +45,6 @@ function useSetup(dispatch: Dispatch) { } ); - // Swap in web-version of TransformersJsEmbeddingsProvider - if ( - (finalConfig.embeddingsProvider as any)?.providerName === - "transformers.js" - ) { - finalConfig.embeddingsProvider = new TransformersJsEmbeddingsProvider(); - } - // Fall back to config.json dispatch(setConfig(finalConfig)); } catch (e) { diff --git a/gui/src/redux/slices/serverStateReducer.ts b/gui/src/redux/slices/serverStateReducer.ts index fad095ba1..85f0a1ca8 100644 --- a/gui/src/redux/slices/serverStateReducer.ts +++ b/gui/src/redux/slices/serverStateReducer.ts @@ -1,5 +1,4 @@ import { createSlice } from "@reduxjs/toolkit"; -import TransformersJsEmbeddingsProvider from "core/index/embeddings/TransformersJsEmbeddingsProvider"; import FreeTrial from "core/llm/llms/FreeTrial"; import { RootStore } from "../store"; @@ -27,7 +26,6 @@ const initialState: RootStore["serverState"] = { new FreeTrial({ model: "gpt-4" }), new FreeTrial({ model: "gpt-3.5-turbo" }), ], - embeddingsProvider: new TransformersJsEmbeddingsProvider(), }, contextProviders: [], savedContextGroups: [], diff --git a/gui/src/util/TransformersJsEmbeddingsProvider.ts b/gui/src/util/TransformersJsEmbeddingsProvider.ts deleted file mode 100644 index 5365f0056..000000000 --- a/gui/src/util/TransformersJsEmbeddingsProvider.ts +++ /dev/null @@ -1,51 +0,0 @@ -import BaseEmbeddingsProvider from "core/index/embeddings/BaseEmbeddingsProvider"; -import { v4 as uuidv4 } from "uuid"; - -let worker: Worker | null = null; - -class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { - constructor() { - super({ model: "all-MiniLM-L2-v6" }); - } - - get id(): string { - return "transformers-js"; - } - - embed(chunks: string[]) { - return new Promise(async (resolve) => { - if (!worker) { - const resp = await fetch("/worker.js"); - const blob = await resp.blob(); - const blobUrl = URL.createObjectURL(blob); - worker = new Worker(blobUrl, { - type: "module", - }); - - worker.postMessage( - JSON.stringify({ - type: "init", - vscMediaUrl: (window as any).vscMediaUrl, - }) - ); - } - let id = uuidv4(); - const onMessageReceived = (e: any) => { - if (e.data.type === "embeddings" && e.data.id === id) { - worker?.removeEventListener("message", onMessageReceived); - resolve(e.data.embeddings); - } - }; - worker.addEventListener("message", onMessageReceived); - worker.postMessage( - JSON.stringify({ - chunks, - id, - type: "embeddings", - }) - ); - }); - } -} - -export default TransformersJsEmbeddingsProvider; diff --git a/package/.gitignore b/package/.gitignore new file mode 100644 index 000000000..2124e6f6d --- /dev/null +++ b/package/.gitignore @@ -0,0 +1,3 @@ +bin +data +out \ No newline at end of file diff --git a/package/package-lock.json b/package/package-lock.json new file mode 100644 index 000000000..82201e04a --- /dev/null +++ b/package/package-lock.json @@ -0,0 +1,2370 @@ +{ + "name": "package", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "package", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "@lancedb/vectordb-darwin-arm64": "^0.4.3", + "vectordb": "^0.4.3" + }, + "bin": { + "package": "out/index.js" + }, + "devDependencies": { + "@vercel/ncc": "^0.38.1", + "esbuild": "^0.19.11", + "pkg": "^5.8.1", + "typescript": "^5.3.3" + } + }, + "node_modules/@75lb/deep-merge": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz", + "integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==", + "dependencies": { + "lodash.assignwith": "^4.2.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@75lb/deep-merge/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@apache-arrow/ts": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", + "integrity": "sha512-CtwAvLkK0CZv7xsYeCo91ml6PvlfzAmAJZkRYuz2GNBwfYufj5SVi0iuSMwIMkcU/szVwvLdzORSLa5PlF/2ug==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + } + }, + "node_modules/@babel/generator": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.18.2.tgz", + "integrity": "sha512-W1lG5vUwFvfMd8HVXqdfbuG7RuaSrTCCD8cl8fP8wOivdbtbIg2Db3IWUcgvfxKbbn6ZBGYRW/Zk1MIwK49mgw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.18.2", + "@jridgewell/gen-mapping": "^0.3.0", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.18.4.tgz", + "integrity": "sha512-FDge0dFazETFcxGw/EXzOkN8uJp0PC7Qbm+Pe9T+av2zlBpOgunFHkQPPn+eRuClU73JF+98D531UgayY89tow==", + "dev": true, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.19.0.tgz", + "integrity": "sha512-YuGopBq3ke25BVSiS6fgF49Ul9gH1x70Bcr6bqRLjWCkcX8Hre1/5+z+IiWOIerRMSSEfGZVB9z9kyq7wVs9YA==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.18.10", + "@babel/helper-validator-identifier": "^7.18.6", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz", + "integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz", + "integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz", + "integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz", + "integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz", + "integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz", + "integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz", + "integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz", + "integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz", + "integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz", + "integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz", + "integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz", + "integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz", + "integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz", + "integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz", + "integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz", + "integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz", + "integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz", + "integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz", + "integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz", + "integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz", + "integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz", + "integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz", + "integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.21", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz", + "integrity": "sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.3.tgz", + "integrity": "sha512-47CvvSaV1EdUsFEpXUJApTk+hMzAhCxVizipCFUlXCgcmzpCDL86wNgJij/X9a+j6zADhIX//Lsu0qd/an/Bpw==", + "cpu": [ + "arm64" + ], + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-darwin-x64": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.3.tgz", + "integrity": "sha512-UlZZv8CmJIuRJNJG+Y1VmFsGyPR8W/72Q5EwgMMsSES6zpMQ9pNdBDWhL3UGX6nMRgnbprkwYiWJ3xHhJvtqtw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.3.tgz", + "integrity": "sha512-L6NVJr/lKEd8+904FzZNpT8BGQMs2cHNYbGJMIaVvGnMiIJgKAFKtOyGtdDjoe1xRZoEw21yjRGksGbnRO5wHQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.3.tgz", + "integrity": "sha512-OBx3WF3pK0xNfFJeErmuD9R2QWLa3XdeZspyTsIrQmBDeKj3HKh8y7Scpx4NH5Y09+9JNqRRKRZN7OqWTYhITg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.3.tgz", + "integrity": "sha512-n9IvR81NXZKnSN91mrgeXbEyCiGM+YLJpOgbdHoEtMP04VDnS+iSU4jGOtQBKErvWeCJQaGFQ9qzdcVchpRGyw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@neon-rs/load": { + "version": "0.0.74", + "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", + "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@types/command-line-args": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.0.tgz", + "integrity": "sha512-UuKzKpJJ/Ief6ufIaIzr3A/0XnluX7RvFgwkV89Yzvm77wCh1kFaFmqN8XEnGcN62EuHdedQjEMb8mYxFLGPyA==" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", + "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" + }, + "node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/@types/pad-left": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@types/pad-left/-/pad-left-2.1.1.tgz", + "integrity": "sha512-Xd22WCRBydkGSApl5Bw0PhAOHKSVjNL3E3AwzKaps96IMraPqy5BvZIsBVK6JLwdybUzjHnuWVwpDd0JjTfHXA==" + }, + "node_modules/@vercel/ncc": { + "version": "0.38.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.1.tgz", + "integrity": "sha512-IBBb+iI2NLu4VQn3Vwldyi2QwaXt5+hTyh58ggAMoCGE6DJmPvwL3KPBWcJl1m9LYPChBLE980Jw+CS4Wokqxw==", + "dev": true, + "bin": { + "ncc": "dist/ncc/cli.js" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/apache-arrow": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-14.0.2.tgz", + "integrity": "sha512-EBO2xJN36/XoY81nhLcwCJgFwkboDZeyNQ+OPsG7bCoQjc2BT0aTyH/MR6SrL+LirSNz+cYqjGRlupMMlP1aEg==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/array-back": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", + "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/axios": { + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", + "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "dev": true + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/command-line-args": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", + "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==", + "dependencies": { + "array-back": "^3.1.0", + "find-replace": "^3.0.0", + "lodash.camelcase": "^4.3.0", + "typical": "^4.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/command-line-usage": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.1.tgz", + "integrity": "sha512-NCyznE//MuTjwi3y84QVUGEOT+P5oto1e1Pk/jFPVdPPfsG03qpTIl3yw6etR+v73d0lXsoojRpvbru2sqePxQ==", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^3.0.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/command-line-usage/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/command-line-usage/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dev": true, + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dev": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/esbuild": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz", + "integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.11", + "@esbuild/android-arm": "0.19.11", + "@esbuild/android-arm64": "0.19.11", + "@esbuild/android-x64": "0.19.11", + "@esbuild/darwin-arm64": "0.19.11", + "@esbuild/darwin-x64": "0.19.11", + "@esbuild/freebsd-arm64": "0.19.11", + "@esbuild/freebsd-x64": "0.19.11", + "@esbuild/linux-arm": "0.19.11", + "@esbuild/linux-arm64": "0.19.11", + "@esbuild/linux-ia32": "0.19.11", + "@esbuild/linux-loong64": "0.19.11", + "@esbuild/linux-mips64el": "0.19.11", + "@esbuild/linux-ppc64": "0.19.11", + "@esbuild/linux-riscv64": "0.19.11", + "@esbuild/linux-s390x": "0.19.11", + "@esbuild/linux-x64": "0.19.11", + "@esbuild/netbsd-x64": "0.19.11", + "@esbuild/openbsd-x64": "0.19.11", + "@esbuild/sunos-x64": "0.19.11", + "@esbuild/win32-arm64": "0.19.11", + "@esbuild/win32-ia32": "0.19.11", + "@esbuild/win32-x64": "0.19.11" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fastq": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.16.0.tgz", + "integrity": "sha512-ifCoaXsDrsdkWTtiNJX5uzHDsrck5TzfKKDcuFFTIrrc/BS076qgEIfoIy1VeZqViznfKiysPYTh/QeHtnIsYA==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-replace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", + "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", + "dependencies": { + "array-back": "^3.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/flatbuffers": { + "version": "23.5.26", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", + "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==" + }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha512-OMcX/4IC/uqEPVgGeyfN22LJk6AZrMkRZHxcHBMBvHScDGgwTm2GT2Wkgtocyd3JfZffjj2kYUDXXII0Fk9W0g==", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true + }, + "node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "dev": true + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", + "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true + }, + "node_modules/into-stream": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/into-stream/-/into-stream-6.0.0.tgz", + "integrity": "sha512-XHbaOAvP+uFKUFsOgoNPRjLkwB+I22JFPFe5OjTkQ0nwgj6+pSjb4NmB6VMxaPshLiOf+zcpOCBQuLwC1KHhZA==", + "dev": true, + "dependencies": { + "from2": "^2.3.0", + "p-is-promise": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-core-module": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.9.0.tgz", + "integrity": "sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/lodash.assignwith": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz", + "integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "dev": true + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/multistream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/multistream/-/multistream-4.1.0.tgz", + "integrity": "sha512-J1XDiAmmNpRCBfIWJv+n0ymC4ABcf/Pl+5YvC5B/D2f/2+8PtHvCNxMPKiQcZyi922Hq69J2YOpb1pTywfifyw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "once": "^1.4.0", + "readable-stream": "^3.6.0" + } + }, + "node_modules/multistream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", + "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==", + "dev": true + }, + "node_modules/node-abi": { + "version": "3.54.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.54.0.tgz", + "integrity": "sha512-p7eGEiQil0YUV3ItH4/tBb781L5impVmmx2E9FRKF7d18XXzp4PGT2tdYMFY6wQqgxD0IwNZOiSJ0/K0fSi/OA==", + "dev": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-is-promise": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-3.0.0.tgz", + "integrity": "sha512-Wo8VsW4IRQSKVXsJCn7TomUaVtyfjVDn3nUP7kE967BQk0CwFpdbZs0X0uk5sW9mkBa9eNM7hCMaG93WUAwxYQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/pad-left": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", + "integrity": "sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA==", + "dependencies": { + "repeat-string": "^1.5.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg": { + "version": "5.8.1", + "resolved": "https://registry.npmjs.org/pkg/-/pkg-5.8.1.tgz", + "integrity": "sha512-CjBWtFStCfIiT4Bde9QpJy0KeH19jCfwZRJqHFDFXfhUklCx8JoFmMj3wgnEYIwGmZVNkhsStPHEOnrtrQhEXA==", + "dev": true, + "dependencies": { + "@babel/generator": "7.18.2", + "@babel/parser": "7.18.4", + "@babel/types": "7.19.0", + "chalk": "^4.1.2", + "fs-extra": "^9.1.0", + "globby": "^11.1.0", + "into-stream": "^6.0.0", + "is-core-module": "2.9.0", + "minimist": "^1.2.6", + "multistream": "^4.1.0", + "pkg-fetch": "3.4.2", + "prebuild-install": "7.1.1", + "resolve": "^1.22.0", + "stream-meter": "^1.0.4" + }, + "bin": { + "pkg": "lib-es5/bin.js" + }, + "peerDependencies": { + "node-notifier": ">=9.0.1" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/pkg-fetch": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/pkg-fetch/-/pkg-fetch-3.4.2.tgz", + "integrity": "sha512-0+uijmzYcnhC0hStDjm/cl2VYdrmVVBpe7Q8k9YBojxmR5tG8mvR9/nooQq3QSXiQqORDVOTY3XqMEqJVIzkHA==", + "dev": true, + "dependencies": { + "chalk": "^4.1.2", + "fs-extra": "^9.1.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.6", + "progress": "^2.0.3", + "semver": "^7.3.5", + "tar-fs": "^2.1.1", + "yargs": "^16.2.0" + }, + "bin": { + "pkg-fetch": "lib-es5/bin.js" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", + "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", + "dev": true, + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dev": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve/node_modules/is-core-module": { + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "dev": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/stream-meter": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/stream-meter/-/stream-meter-1.0.4.tgz", + "integrity": "sha512-4sOEtrbgFotXwnEuzzsQBYEV1elAeFSO8rSGeTwabuX1RRn/kEq9JVH7I0MRBhKVRR0sJkr0M0QCH7yOLf9fhQ==", + "dev": true, + "dependencies": { + "readable-stream": "^2.1.4" + } + }, + "node_modules/stream-read-all": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz", + "integrity": "sha512-EWZT9XOceBPlVJRrYcykW8jyRSZYbkb/0ZK36uLEmoWVO5gxBOnntNTseNzfREsqxqdfEGQrD8SXQ3QWbBmq8A==", + "engines": { + "node": ">=10" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/table-layout": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz", + "integrity": "sha512-rpyNZYRw+/C+dYkcQ3Pr+rLxW4CfHpXjPDnG7lYhdRoUcZTUt+KEsX+94RGp/aVp/MQU35JCITv2T/beY4m+hw==", + "dependencies": { + "@75lb/deep-merge": "^1.1.1", + "array-back": "^6.2.2", + "command-line-args": "^5.2.1", + "command-line-usage": "^7.0.0", + "stream-read-all": "^3.0.1", + "typical": "^7.1.1", + "wordwrapjs": "^5.1.0" + }, + "bin": { + "table-layout": "bin/cli.js" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "dev": true, + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dev": true, + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", + "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typical": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", + "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true + }, + "node_modules/vectordb": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.3.tgz", + "integrity": "sha512-7ToixoZgAB/hn44EE4ftcdE74SGRX+wmGejatTQodFBiYD9RQLW8LIuGo8MmT+AkYEDAuOR98jTEFUwnEU5sqA==", + "cpu": [ + "x64", + "arm64" + ], + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@apache-arrow/ts": "^14.0.2", + "@neon-rs/load": "^0.0.74", + "apache-arrow": "^14.0.2", + "axios": "^1.4.0" + }, + "optionalDependencies": { + "@lancedb/vectordb-darwin-arm64": "0.4.3", + "@lancedb/vectordb-darwin-x64": "0.4.3", + "@lancedb/vectordb-linux-arm64-gnu": "0.4.3", + "@lancedb/vectordb-linux-x64-gnu": "0.4.3", + "@lancedb/vectordb-win32-x64-msvc": "0.4.3" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wordwrapjs": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.0.tgz", + "integrity": "sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "engines": { + "node": ">=10" + } + } + } +} diff --git a/package/package.json b/package/package.json new file mode 100644 index 000000000..5cc645f5a --- /dev/null +++ b/package/package.json @@ -0,0 +1,36 @@ +{ + "name": "package", + "version": "1.0.0", + "description": "", + "main": "out/index.js", + "bin": "out/index.js", + "pkg": { + "scripts": [ + "node_modules/axios/**/*" + ], + "assets": [ + "node_modules/@lancedb/vectordb-darwin-arm64/**/*" + ], + "targets": [ + "node18-darwin-arm64" + ], + "outputPath": "bin" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "ncc build src/index.ts -o out && pkg .", + "build:dev": "tsc" + }, + "author": "Nate Sesti and Ty Dunn", + "license": "Apache-2.0", + "devDependencies": { + "@vercel/ncc": "^0.38.1", + "esbuild": "^0.19.11", + "pkg": "^5.8.1", + "typescript": "^5.3.3" + }, + "dependencies": { + "@lancedb/vectordb-darwin-arm64": "^0.4.3", + "vectordb": "^0.4.3" + } +} diff --git a/package/src/index.ts b/package/src/index.ts new file mode 100644 index 000000000..2acb48728 --- /dev/null +++ b/package/src/index.ts @@ -0,0 +1,14 @@ +import * as lancedb from "vectordb"; + +(async () => { + console.log("Hello!"); + const uri = "data/sample-lancedb"; + const db = await lancedb.connect(uri); + const tb = await db.createTable("myTable", [ + { vector: [3.1, 4.1], item: "foo", price: 10.0 }, + { vector: [5.9, 26.5], item: "bar", price: 20.0 }, + ]); + const query = await tb.search([100, 100]).limit(2).execute(); + console.log(query); + console.log("DONE"); +})(); diff --git a/package/tsconfig.json b/package/tsconfig.json new file mode 100644 index 000000000..b4e96c713 --- /dev/null +++ b/package/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "ES2020", + "outDir": "out", + "lib": ["ES2020", "dom", "es6", "es5", "dom.iterable", "scripthost"], + "sourceMap": true, + "rootDir": "src", + "allowJs": true, + "strict": true /* enable all strict type-checking options */, + /* Additional Checks */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + "resolveJsonModule": true /* Enable importing .json files */ + }, + "include": ["src/**/*"] +} diff --git a/webworker/esbuild.js b/webworker/esbuild.js deleted file mode 100644 index 82810b17f..000000000 --- a/webworker/esbuild.js +++ /dev/null @@ -1,9 +0,0 @@ -const { build } = require("esbuild"); - -build({ - entryPoints: ["worker.ts"], - bundle: true, - outfile: "dist/worker.js", - platform: "browser", - sourcemap: true, -}).catch(() => process.exit(1)); diff --git a/webworker/package.json b/webworker/package.json deleted file mode 100644 index 79da015f0..000000000 --- a/webworker/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "webworker", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "build": "node esbuild.js && cp dist/worker.js ../gui/public/worker.js" - }, - "author": "", - "license": "ISC", - "dependencies": { - "@xenova/transformers": "^2.13.4" - }, - "devDependencies": { - "esbuild": "^0.19.11", - "typescript": "^5.3.3" - } -} diff --git a/webworker/tsconfig.json b/webworker/tsconfig.json deleted file mode 100644 index e40b95d7a..000000000 --- a/webworker/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "useDefineForClassFields": true, - "lib": ["DOM", "DOM.Iterable", "ESNext"], - "allowJs": false, - "skipLibCheck": true, - "esModuleInterop": false, - "allowSyntheticDefaultImports": true, - "strict": false, - "forceConsistentCasingInFileNames": true, - "module": "ESNext", - "moduleResolution": "Node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "react-jsx", - "noEmitOnError": false - }, - "include": ["worker.ts"] -} diff --git a/webworker/worker.ts b/webworker/worker.ts deleted file mode 100644 index 19f87dd55..000000000 --- a/webworker/worker.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { PipelineType, env, pipeline } from "@xenova/transformers"; - -// --- Allow web worker to fetch from the same origin -let _fetch = self.fetch; - -function handleInit(e: any) { - const data = JSON.parse(e.data); - if (data.type === "init") { - self.fetch = function proxyFetch( - url: string, - init?: RequestInit - ): Promise { - if (!(url.startsWith("http://") || url.startsWith("https://"))) { - const fullUrl = `${data.vscMediaUrl}/${url}`; - return _fetch(fullUrl, init); - } - - return _fetch(url, init); - }; - - self.removeEventListener("message", handleInit); - } -} -self.addEventListener("message", handleInit); - -// --- - -env.allowLocalModels = true; -env.allowRemoteModels = false; -env.useBrowserCache = false; // Doesn't work with web workers (only in VS Code?) -env.backends.onnx.wasm.wasmPaths = "ort-wasm/"; - -class EmbeddingsPipeline { - static task: PipelineType = "feature-extraction"; - static model = "all-MiniLM-L6-v2"; - static instance = null; - - static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); - } - - return this.instance; - } -} - -// Listen for messages from the main thread -self.addEventListener("message", async (event) => { - const data = JSON.parse(event.data); - if (data.type !== "embeddings") { - return; - } - - let extractor = await EmbeddingsPipeline.getInstance(); - - let output = await extractor(data.chunks, { - pooling: "mean", - normalize: true, - }); - - // Send the output back to the main thread - self.postMessage({ - embeddings: output.tolist(), - id: data.id, - type: "embeddings", - }); -});