Huggingface.js documentation
🤗 Hugging Face Hub API
🤗 Hugging Face Hub API
Hugging Face Hub API'sini kullanmak için resmi yardımcılar.
Yükle
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"Kullanım
Bazı çağrılar için bir hesap oluşturmanız ve bir erişim belirteci üretmeniz gerekir.
Bu etkileşimli öğreticide, hub paketini kullanarak ücretsiz modelleri nasıl bulacağınızı öğrenin.
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_..." });Kovalar
Depolama Kovaları, Hub'da değiştirilebilir, sürüm yönetimi yapılmayan depolama alanlarıdır. Aynı işlevlerle buckets/ öneki (veya { type: "bucket", name }) kullanın:
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 kullanımı
@huggingface/hub paketini CLI modunda kullanarak dosyaları ve klasörleri reponuza yükleyebilir veya repodan indirebilirsiniz.
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 --helpAyrıca npm install -g @huggingface/hub ile global olarak da kurabilirsiniz. Ardından şunu yapabilirsiniz:
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 Giriş
OAuth (“HF ile oturum aç”) kullanarak oturum açmak mümkündür.
Bu, Uzay veya OAuth Uygulaması içinde ayarlanan kapsamlara bağlı olarak API'nin bazı kısımlarını kullanmak için bir erişim jetonu almanızı sağlar.
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);Demoyu inceleyin: https://huggingface.co/spaces/huggingfacejs/client-side-oauth
Hugging Face önbelleği
@huggingface/hub paketi, önbellek dizinini taramak için temel yetenekler sağlar. huggingface_hub önbellek sistemini yönetme hakkında daha fazla bilgi edinin.
scanCacheDir
Önbelleğe alınmış depoların listesini scanCacheDir işlevini kullanarak alabilirsiniz.
import { scanCacheDir } from "@huggingface/hub";
const result = await scanCacheDir();
console.log(result);Not: bu tarayıcıda çalışmaz
downloadFileToCacheDir
Bir depodaki dosyayı downloadFileToCacheDir işlevi kullanarak önbelleğe alabilirsiniz.
import { downloadFileToCacheDir } from "@huggingface/hub";
const file = await downloadFileToCacheDir({
repo: 'foo/bar',
path: 'README.md'
});
console.log(file);Not: bu tarayıcıda çalışmaz
snapshotDownload
Belirli bir revizyondaki tüm bir depoyu, önbellek dizininde snapshotDownload işlevini kullanarak indirebilirsiniz.
import { snapshotDownload } from "@huggingface/hub";
const directory = await snapshotDownload({
repo: 'foo/bar',
});
console.log(directory);Kod, içsel olarak downloadFileToCacheDir fonksiyonunu kullanır.
Not: bu tarayıcıda çalışmaz
Performans hususları
Büyük dosyaları yüklerken, sha256 hesaplamalarını devretmek için commit çağrılarını bir işçi (worker) içinde çalıştırmak isteyebilirsiniz.
Uzak kaynaklar ve yerel dosyalar, RAM kullanımını azaltmak için parçalar halinde tembel yüklenebilmeleri adına mümkün olduğunda URL olarak geçirilmelidir. Tarayıcı bağlamında bir File geçmek uygundur, çünkü bu, yerel olarak bir Blob gibi davranır.
Arka planda, @huggingface/hub dosyayı yüklemek için tembel blob uygulaması kullanır.
Mevcut bir dosyayı düzenlemek için, downloadFile tarafından döndürülen blob'u originalContent olarak kullanarak edit commit işlemini tercih edin: yalnızca düzenlenmiş bölgeler indirilir, yeniden parçalanır ve hash'lenir. Aynı dosyaya tekrarlanan eklemeler için, depolama-metadata gidiş-dönüşlerini de atlamak üzere commit çağrılarına ortak bir rangeEditCache: new Map() iletin.
Bağımlılıklar
@huggingface/tasks: Yalnızca tipler