Huggingface.js documentation

🤗 API của Hugging Face Hub

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

🤗 API của Hugging Face Hub

Công cụ chính thức để sử dụng API của Hugging Face Hub.

Cài đặt

pnpm add @huggingface/hub

npm add @huggingface/hub

yarn add @huggingface/hub

Deno

// esm.sh
import { uploadFiles, listModels } from "https://esm.sh/@huggingface/hub"
// or npm:
import { uploadFiles, listModels } from "npm:@huggingface/hub"

Cách sử dụng

Đối với một số cuộc gọi, bạn cần tạo tài khoản và tạo access token.

Tìm hiểu cách tìm các mô hình miễn phí bằng cách sử dụng gói hub trong tutorial tương tác này.

import * as hub from "@huggingface/hub";
import type { RepoDesignation } from "@huggingface/hub";

const repo: RepoDesignation = { type: "model", name: "myname/some-model" };

const {name: username} = await hub.whoAmI({accessToken: "hf_..."});

for await (const model of hub.listModels({search: {owner: username}, accessToken: "hf_..."})) {
  console.log("My model:", model);
}

const specificModel = await hub.modelInfo({name: "openai-community/gpt2"});
await hub.checkRepoAccess({repo, accessToken: "hf_..."});

await hub.createRepo({ repo, accessToken: "hf_...", license: "mit" });

await hub.uploadFiles({
  repo,
  accessToken: "hf_...",
  files: [
    // path + blob content
    {
      path: "file.txt",
      content: new Blob(["Hello World"]),
    },
    // Local file URL
    pathToFileURL("./pytorch-model.bin"),
    // Local folder URL
    pathToFileURL("./models"),
    // Web URL
    new URL("https://huggingface.co/xlm-roberta-base/resolve/main/tokenizer.json"),
    // Path + Web URL
    {
      path: "myfile.bin",
      content: new URL("https://huggingface.co/bert-base-uncased/resolve/main/pytorch_model.bin")
    }
    // Can also work with native File in browsers
  ],
});

// or

for await (const progressEvent of await hub.uploadFilesWithProgress({
  repo,
  accessToken: "hf_...",
  files: [
    ...
  ],
})) {
  console.log(progressEvent);
}

// Edit a file in place, without downloading/uploading its unchanged data
const file = await hub.downloadFile({ repo, path: "myfile.bin", accessToken: "hf_..." });
await hub.uploadFile({
  repo,
  accessToken: "hf_...",
  file: {
    path: "myfile.bin",
    originalContent: file,
    edits: [{
      // Replace bytes [0, 4)
      start: 0,
      end: 4,
      content: new Blob(["new prefix"])
    }, {
      // Append at the end
      start: file.size,
      end: file.size,
      content: new Blob(["suffix"])
    }]
  }
});

await hub.deleteFile({repo, accessToken: "hf_...", path: "myfile.bin"});

await (await hub.downloadFile({ repo, path: "README.md" })).text();

for await (const fileInfo of hub.listFiles({repo})) {
  console.log(fileInfo);
}

await hub.deleteRepo({ repo, accessToken: "hf_..." });

Các nhóm

Storage Buckets là kho lưu trữ có thể thay đổi, không có phiên bản trên Hub. Hãy sử dụng tiền tố buckets/ (hoặc { type: "bucket", name }) với các hàm tương tự:

const bucket = "buckets/myname/my-bucket";

await hub.createRepo({ repo: bucket, accessToken: "hf_..." });

await hub.uploadFiles({ repo: bucket, accessToken: "hf_...", files: [pathToFileURL("./checkpoints")] });

for await (const fileInfo of hub.listFiles({ repo: bucket, recursive: true, accessToken: "hf_..." })) {
  console.log(fileInfo.path, fileInfo.uploadedAt);
}

// Copy files from a model or dataset repo into a bucket server-side, without downloading them
await hub.copyFolder({
  source: { repo: { type: "dataset", name: "myname/my-dataset" }, path: "data" },
  destination: { repo: bucket, path: "data" },
  accessToken: "hf_...",
});

Cách sử dụng CLI

Bạn có thể sử dụng @huggingface/hub ở chế độ CLI để tải lên và tải xuống các tệp và thư mục từ/đến kho của bạn.

npx @huggingface/hub upload coyotte508/test-model .
npx @huggingface/hub upload datasets/coyotte508/test-dataset .
# Same thing
npx @huggingface/hub upload --repo-type dataset coyotte508/test-dataset .
# Upload new data with 0 history in a separate branch
npx @huggingface/hub branch create coyotte508/test-model release --empty
npx @huggingface/hub upload coyotte508/test-model . --revision release

# Download files to the current directory (or --local-dir)
npx @huggingface/hub download coyotte508/test-model config.json
npx @huggingface/hub download coyotte508/test-model config.json README.md --local-dir ./test-model
# Download an entire repo, optionally filtered with --include / --exclude
npx @huggingface/hub download coyotte508/test-model --local-dir ./test-model
npx @huggingface/hub download --repo-type dataset coyotte508/test-dataset --include "*.json"

npx @huggingface/hub --help
npx @huggingface/hub upload --help
npx @huggingface/hub download --help

Bạn cũng có thể cài đặt toàn cục bằng npm install -g @huggingface/hub. Sau đó bạn có thể thực hiện:

hfjs upload coyotte508/test-model .

hfjs branch create --repo-type dataset coyotte508/test-dataset release --empty
hfjs upload --repo-type dataset coyotte508/test-dataset . --revision release

hfjs download coyotte508/test-model config.json
hfjs download coyotte508/test-model --local-dir ./test-model

hfjs --help
hfjs  upload --help

hfjs help jobs
hfjs download --help

Đăng nhập OAuth

Bạn có thể đăng nhập bằng OAuth (“Đăng nhập bằng HF”).

Điều này sẽ cho phép bạn nhận được một access token để sử dụng một số API, tùy thuộc vào các scopes được thiết lập bên trong Space hoặc OAuth App.

import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";

const oauthResult = await oauthHandleRedirectIfPresent();

if (!oauthResult) {
  // If the user is not logged in, redirect to the login page
  window.location.href = await oauthLoginUrl();
}

// You can use oauthResult.accessToken, oauthResult.accessTokenExpiresAt and oauthResult.userInfo
console.log(oauthResult);

Xem demo: https://huggingface.co/spaces/huggingfacejs/client-side-oauth

Bộ nhớ đệm Hugging Face

Gói @huggingface/hub cung cấp các khả năng cơ bản để quét thư mục cache. Tìm hiểu thêm về Quản lý hệ thống cache của huggingface_hub.

scanCacheDir

Bạn có thể lấy danh sách các kho lưu trữ đã được lưu bộ nhớ đệm bằng cách sử dụng hàm scanCacheDir.

import { scanCacheDir } from "@huggingface/hub";

const result = await scanCacheDir();

console.log(result);

Lưu ý: điều này không hoạt động trong trình duyệt

downloadFileToCacheDir

Bạn có thể lưu trữ một tệp của kho lưu trữ vào bộ nhớ đệm bằng cách sử dụng hàm downloadFileToCacheDir.

import { downloadFileToCacheDir } from "@huggingface/hub";

const file = await downloadFileToCacheDir({
  repo: 'foo/bar',
  path: 'README.md'
});

console.log(file);

Lưu ý: điều này không hoạt động trong trình duyệt

snapshotDownload

Bạn có thể tải xuống toàn bộ một kho lưu trữ tại một phiên bản nhất định trong thư mục cache bằng cách sử dụng hàm snapshotDownload.

import { snapshotDownload } from "@huggingface/hub";

const directory = await snapshotDownload({
  repo: 'foo/bar',
});

console.log(directory);

Mã sử dụng bên trong hàm downloadFileToCacheDir.

Lưu ý: điều này không hoạt động trong trình duyệt

Xem xét hiệu năng

Khi tải lên các tệp lớn, bạn có thể muốn chạy các lệnh commit bên trong một worker để chuyển việc tính toán sha256 sang đó.

Tài nguyên từ xa và tệp cục bộ nên được truyền dưới dạng URL bất cứ khi nào có thể để chúng có thể được nạp theo cách lười biếng từng phần, giúp giảm mức sử dụng RAM. Việc truyền một File trong ngữ cảnh của trình duyệt là hoàn toàn ổn, vì nó vốn đã hoạt động như một Blob.

Bên trong, @huggingface/hub sử dụng một triển khai blob lười (lazy) để tải tệp.

Để chỉnh sửa một tệp hiện có, hãy ưu tiên thao tác commit edit với blob do downloadFile trả về làm originalContent: chỉ các vùng được chỉnh sửa sẽ được tải xuống, chia chunk lại và băm. Đối với các lần thêm liên tiếp vào cùng một tệp, hãy truyền rangeEditCache: new Map() dùng chung cho các lời gọi commit để cũng bỏ qua các vòng lặp trao đổi metadata lưu trữ.

Phụ thuộc

  • @huggingface/tasks : Chỉ có kiểu
Update on GitHub