Huggingface.js documentation
🤗 Hugging Face Hub API
🤗 Hugging Face Hub API
Hugging Face Hub API を利用するための公式ユーティリティ。
インストール
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"使用方法
一部の呼び出しでは、アカウントの作成とアクセストークンの生成が必要です。
このインタラクティブなチュートリアルで、hubパッケージを使用して無料のモデルを見つける方法を学びましょう。
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_..." });バケット
Storage Bucketsは、Hub上の可変でバージョン管理されないストレージです。同じ関数にbuckets/プレフィックス(または{ type: "bucket", name })を付けて使用します:
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_...",
});CLIの使用方法
@huggingface/hubをCLIモードで使用すると、リポジトリへのファイルやフォルダのアップロードおよびダウンロードを行うことができます。
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 --helpnpm install -g @huggingface/hub を使用してグローバルにインストールすることもできます。その後、以下のように実行できます。
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
OAuthログイン
OAuth(“Sign in with HF”)を使用してログインすることも可能です。
これにより、SpaceまたはOAuth App内で設定されたスコープに応じて、APIの一部を使用するためのアクセストークンを取得できます。
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);デモを確認してください: https://huggingface.co/spaces/huggingfacejs/client-side-oauth
Hugging Face キャッシュ
@huggingface/hub パッケージは、キャッシュディレクトリをスキャンするための基本的な機能を提供します。huggingface_hub のキャッシュシステムの管理について詳しく学習してください。
scanCacheDir
scanCacheDir関数を使用して、キャッシュされたリポジトリのリストを取得できます。
import { scanCacheDir } from "@huggingface/hub";
const result = await scanCacheDir();
console.log(result);注: これはブラウザでは動作しません
downloadFileToCacheDir
downloadFileToCacheDir 関数を使用して、リポジトリのファイルをキャッシュできます。
import { downloadFileToCacheDir } from "@huggingface/hub";
const file = await downloadFileToCacheDir({
repo: 'foo/bar',
path: 'README.md'
});
console.log(file);注: これはブラウザでは動作しません
snapshotDownload
snapshotDownload関数を使用すると、指定されたリビジョンのレポジトリ全体をキャッシュディレクトリにダウンロードできます。
import { snapshotDownload } from "@huggingface/hub";
const directory = await snapshotDownload({
repo: 'foo/bar',
});
console.log(directory);このコードは内部でdownloadFileToCacheDir関数を使用しています。
注: これはブラウザでは動作しません
パフォーマンスに関する考慮事項
大きなファイルをアップロードする場合は、sha256の計算をオフロードするために、commitコールをワーカー内で実行することを検討してください。
リモートリソースとローカルファイルは、RAM使用量を削減するためにチャンク単位で遅延読み込みできるように、可能な限りURLとして渡す必要があります。ブラウザのコンテキスト内でFileを渡すのは問題ありません。これはネイティブでBlobとして動作するからです。
内部では、@huggingface/hubはファイルを読み込むために遅延型ブロブ実装を使用しています。
既存のファイルを編集する場合は、downloadFile が返す blob を originalContent として渡す edit コミット操作を推奨します。これにより、編集された領域のみがダウンロード、再チャンク化、ハッシュ化されます。同じファイルへの繰り返し追記を行う場合は、commit 呼び出しに共有の rangeEditCache: new Map() を渡すことで、ストレージメタデータへの往復もスキップできます。
依存関係
@huggingface/tasks: 型定義のみ