Huggingface.js documentation
🤗 API Hugging Face Hub
🤗 API Hugging Face Hub
Utilitas resmi untuk menggunakan API Hugging Face Hub.
Instal
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"Penggunaan
Untuk beberapa panggilan, Anda perlu membuat akun dan menghasilkan token akses.
Pelajari cara menemukan model gratis menggunakan paket hub dalam tutorial interaktif ini.
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_..." });Buckets
Storage Buckets adalah penyimpanan yang dapat diubah dan tidak ber-versi di Hub. Gunakan awalan buckets/ (atau { type: "bucket", name }) dengan fungsi yang sama:
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_...",
});Penggunaan CLI
Anda dapat menggunakan @huggingface/hub dalam mode CLI untuk mengunggah dan mengunduh file serta folder ke/dari repo Anda.
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 --helpAnda juga dapat menginstalnya secara global dengan npm install -g @huggingface/hub. Kemudian Anda dapat melakukan:
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
Login OAuth
Anda dapat masuk menggunakan OAuth (“Sign in with HF”).
Hal ini akan memungkinkan Anda mendapatkan token akses untuk menggunakan sebagian API, tergantung pada cakupan (scopes) yang diatur di dalam Space atau Aplikasi OAuth.
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);Coba lihat demonya: https://huggingface.co/spaces/huggingfacejs/client-side-oauth
Cache Hugging Face
Paket @huggingface/hub menyediakan kemampuan dasar untuk memindai direktori cache. Pelajari lebih lanjut tentang Manage huggingface_hub cache-system.
scanCacheDir
Anda dapat memperoleh daftar repositori yang di-cache menggunakan fungsi scanCacheDir.
import { scanCacheDir } from "@huggingface/hub";
const result = await scanCacheDir();
console.log(result);Catatan: ini tidak berfungsi di browser
downloadFileToCacheDir
Anda dapat meng-cache file dari sebuah repositori menggunakan fungsi downloadFileToCacheDir.
import { downloadFileToCacheDir } from "@huggingface/hub";
const file = await downloadFileToCacheDir({
repo: 'foo/bar',
path: 'README.md'
});
console.log(file);Catatan: ini tidak berfungsi di browser
snapshotDownload
Anda dapat mengunduh seluruh repositori pada revisi tertentu di direktori cache menggunakan fungsi snapshotDownload.
import { snapshotDownload } from "@huggingface/hub";
const directory = await snapshotDownload({
repo: 'foo/bar',
});
console.log(directory);Kode menggunakan fungsi downloadFileToCacheDir secara internal.
Catatan: ini tidak berfungsi di browser
Pertimbangan kinerja
Saat mengunggah file berukuran besar, Anda mungkin ingin menjalankan panggilan commit di dalam worker, untuk memindahkan komputasi sha256.
Sumber daya jarak jauh dan file lokal sebaiknya diteruskan sebagai URL setiap kali memungkinkan agar dapat dimuat secara malas dalam potongan untuk mengurangi penggunaan RAM. Meneruskan File di dalam konteks browser tidak masalah, karena secara bawaan berperilaku sebagai Blob.
Di balik layar, @huggingface/hub menggunakan implementasi blob yang dimuat secara lambat (lazy) untuk memuat file.
Untuk mengedit file yang sudah ada, lebih baik gunakan operasi commit edit dengan blob yang dikembalikan oleh downloadFile sebagai originalContent: hanya wilayah yang diedit yang diunduh, di-chunk ulang, dan di-hash. Untuk penambahan berulang ke file yang sama, berikan rangeEditCache: new Map() yang dibagikan ke panggilan commit untuk juga melewati round-trip metadata penyimpanan.
Dependensi
@huggingface/tasks: Hanya tip