Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- node_modules/@huggingface/hub/src/lib/list-datasets.spec.ts +47 -0
- node_modules/@huggingface/hub/src/lib/list-datasets.ts +135 -0
- node_modules/@huggingface/hub/src/lib/list-files.spec.ts +173 -0
- node_modules/@huggingface/hub/src/lib/list-files.ts +94 -0
- node_modules/@huggingface/hub/src/lib/list-models.spec.ts +151 -0
- node_modules/@huggingface/hub/src/lib/list-models.ts +171 -0
- node_modules/@huggingface/hub/src/lib/list-spaces.spec.ts +40 -0
- node_modules/@huggingface/hub/src/lib/list-spaces.ts +116 -0
- node_modules/@huggingface/hub/src/lib/model-info.spec.ts +75 -0
- node_modules/@huggingface/hub/src/lib/model-info.ts +68 -0
- node_modules/@huggingface/hub/src/lib/oauth-handle-redirect.spec.ts +60 -0
- node_modules/@huggingface/hub/src/lib/oauth-handle-redirect.ts +343 -0
- node_modules/@huggingface/hub/src/lib/oauth-login-url.ts +166 -0
- node_modules/@huggingface/hub/src/lib/parse-safetensors-metadata.spec.ts +326 -0
- node_modules/@huggingface/hub/src/lib/parse-safetensors-metadata.ts +501 -0
- node_modules/@huggingface/hub/src/lib/paths-info.spec.ts +73 -0
- node_modules/@huggingface/hub/src/lib/paths-info.ts +124 -0
- node_modules/@huggingface/hub/src/lib/repo-exists.spec.ts +13 -0
- node_modules/@huggingface/hub/src/lib/repo-exists.ts +43 -0
- node_modules/@huggingface/hub/src/lib/snapshot-download.spec.ts +275 -0
- node_modules/@huggingface/hub/src/lib/snapshot-download.ts +124 -0
- node_modules/@huggingface/hub/src/lib/space-info.spec.ts +53 -0
- node_modules/@huggingface/hub/src/lib/space-info.ts +60 -0
- node_modules/@huggingface/hub/src/lib/upload-file.spec.ts +99 -0
- node_modules/@huggingface/hub/src/lib/upload-file.ts +49 -0
- node_modules/@huggingface/hub/src/lib/upload-files-with-progress.spec.ts +178 -0
- node_modules/@huggingface/hub/src/lib/upload-files-with-progress.ts +159 -0
- node_modules/@huggingface/hub/src/lib/upload-files.fs.spec.ts +72 -0
- node_modules/@huggingface/hub/src/lib/upload-files.spec.ts +96 -0
- node_modules/@huggingface/hub/src/lib/upload-files.ts +41 -0
- node_modules/@huggingface/hub/src/lib/who-am-i.spec.ts +36 -0
- node_modules/@huggingface/hub/src/lib/who-am-i.ts +92 -0
- node_modules/@huggingface/hub/src/test/consts.ts +4 -0
- node_modules/@huggingface/hub/src/types/api/api-author.ts +26 -0
- node_modules/@huggingface/hub/src/types/api/api-collection.ts +328 -0
- node_modules/@huggingface/hub/src/types/api/api-commit.ts +204 -0
- node_modules/@huggingface/hub/src/types/api/api-create-collection.ts +19 -0
- node_modules/@huggingface/hub/src/types/api/api-create-repo.ts +26 -0
- node_modules/@huggingface/hub/src/types/api/api-dataset.ts +89 -0
- node_modules/@huggingface/hub/src/types/api/api-index-tree.ts +46 -0
- node_modules/@huggingface/hub/src/types/api/api-jobs.ts +146 -0
- node_modules/@huggingface/hub/src/types/api/api-model.ts +282 -0
- node_modules/@huggingface/hub/src/types/api/api-space.ts +93 -0
- node_modules/@huggingface/hub/src/types/api/api-who-am-i.ts +52 -0
- node_modules/@huggingface/hub/src/types/public.ts +191 -0
- node_modules/@huggingface/hub/src/utils/ChunkCache.spec.ts +265 -0
- node_modules/@huggingface/hub/src/utils/ChunkCache.ts +99 -0
- node_modules/@huggingface/hub/src/utils/FileBlob.spec.ts +45 -0
- node_modules/@huggingface/hub/src/utils/FileBlob.ts +122 -0
- node_modules/@huggingface/hub/src/utils/RangeList.spec.ts +96 -0
node_modules/@huggingface/hub/src/lib/list-datasets.spec.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import type { DatasetEntry } from "./list-datasets";
|
| 3 |
+
import { listDatasets } from "./list-datasets";
|
| 4 |
+
|
| 5 |
+
describe("listDatasets", () => {
|
| 6 |
+
it("should list datasets from hf-doc-builder", async () => {
|
| 7 |
+
const results: DatasetEntry[] = [];
|
| 8 |
+
|
| 9 |
+
for await (const entry of listDatasets({ search: { owner: "hf-doc-build" } })) {
|
| 10 |
+
if (entry.name !== "hf-doc-build/doc-build" && entry.name !== "hf-doc-build/doc-build-dev") {
|
| 11 |
+
continue;
|
| 12 |
+
}
|
| 13 |
+
if (typeof entry.downloads === "number") {
|
| 14 |
+
entry.downloads = 0;
|
| 15 |
+
}
|
| 16 |
+
if (typeof entry.likes === "number") {
|
| 17 |
+
entry.likes = 0;
|
| 18 |
+
}
|
| 19 |
+
if (entry.updatedAt instanceof Date && !isNaN(entry.updatedAt.getTime())) {
|
| 20 |
+
entry.updatedAt = new Date(0);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
results.push(entry);
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
expect(results.sort((a, b) => a.id.localeCompare(b.id))).to.deep.equal([
|
| 27 |
+
{
|
| 28 |
+
id: "6356b19985da6f13863228bd",
|
| 29 |
+
name: "hf-doc-build/doc-build",
|
| 30 |
+
private: false,
|
| 31 |
+
gated: false,
|
| 32 |
+
downloads: 0,
|
| 33 |
+
likes: 0,
|
| 34 |
+
updatedAt: new Date(0),
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
id: "636a1b69f2f9ec4289c4c19e",
|
| 38 |
+
name: "hf-doc-build/doc-build-dev",
|
| 39 |
+
gated: false,
|
| 40 |
+
private: false,
|
| 41 |
+
downloads: 0,
|
| 42 |
+
likes: 0,
|
| 43 |
+
updatedAt: new Date(0),
|
| 44 |
+
},
|
| 45 |
+
]);
|
| 46 |
+
});
|
| 47 |
+
});
|
node_modules/@huggingface/hub/src/lib/list-datasets.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiDatasetInfo } from "../types/api/api-dataset";
|
| 4 |
+
import type { CredentialsParams } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { parseLinkHeader } from "../utils/parseLinkHeader";
|
| 7 |
+
import { pick } from "../utils/pick";
|
| 8 |
+
|
| 9 |
+
export const DATASET_EXPAND_KEYS = [
|
| 10 |
+
"private",
|
| 11 |
+
"downloads",
|
| 12 |
+
"gated",
|
| 13 |
+
"likes",
|
| 14 |
+
"lastModified",
|
| 15 |
+
] as const satisfies readonly (keyof ApiDatasetInfo)[];
|
| 16 |
+
|
| 17 |
+
export const DATASET_EXPANDABLE_KEYS = [
|
| 18 |
+
"author",
|
| 19 |
+
"cardData",
|
| 20 |
+
"citation",
|
| 21 |
+
"createdAt",
|
| 22 |
+
"disabled",
|
| 23 |
+
"description",
|
| 24 |
+
"downloads",
|
| 25 |
+
"downloadsAllTime",
|
| 26 |
+
"gated",
|
| 27 |
+
"gitalyUid",
|
| 28 |
+
"lastModified",
|
| 29 |
+
"likes",
|
| 30 |
+
"paperswithcode_id",
|
| 31 |
+
"private",
|
| 32 |
+
// "siblings",
|
| 33 |
+
"sha",
|
| 34 |
+
"tags",
|
| 35 |
+
] as const satisfies readonly (keyof ApiDatasetInfo)[];
|
| 36 |
+
|
| 37 |
+
export interface DatasetEntry {
|
| 38 |
+
id: string;
|
| 39 |
+
name: string;
|
| 40 |
+
private: boolean;
|
| 41 |
+
downloads: number;
|
| 42 |
+
gated: false | "auto" | "manual";
|
| 43 |
+
likes: number;
|
| 44 |
+
updatedAt: Date;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
export async function* listDatasets<
|
| 48 |
+
const T extends Exclude<(typeof DATASET_EXPANDABLE_KEYS)[number], (typeof DATASET_EXPAND_KEYS)[number]> = never,
|
| 49 |
+
>(
|
| 50 |
+
params?: {
|
| 51 |
+
search?: {
|
| 52 |
+
/**
|
| 53 |
+
* Will search in the dataset name for matches
|
| 54 |
+
*/
|
| 55 |
+
query?: string;
|
| 56 |
+
owner?: string;
|
| 57 |
+
tags?: string[];
|
| 58 |
+
};
|
| 59 |
+
hubUrl?: string;
|
| 60 |
+
additionalFields?: T[];
|
| 61 |
+
/**
|
| 62 |
+
* Set to limit the number of datasets returned.
|
| 63 |
+
*/
|
| 64 |
+
limit?: number;
|
| 65 |
+
/**
|
| 66 |
+
* Sort datasets by a specific field.
|
| 67 |
+
*/
|
| 68 |
+
sort?:
|
| 69 |
+
| "createdAt"
|
| 70 |
+
| "downloads"
|
| 71 |
+
| "likes"
|
| 72 |
+
| "lastModified"
|
| 73 |
+
| "likes30d"
|
| 74 |
+
| "trendingScore"
|
| 75 |
+
| "datasetsServerInfo.numRows"
|
| 76 |
+
| "mainSize"
|
| 77 |
+
| "id";
|
| 78 |
+
/**
|
| 79 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 80 |
+
*/
|
| 81 |
+
fetch?: typeof fetch;
|
| 82 |
+
} & Partial<CredentialsParams>,
|
| 83 |
+
): AsyncGenerator<DatasetEntry & Pick<ApiDatasetInfo, T>> {
|
| 84 |
+
const accessToken = params && checkCredentials(params);
|
| 85 |
+
let totalToFetch = params?.limit ?? Infinity;
|
| 86 |
+
const search = new URLSearchParams([
|
| 87 |
+
...Object.entries({
|
| 88 |
+
limit: String(Math.min(totalToFetch, 500)),
|
| 89 |
+
...(params?.search?.owner ? { author: params.search.owner } : undefined),
|
| 90 |
+
...(params?.search?.query ? { search: params.search.query } : undefined),
|
| 91 |
+
...(params?.sort ? { sort: params.sort } : undefined),
|
| 92 |
+
}),
|
| 93 |
+
...(params?.search?.tags?.map((tag) => ["filter", tag]) ?? []),
|
| 94 |
+
...DATASET_EXPAND_KEYS.map((val) => ["expand", val] satisfies [string, string]),
|
| 95 |
+
...(params?.additionalFields?.map((val) => ["expand", val] satisfies [string, string]) ?? []),
|
| 96 |
+
]).toString();
|
| 97 |
+
let url: string | undefined = `${params?.hubUrl || HUB_URL}/api/datasets` + (search ? "?" + search : "");
|
| 98 |
+
|
| 99 |
+
while (url) {
|
| 100 |
+
const res: Response = await (params?.fetch ?? fetch)(url, {
|
| 101 |
+
headers: {
|
| 102 |
+
accept: "application/json",
|
| 103 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
|
| 104 |
+
},
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
if (!res.ok) {
|
| 108 |
+
throw await createApiError(res);
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const items: ApiDatasetInfo[] = await res.json();
|
| 112 |
+
|
| 113 |
+
for (const item of items) {
|
| 114 |
+
yield {
|
| 115 |
+
...(params?.additionalFields && pick(item, params.additionalFields)),
|
| 116 |
+
id: item._id,
|
| 117 |
+
name: item.id,
|
| 118 |
+
private: item.private,
|
| 119 |
+
downloads: item.downloads,
|
| 120 |
+
likes: item.likes,
|
| 121 |
+
gated: item.gated,
|
| 122 |
+
updatedAt: new Date(item.lastModified),
|
| 123 |
+
} as DatasetEntry & Pick<ApiDatasetInfo, T>;
|
| 124 |
+
totalToFetch--;
|
| 125 |
+
if (totalToFetch <= 0) {
|
| 126 |
+
return;
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
const linkHeader = res.headers.get("Link");
|
| 131 |
+
|
| 132 |
+
url = linkHeader ? parseLinkHeader(linkHeader).next : undefined;
|
| 133 |
+
// Could update limit in url to fetch less items if not all items of next page are needed.
|
| 134 |
+
}
|
| 135 |
+
}
|
node_modules/@huggingface/hub/src/lib/list-files.spec.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe } from "vitest";
|
| 2 |
+
import type { ListFileEntry } from "./list-files";
|
| 3 |
+
import { listFiles } from "./list-files";
|
| 4 |
+
|
| 5 |
+
describe("listFiles", () => {
|
| 6 |
+
it("should fetch the list of files from the repo", async () => {
|
| 7 |
+
const cursor = listFiles({
|
| 8 |
+
repo: {
|
| 9 |
+
name: "google-bert/bert-base-uncased",
|
| 10 |
+
type: "model",
|
| 11 |
+
},
|
| 12 |
+
revision: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
const files: ListFileEntry[] = [];
|
| 16 |
+
|
| 17 |
+
for await (const entry of cursor) {
|
| 18 |
+
files.push(entry);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
assert.deepStrictEqual(files, [
|
| 22 |
+
{
|
| 23 |
+
oid: "dc08351d4dc0732d9c8af04070ced089b201ce2f",
|
| 24 |
+
path: ".gitattributes",
|
| 25 |
+
size: 345,
|
| 26 |
+
type: "file",
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
oid: "fca794a5f07ff8f963fe8b61e3694b0fb7f955df",
|
| 30 |
+
path: "config.json",
|
| 31 |
+
size: 313,
|
| 32 |
+
type: "file",
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
lfs: {
|
| 36 |
+
oid: "097417381d6c7230bd9e3557456d726de6e83245ec8b24f529f60198a67b203a",
|
| 37 |
+
size: 440473133,
|
| 38 |
+
pointerSize: 134,
|
| 39 |
+
},
|
| 40 |
+
xetHash: "2d8408d3a894d02517d04956e2f7546ff08362594072f3527ce144b5212a3296",
|
| 41 |
+
oid: "ba5d19791be1dd7992e33bd61f20207b0f7f50a5",
|
| 42 |
+
path: "pytorch_model.bin",
|
| 43 |
+
size: 440473133,
|
| 44 |
+
type: "file",
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
lfs: {
|
| 48 |
+
oid: "a7a17d6d844b5de815ccab5f42cad6d24496db3850a2a43d8258221018ce87d2",
|
| 49 |
+
size: 536063208,
|
| 50 |
+
pointerSize: 134,
|
| 51 |
+
},
|
| 52 |
+
xetHash: "879c5715c18a0b7f051dd33f70f0a5c8dd1522e0a43f6f75520f16167f29279b",
|
| 53 |
+
oid: "9eb98c817f04b051b3bcca591bcd4e03cec88018",
|
| 54 |
+
path: "tf_model.h5",
|
| 55 |
+
size: 536063208,
|
| 56 |
+
type: "file",
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
oid: "fb140275c155a9c7c5a3b3e0e77a9e839594a938",
|
| 60 |
+
path: "vocab.txt",
|
| 61 |
+
size: 231508,
|
| 62 |
+
type: "file",
|
| 63 |
+
},
|
| 64 |
+
]);
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
it("should fetch the list of files from the repo, including last commit", async () => {
|
| 68 |
+
const cursor = listFiles({
|
| 69 |
+
repo: {
|
| 70 |
+
name: "google-bert/bert-base-uncased",
|
| 71 |
+
type: "model",
|
| 72 |
+
},
|
| 73 |
+
revision: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 74 |
+
expand: true,
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
const files: ListFileEntry[] = [];
|
| 78 |
+
|
| 79 |
+
for await (const entry of cursor) {
|
| 80 |
+
delete entry.securityFileStatus; // flaky
|
| 81 |
+
files.push(entry);
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
assert.deepStrictEqual(files, [
|
| 85 |
+
{
|
| 86 |
+
lastCommit: {
|
| 87 |
+
date: "2018-11-14T23:35:08.000Z",
|
| 88 |
+
id: "504939aa53e8ce310dba3dd2296dbe266c575de4",
|
| 89 |
+
title: "initial commit",
|
| 90 |
+
},
|
| 91 |
+
oid: "dc08351d4dc0732d9c8af04070ced089b201ce2f",
|
| 92 |
+
path: ".gitattributes",
|
| 93 |
+
size: 345,
|
| 94 |
+
type: "file",
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
lastCommit: {
|
| 98 |
+
date: "2019-06-18T09:06:51.000Z",
|
| 99 |
+
id: "bb3c1c3256d2598217df9889a14a2e811587891d",
|
| 100 |
+
title: "Update config.json",
|
| 101 |
+
},
|
| 102 |
+
oid: "fca794a5f07ff8f963fe8b61e3694b0fb7f955df",
|
| 103 |
+
path: "config.json",
|
| 104 |
+
size: 313,
|
| 105 |
+
type: "file",
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
lastCommit: {
|
| 109 |
+
date: "2019-06-18T09:06:34.000Z",
|
| 110 |
+
id: "3d2477d72b675a999d1b13ca822aaaf4908634ad",
|
| 111 |
+
title: "Update pytorch_model.bin",
|
| 112 |
+
},
|
| 113 |
+
lfs: {
|
| 114 |
+
oid: "097417381d6c7230bd9e3557456d726de6e83245ec8b24f529f60198a67b203a",
|
| 115 |
+
size: 440473133,
|
| 116 |
+
pointerSize: 134,
|
| 117 |
+
},
|
| 118 |
+
xetHash: "2d8408d3a894d02517d04956e2f7546ff08362594072f3527ce144b5212a3296",
|
| 119 |
+
oid: "ba5d19791be1dd7992e33bd61f20207b0f7f50a5",
|
| 120 |
+
path: "pytorch_model.bin",
|
| 121 |
+
size: 440473133,
|
| 122 |
+
type: "file",
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
lastCommit: {
|
| 126 |
+
date: "2019-09-23T19:48:44.000Z",
|
| 127 |
+
id: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 128 |
+
title: "Update tf_model.h5",
|
| 129 |
+
},
|
| 130 |
+
lfs: {
|
| 131 |
+
oid: "a7a17d6d844b5de815ccab5f42cad6d24496db3850a2a43d8258221018ce87d2",
|
| 132 |
+
size: 536063208,
|
| 133 |
+
pointerSize: 134,
|
| 134 |
+
},
|
| 135 |
+
xetHash: "879c5715c18a0b7f051dd33f70f0a5c8dd1522e0a43f6f75520f16167f29279b",
|
| 136 |
+
oid: "9eb98c817f04b051b3bcca591bcd4e03cec88018",
|
| 137 |
+
path: "tf_model.h5",
|
| 138 |
+
size: 536063208,
|
| 139 |
+
type: "file",
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
lastCommit: {
|
| 143 |
+
date: "2018-11-14T23:35:08.000Z",
|
| 144 |
+
id: "2f07d813ca87c8c709147704c87210359ccf2309",
|
| 145 |
+
title: "Update vocab.txt",
|
| 146 |
+
},
|
| 147 |
+
oid: "fb140275c155a9c7c5a3b3e0e77a9e839594a938",
|
| 148 |
+
path: "vocab.txt",
|
| 149 |
+
size: 231508,
|
| 150 |
+
type: "file",
|
| 151 |
+
},
|
| 152 |
+
]);
|
| 153 |
+
});
|
| 154 |
+
|
| 155 |
+
it("should fetch the list of files from the repo, including subfolders", async () => {
|
| 156 |
+
const cursor = listFiles({
|
| 157 |
+
repo: {
|
| 158 |
+
name: "xsum",
|
| 159 |
+
type: "dataset",
|
| 160 |
+
},
|
| 161 |
+
revision: "0f3ea2f2b55fcb11e71fb1e3aec6822e44ddcb0f",
|
| 162 |
+
recursive: true,
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
const files: ListFileEntry[] = [];
|
| 166 |
+
|
| 167 |
+
for await (const entry of cursor) {
|
| 168 |
+
files.push(entry);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
assert(files.some((file) => file.path === "data/XSUM-EMNLP18-Summary-Data-Original.tar.gz"));
|
| 172 |
+
});
|
| 173 |
+
});
|
node_modules/@huggingface/hub/src/lib/list-files.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiIndexTreeEntry } from "../types/api/api-index-tree";
|
| 4 |
+
import type { CredentialsParams, RepoDesignation } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { parseLinkHeader } from "../utils/parseLinkHeader";
|
| 7 |
+
import { toRepoId } from "../utils/toRepoId";
|
| 8 |
+
|
| 9 |
+
export interface ListFileEntry {
|
| 10 |
+
type: "file" | "directory" | "unknown";
|
| 11 |
+
size: number;
|
| 12 |
+
path: string;
|
| 13 |
+
oid: string;
|
| 14 |
+
lfs?: {
|
| 15 |
+
oid: string;
|
| 16 |
+
size: number;
|
| 17 |
+
/** Size of the raw pointer file, 100~200 bytes */
|
| 18 |
+
pointerSize: number;
|
| 19 |
+
};
|
| 20 |
+
/**
|
| 21 |
+
* Xet-backed hash, a new protocol replacing LFS for big files.
|
| 22 |
+
*/
|
| 23 |
+
xetHash?: string;
|
| 24 |
+
/**
|
| 25 |
+
* Only fetched if `expand` is set to `true` in the `listFiles` call.
|
| 26 |
+
*/
|
| 27 |
+
lastCommit?: {
|
| 28 |
+
date: string;
|
| 29 |
+
id: string;
|
| 30 |
+
title: string;
|
| 31 |
+
};
|
| 32 |
+
/**
|
| 33 |
+
* Only fetched if `expand` is set to `true` in the `listFiles` call.
|
| 34 |
+
*/
|
| 35 |
+
securityFileStatus?: unknown;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
/**
|
| 39 |
+
* List files in a folder. To list ALL files in the directory, call it
|
| 40 |
+
* with {@link params.recursive} set to `true`.
|
| 41 |
+
*/
|
| 42 |
+
export async function* listFiles(
|
| 43 |
+
params: {
|
| 44 |
+
repo: RepoDesignation;
|
| 45 |
+
/**
|
| 46 |
+
* Do we want to list files in subdirectories?
|
| 47 |
+
*/
|
| 48 |
+
recursive?: boolean;
|
| 49 |
+
/**
|
| 50 |
+
* Eg 'data' for listing all files in the 'data' folder. Leave it empty to list all
|
| 51 |
+
* files in the repo.
|
| 52 |
+
*/
|
| 53 |
+
path?: string;
|
| 54 |
+
/**
|
| 55 |
+
* Fetch `lastCommit` and `securityFileStatus` for each file.
|
| 56 |
+
*/
|
| 57 |
+
expand?: boolean;
|
| 58 |
+
revision?: string;
|
| 59 |
+
hubUrl?: string;
|
| 60 |
+
/**
|
| 61 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 62 |
+
*/
|
| 63 |
+
fetch?: typeof fetch;
|
| 64 |
+
} & Partial<CredentialsParams>,
|
| 65 |
+
): AsyncGenerator<ListFileEntry> {
|
| 66 |
+
const accessToken = checkCredentials(params);
|
| 67 |
+
const repoId = toRepoId(params.repo);
|
| 68 |
+
let url: string | undefined = `${params.hubUrl || HUB_URL}/api/${repoId.type}s/${repoId.name}/tree/${
|
| 69 |
+
params.revision || "main"
|
| 70 |
+
}${params.path ? "/" + params.path : ""}?recursive=${!!params.recursive}&expand=${!!params.expand}`;
|
| 71 |
+
|
| 72 |
+
while (url) {
|
| 73 |
+
const res: Response = await (params.fetch ?? fetch)(url, {
|
| 74 |
+
headers: {
|
| 75 |
+
accept: "application/json",
|
| 76 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
|
| 77 |
+
},
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
if (!res.ok) {
|
| 81 |
+
throw await createApiError(res);
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
const items: ApiIndexTreeEntry[] = await res.json();
|
| 85 |
+
|
| 86 |
+
for (const item of items) {
|
| 87 |
+
yield item;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
const linkHeader = res.headers.get("Link");
|
| 91 |
+
|
| 92 |
+
url = linkHeader ? parseLinkHeader(linkHeader).next : undefined;
|
| 93 |
+
}
|
| 94 |
+
}
|
node_modules/@huggingface/hub/src/lib/list-models.spec.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import type { ModelEntry } from "./list-models";
|
| 3 |
+
import { listModels } from "./list-models";
|
| 4 |
+
|
| 5 |
+
describe("listModels", () => {
|
| 6 |
+
it("should list models for depth estimation", async () => {
|
| 7 |
+
const results: ModelEntry[] = [];
|
| 8 |
+
|
| 9 |
+
for await (const entry of listModels({
|
| 10 |
+
search: { owner: "Intel", task: "depth-estimation" },
|
| 11 |
+
})) {
|
| 12 |
+
if (typeof entry.downloads === "number") {
|
| 13 |
+
entry.downloads = 0;
|
| 14 |
+
}
|
| 15 |
+
if (typeof entry.likes === "number") {
|
| 16 |
+
entry.likes = 0;
|
| 17 |
+
}
|
| 18 |
+
if (entry.updatedAt instanceof Date && !isNaN(entry.updatedAt.getTime())) {
|
| 19 |
+
entry.updatedAt = new Date(0);
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
if (!["Intel/dpt-large", "Intel/dpt-hybrid-midas"].includes(entry.name)) {
|
| 23 |
+
expect(entry.task).to.equal("depth-estimation");
|
| 24 |
+
continue;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
results.push(entry);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
results.sort((a, b) => a.id.localeCompare(b.id));
|
| 31 |
+
|
| 32 |
+
expect(results).deep.equal([
|
| 33 |
+
{
|
| 34 |
+
id: "621ffdc136468d709f17e709",
|
| 35 |
+
name: "Intel/dpt-large",
|
| 36 |
+
private: false,
|
| 37 |
+
gated: false,
|
| 38 |
+
downloads: 0,
|
| 39 |
+
likes: 0,
|
| 40 |
+
task: "depth-estimation",
|
| 41 |
+
updatedAt: new Date(0),
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
id: "638f07977559bf9a2b2b04ac",
|
| 45 |
+
name: "Intel/dpt-hybrid-midas",
|
| 46 |
+
gated: false,
|
| 47 |
+
private: false,
|
| 48 |
+
downloads: 0,
|
| 49 |
+
likes: 0,
|
| 50 |
+
task: "depth-estimation",
|
| 51 |
+
updatedAt: new Date(0),
|
| 52 |
+
},
|
| 53 |
+
]);
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
it("should list indonesian models with gguf format", async () => {
|
| 57 |
+
let count = 0;
|
| 58 |
+
for await (const entry of listModels({
|
| 59 |
+
search: { tags: ["gguf", "id"] },
|
| 60 |
+
additionalFields: ["tags"],
|
| 61 |
+
limit: 2,
|
| 62 |
+
})) {
|
| 63 |
+
count++;
|
| 64 |
+
expect(entry.tags).to.include("gguf");
|
| 65 |
+
expect(entry.tags).to.include("id");
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
expect(count).to.equal(2);
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it("should search model by name", async () => {
|
| 72 |
+
let count = 0;
|
| 73 |
+
for await (const entry of listModels({
|
| 74 |
+
search: { query: "t5" },
|
| 75 |
+
limit: 10,
|
| 76 |
+
})) {
|
| 77 |
+
count++;
|
| 78 |
+
expect(entry.name.toLocaleLowerCase()).to.include("t5");
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
expect(count).to.equal(10);
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it("should search model by inference provider", async () => {
|
| 85 |
+
let count = 0;
|
| 86 |
+
for await (const entry of listModels({
|
| 87 |
+
search: { inferenceProviders: ["together"] },
|
| 88 |
+
additionalFields: ["inferenceProviderMapping"],
|
| 89 |
+
limit: 10,
|
| 90 |
+
})) {
|
| 91 |
+
count++;
|
| 92 |
+
if (Array.isArray(entry.inferenceProviderMapping)) {
|
| 93 |
+
expect(entry.inferenceProviderMapping.map(({ provider }) => provider)).to.include("together");
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
expect(count).to.equal(10);
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it("should search model by several inference providers", async () => {
|
| 101 |
+
let count = 0;
|
| 102 |
+
const inferenceProviders = ["together", "replicate"];
|
| 103 |
+
for await (const entry of listModels({
|
| 104 |
+
search: { inferenceProviders },
|
| 105 |
+
additionalFields: ["inferenceProviderMapping"],
|
| 106 |
+
limit: 10,
|
| 107 |
+
})) {
|
| 108 |
+
count++;
|
| 109 |
+
if (Array.isArray(entry.inferenceProviderMapping)) {
|
| 110 |
+
expect(
|
| 111 |
+
entry.inferenceProviderMapping.filter(({ provider }) => inferenceProviders.includes(provider)).length,
|
| 112 |
+
).toBeGreaterThan(0);
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
expect(count).to.equal(10);
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it("should list meta-llama models with inference provider mapping", async () => {
|
| 120 |
+
let count = 0;
|
| 121 |
+
for await (const entry of listModels({
|
| 122 |
+
search: { owner: "meta-llama" },
|
| 123 |
+
additionalFields: ["inferenceProviderMapping"],
|
| 124 |
+
limit: 1,
|
| 125 |
+
})) {
|
| 126 |
+
count++;
|
| 127 |
+
expect(entry.inferenceProviderMapping).to.be.an("array").that.is.not.empty;
|
| 128 |
+
for (const item of entry.inferenceProviderMapping ?? []) {
|
| 129 |
+
expect(item).to.have.property("provider").that.is.a("string").and.is.not.empty;
|
| 130 |
+
expect(item).to.have.property("hfModelId").that.is.a("string").and.is.not.empty;
|
| 131 |
+
expect(item).to.have.property("providerId").that.is.a("string").and.is.not.empty;
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
expect(count).to.equal(1);
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
it("should search models by apps", async () => {
|
| 139 |
+
let count = 0;
|
| 140 |
+
for await (const entry of listModels({
|
| 141 |
+
search: { apps: ["mlx-lm"] },
|
| 142 |
+
additionalFields: ["tags"],
|
| 143 |
+
limit: 10,
|
| 144 |
+
})) {
|
| 145 |
+
count++;
|
| 146 |
+
expect(entry.tags).to.include("mlx");
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
expect(count).to.equal(10);
|
| 150 |
+
});
|
| 151 |
+
});
|
node_modules/@huggingface/hub/src/lib/list-models.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiModelInfo } from "../types/api/api-model";
|
| 4 |
+
import type { CredentialsParams, PipelineType } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { parseLinkHeader } from "../utils/parseLinkHeader";
|
| 7 |
+
import { pick } from "../utils/pick";
|
| 8 |
+
import { normalizeInferenceProviderMapping } from "../utils/normalizeInferenceProviderMapping";
|
| 9 |
+
|
| 10 |
+
export const MODEL_EXPAND_KEYS = [
|
| 11 |
+
"pipeline_tag",
|
| 12 |
+
"private",
|
| 13 |
+
"gated",
|
| 14 |
+
"downloads",
|
| 15 |
+
"likes",
|
| 16 |
+
"lastModified",
|
| 17 |
+
] as const satisfies readonly (keyof ApiModelInfo)[];
|
| 18 |
+
|
| 19 |
+
export const MODEL_EXPANDABLE_KEYS = [
|
| 20 |
+
"author",
|
| 21 |
+
"cardData",
|
| 22 |
+
"config",
|
| 23 |
+
"createdAt",
|
| 24 |
+
"disabled",
|
| 25 |
+
"downloads",
|
| 26 |
+
"downloadsAllTime",
|
| 27 |
+
"gated",
|
| 28 |
+
"gitalyUid",
|
| 29 |
+
"inferenceProviderMapping",
|
| 30 |
+
"lastModified",
|
| 31 |
+
"library_name",
|
| 32 |
+
"likes",
|
| 33 |
+
"model-index",
|
| 34 |
+
"pipeline_tag",
|
| 35 |
+
"private",
|
| 36 |
+
"safetensors",
|
| 37 |
+
"sha",
|
| 38 |
+
// "siblings",
|
| 39 |
+
"spaces",
|
| 40 |
+
"tags",
|
| 41 |
+
"transformersInfo",
|
| 42 |
+
] as const satisfies readonly (keyof ApiModelInfo)[];
|
| 43 |
+
|
| 44 |
+
export interface ModelEntry {
|
| 45 |
+
id: string;
|
| 46 |
+
name: string;
|
| 47 |
+
private: boolean;
|
| 48 |
+
gated: false | "auto" | "manual";
|
| 49 |
+
task?: PipelineType;
|
| 50 |
+
likes: number;
|
| 51 |
+
downloads: number;
|
| 52 |
+
updatedAt: Date;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export async function* listModels<
|
| 56 |
+
const T extends Exclude<(typeof MODEL_EXPANDABLE_KEYS)[number], (typeof MODEL_EXPAND_KEYS)[number]> = never,
|
| 57 |
+
>(
|
| 58 |
+
params?: {
|
| 59 |
+
search?: {
|
| 60 |
+
/**
|
| 61 |
+
* Will search in the model name for matches
|
| 62 |
+
*/
|
| 63 |
+
query?: string;
|
| 64 |
+
owner?: string;
|
| 65 |
+
task?: PipelineType;
|
| 66 |
+
tags?: string[];
|
| 67 |
+
/**
|
| 68 |
+
* Will search for models that have one of the inference providers in the list.
|
| 69 |
+
*/
|
| 70 |
+
inferenceProviders?: string[];
|
| 71 |
+
/**
|
| 72 |
+
* Will search for models that support at least one of those local apps (eg "lmstudio", "mlx-lm", ...)
|
| 73 |
+
*/
|
| 74 |
+
apps?: string[];
|
| 75 |
+
};
|
| 76 |
+
hubUrl?: string;
|
| 77 |
+
additionalFields?: T[];
|
| 78 |
+
/**
|
| 79 |
+
* Set to limit the number of models returned.
|
| 80 |
+
*/
|
| 81 |
+
limit?: number;
|
| 82 |
+
/**
|
| 83 |
+
* Sort models by a specific field.
|
| 84 |
+
*/
|
| 85 |
+
sort?:
|
| 86 |
+
| "createdAt"
|
| 87 |
+
| "downloads"
|
| 88 |
+
| "likes"
|
| 89 |
+
| "lastModified"
|
| 90 |
+
| "likes30d"
|
| 91 |
+
| "trendingScore"
|
| 92 |
+
| "num_parameters"
|
| 93 |
+
| "mainSize"
|
| 94 |
+
| "id";
|
| 95 |
+
/**
|
| 96 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 97 |
+
*/
|
| 98 |
+
fetch?: typeof fetch;
|
| 99 |
+
} & Partial<CredentialsParams>,
|
| 100 |
+
): AsyncGenerator<ModelEntry & Pick<ApiModelInfo, T>> {
|
| 101 |
+
const accessToken = params && checkCredentials(params);
|
| 102 |
+
let totalToFetch = params?.limit ?? Infinity;
|
| 103 |
+
const search = new URLSearchParams([
|
| 104 |
+
...Object.entries({
|
| 105 |
+
limit: String(Math.min(totalToFetch, 500)),
|
| 106 |
+
...(params?.search?.owner ? { author: params.search.owner } : undefined),
|
| 107 |
+
...(params?.search?.task ? { pipeline_tag: params.search.task } : undefined),
|
| 108 |
+
...(params?.search?.query ? { search: params.search.query } : undefined),
|
| 109 |
+
...(params?.search?.inferenceProviders
|
| 110 |
+
? { inference_provider: params.search.inferenceProviders.join(",") }
|
| 111 |
+
: undefined),
|
| 112 |
+
...(params?.search?.apps ? { apps: params.search.apps.join(",") } : undefined),
|
| 113 |
+
...(params?.sort ? { sort: params.sort } : undefined),
|
| 114 |
+
}),
|
| 115 |
+
...(params?.search?.tags?.map((tag) => ["filter", tag]) ?? []),
|
| 116 |
+
...MODEL_EXPAND_KEYS.map((val) => ["expand", val] satisfies [string, string]),
|
| 117 |
+
...(params?.additionalFields?.map((val) => ["expand", val] satisfies [string, string]) ?? []),
|
| 118 |
+
]).toString();
|
| 119 |
+
let url: string | undefined = `${params?.hubUrl || HUB_URL}/api/models?${search}`;
|
| 120 |
+
|
| 121 |
+
while (url) {
|
| 122 |
+
const res: Response = await (params?.fetch ?? fetch)(url, {
|
| 123 |
+
headers: {
|
| 124 |
+
accept: "application/json",
|
| 125 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
|
| 126 |
+
},
|
| 127 |
+
});
|
| 128 |
+
|
| 129 |
+
if (!res.ok) {
|
| 130 |
+
throw await createApiError(res);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
const items: ApiModelInfo[] = await res.json();
|
| 134 |
+
|
| 135 |
+
for (const item of items) {
|
| 136 |
+
// Handle inferenceProviderMapping normalization
|
| 137 |
+
const normalizedItem = { ...item };
|
| 138 |
+
if (
|
| 139 |
+
(params?.additionalFields as string[])?.includes("inferenceProviderMapping") &&
|
| 140 |
+
item.inferenceProviderMapping
|
| 141 |
+
) {
|
| 142 |
+
normalizedItem.inferenceProviderMapping = normalizeInferenceProviderMapping(
|
| 143 |
+
item.id,
|
| 144 |
+
item.inferenceProviderMapping,
|
| 145 |
+
);
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
yield {
|
| 149 |
+
...(params?.additionalFields && pick(normalizedItem, params.additionalFields)),
|
| 150 |
+
id: item._id,
|
| 151 |
+
name: item.id,
|
| 152 |
+
private: item.private,
|
| 153 |
+
task: item.pipeline_tag,
|
| 154 |
+
downloads: item.downloads,
|
| 155 |
+
gated: item.gated,
|
| 156 |
+
likes: item.likes,
|
| 157 |
+
updatedAt: new Date(item.lastModified),
|
| 158 |
+
} as ModelEntry & Pick<ApiModelInfo, T>;
|
| 159 |
+
totalToFetch--;
|
| 160 |
+
|
| 161 |
+
if (totalToFetch <= 0) {
|
| 162 |
+
return;
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
const linkHeader = res.headers.get("Link");
|
| 167 |
+
|
| 168 |
+
url = linkHeader ? parseLinkHeader(linkHeader).next : undefined;
|
| 169 |
+
// Could update url to reduce the limit if we don't need the whole 500 of the next batch.
|
| 170 |
+
}
|
| 171 |
+
}
|
node_modules/@huggingface/hub/src/lib/list-spaces.spec.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import type { SpaceEntry } from "./list-spaces";
|
| 3 |
+
import { listSpaces } from "./list-spaces";
|
| 4 |
+
|
| 5 |
+
describe("listSpaces", () => {
|
| 6 |
+
it("should list spaces for Microsoft", async () => {
|
| 7 |
+
const results: SpaceEntry[] = [];
|
| 8 |
+
|
| 9 |
+
for await (const entry of listSpaces({
|
| 10 |
+
search: { owner: "microsoft" },
|
| 11 |
+
additionalFields: ["subdomain"],
|
| 12 |
+
})) {
|
| 13 |
+
if (entry.name !== "microsoft/visual_chatgpt") {
|
| 14 |
+
continue;
|
| 15 |
+
}
|
| 16 |
+
if (typeof entry.likes === "number") {
|
| 17 |
+
entry.likes = 0;
|
| 18 |
+
}
|
| 19 |
+
if (entry.updatedAt instanceof Date && !isNaN(entry.updatedAt.getTime())) {
|
| 20 |
+
entry.updatedAt = new Date(0);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
results.push(entry);
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
results.sort((a, b) => a.id.localeCompare(b.id));
|
| 27 |
+
|
| 28 |
+
expect(results).deep.equal([
|
| 29 |
+
{
|
| 30 |
+
id: "6409a392bbc73d022c58c980",
|
| 31 |
+
name: "microsoft/visual_chatgpt",
|
| 32 |
+
private: false,
|
| 33 |
+
likes: 0,
|
| 34 |
+
sdk: "gradio",
|
| 35 |
+
subdomain: "microsoft-visual-chatgpt",
|
| 36 |
+
updatedAt: new Date(0),
|
| 37 |
+
},
|
| 38 |
+
]);
|
| 39 |
+
});
|
| 40 |
+
});
|
node_modules/@huggingface/hub/src/lib/list-spaces.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiSpaceInfo } from "../types/api/api-space";
|
| 4 |
+
import type { CredentialsParams, SpaceSdk } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { parseLinkHeader } from "../utils/parseLinkHeader";
|
| 7 |
+
import { pick } from "../utils/pick";
|
| 8 |
+
|
| 9 |
+
export const SPACE_EXPAND_KEYS = [
|
| 10 |
+
"sdk",
|
| 11 |
+
"likes",
|
| 12 |
+
"private",
|
| 13 |
+
"lastModified",
|
| 14 |
+
] as const satisfies readonly (keyof ApiSpaceInfo)[];
|
| 15 |
+
export const SPACE_EXPANDABLE_KEYS = [
|
| 16 |
+
"author",
|
| 17 |
+
"cardData",
|
| 18 |
+
"datasets",
|
| 19 |
+
"disabled",
|
| 20 |
+
"gitalyUid",
|
| 21 |
+
"lastModified",
|
| 22 |
+
"createdAt",
|
| 23 |
+
"likes",
|
| 24 |
+
"private",
|
| 25 |
+
"runtime",
|
| 26 |
+
"sdk",
|
| 27 |
+
// "siblings",
|
| 28 |
+
"sha",
|
| 29 |
+
"subdomain",
|
| 30 |
+
"tags",
|
| 31 |
+
"models",
|
| 32 |
+
] as const satisfies readonly (keyof ApiSpaceInfo)[];
|
| 33 |
+
|
| 34 |
+
export interface SpaceEntry {
|
| 35 |
+
id: string;
|
| 36 |
+
name: string;
|
| 37 |
+
sdk?: SpaceSdk;
|
| 38 |
+
likes: number;
|
| 39 |
+
private: boolean;
|
| 40 |
+
updatedAt: Date;
|
| 41 |
+
// Use additionalFields to fetch the fields from ApiSpaceInfo
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
export async function* listSpaces<
|
| 45 |
+
const T extends Exclude<(typeof SPACE_EXPANDABLE_KEYS)[number], (typeof SPACE_EXPAND_KEYS)[number]> = never,
|
| 46 |
+
>(
|
| 47 |
+
params?: {
|
| 48 |
+
search?: {
|
| 49 |
+
/**
|
| 50 |
+
* Will search in the space name for matches
|
| 51 |
+
*/
|
| 52 |
+
query?: string;
|
| 53 |
+
owner?: string;
|
| 54 |
+
tags?: string[];
|
| 55 |
+
};
|
| 56 |
+
hubUrl?: string;
|
| 57 |
+
/**
|
| 58 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 59 |
+
*/
|
| 60 |
+
fetch?: typeof fetch;
|
| 61 |
+
/**
|
| 62 |
+
* Additional fields to fetch from huggingface.co.
|
| 63 |
+
*/
|
| 64 |
+
additionalFields?: T[];
|
| 65 |
+
/**
|
| 66 |
+
* Sort spaces by a specific field.
|
| 67 |
+
*/
|
| 68 |
+
sort?: "createdAt" | "downloads" | "likes" | "lastModified" | "likes30d" | "trendingScore" | "mainSize" | "id";
|
| 69 |
+
} & Partial<CredentialsParams>,
|
| 70 |
+
): AsyncGenerator<SpaceEntry & Pick<ApiSpaceInfo, T>> {
|
| 71 |
+
const accessToken = params && checkCredentials(params);
|
| 72 |
+
const search = new URLSearchParams([
|
| 73 |
+
...Object.entries({
|
| 74 |
+
limit: "500",
|
| 75 |
+
...(params?.search?.owner ? { author: params.search.owner } : undefined),
|
| 76 |
+
...(params?.search?.query ? { search: params.search.query } : undefined),
|
| 77 |
+
...(params?.sort ? { sort: params.sort } : undefined),
|
| 78 |
+
}),
|
| 79 |
+
...(params?.search?.tags?.map((tag) => ["filter", tag]) ?? []),
|
| 80 |
+
...[...SPACE_EXPAND_KEYS, ...(params?.additionalFields ?? [])].map(
|
| 81 |
+
(val) => ["expand", val] satisfies [string, string],
|
| 82 |
+
),
|
| 83 |
+
]).toString();
|
| 84 |
+
let url: string | undefined = `${params?.hubUrl || HUB_URL}/api/spaces?${search}`;
|
| 85 |
+
|
| 86 |
+
while (url) {
|
| 87 |
+
const res: Response = await (params?.fetch ?? fetch)(url, {
|
| 88 |
+
headers: {
|
| 89 |
+
accept: "application/json",
|
| 90 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
|
| 91 |
+
},
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
if (!res.ok) {
|
| 95 |
+
throw await createApiError(res);
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
const items: ApiSpaceInfo[] = await res.json();
|
| 99 |
+
|
| 100 |
+
for (const item of items) {
|
| 101 |
+
yield {
|
| 102 |
+
...(params?.additionalFields && pick(item, params.additionalFields)),
|
| 103 |
+
id: item._id,
|
| 104 |
+
name: item.id,
|
| 105 |
+
sdk: item.sdk,
|
| 106 |
+
likes: item.likes,
|
| 107 |
+
private: item.private,
|
| 108 |
+
updatedAt: new Date(item.lastModified),
|
| 109 |
+
} as SpaceEntry & Pick<ApiSpaceInfo, T>;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
const linkHeader = res.headers.get("Link");
|
| 113 |
+
|
| 114 |
+
url = linkHeader ? parseLinkHeader(linkHeader).next : undefined;
|
| 115 |
+
}
|
| 116 |
+
}
|
node_modules/@huggingface/hub/src/lib/model-info.spec.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { modelInfo } from "./model-info";
|
| 3 |
+
import type { ModelEntry } from "./list-models";
|
| 4 |
+
import type { ApiModelInfo } from "../types/api/api-model";
|
| 5 |
+
|
| 6 |
+
describe("modelInfo", () => {
|
| 7 |
+
it("should return the model info", async () => {
|
| 8 |
+
const info = await modelInfo({
|
| 9 |
+
name: "openai-community/gpt2",
|
| 10 |
+
});
|
| 11 |
+
expect(info).toEqual({
|
| 12 |
+
id: "621ffdc036468d709f17434d",
|
| 13 |
+
downloads: expect.any(Number),
|
| 14 |
+
gated: false,
|
| 15 |
+
name: "openai-community/gpt2",
|
| 16 |
+
updatedAt: expect.any(Date),
|
| 17 |
+
likes: expect.any(Number),
|
| 18 |
+
task: "text-generation",
|
| 19 |
+
private: false,
|
| 20 |
+
});
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
it("should return the model info with author", async () => {
|
| 24 |
+
const info: ModelEntry & Pick<ApiModelInfo, "author"> = await modelInfo({
|
| 25 |
+
name: "openai-community/gpt2",
|
| 26 |
+
additionalFields: ["author"],
|
| 27 |
+
});
|
| 28 |
+
expect(info).toEqual({
|
| 29 |
+
id: "621ffdc036468d709f17434d",
|
| 30 |
+
downloads: expect.any(Number),
|
| 31 |
+
author: "openai-community",
|
| 32 |
+
gated: false,
|
| 33 |
+
name: "openai-community/gpt2",
|
| 34 |
+
updatedAt: expect.any(Date),
|
| 35 |
+
likes: expect.any(Number),
|
| 36 |
+
task: "text-generation",
|
| 37 |
+
private: false,
|
| 38 |
+
});
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
it("should return the model info for a specific revision", async () => {
|
| 42 |
+
const info: ModelEntry & Pick<ApiModelInfo, "sha"> = await modelInfo({
|
| 43 |
+
name: "openai-community/gpt2",
|
| 44 |
+
additionalFields: ["sha"],
|
| 45 |
+
revision: "f27b190eeac4c2302d24068eabf5e9d6044389ae",
|
| 46 |
+
});
|
| 47 |
+
expect(info).toEqual({
|
| 48 |
+
id: "621ffdc036468d709f17434d",
|
| 49 |
+
downloads: expect.any(Number),
|
| 50 |
+
gated: false,
|
| 51 |
+
name: "openai-community/gpt2",
|
| 52 |
+
updatedAt: expect.any(Date),
|
| 53 |
+
likes: expect.any(Number),
|
| 54 |
+
task: "text-generation",
|
| 55 |
+
private: false,
|
| 56 |
+
sha: "f27b190eeac4c2302d24068eabf5e9d6044389ae",
|
| 57 |
+
});
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it("should return model info deepseek-ai models with inference provider mapping", async () => {
|
| 61 |
+
const info = await modelInfo({
|
| 62 |
+
name: "deepseek-ai/DeepSeek-R1-0528",
|
| 63 |
+
additionalFields: ["inferenceProviderMapping"],
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
expect(info.inferenceProviderMapping).toBeDefined();
|
| 67 |
+
expect(info.inferenceProviderMapping).toBeInstanceOf(Array);
|
| 68 |
+
expect(info.inferenceProviderMapping?.length).toBeGreaterThan(0);
|
| 69 |
+
info.inferenceProviderMapping?.forEach((item) => {
|
| 70 |
+
expect(item).toHaveProperty("provider");
|
| 71 |
+
expect(item).toHaveProperty("hfModelId", "deepseek-ai/DeepSeek-R1-0528");
|
| 72 |
+
expect(item).toHaveProperty("providerId");
|
| 73 |
+
});
|
| 74 |
+
});
|
| 75 |
+
});
|
node_modules/@huggingface/hub/src/lib/model-info.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiModelInfo } from "../types/api/api-model";
|
| 4 |
+
import type { CredentialsParams } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { pick } from "../utils/pick";
|
| 7 |
+
import { normalizeInferenceProviderMapping } from "../utils/normalizeInferenceProviderMapping";
|
| 8 |
+
import { MODEL_EXPAND_KEYS, type MODEL_EXPANDABLE_KEYS, type ModelEntry } from "./list-models";
|
| 9 |
+
|
| 10 |
+
export async function modelInfo<
|
| 11 |
+
const T extends Exclude<(typeof MODEL_EXPANDABLE_KEYS)[number], (typeof MODEL_EXPAND_KEYS)[number]> = never,
|
| 12 |
+
>(
|
| 13 |
+
params: {
|
| 14 |
+
name: string;
|
| 15 |
+
hubUrl?: string;
|
| 16 |
+
additionalFields?: T[];
|
| 17 |
+
/**
|
| 18 |
+
* An optional Git revision id which can be a branch name, a tag, or a commit hash.
|
| 19 |
+
*/
|
| 20 |
+
revision?: string;
|
| 21 |
+
/**
|
| 22 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 23 |
+
*/
|
| 24 |
+
fetch?: typeof fetch;
|
| 25 |
+
} & Partial<CredentialsParams>,
|
| 26 |
+
): Promise<ModelEntry & Pick<ApiModelInfo, T>> {
|
| 27 |
+
const accessToken = params && checkCredentials(params);
|
| 28 |
+
|
| 29 |
+
const search = new URLSearchParams([
|
| 30 |
+
...MODEL_EXPAND_KEYS.map((val) => ["expand", val] satisfies [string, string]),
|
| 31 |
+
...(params?.additionalFields?.map((val) => ["expand", val] satisfies [string, string]) ?? []),
|
| 32 |
+
]).toString();
|
| 33 |
+
|
| 34 |
+
const response = await (params.fetch || fetch)(
|
| 35 |
+
`${params?.hubUrl || HUB_URL}/api/models/${params.name}/revision/${encodeURIComponent(
|
| 36 |
+
params.revision ?? "HEAD",
|
| 37 |
+
)}?${search.toString()}`,
|
| 38 |
+
{
|
| 39 |
+
headers: {
|
| 40 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
| 41 |
+
},
|
| 42 |
+
},
|
| 43 |
+
);
|
| 44 |
+
|
| 45 |
+
if (!response.ok) {
|
| 46 |
+
throw await createApiError(response);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
const data = await response.json();
|
| 50 |
+
|
| 51 |
+
// Handle inferenceProviderMapping normalization
|
| 52 |
+
const normalizedData = { ...data };
|
| 53 |
+
if ((params?.additionalFields as string[])?.includes("inferenceProviderMapping") && data.inferenceProviderMapping) {
|
| 54 |
+
normalizedData.inferenceProviderMapping = normalizeInferenceProviderMapping(data.id, data.inferenceProviderMapping);
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
return {
|
| 58 |
+
...(params?.additionalFields && pick(normalizedData, params.additionalFields)),
|
| 59 |
+
id: data._id,
|
| 60 |
+
name: data.id,
|
| 61 |
+
private: data.private,
|
| 62 |
+
task: data.pipeline_tag,
|
| 63 |
+
downloads: data.downloads,
|
| 64 |
+
gated: data.gated,
|
| 65 |
+
likes: data.likes,
|
| 66 |
+
updatedAt: new Date(data.lastModified),
|
| 67 |
+
} as ModelEntry & Pick<ApiModelInfo, T>;
|
| 68 |
+
}
|
node_modules/@huggingface/hub/src/lib/oauth-handle-redirect.spec.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { TEST_COOKIE, TEST_HUB_URL } from "../test/consts";
|
| 3 |
+
import { oauthLoginUrl } from "./oauth-login-url";
|
| 4 |
+
import { oauthHandleRedirect } from "./oauth-handle-redirect";
|
| 5 |
+
|
| 6 |
+
describe("oauthHandleRedirect", () => {
|
| 7 |
+
it("should work", async () => {
|
| 8 |
+
const localStorage = {
|
| 9 |
+
nonce: undefined,
|
| 10 |
+
codeVerifier: undefined,
|
| 11 |
+
};
|
| 12 |
+
const url = await oauthLoginUrl({
|
| 13 |
+
clientId: "dummy-app",
|
| 14 |
+
redirectUrl: "http://localhost:3000",
|
| 15 |
+
localStorage,
|
| 16 |
+
scopes: "openid profile email",
|
| 17 |
+
hubUrl: TEST_HUB_URL,
|
| 18 |
+
});
|
| 19 |
+
const resp = await fetch(url, {
|
| 20 |
+
method: "POST",
|
| 21 |
+
headers: {
|
| 22 |
+
Cookie: `token=${TEST_COOKIE}`,
|
| 23 |
+
},
|
| 24 |
+
redirect: "manual",
|
| 25 |
+
});
|
| 26 |
+
if (resp.status !== 303) {
|
| 27 |
+
throw new Error(`Failed to fetch url ${url}: ${resp.status} ${resp.statusText}`);
|
| 28 |
+
}
|
| 29 |
+
const location = resp.headers.get("Location");
|
| 30 |
+
if (!location) {
|
| 31 |
+
throw new Error(`No location header in response`);
|
| 32 |
+
}
|
| 33 |
+
const result = await oauthHandleRedirect({
|
| 34 |
+
redirectedUrl: location,
|
| 35 |
+
codeVerifier: localStorage.codeVerifier,
|
| 36 |
+
nonce: localStorage.nonce,
|
| 37 |
+
hubUrl: TEST_HUB_URL,
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
if (!result) {
|
| 41 |
+
throw new Error("Expected result to be defined");
|
| 42 |
+
}
|
| 43 |
+
expect(result.accessToken).toEqual(expect.any(String));
|
| 44 |
+
expect(result.accessTokenExpiresAt).toBeInstanceOf(Date);
|
| 45 |
+
expect(result.accessTokenExpiresAt.getTime()).toBeGreaterThan(Date.now());
|
| 46 |
+
expect(result.scope).toEqual(expect.any(String));
|
| 47 |
+
expect(result.userInfo).toEqual({
|
| 48 |
+
sub: "62f264b9f3c90f4b6514a269",
|
| 49 |
+
name: "@huggingface/hub CI bot",
|
| 50 |
+
preferred_username: "hub.js",
|
| 51 |
+
email_verified: true,
|
| 52 |
+
email: "eliott@huggingface.co",
|
| 53 |
+
isPro: false,
|
| 54 |
+
picture: "https://hub-ci.huggingface.co/avatars/934b830e9fdaa879487852f79eef7165.svg",
|
| 55 |
+
profile: "https://hub-ci.huggingface.co/hub.js",
|
| 56 |
+
website: "https://github.com/huggingface/hub.js",
|
| 57 |
+
orgs: [],
|
| 58 |
+
});
|
| 59 |
+
});
|
| 60 |
+
});
|
node_modules/@huggingface/hub/src/lib/oauth-handle-redirect.ts
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
|
| 4 |
+
export interface UserInfo {
|
| 5 |
+
/**
|
| 6 |
+
* OpenID Connect field. Unique identifier for the user, even in case of rename.
|
| 7 |
+
*/
|
| 8 |
+
sub: string;
|
| 9 |
+
/**
|
| 10 |
+
* OpenID Connect field. The user's full name.
|
| 11 |
+
*/
|
| 12 |
+
name: string;
|
| 13 |
+
/**
|
| 14 |
+
* OpenID Connect field. The user's username.
|
| 15 |
+
*/
|
| 16 |
+
preferred_username: string;
|
| 17 |
+
/**
|
| 18 |
+
* OpenID Connect field, available if scope "email" was granted.
|
| 19 |
+
*/
|
| 20 |
+
email_verified?: boolean;
|
| 21 |
+
/**
|
| 22 |
+
* OpenID Connect field, available if scope "email" was granted.
|
| 23 |
+
*/
|
| 24 |
+
email?: string;
|
| 25 |
+
/**
|
| 26 |
+
* OpenID Connect field. The user's profile picture URL.
|
| 27 |
+
*/
|
| 28 |
+
picture: string;
|
| 29 |
+
/**
|
| 30 |
+
* OpenID Connect field. The user's profile URL.
|
| 31 |
+
*/
|
| 32 |
+
profile: string;
|
| 33 |
+
/**
|
| 34 |
+
* OpenID Connect field. The user's website URL.
|
| 35 |
+
*/
|
| 36 |
+
website?: string;
|
| 37 |
+
|
| 38 |
+
/**
|
| 39 |
+
* Hugging Face field. Whether the user is a pro user.
|
| 40 |
+
*/
|
| 41 |
+
isPro: boolean;
|
| 42 |
+
/**
|
| 43 |
+
* Hugging Face field. Whether the user has a payment method set up. Needs "read-billing" scope.
|
| 44 |
+
*/
|
| 45 |
+
canPay?: boolean;
|
| 46 |
+
/**
|
| 47 |
+
* Hugging Face field. The user's orgs
|
| 48 |
+
*/
|
| 49 |
+
orgs?: Array<{
|
| 50 |
+
/**
|
| 51 |
+
* OpenID Connect field. Unique identifier for the org.
|
| 52 |
+
*/
|
| 53 |
+
sub: string;
|
| 54 |
+
/**
|
| 55 |
+
* OpenID Connect field. The org's full name.
|
| 56 |
+
*/
|
| 57 |
+
name: string;
|
| 58 |
+
/**
|
| 59 |
+
* OpenID Connect field. The org's username.
|
| 60 |
+
*/
|
| 61 |
+
preferred_username: string;
|
| 62 |
+
/**
|
| 63 |
+
* OpenID Connect field. The org's profile picture URL.
|
| 64 |
+
*/
|
| 65 |
+
picture: string;
|
| 66 |
+
|
| 67 |
+
/**
|
| 68 |
+
* Hugging Face field. The org's plan (e.g., "enterprise", "team").
|
| 69 |
+
*/
|
| 70 |
+
plan?: string;
|
| 71 |
+
/**
|
| 72 |
+
* Hugging Face field. Whether the org has a payment method set up. Needs "read-billing" scope, and the user needs to approve access to the org in the OAuth page.
|
| 73 |
+
*/
|
| 74 |
+
canPay?: boolean;
|
| 75 |
+
/**
|
| 76 |
+
* Hugging Face field. The user's role in the org. The user needs to approve access to the org in the OAuth page.
|
| 77 |
+
*/
|
| 78 |
+
roleInOrg?: string;
|
| 79 |
+
/**
|
| 80 |
+
* @deprecated Use securityRestrictions instead with "sso"
|
| 81 |
+
* HuggingFace field. When the user granted the oauth app access to the org, but didn't complete SSO.
|
| 82 |
+
*
|
| 83 |
+
* Should never happen directly after the oauth flow.
|
| 84 |
+
*/
|
| 85 |
+
pendingSSO?: boolean;
|
| 86 |
+
/**
|
| 87 |
+
* @deprecated Use securityRestrictions instead with "mfa"
|
| 88 |
+
*
|
| 89 |
+
* HuggingFace field. When the user granted the oauth app access to the org, but didn't complete MFA.
|
| 90 |
+
*
|
| 91 |
+
* Should never happen directly after the oauth flow.
|
| 92 |
+
*/
|
| 93 |
+
missingMFA?: boolean;
|
| 94 |
+
/**
|
| 95 |
+
* HuggingFace field. When the user granted the oauth app access to the org, but didn't complete following security restrictions.
|
| 96 |
+
*
|
| 97 |
+
* Should never happen directly after the oauth flow.
|
| 98 |
+
*/
|
| 99 |
+
securityRestrictions?: ("mfa" | "sso" | "ip" | "token-policy")[];
|
| 100 |
+
}>;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
export interface OAuthResult {
|
| 104 |
+
accessToken: string;
|
| 105 |
+
accessTokenExpiresAt: Date;
|
| 106 |
+
userInfo: UserInfo;
|
| 107 |
+
/**
|
| 108 |
+
* State passed to the OAuth provider in the original request to the OAuth provider.
|
| 109 |
+
*/
|
| 110 |
+
state?: string;
|
| 111 |
+
/**
|
| 112 |
+
* Granted scope
|
| 113 |
+
*/
|
| 114 |
+
scope: string;
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/**
|
| 118 |
+
* To call after the OAuth provider redirects back to the app.
|
| 119 |
+
*
|
| 120 |
+
* There is also a helper function {@link oauthHandleRedirectIfPresent}, which will call `oauthHandleRedirect` if the URL contains an oauth code
|
| 121 |
+
* in the query parameters and return `false` otherwise.
|
| 122 |
+
*/
|
| 123 |
+
export async function oauthHandleRedirect(opts?: {
|
| 124 |
+
/**
|
| 125 |
+
* The URL of the hub. Defaults to {@link HUB_URL}.
|
| 126 |
+
*/
|
| 127 |
+
hubUrl?: string;
|
| 128 |
+
/**
|
| 129 |
+
* The URL to analyze.
|
| 130 |
+
*
|
| 131 |
+
* @default window.location.href
|
| 132 |
+
*/
|
| 133 |
+
redirectedUrl?: string;
|
| 134 |
+
/**
|
| 135 |
+
* nonce generated by oauthLoginUrl
|
| 136 |
+
*
|
| 137 |
+
* @default localStorage.getItem("huggingface.co:oauth:nonce")
|
| 138 |
+
*/
|
| 139 |
+
nonce?: string;
|
| 140 |
+
/**
|
| 141 |
+
* codeVerifier generated by oauthLoginUrl
|
| 142 |
+
*
|
| 143 |
+
* @default localStorage.getItem("huggingface.co:oauth:code_verifier")
|
| 144 |
+
*/
|
| 145 |
+
codeVerifier?: string;
|
| 146 |
+
}): Promise<OAuthResult> {
|
| 147 |
+
if (typeof window === "undefined" && !opts?.redirectedUrl) {
|
| 148 |
+
throw new Error("oauthHandleRedirect is only available in the browser, unless you provide redirectedUrl");
|
| 149 |
+
}
|
| 150 |
+
if (typeof localStorage === "undefined" && (!opts?.nonce || !opts?.codeVerifier)) {
|
| 151 |
+
throw new Error(
|
| 152 |
+
"oauthHandleRedirect requires localStorage to be available, unless you provide nonce and codeVerifier",
|
| 153 |
+
);
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
const redirectedUrl = opts?.redirectedUrl ?? window.location.href;
|
| 157 |
+
const searchParams = (() => {
|
| 158 |
+
try {
|
| 159 |
+
return new URL(redirectedUrl).searchParams;
|
| 160 |
+
} catch (err) {
|
| 161 |
+
throw new Error("Failed to parse redirected URL: " + redirectedUrl);
|
| 162 |
+
}
|
| 163 |
+
})();
|
| 164 |
+
|
| 165 |
+
const [error, errorDescription] = [searchParams.get("error"), searchParams.get("error_description")];
|
| 166 |
+
|
| 167 |
+
if (error) {
|
| 168 |
+
throw new Error(`${error}: ${errorDescription}`);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
const code = searchParams.get("code");
|
| 172 |
+
const nonce = opts?.nonce ?? localStorage.getItem("huggingface.co:oauth:nonce");
|
| 173 |
+
|
| 174 |
+
if (!code) {
|
| 175 |
+
throw new Error("Missing oauth code from query parameters in redirected URL: " + redirectedUrl);
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
if (!nonce) {
|
| 179 |
+
throw new Error("Missing oauth nonce from localStorage");
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
const codeVerifier = opts?.codeVerifier ?? localStorage.getItem("huggingface.co:oauth:code_verifier");
|
| 183 |
+
|
| 184 |
+
if (!codeVerifier) {
|
| 185 |
+
throw new Error("Missing oauth code_verifier from localStorage");
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
const state = searchParams.get("state");
|
| 189 |
+
|
| 190 |
+
if (!state) {
|
| 191 |
+
throw new Error("Missing oauth state from query parameters in redirected URL");
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
let parsedState: { nonce: string; redirectUri: string; state?: string };
|
| 195 |
+
|
| 196 |
+
try {
|
| 197 |
+
parsedState = JSON.parse(state);
|
| 198 |
+
} catch {
|
| 199 |
+
throw new Error("Invalid oauth state in redirected URL, unable to parse JSON: " + state);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
if (parsedState.nonce !== nonce) {
|
| 203 |
+
throw new Error("Invalid oauth state in redirected URL");
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
const hubUrl = opts?.hubUrl || HUB_URL;
|
| 207 |
+
|
| 208 |
+
const openidConfigUrl = `${new URL(hubUrl).origin}/.well-known/openid-configuration`;
|
| 209 |
+
const openidConfigRes = await fetch(openidConfigUrl, {
|
| 210 |
+
headers: {
|
| 211 |
+
Accept: "application/json",
|
| 212 |
+
},
|
| 213 |
+
});
|
| 214 |
+
|
| 215 |
+
if (!openidConfigRes.ok) {
|
| 216 |
+
throw await createApiError(openidConfigRes);
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
const openidConfig: {
|
| 220 |
+
authorization_endpoint: string;
|
| 221 |
+
token_endpoint: string;
|
| 222 |
+
userinfo_endpoint: string;
|
| 223 |
+
} = await openidConfigRes.json();
|
| 224 |
+
|
| 225 |
+
const tokenRes = await fetch(openidConfig.token_endpoint, {
|
| 226 |
+
method: "POST",
|
| 227 |
+
headers: {
|
| 228 |
+
"Content-Type": "application/x-www-form-urlencoded",
|
| 229 |
+
},
|
| 230 |
+
body: new URLSearchParams({
|
| 231 |
+
grant_type: "authorization_code",
|
| 232 |
+
code,
|
| 233 |
+
redirect_uri: parsedState.redirectUri,
|
| 234 |
+
code_verifier: codeVerifier,
|
| 235 |
+
}).toString(),
|
| 236 |
+
});
|
| 237 |
+
|
| 238 |
+
if (!opts?.codeVerifier) {
|
| 239 |
+
localStorage.removeItem("huggingface.co:oauth:code_verifier");
|
| 240 |
+
}
|
| 241 |
+
if (!opts?.nonce) {
|
| 242 |
+
localStorage.removeItem("huggingface.co:oauth:nonce");
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
if (!tokenRes.ok) {
|
| 246 |
+
throw await createApiError(tokenRes);
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
const token: {
|
| 250 |
+
access_token: string;
|
| 251 |
+
expires_in: number;
|
| 252 |
+
id_token: string;
|
| 253 |
+
// refresh_token: string;
|
| 254 |
+
scope: string;
|
| 255 |
+
token_type: string;
|
| 256 |
+
} = await tokenRes.json();
|
| 257 |
+
|
| 258 |
+
const accessTokenExpiresAt = new Date(Date.now() + token.expires_in * 1000);
|
| 259 |
+
|
| 260 |
+
const userInfoRes = await fetch(openidConfig.userinfo_endpoint, {
|
| 261 |
+
headers: {
|
| 262 |
+
Authorization: `Bearer ${token.access_token}`,
|
| 263 |
+
},
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
if (!userInfoRes.ok) {
|
| 267 |
+
throw await createApiError(userInfoRes);
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
const userInfo: UserInfo = await userInfoRes.json();
|
| 271 |
+
|
| 272 |
+
return {
|
| 273 |
+
accessToken: token.access_token,
|
| 274 |
+
accessTokenExpiresAt,
|
| 275 |
+
userInfo: userInfo,
|
| 276 |
+
state: parsedState.state,
|
| 277 |
+
scope: token.scope,
|
| 278 |
+
};
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
// if (code && !nonce) {
|
| 282 |
+
// console.warn("Missing oauth nonce from localStorage");
|
| 283 |
+
// }
|
| 284 |
+
|
| 285 |
+
/**
|
| 286 |
+
* To call after the OAuth provider redirects back to the app.
|
| 287 |
+
*
|
| 288 |
+
* It returns false if the URL does not contain an oauth code in the query parameters, otherwise
|
| 289 |
+
* it calls {@link oauthHandleRedirect}.
|
| 290 |
+
*
|
| 291 |
+
* Depending on your app, you may want to call {@link oauthHandleRedirect} directly instead.
|
| 292 |
+
*/
|
| 293 |
+
export async function oauthHandleRedirectIfPresent(opts?: {
|
| 294 |
+
/**
|
| 295 |
+
* The URL of the hub. Defaults to {@link HUB_URL}.
|
| 296 |
+
*/
|
| 297 |
+
hubUrl?: string;
|
| 298 |
+
/**
|
| 299 |
+
* The URL to analyze.
|
| 300 |
+
*
|
| 301 |
+
* @default window.location.href
|
| 302 |
+
*/
|
| 303 |
+
redirectedUrl?: string;
|
| 304 |
+
/**
|
| 305 |
+
* nonce generated by oauthLoginUrl
|
| 306 |
+
*
|
| 307 |
+
* @default localStorage.getItem("huggingface.co:oauth:nonce")
|
| 308 |
+
*/
|
| 309 |
+
nonce?: string;
|
| 310 |
+
/**
|
| 311 |
+
* codeVerifier generated by oauthLoginUrl
|
| 312 |
+
*
|
| 313 |
+
* @default localStorage.getItem("huggingface.co:oauth:code_verifier")
|
| 314 |
+
*/
|
| 315 |
+
codeVerifier?: string;
|
| 316 |
+
}): Promise<OAuthResult | false> {
|
| 317 |
+
if (typeof window === "undefined" && !opts?.redirectedUrl) {
|
| 318 |
+
throw new Error("oauthHandleRedirect is only available in the browser, unless you provide redirectedUrl");
|
| 319 |
+
}
|
| 320 |
+
if (typeof localStorage === "undefined" && (!opts?.nonce || !opts?.codeVerifier)) {
|
| 321 |
+
throw new Error(
|
| 322 |
+
"oauthHandleRedirect requires localStorage to be available, unless you provide nonce and codeVerifier",
|
| 323 |
+
);
|
| 324 |
+
}
|
| 325 |
+
const searchParams = new URLSearchParams(opts?.redirectedUrl ?? window.location.search);
|
| 326 |
+
|
| 327 |
+
if (searchParams.has("error")) {
|
| 328 |
+
return oauthHandleRedirect(opts);
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
if (searchParams.has("code")) {
|
| 332 |
+
if (!localStorage.getItem("huggingface.co:oauth:nonce")) {
|
| 333 |
+
console.warn(
|
| 334 |
+
"Missing oauth nonce from localStorage. This can happen when the user refreshes the page after logging in, without changing the URL.",
|
| 335 |
+
);
|
| 336 |
+
return false;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
return oauthHandleRedirect(opts);
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
return false;
|
| 343 |
+
}
|
node_modules/@huggingface/hub/src/lib/oauth-login-url.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import { base64FromBytes } from "../utils/base64FromBytes";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Use "Sign in with Hub" to authenticate a user, and get oauth user info / access token.
|
| 7 |
+
*
|
| 8 |
+
* Returns an url to redirect to. After the user is redirected back to your app, call `oauthHandleRedirect` to get the oauth user info / access token.
|
| 9 |
+
*
|
| 10 |
+
* When called from inside a static Space with OAuth enabled, it will load the config from the space, otherwise you need to at least specify
|
| 11 |
+
* the client ID of your OAuth App.
|
| 12 |
+
*
|
| 13 |
+
* @example
|
| 14 |
+
* ```ts
|
| 15 |
+
* import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";
|
| 16 |
+
*
|
| 17 |
+
* const oauthResult = await oauthHandleRedirectIfPresent();
|
| 18 |
+
*
|
| 19 |
+
* if (!oauthResult) {
|
| 20 |
+
* // If the user is not logged in, redirect to the login page
|
| 21 |
+
* window.location.href = await oauthLoginUrl();
|
| 22 |
+
* }
|
| 23 |
+
*
|
| 24 |
+
* // You can use oauthResult.accessToken, oauthResult.accessTokenExpiresAt and oauthResult.userInfo
|
| 25 |
+
* console.log(oauthResult);
|
| 26 |
+
* ```
|
| 27 |
+
*
|
| 28 |
+
* (Theoretically, this function could be used to authenticate a user for any OAuth provider supporting PKCE and OpenID Connect by changing `hubUrl`,
|
| 29 |
+
* but it is currently only tested with the Hugging Face Hub.)
|
| 30 |
+
*/
|
| 31 |
+
export async function oauthLoginUrl(opts?: {
|
| 32 |
+
/**
|
| 33 |
+
* OAuth client ID.
|
| 34 |
+
*
|
| 35 |
+
* For static Spaces, you can omit this and it will be loaded from the Space config, as long as `hf_oauth: true` is present in the README.md's metadata.
|
| 36 |
+
* For other Spaces, it is available to the backend in the OAUTH_CLIENT_ID environment variable, as long as `hf_oauth: true` is present in the README.md's metadata.
|
| 37 |
+
*
|
| 38 |
+
* You can also create a Developer Application at https://huggingface.co/settings/connected-applications and use its client ID.
|
| 39 |
+
*/
|
| 40 |
+
clientId?: string;
|
| 41 |
+
hubUrl?: string;
|
| 42 |
+
/**
|
| 43 |
+
* OAuth scope, a list of space-separated scopes.
|
| 44 |
+
*
|
| 45 |
+
* For static Spaces, you can omit this and it will be loaded from the Space config, as long as `hf_oauth: true` is present in the README.md's metadata.
|
| 46 |
+
* For other Spaces, it is available to the backend in the OAUTH_SCOPES environment variable, as long as `hf_oauth: true` is present in the README.md's metadata.
|
| 47 |
+
*
|
| 48 |
+
* Defaults to "openid profile".
|
| 49 |
+
*
|
| 50 |
+
* You can also create a Developer Application at https://huggingface.co/settings/connected-applications and use its scopes.
|
| 51 |
+
*
|
| 52 |
+
* See https://huggingface.co/docs/hub/oauth for a list of available scopes.
|
| 53 |
+
*/
|
| 54 |
+
scopes?: string;
|
| 55 |
+
/**
|
| 56 |
+
* Redirect URI, defaults to the current URL.
|
| 57 |
+
*
|
| 58 |
+
* For Spaces, any URL within the Space is allowed.
|
| 59 |
+
*
|
| 60 |
+
* For Developer Applications, you can add any URL you want to the list of allowed redirect URIs at https://huggingface.co/settings/connected-applications.
|
| 61 |
+
*/
|
| 62 |
+
redirectUrl?: string;
|
| 63 |
+
/**
|
| 64 |
+
* State to pass to the OAuth provider, which will be returned in the call to `oauthLogin` after the redirect.
|
| 65 |
+
*/
|
| 66 |
+
state?: string;
|
| 67 |
+
/**
|
| 68 |
+
* If provided, will be filled with the code verifier and nonce used for the OAuth flow,
|
| 69 |
+
* instead of using localStorage.
|
| 70 |
+
*
|
| 71 |
+
* When calling {@link `oauthHandleRedirectIfPresent`} or {@link `oauthHandleRedirect`} you will need to provide the same values.
|
| 72 |
+
*/
|
| 73 |
+
localStorage?: {
|
| 74 |
+
codeVerifier?: string;
|
| 75 |
+
nonce?: string;
|
| 76 |
+
};
|
| 77 |
+
}): Promise<string> {
|
| 78 |
+
if (typeof window === "undefined" && (!opts?.redirectUrl || !opts?.clientId)) {
|
| 79 |
+
throw new Error("oauthLogin is only available in the browser, unless you provide clientId and redirectUrl");
|
| 80 |
+
}
|
| 81 |
+
if (typeof localStorage === "undefined" && !opts?.localStorage) {
|
| 82 |
+
throw new Error(
|
| 83 |
+
"oauthLogin requires localStorage to be available in the context, unless you provide a localStorage empty object as argument",
|
| 84 |
+
);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
const hubUrl = opts?.hubUrl || HUB_URL;
|
| 88 |
+
const openidConfigUrl = `${new URL(hubUrl).origin}/.well-known/openid-configuration`;
|
| 89 |
+
const openidConfigRes = await fetch(openidConfigUrl, {
|
| 90 |
+
headers: {
|
| 91 |
+
Accept: "application/json",
|
| 92 |
+
},
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
if (!openidConfigRes.ok) {
|
| 96 |
+
throw await createApiError(openidConfigRes);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
const opendidConfig: {
|
| 100 |
+
authorization_endpoint: string;
|
| 101 |
+
token_endpoint: string;
|
| 102 |
+
userinfo_endpoint: string;
|
| 103 |
+
} = await openidConfigRes.json();
|
| 104 |
+
|
| 105 |
+
const newNonce = globalThis.crypto.randomUUID();
|
| 106 |
+
// Two random UUIDs concatenated together, because min length is 43 and max length is 128
|
| 107 |
+
const newCodeVerifier = globalThis.crypto.randomUUID() + globalThis.crypto.randomUUID();
|
| 108 |
+
|
| 109 |
+
if (opts?.localStorage) {
|
| 110 |
+
if (opts.localStorage.codeVerifier !== undefined && opts.localStorage.codeVerifier !== null) {
|
| 111 |
+
throw new Error(
|
| 112 |
+
"localStorage.codeVerifier must be initially set to null or undefined, and will be filled by oauthLoginUrl",
|
| 113 |
+
);
|
| 114 |
+
}
|
| 115 |
+
if (opts.localStorage.nonce !== undefined && opts.localStorage.nonce !== null) {
|
| 116 |
+
throw new Error(
|
| 117 |
+
"localStorage.nonce must be initially set to null or undefined, and will be filled by oauthLoginUrl",
|
| 118 |
+
);
|
| 119 |
+
}
|
| 120 |
+
opts.localStorage.codeVerifier = newCodeVerifier;
|
| 121 |
+
opts.localStorage.nonce = newNonce;
|
| 122 |
+
} else {
|
| 123 |
+
localStorage.setItem("huggingface.co:oauth:nonce", newNonce);
|
| 124 |
+
localStorage.setItem("huggingface.co:oauth:code_verifier", newCodeVerifier);
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
const redirectUri = opts?.redirectUrl || (typeof window !== "undefined" ? window.location.href : undefined);
|
| 128 |
+
if (!redirectUri) {
|
| 129 |
+
throw new Error("Missing redirectUrl");
|
| 130 |
+
}
|
| 131 |
+
const state = JSON.stringify({
|
| 132 |
+
nonce: newNonce,
|
| 133 |
+
redirectUri,
|
| 134 |
+
state: opts?.state,
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
const variables: Record<string, string> | null =
|
| 138 |
+
// @ts-expect-error window.huggingface is defined inside static Spaces.
|
| 139 |
+
typeof window !== "undefined" ? (window.huggingface?.variables ?? null) : null;
|
| 140 |
+
|
| 141 |
+
const clientId = opts?.clientId || variables?.OAUTH_CLIENT_ID;
|
| 142 |
+
|
| 143 |
+
if (!clientId) {
|
| 144 |
+
if (variables) {
|
| 145 |
+
throw new Error("Missing clientId, please add hf_oauth: true to the README.md's metadata in your static Space");
|
| 146 |
+
}
|
| 147 |
+
throw new Error("Missing clientId");
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
const challenge = base64FromBytes(
|
| 151 |
+
new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(newCodeVerifier))),
|
| 152 |
+
)
|
| 153 |
+
.replace(/[+]/g, "-")
|
| 154 |
+
.replace(/[/]/g, "_")
|
| 155 |
+
.replace(/=/g, "");
|
| 156 |
+
|
| 157 |
+
return `${opendidConfig.authorization_endpoint}?${new URLSearchParams({
|
| 158 |
+
client_id: clientId,
|
| 159 |
+
scope: opts?.scopes || variables?.OAUTH_SCOPES || "openid profile",
|
| 160 |
+
response_type: "code",
|
| 161 |
+
redirect_uri: redirectUri,
|
| 162 |
+
state,
|
| 163 |
+
code_challenge: challenge,
|
| 164 |
+
code_challenge_method: "S256",
|
| 165 |
+
}).toString()}`;
|
| 166 |
+
}
|
node_modules/@huggingface/hub/src/lib/parse-safetensors-metadata.spec.ts
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe } from "vitest";
|
| 2 |
+
import { parseSafetensorsMetadata, parseSafetensorsShardFilename } from "./parse-safetensors-metadata";
|
| 3 |
+
import { sum } from "../utils/sum";
|
| 4 |
+
|
| 5 |
+
describe("parseSafetensorsMetadata", () => {
|
| 6 |
+
it("fetch info for single-file (with the default conventional filename)", async () => {
|
| 7 |
+
const parse = await parseSafetensorsMetadata({
|
| 8 |
+
repo: "google-bert/bert-base-uncased",
|
| 9 |
+
computeParametersCount: true,
|
| 10 |
+
revision: "86b5e0934494bd15c9632b12f734a8a67f723594",
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
assert(!parse.sharded);
|
| 14 |
+
assert.deepStrictEqual(parse.header.__metadata__, { format: "pt" });
|
| 15 |
+
|
| 16 |
+
// Example of one tensor (the header contains many tensors)
|
| 17 |
+
|
| 18 |
+
assert.deepStrictEqual(parse.header["bert.embeddings.LayerNorm.beta"], {
|
| 19 |
+
dtype: "F32",
|
| 20 |
+
shape: [768],
|
| 21 |
+
data_offsets: [0, 3072],
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
assert.deepStrictEqual(parse.parameterCount, { F32: 110_106_428 });
|
| 25 |
+
assert.deepStrictEqual(sum(Object.values(parse.parameterCount)), 110_106_428);
|
| 26 |
+
// total params = 110m
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
it("fetch info for sharded (with the default conventional filename)", async () => {
|
| 30 |
+
const parse = await parseSafetensorsMetadata({
|
| 31 |
+
repo: "bigscience/bloom",
|
| 32 |
+
computeParametersCount: true,
|
| 33 |
+
revision: "053d9cd9fbe814e091294f67fcfedb3397b954bb",
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
assert(parse.sharded);
|
| 37 |
+
|
| 38 |
+
assert.strictEqual(Object.keys(parse.headers).length, 72);
|
| 39 |
+
// This model has 72 shards!
|
| 40 |
+
|
| 41 |
+
// Example of one tensor inside one file
|
| 42 |
+
|
| 43 |
+
assert.deepStrictEqual(parse.headers["model_00012-of-00072.safetensors"]["h.10.input_layernorm.weight"], {
|
| 44 |
+
dtype: "BF16",
|
| 45 |
+
shape: [14336],
|
| 46 |
+
data_offsets: [3288649728, 3288678400],
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
assert.deepStrictEqual(parse.parameterCount, { BF16: 176_247_271_424 });
|
| 50 |
+
assert.deepStrictEqual(sum(Object.values(parse.parameterCount)), 176_247_271_424);
|
| 51 |
+
// total params = 176B
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
it("fetch info for single-file with multiple dtypes", async () => {
|
| 55 |
+
const parse = await parseSafetensorsMetadata({
|
| 56 |
+
repo: "roberta-base",
|
| 57 |
+
computeParametersCount: true,
|
| 58 |
+
revision: "e2da8e2f811d1448a5b465c236feacd80ffbac7b",
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
assert(!parse.sharded);
|
| 62 |
+
|
| 63 |
+
assert.deepStrictEqual(parse.parameterCount, { F32: 124_697_433, I64: 514 });
|
| 64 |
+
assert.deepStrictEqual(sum(Object.values(parse.parameterCount)), 124_697_947);
|
| 65 |
+
// total params = 124m
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
it("fetch info for single-file with file path", async () => {
|
| 69 |
+
const parse = await parseSafetensorsMetadata({
|
| 70 |
+
repo: "CompVis/stable-diffusion-v1-4",
|
| 71 |
+
computeParametersCount: true,
|
| 72 |
+
path: "unet/diffusion_pytorch_model.safetensors",
|
| 73 |
+
revision: "133a221b8aa7292a167afc5127cb63fb5005638b",
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
assert(!parse.sharded);
|
| 77 |
+
assert.deepStrictEqual(parse.header.__metadata__, { format: "pt" });
|
| 78 |
+
|
| 79 |
+
// Example of one tensor (the header contains many tensors)
|
| 80 |
+
|
| 81 |
+
assert.deepStrictEqual(parse.header["up_blocks.3.resnets.0.norm2.bias"], {
|
| 82 |
+
dtype: "F32",
|
| 83 |
+
shape: [320],
|
| 84 |
+
data_offsets: [3_409_382_416, 3_409_383_696],
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
assert.deepStrictEqual(parse.parameterCount, { F32: 859_520_964 });
|
| 88 |
+
assert.deepStrictEqual(sum(Object.values(parse.parameterCount)), 859_520_964);
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
it("fetch info for sharded with file path", async () => {
|
| 92 |
+
const parse = await parseSafetensorsMetadata({
|
| 93 |
+
repo: "Alignment-Lab-AI/ALAI-gemma-7b",
|
| 94 |
+
computeParametersCount: true,
|
| 95 |
+
path: "7b/1/model.safetensors.index.json",
|
| 96 |
+
revision: "37e307261fe97bbf8b2463d61dbdd1a10daa264c",
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
assert(parse.sharded);
|
| 100 |
+
|
| 101 |
+
assert.strictEqual(Object.keys(parse.headers).length, 4);
|
| 102 |
+
|
| 103 |
+
assert.deepStrictEqual(parse.headers["model-00004-of-00004.safetensors"]["model.layers.24.mlp.up_proj.weight"], {
|
| 104 |
+
dtype: "BF16",
|
| 105 |
+
shape: [24576, 3072],
|
| 106 |
+
data_offsets: [301996032, 452990976],
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
assert.deepStrictEqual(parse.parameterCount, { BF16: 8_537_680_896 });
|
| 110 |
+
assert.deepStrictEqual(sum(Object.values(parse.parameterCount)), 8_537_680_896);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it("fetch info for sharded, but get param count directly from metadata", async () => {
|
| 114 |
+
const parse = await parseSafetensorsMetadata({
|
| 115 |
+
repo: "hf-internal-testing/sharded-model-metadata-num-parameters",
|
| 116 |
+
computeParametersCount: true,
|
| 117 |
+
revision: "999395eb3db277f3d7a0393402b02486ca91cef8",
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
assert(parse.sharded);
|
| 121 |
+
assert.deepStrictEqual(parse.parameterTotal, 109_482_240);
|
| 122 |
+
// total params = 109M
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
it("fetch info for single-file, but get param count directly from metadata", async () => {
|
| 126 |
+
const parse = await parseSafetensorsMetadata({
|
| 127 |
+
repo: "hf-internal-testing/single-file-model",
|
| 128 |
+
computeParametersCount: true,
|
| 129 |
+
revision: "75fcd3fed0285ac7f1092897ff2aefdf24bf872e",
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
assert(!parse.sharded);
|
| 133 |
+
assert.deepStrictEqual(parse.parameterTotal, 109_482_240);
|
| 134 |
+
});
|
| 135 |
+
|
| 136 |
+
it("should detect sharded safetensors filename", async () => {
|
| 137 |
+
const safetensorsFilename = "model_00005-of-00072.safetensors"; // https://huggingface.co/bigscience/bloom/blob/4d8e28c67403974b0f17a4ac5992e4ba0b0dbb6f/model_00005-of-00072.safetensors
|
| 138 |
+
const safetensorsShardFileInfo = parseSafetensorsShardFilename(safetensorsFilename);
|
| 139 |
+
|
| 140 |
+
assert.strictEqual(safetensorsShardFileInfo?.prefix, "model_");
|
| 141 |
+
assert.strictEqual(safetensorsShardFileInfo?.basePrefix, "model");
|
| 142 |
+
assert.strictEqual(safetensorsShardFileInfo?.shard, "00005");
|
| 143 |
+
assert.strictEqual(safetensorsShardFileInfo?.total, "00072");
|
| 144 |
+
});
|
| 145 |
+
|
| 146 |
+
it("should detect sharded safetensors filename with 6 digits", async () => {
|
| 147 |
+
const safetensorsFilename = "model-00001-of-000163.safetensors"; // https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp/blob/main/model-00001-of-000163.safetensors
|
| 148 |
+
const safetensorsShardFileInfo = parseSafetensorsShardFilename(safetensorsFilename);
|
| 149 |
+
|
| 150 |
+
assert.strictEqual(safetensorsShardFileInfo?.prefix, "model-");
|
| 151 |
+
assert.strictEqual(safetensorsShardFileInfo?.basePrefix, "model");
|
| 152 |
+
assert.strictEqual(safetensorsShardFileInfo?.shard, "00001");
|
| 153 |
+
assert.strictEqual(safetensorsShardFileInfo?.total, "000163");
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
it("should support sub-byte data types", async () => {
|
| 157 |
+
const newDataTypes: Array<"F4" | "F6_E2M3" | "F6_E3M2" | "E8M0"> = ["F4", "F6_E2M3", "F6_E3M2", "E8M0"];
|
| 158 |
+
|
| 159 |
+
for (const dtype of newDataTypes) {
|
| 160 |
+
const tensorInfo = {
|
| 161 |
+
dtype,
|
| 162 |
+
shape: [1, 2],
|
| 163 |
+
data_offsets: [0, 1] as [number, number],
|
| 164 |
+
};
|
| 165 |
+
|
| 166 |
+
assert.ok(typeof tensorInfo.dtype === "string");
|
| 167 |
+
assert.ok(["F4", "F6_E2M3", "F6_E3M2", "E8M0"].includes(tensorInfo.dtype));
|
| 168 |
+
}
|
| 169 |
+
});
|
| 170 |
+
|
| 171 |
+
it("should handle parameter counting with sub-byte data types", () => {
|
| 172 |
+
const mockHeader = {
|
| 173 |
+
tensor_f4: {
|
| 174 |
+
dtype: "F4" as const,
|
| 175 |
+
shape: [10, 20],
|
| 176 |
+
data_offsets: [0, 100] as [number, number],
|
| 177 |
+
},
|
| 178 |
+
tensor_f6_e2m3: {
|
| 179 |
+
dtype: "F6_E2M3" as const,
|
| 180 |
+
shape: [5, 10],
|
| 181 |
+
data_offsets: [100, 150] as [number, number],
|
| 182 |
+
},
|
| 183 |
+
tensor_f6_e3m2: {
|
| 184 |
+
dtype: "F6_E3M2" as const,
|
| 185 |
+
shape: [8, 12],
|
| 186 |
+
data_offsets: [150, 246] as [number, number],
|
| 187 |
+
},
|
| 188 |
+
tensor_e8m0: {
|
| 189 |
+
dtype: "E8M0" as const,
|
| 190 |
+
shape: [4, 6],
|
| 191 |
+
data_offsets: [246, 270] as [number, number],
|
| 192 |
+
},
|
| 193 |
+
__metadata__: { format: "pt" },
|
| 194 |
+
};
|
| 195 |
+
|
| 196 |
+
const computeNumOfParamsByDtypeSingleFile = (header: typeof mockHeader) => {
|
| 197 |
+
const counter: Partial<Record<string, number>> = {};
|
| 198 |
+
const tensors = Object.fromEntries(Object.entries(header).filter(([key]) => key !== "__metadata__"));
|
| 199 |
+
|
| 200 |
+
for (const [, v] of Object.entries(tensors) as [
|
| 201 |
+
string,
|
| 202 |
+
{ dtype: string; shape: number[]; data_offsets: [number, number] },
|
| 203 |
+
][]) {
|
| 204 |
+
if (v.shape.length === 0) {
|
| 205 |
+
continue;
|
| 206 |
+
}
|
| 207 |
+
counter[v.dtype] = (counter[v.dtype] ?? 0) + v.shape.reduce((a: number, b: number) => a * b);
|
| 208 |
+
}
|
| 209 |
+
return counter;
|
| 210 |
+
};
|
| 211 |
+
|
| 212 |
+
const parameterCount = computeNumOfParamsByDtypeSingleFile(mockHeader);
|
| 213 |
+
|
| 214 |
+
assert.strictEqual(parameterCount.F4, 200);
|
| 215 |
+
assert.strictEqual(parameterCount.F6_E2M3, 50);
|
| 216 |
+
assert.strictEqual(parameterCount.F6_E3M2, 96);
|
| 217 |
+
assert.strictEqual(parameterCount.E8M0, 24);
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
it("fetch info for GPTQ quantized 8B model", async () => {
|
| 221 |
+
const parse = await parseSafetensorsMetadata({
|
| 222 |
+
repo: "RedHatAI/Meta-Llama-3.1-8B-Instruct-quantized.w4a16",
|
| 223 |
+
revision: "3921b6aee65496a708b0af456c964ceca7423193",
|
| 224 |
+
computeParametersCount: true,
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
const parameterCount = parse.parameterCount;
|
| 228 |
+
assert.ok(parameterCount);
|
| 229 |
+
assert.ok(parameterCount.I32);
|
| 230 |
+
assert.ok(parameterCount.F16);
|
| 231 |
+
assert.strictEqual(parameterCount.I32, 6_979_321_856);
|
| 232 |
+
assert.strictEqual(parameterCount.F16, 1_052_315_648);
|
| 233 |
+
|
| 234 |
+
const parameterCountTotal =
|
| 235 |
+
parse.parameterTotal ??
|
| 236 |
+
sum(
|
| 237 |
+
Object.entries(parameterCount)
|
| 238 |
+
.filter(([, value]) => typeof value === "number")
|
| 239 |
+
.map(([, value]) => value as number),
|
| 240 |
+
);
|
| 241 |
+
|
| 242 |
+
assert.strictEqual(parameterCountTotal, 8_031_637_504);
|
| 243 |
+
});
|
| 244 |
+
|
| 245 |
+
it("fetch info for openai/gpt-oss-20b (large sharded model)", async () => {
|
| 246 |
+
const parse = await parseSafetensorsMetadata({
|
| 247 |
+
repo: "openai/gpt-oss-20b",
|
| 248 |
+
computeParametersCount: true,
|
| 249 |
+
revision: "bbf09307421df45099c1e7dcbd64e3106ce5b403",
|
| 250 |
+
});
|
| 251 |
+
|
| 252 |
+
assert(parse.sharded);
|
| 253 |
+
|
| 254 |
+
assert.ok(Object.keys(parse.headers).length > 1);
|
| 255 |
+
assert.ok(parse.parameterCount);
|
| 256 |
+
|
| 257 |
+
const totalParams = parse.parameterTotal || sum(Object.values(parse.parameterCount));
|
| 258 |
+
|
| 259 |
+
assert.strictEqual(totalParams, 21_511_953_984); // 21.5B
|
| 260 |
+
|
| 261 |
+
assert.ok(parse.parameterCount.BF16 && parse.parameterCount.U8);
|
| 262 |
+
|
| 263 |
+
assert.strictEqual(Object.keys(parse.headers).length, 3);
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
it("should support FP4 and UE8 data types in type system", () => {
|
| 267 |
+
const newDataTypes: Array<"FP4" | "UE8"> = ["FP4", "UE8"];
|
| 268 |
+
|
| 269 |
+
for (const dtype of newDataTypes) {
|
| 270 |
+
const tensorInfo = {
|
| 271 |
+
dtype,
|
| 272 |
+
shape: [1, 2],
|
| 273 |
+
data_offsets: [0, 1] as [number, number],
|
| 274 |
+
};
|
| 275 |
+
|
| 276 |
+
assert.ok(typeof tensorInfo.dtype === "string");
|
| 277 |
+
assert.ok(["FP4", "UE8"].includes(tensorInfo.dtype));
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
const mockHeader = {
|
| 281 |
+
tensor_fp4: {
|
| 282 |
+
dtype: "FP4" as const,
|
| 283 |
+
shape: [100, 200],
|
| 284 |
+
data_offsets: [0, 5000] as [number, number],
|
| 285 |
+
},
|
| 286 |
+
tensor_ue8: {
|
| 287 |
+
dtype: "UE8" as const,
|
| 288 |
+
shape: [50, 100],
|
| 289 |
+
data_offsets: [5000, 10000] as [number, number],
|
| 290 |
+
},
|
| 291 |
+
__metadata__: { format: "pt" },
|
| 292 |
+
};
|
| 293 |
+
|
| 294 |
+
const computeNumOfParamsByDtypeSingleFile = (header: typeof mockHeader) => {
|
| 295 |
+
const counter: Partial<Record<string, number>> = {};
|
| 296 |
+
const tensors = Object.fromEntries(Object.entries(header).filter(([key]) => key !== "__metadata__"));
|
| 297 |
+
|
| 298 |
+
for (const [, v] of Object.entries(tensors) as [
|
| 299 |
+
string,
|
| 300 |
+
{ dtype: string; shape: number[]; data_offsets: [number, number] },
|
| 301 |
+
][]) {
|
| 302 |
+
if (v.shape.length === 0) {
|
| 303 |
+
continue;
|
| 304 |
+
}
|
| 305 |
+
counter[v.dtype] = (counter[v.dtype] ?? 0) + v.shape.reduce((a: number, b: number) => a * b);
|
| 306 |
+
}
|
| 307 |
+
return counter;
|
| 308 |
+
};
|
| 309 |
+
|
| 310 |
+
const parameterCount = computeNumOfParamsByDtypeSingleFile(mockHeader);
|
| 311 |
+
|
| 312 |
+
assert.strictEqual(parameterCount.FP4, 20000);
|
| 313 |
+
assert.strictEqual(parameterCount.UE8, 5000);
|
| 314 |
+
});
|
| 315 |
+
|
| 316 |
+
it("fetch info for moonshotai/Kimi-K2.5 (large index file >20MB)", async () => {
|
| 317 |
+
// This model has a ~23.5MB index file due to having many experts
|
| 318 |
+
const parse = await parseSafetensorsMetadata({
|
| 319 |
+
repo: "moonshotai/Kimi-K2.5",
|
| 320 |
+
revision: "2426b45b6af0da48d0dcce71bbce6225e5c73adc",
|
| 321 |
+
});
|
| 322 |
+
|
| 323 |
+
assert(parse.sharded);
|
| 324 |
+
assert.strictEqual(Object.keys(parse.headers).length, 64);
|
| 325 |
+
});
|
| 326 |
+
});
|
node_modules/@huggingface/hub/src/lib/parse-safetensors-metadata.ts
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams, RepoDesignation } from "../types/public";
|
| 2 |
+
import { omit } from "../utils/omit";
|
| 3 |
+
import { toRepoId } from "../utils/toRepoId";
|
| 4 |
+
import { typedEntries } from "../utils/typedEntries";
|
| 5 |
+
import { downloadFile } from "./download-file";
|
| 6 |
+
import { fileExists } from "./file-exists";
|
| 7 |
+
import { promisesQueue } from "../utils/promisesQueue";
|
| 8 |
+
import type { SetRequired } from "../vendor/type-fest/set-required";
|
| 9 |
+
|
| 10 |
+
export const SAFETENSORS_FILE = "model.safetensors";
|
| 11 |
+
export const SAFETENSORS_INDEX_FILE = "model.safetensors.index.json";
|
| 12 |
+
/// We advise model/library authors to use the filenames above for convention inside model repos,
|
| 13 |
+
/// but in some situations safetensors weights have different filenames.
|
| 14 |
+
export const RE_SAFETENSORS_FILE = /\.safetensors$/;
|
| 15 |
+
export const RE_SAFETENSORS_INDEX_FILE = /\.safetensors\.index\.json$/;
|
| 16 |
+
export const RE_SAFETENSORS_SHARD_FILE =
|
| 17 |
+
/^(?<prefix>(?<basePrefix>.*?)[_-])(?<shard>\d{5,6})-of-(?<total>\d{5,6})\.safetensors$/;
|
| 18 |
+
export interface SafetensorsShardFileInfo {
|
| 19 |
+
prefix: string;
|
| 20 |
+
basePrefix: string;
|
| 21 |
+
shard: string;
|
| 22 |
+
total: string;
|
| 23 |
+
}
|
| 24 |
+
export function parseSafetensorsShardFilename(filename: string): SafetensorsShardFileInfo | null {
|
| 25 |
+
const match = RE_SAFETENSORS_SHARD_FILE.exec(filename);
|
| 26 |
+
if (match && match.groups) {
|
| 27 |
+
return {
|
| 28 |
+
prefix: match.groups["prefix"],
|
| 29 |
+
basePrefix: match.groups["basePrefix"],
|
| 30 |
+
shard: match.groups["shard"],
|
| 31 |
+
total: match.groups["total"],
|
| 32 |
+
};
|
| 33 |
+
}
|
| 34 |
+
return null;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
const PARALLEL_DOWNLOADS = 20;
|
| 38 |
+
const MAX_HEADER_LENGTH = 25_000_000; // 25MB
|
| 39 |
+
const GPTQ_QWEIGHT_SUFFIX = "qweight";
|
| 40 |
+
|
| 41 |
+
class SafetensorParseError extends Error {}
|
| 42 |
+
|
| 43 |
+
type FileName = string;
|
| 44 |
+
|
| 45 |
+
export type TensorName = string;
|
| 46 |
+
export type Dtype =
|
| 47 |
+
| "F64"
|
| 48 |
+
| "F32"
|
| 49 |
+
| "F16"
|
| 50 |
+
| "F8_E4M3"
|
| 51 |
+
| "F8_E5M2"
|
| 52 |
+
| "E8M0"
|
| 53 |
+
| "F6_E3M2"
|
| 54 |
+
| "F6_E2M3"
|
| 55 |
+
| "F4"
|
| 56 |
+
| "FP4"
|
| 57 |
+
| "BF16"
|
| 58 |
+
| "I64"
|
| 59 |
+
| "I32"
|
| 60 |
+
| "I16"
|
| 61 |
+
| "I8"
|
| 62 |
+
| "U16"
|
| 63 |
+
| "U8"
|
| 64 |
+
| "UE8"
|
| 65 |
+
| "BOOL";
|
| 66 |
+
|
| 67 |
+
export interface TensorInfo {
|
| 68 |
+
dtype: Dtype;
|
| 69 |
+
shape: number[];
|
| 70 |
+
data_offsets: [number, number];
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
export type SafetensorsFileHeader = Record<TensorName, TensorInfo> & {
|
| 74 |
+
__metadata__: { total_parameters?: string | number } & Record<string, string>;
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
export interface SafetensorsIndexJson {
|
| 78 |
+
dtype?: string;
|
| 79 |
+
/// ^there's sometimes a dtype but it looks inconsistent.
|
| 80 |
+
metadata?: { total_parameters?: string | number } & Record<string, string>;
|
| 81 |
+
/// ^ why the naming inconsistency?
|
| 82 |
+
weight_map: Record<TensorName, FileName>;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
export type SafetensorsShardedHeaders = Record<FileName, SafetensorsFileHeader>;
|
| 86 |
+
|
| 87 |
+
export type SafetensorsParseFromRepo =
|
| 88 |
+
| {
|
| 89 |
+
sharded: false;
|
| 90 |
+
header: SafetensorsFileHeader;
|
| 91 |
+
parameterCount?: Partial<Record<Dtype, number>>;
|
| 92 |
+
parameterTotal?: number;
|
| 93 |
+
}
|
| 94 |
+
| {
|
| 95 |
+
sharded: true;
|
| 96 |
+
index: SafetensorsIndexJson;
|
| 97 |
+
headers: SafetensorsShardedHeaders;
|
| 98 |
+
parameterCount?: Partial<Record<Dtype, number>>;
|
| 99 |
+
parameterTotal?: number;
|
| 100 |
+
};
|
| 101 |
+
|
| 102 |
+
/**
|
| 103 |
+
* Fetches and parses model config.json
|
| 104 |
+
*/
|
| 105 |
+
async function fetchModelConfig(
|
| 106 |
+
params: {
|
| 107 |
+
repo: RepoDesignation;
|
| 108 |
+
revision?: string;
|
| 109 |
+
hubUrl?: string;
|
| 110 |
+
fetch?: typeof fetch;
|
| 111 |
+
} & Partial<CredentialsParams>,
|
| 112 |
+
): Promise<ModelConfig | null> {
|
| 113 |
+
try {
|
| 114 |
+
const configBlob = await downloadFile({
|
| 115 |
+
...params,
|
| 116 |
+
path: "config.json",
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
if (!configBlob) {
|
| 120 |
+
return null;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
const config = JSON.parse(await configBlob.text());
|
| 124 |
+
return config as ModelConfig;
|
| 125 |
+
} catch (error) {
|
| 126 |
+
// Config file might not exist or be inaccessible
|
| 127 |
+
return null;
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
async function parseSingleFile(
|
| 132 |
+
path: string,
|
| 133 |
+
params: {
|
| 134 |
+
repo: RepoDesignation;
|
| 135 |
+
revision?: string;
|
| 136 |
+
hubUrl?: string;
|
| 137 |
+
/**
|
| 138 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 139 |
+
*/
|
| 140 |
+
fetch?: typeof fetch;
|
| 141 |
+
} & Partial<CredentialsParams>,
|
| 142 |
+
): Promise<SafetensorsFileHeader> {
|
| 143 |
+
const blob = await downloadFile({ ...params, path });
|
| 144 |
+
|
| 145 |
+
if (!blob) {
|
| 146 |
+
throw new SafetensorParseError(`Failed to parse file ${path}: failed to fetch safetensors header length.`);
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
const bufLengthOfHeaderLE = await blob.slice(0, 8).arrayBuffer();
|
| 150 |
+
const lengthOfHeader = new DataView(bufLengthOfHeaderLE).getBigUint64(0, true);
|
| 151 |
+
// ^little-endian
|
| 152 |
+
if (lengthOfHeader <= 0) {
|
| 153 |
+
throw new SafetensorParseError(`Failed to parse file ${path}: safetensors header is malformed.`);
|
| 154 |
+
}
|
| 155 |
+
if (lengthOfHeader > MAX_HEADER_LENGTH) {
|
| 156 |
+
throw new SafetensorParseError(
|
| 157 |
+
`Failed to parse file ${path}: safetensor header is too big. Maximum supported size is ${MAX_HEADER_LENGTH} bytes.`,
|
| 158 |
+
);
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
try {
|
| 162 |
+
// no validation for now, we assume it's a valid FileHeader.
|
| 163 |
+
const header: SafetensorsFileHeader = JSON.parse(await blob.slice(8, 8 + Number(lengthOfHeader)).text());
|
| 164 |
+
return header;
|
| 165 |
+
} catch (err) {
|
| 166 |
+
throw new SafetensorParseError(`Failed to parse file ${path}: safetensors header is not valid JSON.`);
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
async function parseShardedIndex(
|
| 171 |
+
path: string,
|
| 172 |
+
params: {
|
| 173 |
+
repo: RepoDesignation;
|
| 174 |
+
revision?: string;
|
| 175 |
+
hubUrl?: string;
|
| 176 |
+
/**
|
| 177 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 178 |
+
*/
|
| 179 |
+
fetch?: typeof fetch;
|
| 180 |
+
} & Partial<CredentialsParams>,
|
| 181 |
+
): Promise<SafetensorsIndexJson> {
|
| 182 |
+
const indexBlob = await downloadFile({
|
| 183 |
+
...params,
|
| 184 |
+
path,
|
| 185 |
+
});
|
| 186 |
+
|
| 187 |
+
if (!indexBlob) {
|
| 188 |
+
throw new SafetensorParseError(`Failed to parse file ${path}: failed to fetch safetensors index.`);
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
try {
|
| 192 |
+
// no validation for now, we assume it's a valid IndexJson.
|
| 193 |
+
const index = JSON.parse(await indexBlob.slice(0, MAX_HEADER_LENGTH).text());
|
| 194 |
+
return index;
|
| 195 |
+
} catch (error) {
|
| 196 |
+
throw new SafetensorParseError(`Failed to parse file ${path}: not a valid JSON.`);
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
async function fetchAllHeaders(
|
| 201 |
+
path: string,
|
| 202 |
+
index: SafetensorsIndexJson,
|
| 203 |
+
params: {
|
| 204 |
+
repo: RepoDesignation;
|
| 205 |
+
revision?: string;
|
| 206 |
+
hubUrl?: string;
|
| 207 |
+
/**
|
| 208 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 209 |
+
*/
|
| 210 |
+
fetch?: typeof fetch;
|
| 211 |
+
} & Partial<CredentialsParams>,
|
| 212 |
+
): Promise<SafetensorsShardedHeaders> {
|
| 213 |
+
const pathPrefix = path.slice(0, path.lastIndexOf("/") + 1);
|
| 214 |
+
const filenames = [...new Set(Object.values(index.weight_map))];
|
| 215 |
+
const shardedMap: SafetensorsShardedHeaders = Object.fromEntries(
|
| 216 |
+
await promisesQueue(
|
| 217 |
+
filenames.map(
|
| 218 |
+
(filename) => async () =>
|
| 219 |
+
[filename, await parseSingleFile(pathPrefix + filename, params)] satisfies [string, SafetensorsFileHeader],
|
| 220 |
+
),
|
| 221 |
+
PARALLEL_DOWNLOADS,
|
| 222 |
+
),
|
| 223 |
+
);
|
| 224 |
+
return shardedMap;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
/**
|
| 228 |
+
* Analyze model.safetensors.index.json or model.safetensors from a model hosted
|
| 229 |
+
* on Hugging Face using smart range requests to extract its metadata.
|
| 230 |
+
*/
|
| 231 |
+
export async function parseSafetensorsMetadata(
|
| 232 |
+
params: {
|
| 233 |
+
/** Only models are supported */
|
| 234 |
+
repo: RepoDesignation;
|
| 235 |
+
/**
|
| 236 |
+
* Relative file path to safetensors file inside `repo`. Defaults to `SAFETENSORS_FILE` or `SAFETENSORS_INDEX_FILE` (whichever one exists).
|
| 237 |
+
*/
|
| 238 |
+
path?: string;
|
| 239 |
+
/**
|
| 240 |
+
* Will include SafetensorsParseFromRepo["parameterCount"], an object containing the number of parameters for each DType
|
| 241 |
+
*
|
| 242 |
+
* @default false
|
| 243 |
+
*/
|
| 244 |
+
computeParametersCount: true;
|
| 245 |
+
hubUrl?: string;
|
| 246 |
+
revision?: string;
|
| 247 |
+
/**
|
| 248 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 249 |
+
*/
|
| 250 |
+
fetch?: typeof fetch;
|
| 251 |
+
} & Partial<CredentialsParams>,
|
| 252 |
+
): Promise<SetRequired<SafetensorsParseFromRepo, "parameterCount">>;
|
| 253 |
+
export async function parseSafetensorsMetadata(
|
| 254 |
+
params: {
|
| 255 |
+
/** Only models are supported */
|
| 256 |
+
repo: RepoDesignation;
|
| 257 |
+
path?: string;
|
| 258 |
+
/**
|
| 259 |
+
* Will include SafetensorsParseFromRepo["parameterCount"], an object containing the number of parameters for each DType
|
| 260 |
+
*
|
| 261 |
+
* @default false
|
| 262 |
+
*/
|
| 263 |
+
computeParametersCount?: boolean;
|
| 264 |
+
hubUrl?: string;
|
| 265 |
+
revision?: string;
|
| 266 |
+
/**
|
| 267 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 268 |
+
*/
|
| 269 |
+
fetch?: typeof fetch;
|
| 270 |
+
} & Partial<CredentialsParams>,
|
| 271 |
+
): Promise<SafetensorsParseFromRepo>;
|
| 272 |
+
export async function parseSafetensorsMetadata(
|
| 273 |
+
params: {
|
| 274 |
+
repo: RepoDesignation;
|
| 275 |
+
path?: string;
|
| 276 |
+
computeParametersCount?: boolean;
|
| 277 |
+
hubUrl?: string;
|
| 278 |
+
revision?: string;
|
| 279 |
+
/**
|
| 280 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 281 |
+
*/
|
| 282 |
+
fetch?: typeof fetch;
|
| 283 |
+
} & Partial<CredentialsParams>,
|
| 284 |
+
): Promise<SafetensorsParseFromRepo> {
|
| 285 |
+
const repoId = toRepoId(params.repo);
|
| 286 |
+
|
| 287 |
+
if (repoId.type !== "model") {
|
| 288 |
+
throw new TypeError("Only model repos should contain safetensors files.");
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
// Fetch model config for quantization information
|
| 292 |
+
const modelConfig = params.computeParametersCount ? await fetchModelConfig(params) : null;
|
| 293 |
+
const quantConfig = modelConfig?.quantization_config;
|
| 294 |
+
|
| 295 |
+
if (
|
| 296 |
+
(params.path && RE_SAFETENSORS_FILE.test(params.path)) ||
|
| 297 |
+
(await fileExists({ ...params, path: SAFETENSORS_FILE }))
|
| 298 |
+
) {
|
| 299 |
+
const header = await parseSingleFile(params.path ?? SAFETENSORS_FILE, params);
|
| 300 |
+
return {
|
| 301 |
+
sharded: false,
|
| 302 |
+
header,
|
| 303 |
+
...(params.computeParametersCount
|
| 304 |
+
? {
|
| 305 |
+
parameterCount: computeNumOfParamsByDtypeSingleFile(header, quantConfig),
|
| 306 |
+
parameterTotal:
|
| 307 |
+
/// shortcut: get param count directly from metadata
|
| 308 |
+
header.__metadata__.total_parameters
|
| 309 |
+
? typeof header.__metadata__.total_parameters === "number"
|
| 310 |
+
? header.__metadata__.total_parameters
|
| 311 |
+
: typeof header.__metadata__.total_parameters === "string"
|
| 312 |
+
? parseInt(header.__metadata__.total_parameters)
|
| 313 |
+
: undefined
|
| 314 |
+
: undefined,
|
| 315 |
+
}
|
| 316 |
+
: undefined),
|
| 317 |
+
};
|
| 318 |
+
} else if (
|
| 319 |
+
(params.path && RE_SAFETENSORS_INDEX_FILE.test(params.path)) ||
|
| 320 |
+
(await fileExists({ ...params, path: SAFETENSORS_INDEX_FILE }))
|
| 321 |
+
) {
|
| 322 |
+
const path = params.path ?? SAFETENSORS_INDEX_FILE;
|
| 323 |
+
const index = await parseShardedIndex(path, params);
|
| 324 |
+
const shardedMap = await fetchAllHeaders(path, index, params);
|
| 325 |
+
|
| 326 |
+
return {
|
| 327 |
+
sharded: true,
|
| 328 |
+
index,
|
| 329 |
+
headers: shardedMap,
|
| 330 |
+
...(params.computeParametersCount
|
| 331 |
+
? {
|
| 332 |
+
parameterCount: computeNumOfParamsByDtypeSharded(shardedMap, quantConfig),
|
| 333 |
+
parameterTotal:
|
| 334 |
+
/// shortcut: get param count directly from metadata
|
| 335 |
+
index.metadata?.total_parameters
|
| 336 |
+
? typeof index.metadata.total_parameters === "number"
|
| 337 |
+
? index.metadata.total_parameters
|
| 338 |
+
: typeof index.metadata.total_parameters === "string"
|
| 339 |
+
? parseInt(index.metadata.total_parameters)
|
| 340 |
+
: undefined
|
| 341 |
+
: undefined,
|
| 342 |
+
}
|
| 343 |
+
: undefined),
|
| 344 |
+
};
|
| 345 |
+
} else {
|
| 346 |
+
throw new Error("model id does not seem to contain safetensors weights");
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
export interface QuantizationConfig {
|
| 351 |
+
quant_method?: string;
|
| 352 |
+
modules_to_not_convert?: string[];
|
| 353 |
+
bits?: number;
|
| 354 |
+
load_in_4bit?: boolean;
|
| 355 |
+
load_in_8bit?: boolean;
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
export interface ModelConfig {
|
| 359 |
+
quantization_config?: QuantizationConfig;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
/**
|
| 363 |
+
* Determines if a tensor is quantized based on quantization config and tensor name
|
| 364 |
+
*/
|
| 365 |
+
function isQuantizedTensor(tensorName: string, quantConfig?: QuantizationConfig): boolean {
|
| 366 |
+
if (!quantConfig) {
|
| 367 |
+
return false;
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
if (!quantConfig.modules_to_not_convert || quantConfig.modules_to_not_convert.length === 0) {
|
| 371 |
+
return true;
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
for (const pattern of quantConfig.modules_to_not_convert) {
|
| 375 |
+
const regexPattern = pattern.replace(/\*/g, ".*");
|
| 376 |
+
const regex = new RegExp(regexPattern);
|
| 377 |
+
if (regex.test(tensorName)) {
|
| 378 |
+
return false;
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
return true;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
/**
|
| 386 |
+
* Gets the parameter multiplier for a quantized tensor based on quantization method
|
| 387 |
+
*/
|
| 388 |
+
function getQuantizationMultiplier(tensorName: string, dtype: Dtype, quantConfig?: QuantizationConfig): number {
|
| 389 |
+
if (!quantConfig || !isQuantizedTensor(tensorName, quantConfig)) {
|
| 390 |
+
return 1;
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
const quantMethod = quantConfig.quant_method?.toLowerCase();
|
| 394 |
+
|
| 395 |
+
switch (quantMethod) {
|
| 396 |
+
case "mxfp4":
|
| 397 |
+
if (dtype === "U8" && tensorName.includes("_blocks")) {
|
| 398 |
+
return 2;
|
| 399 |
+
}
|
| 400 |
+
return 1;
|
| 401 |
+
|
| 402 |
+
case "gptq":
|
| 403 |
+
case "awq":
|
| 404 |
+
if (getTensorSuffix(tensorName) === GPTQ_QWEIGHT_SUFFIX) {
|
| 405 |
+
const bits = quantConfig.bits && quantConfig.bits > 0 ? quantConfig.bits : 4;
|
| 406 |
+
return Math.max(1, Math.floor(32 / bits));
|
| 407 |
+
}
|
| 408 |
+
if (quantConfig.bits === 4 && dtype === "U8") {
|
| 409 |
+
return 2;
|
| 410 |
+
}
|
| 411 |
+
if (quantConfig.bits === 2 && dtype === "U8") {
|
| 412 |
+
return 4;
|
| 413 |
+
}
|
| 414 |
+
return 1;
|
| 415 |
+
|
| 416 |
+
case "bitsandbytes":
|
| 417 |
+
if (quantConfig.load_in_4bit && dtype === "U8") {
|
| 418 |
+
return 2;
|
| 419 |
+
}
|
| 420 |
+
if (quantConfig.load_in_8bit) {
|
| 421 |
+
return 1;
|
| 422 |
+
}
|
| 423 |
+
return 1;
|
| 424 |
+
|
| 425 |
+
default:
|
| 426 |
+
if (quantConfig.load_in_4bit && dtype === "U8") {
|
| 427 |
+
return 2;
|
| 428 |
+
}
|
| 429 |
+
if (quantConfig.bits === 4 && dtype === "U8") {
|
| 430 |
+
return 2;
|
| 431 |
+
}
|
| 432 |
+
return 1;
|
| 433 |
+
}
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
function computeNumOfParamsByDtypeSingleFile(
|
| 437 |
+
header: SafetensorsFileHeader,
|
| 438 |
+
quantConfig?: QuantizationConfig,
|
| 439 |
+
): Partial<Record<Dtype, number>> {
|
| 440 |
+
const counter: Partial<Record<Dtype, number>> = {};
|
| 441 |
+
const tensors = omit(header, "__metadata__");
|
| 442 |
+
|
| 443 |
+
for (const [tensorName, v] of typedEntries(tensors)) {
|
| 444 |
+
if (shouldSkipTensor(tensorName, quantConfig)) {
|
| 445 |
+
continue;
|
| 446 |
+
}
|
| 447 |
+
if (v.shape.length === 0) {
|
| 448 |
+
continue;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
const elements = v.shape.reduce((a, b) => a * b);
|
| 452 |
+
const multiplier = quantConfig ? getQuantizationMultiplier(tensorName, v.dtype, quantConfig) : 1;
|
| 453 |
+
if (multiplier === 0) {
|
| 454 |
+
continue;
|
| 455 |
+
}
|
| 456 |
+
counter[v.dtype] = (counter[v.dtype] ?? 0) + elements * multiplier;
|
| 457 |
+
}
|
| 458 |
+
return counter;
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
function computeNumOfParamsByDtypeSharded(
|
| 462 |
+
shardedMap: SafetensorsShardedHeaders,
|
| 463 |
+
quantConfig?: QuantizationConfig,
|
| 464 |
+
): Partial<Record<Dtype, number>> {
|
| 465 |
+
const counter: Partial<Record<Dtype, number>> = {};
|
| 466 |
+
for (const header of Object.values(shardedMap)) {
|
| 467 |
+
for (const [k, v] of typedEntries(computeNumOfParamsByDtypeSingleFile(header, quantConfig))) {
|
| 468 |
+
counter[k] = (counter[k] ?? 0) + (v ?? 0);
|
| 469 |
+
}
|
| 470 |
+
}
|
| 471 |
+
return counter;
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
function getTensorSuffix(tensorName: string): string {
|
| 475 |
+
const lastDotIndex = tensorName.lastIndexOf(".");
|
| 476 |
+
return lastDotIndex === -1 ? tensorName : tensorName.slice(lastDotIndex + 1);
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
function shouldSkipTensor(tensorName: string, quantConfig?: QuantizationConfig): boolean {
|
| 480 |
+
const GPTQ_AWQ_AUXILIARY_SUFFIXES = ["qzeros", "g_idx", "scales"];
|
| 481 |
+
|
| 482 |
+
if (!quantConfig) {
|
| 483 |
+
return false;
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
const quantMethod = quantConfig.quant_method?.toLowerCase();
|
| 487 |
+
if (!quantMethod || (quantMethod !== "gptq" && quantMethod !== "awq")) {
|
| 488 |
+
return false;
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
if (!isQuantizedTensor(tensorName, quantConfig)) {
|
| 492 |
+
return false;
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
const suffix = getTensorSuffix(tensorName);
|
| 496 |
+
if (suffix === GPTQ_QWEIGHT_SUFFIX) {
|
| 497 |
+
return false;
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
return GPTQ_AWQ_AUXILIARY_SUFFIXES.includes(suffix);
|
| 501 |
+
}
|
node_modules/@huggingface/hub/src/lib/paths-info.spec.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, it, describe } from "vitest";
|
| 2 |
+
import type { CommitInfo, PathInfo } from "./paths-info";
|
| 3 |
+
import { pathsInfo } from "./paths-info";
|
| 4 |
+
|
| 5 |
+
describe("pathsInfo", () => {
|
| 6 |
+
it("should fetch LFS path info", async () => {
|
| 7 |
+
const result: PathInfo[] = await pathsInfo({
|
| 8 |
+
repo: {
|
| 9 |
+
name: "google-bert/bert-base-uncased",
|
| 10 |
+
type: "model",
|
| 11 |
+
},
|
| 12 |
+
paths: ["tf_model.h5"],
|
| 13 |
+
revision: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
expect(result).toHaveLength(1);
|
| 17 |
+
|
| 18 |
+
const modelPathInfo = result[0];
|
| 19 |
+
expect(modelPathInfo.path).toBe("tf_model.h5");
|
| 20 |
+
expect(modelPathInfo.type).toBe("file");
|
| 21 |
+
// lfs pointer, therefore lfs should be defined
|
| 22 |
+
expect(modelPathInfo?.lfs).toBeDefined();
|
| 23 |
+
expect(modelPathInfo?.lfs?.oid).toBe("a7a17d6d844b5de815ccab5f42cad6d24496db3850a2a43d8258221018ce87d2");
|
| 24 |
+
expect(modelPathInfo?.lfs?.size).toBe(536063208);
|
| 25 |
+
expect(modelPathInfo?.lfs?.pointerSize).toBe(134);
|
| 26 |
+
|
| 27 |
+
// should not include expand info
|
| 28 |
+
expect(modelPathInfo.lastCommit).toBeUndefined();
|
| 29 |
+
expect(modelPathInfo.securityFileStatus).toBeUndefined();
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
it("expand params should fetch lastCommit", async () => {
|
| 33 |
+
const result: (PathInfo & {
|
| 34 |
+
lastCommit: CommitInfo;
|
| 35 |
+
})[] = await pathsInfo({
|
| 36 |
+
repo: {
|
| 37 |
+
name: "google-bert/bert-base-uncased",
|
| 38 |
+
type: "model",
|
| 39 |
+
},
|
| 40 |
+
paths: ["tf_model.h5"],
|
| 41 |
+
revision: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 42 |
+
expand: true, // include
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
expect(result).toHaveLength(1);
|
| 46 |
+
|
| 47 |
+
const modelPathInfo = result[0];
|
| 48 |
+
|
| 49 |
+
// should include expand info
|
| 50 |
+
expect(modelPathInfo.lastCommit).toBeDefined();
|
| 51 |
+
|
| 52 |
+
expect(modelPathInfo.lastCommit.id).toBe("dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7");
|
| 53 |
+
expect(modelPathInfo.lastCommit.title).toBe("Update tf_model.h5");
|
| 54 |
+
expect(modelPathInfo.lastCommit.date.getTime()).toBe(1569268124000); // 2019-09-23T19:48:44.000Z
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
it("non-LFS pointer should have lfs undefined", async () => {
|
| 58 |
+
const result: PathInfo[] = await pathsInfo({
|
| 59 |
+
repo: {
|
| 60 |
+
name: "google-bert/bert-base-uncased",
|
| 61 |
+
type: "model",
|
| 62 |
+
},
|
| 63 |
+
paths: ["config.json"],
|
| 64 |
+
revision: "dd4bc8b21efa05ec961e3efc4ee5e3832a3679c7",
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
expect(result).toHaveLength(1);
|
| 68 |
+
|
| 69 |
+
const modelPathInfo = result[0];
|
| 70 |
+
expect(modelPathInfo.path).toBe("config.json");
|
| 71 |
+
expect(modelPathInfo.lfs).toBeUndefined();
|
| 72 |
+
});
|
| 73 |
+
});
|
node_modules/@huggingface/hub/src/lib/paths-info.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams, RepoDesignation } from "../types/public";
|
| 2 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 3 |
+
import { toRepoId } from "../utils/toRepoId";
|
| 4 |
+
import { HUB_URL } from "../consts";
|
| 5 |
+
import { createApiError } from "../error";
|
| 6 |
+
|
| 7 |
+
export interface LfsPathInfo {
|
| 8 |
+
oid: string;
|
| 9 |
+
size: number;
|
| 10 |
+
pointerSize: number;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
export interface CommitInfo {
|
| 14 |
+
id: string;
|
| 15 |
+
title: string;
|
| 16 |
+
date: Date;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export interface SecurityFileStatus {
|
| 20 |
+
status: string;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
export interface PathInfo {
|
| 24 |
+
path: string;
|
| 25 |
+
type: string;
|
| 26 |
+
oid: string;
|
| 27 |
+
size: number;
|
| 28 |
+
/**
|
| 29 |
+
* Only defined when path is LFS pointer
|
| 30 |
+
*/
|
| 31 |
+
lfs?: LfsPathInfo;
|
| 32 |
+
lastCommit?: CommitInfo;
|
| 33 |
+
securityFileStatus?: SecurityFileStatus;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// Define the overloaded signatures
|
| 37 |
+
export function pathsInfo(
|
| 38 |
+
params: {
|
| 39 |
+
repo: RepoDesignation;
|
| 40 |
+
paths: string[];
|
| 41 |
+
expand: true; // if expand true
|
| 42 |
+
revision?: string;
|
| 43 |
+
hubUrl?: string;
|
| 44 |
+
/**
|
| 45 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 46 |
+
*/
|
| 47 |
+
fetch?: typeof fetch;
|
| 48 |
+
} & Partial<CredentialsParams>,
|
| 49 |
+
): Promise<(PathInfo & { lastCommit: CommitInfo; securityFileStatus: SecurityFileStatus })[]>;
|
| 50 |
+
export function pathsInfo(
|
| 51 |
+
params: {
|
| 52 |
+
repo: RepoDesignation;
|
| 53 |
+
paths: string[];
|
| 54 |
+
expand?: boolean;
|
| 55 |
+
revision?: string;
|
| 56 |
+
hubUrl?: string;
|
| 57 |
+
/**
|
| 58 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 59 |
+
*/
|
| 60 |
+
fetch?: typeof fetch;
|
| 61 |
+
} & Partial<CredentialsParams>,
|
| 62 |
+
): Promise<PathInfo[]>;
|
| 63 |
+
|
| 64 |
+
export async function pathsInfo(
|
| 65 |
+
params: {
|
| 66 |
+
repo: RepoDesignation;
|
| 67 |
+
paths: string[];
|
| 68 |
+
expand?: boolean;
|
| 69 |
+
revision?: string;
|
| 70 |
+
hubUrl?: string;
|
| 71 |
+
/**
|
| 72 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 73 |
+
*/
|
| 74 |
+
fetch?: typeof fetch;
|
| 75 |
+
} & Partial<CredentialsParams>,
|
| 76 |
+
): Promise<PathInfo[]> {
|
| 77 |
+
const accessToken = checkCredentials(params);
|
| 78 |
+
const repoId = toRepoId(params.repo);
|
| 79 |
+
|
| 80 |
+
const hubUrl = params.hubUrl ?? HUB_URL;
|
| 81 |
+
|
| 82 |
+
const url = `${hubUrl}/api/${repoId.type}s/${repoId.name}/paths-info/${encodeURIComponent(
|
| 83 |
+
params.revision ?? "main",
|
| 84 |
+
)}`;
|
| 85 |
+
|
| 86 |
+
const resp = await (params.fetch ?? fetch)(url, {
|
| 87 |
+
method: "POST",
|
| 88 |
+
headers: {
|
| 89 |
+
...(accessToken && {
|
| 90 |
+
Authorization: `Bearer ${accessToken}`,
|
| 91 |
+
}),
|
| 92 |
+
Accept: "application/json",
|
| 93 |
+
"Content-Type": "application/json",
|
| 94 |
+
},
|
| 95 |
+
body: JSON.stringify({
|
| 96 |
+
paths: params.paths,
|
| 97 |
+
expand: params.expand,
|
| 98 |
+
}),
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
if (!resp.ok) {
|
| 102 |
+
throw await createApiError(resp);
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
const json: unknown = await resp.json();
|
| 106 |
+
if (!Array.isArray(json)) throw new Error("malformed response: expected array");
|
| 107 |
+
|
| 108 |
+
return json.map((item: PathInfo) => ({
|
| 109 |
+
path: item.path,
|
| 110 |
+
lfs: item.lfs,
|
| 111 |
+
type: item.type,
|
| 112 |
+
oid: item.oid,
|
| 113 |
+
size: item.size,
|
| 114 |
+
// expand fields
|
| 115 |
+
securityFileStatus: item.securityFileStatus,
|
| 116 |
+
lastCommit: item.lastCommit
|
| 117 |
+
? {
|
| 118 |
+
date: new Date(item.lastCommit.date),
|
| 119 |
+
title: item.lastCommit.title,
|
| 120 |
+
id: item.lastCommit.id,
|
| 121 |
+
}
|
| 122 |
+
: undefined,
|
| 123 |
+
}));
|
| 124 |
+
}
|
node_modules/@huggingface/hub/src/lib/repo-exists.spec.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { repoExists } from "./repo-exists";
|
| 3 |
+
|
| 4 |
+
describe("repoExists", () => {
|
| 5 |
+
it("should check if a repo exists", async () => {
|
| 6 |
+
const exists1 = await repoExists({ repo: { type: "model", name: "openai-community/gpt2" } });
|
| 7 |
+
|
| 8 |
+
expect(exists1).toBe(true);
|
| 9 |
+
|
| 10 |
+
const exists2 = await repoExists({ repo: { type: "model", name: "openai-community/gpt9000" } });
|
| 11 |
+
expect(exists2).toBe(false);
|
| 12 |
+
});
|
| 13 |
+
});
|
node_modules/@huggingface/hub/src/lib/repo-exists.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { RepoDesignation } from "../types/public";
|
| 4 |
+
import { toRepoId } from "../utils/toRepoId";
|
| 5 |
+
|
| 6 |
+
export async function repoExists(params: {
|
| 7 |
+
repo: RepoDesignation;
|
| 8 |
+
|
| 9 |
+
hubUrl?: string;
|
| 10 |
+
/**
|
| 11 |
+
* An optional Git revision id which can be a branch name, a tag, or a commit hash.
|
| 12 |
+
*/
|
| 13 |
+
revision?: string;
|
| 14 |
+
/**
|
| 15 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 16 |
+
*/
|
| 17 |
+
fetch?: typeof fetch;
|
| 18 |
+
accessToken?: string;
|
| 19 |
+
}): Promise<boolean> {
|
| 20 |
+
const repoId = toRepoId(params.repo);
|
| 21 |
+
|
| 22 |
+
const res = await (params.fetch ?? fetch)(
|
| 23 |
+
`${params.hubUrl ?? HUB_URL}/api/${repoId.type}s/${repoId.name}?expand[]=likes`,
|
| 24 |
+
{
|
| 25 |
+
method: "GET",
|
| 26 |
+
headers: {
|
| 27 |
+
...(params.accessToken && {
|
| 28 |
+
Authorization: `Bearer ${params.accessToken}`,
|
| 29 |
+
}),
|
| 30 |
+
},
|
| 31 |
+
},
|
| 32 |
+
);
|
| 33 |
+
|
| 34 |
+
if (res.status === 404 || res.status === 401) {
|
| 35 |
+
return false;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
if (!res.ok) {
|
| 39 |
+
throw await createApiError(res);
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
return true;
|
| 43 |
+
}
|
node_modules/@huggingface/hub/src/lib/snapshot-download.spec.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test, describe, vi, beforeEach } from "vitest";
|
| 2 |
+
import { dirname, join } from "node:path";
|
| 3 |
+
import { mkdir, writeFile } from "node:fs/promises";
|
| 4 |
+
import { getHFHubCachePath } from "./cache-management";
|
| 5 |
+
import { downloadFileToCacheDir } from "./download-file-to-cache-dir";
|
| 6 |
+
import { snapshotDownload } from "./snapshot-download";
|
| 7 |
+
import type { ListFileEntry } from "./list-files";
|
| 8 |
+
import { listFiles } from "./list-files";
|
| 9 |
+
import { modelInfo } from "./model-info";
|
| 10 |
+
import type { ModelEntry } from "./list-models";
|
| 11 |
+
import type { ApiModelInfo } from "../types/api/api-model";
|
| 12 |
+
import { datasetInfo } from "./dataset-info";
|
| 13 |
+
import type { DatasetEntry } from "./list-datasets";
|
| 14 |
+
import type { ApiDatasetInfo } from "../types/api/api-dataset";
|
| 15 |
+
import { spaceInfo } from "./space-info";
|
| 16 |
+
import type { SpaceEntry } from "./list-spaces";
|
| 17 |
+
import type { ApiSpaceInfo } from "../types/api/api-space";
|
| 18 |
+
|
| 19 |
+
vi.mock("node:fs/promises", () => ({
|
| 20 |
+
writeFile: vi.fn(),
|
| 21 |
+
mkdir: vi.fn(),
|
| 22 |
+
}));
|
| 23 |
+
|
| 24 |
+
vi.mock("./space-info", () => ({
|
| 25 |
+
spaceInfo: vi.fn(),
|
| 26 |
+
}));
|
| 27 |
+
|
| 28 |
+
vi.mock("./dataset-info", () => ({
|
| 29 |
+
datasetInfo: vi.fn(),
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
vi.mock("./model-info", () => ({
|
| 33 |
+
modelInfo: vi.fn(),
|
| 34 |
+
}));
|
| 35 |
+
|
| 36 |
+
vi.mock("./list-files", () => ({
|
| 37 |
+
listFiles: vi.fn(),
|
| 38 |
+
}));
|
| 39 |
+
|
| 40 |
+
vi.mock("./download-file-to-cache-dir", () => ({
|
| 41 |
+
downloadFileToCacheDir: vi.fn(),
|
| 42 |
+
}));
|
| 43 |
+
|
| 44 |
+
const DUMMY_SHA = "dummy-sha";
|
| 45 |
+
|
| 46 |
+
// utility method to transform an array of ListFileEntry to an AsyncGenerator<ListFileEntry>
|
| 47 |
+
async function* toAsyncGenerator(content: ListFileEntry[]): AsyncGenerator<ListFileEntry> {
|
| 48 |
+
for (const entry of content) {
|
| 49 |
+
yield Promise.resolve(entry);
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
beforeEach(() => {
|
| 54 |
+
vi.resetAllMocks();
|
| 55 |
+
vi.mocked(listFiles).mockReturnValue(toAsyncGenerator([]));
|
| 56 |
+
|
| 57 |
+
// mock repo info
|
| 58 |
+
vi.mocked(modelInfo).mockResolvedValue({
|
| 59 |
+
sha: DUMMY_SHA,
|
| 60 |
+
} as ModelEntry & ApiModelInfo);
|
| 61 |
+
vi.mocked(datasetInfo).mockResolvedValue({
|
| 62 |
+
sha: DUMMY_SHA,
|
| 63 |
+
} as DatasetEntry & ApiDatasetInfo);
|
| 64 |
+
vi.mocked(spaceInfo).mockResolvedValue({
|
| 65 |
+
sha: DUMMY_SHA,
|
| 66 |
+
} as SpaceEntry & ApiSpaceInfo);
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
describe("snapshotDownload", () => {
|
| 70 |
+
test("empty AsyncGenerator should not call downloadFileToCacheDir", async () => {
|
| 71 |
+
await snapshotDownload({
|
| 72 |
+
repo: {
|
| 73 |
+
name: "foo/bar",
|
| 74 |
+
type: "space",
|
| 75 |
+
},
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
expect(downloadFileToCacheDir).not.toHaveBeenCalled();
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
test("repo type model should use modelInfo", async () => {
|
| 82 |
+
await snapshotDownload({
|
| 83 |
+
repo: {
|
| 84 |
+
name: "foo/bar",
|
| 85 |
+
type: "model",
|
| 86 |
+
},
|
| 87 |
+
});
|
| 88 |
+
expect(modelInfo).toHaveBeenCalledOnce();
|
| 89 |
+
expect(modelInfo).toHaveBeenCalledWith({
|
| 90 |
+
name: "foo/bar",
|
| 91 |
+
additionalFields: ["sha"],
|
| 92 |
+
revision: "main",
|
| 93 |
+
repo: {
|
| 94 |
+
name: "foo/bar",
|
| 95 |
+
type: "model",
|
| 96 |
+
},
|
| 97 |
+
});
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
test("repo type dataset should use datasetInfo", async () => {
|
| 101 |
+
await snapshotDownload({
|
| 102 |
+
repo: {
|
| 103 |
+
name: "foo/bar",
|
| 104 |
+
type: "dataset",
|
| 105 |
+
},
|
| 106 |
+
});
|
| 107 |
+
expect(datasetInfo).toHaveBeenCalledOnce();
|
| 108 |
+
expect(datasetInfo).toHaveBeenCalledWith({
|
| 109 |
+
name: "foo/bar",
|
| 110 |
+
additionalFields: ["sha"],
|
| 111 |
+
revision: "main",
|
| 112 |
+
repo: {
|
| 113 |
+
name: "foo/bar",
|
| 114 |
+
type: "dataset",
|
| 115 |
+
},
|
| 116 |
+
});
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
test("repo type space should use spaceInfo", async () => {
|
| 120 |
+
await snapshotDownload({
|
| 121 |
+
repo: {
|
| 122 |
+
name: "foo/bar",
|
| 123 |
+
type: "space",
|
| 124 |
+
},
|
| 125 |
+
});
|
| 126 |
+
expect(spaceInfo).toHaveBeenCalledOnce();
|
| 127 |
+
expect(spaceInfo).toHaveBeenCalledWith({
|
| 128 |
+
name: "foo/bar",
|
| 129 |
+
additionalFields: ["sha"],
|
| 130 |
+
revision: "main",
|
| 131 |
+
repo: {
|
| 132 |
+
name: "foo/bar",
|
| 133 |
+
type: "space",
|
| 134 |
+
},
|
| 135 |
+
});
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
test("commitHash should be saved to ref folder", async () => {
|
| 139 |
+
await snapshotDownload({
|
| 140 |
+
repo: {
|
| 141 |
+
name: "foo/bar",
|
| 142 |
+
type: "space",
|
| 143 |
+
},
|
| 144 |
+
revision: "dummy-revision",
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
// cross-platform testing
|
| 148 |
+
const expectedPath = join(getHFHubCachePath(), "spaces--foo--bar", "refs", "dummy-revision");
|
| 149 |
+
expect(mkdir).toHaveBeenCalledWith(dirname(expectedPath), { recursive: true });
|
| 150 |
+
expect(writeFile).toHaveBeenCalledWith(expectedPath, DUMMY_SHA);
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
test("directory ListFileEntry should mkdir it", async () => {
|
| 154 |
+
vi.mocked(listFiles).mockReturnValue(
|
| 155 |
+
toAsyncGenerator([
|
| 156 |
+
{
|
| 157 |
+
oid: "dummy-etag",
|
| 158 |
+
type: "directory",
|
| 159 |
+
path: "potatoes",
|
| 160 |
+
size: 0,
|
| 161 |
+
lastCommit: {
|
| 162 |
+
date: new Date().toISOString(),
|
| 163 |
+
id: DUMMY_SHA,
|
| 164 |
+
title: "feat: best commit",
|
| 165 |
+
},
|
| 166 |
+
},
|
| 167 |
+
]),
|
| 168 |
+
);
|
| 169 |
+
|
| 170 |
+
await snapshotDownload({
|
| 171 |
+
repo: {
|
| 172 |
+
name: "foo/bar",
|
| 173 |
+
type: "space",
|
| 174 |
+
},
|
| 175 |
+
});
|
| 176 |
+
|
| 177 |
+
// cross-platform testing
|
| 178 |
+
const expectedPath = join(getHFHubCachePath(), "spaces--foo--bar", "snapshots", DUMMY_SHA, "potatoes");
|
| 179 |
+
expect(mkdir).toHaveBeenCalledWith(expectedPath, { recursive: true });
|
| 180 |
+
});
|
| 181 |
+
|
| 182 |
+
test("files in ListFileEntry should download them", async () => {
|
| 183 |
+
const entries: ListFileEntry[] = Array.from({ length: 10 }, (_, i) => ({
|
| 184 |
+
oid: `dummy-etag-${i}`,
|
| 185 |
+
type: "file",
|
| 186 |
+
path: `file-${i}.txt`,
|
| 187 |
+
size: i,
|
| 188 |
+
lastCommit: {
|
| 189 |
+
date: new Date().toISOString(),
|
| 190 |
+
id: DUMMY_SHA,
|
| 191 |
+
title: "feat: best commit",
|
| 192 |
+
},
|
| 193 |
+
}));
|
| 194 |
+
vi.mocked(listFiles).mockReturnValue(toAsyncGenerator(entries));
|
| 195 |
+
|
| 196 |
+
await snapshotDownload({
|
| 197 |
+
repo: {
|
| 198 |
+
name: "foo/bar",
|
| 199 |
+
type: "space",
|
| 200 |
+
},
|
| 201 |
+
});
|
| 202 |
+
|
| 203 |
+
for (const entry of entries) {
|
| 204 |
+
expect(downloadFileToCacheDir).toHaveBeenCalledWith(
|
| 205 |
+
expect.objectContaining({
|
| 206 |
+
repo: {
|
| 207 |
+
name: "foo/bar",
|
| 208 |
+
type: "space",
|
| 209 |
+
},
|
| 210 |
+
path: entry.path,
|
| 211 |
+
revision: DUMMY_SHA,
|
| 212 |
+
}),
|
| 213 |
+
);
|
| 214 |
+
}
|
| 215 |
+
});
|
| 216 |
+
|
| 217 |
+
test("custom params should be propagated", async () => {
|
| 218 |
+
// fetch mock
|
| 219 |
+
const fetchMock: typeof fetch = vi.fn();
|
| 220 |
+
const hubMock = "https://foor.bar";
|
| 221 |
+
const accessTokenMock = "dummy-access-token";
|
| 222 |
+
|
| 223 |
+
vi.mocked(listFiles).mockReturnValue(
|
| 224 |
+
toAsyncGenerator([
|
| 225 |
+
{
|
| 226 |
+
oid: `dummy-etag`,
|
| 227 |
+
type: "file",
|
| 228 |
+
path: `file.txt`,
|
| 229 |
+
size: 10,
|
| 230 |
+
lastCommit: {
|
| 231 |
+
date: new Date().toISOString(),
|
| 232 |
+
id: DUMMY_SHA,
|
| 233 |
+
title: "feat: best commit",
|
| 234 |
+
},
|
| 235 |
+
},
|
| 236 |
+
]),
|
| 237 |
+
);
|
| 238 |
+
|
| 239 |
+
await snapshotDownload({
|
| 240 |
+
repo: {
|
| 241 |
+
name: "foo/bar",
|
| 242 |
+
type: "space",
|
| 243 |
+
},
|
| 244 |
+
hubUrl: hubMock,
|
| 245 |
+
fetch: fetchMock,
|
| 246 |
+
accessToken: accessTokenMock,
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
expect(spaceInfo).toHaveBeenCalledWith(
|
| 250 |
+
expect.objectContaining({
|
| 251 |
+
fetch: fetchMock,
|
| 252 |
+
hubUrl: hubMock,
|
| 253 |
+
accessToken: accessTokenMock,
|
| 254 |
+
}),
|
| 255 |
+
);
|
| 256 |
+
|
| 257 |
+
// list files should receive custom fetch
|
| 258 |
+
expect(listFiles).toHaveBeenCalledWith(
|
| 259 |
+
expect.objectContaining({
|
| 260 |
+
fetch: fetchMock,
|
| 261 |
+
hubUrl: hubMock,
|
| 262 |
+
accessToken: accessTokenMock,
|
| 263 |
+
}),
|
| 264 |
+
);
|
| 265 |
+
|
| 266 |
+
// download file to cache should receive custom fetch
|
| 267 |
+
expect(downloadFileToCacheDir).toHaveBeenCalledWith(
|
| 268 |
+
expect.objectContaining({
|
| 269 |
+
fetch: fetchMock,
|
| 270 |
+
hubUrl: hubMock,
|
| 271 |
+
accessToken: accessTokenMock,
|
| 272 |
+
}),
|
| 273 |
+
);
|
| 274 |
+
});
|
| 275 |
+
});
|
node_modules/@huggingface/hub/src/lib/snapshot-download.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams, RepoDesignation } from "../types/public";
|
| 2 |
+
import { listFiles } from "./list-files";
|
| 3 |
+
import { getHFHubCachePath, getRepoFolderName } from "./cache-management";
|
| 4 |
+
import { spaceInfo } from "./space-info";
|
| 5 |
+
import { datasetInfo } from "./dataset-info";
|
| 6 |
+
import { modelInfo } from "./model-info";
|
| 7 |
+
import { toRepoId } from "../utils/toRepoId";
|
| 8 |
+
import { join, dirname } from "node:path";
|
| 9 |
+
import { mkdir, writeFile } from "node:fs/promises";
|
| 10 |
+
import { downloadFileToCacheDir } from "./download-file-to-cache-dir";
|
| 11 |
+
|
| 12 |
+
export const DEFAULT_REVISION = "main";
|
| 13 |
+
|
| 14 |
+
/**
|
| 15 |
+
* Downloads an entire repository at a given revision in the cache directory {@link getHFHubCachePath}.
|
| 16 |
+
* You can list all cached repositories using {@link scanCachedRepo}
|
| 17 |
+
* @remarks It uses internally {@link downloadFileToCacheDir}.
|
| 18 |
+
*/
|
| 19 |
+
export async function snapshotDownload(
|
| 20 |
+
params: {
|
| 21 |
+
repo: RepoDesignation;
|
| 22 |
+
cacheDir?: string;
|
| 23 |
+
/**
|
| 24 |
+
* An optional Git revision id which can be a branch name, a tag, or a commit hash.
|
| 25 |
+
*
|
| 26 |
+
* @default "main"
|
| 27 |
+
*/
|
| 28 |
+
revision?: string;
|
| 29 |
+
hubUrl?: string;
|
| 30 |
+
/**
|
| 31 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 32 |
+
*/
|
| 33 |
+
fetch?: typeof fetch;
|
| 34 |
+
} & Partial<CredentialsParams>,
|
| 35 |
+
): Promise<string> {
|
| 36 |
+
let cacheDir: string;
|
| 37 |
+
if (params.cacheDir) {
|
| 38 |
+
cacheDir = params.cacheDir;
|
| 39 |
+
} else {
|
| 40 |
+
cacheDir = getHFHubCachePath();
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
let revision: string;
|
| 44 |
+
if (params.revision) {
|
| 45 |
+
revision = params.revision;
|
| 46 |
+
} else {
|
| 47 |
+
revision = DEFAULT_REVISION;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
const repoId = toRepoId(params.repo);
|
| 51 |
+
|
| 52 |
+
// get repository revision value (sha)
|
| 53 |
+
let repoInfo: { sha: string };
|
| 54 |
+
switch (repoId.type) {
|
| 55 |
+
case "space":
|
| 56 |
+
repoInfo = await spaceInfo({
|
| 57 |
+
...params,
|
| 58 |
+
name: repoId.name,
|
| 59 |
+
additionalFields: ["sha"],
|
| 60 |
+
revision: revision,
|
| 61 |
+
});
|
| 62 |
+
break;
|
| 63 |
+
case "dataset":
|
| 64 |
+
repoInfo = await datasetInfo({
|
| 65 |
+
...params,
|
| 66 |
+
name: repoId.name,
|
| 67 |
+
additionalFields: ["sha"],
|
| 68 |
+
revision: revision,
|
| 69 |
+
});
|
| 70 |
+
break;
|
| 71 |
+
case "model":
|
| 72 |
+
repoInfo = await modelInfo({
|
| 73 |
+
...params,
|
| 74 |
+
name: repoId.name,
|
| 75 |
+
additionalFields: ["sha"],
|
| 76 |
+
revision: revision,
|
| 77 |
+
});
|
| 78 |
+
break;
|
| 79 |
+
default:
|
| 80 |
+
throw new Error(`invalid repository type ${repoId.type}`);
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
const commitHash: string = repoInfo.sha;
|
| 84 |
+
|
| 85 |
+
// get storage folder
|
| 86 |
+
const storageFolder = join(cacheDir, getRepoFolderName(repoId));
|
| 87 |
+
const snapshotFolder = join(storageFolder, "snapshots", commitHash);
|
| 88 |
+
|
| 89 |
+
// if passed revision is not identical to commit_hash
|
| 90 |
+
// then revision has to be a branch name or tag name.
|
| 91 |
+
// In that case store a ref.
|
| 92 |
+
if (revision !== commitHash) {
|
| 93 |
+
const refPath = join(storageFolder, "refs", revision);
|
| 94 |
+
await mkdir(dirname(refPath), { recursive: true });
|
| 95 |
+
await writeFile(refPath, commitHash);
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
const cursor = listFiles({
|
| 99 |
+
...params,
|
| 100 |
+
repo: params.repo,
|
| 101 |
+
recursive: true,
|
| 102 |
+
revision: repoInfo.sha,
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
for await (const entry of cursor) {
|
| 106 |
+
switch (entry.type) {
|
| 107 |
+
case "file":
|
| 108 |
+
await downloadFileToCacheDir({
|
| 109 |
+
...params,
|
| 110 |
+
path: entry.path,
|
| 111 |
+
revision: commitHash,
|
| 112 |
+
cacheDir: cacheDir,
|
| 113 |
+
});
|
| 114 |
+
break;
|
| 115 |
+
case "directory":
|
| 116 |
+
await mkdir(join(snapshotFolder, entry.path), { recursive: true });
|
| 117 |
+
break;
|
| 118 |
+
default:
|
| 119 |
+
throw new Error(`unknown entry type: ${entry.type}`);
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
return snapshotFolder;
|
| 124 |
+
}
|
node_modules/@huggingface/hub/src/lib/space-info.spec.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { spaceInfo } from "./space-info";
|
| 3 |
+
import type { SpaceEntry } from "./list-spaces";
|
| 4 |
+
import type { ApiSpaceInfo } from "../types/api/api-space";
|
| 5 |
+
|
| 6 |
+
describe("spaceInfo", () => {
|
| 7 |
+
it("should return the space info", async () => {
|
| 8 |
+
const info = await spaceInfo({
|
| 9 |
+
name: "huggingfacejs/client-side-oauth",
|
| 10 |
+
});
|
| 11 |
+
expect(info).toEqual({
|
| 12 |
+
id: "659835e689010f9c7aed608d",
|
| 13 |
+
name: "huggingfacejs/client-side-oauth",
|
| 14 |
+
updatedAt: expect.any(Date),
|
| 15 |
+
likes: expect.any(Number),
|
| 16 |
+
private: false,
|
| 17 |
+
sdk: "static",
|
| 18 |
+
});
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
it("should return the space info with author", async () => {
|
| 22 |
+
const info: SpaceEntry & Pick<ApiSpaceInfo, "author"> = await spaceInfo({
|
| 23 |
+
name: "huggingfacejs/client-side-oauth",
|
| 24 |
+
additionalFields: ["author"],
|
| 25 |
+
});
|
| 26 |
+
expect(info).toEqual({
|
| 27 |
+
id: "659835e689010f9c7aed608d",
|
| 28 |
+
name: "huggingfacejs/client-side-oauth",
|
| 29 |
+
updatedAt: expect.any(Date),
|
| 30 |
+
likes: expect.any(Number),
|
| 31 |
+
private: false,
|
| 32 |
+
sdk: "static",
|
| 33 |
+
author: "huggingfacejs",
|
| 34 |
+
});
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
it("should return the space info for a given revision", async () => {
|
| 38 |
+
const info: SpaceEntry & Pick<ApiSpaceInfo, "sha"> = await spaceInfo({
|
| 39 |
+
name: "huggingfacejs/client-side-oauth",
|
| 40 |
+
additionalFields: ["sha"],
|
| 41 |
+
revision: "e410a9ff348e6bed393b847711e793282d7c672e",
|
| 42 |
+
});
|
| 43 |
+
expect(info).toEqual({
|
| 44 |
+
id: "659835e689010f9c7aed608d",
|
| 45 |
+
name: "huggingfacejs/client-side-oauth",
|
| 46 |
+
updatedAt: expect.any(Date),
|
| 47 |
+
likes: expect.any(Number),
|
| 48 |
+
private: false,
|
| 49 |
+
sdk: "static",
|
| 50 |
+
sha: "e410a9ff348e6bed393b847711e793282d7c672e",
|
| 51 |
+
});
|
| 52 |
+
});
|
| 53 |
+
});
|
node_modules/@huggingface/hub/src/lib/space-info.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiSpaceInfo } from "../types/api/api-space";
|
| 4 |
+
import type { CredentialsParams } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
import { pick } from "../utils/pick";
|
| 7 |
+
import type { SPACE_EXPANDABLE_KEYS, SpaceEntry } from "./list-spaces";
|
| 8 |
+
import { SPACE_EXPAND_KEYS } from "./list-spaces";
|
| 9 |
+
|
| 10 |
+
export async function spaceInfo<
|
| 11 |
+
const T extends Exclude<(typeof SPACE_EXPANDABLE_KEYS)[number], (typeof SPACE_EXPAND_KEYS)[number]> = never,
|
| 12 |
+
>(
|
| 13 |
+
params: {
|
| 14 |
+
name: string;
|
| 15 |
+
hubUrl?: string;
|
| 16 |
+
additionalFields?: T[];
|
| 17 |
+
/**
|
| 18 |
+
* An optional Git revision id which can be a branch name, a tag, or a commit hash.
|
| 19 |
+
*/
|
| 20 |
+
revision?: string;
|
| 21 |
+
/**
|
| 22 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 23 |
+
*/
|
| 24 |
+
fetch?: typeof fetch;
|
| 25 |
+
} & Partial<CredentialsParams>,
|
| 26 |
+
): Promise<SpaceEntry & Pick<ApiSpaceInfo, T>> {
|
| 27 |
+
const accessToken = params && checkCredentials(params);
|
| 28 |
+
|
| 29 |
+
const search = new URLSearchParams([
|
| 30 |
+
...SPACE_EXPAND_KEYS.map((val) => ["expand", val] satisfies [string, string]),
|
| 31 |
+
...(params?.additionalFields?.map((val) => ["expand", val] satisfies [string, string]) ?? []),
|
| 32 |
+
]).toString();
|
| 33 |
+
|
| 34 |
+
const response = await (params.fetch || fetch)(
|
| 35 |
+
`${params?.hubUrl || HUB_URL}/api/spaces/${params.name}/revision/${encodeURIComponent(
|
| 36 |
+
params.revision ?? "HEAD",
|
| 37 |
+
)}?${search.toString()}`,
|
| 38 |
+
{
|
| 39 |
+
headers: {
|
| 40 |
+
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
| 41 |
+
},
|
| 42 |
+
},
|
| 43 |
+
);
|
| 44 |
+
|
| 45 |
+
if (!response.ok) {
|
| 46 |
+
throw await createApiError(response);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
const data = await response.json();
|
| 50 |
+
|
| 51 |
+
return {
|
| 52 |
+
...(params?.additionalFields && pick(data, params.additionalFields)),
|
| 53 |
+
id: data._id,
|
| 54 |
+
name: data.id,
|
| 55 |
+
sdk: data.sdk,
|
| 56 |
+
likes: data.likes,
|
| 57 |
+
private: data.private,
|
| 58 |
+
updatedAt: new Date(data.lastModified),
|
| 59 |
+
} as SpaceEntry & Pick<ApiSpaceInfo, T>;
|
| 60 |
+
}
|
node_modules/@huggingface/hub/src/lib/upload-file.spec.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe, expect } from "vitest";
|
| 2 |
+
|
| 3 |
+
import { TEST_ACCESS_TOKEN, TEST_HUB_URL, TEST_USER } from "../test/consts";
|
| 4 |
+
import type { RepoId } from "../types/public";
|
| 5 |
+
import { insecureRandomString } from "../utils/insecureRandomString";
|
| 6 |
+
import { createRepo } from "./create-repo";
|
| 7 |
+
import { deleteRepo } from "./delete-repo";
|
| 8 |
+
import { downloadFile } from "./download-file";
|
| 9 |
+
import { uploadFile } from "./upload-file";
|
| 10 |
+
|
| 11 |
+
describe("uploadFile", () => {
|
| 12 |
+
it("should upload a file", async () => {
|
| 13 |
+
const repoName = `${TEST_USER}/TEST-${insecureRandomString()}`;
|
| 14 |
+
const repo = { type: "model", name: repoName } satisfies RepoId;
|
| 15 |
+
|
| 16 |
+
try {
|
| 17 |
+
const result = await createRepo({
|
| 18 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 19 |
+
repo,
|
| 20 |
+
hubUrl: TEST_HUB_URL,
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
expect(result).toEqual({
|
| 24 |
+
repoUrl: `${TEST_HUB_URL}/${repoName}`,
|
| 25 |
+
id: expect.any(String),
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
await uploadFile({
|
| 29 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 30 |
+
repo,
|
| 31 |
+
file: { content: new Blob(["file1"]), path: "file1" },
|
| 32 |
+
hubUrl: TEST_HUB_URL,
|
| 33 |
+
});
|
| 34 |
+
await uploadFile({
|
| 35 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 36 |
+
repo,
|
| 37 |
+
file: new URL("https://huggingface.co/gpt2/raw/main/config.json"),
|
| 38 |
+
hubUrl: TEST_HUB_URL,
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
let content = await downloadFile({
|
| 42 |
+
repo,
|
| 43 |
+
path: "file1",
|
| 44 |
+
hubUrl: TEST_HUB_URL,
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
assert.strictEqual(await content?.text(), "file1");
|
| 48 |
+
|
| 49 |
+
content = await downloadFile({
|
| 50 |
+
repo,
|
| 51 |
+
path: "config.json",
|
| 52 |
+
hubUrl: TEST_HUB_URL,
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
assert.strictEqual(
|
| 56 |
+
(await content?.text())?.trim(),
|
| 57 |
+
`
|
| 58 |
+
{
|
| 59 |
+
"activation_function": "gelu_new",
|
| 60 |
+
"architectures": [
|
| 61 |
+
"GPT2LMHeadModel"
|
| 62 |
+
],
|
| 63 |
+
"attn_pdrop": 0.1,
|
| 64 |
+
"bos_token_id": 50256,
|
| 65 |
+
"embd_pdrop": 0.1,
|
| 66 |
+
"eos_token_id": 50256,
|
| 67 |
+
"initializer_range": 0.02,
|
| 68 |
+
"layer_norm_epsilon": 1e-05,
|
| 69 |
+
"model_type": "gpt2",
|
| 70 |
+
"n_ctx": 1024,
|
| 71 |
+
"n_embd": 768,
|
| 72 |
+
"n_head": 12,
|
| 73 |
+
"n_layer": 12,
|
| 74 |
+
"n_positions": 1024,
|
| 75 |
+
"resid_pdrop": 0.1,
|
| 76 |
+
"summary_activation": null,
|
| 77 |
+
"summary_first_dropout": 0.1,
|
| 78 |
+
"summary_proj_to_labels": true,
|
| 79 |
+
"summary_type": "cls_index",
|
| 80 |
+
"summary_use_proj": true,
|
| 81 |
+
"task_specific_params": {
|
| 82 |
+
"text-generation": {
|
| 83 |
+
"do_sample": true,
|
| 84 |
+
"max_length": 50
|
| 85 |
+
}
|
| 86 |
+
},
|
| 87 |
+
"vocab_size": 50257
|
| 88 |
+
}
|
| 89 |
+
`.trim(),
|
| 90 |
+
);
|
| 91 |
+
} finally {
|
| 92 |
+
await deleteRepo({
|
| 93 |
+
repo,
|
| 94 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 95 |
+
hubUrl: TEST_HUB_URL,
|
| 96 |
+
});
|
| 97 |
+
}
|
| 98 |
+
});
|
| 99 |
+
});
|
node_modules/@huggingface/hub/src/lib/upload-file.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams } from "../types/public";
|
| 2 |
+
import type { CommitOutput, CommitParams, ContentSource } from "./commit";
|
| 3 |
+
import { commit } from "./commit";
|
| 4 |
+
|
| 5 |
+
export function uploadFile(
|
| 6 |
+
params: {
|
| 7 |
+
repo: CommitParams["repo"];
|
| 8 |
+
file: URL | File | { path: string; content: ContentSource };
|
| 9 |
+
commitTitle?: CommitParams["title"];
|
| 10 |
+
commitDescription?: CommitParams["description"];
|
| 11 |
+
hubUrl?: CommitParams["hubUrl"];
|
| 12 |
+
branch?: CommitParams["branch"];
|
| 13 |
+
isPullRequest?: CommitParams["isPullRequest"];
|
| 14 |
+
parentCommit?: CommitParams["parentCommit"];
|
| 15 |
+
fetch?: CommitParams["fetch"];
|
| 16 |
+
useWebWorkers?: CommitParams["useWebWorkers"];
|
| 17 |
+
abortSignal?: CommitParams["abortSignal"];
|
| 18 |
+
useXet?: CommitParams["useXet"];
|
| 19 |
+
} & Partial<CredentialsParams>,
|
| 20 |
+
): Promise<CommitOutput | undefined> {
|
| 21 |
+
const path =
|
| 22 |
+
params.file instanceof URL
|
| 23 |
+
? (params.file.pathname.split("/").at(-1) ?? "file")
|
| 24 |
+
: "path" in params.file
|
| 25 |
+
? params.file.path
|
| 26 |
+
: params.file.name;
|
| 27 |
+
|
| 28 |
+
return commit({
|
| 29 |
+
...(params.accessToken ? { accessToken: params.accessToken } : { credentials: params.credentials }),
|
| 30 |
+
repo: params.repo,
|
| 31 |
+
operations: [
|
| 32 |
+
{
|
| 33 |
+
operation: "addOrUpdate",
|
| 34 |
+
path,
|
| 35 |
+
content: "content" in params.file ? params.file.content : params.file,
|
| 36 |
+
},
|
| 37 |
+
],
|
| 38 |
+
title: params.commitTitle ?? `Add ${path}`,
|
| 39 |
+
description: params.commitDescription,
|
| 40 |
+
hubUrl: params.hubUrl,
|
| 41 |
+
branch: params.branch,
|
| 42 |
+
isPullRequest: params.isPullRequest,
|
| 43 |
+
parentCommit: params.parentCommit,
|
| 44 |
+
fetch: params.fetch,
|
| 45 |
+
useWebWorkers: params.useWebWorkers,
|
| 46 |
+
abortSignal: params.abortSignal,
|
| 47 |
+
useXet: params.useXet,
|
| 48 |
+
});
|
| 49 |
+
}
|
node_modules/@huggingface/hub/src/lib/upload-files-with-progress.spec.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe, expect } from "vitest";
|
| 2 |
+
|
| 3 |
+
import { TEST_HUB_URL, TEST_ACCESS_TOKEN, TEST_USER } from "../test/consts";
|
| 4 |
+
import type { RepoId } from "../types/public";
|
| 5 |
+
import { insecureRandomString } from "../utils/insecureRandomString";
|
| 6 |
+
import { createRepo } from "./create-repo";
|
| 7 |
+
import { deleteRepo } from "./delete-repo";
|
| 8 |
+
import { downloadFile } from "./download-file";
|
| 9 |
+
import { uploadFilesWithProgress } from "./upload-files-with-progress";
|
| 10 |
+
import type { CommitOutput, CommitProgressEvent } from "./commit";
|
| 11 |
+
|
| 12 |
+
describe("uploadFilesWithProgress", () => {
|
| 13 |
+
for (const useXet of [false, true]) {
|
| 14 |
+
describe(`useXet: ${useXet}`, () => {
|
| 15 |
+
it("should upload files", async () => {
|
| 16 |
+
const repoName = `${TEST_USER}/TEST-${insecureRandomString()}`;
|
| 17 |
+
const repo = { type: "model", name: repoName } satisfies RepoId;
|
| 18 |
+
const lfsContent = "O123456789".repeat(100_000);
|
| 19 |
+
|
| 20 |
+
try {
|
| 21 |
+
const result = await createRepo({
|
| 22 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 23 |
+
repo,
|
| 24 |
+
hubUrl: TEST_HUB_URL,
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
expect(result).toEqual({
|
| 28 |
+
repoUrl: `${TEST_HUB_URL}/${repoName}`,
|
| 29 |
+
id: expect.any(String),
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
const it = uploadFilesWithProgress({
|
| 33 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 34 |
+
repo,
|
| 35 |
+
files: [
|
| 36 |
+
{ content: new Blob(["file1"]), path: "file1" },
|
| 37 |
+
new URL("https://huggingface.co/gpt2/raw/main/config.json"),
|
| 38 |
+
// Large file
|
| 39 |
+
{
|
| 40 |
+
content: new Blob([lfsContent]),
|
| 41 |
+
path: "test.lfs.txt",
|
| 42 |
+
},
|
| 43 |
+
],
|
| 44 |
+
useWebWorkers: {
|
| 45 |
+
minSize: 1_000,
|
| 46 |
+
},
|
| 47 |
+
hubUrl: TEST_HUB_URL,
|
| 48 |
+
useXet,
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
let res: IteratorResult<CommitProgressEvent, CommitOutput | undefined>;
|
| 52 |
+
let progressEvents: CommitProgressEvent[] = [];
|
| 53 |
+
|
| 54 |
+
do {
|
| 55 |
+
res = await it.next();
|
| 56 |
+
if (!res.done) {
|
| 57 |
+
progressEvents.push(res.value);
|
| 58 |
+
}
|
| 59 |
+
} while (!res.done);
|
| 60 |
+
|
| 61 |
+
// const intermediateHashingEvents = progressEvents.filter(
|
| 62 |
+
// (e) => e.event === "fileProgress" && e.type === "hashing" && e.progress !== 0 && e.progress !== 1
|
| 63 |
+
// );
|
| 64 |
+
// if (isFrontend) {
|
| 65 |
+
// assert(intermediateHashingEvents.length > 0);
|
| 66 |
+
// }
|
| 67 |
+
// const intermediateUploadEvents = progressEvents.filter(
|
| 68 |
+
// (e) => e.event === "fileProgress" && e.type === "uploading" && e.progress !== 0 && e.progress !== 1
|
| 69 |
+
// );
|
| 70 |
+
// if (isFrontend) {
|
| 71 |
+
// assert(intermediateUploadEvents.length > 0, "There should be at least one intermediate upload event");
|
| 72 |
+
// }
|
| 73 |
+
progressEvents = progressEvents.filter(
|
| 74 |
+
(e, i) =>
|
| 75 |
+
(e.event !== "fileProgress" || e.progress === 0 || e.progress === 1) &&
|
| 76 |
+
(i === 0 || JSON.stringify(e) !== JSON.stringify(progressEvents[i - 1])),
|
| 77 |
+
);
|
| 78 |
+
|
| 79 |
+
assert.deepStrictEqual(progressEvents, [
|
| 80 |
+
{
|
| 81 |
+
event: "phase",
|
| 82 |
+
phase: "preuploading",
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
event: "phase",
|
| 86 |
+
phase: "uploadingLargeFiles",
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
event: "fileProgress",
|
| 90 |
+
path: "test.lfs.txt",
|
| 91 |
+
progress: 0,
|
| 92 |
+
state: "hashing",
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
event: "fileProgress",
|
| 96 |
+
path: "test.lfs.txt",
|
| 97 |
+
progress: 1,
|
| 98 |
+
state: "hashing",
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
event: "fileProgress",
|
| 102 |
+
path: "test.lfs.txt",
|
| 103 |
+
progress: 0,
|
| 104 |
+
state: "uploading",
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
event: "fileProgress",
|
| 108 |
+
path: "test.lfs.txt",
|
| 109 |
+
progress: 1,
|
| 110 |
+
state: "uploading",
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
event: "phase",
|
| 114 |
+
phase: "committing",
|
| 115 |
+
},
|
| 116 |
+
]);
|
| 117 |
+
|
| 118 |
+
let content = await downloadFile({
|
| 119 |
+
repo,
|
| 120 |
+
path: "file1",
|
| 121 |
+
hubUrl: TEST_HUB_URL,
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
assert.strictEqual(await content?.text(), "file1");
|
| 125 |
+
|
| 126 |
+
content = await downloadFile({
|
| 127 |
+
repo,
|
| 128 |
+
path: "config.json",
|
| 129 |
+
hubUrl: TEST_HUB_URL,
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
assert.strictEqual(
|
| 133 |
+
(await content?.text())?.trim(),
|
| 134 |
+
`
|
| 135 |
+
{
|
| 136 |
+
"activation_function": "gelu_new",
|
| 137 |
+
"architectures": [
|
| 138 |
+
"GPT2LMHeadModel"
|
| 139 |
+
],
|
| 140 |
+
"attn_pdrop": 0.1,
|
| 141 |
+
"bos_token_id": 50256,
|
| 142 |
+
"embd_pdrop": 0.1,
|
| 143 |
+
"eos_token_id": 50256,
|
| 144 |
+
"initializer_range": 0.02,
|
| 145 |
+
"layer_norm_epsilon": 1e-05,
|
| 146 |
+
"model_type": "gpt2",
|
| 147 |
+
"n_ctx": 1024,
|
| 148 |
+
"n_embd": 768,
|
| 149 |
+
"n_head": 12,
|
| 150 |
+
"n_layer": 12,
|
| 151 |
+
"n_positions": 1024,
|
| 152 |
+
"resid_pdrop": 0.1,
|
| 153 |
+
"summary_activation": null,
|
| 154 |
+
"summary_first_dropout": 0.1,
|
| 155 |
+
"summary_proj_to_labels": true,
|
| 156 |
+
"summary_type": "cls_index",
|
| 157 |
+
"summary_use_proj": true,
|
| 158 |
+
"task_specific_params": {
|
| 159 |
+
"text-generation": {
|
| 160 |
+
"do_sample": true,
|
| 161 |
+
"max_length": 50
|
| 162 |
+
}
|
| 163 |
+
},
|
| 164 |
+
"vocab_size": 50257
|
| 165 |
+
}
|
| 166 |
+
`.trim(),
|
| 167 |
+
);
|
| 168 |
+
} finally {
|
| 169 |
+
await deleteRepo({
|
| 170 |
+
repo,
|
| 171 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 172 |
+
hubUrl: TEST_HUB_URL,
|
| 173 |
+
});
|
| 174 |
+
}
|
| 175 |
+
});
|
| 176 |
+
});
|
| 177 |
+
}
|
| 178 |
+
});
|
node_modules/@huggingface/hub/src/lib/upload-files-with-progress.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams } from "../types/public";
|
| 2 |
+
import { typedInclude } from "../utils/typedInclude";
|
| 3 |
+
import type { CommitOutput, CommitParams, CommitProgressEvent, ContentSource } from "./commit";
|
| 4 |
+
import { commitIter } from "./commit";
|
| 5 |
+
|
| 6 |
+
const multipartUploadTracking = new WeakMap<
|
| 7 |
+
(progress: number) => void,
|
| 8 |
+
{
|
| 9 |
+
numParts: number;
|
| 10 |
+
partsProgress: Record<number, number>;
|
| 11 |
+
}
|
| 12 |
+
>();
|
| 13 |
+
|
| 14 |
+
/**
|
| 15 |
+
* Uploads with progress
|
| 16 |
+
*
|
| 17 |
+
* Needs XMLHttpRequest to be available for progress events for uploads on models, datasets and spaces.
|
| 18 |
+
* Set useWebWorkers to true in order to have progress events for hashing for models, datasets and spaces.
|
| 19 |
+
*/
|
| 20 |
+
export async function* uploadFilesWithProgress(
|
| 21 |
+
params: {
|
| 22 |
+
repo: CommitParams["repo"];
|
| 23 |
+
files: Array<URL | File | { path: string; content: ContentSource }>;
|
| 24 |
+
commitTitle?: CommitParams["title"];
|
| 25 |
+
commitDescription?: CommitParams["description"];
|
| 26 |
+
hubUrl?: CommitParams["hubUrl"];
|
| 27 |
+
branch?: CommitParams["branch"];
|
| 28 |
+
isPullRequest?: CommitParams["isPullRequest"];
|
| 29 |
+
parentCommit?: CommitParams["parentCommit"];
|
| 30 |
+
abortSignal?: CommitParams["abortSignal"];
|
| 31 |
+
maxFolderDepth?: CommitParams["maxFolderDepth"];
|
| 32 |
+
useXet?: CommitParams["useXet"];
|
| 33 |
+
/**
|
| 34 |
+
* Set this to true in order to have progress events for hashing
|
| 35 |
+
*/
|
| 36 |
+
useWebWorkers?: CommitParams["useWebWorkers"];
|
| 37 |
+
} & Partial<CredentialsParams>,
|
| 38 |
+
): AsyncGenerator<CommitProgressEvent, CommitOutput | undefined> {
|
| 39 |
+
return yield* commitIter({
|
| 40 |
+
...(params.accessToken ? { accessToken: params.accessToken } : { credentials: params.credentials }),
|
| 41 |
+
repo: params.repo,
|
| 42 |
+
operations: params.files.map((file) => ({
|
| 43 |
+
operation: "addOrUpdate",
|
| 44 |
+
path: file instanceof URL ? (file.pathname.split("/").at(-1) ?? "file") : "path" in file ? file.path : file.name,
|
| 45 |
+
content: "content" in file ? file.content : file,
|
| 46 |
+
})),
|
| 47 |
+
title: params.commitTitle ?? `Add ${params.files.length} files`,
|
| 48 |
+
description: params.commitDescription,
|
| 49 |
+
hubUrl: params.hubUrl,
|
| 50 |
+
branch: params.branch,
|
| 51 |
+
isPullRequest: params.isPullRequest,
|
| 52 |
+
parentCommit: params.parentCommit,
|
| 53 |
+
useWebWorkers: params.useWebWorkers,
|
| 54 |
+
abortSignal: params.abortSignal,
|
| 55 |
+
useXet: params.useXet,
|
| 56 |
+
fetch: async (input, init) => {
|
| 57 |
+
if (!init) {
|
| 58 |
+
return fetch(input);
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if (
|
| 62 |
+
!typedInclude(["PUT", "POST"], init.method) ||
|
| 63 |
+
!("progressHint" in init) ||
|
| 64 |
+
!init.progressHint ||
|
| 65 |
+
typeof XMLHttpRequest === "undefined" ||
|
| 66 |
+
typeof input !== "string" ||
|
| 67 |
+
(!(init.body instanceof ArrayBuffer) &&
|
| 68 |
+
!(init.body instanceof Blob) &&
|
| 69 |
+
!(init.body instanceof File) &&
|
| 70 |
+
typeof init.body !== "string")
|
| 71 |
+
) {
|
| 72 |
+
return fetch(input, init);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
const progressHint = init.progressHint as {
|
| 76 |
+
progressCallback: (progress: number) => void;
|
| 77 |
+
} & (Record<string, never> | { part: number; numParts: number });
|
| 78 |
+
const progressCallback = progressHint.progressCallback;
|
| 79 |
+
|
| 80 |
+
const xhr = new XMLHttpRequest();
|
| 81 |
+
|
| 82 |
+
xhr.upload.addEventListener("progress", (event) => {
|
| 83 |
+
if (event.lengthComputable) {
|
| 84 |
+
if (progressHint.part !== undefined) {
|
| 85 |
+
let tracking = multipartUploadTracking.get(progressCallback);
|
| 86 |
+
if (!tracking) {
|
| 87 |
+
tracking = { numParts: progressHint.numParts, partsProgress: {} };
|
| 88 |
+
multipartUploadTracking.set(progressCallback, tracking);
|
| 89 |
+
}
|
| 90 |
+
tracking.partsProgress[progressHint.part] = event.loaded / event.total;
|
| 91 |
+
let totalProgress = 0;
|
| 92 |
+
for (const partProgress of Object.values(tracking.partsProgress)) {
|
| 93 |
+
totalProgress += partProgress;
|
| 94 |
+
}
|
| 95 |
+
if (totalProgress === tracking.numParts) {
|
| 96 |
+
progressCallback(0.9999999999);
|
| 97 |
+
} else {
|
| 98 |
+
progressCallback(totalProgress / tracking.numParts);
|
| 99 |
+
}
|
| 100 |
+
} else {
|
| 101 |
+
if (event.loaded === event.total) {
|
| 102 |
+
progressCallback(0.9999999999);
|
| 103 |
+
} else {
|
| 104 |
+
progressCallback(event.loaded / event.total);
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
xhr.open(init.method, input, true);
|
| 111 |
+
|
| 112 |
+
if (init.headers) {
|
| 113 |
+
const headers = new Headers(init.headers);
|
| 114 |
+
headers.forEach((value, key) => {
|
| 115 |
+
xhr.setRequestHeader(key, value);
|
| 116 |
+
});
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
init.signal?.throwIfAborted();
|
| 120 |
+
xhr.send(init.body);
|
| 121 |
+
|
| 122 |
+
return new Promise((resolve, reject) => {
|
| 123 |
+
xhr.addEventListener("load", () => {
|
| 124 |
+
resolve(
|
| 125 |
+
new Response(xhr.responseText, {
|
| 126 |
+
status: xhr.status,
|
| 127 |
+
statusText: xhr.statusText,
|
| 128 |
+
headers: Object.fromEntries(
|
| 129 |
+
xhr
|
| 130 |
+
.getAllResponseHeaders()
|
| 131 |
+
.trim()
|
| 132 |
+
.split("\n")
|
| 133 |
+
.map((header) => [
|
| 134 |
+
header.slice(0, header.indexOf(":")),
|
| 135 |
+
header.slice(header.indexOf(":") + 1).trim(),
|
| 136 |
+
]),
|
| 137 |
+
),
|
| 138 |
+
}),
|
| 139 |
+
);
|
| 140 |
+
});
|
| 141 |
+
xhr.addEventListener("error", () => {
|
| 142 |
+
reject(new Error(xhr.statusText));
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
if (init.signal) {
|
| 146 |
+
init.signal.addEventListener("abort", () => {
|
| 147 |
+
xhr.abort();
|
| 148 |
+
|
| 149 |
+
try {
|
| 150 |
+
init.signal?.throwIfAborted();
|
| 151 |
+
} catch (err) {
|
| 152 |
+
reject(err);
|
| 153 |
+
}
|
| 154 |
+
});
|
| 155 |
+
}
|
| 156 |
+
});
|
| 157 |
+
},
|
| 158 |
+
});
|
| 159 |
+
}
|
node_modules/@huggingface/hub/src/lib/upload-files.fs.spec.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe, expect } from "vitest";
|
| 2 |
+
|
| 3 |
+
import { TEST_ACCESS_TOKEN, TEST_HUB_URL, TEST_USER } from "../test/consts";
|
| 4 |
+
import type { RepoId } from "../types/public";
|
| 5 |
+
import { insecureRandomString } from "../utils/insecureRandomString";
|
| 6 |
+
import { createRepo } from "./create-repo";
|
| 7 |
+
import { deleteRepo } from "./delete-repo";
|
| 8 |
+
import { downloadFile } from "./download-file";
|
| 9 |
+
import { uploadFiles } from "./upload-files";
|
| 10 |
+
import { mkdir } from "fs/promises";
|
| 11 |
+
import { writeFile } from "fs/promises";
|
| 12 |
+
import { pathToFileURL } from "url";
|
| 13 |
+
import { tmpdir } from "os";
|
| 14 |
+
|
| 15 |
+
describe("uploadFiles", () => {
|
| 16 |
+
it("should upload local folder", async () => {
|
| 17 |
+
const tmpDir = tmpdir();
|
| 18 |
+
|
| 19 |
+
await mkdir(`${tmpDir}/test-folder/sub`, { recursive: true });
|
| 20 |
+
|
| 21 |
+
await writeFile(`${tmpDir}/test-folder/sub/file1.txt`, "file1");
|
| 22 |
+
await writeFile(`${tmpDir}/test-folder/sub/file2.txt`, "file2");
|
| 23 |
+
|
| 24 |
+
await writeFile(`${tmpDir}/test-folder/file3.txt`, "file3");
|
| 25 |
+
await writeFile(`${tmpDir}/test-folder/file4.txt`, "file4");
|
| 26 |
+
|
| 27 |
+
const repoName = `${TEST_USER}/TEST-${insecureRandomString()}`;
|
| 28 |
+
const repo = { type: "model", name: repoName } satisfies RepoId;
|
| 29 |
+
|
| 30 |
+
try {
|
| 31 |
+
const result = await createRepo({
|
| 32 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 33 |
+
repo,
|
| 34 |
+
hubUrl: TEST_HUB_URL,
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
expect(result).toEqual({
|
| 38 |
+
repoUrl: `${TEST_HUB_URL}/${repoName}`,
|
| 39 |
+
id: expect.any(String),
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
await uploadFiles({
|
| 43 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 44 |
+
repo,
|
| 45 |
+
files: [pathToFileURL(`${tmpDir}/test-folder`)],
|
| 46 |
+
hubUrl: TEST_HUB_URL,
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
let content = await downloadFile({
|
| 50 |
+
repo,
|
| 51 |
+
path: "test-folder/sub/file1.txt",
|
| 52 |
+
hubUrl: TEST_HUB_URL,
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
assert.strictEqual(await content?.text(), "file1");
|
| 56 |
+
|
| 57 |
+
content = await downloadFile({
|
| 58 |
+
repo,
|
| 59 |
+
path: "test-folder/file3.txt",
|
| 60 |
+
hubUrl: TEST_HUB_URL,
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
assert.strictEqual(await content?.text(), `file3`);
|
| 64 |
+
} finally {
|
| 65 |
+
await deleteRepo({
|
| 66 |
+
repo,
|
| 67 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 68 |
+
hubUrl: TEST_HUB_URL,
|
| 69 |
+
});
|
| 70 |
+
}
|
| 71 |
+
});
|
| 72 |
+
});
|
node_modules/@huggingface/hub/src/lib/upload-files.spec.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe, expect } from "vitest";
|
| 2 |
+
|
| 3 |
+
import { TEST_ACCESS_TOKEN, TEST_HUB_URL, TEST_USER } from "../test/consts";
|
| 4 |
+
import type { RepoId } from "../types/public";
|
| 5 |
+
import { insecureRandomString } from "../utils/insecureRandomString";
|
| 6 |
+
import { createRepo } from "./create-repo";
|
| 7 |
+
import { deleteRepo } from "./delete-repo";
|
| 8 |
+
import { downloadFile } from "./download-file";
|
| 9 |
+
import { uploadFiles } from "./upload-files";
|
| 10 |
+
|
| 11 |
+
describe("uploadFiles", () => {
|
| 12 |
+
it("should upload files", async () => {
|
| 13 |
+
const repoName = `${TEST_USER}/TEST-${insecureRandomString()}`;
|
| 14 |
+
const repo = { type: "model", name: repoName } satisfies RepoId;
|
| 15 |
+
|
| 16 |
+
try {
|
| 17 |
+
const result = await createRepo({
|
| 18 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 19 |
+
repo,
|
| 20 |
+
hubUrl: TEST_HUB_URL,
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
expect(result).toEqual({
|
| 24 |
+
repoUrl: `${TEST_HUB_URL}/${repoName}`,
|
| 25 |
+
id: expect.any(String),
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
await uploadFiles({
|
| 29 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 30 |
+
repo,
|
| 31 |
+
files: [
|
| 32 |
+
{ content: new Blob(["file1"]), path: "file1" },
|
| 33 |
+
new URL("https://huggingface.co/gpt2/raw/main/config.json"),
|
| 34 |
+
],
|
| 35 |
+
hubUrl: TEST_HUB_URL,
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
let content = await downloadFile({
|
| 39 |
+
repo,
|
| 40 |
+
path: "file1",
|
| 41 |
+
hubUrl: TEST_HUB_URL,
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
assert.strictEqual(await content?.text(), "file1");
|
| 45 |
+
|
| 46 |
+
content = await downloadFile({
|
| 47 |
+
repo,
|
| 48 |
+
path: "config.json",
|
| 49 |
+
hubUrl: TEST_HUB_URL,
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
assert.strictEqual(
|
| 53 |
+
(await content?.text())?.trim(),
|
| 54 |
+
`
|
| 55 |
+
{
|
| 56 |
+
"activation_function": "gelu_new",
|
| 57 |
+
"architectures": [
|
| 58 |
+
"GPT2LMHeadModel"
|
| 59 |
+
],
|
| 60 |
+
"attn_pdrop": 0.1,
|
| 61 |
+
"bos_token_id": 50256,
|
| 62 |
+
"embd_pdrop": 0.1,
|
| 63 |
+
"eos_token_id": 50256,
|
| 64 |
+
"initializer_range": 0.02,
|
| 65 |
+
"layer_norm_epsilon": 1e-05,
|
| 66 |
+
"model_type": "gpt2",
|
| 67 |
+
"n_ctx": 1024,
|
| 68 |
+
"n_embd": 768,
|
| 69 |
+
"n_head": 12,
|
| 70 |
+
"n_layer": 12,
|
| 71 |
+
"n_positions": 1024,
|
| 72 |
+
"resid_pdrop": 0.1,
|
| 73 |
+
"summary_activation": null,
|
| 74 |
+
"summary_first_dropout": 0.1,
|
| 75 |
+
"summary_proj_to_labels": true,
|
| 76 |
+
"summary_type": "cls_index",
|
| 77 |
+
"summary_use_proj": true,
|
| 78 |
+
"task_specific_params": {
|
| 79 |
+
"text-generation": {
|
| 80 |
+
"do_sample": true,
|
| 81 |
+
"max_length": 50
|
| 82 |
+
}
|
| 83 |
+
},
|
| 84 |
+
"vocab_size": 50257
|
| 85 |
+
}
|
| 86 |
+
`.trim(),
|
| 87 |
+
);
|
| 88 |
+
} finally {
|
| 89 |
+
await deleteRepo({
|
| 90 |
+
repo,
|
| 91 |
+
accessToken: TEST_ACCESS_TOKEN,
|
| 92 |
+
hubUrl: TEST_HUB_URL,
|
| 93 |
+
});
|
| 94 |
+
}
|
| 95 |
+
});
|
| 96 |
+
});
|
node_modules/@huggingface/hub/src/lib/upload-files.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CredentialsParams } from "../types/public";
|
| 2 |
+
import type { CommitOutput, CommitParams, ContentSource } from "./commit";
|
| 3 |
+
import { commit } from "./commit";
|
| 4 |
+
|
| 5 |
+
export function uploadFiles(
|
| 6 |
+
params: {
|
| 7 |
+
repo: CommitParams["repo"];
|
| 8 |
+
files: Array<URL | File | { path: string; content: ContentSource }>;
|
| 9 |
+
commitTitle?: CommitParams["title"];
|
| 10 |
+
commitDescription?: CommitParams["description"];
|
| 11 |
+
hubUrl?: CommitParams["hubUrl"];
|
| 12 |
+
branch?: CommitParams["branch"];
|
| 13 |
+
isPullRequest?: CommitParams["isPullRequest"];
|
| 14 |
+
parentCommit?: CommitParams["parentCommit"];
|
| 15 |
+
fetch?: CommitParams["fetch"];
|
| 16 |
+
useWebWorkers?: CommitParams["useWebWorkers"];
|
| 17 |
+
maxFolderDepth?: CommitParams["maxFolderDepth"];
|
| 18 |
+
abortSignal?: CommitParams["abortSignal"];
|
| 19 |
+
useXet?: CommitParams["useXet"];
|
| 20 |
+
} & Partial<CredentialsParams>,
|
| 21 |
+
): Promise<CommitOutput | undefined> {
|
| 22 |
+
return commit({
|
| 23 |
+
...(params.accessToken ? { accessToken: params.accessToken } : { credentials: params.credentials }),
|
| 24 |
+
repo: params.repo,
|
| 25 |
+
operations: params.files.map((file) => ({
|
| 26 |
+
operation: "addOrUpdate",
|
| 27 |
+
path: file instanceof URL ? (file.pathname.split("/").at(-1) ?? "file") : "path" in file ? file.path : file.name,
|
| 28 |
+
content: "content" in file ? file.content : file,
|
| 29 |
+
})),
|
| 30 |
+
title: params.commitTitle ?? `Add ${params.files.length} files`,
|
| 31 |
+
description: params.commitDescription,
|
| 32 |
+
hubUrl: params.hubUrl,
|
| 33 |
+
branch: params.branch,
|
| 34 |
+
isPullRequest: params.isPullRequest,
|
| 35 |
+
parentCommit: params.parentCommit,
|
| 36 |
+
fetch: params.fetch,
|
| 37 |
+
useWebWorkers: params.useWebWorkers,
|
| 38 |
+
abortSignal: params.abortSignal,
|
| 39 |
+
useXet: params.useXet,
|
| 40 |
+
});
|
| 41 |
+
}
|
node_modules/@huggingface/hub/src/lib/who-am-i.spec.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { assert, it, describe } from "vitest";
|
| 2 |
+
import { TEST_ACCESS_TOKEN, TEST_HUB_URL } from "../test/consts";
|
| 3 |
+
import { whoAmI } from "./who-am-i";
|
| 4 |
+
|
| 5 |
+
describe("whoAmI", () => {
|
| 6 |
+
it("should fetch identity info", async () => {
|
| 7 |
+
const info = await whoAmI({ accessToken: TEST_ACCESS_TOKEN, hubUrl: TEST_HUB_URL });
|
| 8 |
+
|
| 9 |
+
if (info.auth.accessToken?.createdAt instanceof Date) {
|
| 10 |
+
info.auth.accessToken.createdAt = new Date(0);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
assert.deepStrictEqual(info, {
|
| 14 |
+
type: "user",
|
| 15 |
+
id: "62f264b9f3c90f4b6514a269",
|
| 16 |
+
name: "hub.js",
|
| 17 |
+
fullname: "@huggingface/hub CI bot",
|
| 18 |
+
email: "eliott@huggingface.co",
|
| 19 |
+
emailVerified: true,
|
| 20 |
+
canPay: false,
|
| 21 |
+
isPro: false,
|
| 22 |
+
periodEnd: null,
|
| 23 |
+
avatarUrl: "/avatars/934b830e9fdaa879487852f79eef7165.svg",
|
| 24 |
+
billingMode: "postpaid",
|
| 25 |
+
orgs: [],
|
| 26 |
+
auth: {
|
| 27 |
+
type: "access_token",
|
| 28 |
+
accessToken: {
|
| 29 |
+
createdAt: new Date(0),
|
| 30 |
+
displayName: "ci-hub.js",
|
| 31 |
+
role: "write",
|
| 32 |
+
},
|
| 33 |
+
},
|
| 34 |
+
});
|
| 35 |
+
});
|
| 36 |
+
});
|
node_modules/@huggingface/hub/src/lib/who-am-i.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { HUB_URL } from "../consts";
|
| 2 |
+
import { createApiError } from "../error";
|
| 3 |
+
import type { ApiWhoAmIReponse } from "../types/api/api-who-am-i";
|
| 4 |
+
import type { AccessTokenRole, AuthType, CredentialsParams } from "../types/public";
|
| 5 |
+
import { checkCredentials } from "../utils/checkCredentials";
|
| 6 |
+
|
| 7 |
+
export interface WhoAmIUser {
|
| 8 |
+
/** Unique ID persistent across renames */
|
| 9 |
+
id: string;
|
| 10 |
+
type: "user";
|
| 11 |
+
email: string;
|
| 12 |
+
emailVerified: boolean;
|
| 13 |
+
isPro: boolean;
|
| 14 |
+
orgs: WhoAmIOrg[];
|
| 15 |
+
name: string;
|
| 16 |
+
fullname: string;
|
| 17 |
+
canPay: boolean;
|
| 18 |
+
avatarUrl: string;
|
| 19 |
+
/**
|
| 20 |
+
* Unix timestamp in seconds
|
| 21 |
+
*/
|
| 22 |
+
periodEnd: number | null;
|
| 23 |
+
billingMode: "postpaid" | "prepaid";
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export interface WhoAmIOrg {
|
| 27 |
+
/** Unique ID persistent across renames */
|
| 28 |
+
id: string;
|
| 29 |
+
type: "org";
|
| 30 |
+
name: string;
|
| 31 |
+
fullname: string;
|
| 32 |
+
email: string | null;
|
| 33 |
+
canPay: boolean;
|
| 34 |
+
avatarUrl: string;
|
| 35 |
+
/**
|
| 36 |
+
* Unix timestamp in seconds
|
| 37 |
+
*/
|
| 38 |
+
periodEnd: number | null;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
export interface WhoAmIApp {
|
| 42 |
+
id: string;
|
| 43 |
+
type: "app";
|
| 44 |
+
name: string;
|
| 45 |
+
scope?: {
|
| 46 |
+
entities: string[];
|
| 47 |
+
role: "admin" | "write" | "contributor" | "read";
|
| 48 |
+
};
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
export type WhoAmI = WhoAmIApp | WhoAmIOrg | WhoAmIUser;
|
| 52 |
+
export interface AuthInfo {
|
| 53 |
+
type: AuthType;
|
| 54 |
+
accessToken?: {
|
| 55 |
+
displayName: string;
|
| 56 |
+
role: AccessTokenRole;
|
| 57 |
+
createdAt: Date;
|
| 58 |
+
};
|
| 59 |
+
expiresAt?: Date;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
export async function whoAmI(
|
| 63 |
+
params: {
|
| 64 |
+
hubUrl?: string;
|
| 65 |
+
/**
|
| 66 |
+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
|
| 67 |
+
*/
|
| 68 |
+
fetch?: typeof fetch;
|
| 69 |
+
} & CredentialsParams,
|
| 70 |
+
): Promise<WhoAmI & { auth: AuthInfo }> {
|
| 71 |
+
const accessToken = checkCredentials(params);
|
| 72 |
+
|
| 73 |
+
const res = await (params.fetch ?? fetch)(`${params.hubUrl ?? HUB_URL}/api/whoami-v2`, {
|
| 74 |
+
headers: {
|
| 75 |
+
Authorization: `Bearer ${accessToken}`,
|
| 76 |
+
},
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
if (!res.ok) {
|
| 80 |
+
throw await createApiError(res);
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
const response: ApiWhoAmIReponse & {
|
| 84 |
+
auth: AuthInfo;
|
| 85 |
+
} = await res.json();
|
| 86 |
+
|
| 87 |
+
if (typeof response.auth.accessToken?.createdAt === "string") {
|
| 88 |
+
response.auth.accessToken.createdAt = new Date(response.auth.accessToken.createdAt);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
return response;
|
| 92 |
+
}
|
node_modules/@huggingface/hub/src/test/consts.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export const TEST_HUB_URL = "https://hub-ci.huggingface.co";
|
| 2 |
+
export const TEST_USER = "hub.js";
|
| 3 |
+
export const TEST_ACCESS_TOKEN = "hf_hub.js";
|
| 4 |
+
export const TEST_COOKIE = "huggingface-hub.js-cookie";
|
node_modules/@huggingface/hub/src/types/api/api-author.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export type ApiAuthor =
|
| 2 |
+
| {
|
| 3 |
+
avatarUrl: string;
|
| 4 |
+
fullname: string;
|
| 5 |
+
name: string;
|
| 6 |
+
isHf: boolean;
|
| 7 |
+
isHfAdmin: boolean;
|
| 8 |
+
isMod: boolean;
|
| 9 |
+
followerCount?: number;
|
| 10 |
+
type: "org";
|
| 11 |
+
plan?: string;
|
| 12 |
+
isUserFollowing?: boolean;
|
| 13 |
+
}
|
| 14 |
+
| {
|
| 15 |
+
avatarUrl: string;
|
| 16 |
+
fullname: string;
|
| 17 |
+
name: string;
|
| 18 |
+
isHf: boolean;
|
| 19 |
+
isHfAdmin: boolean;
|
| 20 |
+
isMod: boolean;
|
| 21 |
+
followerCount?: number;
|
| 22 |
+
type: "user";
|
| 23 |
+
isPro: boolean;
|
| 24 |
+
_id: string;
|
| 25 |
+
isUserFollowing?: boolean;
|
| 26 |
+
};
|
node_modules/@huggingface/hub/src/types/api/api-collection.ts
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { ApiAuthor } from "./api-author";
|
| 2 |
+
|
| 3 |
+
export interface ApiCollectionInfo {
|
| 4 |
+
slug: string;
|
| 5 |
+
title: string;
|
| 6 |
+
description?: string;
|
| 7 |
+
lastUpdated: string;
|
| 8 |
+
gating:
|
| 9 |
+
| true
|
| 10 |
+
| (
|
| 11 |
+
| false
|
| 12 |
+
| {
|
| 13 |
+
mode: "auto";
|
| 14 |
+
}
|
| 15 |
+
| {
|
| 16 |
+
mode: "manual";
|
| 17 |
+
notifications: {
|
| 18 |
+
mode: "bulk" | "real-time";
|
| 19 |
+
email?: string;
|
| 20 |
+
};
|
| 21 |
+
}
|
| 22 |
+
);
|
| 23 |
+
owner: ApiAuthor;
|
| 24 |
+
/**
|
| 25 |
+
* Note that it's limited to 4 items when the listing endpoint is used.
|
| 26 |
+
*/
|
| 27 |
+
items: ApiCollectionItem[];
|
| 28 |
+
theme: "orange" | "blue" | "green" | "purple" | "pink" | "indigo";
|
| 29 |
+
private: boolean;
|
| 30 |
+
upvotes: number;
|
| 31 |
+
isUpvotedByUser: boolean;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
interface ApiCollectionItemBase {
|
| 35 |
+
_id: string;
|
| 36 |
+
position: number;
|
| 37 |
+
note?: {
|
| 38 |
+
html: string;
|
| 39 |
+
text: string;
|
| 40 |
+
};
|
| 41 |
+
gallery?: string[];
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
interface ApiCollectionItemModel extends ApiCollectionItemBase {
|
| 45 |
+
type: "model";
|
| 46 |
+
author: string;
|
| 47 |
+
downloads: number;
|
| 48 |
+
id: string;
|
| 49 |
+
availableInferenceProviders: {
|
| 50 |
+
provider:
|
| 51 |
+
| "black-forest-labs"
|
| 52 |
+
| "cerebras"
|
| 53 |
+
| "cohere"
|
| 54 |
+
| "fal-ai"
|
| 55 |
+
| "featherless-ai"
|
| 56 |
+
| "fireworks-ai"
|
| 57 |
+
| "groq"
|
| 58 |
+
| "hf-inference"
|
| 59 |
+
| "hyperbolic"
|
| 60 |
+
| "nebius"
|
| 61 |
+
| "novita"
|
| 62 |
+
| "nscale"
|
| 63 |
+
| "openai"
|
| 64 |
+
| "ovhcloud"
|
| 65 |
+
| "replicate"
|
| 66 |
+
| "sambanova"
|
| 67 |
+
| "together";
|
| 68 |
+
providerStatus: "live" | "staging" | "error";
|
| 69 |
+
modelStatus: "live" | "staging" | "error";
|
| 70 |
+
providerId: string;
|
| 71 |
+
task:
|
| 72 |
+
| "text-classification"
|
| 73 |
+
| "token-classification"
|
| 74 |
+
| "table-question-answering"
|
| 75 |
+
| "question-answering"
|
| 76 |
+
| "zero-shot-classification"
|
| 77 |
+
| "translation"
|
| 78 |
+
| "summarization"
|
| 79 |
+
| "feature-extraction"
|
| 80 |
+
| "text-generation"
|
| 81 |
+
| "text2text-generation"
|
| 82 |
+
| "fill-mask"
|
| 83 |
+
| "sentence-similarity"
|
| 84 |
+
| "text-to-speech"
|
| 85 |
+
| "text-to-audio"
|
| 86 |
+
| "automatic-speech-recognition"
|
| 87 |
+
| "audio-to-audio"
|
| 88 |
+
| "audio-classification"
|
| 89 |
+
| "audio-text-to-text"
|
| 90 |
+
| "voice-activity-detection"
|
| 91 |
+
| "depth-estimation"
|
| 92 |
+
| "image-classification"
|
| 93 |
+
| "object-detection"
|
| 94 |
+
| "image-segmentation"
|
| 95 |
+
| "text-to-image"
|
| 96 |
+
| "image-to-text"
|
| 97 |
+
| "image-to-image"
|
| 98 |
+
| "image-to-video"
|
| 99 |
+
| "unconditional-image-generation"
|
| 100 |
+
| "video-classification"
|
| 101 |
+
| "reinforcement-learning"
|
| 102 |
+
| "robotics"
|
| 103 |
+
| "tabular-classification"
|
| 104 |
+
| "tabular-regression"
|
| 105 |
+
| "tabular-to-text"
|
| 106 |
+
| "table-to-text"
|
| 107 |
+
| "multiple-choice"
|
| 108 |
+
| "text-ranking"
|
| 109 |
+
| "text-retrieval"
|
| 110 |
+
| "time-series-forecasting"
|
| 111 |
+
| "text-to-video"
|
| 112 |
+
| "image-text-to-text"
|
| 113 |
+
| "visual-question-answering"
|
| 114 |
+
| "document-question-answering"
|
| 115 |
+
| "zero-shot-image-classification"
|
| 116 |
+
| "graph-ml"
|
| 117 |
+
| "mask-generation"
|
| 118 |
+
| "zero-shot-object-detection"
|
| 119 |
+
| "text-to-3d"
|
| 120 |
+
| "image-to-3d"
|
| 121 |
+
| "image-feature-extraction"
|
| 122 |
+
| "video-text-to-text"
|
| 123 |
+
| "keypoint-detection"
|
| 124 |
+
| "visual-document-retrieval"
|
| 125 |
+
| "any-to-any"
|
| 126 |
+
| "video-to-video"
|
| 127 |
+
| "other"
|
| 128 |
+
| "conversational";
|
| 129 |
+
adapterType?: "lora";
|
| 130 |
+
adapterWeightsPath?: string;
|
| 131 |
+
}[];
|
| 132 |
+
isLikedByUser: boolean;
|
| 133 |
+
lastModified: string;
|
| 134 |
+
likes: number;
|
| 135 |
+
pipeline_tag?: string;
|
| 136 |
+
private: boolean;
|
| 137 |
+
repoType: "model";
|
| 138 |
+
gated: false | ("auto" | "manual");
|
| 139 |
+
resourceGroup?: {
|
| 140 |
+
id: string;
|
| 141 |
+
name: string;
|
| 142 |
+
numUsers: number;
|
| 143 |
+
};
|
| 144 |
+
numParameters?: number;
|
| 145 |
+
authorData?: ApiAuthor;
|
| 146 |
+
widgetOutputUrls?: string[];
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
interface ApiCollectionItemDataset extends ApiCollectionItemBase {
|
| 150 |
+
type: "dataset";
|
| 151 |
+
author: string;
|
| 152 |
+
id: string;
|
| 153 |
+
isLikedByUser: boolean;
|
| 154 |
+
likes: number;
|
| 155 |
+
datasetsServerInfo?: {
|
| 156 |
+
viewer: "preview" | "viewer-partial" | "viewer";
|
| 157 |
+
numRows: number | null;
|
| 158 |
+
libraries: (
|
| 159 |
+
| "mlcroissant"
|
| 160 |
+
| "webdataset"
|
| 161 |
+
| "datasets"
|
| 162 |
+
| "pandas"
|
| 163 |
+
| "dask"
|
| 164 |
+
| "distilabel"
|
| 165 |
+
| "fiftyone"
|
| 166 |
+
| "argilla"
|
| 167 |
+
| "polars"
|
| 168 |
+
| "duckdb"
|
| 169 |
+
)[];
|
| 170 |
+
formats: ("json" | "csv" | "parquet" | "imagefolder" | "audiofolder" | "webdataset" | "text" | "arrow")[];
|
| 171 |
+
modalities: ("3d" | "audio" | "document" | "geospatial" | "image" | "tabular" | "text" | "timeseries" | "video")[];
|
| 172 |
+
};
|
| 173 |
+
private: boolean;
|
| 174 |
+
repoType: "dataset";
|
| 175 |
+
downloads: number;
|
| 176 |
+
gated: false | ("auto" | "manual");
|
| 177 |
+
lastModified: string;
|
| 178 |
+
resourceGroup?: {
|
| 179 |
+
id: string;
|
| 180 |
+
name: string;
|
| 181 |
+
numUsers: number;
|
| 182 |
+
};
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
interface ApiCollectionItemSpace extends ApiCollectionItemBase {
|
| 186 |
+
type: "space";
|
| 187 |
+
author: string;
|
| 188 |
+
colorFrom: string;
|
| 189 |
+
colorTo: string;
|
| 190 |
+
createdAt: string;
|
| 191 |
+
emoji: string;
|
| 192 |
+
id: string;
|
| 193 |
+
isLikedByUser: boolean;
|
| 194 |
+
lastModified: string;
|
| 195 |
+
likes: number;
|
| 196 |
+
pinned: boolean;
|
| 197 |
+
private: boolean;
|
| 198 |
+
featured: boolean;
|
| 199 |
+
repoType: "space";
|
| 200 |
+
title: string;
|
| 201 |
+
sdk?: "gradio" | "docker" | "static" | "streamlit";
|
| 202 |
+
runtime: {
|
| 203 |
+
stage:
|
| 204 |
+
| "NO_APP_FILE"
|
| 205 |
+
| "CONFIG_ERROR"
|
| 206 |
+
| "BUILDING"
|
| 207 |
+
| "BUILD_ERROR"
|
| 208 |
+
| "APP_STARTING"
|
| 209 |
+
| "RUNNING"
|
| 210 |
+
| "RUNNING_BUILDING"
|
| 211 |
+
| "RUNNING_APP_STARTING"
|
| 212 |
+
| "RUNTIME_ERROR"
|
| 213 |
+
| "DELETING"
|
| 214 |
+
| "STOPPED"
|
| 215 |
+
| "PAUSED"
|
| 216 |
+
| "SLEEPING";
|
| 217 |
+
hardware: {
|
| 218 |
+
current:
|
| 219 |
+
| (
|
| 220 |
+
| "cpu-basic"
|
| 221 |
+
| "cpu-upgrade"
|
| 222 |
+
| "cpu-performance"
|
| 223 |
+
| "cpu-xl"
|
| 224 |
+
| "zero-a10g"
|
| 225 |
+
| "t4-small"
|
| 226 |
+
| "t4-medium"
|
| 227 |
+
| "l4x1"
|
| 228 |
+
| "l4x4"
|
| 229 |
+
| "l40sx1"
|
| 230 |
+
| "l40sx4"
|
| 231 |
+
| "l40sx8"
|
| 232 |
+
| "a10g-small"
|
| 233 |
+
| "a10g-large"
|
| 234 |
+
| "a10g-largex2"
|
| 235 |
+
| "a10g-largex4"
|
| 236 |
+
| "a100-large"
|
| 237 |
+
| "h100"
|
| 238 |
+
| "h100x8"
|
| 239 |
+
)
|
| 240 |
+
| null;
|
| 241 |
+
requested:
|
| 242 |
+
| (
|
| 243 |
+
| "cpu-basic"
|
| 244 |
+
| "cpu-upgrade"
|
| 245 |
+
| "cpu-performance"
|
| 246 |
+
| "cpu-xl"
|
| 247 |
+
| "zero-a10g"
|
| 248 |
+
| "t4-small"
|
| 249 |
+
| "t4-medium"
|
| 250 |
+
| "l4x1"
|
| 251 |
+
| "l4x4"
|
| 252 |
+
| "l40sx1"
|
| 253 |
+
| "l40sx4"
|
| 254 |
+
| "l40sx8"
|
| 255 |
+
| "a10g-small"
|
| 256 |
+
| "a10g-large"
|
| 257 |
+
| "a10g-largex2"
|
| 258 |
+
| "a10g-largex4"
|
| 259 |
+
| "a100-large"
|
| 260 |
+
| "h100"
|
| 261 |
+
| "h100x8"
|
| 262 |
+
)
|
| 263 |
+
| null;
|
| 264 |
+
};
|
| 265 |
+
storage: ("small" | "medium" | "large") | null;
|
| 266 |
+
errorMessage?: string;
|
| 267 |
+
gcTimeout?: number | null;
|
| 268 |
+
replicas: {
|
| 269 |
+
current?: number | null;
|
| 270 |
+
requested: number | "auto";
|
| 271 |
+
};
|
| 272 |
+
devMode?: boolean;
|
| 273 |
+
domains?: {
|
| 274 |
+
domain: string;
|
| 275 |
+
isCustom?: boolean | null;
|
| 276 |
+
stage: "READY" | "PENDING";
|
| 277 |
+
}[];
|
| 278 |
+
sha?: string;
|
| 279 |
+
};
|
| 280 |
+
originSpace?: {
|
| 281 |
+
author: ApiAuthor;
|
| 282 |
+
name: string;
|
| 283 |
+
};
|
| 284 |
+
ai_short_description?: string;
|
| 285 |
+
ai_category?: string;
|
| 286 |
+
trendingScore?: number;
|
| 287 |
+
resourceGroup?: {
|
| 288 |
+
id: string;
|
| 289 |
+
name: string;
|
| 290 |
+
numUsers: number;
|
| 291 |
+
};
|
| 292 |
+
tags: string[];
|
| 293 |
+
authorData?: ApiAuthor;
|
| 294 |
+
shortDescription?: string;
|
| 295 |
+
semanticRelevancyScore?: number;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
interface ApiCollectionItemPaper extends ApiCollectionItemBase {
|
| 299 |
+
type: "paper";
|
| 300 |
+
id: string;
|
| 301 |
+
title: string;
|
| 302 |
+
upvotes: number;
|
| 303 |
+
publishedAt: string;
|
| 304 |
+
thumbnailUrl?: string;
|
| 305 |
+
isUpvotedByUser?: boolean;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
interface ApiCollectionItemCollection extends ApiCollectionItemBase {
|
| 309 |
+
type: "collection";
|
| 310 |
+
slug: string;
|
| 311 |
+
lastUpdated: string;
|
| 312 |
+
description?: string;
|
| 313 |
+
owner: ApiAuthor;
|
| 314 |
+
title: string;
|
| 315 |
+
theme: "orange" | "blue" | "green" | "purple" | "pink" | "indigo";
|
| 316 |
+
upvotes: number;
|
| 317 |
+
isUpvotedByUser: boolean;
|
| 318 |
+
id: string;
|
| 319 |
+
numberItems: number;
|
| 320 |
+
shareUrl: string;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
type ApiCollectionItem =
|
| 324 |
+
| ApiCollectionItemModel
|
| 325 |
+
| ApiCollectionItemDataset
|
| 326 |
+
| ApiCollectionItemSpace
|
| 327 |
+
| ApiCollectionItemPaper
|
| 328 |
+
| ApiCollectionItemCollection;
|
node_modules/@huggingface/hub/src/types/api/api-commit.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface ApiLfsBatchRequest {
|
| 2 |
+
/// github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
|
| 3 |
+
operation: "download" | "upload";
|
| 4 |
+
transfers?: Array<ApiLfsResponseTransfer>;
|
| 5 |
+
/**
|
| 6 |
+
* Optional object describing the server ref that the objects belong to. Note: Added in v2.4.
|
| 7 |
+
*
|
| 8 |
+
* We use this object for QOL and to fail early for users when they're trying to push to the wrong reference.
|
| 9 |
+
* But it does nothing for security.
|
| 10 |
+
*/
|
| 11 |
+
ref?: {
|
| 12 |
+
name: string;
|
| 13 |
+
} | null;
|
| 14 |
+
objects: {
|
| 15 |
+
oid: string;
|
| 16 |
+
/**
|
| 17 |
+
* Integer byte size of the LFS object. Must be at least zero.
|
| 18 |
+
*/
|
| 19 |
+
size: number;
|
| 20 |
+
}[];
|
| 21 |
+
/**
|
| 22 |
+
* The hash algorithm used to name Git LFS objects. Optional; defaults to sha256 if not specified.
|
| 23 |
+
* */
|
| 24 |
+
hash_algo?: string;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
export interface ApiLfsBatchResponse {
|
| 28 |
+
transfer?: ApiLfsResponseTransfer;
|
| 29 |
+
objects: ApiLfsResponseObject[];
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export type ApiLfsResponseTransfer = "basic" | "multipart" | "xet";
|
| 33 |
+
|
| 34 |
+
export interface ApiLfsCompleteMultipartRequest {
|
| 35 |
+
oid: string;
|
| 36 |
+
parts: { etag: string; partNumber: number }[];
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
export interface ApiLfsResponseObject {
|
| 40 |
+
/**
|
| 41 |
+
* Optional boolean specifying whether the request
|
| 42 |
+
* for this specific object is authenticated.
|
| 43 |
+
* If omitted or false, Git LFS will attempt to find credentials for this URL.
|
| 44 |
+
*/
|
| 45 |
+
authenticated?: boolean;
|
| 46 |
+
oid: string;
|
| 47 |
+
/**
|
| 48 |
+
* Integer byte size of the LFS object. Must be at least zero.
|
| 49 |
+
*/
|
| 50 |
+
size: number;
|
| 51 |
+
/**
|
| 52 |
+
* Applicable actions depend on which `operation` is specified in the request.
|
| 53 |
+
* How these properties are interpreted depends on which transfer adapter
|
| 54 |
+
* the client will be using.
|
| 55 |
+
*/
|
| 56 |
+
actions?: {
|
| 57 |
+
/**
|
| 58 |
+
* Download operations MUST specify a download action,
|
| 59 |
+
* or an object error if the object cannot be downloaded for some reason
|
| 60 |
+
*/
|
| 61 |
+
download?: ApiLfsAction;
|
| 62 |
+
/**
|
| 63 |
+
* Upload operations can specify an upload and a verify action.
|
| 64 |
+
* The upload action describes how to upload the object.
|
| 65 |
+
*/
|
| 66 |
+
upload?: ApiLfsAction;
|
| 67 |
+
/**
|
| 68 |
+
* The LFS client will hit this URL after a successful upload.
|
| 69 |
+
* Servers can use this for extra verification, if needed.
|
| 70 |
+
*/
|
| 71 |
+
verify?: ApiLfsAction;
|
| 72 |
+
};
|
| 73 |
+
/**
|
| 74 |
+
* If there are problems accessing individual objects, servers should continue
|
| 75 |
+
* to return a 200 status code, and provide per-object errors
|
| 76 |
+
*/
|
| 77 |
+
error?: {
|
| 78 |
+
code: number;
|
| 79 |
+
message: string;
|
| 80 |
+
};
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
export interface ApiLfsAction {
|
| 84 |
+
href: string;
|
| 85 |
+
/**
|
| 86 |
+
* Optional hash of String HTTP header key/value pairs to apply to the request
|
| 87 |
+
*/
|
| 88 |
+
header?: { [key: string]: string } & { chunk_size?: string };
|
| 89 |
+
/**
|
| 90 |
+
* Whole number of seconds after local client time when transfer will expire.
|
| 91 |
+
* Preferred over `expires_at` if both are provided.
|
| 92 |
+
* Maximum of 2147483647, minimum of -2147483647.
|
| 93 |
+
*/
|
| 94 |
+
expires_in?: number;
|
| 95 |
+
/**
|
| 96 |
+
* String uppercase RFC 3339-formatted timestamp with second precision
|
| 97 |
+
* for when the given action expires (usually due to a temporary token).
|
| 98 |
+
*/
|
| 99 |
+
expires_at?: string;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
export interface ApiPreuploadRequest {
|
| 103 |
+
/**
|
| 104 |
+
* Optional, otherwise takes the existing content of `.gitattributes` for the revision.
|
| 105 |
+
*
|
| 106 |
+
* Provide this parameter if you plan to modify `.gitattributes` yourself at the same
|
| 107 |
+
* time as uploading LFS files.
|
| 108 |
+
*
|
| 109 |
+
* Note that this is not needed if you solely rely on automatic LFS detection from HF: the commit endpoint
|
| 110 |
+
* will automatically edit the `.gitattributes` file to track the files passed to its `lfsFiles` param.
|
| 111 |
+
*/
|
| 112 |
+
gitAttributes?: string;
|
| 113 |
+
files: Array<{
|
| 114 |
+
/**
|
| 115 |
+
* Path of the LFS file
|
| 116 |
+
*/
|
| 117 |
+
path: string;
|
| 118 |
+
/**
|
| 119 |
+
* Full size of the LFS file
|
| 120 |
+
*/
|
| 121 |
+
size: number;
|
| 122 |
+
/**
|
| 123 |
+
* Base64-encoded sample of the first 512 bytes of the file
|
| 124 |
+
*/
|
| 125 |
+
sample: string;
|
| 126 |
+
}>;
|
| 127 |
+
}
|
| 128 |
+
export interface ApiBucketBatchResponse {
|
| 129 |
+
/** True if all files were successfully added */
|
| 130 |
+
success: boolean;
|
| 131 |
+
/** Total number of operations attempted */
|
| 132 |
+
processed: number;
|
| 133 |
+
/** Number of successful operations */
|
| 134 |
+
succeeded: number;
|
| 135 |
+
/** List of failed operations */
|
| 136 |
+
failed: Array<{
|
| 137 |
+
path: string;
|
| 138 |
+
error: string;
|
| 139 |
+
}>;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
export interface ApiPreuploadResponse {
|
| 143 |
+
files: Array<{
|
| 144 |
+
path: string;
|
| 145 |
+
uploadMode: "lfs" | "regular";
|
| 146 |
+
}>;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
export interface ApiCommitHeader {
|
| 150 |
+
summary: string;
|
| 151 |
+
description?: string;
|
| 152 |
+
/**
|
| 153 |
+
* Parent commit. Optional
|
| 154 |
+
*
|
| 155 |
+
* - When opening a PR: will use parentCommit as the parent commit
|
| 156 |
+
* - When committing on a branch: Will make sure that there were no intermediate commits
|
| 157 |
+
*/
|
| 158 |
+
parentCommit?: string;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
export interface ApiCommitDeletedEntry {
|
| 162 |
+
path: string;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
export interface ApiCommitLfsFile {
|
| 166 |
+
path: string;
|
| 167 |
+
oldPath?: string;
|
| 168 |
+
/** Required if {@link oldPath} is not set */
|
| 169 |
+
algo?: "sha256";
|
| 170 |
+
/** Required if {@link oldPath} is not set */
|
| 171 |
+
oid?: string;
|
| 172 |
+
size?: number;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
export interface ApiCommitFile {
|
| 176 |
+
/** Required if {@link oldPath} is not set */
|
| 177 |
+
content?: string;
|
| 178 |
+
path: string;
|
| 179 |
+
oldPath?: string;
|
| 180 |
+
encoding?: "utf-8" | "base64";
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
export type ApiCommitOperation =
|
| 184 |
+
| {
|
| 185 |
+
key: "file";
|
| 186 |
+
value: ApiCommitFile;
|
| 187 |
+
}
|
| 188 |
+
| {
|
| 189 |
+
key: "lfsFile";
|
| 190 |
+
value: ApiCommitLfsFile;
|
| 191 |
+
}
|
| 192 |
+
| {
|
| 193 |
+
key: "deletedFile";
|
| 194 |
+
value: ApiCommitDeletedEntry;
|
| 195 |
+
};
|
| 196 |
+
|
| 197 |
+
export interface ApiCommitData {
|
| 198 |
+
id: string;
|
| 199 |
+
title: string;
|
| 200 |
+
message: string;
|
| 201 |
+
authors: Array<{ user: string; avatar: string }>;
|
| 202 |
+
date: string;
|
| 203 |
+
formatted?: string;
|
| 204 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-create-collection.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface ApiCreateCollectionPayload {
|
| 2 |
+
/**
|
| 3 |
+
* Title of the collection to create.
|
| 4 |
+
*/
|
| 5 |
+
title: string;
|
| 6 |
+
/**
|
| 7 |
+
* Namespace of the collection to create (username or org).
|
| 8 |
+
*/
|
| 9 |
+
namespace: string;
|
| 10 |
+
/**
|
| 11 |
+
* Description of the collection to create.
|
| 12 |
+
*/
|
| 13 |
+
description?: string;
|
| 14 |
+
/**
|
| 15 |
+
* Whether the collection should be private or not. Defaults to False (i.e. public collection).
|
| 16 |
+
* @default false
|
| 17 |
+
*/
|
| 18 |
+
private?: boolean;
|
| 19 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-create-repo.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { SetRequired } from "../../vendor/type-fest/set-required";
|
| 2 |
+
import type { RepoType, SpaceHardwareFlavor, SpaceSdk } from "../public";
|
| 3 |
+
import type { ApiCommitFile } from "./api-commit";
|
| 4 |
+
|
| 5 |
+
export type ApiCreateRepoPayload = {
|
| 6 |
+
name: string;
|
| 7 |
+
canonical?: boolean;
|
| 8 |
+
license?: string;
|
| 9 |
+
resourceGroupId?: string;
|
| 10 |
+
template?: string;
|
| 11 |
+
organization?: string;
|
| 12 |
+
/** @default false */
|
| 13 |
+
private?: boolean;
|
| 14 |
+
lfsmultipartthresh?: number;
|
| 15 |
+
files?: SetRequired<ApiCommitFile, "content">[];
|
| 16 |
+
} & (
|
| 17 |
+
| {
|
| 18 |
+
type: Exclude<RepoType, "space">;
|
| 19 |
+
}
|
| 20 |
+
| {
|
| 21 |
+
type: "space";
|
| 22 |
+
hardware?: SpaceHardwareFlavor;
|
| 23 |
+
sdk: SpaceSdk;
|
| 24 |
+
sdkVersion?: string;
|
| 25 |
+
}
|
| 26 |
+
);
|
node_modules/@huggingface/hub/src/types/api/api-dataset.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { License } from "../public";
|
| 2 |
+
|
| 3 |
+
export interface ApiDatasetInfo {
|
| 4 |
+
_id: string;
|
| 5 |
+
id: string;
|
| 6 |
+
arxivIds?: string[];
|
| 7 |
+
author?: string;
|
| 8 |
+
cardExists?: true;
|
| 9 |
+
cardError?: unknown;
|
| 10 |
+
cardData?: ApiDatasetMetadata;
|
| 11 |
+
contributors?: Array<{ user: string; _id: string }>;
|
| 12 |
+
disabled: boolean;
|
| 13 |
+
discussionsDisabled: boolean;
|
| 14 |
+
gated: false | "auto" | "manual";
|
| 15 |
+
gitalyUid: string;
|
| 16 |
+
lastAuthor: { email: string; user?: string };
|
| 17 |
+
lastModified: string; // date
|
| 18 |
+
likes: number;
|
| 19 |
+
likesRecent: number;
|
| 20 |
+
private: boolean;
|
| 21 |
+
updatedAt: string; // date
|
| 22 |
+
createdAt: string; // date
|
| 23 |
+
tags: string[];
|
| 24 |
+
paperswithcode_id?: string;
|
| 25 |
+
sha: string;
|
| 26 |
+
files?: string[];
|
| 27 |
+
citation?: string;
|
| 28 |
+
description?: string;
|
| 29 |
+
downloads: number;
|
| 30 |
+
downloadsAllTime: number;
|
| 31 |
+
previewable?: boolean;
|
| 32 |
+
doi?: { id: string; commit: string };
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
export interface ApiDatasetMetadata {
|
| 36 |
+
licenses?: undefined;
|
| 37 |
+
license?: License | License[];
|
| 38 |
+
license_name?: string;
|
| 39 |
+
license_link?: "LICENSE" | "LICENSE.md" | string;
|
| 40 |
+
license_details?: string;
|
| 41 |
+
languages?: undefined;
|
| 42 |
+
language?: string | string[];
|
| 43 |
+
language_bcp47?: string[];
|
| 44 |
+
language_details?: string;
|
| 45 |
+
tags?: string[];
|
| 46 |
+
task_categories?: string[];
|
| 47 |
+
task_ids?: string[];
|
| 48 |
+
config_names?: string[];
|
| 49 |
+
configs?: {
|
| 50 |
+
config_name: string;
|
| 51 |
+
data_files?:
|
| 52 |
+
| string
|
| 53 |
+
| string[]
|
| 54 |
+
| {
|
| 55 |
+
split: string;
|
| 56 |
+
path: string | string[];
|
| 57 |
+
}[];
|
| 58 |
+
data_dir?: string;
|
| 59 |
+
}[];
|
| 60 |
+
benchmark?: string;
|
| 61 |
+
paperswithcode_id?: string | null;
|
| 62 |
+
pretty_name?: string;
|
| 63 |
+
viewer?: boolean;
|
| 64 |
+
viewer_display_urls?: boolean;
|
| 65 |
+
thumbnail?: string | null;
|
| 66 |
+
description?: string | null;
|
| 67 |
+
annotations_creators?: string[];
|
| 68 |
+
language_creators?: string[];
|
| 69 |
+
multilinguality?: string[];
|
| 70 |
+
size_categories?: string[];
|
| 71 |
+
source_datasets?: string[];
|
| 72 |
+
extra_gated_prompt?: string;
|
| 73 |
+
extra_gated_fields?: {
|
| 74 |
+
/**
|
| 75 |
+
* "text" | "checkbox" | "date_picker" | "country" | "ip_location" | { type: "text" | "checkbox" | "date_picker" | "country" | "ip_location" } | { type: "select", options: Array<string | { label: string; value: string; }> } Property
|
| 76 |
+
*/
|
| 77 |
+
[x: string]:
|
| 78 |
+
| "text"
|
| 79 |
+
| "checkbox"
|
| 80 |
+
| "date_picker"
|
| 81 |
+
| "country"
|
| 82 |
+
| "ip_location"
|
| 83 |
+
| { type: "text" | "checkbox" | "date_picker" | "country" | "ip_location" }
|
| 84 |
+
| { type: "select"; options: Array<string | { label: string; value: string }> };
|
| 85 |
+
};
|
| 86 |
+
extra_gated_heading?: string;
|
| 87 |
+
extra_gated_description?: string;
|
| 88 |
+
extra_gated_button_content?: string;
|
| 89 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-index-tree.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface ApiIndexTreeEntry {
|
| 2 |
+
type: "file" | "directory" | "unknown";
|
| 3 |
+
size: number;
|
| 4 |
+
path: string;
|
| 5 |
+
oid: string;
|
| 6 |
+
lfs?: {
|
| 7 |
+
oid: string;
|
| 8 |
+
size: number;
|
| 9 |
+
/** Size of the raw pointer file, 100~200 bytes */
|
| 10 |
+
pointerSize: number;
|
| 11 |
+
};
|
| 12 |
+
lastCommit?: {
|
| 13 |
+
date: string;
|
| 14 |
+
id: string;
|
| 15 |
+
title: string;
|
| 16 |
+
};
|
| 17 |
+
security?: ApiFileScanResult;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export interface ApiFileScanResult {
|
| 21 |
+
/** namespaced by repo type (models/, datasets/, spaces/) */
|
| 22 |
+
repositoryId: string;
|
| 23 |
+
blobId: string;
|
| 24 |
+
name: string;
|
| 25 |
+
safe: boolean;
|
| 26 |
+
avScan?: ApiAVScan;
|
| 27 |
+
pickleImportScan?: ApiPickleImportScan;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
interface ApiAVScan {
|
| 31 |
+
virusFound: boolean;
|
| 32 |
+
virusNames?: string[];
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
type ApiSafetyLevel = "innocuous" | "suspicious" | "dangerous";
|
| 36 |
+
|
| 37 |
+
interface ApiPickleImport {
|
| 38 |
+
module: string;
|
| 39 |
+
name: string;
|
| 40 |
+
safety: ApiSafetyLevel;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
interface ApiPickleImportScan {
|
| 44 |
+
highestSafetyLevel: ApiSafetyLevel;
|
| 45 |
+
imports: ApiPickleImport[];
|
| 46 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-jobs.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { SpaceHardwareFlavor } from "../public";
|
| 2 |
+
|
| 3 |
+
export interface ApiJobHardware {
|
| 4 |
+
name: string;
|
| 5 |
+
prettyName: string;
|
| 6 |
+
cpu: string;
|
| 7 |
+
ram: string;
|
| 8 |
+
accelerator: {
|
| 9 |
+
type: "gpu" | "neuron";
|
| 10 |
+
model: string;
|
| 11 |
+
quantity: string;
|
| 12 |
+
vram: string;
|
| 13 |
+
manufacturer: "Nvidia" | "AWS";
|
| 14 |
+
} | null;
|
| 15 |
+
unitCostMicroUSD: number;
|
| 16 |
+
unitCostUSD: number;
|
| 17 |
+
unitLabel: string;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export type JobStatusStage = "DELETING" | "RUNNING" | "PAUSED" | "STOPPED" | "UPDATING" | "ERROR";
|
| 21 |
+
|
| 22 |
+
export interface ApiJobStatus {
|
| 23 |
+
stage: JobStatusStage;
|
| 24 |
+
message?: string | null;
|
| 25 |
+
failureCount: number;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export interface ApiJobUser {
|
| 29 |
+
id: string;
|
| 30 |
+
name: string;
|
| 31 |
+
type?: "user" | "org";
|
| 32 |
+
avatarUrl?: string;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
export interface ApiJob {
|
| 36 |
+
type: "job";
|
| 37 |
+
id: string;
|
| 38 |
+
status: ApiJobStatus;
|
| 39 |
+
createdAt: string;
|
| 40 |
+
updatedAt?: string;
|
| 41 |
+
startedAt?: string | null;
|
| 42 |
+
finishedAt?: string | null;
|
| 43 |
+
createdBy?: {
|
| 44 |
+
id: string;
|
| 45 |
+
name: string;
|
| 46 |
+
};
|
| 47 |
+
dockerImage?: string | null;
|
| 48 |
+
spaceId?: string | null;
|
| 49 |
+
command?: string[] | null;
|
| 50 |
+
arguments?: string[] | null;
|
| 51 |
+
environment?: Record<string, string> | null;
|
| 52 |
+
flavor: SpaceHardwareFlavor;
|
| 53 |
+
arch?: "amd64" | "arm64" | null;
|
| 54 |
+
timeoutSeconds?: number | null;
|
| 55 |
+
attempts?: number;
|
| 56 |
+
owner?: ApiJobUser;
|
| 57 |
+
initiator?: ApiJobUser;
|
| 58 |
+
secrets?: string[];
|
| 59 |
+
labels?: Record<string, string> | null;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
export interface ApiScheduledJob {
|
| 63 |
+
id: string;
|
| 64 |
+
schedule: string;
|
| 65 |
+
suspend: boolean;
|
| 66 |
+
concurrency: boolean;
|
| 67 |
+
createdAt: string;
|
| 68 |
+
updatedAt: string;
|
| 69 |
+
jobSpec: {
|
| 70 |
+
dockerImage?: string | null;
|
| 71 |
+
spaceId?: string | null;
|
| 72 |
+
command?: string[] | null;
|
| 73 |
+
environment?: Record<string, string> | null;
|
| 74 |
+
flavor: SpaceHardwareFlavor;
|
| 75 |
+
arch?: "amd64" | "arm64" | null;
|
| 76 |
+
timeoutSeconds?: number | null;
|
| 77 |
+
attempts?: number;
|
| 78 |
+
labels?: Record<string, string> | null;
|
| 79 |
+
};
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
export interface CreateJobOptions {
|
| 83 |
+
/**
|
| 84 |
+
* The Docker image to run (e.g., "python:3.12" or "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel")
|
| 85 |
+
*/
|
| 86 |
+
dockerImage?: string;
|
| 87 |
+
/**
|
| 88 |
+
* The Space ID to run (e.g., "username/space-name")
|
| 89 |
+
*/
|
| 90 |
+
spaceId?: string;
|
| 91 |
+
/**
|
| 92 |
+
* The command to run (array of strings)
|
| 93 |
+
*/
|
| 94 |
+
command?: string[];
|
| 95 |
+
/**
|
| 96 |
+
* Additional arguments to pass to the command
|
| 97 |
+
*/
|
| 98 |
+
arguments?: string[];
|
| 99 |
+
/**
|
| 100 |
+
* Environment variables to set
|
| 101 |
+
*/
|
| 102 |
+
environment?: Record<string, string>;
|
| 103 |
+
/**
|
| 104 |
+
* Secrets to pass (will be encrypted server-side)
|
| 105 |
+
*/
|
| 106 |
+
secrets?: Record<string, string>;
|
| 107 |
+
/**
|
| 108 |
+
* Hardware flavor to use
|
| 109 |
+
*/
|
| 110 |
+
flavor: SpaceHardwareFlavor;
|
| 111 |
+
/**
|
| 112 |
+
* Architecture (defaults to "amd64")
|
| 113 |
+
*/
|
| 114 |
+
arch?: "amd64" | "arm64";
|
| 115 |
+
/**
|
| 116 |
+
* Timeout in seconds
|
| 117 |
+
*/
|
| 118 |
+
timeoutSeconds?: number | null;
|
| 119 |
+
/**
|
| 120 |
+
* Maximum number of attempts (defaults to 1)
|
| 121 |
+
*/
|
| 122 |
+
attempts?: number;
|
| 123 |
+
/**
|
| 124 |
+
* Labels to attach to the job (key-value pairs)
|
| 125 |
+
*/
|
| 126 |
+
labels?: Record<string, string>;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
export interface CreateScheduledJobOptions {
|
| 130 |
+
/**
|
| 131 |
+
* The job specification
|
| 132 |
+
*/
|
| 133 |
+
jobSpec: Omit<CreateJobOptions, "arguments">;
|
| 134 |
+
/**
|
| 135 |
+
* CRON schedule expression (e.g., "0 9 * * 1" for 9 AM every Monday) or shortcuts like "@hourly", "@daily"
|
| 136 |
+
*/
|
| 137 |
+
schedule: string;
|
| 138 |
+
/**
|
| 139 |
+
* Whether the scheduled job is suspended (paused)
|
| 140 |
+
*/
|
| 141 |
+
suspend?: boolean;
|
| 142 |
+
/**
|
| 143 |
+
* Whether multiple instances of this job can run concurrently
|
| 144 |
+
*/
|
| 145 |
+
concurrency?: boolean;
|
| 146 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-model.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { ModelLibraryKey, TransformersInfo, WidgetType } from "@huggingface/tasks";
|
| 2 |
+
import type { License, PipelineType } from "../public";
|
| 3 |
+
|
| 4 |
+
export interface ApiModelInfo {
|
| 5 |
+
_id: string;
|
| 6 |
+
id: string;
|
| 7 |
+
arxivIds: string[];
|
| 8 |
+
author?: string;
|
| 9 |
+
cardData?: ApiModelMetadata;
|
| 10 |
+
cardError: unknown;
|
| 11 |
+
cardExists?: true;
|
| 12 |
+
config: unknown;
|
| 13 |
+
contributors: Array<{ user: string; _id: string }>;
|
| 14 |
+
disabled: boolean;
|
| 15 |
+
discussionsDisabled: boolean;
|
| 16 |
+
doi?: { id: string; commit: string };
|
| 17 |
+
downloads: number;
|
| 18 |
+
downloadsAllTime: number;
|
| 19 |
+
files: string[];
|
| 20 |
+
gitalyUid: string;
|
| 21 |
+
inferenceProviderMapping?: ApiModelInferenceProviderMappingEntry[];
|
| 22 |
+
lastAuthor: { email: string; user?: string };
|
| 23 |
+
lastModified: string; // convert to date
|
| 24 |
+
library_name?: ModelLibraryKey;
|
| 25 |
+
likes: number;
|
| 26 |
+
likesRecent: number;
|
| 27 |
+
private: boolean;
|
| 28 |
+
gated: false | "auto" | "manual";
|
| 29 |
+
sha: string;
|
| 30 |
+
spaces: string[];
|
| 31 |
+
updatedAt: string; // convert to date
|
| 32 |
+
createdAt: string; // convert to date
|
| 33 |
+
pipeline_tag: PipelineType;
|
| 34 |
+
tags: string[];
|
| 35 |
+
"model-index": unknown;
|
| 36 |
+
safetensors?: {
|
| 37 |
+
parameters: Record<string, number>;
|
| 38 |
+
total: number;
|
| 39 |
+
};
|
| 40 |
+
transformersInfo?: TransformersInfo;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export interface ApiModelIndex {
|
| 44 |
+
name: string;
|
| 45 |
+
results: {
|
| 46 |
+
task: {
|
| 47 |
+
/**
|
| 48 |
+
* Example: automatic-speech-recognition
|
| 49 |
+
Use task id from https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/tasksData.ts
|
| 50 |
+
*/
|
| 51 |
+
type: string;
|
| 52 |
+
/**
|
| 53 |
+
* Example: Speech Recognition
|
| 54 |
+
*/
|
| 55 |
+
name?: string;
|
| 56 |
+
};
|
| 57 |
+
/**
|
| 58 |
+
* This will switch to required at some point.
|
| 59 |
+
in any case, we need them to link to PWC
|
| 60 |
+
*/
|
| 61 |
+
dataset?: {
|
| 62 |
+
/**
|
| 63 |
+
* Example: common_voice. Use dataset id from https://hf.co/datasets
|
| 64 |
+
*/
|
| 65 |
+
type: string;
|
| 66 |
+
/**
|
| 67 |
+
* A pretty name for the dataset. Example: Common Voice zh-CN
|
| 68 |
+
Also encode config params into the name if relevant.
|
| 69 |
+
*/
|
| 70 |
+
name: string;
|
| 71 |
+
/**
|
| 72 |
+
* Optional. The name of the dataset configuration used in `load_dataset()`
|
| 73 |
+
*/
|
| 74 |
+
config?: string;
|
| 75 |
+
/**
|
| 76 |
+
* Optional. Example: test
|
| 77 |
+
*/
|
| 78 |
+
split?: string;
|
| 79 |
+
/**
|
| 80 |
+
* Optional. Example: 5503434ddd753f426f4b38109466949a1217c2bb
|
| 81 |
+
*/
|
| 82 |
+
revision?: string;
|
| 83 |
+
args?:
|
| 84 |
+
| string
|
| 85 |
+
| {
|
| 86 |
+
/**
|
| 87 |
+
* String Property
|
| 88 |
+
*/
|
| 89 |
+
[x: string]: string;
|
| 90 |
+
};
|
| 91 |
+
};
|
| 92 |
+
metrics: {
|
| 93 |
+
/**
|
| 94 |
+
* Example: wer. Use metric id from https://hf.co/metrics
|
| 95 |
+
*/
|
| 96 |
+
type: string;
|
| 97 |
+
/**
|
| 98 |
+
* Required. Example: 20.0 or "20.0 ± 1.2"
|
| 99 |
+
*/
|
| 100 |
+
value: unknown;
|
| 101 |
+
/**
|
| 102 |
+
* Example: Test WER
|
| 103 |
+
*/
|
| 104 |
+
name?: string;
|
| 105 |
+
/**
|
| 106 |
+
* Optional. The name of the metric configuration used in `load_metric()`.
|
| 107 |
+
*/
|
| 108 |
+
config?: string;
|
| 109 |
+
args?:
|
| 110 |
+
| string
|
| 111 |
+
| {
|
| 112 |
+
/**
|
| 113 |
+
* String Property
|
| 114 |
+
*/
|
| 115 |
+
[x: string]: string;
|
| 116 |
+
};
|
| 117 |
+
/**
|
| 118 |
+
* [Automatically computed, do not set] Dynamically overridden by huggingface in API calls to indicate if it was verified by Hugging Face.
|
| 119 |
+
*/
|
| 120 |
+
verified?: boolean;
|
| 121 |
+
/**
|
| 122 |
+
* Generated by Hugging Face to prove the results are valid. <add doc link>
|
| 123 |
+
*/
|
| 124 |
+
verifyToken?: string;
|
| 125 |
+
}[];
|
| 126 |
+
/**
|
| 127 |
+
* The source for this evaluation result.
|
| 128 |
+
*/
|
| 129 |
+
source?: {
|
| 130 |
+
/**
|
| 131 |
+
* Example: Open LLM Leaderboard
|
| 132 |
+
*/
|
| 133 |
+
name?: string;
|
| 134 |
+
/**
|
| 135 |
+
* Example: https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard
|
| 136 |
+
*/
|
| 137 |
+
url: string;
|
| 138 |
+
};
|
| 139 |
+
}[];
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
export interface ApiWidgetExampleFromModelcard {
|
| 143 |
+
example_title?: string;
|
| 144 |
+
group?: string;
|
| 145 |
+
text?: string;
|
| 146 |
+
src?: string;
|
| 147 |
+
table?: {
|
| 148 |
+
/**
|
| 149 |
+
* (string | number)[] Property
|
| 150 |
+
*/
|
| 151 |
+
[x: string]: (string | number)[];
|
| 152 |
+
};
|
| 153 |
+
structured_data?: {
|
| 154 |
+
/**
|
| 155 |
+
* (string | number)[] Property
|
| 156 |
+
*/
|
| 157 |
+
[x: string]: (string | number)[];
|
| 158 |
+
};
|
| 159 |
+
candidate_labels?: string;
|
| 160 |
+
messages?: {
|
| 161 |
+
role: "system" | "user" | "assistant";
|
| 162 |
+
content: string;
|
| 163 |
+
}[];
|
| 164 |
+
multi_class?: boolean;
|
| 165 |
+
source_sentence?: string;
|
| 166 |
+
sentences?: string[];
|
| 167 |
+
parameters?: {
|
| 168 |
+
aggregation_strategy?: string;
|
| 169 |
+
top_k?: number;
|
| 170 |
+
top_p?: number;
|
| 171 |
+
temperature?: number;
|
| 172 |
+
max_new_tokens?: number;
|
| 173 |
+
do_sample?: boolean;
|
| 174 |
+
negative_prompt?: string;
|
| 175 |
+
guidance_scale?: number;
|
| 176 |
+
num_inference_steps?: number;
|
| 177 |
+
};
|
| 178 |
+
output?:
|
| 179 |
+
| {
|
| 180 |
+
label: string;
|
| 181 |
+
score: number;
|
| 182 |
+
}[]
|
| 183 |
+
| {
|
| 184 |
+
answer: string;
|
| 185 |
+
score: number;
|
| 186 |
+
}
|
| 187 |
+
| {
|
| 188 |
+
text: string;
|
| 189 |
+
}
|
| 190 |
+
| {
|
| 191 |
+
url: string;
|
| 192 |
+
};
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export interface ApiModelMetadata {
|
| 196 |
+
datasets?: string | string[];
|
| 197 |
+
license?: License | License[];
|
| 198 |
+
license_name?: string;
|
| 199 |
+
license_link?: "LICENSE" | "LICENSE.md" | string;
|
| 200 |
+
license_details?: string;
|
| 201 |
+
inference?:
|
| 202 |
+
| boolean
|
| 203 |
+
| {
|
| 204 |
+
parameters?: {
|
| 205 |
+
aggregation_strategy?: string;
|
| 206 |
+
top_k?: number;
|
| 207 |
+
top_p?: number;
|
| 208 |
+
temperature?: number;
|
| 209 |
+
max_new_tokens?: number;
|
| 210 |
+
do_sample?: boolean;
|
| 211 |
+
negative_prompt?: string;
|
| 212 |
+
guidance_scale?: number;
|
| 213 |
+
num_inference_steps?: number;
|
| 214 |
+
};
|
| 215 |
+
};
|
| 216 |
+
language?: string | string[];
|
| 217 |
+
language_bcp47?: string[];
|
| 218 |
+
language_details?: string;
|
| 219 |
+
tags?: string[];
|
| 220 |
+
pipeline_tag?: string;
|
| 221 |
+
co2_eq_emissions?:
|
| 222 |
+
| number
|
| 223 |
+
| {
|
| 224 |
+
/**
|
| 225 |
+
* Emissions in grams of CO2
|
| 226 |
+
*/
|
| 227 |
+
emissions: number;
|
| 228 |
+
/**
|
| 229 |
+
* source of the information, either directly from AutoTrain, code carbon or from a scientific article documenting the model
|
| 230 |
+
*/
|
| 231 |
+
source?: string;
|
| 232 |
+
/**
|
| 233 |
+
* pre-training or fine-tuning
|
| 234 |
+
*/
|
| 235 |
+
training_type?: string;
|
| 236 |
+
/**
|
| 237 |
+
* as granular as possible, for instance Quebec, Canada or Brooklyn, NY, USA
|
| 238 |
+
*/
|
| 239 |
+
geographical_location?: string;
|
| 240 |
+
/**
|
| 241 |
+
* how much compute and what kind, e.g. 8 v100 GPUs
|
| 242 |
+
*/
|
| 243 |
+
hardware_used?: string;
|
| 244 |
+
};
|
| 245 |
+
library_name?: string;
|
| 246 |
+
thumbnail?: string | null;
|
| 247 |
+
description?: string | null;
|
| 248 |
+
mask_token?: string;
|
| 249 |
+
widget?: ApiWidgetExampleFromModelcard[];
|
| 250 |
+
"model-index"?: ApiModelIndex[];
|
| 251 |
+
finetuned_from?: string;
|
| 252 |
+
base_model?: string | string[];
|
| 253 |
+
instance_prompt?: string | null;
|
| 254 |
+
extra_gated_prompt?: string;
|
| 255 |
+
extra_gated_fields?: {
|
| 256 |
+
/**
|
| 257 |
+
* "text" | "checkbox" | "date_picker" | "country" | "ip_location" | { type: "text" | "checkbox" | "date_picker" | "country" | "ip_location" } | { type: "select", options: Array<string | { label: string; value: string; }> } Property
|
| 258 |
+
*/
|
| 259 |
+
[x: string]:
|
| 260 |
+
| "text"
|
| 261 |
+
| "checkbox"
|
| 262 |
+
| "date_picker"
|
| 263 |
+
| "country"
|
| 264 |
+
| "ip_location"
|
| 265 |
+
| { type: "text" | "checkbox" | "date_picker" | "country" | "ip_location" }
|
| 266 |
+
| { type: "select"; options: Array<string | { label: string; value: string }> };
|
| 267 |
+
};
|
| 268 |
+
extra_gated_heading?: string;
|
| 269 |
+
extra_gated_description?: string;
|
| 270 |
+
extra_gated_button_content?: string;
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
export interface ApiModelInferenceProviderMappingEntry {
|
| 274 |
+
provider: string; // Provider name
|
| 275 |
+
hfModelId: string; // ID of the model on the Hugging Face Hub
|
| 276 |
+
providerId: string; // ID of the model on the provider's side
|
| 277 |
+
status: "live" | "staging";
|
| 278 |
+
task: WidgetType;
|
| 279 |
+
adapter?: string;
|
| 280 |
+
adapterWeightsPath?: string;
|
| 281 |
+
type?: "single-file" | "tag-filter";
|
| 282 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-space.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { License, SpaceRuntime, SpaceSdk } from "../public";
|
| 2 |
+
|
| 3 |
+
type Color = "red" | "yellow" | "green" | "blue" | "indigo" | "purple" | "pink" | "gray";
|
| 4 |
+
|
| 5 |
+
export interface ApiSpaceInfo {
|
| 6 |
+
_id: string;
|
| 7 |
+
id: string;
|
| 8 |
+
arxivIds?: string[];
|
| 9 |
+
author: string;
|
| 10 |
+
cardExists?: true;
|
| 11 |
+
cardError?: unknown;
|
| 12 |
+
cardData?: unknown;
|
| 13 |
+
contributors?: Array<{ user: string; _id: string }>;
|
| 14 |
+
disabled: boolean;
|
| 15 |
+
discussionsDisabled: boolean;
|
| 16 |
+
duplicationDisabled: boolean;
|
| 17 |
+
gated: false | "auto" | "manual";
|
| 18 |
+
gitalyUid: string;
|
| 19 |
+
lastAuthor: { email: string; user?: string };
|
| 20 |
+
lastModified: string; // date
|
| 21 |
+
likes: number;
|
| 22 |
+
likesRecent: number;
|
| 23 |
+
private: boolean;
|
| 24 |
+
updatedAt: string; // date
|
| 25 |
+
createdAt: string; // date
|
| 26 |
+
tags: string[];
|
| 27 |
+
sha: string;
|
| 28 |
+
subdomain: string;
|
| 29 |
+
title: string;
|
| 30 |
+
emoji: string;
|
| 31 |
+
colorFrom: Color;
|
| 32 |
+
colorTo: Color;
|
| 33 |
+
pinned: boolean;
|
| 34 |
+
siblings: Array<{ rfilename: string }>;
|
| 35 |
+
sdk?: SpaceSdk;
|
| 36 |
+
runtime?: SpaceRuntime;
|
| 37 |
+
models?: string[];
|
| 38 |
+
datasets?: string[];
|
| 39 |
+
originSpace?: { _id: string; authorId: string };
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
export interface ApiSpaceMetadata {
|
| 43 |
+
license?: License | License[];
|
| 44 |
+
tags?: string[];
|
| 45 |
+
title?: string;
|
| 46 |
+
colorFrom?: "red" | "yellow" | "green" | "blue" | "indigo" | "purple" | "pink" | "gray";
|
| 47 |
+
colorTo?: "red" | "yellow" | "green" | "blue" | "indigo" | "purple" | "pink" | "gray";
|
| 48 |
+
emoji?: string;
|
| 49 |
+
sdk?: "streamlit" | "gradio" | "docker" | "static";
|
| 50 |
+
sdk_version?: string | string;
|
| 51 |
+
python_version?: string | string;
|
| 52 |
+
fullWidth?: boolean;
|
| 53 |
+
header?: "mini" | "default";
|
| 54 |
+
app_file?: string;
|
| 55 |
+
app_port?: number;
|
| 56 |
+
base_path?: string;
|
| 57 |
+
models?: string[];
|
| 58 |
+
datasets?: string[];
|
| 59 |
+
pinned?: boolean;
|
| 60 |
+
metaTitle?: string;
|
| 61 |
+
description?: string;
|
| 62 |
+
thumbnail?: string;
|
| 63 |
+
/**
|
| 64 |
+
* If enabled, will associate an oauth app to the Space, adding variables and secrets to the Space's environment
|
| 65 |
+
*/
|
| 66 |
+
hf_oauth?: boolean;
|
| 67 |
+
/**
|
| 68 |
+
* The expiration of access tokens for your oauth app in minutes. max 30 days (43,200 minutes). Defaults to 8 hours (480 minutes)
|
| 69 |
+
*/
|
| 70 |
+
hf_oauth_expiration_minutes?: number;
|
| 71 |
+
/**
|
| 72 |
+
* OAuth scopes to request. By default you have access to the user's profile, you can request access to their repos or inference-api.
|
| 73 |
+
*/
|
| 74 |
+
hf_oauth_scopes?: ("email" | "read-repos" | "write-repos" | "manage-repos" | "inference-api")[];
|
| 75 |
+
suggested_hardware?:
|
| 76 |
+
| "cpu-basic"
|
| 77 |
+
| "zero-a10g"
|
| 78 |
+
| "cpu-upgrade"
|
| 79 |
+
| "cpu-xl"
|
| 80 |
+
| "t4-small"
|
| 81 |
+
| "t4-medium"
|
| 82 |
+
| "a10g-small"
|
| 83 |
+
| "a10g-large"
|
| 84 |
+
| "a10g-largex2"
|
| 85 |
+
| "a10g-largex4"
|
| 86 |
+
| "a100-large";
|
| 87 |
+
suggested_storage?: "small" | "medium" | "large";
|
| 88 |
+
custom_headers?: {
|
| 89 |
+
"cross-origin-embedder-policy"?: "unsafe-none" | "require-corp" | "credentialless";
|
| 90 |
+
"cross-origin-opener-policy"?: "same-origin" | "same-origin-allow-popups" | "unsafe-none";
|
| 91 |
+
"cross-origin-resource-policy"?: "same-site" | "same-origin" | "cross-origin";
|
| 92 |
+
};
|
| 93 |
+
}
|
node_modules/@huggingface/hub/src/types/api/api-who-am-i.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { AccessTokenRole, AuthType } from "../public";
|
| 2 |
+
|
| 3 |
+
interface ApiWhoAmIBase {
|
| 4 |
+
/** Unique ID persistent across renames */
|
| 5 |
+
id: string;
|
| 6 |
+
type: "user" | "org" | "app";
|
| 7 |
+
name: string;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
interface ApiWhoAmIEntityBase extends ApiWhoAmIBase {
|
| 11 |
+
fullname: string;
|
| 12 |
+
email: string | null;
|
| 13 |
+
canPay: boolean;
|
| 14 |
+
avatarUrl: string;
|
| 15 |
+
/**
|
| 16 |
+
* Unix timestamp in seconds
|
| 17 |
+
*/
|
| 18 |
+
periodEnd: number | null;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
interface ApiWhoAmIOrg extends ApiWhoAmIEntityBase {
|
| 22 |
+
type: "org";
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
interface ApiWhoAmIUser extends ApiWhoAmIEntityBase {
|
| 26 |
+
type: "user";
|
| 27 |
+
email: string;
|
| 28 |
+
emailVerified: boolean;
|
| 29 |
+
isPro: boolean;
|
| 30 |
+
orgs: ApiWhoAmIOrg[];
|
| 31 |
+
billingMode: "postpaid" | "prepaid";
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
interface ApiWhoAmIApp extends ApiWhoAmIBase {
|
| 35 |
+
type: "app";
|
| 36 |
+
name: string;
|
| 37 |
+
scope?: {
|
| 38 |
+
entities: string[];
|
| 39 |
+
role: AccessTokenRole;
|
| 40 |
+
};
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export type ApiWhoAmIReponse = ApiWhoAmIUser | ApiWhoAmIOrg | ApiWhoAmIApp;
|
| 44 |
+
|
| 45 |
+
export interface ApiWhoAmIAuthInfo {
|
| 46 |
+
type: AuthType;
|
| 47 |
+
accessToken?: {
|
| 48 |
+
displayName: string;
|
| 49 |
+
expiration?: string;
|
| 50 |
+
role: AccessTokenRole;
|
| 51 |
+
};
|
| 52 |
+
}
|
node_modules/@huggingface/hub/src/types/public.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { PipelineType } from "@huggingface/tasks";
|
| 2 |
+
|
| 3 |
+
export type RepoType = "space" | "dataset" | "model" | "bucket";
|
| 4 |
+
|
| 5 |
+
export interface RepoId {
|
| 6 |
+
name: string;
|
| 7 |
+
type: RepoType;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export type RepoFullName = string | `spaces/${string}` | `datasets/${string}` | `buckets/${string}`;
|
| 11 |
+
|
| 12 |
+
export type RepoDesignation = RepoId | RepoFullName;
|
| 13 |
+
|
| 14 |
+
/** Actually `hf_${string}`, but for convenience, using the string type */
|
| 15 |
+
export type AccessToken = string;
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* @deprecated Use `AccessToken` instead. Pass { accessToken: "hf_..." } instead of { credentials: { accessToken: "hf_..." } }
|
| 19 |
+
*/
|
| 20 |
+
export interface Credentials {
|
| 21 |
+
accessToken: AccessToken;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export type CredentialsParams =
|
| 25 |
+
| {
|
| 26 |
+
accessToken?: undefined;
|
| 27 |
+
/**
|
| 28 |
+
* @deprecated Use `accessToken` instead
|
| 29 |
+
*/
|
| 30 |
+
credentials: Credentials;
|
| 31 |
+
}
|
| 32 |
+
| {
|
| 33 |
+
accessToken: AccessToken;
|
| 34 |
+
/**
|
| 35 |
+
* @deprecated Use `accessToken` instead
|
| 36 |
+
*/
|
| 37 |
+
credentials?: undefined;
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
export type SpaceHardwareFlavor =
|
| 41 |
+
| "cpu-basic"
|
| 42 |
+
| "cpu-upgrade"
|
| 43 |
+
| "cpu-performance"
|
| 44 |
+
| "cpu-xl"
|
| 45 |
+
| "sprx8"
|
| 46 |
+
| "zero-a10g"
|
| 47 |
+
| "inf2x6"
|
| 48 |
+
| "t4-small"
|
| 49 |
+
| "t4-medium"
|
| 50 |
+
| "l4x1"
|
| 51 |
+
| "l4x4"
|
| 52 |
+
| "l40sx1"
|
| 53 |
+
| "l40sx4"
|
| 54 |
+
| "l40sx8"
|
| 55 |
+
| "a10g-small"
|
| 56 |
+
| "a10g-large"
|
| 57 |
+
| "a10g-largex2"
|
| 58 |
+
| "a10g-largex4"
|
| 59 |
+
| "a100-large"
|
| 60 |
+
| "a100x4"
|
| 61 |
+
| "a100x8";
|
| 62 |
+
|
| 63 |
+
export type SpaceSdk = "streamlit" | "gradio" | "docker" | "static";
|
| 64 |
+
|
| 65 |
+
export type SpaceStage =
|
| 66 |
+
| "NO_APP_FILE"
|
| 67 |
+
| "CONFIG_ERROR"
|
| 68 |
+
| "BUILDING"
|
| 69 |
+
| "BUILD_ERROR"
|
| 70 |
+
| "RUNNING"
|
| 71 |
+
| "RUNNING_BUILDING"
|
| 72 |
+
| "RUNTIME_ERROR"
|
| 73 |
+
| "DELETING"
|
| 74 |
+
| "PAUSED"
|
| 75 |
+
| "SLEEPING";
|
| 76 |
+
|
| 77 |
+
export type AccessTokenRole = "admin" | "write" | "contributor" | "read";
|
| 78 |
+
|
| 79 |
+
export type AuthType = "access_token" | "app_token" | "app_token_as_user";
|
| 80 |
+
|
| 81 |
+
export type { PipelineType };
|
| 82 |
+
|
| 83 |
+
export interface SpaceRuntime {
|
| 84 |
+
stage: SpaceStage;
|
| 85 |
+
sdk?: SpaceSdk;
|
| 86 |
+
sdkVersion?: string;
|
| 87 |
+
errorMessage?: string;
|
| 88 |
+
hardware?: {
|
| 89 |
+
current: SpaceHardwareFlavor | null;
|
| 90 |
+
currentPrettyName?: string;
|
| 91 |
+
requested: SpaceHardwareFlavor | null;
|
| 92 |
+
requestedPrettyName?: string;
|
| 93 |
+
};
|
| 94 |
+
/** when calling /spaces, those props are only fetched if ?full=true */
|
| 95 |
+
resources?: SpaceResourceConfig;
|
| 96 |
+
/** in seconds */
|
| 97 |
+
gcTimeout?: number | null;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
export interface SpaceResourceRequirement {
|
| 101 |
+
cpu?: string;
|
| 102 |
+
memory?: string;
|
| 103 |
+
gpu?: string;
|
| 104 |
+
gpuModel?: string;
|
| 105 |
+
ephemeral?: string;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
export interface SpaceResourceConfig {
|
| 109 |
+
requests: SpaceResourceRequirement;
|
| 110 |
+
limits: SpaceResourceRequirement;
|
| 111 |
+
replicas?: number;
|
| 112 |
+
throttled?: boolean;
|
| 113 |
+
is_custom?: boolean;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
export type License =
|
| 117 |
+
| "apache-2.0"
|
| 118 |
+
| "mit"
|
| 119 |
+
| "openrail"
|
| 120 |
+
| "bigscience-openrail-m"
|
| 121 |
+
| "creativeml-openrail-m"
|
| 122 |
+
| "bigscience-bloom-rail-1.0"
|
| 123 |
+
| "bigcode-openrail-m"
|
| 124 |
+
| "afl-3.0"
|
| 125 |
+
| "artistic-2.0"
|
| 126 |
+
| "bsl-1.0"
|
| 127 |
+
| "bsd"
|
| 128 |
+
| "bsd-2-clause"
|
| 129 |
+
| "bsd-3-clause"
|
| 130 |
+
| "bsd-3-clause-clear"
|
| 131 |
+
| "c-uda"
|
| 132 |
+
| "cc"
|
| 133 |
+
| "cc0-1.0"
|
| 134 |
+
| "cc-by-2.0"
|
| 135 |
+
| "cc-by-2.5"
|
| 136 |
+
| "cc-by-3.0"
|
| 137 |
+
| "cc-by-4.0"
|
| 138 |
+
| "cc-by-sa-3.0"
|
| 139 |
+
| "cc-by-sa-4.0"
|
| 140 |
+
| "cc-by-nc-2.0"
|
| 141 |
+
| "cc-by-nc-3.0"
|
| 142 |
+
| "cc-by-nc-4.0"
|
| 143 |
+
| "cc-by-nd-4.0"
|
| 144 |
+
| "cc-by-nc-nd-3.0"
|
| 145 |
+
| "cc-by-nc-nd-4.0"
|
| 146 |
+
| "cc-by-nc-sa-2.0"
|
| 147 |
+
| "cc-by-nc-sa-3.0"
|
| 148 |
+
| "cc-by-nc-sa-4.0"
|
| 149 |
+
| "cdla-sharing-1.0"
|
| 150 |
+
| "cdla-permissive-1.0"
|
| 151 |
+
| "cdla-permissive-2.0"
|
| 152 |
+
| "wtfpl"
|
| 153 |
+
| "ecl-2.0"
|
| 154 |
+
| "epl-1.0"
|
| 155 |
+
| "epl-2.0"
|
| 156 |
+
| "etalab-2.0"
|
| 157 |
+
| "eupl-1.1"
|
| 158 |
+
| "agpl-3.0"
|
| 159 |
+
| "gfdl"
|
| 160 |
+
| "gpl"
|
| 161 |
+
| "gpl-2.0"
|
| 162 |
+
| "gpl-3.0"
|
| 163 |
+
| "lgpl"
|
| 164 |
+
| "lgpl-2.1"
|
| 165 |
+
| "lgpl-3.0"
|
| 166 |
+
| "isc"
|
| 167 |
+
| "lppl-1.3c"
|
| 168 |
+
| "ms-pl"
|
| 169 |
+
| "mpl-2.0"
|
| 170 |
+
| "odc-by"
|
| 171 |
+
| "odbl"
|
| 172 |
+
| "openrail++"
|
| 173 |
+
| "osl-3.0"
|
| 174 |
+
| "postgresql"
|
| 175 |
+
| "ofl-1.1"
|
| 176 |
+
| "ncsa"
|
| 177 |
+
| "unlicense"
|
| 178 |
+
| "zlib"
|
| 179 |
+
| "pddl"
|
| 180 |
+
| "lgpl-lr"
|
| 181 |
+
| "deepfloyd-if-license"
|
| 182 |
+
| "llama2"
|
| 183 |
+
| "llama3"
|
| 184 |
+
| "llama3.1"
|
| 185 |
+
| "llama3.2"
|
| 186 |
+
| "llama3.3"
|
| 187 |
+
| "gemma"
|
| 188 |
+
| "apple-ascl"
|
| 189 |
+
| "apple-amlr"
|
| 190 |
+
| "unknown"
|
| 191 |
+
| "other";
|
node_modules/@huggingface/hub/src/utils/ChunkCache.spec.ts
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { ChunkCache } from "./ChunkCache";
|
| 3 |
+
|
| 4 |
+
describe("ChunkCache", () => {
|
| 5 |
+
describe("basic operations", () => {
|
| 6 |
+
it("should create a cache with specified max size", () => {
|
| 7 |
+
const cache = new ChunkCache(5);
|
| 8 |
+
expect(cache.maxSize).toBe(5);
|
| 9 |
+
expect(cache.index).toBe(0);
|
| 10 |
+
});
|
| 11 |
+
|
| 12 |
+
it("should add and retrieve chunks", () => {
|
| 13 |
+
const cache = new ChunkCache(5);
|
| 14 |
+
|
| 15 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 16 |
+
cache.addChunkToCache("hash2", 200, 20, null);
|
| 17 |
+
|
| 18 |
+
const chunk1 = cache.getChunk("hash1", null);
|
| 19 |
+
const chunk2 = cache.getChunk("hash2", null);
|
| 20 |
+
|
| 21 |
+
expect(chunk1).toEqual({ xorbIndex: 100, chunkIndex: 10 });
|
| 22 |
+
expect(chunk2).toEqual({ xorbIndex: 200, chunkIndex: 20 });
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
it("should return undefined for non-existent chunks", () => {
|
| 26 |
+
const cache = new ChunkCache(5);
|
| 27 |
+
|
| 28 |
+
const chunk = cache.getChunk("nonexistent", null);
|
| 29 |
+
expect(chunk).toBeUndefined();
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
it("should remove chunks from cache", () => {
|
| 33 |
+
const cache = new ChunkCache(5);
|
| 34 |
+
|
| 35 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 36 |
+
expect(cache.getChunk("hash1", null)).toBeDefined();
|
| 37 |
+
|
| 38 |
+
cache.removeChunkFromCache("hash1");
|
| 39 |
+
expect(cache.getChunk("hash1", null)).toBeUndefined();
|
| 40 |
+
});
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
describe("duplicate handling", () => {
|
| 44 |
+
it("should ignore duplicate hashes", () => {
|
| 45 |
+
const cache = new ChunkCache(5);
|
| 46 |
+
|
| 47 |
+
// Add initial chunk
|
| 48 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 49 |
+
expect(cache.index).toBe(1);
|
| 50 |
+
expect(cache.map.size).toBe(1);
|
| 51 |
+
|
| 52 |
+
// Try to add same hash again - should be ignored
|
| 53 |
+
cache.addChunkToCache("hash1", 999, 99, null);
|
| 54 |
+
expect(cache.index).toBe(1); // index should not increment
|
| 55 |
+
expect(cache.map.size).toBe(1); // map size should not increase
|
| 56 |
+
|
| 57 |
+
// Original data should be preserved
|
| 58 |
+
const chunk = cache.getChunk("hash1", null);
|
| 59 |
+
expect(chunk).toEqual({ xorbIndex: 100, chunkIndex: 10 });
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
it("should maintain consistency when adding duplicates mixed with new hashes", () => {
|
| 63 |
+
const cache = new ChunkCache(5);
|
| 64 |
+
|
| 65 |
+
// Add some chunks
|
| 66 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 67 |
+
cache.addChunkToCache("hash2", 200, 20, null);
|
| 68 |
+
cache.addChunkToCache("hash3", 300, 30, null);
|
| 69 |
+
|
| 70 |
+
expect(cache.index).toBe(3);
|
| 71 |
+
expect(cache.map.size).toBe(3);
|
| 72 |
+
|
| 73 |
+
// Try to add duplicates
|
| 74 |
+
cache.addChunkToCache("hash1", 999, 99, null); // duplicate
|
| 75 |
+
cache.addChunkToCache("hash4", 400, 40, null); // new
|
| 76 |
+
cache.addChunkToCache("hash2", 888, 88, null); // duplicate
|
| 77 |
+
|
| 78 |
+
expect(cache.index).toBe(4); // only incremented for hash4
|
| 79 |
+
expect(cache.map.size).toBe(4);
|
| 80 |
+
|
| 81 |
+
// Verify all chunks are accessible and have correct data
|
| 82 |
+
expect(cache.getChunk("hash1", null)).toEqual({ xorbIndex: 100, chunkIndex: 10 });
|
| 83 |
+
expect(cache.getChunk("hash2", null)).toEqual({ xorbIndex: 200, chunkIndex: 20 });
|
| 84 |
+
expect(cache.getChunk("hash3", null)).toEqual({ xorbIndex: 300, chunkIndex: 30 });
|
| 85 |
+
expect(cache.getChunk("hash4", null)).toEqual({ xorbIndex: 400, chunkIndex: 40 });
|
| 86 |
+
});
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
describe("cache overflow and circular buffer behavior", () => {
|
| 90 |
+
it("should handle cache overflow correctly", () => {
|
| 91 |
+
const cache = new ChunkCache(3); // Small cache size
|
| 92 |
+
|
| 93 |
+
// Fill the cache to capacity
|
| 94 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 95 |
+
cache.addChunkToCache("hash2", 200, 20, null);
|
| 96 |
+
cache.addChunkToCache("hash3", 300, 30, null);
|
| 97 |
+
|
| 98 |
+
expect(cache.index).toBe(0); // wrapped around (3 % 3 = 0)
|
| 99 |
+
expect(cache.map.size).toBe(3);
|
| 100 |
+
|
| 101 |
+
// All chunks should be accessible
|
| 102 |
+
expect(cache.getChunk("hash1", null)).toBeDefined();
|
| 103 |
+
expect(cache.getChunk("hash2", null)).toBeDefined();
|
| 104 |
+
expect(cache.getChunk("hash3", null)).toBeDefined();
|
| 105 |
+
|
| 106 |
+
// Add one more chunk - should evict the oldest (hash1)
|
| 107 |
+
cache.addChunkToCache("hash4", 400, 40, null);
|
| 108 |
+
|
| 109 |
+
expect(cache.index).toBe(1); // wrapped around (4 % 3 = 1)
|
| 110 |
+
expect(cache.map.size).toBe(3); // size should remain the same
|
| 111 |
+
|
| 112 |
+
// hash1 should be evicted, others should remain
|
| 113 |
+
expect(cache.getChunk("hash1", null)).toBeUndefined();
|
| 114 |
+
expect(cache.getChunk("hash2", null)).toEqual({ xorbIndex: 200, chunkIndex: 20 });
|
| 115 |
+
expect(cache.getChunk("hash3", null)).toEqual({ xorbIndex: 300, chunkIndex: 30 });
|
| 116 |
+
expect(cache.getChunk("hash4", null)).toEqual({ xorbIndex: 400, chunkIndex: 40 });
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it("should continue evicting oldest entries as new ones are added", () => {
|
| 120 |
+
const cache = new ChunkCache(3);
|
| 121 |
+
|
| 122 |
+
// Fill cache
|
| 123 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 124 |
+
cache.addChunkToCache("hash2", 200, 20, null);
|
| 125 |
+
cache.addChunkToCache("hash3", 300, 30, null);
|
| 126 |
+
|
| 127 |
+
// Add more chunks to test multiple evictions
|
| 128 |
+
cache.addChunkToCache("hash4", 400, 40, null); // evicts hash1
|
| 129 |
+
cache.addChunkToCache("hash5", 500, 50, null); // evicts hash2
|
| 130 |
+
cache.addChunkToCache("hash6", 600, 60, null); // evicts hash3
|
| 131 |
+
|
| 132 |
+
expect(cache.map.size).toBe(3);
|
| 133 |
+
|
| 134 |
+
// Only the last 3 should remain
|
| 135 |
+
expect(cache.getChunk("hash1", null)).toBeUndefined();
|
| 136 |
+
expect(cache.getChunk("hash2", null)).toBeUndefined();
|
| 137 |
+
expect(cache.getChunk("hash3", null)).toBeUndefined();
|
| 138 |
+
expect(cache.getChunk("hash4", null)).toEqual({ xorbIndex: 400, chunkIndex: 40 });
|
| 139 |
+
expect(cache.getChunk("hash5", null)).toEqual({ xorbIndex: 500, chunkIndex: 50 });
|
| 140 |
+
expect(cache.getChunk("hash6", null)).toEqual({ xorbIndex: 600, chunkIndex: 60 });
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
it("should handle removals during overflow correctly", () => {
|
| 144 |
+
const cache = new ChunkCache(3);
|
| 145 |
+
|
| 146 |
+
// Fill cache
|
| 147 |
+
cache.addChunkToCache("hash1", 100, 10, null);
|
| 148 |
+
cache.addChunkToCache("hash2", 200, 20, null);
|
| 149 |
+
cache.addChunkToCache("hash3", 300, 30, null);
|
| 150 |
+
|
| 151 |
+
// Remove middle element
|
| 152 |
+
cache.removeChunkFromCache("hash2");
|
| 153 |
+
expect(cache.map.size).toBe(2);
|
| 154 |
+
|
| 155 |
+
// Add new elements
|
| 156 |
+
cache.addChunkToCache("hash4", 400, 40, null);
|
| 157 |
+
cache.addChunkToCache("hash5", 500, 50, null);
|
| 158 |
+
|
| 159 |
+
// The removal should not affect the eviction logic
|
| 160 |
+
expect(cache.getChunk("hash1", null)).toBeUndefined(); // evicted
|
| 161 |
+
expect(cache.getChunk("hash2", null)).toBeUndefined(); // removed
|
| 162 |
+
expect(cache.getChunk("hash3", null)).toEqual({ xorbIndex: 300, chunkIndex: 30 });
|
| 163 |
+
expect(cache.getChunk("hash4", null)).toEqual({ xorbIndex: 400, chunkIndex: 40 });
|
| 164 |
+
expect(cache.getChunk("hash5", null)).toEqual({ xorbIndex: 500, chunkIndex: 50 });
|
| 165 |
+
});
|
| 166 |
+
});
|
| 167 |
+
|
| 168 |
+
describe("consistency after operations", () => {
|
| 169 |
+
it("should maintain consistent state after mixed operations", () => {
|
| 170 |
+
const cache = new ChunkCache(4);
|
| 171 |
+
|
| 172 |
+
// Add initial chunks
|
| 173 |
+
cache.addChunkToCache("a", 1, 10, null);
|
| 174 |
+
cache.addChunkToCache("b", 2, 20, null);
|
| 175 |
+
cache.addChunkToCache("c", 3, 30, null);
|
| 176 |
+
|
| 177 |
+
// Mix of operations
|
| 178 |
+
cache.addChunkToCache("a", 999, 999, null); // duplicate (ignored)
|
| 179 |
+
cache.removeChunkFromCache("b"); // removal
|
| 180 |
+
cache.addChunkToCache("d", 4, 40, null); // new addition
|
| 181 |
+
cache.addChunkToCache("e", 5, 50, null); // new addition - this triggers overflow
|
| 182 |
+
cache.addChunkToCache("c", 888, 888, null); // duplicate (ignored)
|
| 183 |
+
|
| 184 |
+
// Verify final state
|
| 185 |
+
// With cache size 4: a(0), b(1, removed), c(2), d(3), e(4 -> 0, wraps and evicts a)
|
| 186 |
+
expect(cache.getChunk("a", null)).toBeUndefined(); // evicted by e
|
| 187 |
+
expect(cache.getChunk("b", null)).toBeUndefined(); // removed
|
| 188 |
+
expect(cache.getChunk("c", null)).toEqual({ xorbIndex: 3, chunkIndex: 30 });
|
| 189 |
+
expect(cache.getChunk("d", null)).toEqual({ xorbIndex: 4, chunkIndex: 40 });
|
| 190 |
+
expect(cache.getChunk("e", null)).toEqual({ xorbIndex: 5, chunkIndex: 50 });
|
| 191 |
+
|
| 192 |
+
// Map size should be 3 (a evicted, b removed)
|
| 193 |
+
expect(cache.map.size).toBe(3);
|
| 194 |
+
});
|
| 195 |
+
|
| 196 |
+
it("should maintain consistency after cache overflow with mixed operations", () => {
|
| 197 |
+
const cache = new ChunkCache(3);
|
| 198 |
+
|
| 199 |
+
// Fill cache
|
| 200 |
+
cache.addChunkToCache("first", 1, 1, null);
|
| 201 |
+
cache.addChunkToCache("second", 2, 2, null);
|
| 202 |
+
cache.addChunkToCache("third", 3, 3, null);
|
| 203 |
+
|
| 204 |
+
// Cause overflow with duplicates and removals mixed in
|
| 205 |
+
cache.addChunkToCache("fourth", 4, 4, null); // evicts "first"
|
| 206 |
+
cache.addChunkToCache("second", 999, 999, null); // duplicate (ignored)
|
| 207 |
+
cache.removeChunkFromCache("third"); // removal
|
| 208 |
+
cache.addChunkToCache("fifth", 5, 5, null); // evicts "second"
|
| 209 |
+
|
| 210 |
+
// Final state verification
|
| 211 |
+
expect(cache.getChunk("first", null)).toBeUndefined(); // evicted
|
| 212 |
+
expect(cache.getChunk("second", null)).toBeUndefined(); // evicted
|
| 213 |
+
expect(cache.getChunk("third", null)).toBeUndefined(); // removed
|
| 214 |
+
expect(cache.getChunk("fourth", null)).toEqual({ xorbIndex: 4, chunkIndex: 4 });
|
| 215 |
+
expect(cache.getChunk("fifth", null)).toEqual({ xorbIndex: 5, chunkIndex: 5 });
|
| 216 |
+
|
| 217 |
+
cache.addChunkToCache("sixth", 6, 6, null); // new, takes "third" place
|
| 218 |
+
expect(cache.getChunk("sixth", null)).toEqual({ xorbIndex: 6, chunkIndex: 6 });
|
| 219 |
+
expect(cache.getChunk("fourth", null)).toEqual({ xorbIndex: 4, chunkIndex: 4 });
|
| 220 |
+
expect(cache.getChunk("fifth", null)).toEqual({ xorbIndex: 5, chunkIndex: 5 });
|
| 221 |
+
|
| 222 |
+
cache.addChunkToCache("seventh", 7, 7, null); // new, takes "fourth" place
|
| 223 |
+
expect(cache.getChunk("seventh", null)).toEqual({ xorbIndex: 7, chunkIndex: 7 });
|
| 224 |
+
expect(cache.getChunk("fourth", null)).toBeUndefined(); // evicted
|
| 225 |
+
expect(cache.getChunk("fifth", null)).toEqual({ xorbIndex: 5, chunkIndex: 5 });
|
| 226 |
+
|
| 227 |
+
expect(cache.map.size).toBe(3);
|
| 228 |
+
});
|
| 229 |
+
});
|
| 230 |
+
|
| 231 |
+
describe("negative xorbIndex handling", () => {
|
| 232 |
+
it("should handle negative xorbIndex values (remote xorbs)", () => {
|
| 233 |
+
const cache = new ChunkCache(5);
|
| 234 |
+
|
| 235 |
+
cache.addChunkToCache("remote1", -1, 10, null);
|
| 236 |
+
cache.addChunkToCache("local1", 1, 20, null);
|
| 237 |
+
cache.addChunkToCache("remote2", -100, 30, null);
|
| 238 |
+
|
| 239 |
+
expect(cache.getChunk("remote1", null)).toEqual({ xorbIndex: -1, chunkIndex: 10 });
|
| 240 |
+
expect(cache.getChunk("local1", null)).toEqual({ xorbIndex: 1, chunkIndex: 20 });
|
| 241 |
+
expect(cache.getChunk("remote2", null)).toEqual({ xorbIndex: -100, chunkIndex: 30 });
|
| 242 |
+
});
|
| 243 |
+
});
|
| 244 |
+
|
| 245 |
+
describe("edge cases", () => {
|
| 246 |
+
it("should handle cache with max size of 1", () => {
|
| 247 |
+
const cache = new ChunkCache(1);
|
| 248 |
+
|
| 249 |
+
cache.addChunkToCache("hash1", 1, 1, null);
|
| 250 |
+
expect(cache.getChunk("hash1", null)).toBeDefined();
|
| 251 |
+
|
| 252 |
+
cache.addChunkToCache("hash2", 2, 2, null);
|
| 253 |
+
expect(cache.getChunk("hash1", null)).toBeUndefined(); // evicted
|
| 254 |
+
expect(cache.getChunk("hash2", null)).toEqual({ xorbIndex: 2, chunkIndex: 2 });
|
| 255 |
+
});
|
| 256 |
+
|
| 257 |
+
it("should handle empty cache operations", () => {
|
| 258 |
+
const cache = new ChunkCache(5);
|
| 259 |
+
|
| 260 |
+
expect(cache.getChunk("nonexistent", null)).toBeUndefined();
|
| 261 |
+
cache.removeChunkFromCache("nonexistent"); // should not throw
|
| 262 |
+
expect(cache.map.size).toBe(0);
|
| 263 |
+
});
|
| 264 |
+
});
|
| 265 |
+
});
|
node_modules/@huggingface/hub/src/utils/ChunkCache.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const CHUNK_CACHE_INITIAL_SIZE = 10_000;
|
| 2 |
+
const CHUNK_CACHE_GROW_FACTOR = 1.5;
|
| 3 |
+
const CHUNK_CACHE_MAX_SIZE = 1_000_000;
|
| 4 |
+
|
| 5 |
+
export class ChunkCache {
|
| 6 |
+
index = 0;
|
| 7 |
+
// Index >= 0 means local xorb, < 0 means remote xorb
|
| 8 |
+
xorbIndices: Int32Array;
|
| 9 |
+
// Max 8K chunks per xorb, less than 64K uint16_t
|
| 10 |
+
chunkIndices: Uint16Array;
|
| 11 |
+
map = new Map<string, number>(); // hash -> chunkCacheIndex. Less overhead that way, empty object is 60+B and empty array is 40+B
|
| 12 |
+
hmacs = new Set<string>(); // todo : remove old hmacs
|
| 13 |
+
maxSize: number;
|
| 14 |
+
|
| 15 |
+
constructor(maxSize: number = CHUNK_CACHE_MAX_SIZE) {
|
| 16 |
+
if (maxSize < 1) {
|
| 17 |
+
throw new Error("maxSize must be at least 1");
|
| 18 |
+
}
|
| 19 |
+
this.maxSize = maxSize;
|
| 20 |
+
this.xorbIndices = new Int32Array(Math.min(CHUNK_CACHE_INITIAL_SIZE, maxSize));
|
| 21 |
+
this.chunkIndices = new Uint16Array(Math.min(CHUNK_CACHE_INITIAL_SIZE, maxSize));
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
addChunkToCache(hash: string, xorbIndex: number, chunkIndex: number, hmac: string | null): void {
|
| 25 |
+
if (this.map.has(hash)) {
|
| 26 |
+
// Happens when we receive an existing chunk from remote dedup info (eg duplicate chunk in shard? Or shards with same hmac key
|
| 27 |
+
// sharing chunks/xorbs)
|
| 28 |
+
|
| 29 |
+
// processing this chunk again would desync the cache, as `this.map.size` would not increase, as opposed to `this.index`
|
| 30 |
+
|
| 31 |
+
// We could readd/remove it to "refresh it"
|
| 32 |
+
return;
|
| 33 |
+
}
|
| 34 |
+
if (this.map.values().next().value === this.index) {
|
| 35 |
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
| 36 |
+
this.map.delete(this.map.keys().next().value!);
|
| 37 |
+
}
|
| 38 |
+
this.map.set(hash, this.index);
|
| 39 |
+
if (hmac !== null) {
|
| 40 |
+
this.hmacs.add(hmac);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
if (this.index >= this.xorbIndices.length) {
|
| 44 |
+
// todo: switch to resize() with modern browsers
|
| 45 |
+
const oldXorbIndices = this.xorbIndices;
|
| 46 |
+
const oldChunkIndices = this.chunkIndices;
|
| 47 |
+
this.xorbIndices = new Int32Array(Math.min(this.xorbIndices.length * CHUNK_CACHE_GROW_FACTOR, this.maxSize));
|
| 48 |
+
this.chunkIndices = new Uint16Array(Math.min(this.chunkIndices.length * CHUNK_CACHE_GROW_FACTOR, this.maxSize));
|
| 49 |
+
this.xorbIndices.set(oldXorbIndices);
|
| 50 |
+
this.chunkIndices.set(oldChunkIndices);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
this.xorbIndices[this.index] = xorbIndex;
|
| 54 |
+
this.chunkIndices[this.index] = chunkIndex;
|
| 55 |
+
this.index = (this.index + 1) % this.maxSize;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
getChunk(
|
| 59 |
+
hash: string,
|
| 60 |
+
/**
|
| 61 |
+
* Set to null if you only want to check against locally created chunks, or the hash is already a hmac
|
| 62 |
+
*/
|
| 63 |
+
hmacFunction: ((hash: string, key: string) => string) | null,
|
| 64 |
+
):
|
| 65 |
+
| {
|
| 66 |
+
xorbIndex: number;
|
| 67 |
+
chunkIndex: number;
|
| 68 |
+
}
|
| 69 |
+
| undefined {
|
| 70 |
+
let index = this.map.get(hash);
|
| 71 |
+
if (index === undefined && hmacFunction !== null) {
|
| 72 |
+
for (const hmac of this.hmacs) {
|
| 73 |
+
index = this.map.get(hmacFunction(hash, hmac));
|
| 74 |
+
if (index !== undefined) {
|
| 75 |
+
break;
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
if (index === undefined) {
|
| 80 |
+
return undefined;
|
| 81 |
+
}
|
| 82 |
+
return {
|
| 83 |
+
xorbIndex: this.xorbIndices[index],
|
| 84 |
+
chunkIndex: this.chunkIndices[index],
|
| 85 |
+
};
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
updateChunkIndex(hash: string, chunkIndex: number): void {
|
| 89 |
+
const index = this.map.get(hash);
|
| 90 |
+
if (index === undefined) {
|
| 91 |
+
throw new Error(`Chunk not found in cache: ${hash}`);
|
| 92 |
+
}
|
| 93 |
+
this.chunkIndices[index] = chunkIndex;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
removeChunkFromCache(hash: string): void {
|
| 97 |
+
this.map.delete(hash);
|
| 98 |
+
}
|
| 99 |
+
}
|
node_modules/@huggingface/hub/src/utils/FileBlob.spec.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { open, stat } from "node:fs/promises";
|
| 2 |
+
import { TextDecoder } from "node:util";
|
| 3 |
+
import { describe, expect, it } from "vitest";
|
| 4 |
+
import { FileBlob } from "./FileBlob";
|
| 5 |
+
|
| 6 |
+
describe("FileBlob", () => {
|
| 7 |
+
it("should create a FileBlob with a slice on the entire file", async () => {
|
| 8 |
+
const file = await open("package.json", "r");
|
| 9 |
+
const { size } = await stat("package.json");
|
| 10 |
+
|
| 11 |
+
const fileBlob = await FileBlob.create("package.json");
|
| 12 |
+
|
| 13 |
+
expect(fileBlob).toMatchObject({
|
| 14 |
+
path: "package.json",
|
| 15 |
+
start: 0,
|
| 16 |
+
end: size,
|
| 17 |
+
});
|
| 18 |
+
expect(fileBlob.size).toBe(size);
|
| 19 |
+
expect(fileBlob.type).toBe("");
|
| 20 |
+
const text = await fileBlob.text();
|
| 21 |
+
const expectedText = (await file.read(Buffer.alloc(size), 0, size)).buffer.toString("utf8");
|
| 22 |
+
expect(text).toBe(expectedText);
|
| 23 |
+
const result = await fileBlob.stream().getReader().read();
|
| 24 |
+
expect(new TextDecoder().decode(result.value)).toBe(expectedText);
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
it("should create a slice on the file", async () => {
|
| 28 |
+
const file = await open("package.json", "r");
|
| 29 |
+
const fileBlob = await FileBlob.create("package.json");
|
| 30 |
+
|
| 31 |
+
const slice = fileBlob.slice(10, 20);
|
| 32 |
+
|
| 33 |
+
expect(slice).toMatchObject({
|
| 34 |
+
path: "package.json",
|
| 35 |
+
start: 10,
|
| 36 |
+
end: 20,
|
| 37 |
+
});
|
| 38 |
+
expect(slice.size).toBe(10);
|
| 39 |
+
const sliceText = await slice.text();
|
| 40 |
+
const expectedText = (await file.read(Buffer.alloc(10), 0, 10, 10)).buffer.toString("utf8");
|
| 41 |
+
expect(sliceText).toBe(expectedText);
|
| 42 |
+
const result = await slice.stream().getReader().read();
|
| 43 |
+
expect(new TextDecoder().decode(result.value)).toBe(expectedText);
|
| 44 |
+
});
|
| 45 |
+
});
|
node_modules/@huggingface/hub/src/utils/FileBlob.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createReadStream } from "node:fs";
|
| 2 |
+
import { open, stat } from "node:fs/promises";
|
| 3 |
+
import { Readable } from "node:stream";
|
| 4 |
+
import type { FileHandle } from "node:fs/promises";
|
| 5 |
+
import { fileURLToPath } from "node:url";
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* @internal
|
| 9 |
+
*
|
| 10 |
+
* A FileBlob is a replacement for the Blob class that allows to lazy read files
|
| 11 |
+
* in order to preserve memory.
|
| 12 |
+
*
|
| 13 |
+
* It is a drop-in replacement for the Blob class, so you can use it as a Blob.
|
| 14 |
+
*
|
| 15 |
+
* The main difference is the instantiation, which is done asynchronously using the `FileBlob.create` method.
|
| 16 |
+
*
|
| 17 |
+
* @example
|
| 18 |
+
* const fileBlob = await FileBlob.create("path/to/package.json");
|
| 19 |
+
*
|
| 20 |
+
* await fetch("https://aschen.tech", { method: "POST", body: fileBlob });
|
| 21 |
+
*/
|
| 22 |
+
export class FileBlob extends Blob {
|
| 23 |
+
/**
|
| 24 |
+
* Creates a new FileBlob on the provided file.
|
| 25 |
+
*
|
| 26 |
+
* @param path Path to the file to be lazy readed
|
| 27 |
+
*/
|
| 28 |
+
static async create(path: string | URL): Promise<FileBlob> {
|
| 29 |
+
path = path instanceof URL ? fileURLToPath(path) : path;
|
| 30 |
+
|
| 31 |
+
const { size } = await stat(path);
|
| 32 |
+
|
| 33 |
+
const fileBlob = new FileBlob(path, 0, size);
|
| 34 |
+
|
| 35 |
+
return fileBlob;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
private path: string;
|
| 39 |
+
private start: number;
|
| 40 |
+
private end: number;
|
| 41 |
+
|
| 42 |
+
private constructor(path: string, start: number, end: number) {
|
| 43 |
+
super();
|
| 44 |
+
|
| 45 |
+
this.path = path;
|
| 46 |
+
this.start = start;
|
| 47 |
+
this.end = end;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/**
|
| 51 |
+
* Returns the size of the blob.
|
| 52 |
+
*/
|
| 53 |
+
override get size(): number {
|
| 54 |
+
return this.end - this.start;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* Returns a new instance of FileBlob that is a slice of the current one.
|
| 59 |
+
*
|
| 60 |
+
* The slice is inclusive of the start and exclusive of the end.
|
| 61 |
+
*
|
| 62 |
+
* The slice method does not supports negative start/end.
|
| 63 |
+
*
|
| 64 |
+
* @param start beginning of the slice
|
| 65 |
+
* @param end end of the slice
|
| 66 |
+
*/
|
| 67 |
+
override slice(start = 0, end = this.size): FileBlob {
|
| 68 |
+
if (start < 0 || end < 0) {
|
| 69 |
+
new TypeError("Unsupported negative start/end on FileBlob.slice");
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
const slice = new FileBlob(this.path, this.start + start, Math.min(this.start + end, this.end));
|
| 73 |
+
|
| 74 |
+
return slice;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
/**
|
| 78 |
+
* Read the part of the file delimited by the FileBlob and returns it as an ArrayBuffer.
|
| 79 |
+
*/
|
| 80 |
+
override async arrayBuffer(): Promise<ArrayBuffer> {
|
| 81 |
+
const slice = await this.execute((file) => file.read(Buffer.alloc(this.size), 0, this.size, this.start));
|
| 82 |
+
|
| 83 |
+
return slice.buffer;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
/**
|
| 87 |
+
* Read the part of the file delimited by the FileBlob and returns it as a string.
|
| 88 |
+
*/
|
| 89 |
+
override async text(): Promise<string> {
|
| 90 |
+
const buffer = (await this.arrayBuffer()) as Buffer;
|
| 91 |
+
|
| 92 |
+
return buffer.toString("utf8");
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/**
|
| 96 |
+
* Returns a stream around the part of the file delimited by the FileBlob.
|
| 97 |
+
*/
|
| 98 |
+
override stream(): ReturnType<Blob["stream"]> {
|
| 99 |
+
if (this.start === this.end) {
|
| 100 |
+
return new Blob([]).stream();
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
return Readable.toWeb(createReadStream(this.path, { start: this.start, end: this.end - 1 })) as ReturnType<
|
| 104 |
+
Blob["stream"]
|
| 105 |
+
>;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/**
|
| 109 |
+
* We are opening and closing the file for each action to prevent file descriptor leaks.
|
| 110 |
+
*
|
| 111 |
+
* It is an intended choice of developer experience over performances.
|
| 112 |
+
*/
|
| 113 |
+
private async execute<T>(action: (file: FileHandle) => Promise<T>) {
|
| 114 |
+
const file = await open(this.path, "r");
|
| 115 |
+
|
| 116 |
+
try {
|
| 117 |
+
return await action(file);
|
| 118 |
+
} finally {
|
| 119 |
+
await file.close();
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
}
|
node_modules/@huggingface/hub/src/utils/RangeList.spec.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { RangeList } from "./RangeList";
|
| 3 |
+
|
| 4 |
+
describe("RangeList", () => {
|
| 5 |
+
it("should add a single range", () => {
|
| 6 |
+
const rangeList = new RangeList();
|
| 7 |
+
rangeList.add(1, 100);
|
| 8 |
+
|
| 9 |
+
const ranges = rangeList.getAllRanges();
|
| 10 |
+
expect(ranges).toHaveLength(1);
|
| 11 |
+
expect(ranges[0]).toEqual({
|
| 12 |
+
start: 1,
|
| 13 |
+
end: 100,
|
| 14 |
+
refCount: 1,
|
| 15 |
+
data: null,
|
| 16 |
+
});
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
it("should handle overlapping ranges", () => {
|
| 20 |
+
const rangeList = new RangeList();
|
| 21 |
+
rangeList.add(1, 100);
|
| 22 |
+
rangeList.add(30, 50);
|
| 23 |
+
|
| 24 |
+
const ranges = rangeList.getAllRanges();
|
| 25 |
+
expect(ranges).toHaveLength(3);
|
| 26 |
+
expect(ranges).toEqual([
|
| 27 |
+
{ start: 1, end: 30, refCount: 1, data: null },
|
| 28 |
+
{ start: 30, end: 50, refCount: 2, data: null },
|
| 29 |
+
{ start: 50, end: 100, refCount: 1, data: null },
|
| 30 |
+
]);
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
it("should remove a range at existing boundaries", () => {
|
| 34 |
+
const rangeList = new RangeList();
|
| 35 |
+
rangeList.add(1, 100);
|
| 36 |
+
rangeList.add(30, 50);
|
| 37 |
+
rangeList.remove(30, 50);
|
| 38 |
+
|
| 39 |
+
const ranges = rangeList.getAllRanges();
|
| 40 |
+
expect(ranges).toHaveLength(3);
|
| 41 |
+
expect(ranges).toEqual([
|
| 42 |
+
{ start: 1, end: 30, refCount: 1, data: null },
|
| 43 |
+
{ start: 30, end: 50, refCount: 1, data: null },
|
| 44 |
+
{ start: 50, end: 100, refCount: 1, data: null },
|
| 45 |
+
]);
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
it("should throw error when removing range at non-existing boundaries", () => {
|
| 49 |
+
const rangeList = new RangeList();
|
| 50 |
+
rangeList.add(1, 100);
|
| 51 |
+
rangeList.add(30, 50);
|
| 52 |
+
|
| 53 |
+
expect(() => rangeList.remove(2, 50)).toThrow("Range boundaries must match existing boundaries");
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
it("should get ranges within boundaries", () => {
|
| 57 |
+
const rangeList = new RangeList();
|
| 58 |
+
rangeList.add(1, 100);
|
| 59 |
+
rangeList.add(30, 50);
|
| 60 |
+
|
| 61 |
+
const ranges = rangeList.getRanges(30, 100);
|
| 62 |
+
expect(ranges).toHaveLength(2);
|
| 63 |
+
expect(ranges).toEqual([
|
| 64 |
+
{ start: 30, end: 50, refCount: 2, data: null },
|
| 65 |
+
{ start: 50, end: 100, refCount: 1, data: null },
|
| 66 |
+
]);
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
it("should throw error when end is less than or equal to start", () => {
|
| 70 |
+
const rangeList = new RangeList();
|
| 71 |
+
|
| 72 |
+
expect(() => rangeList.add(100, 1)).toThrow("End must be greater than start");
|
| 73 |
+
expect(() => rangeList.add(1, 1)).toThrow("End must be greater than start");
|
| 74 |
+
expect(() => rangeList.remove(100, 1)).toThrow("End must be greater than start");
|
| 75 |
+
expect(() => rangeList.remove(1, 1)).toThrow("End must be greater than start");
|
| 76 |
+
expect(() => rangeList.getRanges(100, 1)).toThrow("End must be greater than start");
|
| 77 |
+
expect(() => rangeList.getRanges(1, 1)).toThrow("End must be greater than start");
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it("should handle multiple overlapping ranges", () => {
|
| 81 |
+
const rangeList = new RangeList();
|
| 82 |
+
rangeList.add(1, 100);
|
| 83 |
+
rangeList.add(30, 50);
|
| 84 |
+
rangeList.add(40, 60);
|
| 85 |
+
|
| 86 |
+
const ranges = rangeList.getAllRanges();
|
| 87 |
+
expect(ranges).toHaveLength(5);
|
| 88 |
+
expect(ranges).toEqual([
|
| 89 |
+
{ start: 1, end: 30, refCount: 1, data: null },
|
| 90 |
+
{ start: 30, end: 40, refCount: 2, data: null },
|
| 91 |
+
{ start: 40, end: 50, refCount: 3, data: null },
|
| 92 |
+
{ start: 50, end: 60, refCount: 2, data: null },
|
| 93 |
+
{ start: 60, end: 100, refCount: 1, data: null },
|
| 94 |
+
]);
|
| 95 |
+
});
|
| 96 |
+
});
|