fix: formatting
This commit is contained in:
parent
0a3c4b6bd4
commit
9efd0e128e
62 changed files with 22524 additions and 20508 deletions
|
|
@ -13,4 +13,4 @@ description: Standards for writing and maintaining Continue Docs
|
|||
- Include cross-references to related documentation
|
||||
- Reference other docs with relative paths
|
||||
- Keep paragraphs concise and scannable
|
||||
- Use code blocks with appropriate language tags
|
||||
- Use code blocks with appropriate language tags
|
||||
|
|
|
|||
|
|
@ -480,5 +480,5 @@ export {
|
|||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
pruneStringFromBottom,
|
||||
pruneStringFromTop
|
||||
pruneStringFromTop,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
/* eslint-disable max-lines-per-function */
|
||||
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
|
||||
import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
|
||||
import {
|
||||
getSystemMessageWithRules,
|
||||
shouldApplyRule,
|
||||
} from "./getSystemMessageWithRules";
|
||||
|
||||
describe("getSystemMessageWithRules", () => {
|
||||
const baseSystemMessage = "Base system message";
|
||||
|
|
@ -450,7 +453,8 @@ describe("getSystemMessageWithRules", () => {
|
|||
it("should include rules with alwaysApply: false when globs match", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
|
||||
content:
|
||||
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
|
|
@ -701,14 +705,18 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true when alwaysApply is true, regardless of file paths", () => {
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should use glob matching when alwaysApply is false", () => {
|
||||
// Should apply when globs match
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
|
||||
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Should not apply when globs don't match
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
|
||||
|
|
@ -716,7 +724,9 @@ describe("shouldApplyRule", () => {
|
|||
|
||||
it("should return false when alwaysApply is false and no globs specified", () => {
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
|
||||
expect(
|
||||
shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -724,7 +734,9 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true for rules without globs regardless of file paths", () => {
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for rules with globs when no file paths are provided", () => {
|
||||
|
|
@ -734,12 +746,16 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true for rules with globs when matching file paths are provided", () => {
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for rules with globs when no matching file paths are provided", () => {
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -760,19 +776,39 @@ describe("shouldApplyRule", () => {
|
|||
|
||||
it("should handle array of glob patterns", () => {
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle string glob patterns", () => {
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"]),
|
||||
).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return true if any file path matches when multiple paths provided", () => {
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithSpecificPattern, [
|
||||
"utils.js",
|
||||
"models.py",
|
||||
"config.json",
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithGlobs, [
|
||||
"utils.py",
|
||||
"Component.tsx",
|
||||
"script.rb",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -784,7 +820,7 @@ describe("shouldApplyRule", () => {
|
|||
globs: [],
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
|
||||
// Empty array should be treated as "no globs" (truthy check fails)
|
||||
expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
|
||||
});
|
||||
|
|
@ -796,7 +832,7 @@ describe("shouldApplyRule", () => {
|
|||
globs: undefined,
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
|
||||
expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
|
||||
});
|
||||
|
|
|
|||
6
core/vendor/modules/.package-lock.json
generated
vendored
6
core/vendor/modules/.package-lock.json
generated
vendored
|
|
@ -383,11 +383,7 @@
|
|||
"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"
|
||||
],
|
||||
"os": ["win32", "darwin", "linux"],
|
||||
"dependencies": {
|
||||
"onnxruntime-common": "~1.14.0"
|
||||
}
|
||||
|
|
|
|||
186
core/vendor/modules/@xenova/transformers/README.md
vendored
186
core/vendor/modules/@xenova/transformers/README.md
vendored
|
|
@ -1,5 +1,3 @@
|
|||
|
||||
|
||||
<p align="center">
|
||||
<br/>
|
||||
<picture>
|
||||
|
|
@ -28,23 +26,21 @@
|
|||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
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).
|
||||
- 📝 **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.
|
||||
|
||||
<table>
|
||||
|
|
@ -69,12 +65,12 @@ out = pipe('I love transformers!')
|
|||
<td>
|
||||
|
||||
```javascript
|
||||
import { pipeline } from '@xenova/transformers';
|
||||
import { pipeline } from "@xenova/transformers";
|
||||
|
||||
// Allocate a pipeline for sentiment-analysis
|
||||
let pipe = await pipeline('sentiment-analysis');
|
||||
let pipe = await pipeline("sentiment-analysis");
|
||||
|
||||
let out = await pipe('I love transformers!');
|
||||
let out = await pipe("I love transformers!");
|
||||
// [{'label': 'POSITIVE', 'score': 0.999817686}]
|
||||
```
|
||||
|
||||
|
|
@ -82,74 +78,72 @@ let out = await pipe('I love transformers!');
|
|||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
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');
|
||||
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
|
||||
<script type="module">
|
||||
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
|
||||
import { pipeline } from "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0";
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
## 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/) |
|
||||
| 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';
|
||||
import { env } from "@xenova/transformers";
|
||||
|
||||
// Specify a custom location for models (defaults to '/models/').
|
||||
env.localModelPath = '/path/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/';
|
||||
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).
|
||||
|
|
@ -163,6 +157,7 @@ python -m scripts.convert --quantize --model_id <model_name_or_path>
|
|||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
|
@ -181,7 +176,6 @@ bert-base-uncased/
|
|||
|
||||
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.
|
||||
|
|
@ -191,78 +185,72 @@ to open up a feature request [here](https://github.com/xenova/transformers.js/is
|
|||
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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
|
||||
| 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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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). | ❌ |
|
||||
| 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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
|
||||
|
||||
| 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)<br>[(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)<br>[(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)<br>[(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. | ❌ |
|
||||
|
||||
| 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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
|
||||
|
||||
| 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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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)<br>[(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. | ❌ |
|
||||
|
||||
|
||||
| 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
|
||||
|
||||
|
|
@ -274,7 +262,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
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. **[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.
|
||||
|
|
@ -294,7 +282,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
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. **[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.
|
||||
|
|
@ -347,5 +335,3 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
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.
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -6,45 +6,46 @@
|
|||
* 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';
|
||||
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'
|
||||
// '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');
|
||||
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;
|
||||
// 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;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
|
||||
/**
|
||||
* @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');
|
||||
|
|
@ -23,19 +22,16 @@
|
|||
* // ...
|
||||
* // }
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* @module configs
|
||||
*/
|
||||
|
||||
import {
|
||||
getModelJSON,
|
||||
} from './utils/hub.js';
|
||||
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.
|
||||
|
|
@ -43,8 +39,13 @@ import {
|
|||
* @returns {Promise<Array>} 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;
|
||||
let info = await getModelJSON(
|
||||
pretrained_model_name_or_path,
|
||||
"config.json",
|
||||
true,
|
||||
options,
|
||||
);
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -52,56 +53,60 @@ async function loadConfig(pretrained_model_name_or_path, options) {
|
|||
* [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
|
||||
*/
|
||||
export class PretrainedConfig {
|
||||
// NOTE: Typo in original
|
||||
// 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;
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
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<PretrainedConfig>} 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);
|
||||
}
|
||||
/**
|
||||
* 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<PretrainedConfig>} 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');
|
||||
* 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);
|
||||
}
|
||||
/** @type {PretrainedConfig.from_pretrained} */
|
||||
static async from_pretrained(...args) {
|
||||
return PretrainedConfig.from_pretrained(...args);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +1,37 @@
|
|||
/**
|
||||
* @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 fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { ONNX } from './backends/onnx.js';
|
||||
import { ONNX } from "./backends/onnx.js";
|
||||
const { env: onnx_env } = ONNX;
|
||||
|
||||
const VERSION = '2.14.0';
|
||||
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 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
|
||||
|
||||
|
|
@ -43,23 +43,22 @@ const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;
|
|||
|
||||
// Only used for environments with access to file system
|
||||
const DEFAULT_CACHE_DIR = RUNNING_LOCALLY
|
||||
? path.join(__dirname, '/.cache/')
|
||||
: null;
|
||||
? path.join(__dirname, "/.cache/")
|
||||
: null;
|
||||
|
||||
// Set local model path, based on available APIs
|
||||
const DEFAULT_LOCAL_MODEL_PATH = '/models/';
|
||||
const DEFAULT_LOCAL_MODEL_PATH = "/models/";
|
||||
const localModelPath = RUNNING_LOCALLY
|
||||
? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
|
||||
: DEFAULT_LOCAL_MODEL_PATH;
|
||||
? 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/`;
|
||||
|
||||
? 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.
|
||||
|
|
@ -83,44 +82,42 @@ onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
|
|||
* 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,
|
||||
/////////////////// Backends settings ///////////////////
|
||||
backends: {
|
||||
// onnxruntime-web/onnxruntime-node
|
||||
onnx: onnx_env,
|
||||
|
||||
// TensorFlow.js
|
||||
tfjs: {},
|
||||
},
|
||||
// TensorFlow.js
|
||||
tfjs: {},
|
||||
},
|
||||
|
||||
__dirname,
|
||||
version: VERSION,
|
||||
__dirname,
|
||||
version: VERSION,
|
||||
|
||||
/////////////////// Model settings ///////////////////
|
||||
allowRemoteModels: true,
|
||||
remoteHost: 'https://huggingface.co/',
|
||||
remotePathTemplate: '{model}/resolve/{revision}/',
|
||||
/////////////////// Model settings ///////////////////
|
||||
allowRemoteModels: true,
|
||||
remoteHost: "https://huggingface.co/",
|
||||
remotePathTemplate: "{model}/resolve/{revision}/",
|
||||
|
||||
allowLocalModels: true,
|
||||
localModelPath: localModelPath,
|
||||
useFS: FS_AVAILABLE,
|
||||
allowLocalModels: true,
|
||||
localModelPath: localModelPath,
|
||||
useFS: FS_AVAILABLE,
|
||||
|
||||
/////////////////// Cache settings ///////////////////
|
||||
useBrowserCache: WEB_CACHE_AVAILABLE,
|
||||
/////////////////// Cache settings ///////////////////
|
||||
useBrowserCache: WEB_CACHE_AVAILABLE,
|
||||
|
||||
useFSCache: FS_AVAILABLE,
|
||||
cacheDir: DEFAULT_CACHE_DIR,
|
||||
|
||||
useCustomCache: false,
|
||||
customCache: null,
|
||||
//////////////////////////////////////////////////////
|
||||
}
|
||||
useFSCache: FS_AVAILABLE,
|
||||
cacheDir: DEFAULT_CACHE_DIR,
|
||||
|
||||
useCustomCache: false,
|
||||
customCache: null,
|
||||
//////////////////////////////////////////////////////
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Object} obj
|
||||
* @private
|
||||
*/
|
||||
function isEmpty(obj) {
|
||||
return Object.keys(obj).length === 0;
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
|
||||
|
|
|
|||
7197
core/vendor/modules/@xenova/transformers/src/models.js
vendored
7197
core/vendor/modules/@xenova/transformers/src/models.js
vendored
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,18 +1,18 @@
|
|||
/**
|
||||
* @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 "./env.js";
|
||||
export * from "./pipelines.js";
|
||||
// export * from './models.js';
|
||||
// export * from './tokenizers.js';
|
||||
// export * from './processors.js';
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,10 +1,9 @@
|
|||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
|
|
@ -17,7 +16,7 @@
|
|||
* @private
|
||||
*/
|
||||
export function dispatchCallback(progress_callback, data) {
|
||||
if (progress_callback) progress_callback(data);
|
||||
if (progress_callback) progress_callback(data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -28,8 +27,10 @@ export function dispatchCallback(progress_callback, data) {
|
|||
* @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]));
|
||||
// https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
|
||||
return Object.fromEntries(
|
||||
Object.entries(data).map(([key, value]) => [value, key]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -39,29 +40,30 @@ export function reverseDictionary(data) {
|
|||
* @returns {string} The escaped string.
|
||||
*/
|
||||
export function escapeRegExp(string) {
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched 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 {
|
||||
export const Callable = /** @type {any} */ (
|
||||
class {
|
||||
/**
|
||||
* Creates a new instance of the Callable 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)
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -72,29 +74,29 @@ export const Callable = /** @type {any} */ (class {
|
|||
* @throws {Error} If the subclass does not implement the `_call` method.
|
||||
*/
|
||||
_call(...args) {
|
||||
throw Error('Must implement _call method in subclass')
|
||||
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';
|
||||
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'
|
||||
return Number.isInteger(x) || typeof x === "bigint";
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -103,7 +105,7 @@ export function isIntegralNumber(x) {
|
|||
* @returns {boolean} True if the value exists, false otherwise.
|
||||
*/
|
||||
export function exists(x) {
|
||||
return x !== undefined && x !== null;
|
||||
return x !== undefined && x !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -113,13 +115,13 @@ export function exists(x) {
|
|||
* @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;
|
||||
const dimensions = [];
|
||||
let current = arr;
|
||||
while (Array.isArray(current)) {
|
||||
dimensions.push(current.length);
|
||||
current = current[0];
|
||||
}
|
||||
return dimensions;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -131,15 +133,15 @@ export function calculateDimensions(arr) {
|
|||
* @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;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -149,7 +151,7 @@ export function pop(obj, key, defaultValue = undefined) {
|
|||
* @returns {Array} The merged array.
|
||||
*/
|
||||
export function mergeArrays(...arrs) {
|
||||
return Array.prototype.concat.apply([], arrs);
|
||||
return Array.prototype.concat.apply([], arrs);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -159,9 +161,9 @@ export function mergeArrays(...arrs) {
|
|||
* @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])));
|
||||
// Cartesian product of items
|
||||
// Adapted from https://stackoverflow.com/a/43053803
|
||||
return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e])));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -171,5 +173,5 @@ export function product(...a) {
|
|||
* @returns {number} The index offset.
|
||||
*/
|
||||
export function calculateReflectOffset(i, w) {
|
||||
return Math.abs((i + w) % (2 * w) - w);
|
||||
return Math.abs(((i + w) % (2 * w)) - w);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,415 +1,420 @@
|
|||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
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 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;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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<string, CharTrieNode>} 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;
|
||||
}
|
||||
/**
|
||||
* Create a new CharTrieNode.
|
||||
* @param {boolean} isLeaf Whether the node is a leaf node or not.
|
||||
* @param {Map<string, CharTrieNode>} 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());
|
||||
}
|
||||
/**
|
||||
* 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 }, () => []);
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const root = this.beginNodes[len][0];
|
||||
const prev = root.prev;
|
||||
if (prev === null) {
|
||||
return [];
|
||||
if (bestNode !== null) {
|
||||
rnode.prev = bestNode;
|
||||
rnode.backtraceScore = bestScore;
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
++pos;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
const results = [];
|
||||
const root = this.beginNodes[len][0];
|
||||
const prev = root.prev;
|
||||
if (prev === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @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));
|
||||
let node = prev.clone();
|
||||
while (node.prev !== null) {
|
||||
results.push(node.clone());
|
||||
const n = node.clone();
|
||||
node = n.prev.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
tokenIds() {
|
||||
const nodes = this.viterbi();
|
||||
return nodes.map(x => x.tokenId);
|
||||
}
|
||||
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;
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +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
|
||||
import * as ONNX_WEB from "onnxruntime-web";
|
||||
//# sourceMappingURL=onnx.d.ts.map
|
||||
|
|
|
|||
|
|
@ -3,23 +3,32 @@
|
|||
* [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<PretrainedConfig>} 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<PretrainedConfig>;
|
||||
/**
|
||||
* Create a new PreTrainedTokenizer instance.
|
||||
* @param {Object} configJSON The JSON of the config.
|
||||
*/
|
||||
constructor(configJSON: any);
|
||||
model_type: any;
|
||||
is_encoder_decoder: boolean;
|
||||
/**
|
||||
* 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<PretrainedConfig>} 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<PretrainedConfig>;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -28,16 +37,25 @@ export class PretrainedConfig {
|
|||
* 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<PretrainedConfig>} 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<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<PretrainedConfig>} 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<PretrainedConfig>;
|
||||
}
|
||||
export type PretrainedOptions = import('./utils/hub.js').PretrainedOptions;
|
||||
//# sourceMappingURL=configs.d.ts.map
|
||||
export type PretrainedOptions = import("./utils/hub.js").PretrainedOptions;
|
||||
//# sourceMappingURL=configs.d.ts.map
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
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;
|
||||
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;
|
||||
|
|
@ -25,4 +25,4 @@ declare const FS_AVAILABLE: boolean;
|
|||
declare const WEB_CACHE_AVAILABLE: boolean;
|
||||
declare const DEFAULT_CACHE_DIR: any;
|
||||
export {};
|
||||
//# sourceMappingURL=env.d.ts.map
|
||||
//# sourceMappingURL=env.d.ts.map
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -8,4 +8,4 @@ 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
|
||||
//# sourceMappingURL=transformers.d.ts.map
|
||||
|
|
|
|||
|
|
@ -4,7 +4,10 @@
|
|||
* @param {number} sampling_rate The sampling rate to use when decoding the audio.
|
||||
* @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
|
||||
*/
|
||||
export function read_audio(url: string | URL, sampling_rate: number): Promise<Float32Array>;
|
||||
export function read_audio(
|
||||
url: string | URL,
|
||||
sampling_rate: number,
|
||||
): Promise<Float32Array>;
|
||||
/**
|
||||
* Generates a Hanning window of length M.
|
||||
*
|
||||
|
|
@ -29,7 +32,16 @@ export function hanning(M: number): Float64Array;
|
|||
* @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[][];
|
||||
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.
|
||||
*
|
||||
|
|
@ -81,7 +93,29 @@ export function mel_filter_bank(num_frequency_bins: number, num_mel_filters: num
|
|||
* @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, }?: {
|
||||
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;
|
||||
|
|
@ -98,9 +132,10 @@ export function spectrogram(waveform: Float32Array | Float64Array, window: Float
|
|||
max_num_frames?: number;
|
||||
do_pad?: boolean;
|
||||
transpose?: boolean;
|
||||
}): {
|
||||
data: Float32Array;
|
||||
dims: number[];
|
||||
},
|
||||
): {
|
||||
data: Float32Array;
|
||||
dims: number[];
|
||||
};
|
||||
/**
|
||||
* Returns an array containing the specified window.
|
||||
|
|
@ -113,9 +148,17 @@ export function spectrogram(waveform: Float32Array | Float64Array, window: Float
|
|||
* @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, }?: {
|
||||
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
|
||||
},
|
||||
): Float64Array;
|
||||
//# sourceMappingURL=audio.d.ts.map
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ export function calculateReflectOffset(i: number, w: number): number;
|
|||
* @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
|
||||
*/
|
||||
export const Callable: new () => {
|
||||
(...args: any[]): any;
|
||||
_call(...args: any[]): any;
|
||||
(...args: any[]): any;
|
||||
_call(...args: any[]): any;
|
||||
};
|
||||
//# sourceMappingURL=core.d.ts.map
|
||||
//# sourceMappingURL=core.d.ts.map
|
||||
|
|
|
|||
|
|
@ -16,209 +16,215 @@
|
|||
* - 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;
|
||||
/**
|
||||
* 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<string, void, unknown>;
|
||||
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<string, void, unknown>;
|
||||
}
|
||||
/**
|
||||
* 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[];
|
||||
/**
|
||||
* 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<string, CharTrieNode>} 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<string, CharTrieNode>);
|
||||
isLeaf: boolean;
|
||||
children: Map<string, 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<string, CharTrieNode>} 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<string, CharTrieNode>);
|
||||
isLeaf: boolean;
|
||||
children: Map<string, CharTrieNode>;
|
||||
}
|
||||
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;
|
||||
/**
|
||||
* 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
|
||||
//# sourceMappingURL=data-structures.d.ts.map
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
declare const LogitsProcessorList_base: new () => {
|
||||
(...args: any[]): any;
|
||||
_call(...args: any[]): any;
|
||||
(...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
|
||||
|
|
@ -10,47 +10,47 @@ declare const LogitsProcessorList_base: new () => {
|
|||
* @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<any>;
|
||||
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<any>;
|
||||
}
|
||||
declare const LogitsProcessor_base: new () => {
|
||||
(...args: any[]): any;
|
||||
_call(...args: any[]): any;
|
||||
(...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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -58,42 +58,42 @@ export class LogitsProcessor extends LogitsProcessor_base {
|
|||
* @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;
|
||||
/**
|
||||
* 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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -101,21 +101,21 @@ export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
|
|||
* @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;
|
||||
/**
|
||||
* 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
|
||||
|
|
@ -124,53 +124,53 @@ export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
|
|||
* @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;
|
||||
/**
|
||||
* 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;
|
||||
});
|
||||
/**
|
||||
* 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;
|
||||
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;
|
||||
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.
|
||||
|
|
@ -178,38 +178,41 @@ export class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
|
|||
* @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<string, number[]>} Map of generated n-grams
|
||||
*/
|
||||
getNgrams(prevInputIds: number[]): Map<string, number[]>;
|
||||
/**
|
||||
* Generate n-grams from a sequence of token ids.
|
||||
* @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
|
||||
* @param {number[]} prevInputIds List of previous input ids
|
||||
* @returns {number[]} Map of generated n-grams
|
||||
*/
|
||||
getGeneratedNgrams(bannedNgrams: Map<string, number[]>, 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;
|
||||
/**
|
||||
* 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<string, number[]>} Map of generated n-grams
|
||||
*/
|
||||
getNgrams(prevInputIds: number[]): Map<string, number[]>;
|
||||
/**
|
||||
* Generate n-grams from a sequence of token ids.
|
||||
* @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
|
||||
* @param {number[]} prevInputIds List of previous input ids
|
||||
* @returns {number[]} Map of generated n-grams
|
||||
*/
|
||||
getGeneratedNgrams(
|
||||
bannedNgrams: Map<string, number[]>,
|
||||
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.
|
||||
|
|
@ -217,19 +220,19 @@ export class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
|
|||
* @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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -237,21 +240,21 @@ export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
|
|||
* @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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -259,40 +262,44 @@ export class MinLengthLogitsProcessor extends LogitsProcessor {
|
|||
* @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;
|
||||
/**
|
||||
* 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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -355,239 +362,241 @@ export class NoBadWordsLogitsProcessor extends LogitsProcessor {
|
|||
* Class that holds a configuration for a generation task.
|
||||
* @type {new (kwargs?: GenerationConfigType) => GenerationConfigType}
|
||||
*/
|
||||
export const GenerationConfig: new (kwargs?: GenerationConfigType) => GenerationConfigType;
|
||||
export const GenerationConfig: new (
|
||||
kwargs?: GenerationConfigType,
|
||||
) => GenerationConfigType;
|
||||
declare const Sampler_base: new () => {
|
||||
(...args: any[]): any;
|
||||
_call(...args: any[]): any;
|
||||
(...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;
|
||||
/**
|
||||
* 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 parameter 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;
|
||||
/**
|
||||
* 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 parameter 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';
|
||||
import { Tensor } from "./tensor.js";
|
||||
export {};
|
||||
//# sourceMappingURL=generation.d.ts.map
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@
|
|||
* @param {URL|string} urlOrPath The URL/path of the file to get.
|
||||
* @returns {Promise<FileResponse|Response>} 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<FileResponse | Response>;
|
||||
export function getFile(
|
||||
urlOrPath: URL | string,
|
||||
): Promise<FileResponse | Response>;
|
||||
/**
|
||||
*
|
||||
* Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
|
||||
|
|
@ -20,7 +22,12 @@ export function getFile(urlOrPath: URL | string): Promise<FileResponse | Respons
|
|||
* @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<any>;
|
||||
export function getModelFile(
|
||||
path_or_repo_id: string,
|
||||
filename: string,
|
||||
fatal?: boolean,
|
||||
options?: PretrainedOptions,
|
||||
): Promise<any>;
|
||||
/**
|
||||
* Fetches a JSON file from a given path and file name.
|
||||
*
|
||||
|
|
@ -31,43 +38,48 @@ export function getModelFile(path_or_repo_id: string, filename: string, fatal?:
|
|||
* @returns {Promise<Object>} 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<any>;
|
||||
export function getModelJSON(
|
||||
modelPath: string,
|
||||
fileName: string,
|
||||
fatal?: boolean,
|
||||
options?: PretrainedOptions,
|
||||
): Promise<any>;
|
||||
/**
|
||||
* 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;
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -84,71 +96,71 @@ export type PretrainedOptions = {
|
|||
* @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<any>;
|
||||
/**
|
||||
* 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<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
arrayBuffer(): Promise<ArrayBuffer>;
|
||||
/**
|
||||
* 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<Blob>} A Promise that resolves with a Blob containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
blob(): Promise<Blob>;
|
||||
/**
|
||||
* 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<string>} A Promise that resolves with a string containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
text(): Promise<string>;
|
||||
/**
|
||||
* 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<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
json(): Promise<any>;
|
||||
/**
|
||||
* 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<any>;
|
||||
/**
|
||||
* 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<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
arrayBuffer(): Promise<ArrayBuffer>;
|
||||
/**
|
||||
* 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<Blob>} A Promise that resolves with a Blob containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
blob(): Promise<Blob>;
|
||||
/**
|
||||
* 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<string>} A Promise that resolves with a string containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
text(): Promise<string>;
|
||||
/**
|
||||
* 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<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
*/
|
||||
json(): Promise<any>;
|
||||
}
|
||||
export {};
|
||||
//# sourceMappingURL=hub.d.ts.map
|
||||
//# sourceMappingURL=hub.d.ts.map
|
||||
|
|
|
|||
|
|
@ -1,111 +1,125 @@
|
|||
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<RawImage>;
|
||||
/**
|
||||
* 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<RawImage>} The image object.
|
||||
*/
|
||||
static fromURL(url: string | URL): Promise<RawImage>;
|
||||
/**
|
||||
* Helper method to create a new Image from a blob.
|
||||
* @param {Blob} blob The blob to read the image from.
|
||||
* @returns {Promise<RawImage>} The image object.
|
||||
*/
|
||||
static fromBlob(blob: Blob): Promise<RawImage>;
|
||||
/**
|
||||
* 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<RawImage>} `this` to support chaining.
|
||||
*/
|
||||
resize(width: number, height: number, { resample, }?: {
|
||||
resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
|
||||
}): Promise<RawImage>;
|
||||
pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
|
||||
crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
|
||||
center_crop(crop_width: any, crop_height: any): Promise<any>;
|
||||
toBlob(type?: string, quality?: number): Promise<any>;
|
||||
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<any>;
|
||||
toSharp(): any;
|
||||
/**
|
||||
* 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<RawImage>;
|
||||
/**
|
||||
* 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<RawImage>} The image object.
|
||||
*/
|
||||
static fromURL(url: string | URL): Promise<RawImage>;
|
||||
/**
|
||||
* Helper method to create a new Image from a blob.
|
||||
* @param {Blob} blob The blob to read the image from.
|
||||
* @returns {Promise<RawImage>} The image object.
|
||||
*/
|
||||
static fromBlob(blob: Blob): Promise<RawImage>;
|
||||
/**
|
||||
* 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<RawImage>} `this` to support chaining.
|
||||
*/
|
||||
resize(
|
||||
width: number,
|
||||
height: number,
|
||||
{
|
||||
resample,
|
||||
}?: {
|
||||
resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
|
||||
},
|
||||
): Promise<RawImage>;
|
||||
pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
|
||||
crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
|
||||
center_crop(crop_width: any, crop_height: any): Promise<any>;
|
||||
toBlob(type?: string, quality?: number): Promise<any>;
|
||||
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<any>;
|
||||
toSharp(): any;
|
||||
}
|
||||
//# sourceMappingURL=image.d.ts.map
|
||||
//# sourceMappingURL=image.d.ts.map
|
||||
|
|
|
|||
|
|
@ -14,7 +14,13 @@
|
|||
/**
|
||||
* @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;
|
||||
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
|
||||
|
|
@ -23,7 +29,11 @@ export function interpolate_data(input: TypedArray, [in_channels, in_height, in_
|
|||
* @param {number[]} axes
|
||||
* @returns {[T, number[]]} The transposed array and the new shape.
|
||||
*/
|
||||
export function transpose_data<T extends AnyTypedArray>(array: T, dims: number[], axes: number[]): [T, number[]];
|
||||
export function transpose_data<T extends AnyTypedArray>(
|
||||
array: T,
|
||||
dims: number[],
|
||||
axes: number[],
|
||||
): [T, number[]];
|
||||
/**
|
||||
* Compute the softmax of an array of numbers.
|
||||
* @template {TypedArray|number[]} T
|
||||
|
|
@ -51,7 +61,10 @@ export function dot(arr1: number[], arr2: number[]): number;
|
|||
* @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][];
|
||||
export function getTopItems(
|
||||
items: any[] | TypedArray,
|
||||
top_k?: number | null,
|
||||
): [number, any][];
|
||||
/**
|
||||
* Computes the cosine similarity between two arrays.
|
||||
*
|
||||
|
|
@ -94,15 +107,24 @@ export function medianFilter(data: AnyTypedArray, windowSize: number): any;
|
|||
*/
|
||||
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;
|
||||
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 TypedArray =
|
||||
| Int8Array
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Int16Array
|
||||
| Uint16Array
|
||||
| Int32Array
|
||||
| Uint32Array
|
||||
| Float32Array
|
||||
| Float64Array;
|
||||
export type BigTypedArray = BigInt64Array | BigUint64Array;
|
||||
export type AnyTypedArray = TypedArray | BigTypedArray;
|
||||
/**
|
||||
|
|
@ -113,140 +135,166 @@ export type AnyTypedArray = TypedArray | BigTypedArray;
|
|||
* 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;
|
||||
/**
|
||||
* @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
|
||||
|
|
@ -255,23 +303,23 @@ declare class P2FFT {
|
|||
* 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;
|
||||
/**
|
||||
* 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
|
||||
//# sourceMappingURL=maths.d.ts.map
|
||||
|
|
|
|||
|
|
@ -13,14 +13,22 @@ export function transpose(tensor: any, axes: any[]): Tensor;
|
|||
* @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;
|
||||
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;
|
||||
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.
|
||||
|
|
@ -43,7 +51,12 @@ export function stack(tensors: Tensor[], dim?: number): Tensor;
|
|||
* @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[];
|
||||
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.
|
||||
|
|
@ -51,7 +64,11 @@ export function std_mean(input: Tensor, dim?: number | null, correction?: number
|
|||
* @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;
|
||||
export function mean(
|
||||
input: Tensor,
|
||||
dim?: number | null,
|
||||
keepdim?: boolean,
|
||||
): Tensor;
|
||||
/**
|
||||
*
|
||||
* Measures similarity between two temporal sequences (e.g., input audio and output tokens
|
||||
|
|
@ -72,228 +89,236 @@ export function ones(size: number[]): 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<any, any, undefined>;
|
||||
/**
|
||||
* 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<any, any, undefined>;
|
||||
}
|
||||
/**
|
||||
* This creates a nested array of a given type and depth (see examples).
|
||||
*/
|
||||
export type NestArray<T, Depth extends number, Acc extends never[] = []> = Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
|
||||
export type NestArray<
|
||||
T,
|
||||
Depth extends number,
|
||||
Acc extends never[] = [],
|
||||
> = Acc["length"] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
|
||||
export type DataType = keyof typeof DataTypeMap;
|
||||
export type DataArray = import('./maths.js').AnyTypedArray | any[];
|
||||
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;
|
||||
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
|
||||
//# sourceMappingURL=tensor.d.ts.map
|
||||
|
|
|
|||
|
|
@ -10,4 +10,4 @@ If you are not redirected automatically, follow this [link to the changelog](htt
|
|||
|
||||
<head>
|
||||
<meta http-equiv="refresh" content="0;url=https://changelog.continue.dev" />
|
||||
</head>
|
||||
</head>
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
TODO testing scenarios
|
||||
|
||||
- Highlighting code and pressing CMD+L _before_ the GUI was first opened. The highlighted code should be included as chat input.
|
||||
- Highlighting code and pressing CMD+L _before_ the GUI was first opened. The highlighted code should be included as chat input.
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2 with ONNX weights
|
|||
## Usage (Transformers.js)
|
||||
|
||||
If you haven't already, you can install the [Transformers.js](https://huggingface.co/docs/transformers.js) JavaScript library from [NPM](https://www.npmjs.com/package/@xenova/transformers) using:
|
||||
|
||||
```bash
|
||||
npm i @xenova/transformers
|
||||
```
|
||||
|
|
@ -14,14 +15,17 @@ npm i @xenova/transformers
|
|||
You can then use the model to compute embeddings like this:
|
||||
|
||||
```js
|
||||
import { pipeline } from '@xenova/transformers';
|
||||
import { pipeline } from "@xenova/transformers";
|
||||
|
||||
// Create a feature-extraction pipeline
|
||||
const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
|
||||
const extractor = await pipeline(
|
||||
"feature-extraction",
|
||||
"Xenova/all-MiniLM-L6-v2",
|
||||
);
|
||||
|
||||
// Compute sentence embeddings
|
||||
const sentences = ['This is an example sentence', 'Each sentence is converted'];
|
||||
const output = await extractor(sentences, { pooling: 'mean', normalize: true });
|
||||
const sentences = ["This is an example sentence", "Each sentence is converted"];
|
||||
const output = await extractor(sentences, { pooling: "mean", normalize: true });
|
||||
console.log(output);
|
||||
// Tensor {
|
||||
// dims: [ 2, 384 ],
|
||||
|
|
@ -32,6 +36,7 @@ console.log(output);
|
|||
```
|
||||
|
||||
You can convert this Tensor to a nested JavaScript array using `.tolist()`:
|
||||
|
||||
```js
|
||||
console.log(output.tolist());
|
||||
// [
|
||||
|
|
@ -40,5 +45,4 @@ console.log(output.tolist());
|
|||
// ]
|
||||
```
|
||||
|
||||
|
||||
Note: Having a separate repo for ONNX weights is intended to be a temporary solution until WebML gains more traction. If you would like to make your models web-ready, we recommend converting to ONNX using [🤗 Optimum](https://huggingface.co/docs/optimum/index) and structuring your repo like this one (with ONNX weights located in a subfolder named `onnx`).
|
||||
Note: Having a separate repo for ONNX weights is intended to be a temporary solution until WebML gains more traction. If you would like to make your models web-ready, we recommend converting to ONNX using [🤗 Optimum](https://huggingface.co/docs/optimum/index) and structuring your repo like this one (with ONNX weights located in a subfolder named `onnx`).
|
||||
|
|
|
|||
|
|
@ -130,21 +130,13 @@
|
|||
"special_tokens": {
|
||||
"[CLS]": {
|
||||
"id": "[CLS]",
|
||||
"ids": [
|
||||
101
|
||||
],
|
||||
"tokens": [
|
||||
"[CLS]"
|
||||
]
|
||||
"ids": [101],
|
||||
"tokens": ["[CLS]"]
|
||||
},
|
||||
"[SEP]": {
|
||||
"id": "[SEP]",
|
||||
"ids": [
|
||||
102
|
||||
],
|
||||
"tokens": [
|
||||
"[SEP]"
|
||||
]
|
||||
"ids": [102],
|
||||
"tokens": ["[SEP]"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -30683,4 +30675,4 @@
|
|||
"##~": 30521
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ import {
|
|||
import { stripImages } from "core/util/messageContent";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
|
||||
import { ApplyManager } from "../apply";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
|
||||
|
|
|
|||
|
|
@ -45,12 +45,16 @@ class EditDecorationManager {
|
|||
const rangesToPrune: string[] = [];
|
||||
|
||||
for (const [key, existingRange] of this.activeRangesMap.entries()) {
|
||||
if (!this.rangesCoincide(mergedRange, existingRange)) {continue;}
|
||||
if (!this.rangesCoincide(mergedRange, existingRange)) {
|
||||
continue;
|
||||
}
|
||||
mergedRange = mergedRange.union(existingRange);
|
||||
rangesToPrune.push(key);
|
||||
}
|
||||
|
||||
for (const key of rangesToPrune) {this.activeRangesMap.delete(key);}
|
||||
for (const key of rangesToPrune) {
|
||||
this.activeRangesMap.delete(key);
|
||||
}
|
||||
this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange);
|
||||
}
|
||||
|
||||
|
|
@ -61,10 +65,14 @@ class EditDecorationManager {
|
|||
}
|
||||
this._lastEditor = editor;
|
||||
|
||||
for (const range of ranges) {this.mergeNewRange(range);}
|
||||
for (const range of ranges) {
|
||||
this.mergeNewRange(range);
|
||||
}
|
||||
|
||||
const activeRanges = Array.from(this.activeRangesMap.values());
|
||||
if (activeRanges.length === 0) {return;} // No ranges to highlight
|
||||
if (activeRanges.length === 0) {
|
||||
return;
|
||||
} // No ranges to highlight
|
||||
|
||||
// Update active ranges and apply decorations
|
||||
editor.setDecorations(this.decorationType, activeRanges);
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export function remarkTables() {
|
|||
//// header // newline // |:---|----:| // new line // table rows
|
||||
|
||||
// prevent modifying if no markdown tables are present
|
||||
if(!buffer.match(tableRegex)) {
|
||||
if (!buffer.match(tableRegex)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ const getSourceLabel = (source: RuleSource): string => {
|
|||
};
|
||||
|
||||
export function RulesPeekItem({ rule }: RulesPeekItemProps) {
|
||||
const isGlobal = rule.alwaysApply ?? (!rule.globs);
|
||||
const isGlobal = rule.alwaysApply ?? !rule.globs;
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
// Define maximum length for rule text display
|
||||
|
|
|
|||
|
|
@ -1,21 +1,22 @@
|
|||
# openapi-client
|
||||
|
||||
API for Continue IDE to fetch assistants and other related information.
|
||||
These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
|
||||
|
||||
This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
|
||||
|
||||
- API version: 1.0.0
|
||||
- Package version: 1.0.0
|
||||
- Generator version: 7.12.0
|
||||
- Build package: org.openapitools.codegen.languages.PythonClientCodegen
|
||||
For more information, please visit [https://continue.dev](https://continue.dev)
|
||||
For more information, please visit [https://continue.dev](https://continue.dev)
|
||||
|
||||
## Requirements.
|
||||
|
||||
Python 3.8+
|
||||
|
||||
## Installation & Usage
|
||||
|
||||
### pip install
|
||||
|
||||
If the python package is hosted on a repository, you can install directly using:
|
||||
|
|
@ -23,9 +24,11 @@ If the python package is hosted on a repository, you can install directly using:
|
|||
```sh
|
||||
pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git
|
||||
```
|
||||
|
||||
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`)
|
||||
|
||||
Then import the package:
|
||||
|
||||
```python
|
||||
import openapi_client
|
||||
```
|
||||
|
|
@ -37,9 +40,11 @@ Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
|
|||
```sh
|
||||
python setup.py install --user
|
||||
```
|
||||
|
||||
(or `sudo python setup.py install` to install the package for all users)
|
||||
|
||||
Then import the package:
|
||||
|
||||
```python
|
||||
import openapi_client
|
||||
```
|
||||
|
|
@ -96,32 +101,26 @@ with openapi_client.ApiClient(configuration) as api_client:
|
|||
|
||||
All URIs are relative to *https://api.continue.dev*
|
||||
|
||||
Class | Method | HTTP request | Description
|
||||
------------ | ------------- | ------------- | -------------
|
||||
*DefaultApi* | [**list_assistants**](docs/DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE
|
||||
|
||||
| Class | Method | HTTP request | Description |
|
||||
| ------------ | --------------------------------------------------------- | ---------------------------- | ----------------------- |
|
||||
| _DefaultApi_ | [**list_assistants**](docs/DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE |
|
||||
|
||||
## Documentation For Models
|
||||
|
||||
- [ListAssistants200ResponseInner](docs/ListAssistants200ResponseInner.md)
|
||||
- [ListAssistants200ResponseInnerConfigResult](docs/ListAssistants200ResponseInnerConfigResult.md)
|
||||
- [ListAssistants401Response](docs/ListAssistants401Response.md)
|
||||
- [ListAssistants404Response](docs/ListAssistants404Response.md)
|
||||
|
||||
- [ListAssistants200ResponseInner](docs/ListAssistants200ResponseInner.md)
|
||||
- [ListAssistants200ResponseInnerConfigResult](docs/ListAssistants200ResponseInnerConfigResult.md)
|
||||
- [ListAssistants401Response](docs/ListAssistants401Response.md)
|
||||
- [ListAssistants404Response](docs/ListAssistants404Response.md)
|
||||
|
||||
<a id="documentation-for-authorization"></a>
|
||||
## Documentation For Authorization
|
||||
|
||||
## Documentation For Authorization
|
||||
|
||||
Authentication schemes defined for the API:
|
||||
<a id="apiKeyAuth"></a>
|
||||
|
||||
### apiKeyAuth
|
||||
|
||||
- **Type**: Bearer authentication
|
||||
|
||||
|
||||
## Author
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@
|
|||
|
||||
All URIs are relative to *https://api.continue.dev*
|
||||
|
||||
Method | HTTP request | Description
|
||||
------------- | ------------- | -------------
|
||||
[**list_assistants**](DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE
|
||||
|
||||
| Method | HTTP request | Description |
|
||||
| ---------------------------------------------------- | ---------------------------- | ----------------------- |
|
||||
| [**list_assistants**](DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE |
|
||||
|
||||
# **list_assistants**
|
||||
|
||||
> List[ListAssistants200ResponseInner] list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id)
|
||||
|
||||
List assistants for IDE
|
||||
|
|
@ -18,10 +18,9 @@ icons, and other metadata needed by the IDE to display and use them.
|
|||
This endpoint performs a full refresh of the list of assistants, including unrolling
|
||||
configurations and resolving secrets.
|
||||
|
||||
|
||||
### Example
|
||||
|
||||
* Bearer Authentication (apiKeyAuth):
|
||||
- Bearer Authentication (apiKeyAuth):
|
||||
|
||||
```python
|
||||
import openapi_client
|
||||
|
|
@ -61,15 +60,12 @@ with openapi_client.ApiClient(configuration) as api_client:
|
|||
print("Exception when calling DefaultApi->list_assistants: %s\n" % e)
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------- | ------------- | ------------- | -------------
|
||||
**always_use_proxy** | **str**| Whether to always use the Continue-managed proxy for model requests | [optional]
|
||||
**organization_id** | **str**| ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional]
|
||||
| Name | Type | Description | Notes |
|
||||
| -------------------- | ------- | ------------------------------------------------------------------------------------------------- | ---------- |
|
||||
| **always_use_proxy** | **str** | Whether to always use the Continue-managed proxy for model requests | [optional] |
|
||||
| **organization_id** | **str** | ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional] |
|
||||
|
||||
### Return type
|
||||
|
||||
|
|
@ -81,16 +77,15 @@ Name | Type | Description | Notes
|
|||
|
||||
### HTTP request headers
|
||||
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/json
|
||||
- **Content-Type**: Not defined
|
||||
- **Accept**: application/json
|
||||
|
||||
### HTTP response details
|
||||
|
||||
| Status code | Description | Response headers |
|
||||
|-------------|-------------|------------------|
|
||||
**200** | Successfully retrieved assistants | - |
|
||||
**401** | Unauthorized - Authentication failed | - |
|
||||
**404** | User not found | - |
|
||||
| Status code | Description | Response headers |
|
||||
| ----------- | ------------------------------------ | ---------------- |
|
||||
| **200** | Successfully retrieved assistants | - |
|
||||
| **401** | Unauthorized - Authentication failed | - |
|
||||
| **404** | User not found | - |
|
||||
|
||||
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
# ListAssistants200ResponseInner
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | |
|
||||
**owner_slug** | **str** | Slug of the user or organization that owns the assistant |
|
||||
**package_slug** | **str** | Slug of the assistant package |
|
||||
**icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional]
|
||||
**on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional]
|
||||
**use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional]
|
||||
**raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional]
|
||||
| Name | Type | Description | Notes |
|
||||
| --------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------- |
|
||||
| **config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | |
|
||||
| **owner_slug** | **str** | Slug of the user or organization that owns the assistant |
|
||||
| **package_slug** | **str** | Slug of the assistant package |
|
||||
| **icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional] |
|
||||
| **on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional] |
|
||||
| **use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional] |
|
||||
| **raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional] |
|
||||
|
||||
## Example
|
||||
|
||||
|
|
@ -30,6 +29,5 @@ list_assistants200_response_inner_dict = list_assistants200_response_inner_insta
|
|||
# create an instance of ListAssistants200ResponseInner from a dict
|
||||
list_assistants200_response_inner_from_dict = ListAssistants200ResponseInner.from_dict(list_assistants200_response_inner_dict)
|
||||
```
|
||||
|
||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,12 @@
|
|||
# ListAssistants200ResponseInnerConfigResult
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**config** | **object** | The unrolled assistant configuration |
|
||||
**config_load_interrupted** | **bool** | Whether the configuration loading was interrupted |
|
||||
**errors** | **List[str]** | Any errors that occurred during configuration loading | [optional]
|
||||
| Name | Type | Description | Notes |
|
||||
| --------------------------- | ------------- | ----------------------------------------------------- | ---------- |
|
||||
| **config** | **object** | The unrolled assistant configuration |
|
||||
| **config_load_interrupted** | **bool** | Whether the configuration loading was interrupted |
|
||||
| **errors** | **List[str]** | Any errors that occurred during configuration loading | [optional] |
|
||||
|
||||
## Example
|
||||
|
||||
|
|
@ -26,6 +25,5 @@ list_assistants200_response_inner_config_result_dict = list_assistants200_respon
|
|||
# create an instance of ListAssistants200ResponseInnerConfigResult from a dict
|
||||
list_assistants200_response_inner_config_result_from_dict = ListAssistants200ResponseInnerConfigResult.from_dict(list_assistants200_response_inner_config_result_dict)
|
||||
```
|
||||
|
||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
# ListAssistants401Response
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**message** | **str** | | [optional]
|
||||
| Name | Type | Description | Notes |
|
||||
| ----------- | ------- | ----------- | ---------- |
|
||||
| **message** | **str** | | [optional] |
|
||||
|
||||
## Example
|
||||
|
||||
|
|
@ -24,6 +23,5 @@ list_assistants401_response_dict = list_assistants401_response_instance.to_dict(
|
|||
# create an instance of ListAssistants401Response from a dict
|
||||
list_assistants401_response_from_dict = ListAssistants401Response.from_dict(list_assistants401_response_dict)
|
||||
```
|
||||
|
||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
# ListAssistants404Response
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
**message** | **str** | | [optional]
|
||||
| Name | Type | Description | Notes |
|
||||
| ----------- | ------- | ----------- | ---------- |
|
||||
| **message** | **str** | | [optional] |
|
||||
|
||||
## Example
|
||||
|
||||
|
|
@ -24,6 +23,5 @@ list_assistants404_response_dict = list_assistants404_response_instance.to_dict(
|
|||
# create an instance of ListAssistants404Response from a dict
|
||||
list_assistants404_response_from_dict = ListAssistants404Response.from_dict(list_assistants404_response_dict)
|
||||
```
|
||||
|
||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,23 +3,27 @@
|
|||
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
|
||||
|
||||
Environment
|
||||
* Node.js
|
||||
* Webpack
|
||||
* Browserify
|
||||
|
||||
- Node.js
|
||||
- Webpack
|
||||
- Browserify
|
||||
|
||||
Language level
|
||||
* ES5 - you must have a Promises/A+ library installed
|
||||
* ES6
|
||||
|
||||
- ES5 - you must have a Promises/A+ library installed
|
||||
- ES6
|
||||
|
||||
Module system
|
||||
* CommonJS
|
||||
* ES6 module system
|
||||
|
||||
- CommonJS
|
||||
- ES6 module system
|
||||
|
||||
It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
|
||||
|
||||
### Building
|
||||
|
||||
To build and compile the typescript sources to javascript use:
|
||||
|
||||
```
|
||||
npm install
|
||||
npm run build
|
||||
|
|
|
|||
|
|
@ -2,119 +2,136 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
import * as runtime from '../runtime';
|
||||
import * as runtime from "../runtime";
|
||||
import type {
|
||||
ListAssistants200ResponseInner,
|
||||
ListAssistants401Response,
|
||||
ListAssistants404Response,
|
||||
} from '../models/index';
|
||||
} from "../models/index";
|
||||
import {
|
||||
ListAssistants200ResponseInnerFromJSON,
|
||||
ListAssistants200ResponseInnerToJSON,
|
||||
ListAssistants401ResponseFromJSON,
|
||||
ListAssistants401ResponseToJSON,
|
||||
ListAssistants404ResponseFromJSON,
|
||||
ListAssistants404ResponseToJSON,
|
||||
} from '../models/index';
|
||||
ListAssistants200ResponseInnerFromJSON,
|
||||
ListAssistants200ResponseInnerToJSON,
|
||||
ListAssistants401ResponseFromJSON,
|
||||
ListAssistants401ResponseToJSON,
|
||||
ListAssistants404ResponseFromJSON,
|
||||
ListAssistants404ResponseToJSON,
|
||||
} from "../models/index";
|
||||
|
||||
export interface ListAssistantsRequest {
|
||||
alwaysUseProxy?: ListAssistantsAlwaysUseProxyEnum;
|
||||
organizationId?: string;
|
||||
alwaysUseProxy?: ListAssistantsAlwaysUseProxyEnum;
|
||||
organizationId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* DefaultApi - interface
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @interface DefaultApiInterface
|
||||
*/
|
||||
export interface DefaultApiInterface {
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* @summary List assistants for IDE
|
||||
* @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests
|
||||
* @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned.
|
||||
* @param {*} [options] Override http request option.
|
||||
* @throws {RequiredError}
|
||||
* @memberof DefaultApiInterface
|
||||
*/
|
||||
listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Array<ListAssistants200ResponseInner>>>;
|
||||
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
listAssistants(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Array<ListAssistants200ResponseInner>>;
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* @summary List assistants for IDE
|
||||
* @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests
|
||||
* @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned.
|
||||
* @param {*} [options] Override http request option.
|
||||
* @throws {RequiredError}
|
||||
* @memberof DefaultApiInterface
|
||||
*/
|
||||
listAssistantsRaw(
|
||||
requestParameters: ListAssistantsRequest,
|
||||
initOverrides?: RequestInit | runtime.InitOverrideFunction,
|
||||
): Promise<runtime.ApiResponse<Array<ListAssistants200ResponseInner>>>;
|
||||
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
listAssistants(
|
||||
requestParameters: ListAssistantsRequest,
|
||||
initOverrides?: RequestInit | runtime.InitOverrideFunction,
|
||||
): Promise<Array<ListAssistants200ResponseInner>>;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
export class DefaultApi extends runtime.BaseAPI implements DefaultApiInterface {
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
async listAssistantsRaw(
|
||||
requestParameters: ListAssistantsRequest,
|
||||
initOverrides?: RequestInit | runtime.InitOverrideFunction,
|
||||
): Promise<runtime.ApiResponse<Array<ListAssistants200ResponseInner>>> {
|
||||
const queryParameters: any = {};
|
||||
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
async listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Array<ListAssistants200ResponseInner>>> {
|
||||
const queryParameters: any = {};
|
||||
|
||||
if (requestParameters['alwaysUseProxy'] != null) {
|
||||
queryParameters['alwaysUseProxy'] = requestParameters['alwaysUseProxy'];
|
||||
}
|
||||
|
||||
if (requestParameters['organizationId'] != null) {
|
||||
queryParameters['organizationId'] = requestParameters['organizationId'];
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
if (this.configuration && this.configuration.accessToken) {
|
||||
const token = this.configuration.accessToken;
|
||||
const tokenString = await token("apiKeyAuth", []);
|
||||
|
||||
if (tokenString) {
|
||||
headerParameters["Authorization"] = `Bearer ${tokenString}`;
|
||||
}
|
||||
}
|
||||
const response = await this.request({
|
||||
path: `/ide/list-assistants`,
|
||||
method: 'GET',
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
}, initOverrides);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(ListAssistants200ResponseInnerFromJSON));
|
||||
if (requestParameters["alwaysUseProxy"] != null) {
|
||||
queryParameters["alwaysUseProxy"] = requestParameters["alwaysUseProxy"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
async listAssistants(requestParameters: ListAssistantsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Array<ListAssistants200ResponseInner>> {
|
||||
const response = await this.listAssistantsRaw(requestParameters, initOverrides);
|
||||
return await response.value();
|
||||
if (requestParameters["organizationId"] != null) {
|
||||
queryParameters["organizationId"] = requestParameters["organizationId"];
|
||||
}
|
||||
|
||||
const headerParameters: runtime.HTTPHeaders = {};
|
||||
|
||||
if (this.configuration && this.configuration.accessToken) {
|
||||
const token = this.configuration.accessToken;
|
||||
const tokenString = await token("apiKeyAuth", []);
|
||||
|
||||
if (tokenString) {
|
||||
headerParameters["Authorization"] = `Bearer ${tokenString}`;
|
||||
}
|
||||
}
|
||||
const response = await this.request(
|
||||
{
|
||||
path: `/ide/list-assistants`,
|
||||
method: "GET",
|
||||
headers: headerParameters,
|
||||
query: queryParameters,
|
||||
},
|
||||
initOverrides,
|
||||
);
|
||||
|
||||
return new runtime.JSONApiResponse(response, (jsonValue) =>
|
||||
jsonValue.map(ListAssistants200ResponseInnerFromJSON),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets.
|
||||
* List assistants for IDE
|
||||
*/
|
||||
async listAssistants(
|
||||
requestParameters: ListAssistantsRequest = {},
|
||||
initOverrides?: RequestInit | runtime.InitOverrideFunction,
|
||||
): Promise<Array<ListAssistants200ResponseInner>> {
|
||||
const response = await this.listAssistantsRaw(
|
||||
requestParameters,
|
||||
initOverrides,
|
||||
);
|
||||
return await response.value();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @export
|
||||
*/
|
||||
export const ListAssistantsAlwaysUseProxyEnum = {
|
||||
TRUE: 'true',
|
||||
FALSE: 'false'
|
||||
TRUE: "true",
|
||||
FALSE: "false",
|
||||
} as const;
|
||||
export type ListAssistantsAlwaysUseProxyEnum = typeof ListAssistantsAlwaysUseProxyEnum[keyof typeof ListAssistantsAlwaysUseProxyEnum];
|
||||
export type ListAssistantsAlwaysUseProxyEnum =
|
||||
(typeof ListAssistantsAlwaysUseProxyEnum)[keyof typeof ListAssistantsAlwaysUseProxyEnum];
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './DefaultApi';
|
||||
export * from "./DefaultApi";
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './runtime';
|
||||
export * from './apis/index';
|
||||
export * from './models/index';
|
||||
export * from "./runtime";
|
||||
export * from "./apis/index";
|
||||
export * from "./models/index";
|
||||
|
|
|
|||
|
|
@ -2,123 +2,140 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { mapValues } from '../runtime';
|
||||
import type { ListAssistants200ResponseInnerConfigResult } from './ListAssistants200ResponseInnerConfigResult';
|
||||
import { mapValues } from "../runtime";
|
||||
import type { ListAssistants200ResponseInnerConfigResult } from "./ListAssistants200ResponseInnerConfigResult";
|
||||
import {
|
||||
ListAssistants200ResponseInnerConfigResultFromJSON,
|
||||
ListAssistants200ResponseInnerConfigResultFromJSONTyped,
|
||||
ListAssistants200ResponseInnerConfigResultToJSON,
|
||||
ListAssistants200ResponseInnerConfigResultToJSONTyped,
|
||||
} from './ListAssistants200ResponseInnerConfigResult';
|
||||
ListAssistants200ResponseInnerConfigResultFromJSON,
|
||||
ListAssistants200ResponseInnerConfigResultFromJSONTyped,
|
||||
ListAssistants200ResponseInnerConfigResultToJSON,
|
||||
ListAssistants200ResponseInnerConfigResultToJSONTyped,
|
||||
} from "./ListAssistants200ResponseInnerConfigResult";
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @interface ListAssistants200ResponseInner
|
||||
*/
|
||||
export interface ListAssistants200ResponseInner {
|
||||
/**
|
||||
*
|
||||
* @type {ListAssistants200ResponseInnerConfigResult}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
configResult: ListAssistants200ResponseInnerConfigResult;
|
||||
/**
|
||||
* Slug of the user or organization that owns the assistant
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
ownerSlug: string;
|
||||
/**
|
||||
* Slug of the assistant package
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
packageSlug: string;
|
||||
/**
|
||||
* Pre-signed URL for the assistant's icon
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
iconUrl?: string | null;
|
||||
/**
|
||||
* URL of the on-premises proxy if the organization uses one
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
onPremProxyUrl?: string | null;
|
||||
/**
|
||||
* Whether the organization uses an on-premises proxy
|
||||
* @type {boolean}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
useOnPremProxy?: boolean | null;
|
||||
/**
|
||||
* Raw YAML configuration of the assistant
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
rawYaml?: string;
|
||||
/**
|
||||
*
|
||||
* @type {ListAssistants200ResponseInnerConfigResult}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
configResult: ListAssistants200ResponseInnerConfigResult;
|
||||
/**
|
||||
* Slug of the user or organization that owns the assistant
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
ownerSlug: string;
|
||||
/**
|
||||
* Slug of the assistant package
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
packageSlug: string;
|
||||
/**
|
||||
* Pre-signed URL for the assistant's icon
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
iconUrl?: string | null;
|
||||
/**
|
||||
* URL of the on-premises proxy if the organization uses one
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
onPremProxyUrl?: string | null;
|
||||
/**
|
||||
* Whether the organization uses an on-premises proxy
|
||||
* @type {boolean}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
useOnPremProxy?: boolean | null;
|
||||
/**
|
||||
* Raw YAML configuration of the assistant
|
||||
* @type {string}
|
||||
* @memberof ListAssistants200ResponseInner
|
||||
*/
|
||||
rawYaml?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given object implements the ListAssistants200ResponseInner interface.
|
||||
*/
|
||||
export function instanceOfListAssistants200ResponseInner(value: object): value is ListAssistants200ResponseInner {
|
||||
if (!('configResult' in value) || value['configResult'] === undefined) return false;
|
||||
if (!('ownerSlug' in value) || value['ownerSlug'] === undefined) return false;
|
||||
if (!('packageSlug' in value) || value['packageSlug'] === undefined) return false;
|
||||
return true;
|
||||
export function instanceOfListAssistants200ResponseInner(
|
||||
value: object,
|
||||
): value is ListAssistants200ResponseInner {
|
||||
if (!("configResult" in value) || value["configResult"] === undefined)
|
||||
return false;
|
||||
if (!("ownerSlug" in value) || value["ownerSlug"] === undefined) return false;
|
||||
if (!("packageSlug" in value) || value["packageSlug"] === undefined)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerFromJSON(json: any): ListAssistants200ResponseInner {
|
||||
return ListAssistants200ResponseInnerFromJSONTyped(json, false);
|
||||
export function ListAssistants200ResponseInnerFromJSON(
|
||||
json: any,
|
||||
): ListAssistants200ResponseInner {
|
||||
return ListAssistants200ResponseInnerFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInner {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'configResult': ListAssistants200ResponseInnerConfigResultFromJSON(json['configResult']),
|
||||
'ownerSlug': json['ownerSlug'],
|
||||
'packageSlug': json['packageSlug'],
|
||||
'iconUrl': json['iconUrl'] == null ? undefined : json['iconUrl'],
|
||||
'onPremProxyUrl': json['onPremProxyUrl'] == null ? undefined : json['onPremProxyUrl'],
|
||||
'useOnPremProxy': json['useOnPremProxy'] == null ? undefined : json['useOnPremProxy'],
|
||||
'rawYaml': json['rawYaml'] == null ? undefined : json['rawYaml'],
|
||||
};
|
||||
export function ListAssistants200ResponseInnerFromJSONTyped(
|
||||
json: any,
|
||||
ignoreDiscriminator: boolean,
|
||||
): ListAssistants200ResponseInner {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
configResult: ListAssistants200ResponseInnerConfigResultFromJSON(
|
||||
json["configResult"],
|
||||
),
|
||||
ownerSlug: json["ownerSlug"],
|
||||
packageSlug: json["packageSlug"],
|
||||
iconUrl: json["iconUrl"] == null ? undefined : json["iconUrl"],
|
||||
onPremProxyUrl:
|
||||
json["onPremProxyUrl"] == null ? undefined : json["onPremProxyUrl"],
|
||||
useOnPremProxy:
|
||||
json["useOnPremProxy"] == null ? undefined : json["useOnPremProxy"],
|
||||
rawYaml: json["rawYaml"] == null ? undefined : json["rawYaml"],
|
||||
};
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerToJSON(json: any): ListAssistants200ResponseInner {
|
||||
return ListAssistants200ResponseInnerToJSONTyped(json, false);
|
||||
export function ListAssistants200ResponseInnerToJSON(
|
||||
json: any,
|
||||
): ListAssistants200ResponseInner {
|
||||
return ListAssistants200ResponseInnerToJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerToJSONTyped(value?: ListAssistants200ResponseInner | null, ignoreDiscriminator: boolean = false): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
export function ListAssistants200ResponseInnerToJSONTyped(
|
||||
value?: ListAssistants200ResponseInner | null,
|
||||
ignoreDiscriminator: boolean = false,
|
||||
): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
'configResult': ListAssistants200ResponseInnerConfigResultToJSON(value['configResult']),
|
||||
'ownerSlug': value['ownerSlug'],
|
||||
'packageSlug': value['packageSlug'],
|
||||
'iconUrl': value['iconUrl'],
|
||||
'onPremProxyUrl': value['onPremProxyUrl'],
|
||||
'useOnPremProxy': value['useOnPremProxy'],
|
||||
'rawYaml': value['rawYaml'],
|
||||
};
|
||||
return {
|
||||
configResult: ListAssistants200ResponseInnerConfigResultToJSON(
|
||||
value["configResult"],
|
||||
),
|
||||
ownerSlug: value["ownerSlug"],
|
||||
packageSlug: value["packageSlug"],
|
||||
iconUrl: value["iconUrl"],
|
||||
onPremProxyUrl: value["onPremProxyUrl"],
|
||||
useOnPremProxy: value["useOnPremProxy"],
|
||||
rawYaml: value["rawYaml"],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,82 +2,95 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { mapValues } from '../runtime';
|
||||
import { mapValues } from "../runtime";
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @interface ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
export interface ListAssistants200ResponseInnerConfigResult {
|
||||
/**
|
||||
* The unrolled assistant configuration
|
||||
* @type {object}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
config: object | null;
|
||||
/**
|
||||
* Whether the configuration loading was interrupted
|
||||
* @type {boolean}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
configLoadInterrupted: boolean;
|
||||
/**
|
||||
* Any errors that occurred during configuration loading
|
||||
* @type {Array<string>}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
errors?: Array<string> | null;
|
||||
/**
|
||||
* The unrolled assistant configuration
|
||||
* @type {object}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
config: object | null;
|
||||
/**
|
||||
* Whether the configuration loading was interrupted
|
||||
* @type {boolean}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
configLoadInterrupted: boolean;
|
||||
/**
|
||||
* Any errors that occurred during configuration loading
|
||||
* @type {Array<string>}
|
||||
* @memberof ListAssistants200ResponseInnerConfigResult
|
||||
*/
|
||||
errors?: Array<string> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given object implements the ListAssistants200ResponseInnerConfigResult interface.
|
||||
*/
|
||||
export function instanceOfListAssistants200ResponseInnerConfigResult(value: object): value is ListAssistants200ResponseInnerConfigResult {
|
||||
if (!('config' in value) || value['config'] === undefined) return false;
|
||||
if (!('configLoadInterrupted' in value) || value['configLoadInterrupted'] === undefined) return false;
|
||||
return true;
|
||||
export function instanceOfListAssistants200ResponseInnerConfigResult(
|
||||
value: object,
|
||||
): value is ListAssistants200ResponseInnerConfigResult {
|
||||
if (!("config" in value) || value["config"] === undefined) return false;
|
||||
if (
|
||||
!("configLoadInterrupted" in value) ||
|
||||
value["configLoadInterrupted"] === undefined
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerConfigResultFromJSON(json: any): ListAssistants200ResponseInnerConfigResult {
|
||||
return ListAssistants200ResponseInnerConfigResultFromJSONTyped(json, false);
|
||||
export function ListAssistants200ResponseInnerConfigResultFromJSON(
|
||||
json: any,
|
||||
): ListAssistants200ResponseInnerConfigResult {
|
||||
return ListAssistants200ResponseInnerConfigResultFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerConfigResultFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInnerConfigResult {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'config': json['config'],
|
||||
'configLoadInterrupted': json['configLoadInterrupted'],
|
||||
'errors': json['errors'] == null ? undefined : json['errors'],
|
||||
};
|
||||
export function ListAssistants200ResponseInnerConfigResultFromJSONTyped(
|
||||
json: any,
|
||||
ignoreDiscriminator: boolean,
|
||||
): ListAssistants200ResponseInnerConfigResult {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
config: json["config"],
|
||||
configLoadInterrupted: json["configLoadInterrupted"],
|
||||
errors: json["errors"] == null ? undefined : json["errors"],
|
||||
};
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerConfigResultToJSON(json: any): ListAssistants200ResponseInnerConfigResult {
|
||||
return ListAssistants200ResponseInnerConfigResultToJSONTyped(json, false);
|
||||
export function ListAssistants200ResponseInnerConfigResultToJSON(
|
||||
json: any,
|
||||
): ListAssistants200ResponseInnerConfigResult {
|
||||
return ListAssistants200ResponseInnerConfigResultToJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants200ResponseInnerConfigResultToJSONTyped(value?: ListAssistants200ResponseInnerConfigResult | null, ignoreDiscriminator: boolean = false): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
export function ListAssistants200ResponseInnerConfigResultToJSONTyped(
|
||||
value?: ListAssistants200ResponseInnerConfigResult | null,
|
||||
ignoreDiscriminator: boolean = false,
|
||||
): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
'config': value['config'],
|
||||
'configLoadInterrupted': value['configLoadInterrupted'],
|
||||
'errors': value['errors'],
|
||||
};
|
||||
return {
|
||||
config: value["config"],
|
||||
configLoadInterrupted: value["configLoadInterrupted"],
|
||||
errors: value["errors"],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,64 +2,73 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { mapValues } from '../runtime';
|
||||
import { mapValues } from "../runtime";
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @interface ListAssistants401Response
|
||||
*/
|
||||
export interface ListAssistants401Response {
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ListAssistants401Response
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ListAssistants401Response
|
||||
*/
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given object implements the ListAssistants401Response interface.
|
||||
*/
|
||||
export function instanceOfListAssistants401Response(value: object): value is ListAssistants401Response {
|
||||
return true;
|
||||
export function instanceOfListAssistants401Response(
|
||||
value: object,
|
||||
): value is ListAssistants401Response {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function ListAssistants401ResponseFromJSON(json: any): ListAssistants401Response {
|
||||
return ListAssistants401ResponseFromJSONTyped(json, false);
|
||||
export function ListAssistants401ResponseFromJSON(
|
||||
json: any,
|
||||
): ListAssistants401Response {
|
||||
return ListAssistants401ResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants401ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants401Response {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'message': json['message'] == null ? undefined : json['message'],
|
||||
};
|
||||
export function ListAssistants401ResponseFromJSONTyped(
|
||||
json: any,
|
||||
ignoreDiscriminator: boolean,
|
||||
): ListAssistants401Response {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
message: json["message"] == null ? undefined : json["message"],
|
||||
};
|
||||
}
|
||||
|
||||
export function ListAssistants401ResponseToJSON(json: any): ListAssistants401Response {
|
||||
return ListAssistants401ResponseToJSONTyped(json, false);
|
||||
export function ListAssistants401ResponseToJSON(
|
||||
json: any,
|
||||
): ListAssistants401Response {
|
||||
return ListAssistants401ResponseToJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants401ResponseToJSONTyped(value?: ListAssistants401Response | null, ignoreDiscriminator: boolean = false): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
export function ListAssistants401ResponseToJSONTyped(
|
||||
value?: ListAssistants401Response | null,
|
||||
ignoreDiscriminator: boolean = false,
|
||||
): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
'message': value['message'],
|
||||
};
|
||||
return {
|
||||
message: value["message"],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,64 +2,73 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
import { mapValues } from '../runtime';
|
||||
import { mapValues } from "../runtime";
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @interface ListAssistants404Response
|
||||
*/
|
||||
export interface ListAssistants404Response {
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ListAssistants404Response
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ListAssistants404Response
|
||||
*/
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given object implements the ListAssistants404Response interface.
|
||||
*/
|
||||
export function instanceOfListAssistants404Response(value: object): value is ListAssistants404Response {
|
||||
return true;
|
||||
export function instanceOfListAssistants404Response(
|
||||
value: object,
|
||||
): value is ListAssistants404Response {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function ListAssistants404ResponseFromJSON(json: any): ListAssistants404Response {
|
||||
return ListAssistants404ResponseFromJSONTyped(json, false);
|
||||
export function ListAssistants404ResponseFromJSON(
|
||||
json: any,
|
||||
): ListAssistants404Response {
|
||||
return ListAssistants404ResponseFromJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants404ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants404Response {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
|
||||
'message': json['message'] == null ? undefined : json['message'],
|
||||
};
|
||||
export function ListAssistants404ResponseFromJSONTyped(
|
||||
json: any,
|
||||
ignoreDiscriminator: boolean,
|
||||
): ListAssistants404Response {
|
||||
if (json == null) {
|
||||
return json;
|
||||
}
|
||||
return {
|
||||
message: json["message"] == null ? undefined : json["message"],
|
||||
};
|
||||
}
|
||||
|
||||
export function ListAssistants404ResponseToJSON(json: any): ListAssistants404Response {
|
||||
return ListAssistants404ResponseToJSONTyped(json, false);
|
||||
export function ListAssistants404ResponseToJSON(
|
||||
json: any,
|
||||
): ListAssistants404Response {
|
||||
return ListAssistants404ResponseToJSONTyped(json, false);
|
||||
}
|
||||
|
||||
export function ListAssistants404ResponseToJSONTyped(value?: ListAssistants404Response | null, ignoreDiscriminator: boolean = false): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
export function ListAssistants404ResponseToJSONTyped(
|
||||
value?: ListAssistants404Response | null,
|
||||
ignoreDiscriminator: boolean = false,
|
||||
): any {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
'message': value['message'],
|
||||
};
|
||||
return {
|
||||
message: value["message"],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export * from './ListAssistants200ResponseInner';
|
||||
export * from './ListAssistants200ResponseInnerConfigResult';
|
||||
export * from './ListAssistants401Response';
|
||||
export * from './ListAssistants404Response';
|
||||
export * from "./ListAssistants200ResponseInner";
|
||||
export * from "./ListAssistants200ResponseInnerConfigResult";
|
||||
export * from "./ListAssistants401Response";
|
||||
export * from "./ListAssistants404Response";
|
||||
|
|
|
|||
|
|
@ -2,86 +2,97 @@
|
|||
/* eslint-disable */
|
||||
/**
|
||||
* Continue Hub IDE API
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
* API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export const BASE_PATH = "https://api.continue.dev".replace(/\/+$/, "");
|
||||
|
||||
export interface ConfigurationParameters {
|
||||
basePath?: string; // override base path
|
||||
fetchApi?: FetchAPI; // override for fetch implementation
|
||||
middleware?: Middleware[]; // middleware to apply before/after fetch requests
|
||||
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
|
||||
username?: string; // parameter for basic security
|
||||
password?: string; // parameter for basic security
|
||||
apiKey?: string | Promise<string> | ((name: string) => string | Promise<string>); // parameter for apiKey security
|
||||
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
|
||||
headers?: HTTPHeaders; //header params we want to use on every request
|
||||
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
|
||||
basePath?: string; // override base path
|
||||
fetchApi?: FetchAPI; // override for fetch implementation
|
||||
middleware?: Middleware[]; // middleware to apply before/after fetch requests
|
||||
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
|
||||
username?: string; // parameter for basic security
|
||||
password?: string; // parameter for basic security
|
||||
apiKey?:
|
||||
| string
|
||||
| Promise<string>
|
||||
| ((name: string) => string | Promise<string>); // parameter for apiKey security
|
||||
accessToken?:
|
||||
| string
|
||||
| Promise<string>
|
||||
| ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
|
||||
headers?: HTTPHeaders; //header params we want to use on every request
|
||||
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
constructor(private configuration: ConfigurationParameters = {}) {}
|
||||
constructor(private configuration: ConfigurationParameters = {}) {}
|
||||
|
||||
set config(configuration: Configuration) {
|
||||
this.configuration = configuration;
|
||||
}
|
||||
set config(configuration: Configuration) {
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
get basePath(): string {
|
||||
return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
|
||||
}
|
||||
get basePath(): string {
|
||||
return this.configuration.basePath != null
|
||||
? this.configuration.basePath
|
||||
: BASE_PATH;
|
||||
}
|
||||
|
||||
get fetchApi(): FetchAPI | undefined {
|
||||
return this.configuration.fetchApi;
|
||||
}
|
||||
get fetchApi(): FetchAPI | undefined {
|
||||
return this.configuration.fetchApi;
|
||||
}
|
||||
|
||||
get middleware(): Middleware[] {
|
||||
return this.configuration.middleware || [];
|
||||
}
|
||||
get middleware(): Middleware[] {
|
||||
return this.configuration.middleware || [];
|
||||
}
|
||||
|
||||
get queryParamsStringify(): (params: HTTPQuery) => string {
|
||||
return this.configuration.queryParamsStringify || querystring;
|
||||
}
|
||||
get queryParamsStringify(): (params: HTTPQuery) => string {
|
||||
return this.configuration.queryParamsStringify || querystring;
|
||||
}
|
||||
|
||||
get username(): string | undefined {
|
||||
return this.configuration.username;
|
||||
}
|
||||
get username(): string | undefined {
|
||||
return this.configuration.username;
|
||||
}
|
||||
|
||||
get password(): string | undefined {
|
||||
return this.configuration.password;
|
||||
}
|
||||
get password(): string | undefined {
|
||||
return this.configuration.password;
|
||||
}
|
||||
|
||||
get apiKey(): ((name: string) => string | Promise<string>) | undefined {
|
||||
const apiKey = this.configuration.apiKey;
|
||||
if (apiKey) {
|
||||
return typeof apiKey === 'function' ? apiKey : () => apiKey;
|
||||
}
|
||||
return undefined;
|
||||
get apiKey(): ((name: string) => string | Promise<string>) | undefined {
|
||||
const apiKey = this.configuration.apiKey;
|
||||
if (apiKey) {
|
||||
return typeof apiKey === "function" ? apiKey : () => apiKey;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get accessToken(): ((name?: string, scopes?: string[]) => string | Promise<string>) | undefined {
|
||||
const accessToken = this.configuration.accessToken;
|
||||
if (accessToken) {
|
||||
return typeof accessToken === 'function' ? accessToken : async () => accessToken;
|
||||
}
|
||||
return undefined;
|
||||
get accessToken():
|
||||
| ((name?: string, scopes?: string[]) => string | Promise<string>)
|
||||
| undefined {
|
||||
const accessToken = this.configuration.accessToken;
|
||||
if (accessToken) {
|
||||
return typeof accessToken === "function"
|
||||
? accessToken
|
||||
: async () => accessToken;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get headers(): HTTPHeaders | undefined {
|
||||
return this.configuration.headers;
|
||||
}
|
||||
get headers(): HTTPHeaders | undefined {
|
||||
return this.configuration.headers;
|
||||
}
|
||||
|
||||
get credentials(): RequestCredentials | undefined {
|
||||
return this.configuration.credentials;
|
||||
}
|
||||
get credentials(): RequestCredentials | undefined {
|
||||
return this.configuration.credentials;
|
||||
}
|
||||
}
|
||||
|
||||
export const DefaultConfig = new Configuration();
|
||||
|
|
@ -90,342 +101,429 @@ export const DefaultConfig = new Configuration();
|
|||
* This is the base class for all generated API classes.
|
||||
*/
|
||||
export class BaseAPI {
|
||||
private static readonly jsonRegex = new RegExp(
|
||||
"^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$",
|
||||
"i",
|
||||
);
|
||||
private middleware: Middleware[];
|
||||
|
||||
private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
|
||||
private middleware: Middleware[];
|
||||
constructor(protected configuration = DefaultConfig) {
|
||||
this.middleware = configuration.middleware;
|
||||
}
|
||||
|
||||
constructor(protected configuration = DefaultConfig) {
|
||||
this.middleware = configuration.middleware;
|
||||
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
|
||||
const next = this.clone<T>();
|
||||
next.middleware = next.middleware.concat(...middlewares);
|
||||
return next;
|
||||
}
|
||||
|
||||
withPreMiddleware<T extends BaseAPI>(
|
||||
this: T,
|
||||
...preMiddlewares: Array<Middleware["pre"]>
|
||||
) {
|
||||
const middlewares = preMiddlewares.map((pre) => ({ pre }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
|
||||
withPostMiddleware<T extends BaseAPI>(
|
||||
this: T,
|
||||
...postMiddlewares: Array<Middleware["post"]>
|
||||
) {
|
||||
const middlewares = postMiddlewares.map((post) => ({ post }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
protected isJsonMime(mime: string | null | undefined): boolean {
|
||||
if (!mime) {
|
||||
return false;
|
||||
}
|
||||
return BaseAPI.jsonRegex.test(mime);
|
||||
}
|
||||
|
||||
protected async request(
|
||||
context: RequestOpts,
|
||||
initOverrides?: RequestInit | InitOverrideFunction,
|
||||
): Promise<Response> {
|
||||
const { url, init } = await this.createFetchParams(context, initOverrides);
|
||||
const response = await this.fetchApi(url, init);
|
||||
if (response && response.status >= 200 && response.status < 300) {
|
||||
return response;
|
||||
}
|
||||
throw new ResponseError(response, "Response returned an error code");
|
||||
}
|
||||
|
||||
private async createFetchParams(
|
||||
context: RequestOpts,
|
||||
initOverrides?: RequestInit | InitOverrideFunction,
|
||||
) {
|
||||
let url = this.configuration.basePath + context.path;
|
||||
if (
|
||||
context.query !== undefined &&
|
||||
Object.keys(context.query).length !== 0
|
||||
) {
|
||||
// only add the querystring to the URL if there are query parameters.
|
||||
// this is done to avoid urls ending with a "?" character which buggy webservers
|
||||
// do not handle correctly sometimes.
|
||||
url += "?" + this.configuration.queryParamsStringify(context.query);
|
||||
}
|
||||
|
||||
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
|
||||
const next = this.clone<T>();
|
||||
next.middleware = next.middleware.concat(...middlewares);
|
||||
return next;
|
||||
const headers = Object.assign(
|
||||
{},
|
||||
this.configuration.headers,
|
||||
context.headers,
|
||||
);
|
||||
Object.keys(headers).forEach((key) =>
|
||||
headers[key] === undefined ? delete headers[key] : {},
|
||||
);
|
||||
|
||||
const initOverrideFn =
|
||||
typeof initOverrides === "function"
|
||||
? initOverrides
|
||||
: async () => initOverrides;
|
||||
|
||||
const initParams = {
|
||||
method: context.method,
|
||||
headers,
|
||||
body: context.body,
|
||||
credentials: this.configuration.credentials,
|
||||
};
|
||||
|
||||
const overriddenInit: RequestInit = {
|
||||
...initParams,
|
||||
...(await initOverrideFn({
|
||||
init: initParams,
|
||||
context,
|
||||
})),
|
||||
};
|
||||
|
||||
let body: any;
|
||||
if (
|
||||
isFormData(overriddenInit.body) ||
|
||||
overriddenInit.body instanceof URLSearchParams ||
|
||||
isBlob(overriddenInit.body)
|
||||
) {
|
||||
body = overriddenInit.body;
|
||||
} else if (this.isJsonMime(headers["Content-Type"])) {
|
||||
body = JSON.stringify(overriddenInit.body);
|
||||
} else {
|
||||
body = overriddenInit.body;
|
||||
}
|
||||
|
||||
withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
|
||||
const middlewares = preMiddlewares.map((pre) => ({ pre }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
...overriddenInit,
|
||||
body,
|
||||
};
|
||||
|
||||
withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
|
||||
const middlewares = postMiddlewares.map((post) => ({ post }));
|
||||
return this.withMiddleware<T>(...middlewares);
|
||||
}
|
||||
return { url, init };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
protected isJsonMime(mime: string | null | undefined): boolean {
|
||||
if (!mime) {
|
||||
return false;
|
||||
private fetchApi = async (url: string, init: RequestInit) => {
|
||||
let fetchParams = { url, init };
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.pre) {
|
||||
fetchParams =
|
||||
(await middleware.pre({
|
||||
fetch: this.fetchApi,
|
||||
...fetchParams,
|
||||
})) || fetchParams;
|
||||
}
|
||||
}
|
||||
let response: Response | undefined = undefined;
|
||||
try {
|
||||
response = await (this.configuration.fetchApi || fetch)(
|
||||
fetchParams.url,
|
||||
fetchParams.init,
|
||||
);
|
||||
} catch (e) {
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.onError) {
|
||||
response =
|
||||
(await middleware.onError({
|
||||
fetch: this.fetchApi,
|
||||
url: fetchParams.url,
|
||||
init: fetchParams.init,
|
||||
error: e,
|
||||
response: response ? response.clone() : undefined,
|
||||
})) || response;
|
||||
}
|
||||
return BaseAPI.jsonRegex.test(mime);
|
||||
}
|
||||
|
||||
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
|
||||
const { url, init } = await this.createFetchParams(context, initOverrides);
|
||||
const response = await this.fetchApi(url, init);
|
||||
if (response && (response.status >= 200 && response.status < 300)) {
|
||||
return response;
|
||||
}
|
||||
throw new ResponseError(response, 'Response returned an error code');
|
||||
}
|
||||
|
||||
private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
|
||||
let url = this.configuration.basePath + context.path;
|
||||
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
|
||||
// only add the querystring to the URL if there are query parameters.
|
||||
// this is done to avoid urls ending with a "?" character which buggy webservers
|
||||
// do not handle correctly sometimes.
|
||||
url += '?' + this.configuration.queryParamsStringify(context.query);
|
||||
}
|
||||
|
||||
const headers = Object.assign({}, this.configuration.headers, context.headers);
|
||||
Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
|
||||
|
||||
const initOverrideFn =
|
||||
typeof initOverrides === "function"
|
||||
? initOverrides
|
||||
: async () => initOverrides;
|
||||
|
||||
const initParams = {
|
||||
method: context.method,
|
||||
headers,
|
||||
body: context.body,
|
||||
credentials: this.configuration.credentials,
|
||||
};
|
||||
|
||||
const overriddenInit: RequestInit = {
|
||||
...initParams,
|
||||
...(await initOverrideFn({
|
||||
init: initParams,
|
||||
context,
|
||||
}))
|
||||
};
|
||||
|
||||
let body: any;
|
||||
if (isFormData(overriddenInit.body)
|
||||
|| (overriddenInit.body instanceof URLSearchParams)
|
||||
|| isBlob(overriddenInit.body)) {
|
||||
body = overriddenInit.body;
|
||||
} else if (this.isJsonMime(headers['Content-Type'])) {
|
||||
body = JSON.stringify(overriddenInit.body);
|
||||
}
|
||||
if (response === undefined) {
|
||||
if (e instanceof Error) {
|
||||
throw new FetchError(
|
||||
e,
|
||||
"The request failed and the interceptors did not return an alternative response",
|
||||
);
|
||||
} else {
|
||||
body = overriddenInit.body;
|
||||
throw e;
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
...overriddenInit,
|
||||
body
|
||||
};
|
||||
|
||||
return { url, init };
|
||||
}
|
||||
}
|
||||
|
||||
private fetchApi = async (url: string, init: RequestInit) => {
|
||||
let fetchParams = { url, init };
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.pre) {
|
||||
fetchParams = await middleware.pre({
|
||||
fetch: this.fetchApi,
|
||||
...fetchParams,
|
||||
}) || fetchParams;
|
||||
}
|
||||
}
|
||||
let response: Response | undefined = undefined;
|
||||
try {
|
||||
response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
|
||||
} catch (e) {
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.onError) {
|
||||
response = await middleware.onError({
|
||||
fetch: this.fetchApi,
|
||||
url: fetchParams.url,
|
||||
init: fetchParams.init,
|
||||
error: e,
|
||||
response: response ? response.clone() : undefined,
|
||||
}) || response;
|
||||
}
|
||||
}
|
||||
if (response === undefined) {
|
||||
if (e instanceof Error) {
|
||||
throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.post) {
|
||||
response = await middleware.post({
|
||||
fetch: this.fetchApi,
|
||||
url: fetchParams.url,
|
||||
init: fetchParams.init,
|
||||
response: response.clone(),
|
||||
}) || response;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
for (const middleware of this.middleware) {
|
||||
if (middleware.post) {
|
||||
response =
|
||||
(await middleware.post({
|
||||
fetch: this.fetchApi,
|
||||
url: fetchParams.url,
|
||||
init: fetchParams.init,
|
||||
response: response.clone(),
|
||||
})) || response;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a shallow clone of `this` by constructing a new instance
|
||||
* and then shallow cloning data members.
|
||||
*/
|
||||
private clone<T extends BaseAPI>(this: T): T {
|
||||
const constructor = this.constructor as any;
|
||||
const next = new constructor(this.configuration);
|
||||
next.middleware = this.middleware.slice();
|
||||
return next;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Create a shallow clone of `this` by constructing a new instance
|
||||
* and then shallow cloning data members.
|
||||
*/
|
||||
private clone<T extends BaseAPI>(this: T): T {
|
||||
const constructor = this.constructor as any;
|
||||
const next = new constructor(this.configuration);
|
||||
next.middleware = this.middleware.slice();
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
function isBlob(value: any): value is Blob {
|
||||
return typeof Blob !== 'undefined' && value instanceof Blob;
|
||||
return typeof Blob !== "undefined" && value instanceof Blob;
|
||||
}
|
||||
|
||||
function isFormData(value: any): value is FormData {
|
||||
return typeof FormData !== "undefined" && value instanceof FormData;
|
||||
return typeof FormData !== "undefined" && value instanceof FormData;
|
||||
}
|
||||
|
||||
export class ResponseError extends Error {
|
||||
override name: "ResponseError" = "ResponseError";
|
||||
constructor(public response: Response, msg?: string) {
|
||||
super(msg);
|
||||
}
|
||||
override name: "ResponseError" = "ResponseError";
|
||||
constructor(
|
||||
public response: Response,
|
||||
msg?: string,
|
||||
) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export class FetchError extends Error {
|
||||
override name: "FetchError" = "FetchError";
|
||||
constructor(public cause: Error, msg?: string) {
|
||||
super(msg);
|
||||
}
|
||||
override name: "FetchError" = "FetchError";
|
||||
constructor(
|
||||
public cause: Error,
|
||||
msg?: string,
|
||||
) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export class RequiredError extends Error {
|
||||
override name: "RequiredError" = "RequiredError";
|
||||
constructor(public field: string, msg?: string) {
|
||||
super(msg);
|
||||
}
|
||||
override name: "RequiredError" = "RequiredError";
|
||||
constructor(
|
||||
public field: string,
|
||||
msg?: string,
|
||||
) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export const COLLECTION_FORMATS = {
|
||||
csv: ",",
|
||||
ssv: " ",
|
||||
tsv: "\t",
|
||||
pipes: "|",
|
||||
csv: ",",
|
||||
ssv: " ",
|
||||
tsv: "\t",
|
||||
pipes: "|",
|
||||
};
|
||||
|
||||
export type FetchAPI = WindowOrWorkerGlobalScope['fetch'];
|
||||
export type FetchAPI = WindowOrWorkerGlobalScope["fetch"];
|
||||
|
||||
export type Json = any;
|
||||
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
||||
export type HTTPMethod =
|
||||
| "GET"
|
||||
| "POST"
|
||||
| "PUT"
|
||||
| "PATCH"
|
||||
| "DELETE"
|
||||
| "OPTIONS"
|
||||
| "HEAD";
|
||||
export type HTTPHeaders = { [key: string]: string };
|
||||
export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
|
||||
export type HTTPQuery = {
|
||||
[key: string]:
|
||||
| string
|
||||
| number
|
||||
| null
|
||||
| boolean
|
||||
| Array<string | number | null | boolean>
|
||||
| Set<string | number | null | boolean>
|
||||
| HTTPQuery;
|
||||
};
|
||||
export type HTTPBody = Json | FormData | URLSearchParams;
|
||||
export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody };
|
||||
export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
|
||||
export type HTTPRequestInit = {
|
||||
headers?: HTTPHeaders;
|
||||
method: HTTPMethod;
|
||||
credentials?: RequestCredentials;
|
||||
body?: HTTPBody;
|
||||
};
|
||||
export type ModelPropertyNaming =
|
||||
| "camelCase"
|
||||
| "snake_case"
|
||||
| "PascalCase"
|
||||
| "original";
|
||||
|
||||
export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
|
||||
export type InitOverrideFunction = (requestContext: {
|
||||
init: HTTPRequestInit;
|
||||
context: RequestOpts;
|
||||
}) => Promise<RequestInit>;
|
||||
|
||||
export interface FetchParams {
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
}
|
||||
|
||||
export interface RequestOpts {
|
||||
path: string;
|
||||
method: HTTPMethod;
|
||||
headers: HTTPHeaders;
|
||||
query?: HTTPQuery;
|
||||
body?: HTTPBody;
|
||||
path: string;
|
||||
method: HTTPMethod;
|
||||
headers: HTTPHeaders;
|
||||
query?: HTTPQuery;
|
||||
body?: HTTPBody;
|
||||
}
|
||||
|
||||
export function querystring(params: HTTPQuery, prefix: string = ''): string {
|
||||
return Object.keys(params)
|
||||
.map(key => querystringSingleKey(key, params[key], prefix))
|
||||
.filter(part => part.length > 0)
|
||||
.join('&');
|
||||
export function querystring(params: HTTPQuery, prefix: string = ""): string {
|
||||
return Object.keys(params)
|
||||
.map((key) => querystringSingleKey(key, params[key], prefix))
|
||||
.filter((part) => part.length > 0)
|
||||
.join("&");
|
||||
}
|
||||
|
||||
function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
|
||||
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
|
||||
if (value instanceof Array) {
|
||||
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
|
||||
.join(`&${encodeURIComponent(fullKey)}=`);
|
||||
return `${encodeURIComponent(fullKey)}=${multiValue}`;
|
||||
}
|
||||
if (value instanceof Set) {
|
||||
const valueAsArray = Array.from(value);
|
||||
return querystringSingleKey(key, valueAsArray, keyPrefix);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
|
||||
}
|
||||
if (value instanceof Object) {
|
||||
return querystring(value as HTTPQuery, fullKey);
|
||||
}
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
|
||||
function querystringSingleKey(
|
||||
key: string,
|
||||
value:
|
||||
| string
|
||||
| number
|
||||
| null
|
||||
| undefined
|
||||
| boolean
|
||||
| Array<string | number | null | boolean>
|
||||
| Set<string | number | null | boolean>
|
||||
| HTTPQuery,
|
||||
keyPrefix: string = "",
|
||||
): string {
|
||||
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
|
||||
if (value instanceof Array) {
|
||||
const multiValue = value
|
||||
.map((singleValue) => encodeURIComponent(String(singleValue)))
|
||||
.join(`&${encodeURIComponent(fullKey)}=`);
|
||||
return `${encodeURIComponent(fullKey)}=${multiValue}`;
|
||||
}
|
||||
if (value instanceof Set) {
|
||||
const valueAsArray = Array.from(value);
|
||||
return querystringSingleKey(key, valueAsArray, keyPrefix);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
|
||||
}
|
||||
if (value instanceof Object) {
|
||||
return querystring(value as HTTPQuery, fullKey);
|
||||
}
|
||||
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
|
||||
}
|
||||
|
||||
export function exists(json: any, key: string) {
|
||||
const value = json[key];
|
||||
return value !== null && value !== undefined;
|
||||
const value = json[key];
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
export function mapValues(data: any, fn: (item: any) => any) {
|
||||
return Object.keys(data).reduce(
|
||||
(acc, key) => ({ ...acc, [key]: fn(data[key]) }),
|
||||
{}
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
export function canConsumeForm(consumes: Consume[]): boolean {
|
||||
for (const consume of consumes) {
|
||||
if ('multipart/form-data' === consume.contentType) {
|
||||
return true;
|
||||
}
|
||||
for (const consume of consumes) {
|
||||
if ("multipart/form-data" === consume.contentType) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface Consume {
|
||||
contentType: string;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
export interface RequestContext {
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
}
|
||||
|
||||
export interface ResponseContext {
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
response: Response;
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
response: Response;
|
||||
}
|
||||
|
||||
export interface ErrorContext {
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
error: unknown;
|
||||
response?: Response;
|
||||
fetch: FetchAPI;
|
||||
url: string;
|
||||
init: RequestInit;
|
||||
error: unknown;
|
||||
response?: Response;
|
||||
}
|
||||
|
||||
export interface Middleware {
|
||||
pre?(context: RequestContext): Promise<FetchParams | void>;
|
||||
post?(context: ResponseContext): Promise<Response | void>;
|
||||
onError?(context: ErrorContext): Promise<Response | void>;
|
||||
pre?(context: RequestContext): Promise<FetchParams | void>;
|
||||
post?(context: ResponseContext): Promise<Response | void>;
|
||||
onError?(context: ErrorContext): Promise<Response | void>;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
raw: Response;
|
||||
value(): Promise<T>;
|
||||
raw: Response;
|
||||
value(): Promise<T>;
|
||||
}
|
||||
|
||||
export interface ResponseTransformer<T> {
|
||||
(json: any): T;
|
||||
(json: any): T;
|
||||
}
|
||||
|
||||
export class JSONApiResponse<T> {
|
||||
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {}
|
||||
constructor(
|
||||
public raw: Response,
|
||||
private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue,
|
||||
) {}
|
||||
|
||||
async value(): Promise<T> {
|
||||
return this.transformer(await this.raw.json());
|
||||
}
|
||||
async value(): Promise<T> {
|
||||
return this.transformer(await this.raw.json());
|
||||
}
|
||||
}
|
||||
|
||||
export class VoidApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<void> {
|
||||
return undefined;
|
||||
}
|
||||
async value(): Promise<void> {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class BlobApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<Blob> {
|
||||
return await this.raw.blob();
|
||||
};
|
||||
async value(): Promise<Blob> {
|
||||
return await this.raw.blob();
|
||||
}
|
||||
}
|
||||
|
||||
export class TextApiResponse {
|
||||
constructor(public raw: Response) {}
|
||||
constructor(public raw: Response) {}
|
||||
|
||||
async value(): Promise<string> {
|
||||
return await this.raw.text();
|
||||
};
|
||||
async value(): Promise<string> {
|
||||
return await this.raw.text();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,12 +5,7 @@
|
|||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "dist",
|
||||
"typeRoots": [
|
||||
"node_modules/@types"
|
||||
]
|
||||
"typeRoots": ["node_modules/@types"]
|
||||
},
|
||||
"exclude": [
|
||||
"dist",
|
||||
"node_modules"
|
||||
]
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue