Huggingface.js documentation

đŸ€— API do Hugging Face Hub

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

đŸ€— API do Hugging Face Hub

UtilitĂĄrios oficiais para usar a API do Hugging Face Hub.

Instalar

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"

Uso

Para algumas das chamadas, vocĂȘ precisa criar uma conta e gerar um token de acesso.

Aprenda a encontrar modelos gratuitos usando o pacote hub neste tutorial interativo.

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 são armazenamento mutåvel e sem versionamento no Hub. Use o prefixo buckets/ (ou { type: "bucket", name }) com as mesmas funçÔes:

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_...",
});

Uso da CLI

VocĂȘ pode usar @huggingface/hub em modo de CLI para enviar e baixar arquivos e pastas para/do seu repositĂłrio.

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

VocĂȘ tambĂ©m pode instalar globalmente com npm install -g @huggingface/hub. Em seguida, vocĂȘ pode fazer o seguinte:

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 com OAuth

É possível fazer login usando OAuth (“Sign in with HF”).

Isso permitirĂĄ que vocĂȘ obtenha um token de acesso para usar parte da API, dependendo dos escopos definidos no Space ou no aplicativo 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);

Confira a demonstração: https://huggingface.co/spaces/huggingfacejs/client-side-oauth

Cache do Hugging Face

O pacote @huggingface/hub fornece capacidades bĂĄsicas para escanear o diretĂłrio de cache. Saiba mais sobre Gerenciar o sistema de cache do huggingface_hub.

scanCacheDir

VocĂȘ pode obter a lista de repositĂłrios em cache usando a função scanCacheDir.

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

const result = await scanCacheDir();

console.log(result);

Observação: isso não funciona no navegador

downloadFileToCacheDir

VocĂȘ pode fazer o cache de um arquivo de um repositĂłrio usando a função downloadFileToCacheDir.

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

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

console.log(file);

Observação: isso não funciona no navegador

snapshotDownload

VocĂȘ pode baixar um repositĂłrio inteiro em uma revisĂŁo especĂ­fica no diretĂłrio de cache usando a função snapshotDownload.

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

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

console.log(directory);

O código usa internamente a função downloadFileToCacheDir.

Observação: isso não funciona no navegador

ConsideraçÔes de desempenho

Ao fazer upload de arquivos grandes, vocĂȘ pode querer executar as chamadas commit em um worker, para transferir os cĂĄlculos de sha256.

Recursos remotos e arquivos locais devem ser passados como URL sempre que possível, para que possam ser carregados de forma preguiçosa em blocos, reduzindo o uso de RAM. Passar um File dentro do contexto do navegador é aceitåvel, pois ele se comporta nativamente como um Blob.

Por baixo dos panos, @huggingface/hub usa uma implementação de blob preguiçosa para carregar o arquivo.

Para editar um arquivo existente, prefira uma operação de commit edit com o blob retornado por downloadFile como originalContent: apenas as regiÔes editadas são baixadas, re-chunkadas e hasheadas. Para anexos repetidos ao mesmo arquivo, passe um rangeEditCache: new Map() compartilhado para as chamadas de commit para também pular as idas e vindas de metadados de armazenamento.

DependĂȘncias

  • @huggingface/tasks : Apenas tipagens
Update on GitHub