Hub Python Library documentation

Buckets

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Buckets

Buckets oferecem armazenamento de objetos semelhante ao S3 no Hugging Face, impulsionado pelo backend de armazenamento Xet. Diferentemente dos repositórios (que são baseados em git e rastreiam o histórico de arquivos), buckets são contêineres de armazenamento de objetos remotos projetados para arquivos em larga escala com deduplicação endereçável por conteúdo. Eles são projetados para casos de uso em que você precisa de armazenamento simples, rápido e mutável, como armazenar checkpoints de treinamento, logs, artefatos intermediários ou qualquer grande coleção de arquivos que não necessite de controle de versão.

Você pode interagir com buckets usando a API em Python (HfApi) ou a CLI (hf buckets). Neste guia, passaremos por todas as operações disponíveis.

Todos os comandos de CLI estão disponíveis sob hf buckets <command>. Execute hf buckets --help para saber mais.

Criar e gerenciar buckets

Criar um bucket

Crie um bucket com create_bucket(). Você precisa fornecer um nome para o bucket. Se não especificar um namespace, o bucket será criado sob seu nome de usuário.

>>> from huggingface_hub import create_bucket

# Create a bucket under your namespace
>>> url = create_bucket("my-bucket")
>>> url.bucket_id
'username/my-bucket'
>>> url.uri.to_uri()
'hf://buckets/username/my-bucket'

# Create a private bucket
>>> create_bucket("my-private-bucket", private=True)
BucketUrl(...)

# Don't error if bucket already exists
>>> create_bucket("my-bucket", exist_ok=True)
BucketUrl(...)

# Create a bucket in a specific region
>>> create_bucket("my-bucket", region="us")
BucketUrl(...)

Ou via CLI:

>>> hf buckets create my-bucket
✓ Bucket created
  uri: hf://buckets/Wauplin/my-bucket
  url: https://huggingface.co/buckets/Wauplin/my-bucket

# Create a private bucket
>>> hf buckets create my-bucket --private

# Don't error if bucket already exists
>>> hf buckets create my-bucket --exist-ok

# Create a bucket in a specific region
>>> hf buckets create my-bucket --region us

Você também pode especificar o formato completo namespace/bucket_name para criar um bucket sob uma organização:

>>> from huggingface_hub import create_bucket
>>> create_bucket("my-org/shared-bucket")

Ou via CLI:

>>> hf buckets create my-org/shared-bucket

Obter informações do bucket

Use bucket_info() para obter metadados sobre um bucket, incluindo sua visibilidade, tamanho total, contagem de arquivos e data de criação.

>>> from huggingface_hub import bucket_info
>>> bucket_info("username/my-bucket")
BucketInfo(
  id='username/my-bucket',
  private=False,
  created_at=datetime.datetime(2026, 2, 12, 17, 42, 12,
  tzinfo=datetime.timezone.utc),
  size=8411791508,
  total_files=128
)

Ou via CLI:

# JSON output
>>> hf buckets info username/my-bucket
{
  "id": "username/my-bucket",
  "private": false,
  ...
}

Listar buckets

Use list_buckets() para listar todos os buckets em um namespace. Por padrão, ele lista os buckets no namespace do usuário atual.

>>> from huggingface_hub import list_buckets

# List your own buckets
>>> for bucket in list_buckets():
...     print(bucket.id, bucket.size, bucket.total_files)

# List buckets in an organization
>>> for bucket in list_buckets(namespace="huggingface"):
...     print(bucket.id)

Ou via CLI (hf buckets ls é uma abreviação para hf buckets list):

# Table format (default)
>>> hf buckets list
ID                   PRIVATE      SIZE TOTAL_FILES CREATED_AT
-------------------- ------- --------- ----------- ----------
username/my-bucket                  32           5 2026-02-16
username/checkpoints         117609095         700 2026-02-13
username/logs                321757477        2000 2026-02-13

# Human-readable sizes
>>> hf buckets list -h
ID                   PRIVATE     SIZE TOTAL_FILES CREATED_AT
-------------------- ------- -------- ----------- ----------
username/my-bucket               32 B           5 2026-02-16
username/checkpoints         117.6 MB         700 2026-02-13
username/logs                321.8 MB        2000 2026-02-13

# List buckets in a specific namespace
>>> hf buckets ls huggingface

# Filter buckets by name
>>> hf buckets list --search "checkpoint"

Você também pode filtrar buckets por nome usando search:

>>> for bucket in list_buckets(search="checkpoint"):
...     print(bucket.id)

Você pode usar as opções --quiet e --format json para obter um formato de saída diferente. Isso é particularmente interessante se você quiser encaminhar a saída para outra ferramenta, como grep ou jq.

# Quiet mode: prints one bucket ID per line
>>> hf buckets list --quiet
username/my-bucket
username/checkpoints
username/logs

# JSON format
>>> hf buckets list --format json
[
  {
    "id": "username/my-bucket",
    "private": false,
    "created_at": "2026-02-16T15:28:32+00:00",
    "size": 32,
    "total_files": 5
  },
  ...
]

Alterar a visibilidade do bucket

Use update_bucket_settings() para alternar um bucket existente entre privado e público.

>>> from huggingface_hub import update_bucket_settings

# Make a bucket private
>>> update_bucket_settings("username/my-bucket", private=True)

# Make it public again
>>> update_bucket_settings("username/my-bucket", private=False)

Ou via CLI:

# Make a bucket private
>>> hf buckets settings username/my-bucket --private
✓ Bucket settings updated
  bucket_id: username/my-bucket
  private: True

# Make it public again
>>> hf buckets settings username/my-bucket --public

Excluir um bucket

Use delete_bucket() para excluir um bucket. Essa operação é irreversível.

>>> from huggingface_hub import delete_bucket
>>> delete_bucket("username/my-bucket")

# Don't error if bucket doesn't exist
>>> delete_bucket("username/my-bucket", missing_ok=True)

Ou via CLI:

# Prompts for confirmation
>>> hf buckets delete username/my-bucket

# Skip confirmation
>>> hf buckets delete username/my-bucket --yes

# Don't error if bucket doesn't exist
>>> hf buckets delete username/my-bucket --yes --missing-ok

Excluir arquivos

Use batch_bucket_files() com o parâmetro delete para excluir arquivos de um bucket:

>>> from huggingface_hub import batch_bucket_files

# Delete specific files
>>> batch_bucket_files("username/my-bucket", delete=["old-model.bin", "logs/debug.log"])

Ou via CLI com hf buckets rm (ou hf buckets remove):

# Remove a single file
>>> hf buckets rm username/my-bucket/old-model.bin

# Remove all files under a prefix (requires --recursive)
>>> hf buckets rm username/my-bucket/logs/ --recursive

# Remove only files matching a pattern across the entire bucket
>>> hf buckets rm username/my-bucket --recursive --include "*.tmp"

# Exclude specific files from removal
>>> hf buckets rm username/my-bucket/data/ --recursive --exclude "*.safetensors"

# Preview what would be deleted
>>> hf buckets rm username/my-bucket/checkpoints/ --recursive --dry-run

Mover um bucket

Use move_bucket() para mover ou renomear um bucket. Você pode renomear dentro do mesmo namespace ou transferir para um namespace diferente (usuário ou organização).

>>> from huggingface_hub import move_bucket

# Rename a bucket
>>> move_bucket(from_id="username/old-name", to_id="username/new-name")

# Transfer to an organization
>>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")

Ou via CLI:

# Rename a bucket
>>> hf buckets move username/old-bucket username/new-bucket

# Transfer to an organization
>>> hf buckets move username/my-bucket my-org/my-bucket

# Using the hf://buckets/ format
>>> hf buckets move hf://buckets/username/old-bucket hf://buckets/username/new-bucket

Para mais informações sobre a movimentação de repositórios e buckets, consulte a documentação do Hub.

Exibir o conteúdo do bucket

Listar arquivos

Use list_bucket_tree() para listar arquivos e diretórios em um bucket.

>>> from huggingface_hub import list_bucket_tree

# List all files
>>> for item in list_bucket_tree("username/my-bucket"):
...     print(item.path, item.size)
file.txt 5
big.bin 2048
sub/nested.txt 14
sub/deep/file.txt 4

# List top-level entries only
>>> for item in list_bucket_tree("username/my-bucket", recursive=False):
...     print(item.type, item.path)
file file.txt
file big.bin
directory sub

# Filter by prefix
>>> for item in list_bucket_tree("username/my-bucket", prefix="sub"):
...     print(item.path)

Ou via CLI, com suporte aos formatos de tabela, legível por humanos e árvore ASCII. Por padrão, a CLI não é recursiva.

# Default table format (non-recursive, directories shown as entries)
>>> hf buckets list username/my-bucket
        2048  2026-01-15 10:30:00  big.bin
           5  2026-01-15 10:30:00  file.txt
              2026-01-15 10:30:00  sub/

# Recursive listing (all files, including nested)
>>> hf buckets list username/my-bucket -R
        2048  2026-01-15 10:30:00  big.bin
           5  2026-01-15 10:30:00  file.txt
          14  2026-01-15 10:30:00  sub/nested.txt
           4  2026-01-15 10:30:00  sub/deep/file.txt

# Human-readable sizes and short dates
>>> hf buckets list username/my-bucket -R -h
      2.0 KB         Jan 15 10:30  big.bin
         5 B         Jan 15 10:30  file.txt
        14 B         Jan 15 10:30  sub/nested.txt
         4 B         Jan 15 10:30  sub/deep/file.txt

# ASCII tree format
>>> hf buckets list username/my-bucket --tree -h -R
2.0 KB  Jan 15 10:30  ├── big.bin
   5 B  Jan 15 10:30  ├── file.txt
                      └── sub/
                          ├── deep/
   4 B  Jan 15 10:30  │       └── file.txt
  14 B  Jan 15 10:30  └── nested.txt

# Tree structure only (no sizes/dates)
>>> hf buckets list username/my-bucket --tree --quiet -R
├── big.bin
├── file.txt
└── sub/
    ├── deep/
    │   └── file.txt
    └── nested.txt

# Quiet mode: one path per line
>>> hf buckets list username/my-bucket -q
big.bin
file.txt
sub/

# Filter by prefix
>>> hf buckets list username/my-bucket/sub -R

O comando hf buckets list aceita tanto o formato curto (username/my-bucket/sub) quanto o handle completo (hf://buckets/username/my-bucket/sub) como argumentos.

Listar um bucket com HfFileSystem faz cache de seu conteúdo. Passe HfFileSystem(live_follow=True) para que as listagens sejam atualizadas conforme os arquivos são adicionados, atualizados e excluídos no bucket por outros peers, veja o guia do filesystem.

Enviar arquivos

Upload com Python

Use batch_bucket_files() para enviar arquivos para um bucket. Você pode enviar a partir de caminhos de arquivos locais ou de bytes brutos:

>>> from huggingface_hub import batch_bucket_files

# Upload from local file paths
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[
...         ("./model.safetensors", "models/model.safetensors"),
...         ("./config.json", "models/config.json"),
...     ],
... )

# Upload from raw bytes
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[
...         (b'{"key": "value"}', "config.json"),
...     ],
... )

Você também pode copiar arquivos xet de outro bucket ou repositório usando o parâmetro copy. Essa é uma operação no lado do servidor — nenhum dado é baixado ou reenviado:

# Copy files by xet hash (source_repo_type, source_repo_id, xet_hash, destination)
>>> batch_bucket_files(
...     "username/my-bucket",
...     copy=[
...         ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
...         ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
...     ],
... )

Os hashes Xet podem ser obtidos usando list_repo_tree.

Você também pode excluir arquivos enquanto faz o upload de outros.

# Upload and delete in one batch
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[("./new-model.safetensors", "model.safetensors")],
...     delete=["old-model.bin"],
... )

Chamadas para batch_bucket_files() não são transacionais. Se um erro ocorrer durante o processo, alguns arquivos podem ter sido enviados, copiados ou excluídos, enquanto outros não. Quando o servidor relata que algumas operações falharam, um BucketBatchError é lançado com os caminhos que falharam em seu atributo failures.

Envie um arquivo único com a CLI

Use hf buckets cp para enviar um arquivo único:

hf buckets cp é um alias para o comando unificado hf cp (também exposto como hf repos cp). Os três são idênticos, portanto, qualquer exemplo de hf buckets cp abaixo também funciona com hf cp.

# Upload to bucket root (uses local filename as remote name)
>>> hf buckets cp ./config.json hf://buckets/username/my-bucket

# Upload to a subdirectory
>>> hf buckets cp ./data.csv hf://buckets/username/my-bucket/logs/

# Upload with a different remote filename
>>> hf buckets cp ./model.safetensors hf://buckets/username/my-bucket/v2/model.safetensors

Você também pode encaminhar o resultado de um comando diretamente para um novo arquivo usando -:

# Upload from stdin
>>> echo "hello" | hf buckets cp - hf://buckets/username/my-bucket/hello.txt
>>> cat model.safetensors | hf buckets cp - hf://buckets/username/my-bucket/model.safetensors

Envie um diretório com a CLI

Use hf buckets sync para enviar um diretório local inteiro para um bucket:

# Upload a local directory to a bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket

# Upload to a specific prefix in the bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket/train

Veja a seção Sincronizar diretórios abaixo para o conjunto completo de opções de sincronização.

Baixar arquivos

Baixar com Python

Use download_bucket_files() para baixar arquivos de um bucket:

>>> from huggingface_hub import download_bucket_files

# Download specific files by path
>>> download_bucket_files(
...     "username/my-bucket",
...     files=[
...         ("models/model.safetensors", "./local/model.safetensors"),
...         ("config.json", "./local/config.json"),
...     ],
... )

Para um melhor desempenho, você pode passar objetos BucketFile obtidos de list_bucket_tree() em vez de caminhos de string. Isso pula a etapa de busca de metadados:

>>> from huggingface_hub import list_bucket_tree, download_bucket_files

# List and filter files, then download
>>> parquet_files = [
...     item for item in list_bucket_tree("username/my-bucket", recursive=True)
...     if item.type == "file" and item.path.endswith(".parquet")
... ]
>>> download_bucket_files(
...     "username/my-bucket",
...     files=[(f, f"./local/{f.path}") for f in parquet_files],
... )

Baixe um arquivo único com a CLI

Use hf buckets cp para baixar um arquivo único:

# Download to a specific file
>>> hf buckets cp hf://buckets/username/my-bucket/config.json ./config.json

# Download to a directory (uses original filename)
>>> hf buckets cp hf://buckets/username/my-bucket/config.json ./data/

# Download to current directory (omit destination)
>>> hf buckets cp hf://buckets/username/my-bucket/config.json

Você também pode encaminhar o conteúdo de um arquivo diretamente para stdout usando -:

# Download to stdout and pretty-print with jq
>>> hf buckets cp hf://buckets/username/my-bucket/config.json - | jq .

Baixe um diretório com a CLI

Use hf buckets sync para baixar todos os arquivos de um bucket para um diretório local:

# Download bucket contents to a local directory
>>> hf buckets sync hf://buckets/username/my-bucket ./data

# Download only a specific prefix
>>> hf buckets sync hf://buckets/username/my-bucket/models ./local-models

Veja a seção Sincronizar diretórios abaixo para o conjunto completo de opções de sincronização.

Copiar arquivos para o Bucket

Use copy_files() para copiar arquivos já hospedados no Hub para um Bucket:

>>> from huggingface_hub import copy_files

# Bucket to bucket (same or different bucket)
>>> copy_files(
...     "hf://buckets/username/source-bucket/checkpoints/model.safetensors",
...     "hf://buckets/username/destination-bucket/archive/model.safetensors",
... )

# Repo to bucket
>>> copy_files(
...     "hf://datasets/username/my-dataset/processed/",
...     "hf://buckets/username/my-bucket/datasets/processed/",
... )

O mesmo está disponível na CLI por meio do comando unificado hf cp (também exposto como hf buckets cp e hf repos cp — os três são idênticos):

# Bucket to bucket
>>> hf cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/destination-bucket/logs/

# Repo to bucket
>>> hf cp hf://username/my-model/config.json hf://buckets/username/my-bucket/models/config.json

Ao copiar pastas, uma barra / no final da origem usa semântica estilo rsync — apenas o conteúdo da pasta é copiado, sem aninhar a própria pasta:

# Without trailing slash: "logs" dir is nested => destination/logs/...
>>> hf cp hf://buckets/username/source-bucket/logs hf://buckets/username/destination-bucket/

# With trailing slash: only contents of "logs" are copied => destination/...
>>> hf cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/destination-bucket/

Observações:

  • A cópia de bucket para repositório ainda não é suportada.
  • Cópias no lado do servidor funcionam apenas dentro da mesma região de armazenamento.
  • Arquivos rastreados com Xet (em buckets ou repositórios) são copiados no servidor por hash — nenhum dado é baixado ou reenviado.
  • Arquivos de texto pequenos não rastreados com Xet nas fontes do repositório são baixados e reenviados para o bucket de destino.
  • copy_files() também pode ser usado para cópias de repositório para repositório. Consulte o guia de repositórios para mais detalhes.

Sincronizar diretórios

O comando hf buckets sync (e seu equivalente na API, sync_bucket()) é a maneira mais poderosa de transferir arquivos entre um diretório local e um bucket. Ele compara a origem e o destino e transfere apenas os arquivos que foram alterados.

Sincronização básica

# Upload: local directory -> bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket

# Download: bucket -> local directory
>>> hf buckets sync hf://buckets/username/my-bucket ./data

hf sync é um alias conveniente para hf buckets sync. Ambos os comandos são idênticos.

>>> hf sync ./data hf://buckets/username/my-bucket

Ou via Python:

>>> from huggingface_hub import sync_bucket

# Upload: local directory -> bucket
>>> sync_bucket("./data", "hf://buckets/username/my-bucket")

# Download: bucket -> local directory
>>> sync_bucket("hf://buckets/username/my-bucket", "./data")

Excluir arquivos desnecessários

Por padrão, o sync apenas adiciona ou atualiza arquivos. Use --delete (ou delete=True em Python) para também remover arquivos no destino que não existem na origem:

# Upload and remove remote files not present locally
>>> hf buckets sync ./data hf://buckets/username/my-bucket --delete

# Download and remove local files not present in bucket
>>> hf buckets sync hf://buckets/username/my-bucket ./data --delete

Ou via Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", delete=True)
>>> sync_bucket("hf://buckets/username/my-bucket", "./data", delete=True)

Filtragem

Você pode controlar quais arquivos são sincronizados usando padrões de inclusão/exclusão:

# Only sync .txt files
>>> hf buckets sync ./data hf://buckets/username/my-bucket --include "*.txt"

# Exclude log files
>>> hf buckets sync ./data hf://buckets/username/my-bucket --exclude "*.log"

# Combine include and exclude
>>> hf buckets sync ./data hf://buckets/username/my-bucket --include "*.safetensors" --exclude "*.tmp"

Ou via Python:

# Only sync .txt files
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", include=["*.txt"])

# Exclude log files
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", exclude=["*.log"])

# Combine include and exclude
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", include=["*.safetensors"], exclude=["*.tmp"])

Para filtragem mais complexa, use um arquivo de filtro com --filter-from (ou filter_from em Python):

>>> hf buckets sync ./data hf://buckets/username/my-bucket --filter-from filters.txt

O arquivo de filtro usa os prefixos + (incluir) e - (excluir). Linhas que começam com # são comentários. As regras são avaliadas em ordem (a primeira regra correspondente prevalece):

# filters.txt
- *.log
- *.tmp
+ *.safetensors
+ *.json

Modos de comparação

Por padrão, o sync compara arquivos usando tanto o tamanho quanto a data de modificação. Você pode personalizar esse comportamento:

# Only compare sizes (ignore modification times)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-times

# Only compare modification times (ignore sizes)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-sizes

# Only update files that already exist on the receiver (skip new files)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --existing

# Only create new files (skip files that already exist on the receiver)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-existing

Ou via Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_times=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_sizes=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", existing=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_existing=True)

Planejar e aplicar

Para operações críticas, você pode revisar o plano de sincronização antes de executá-lo:

# Step 1: Generate a plan file (nothing is transferred)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --plan sync-plan.jsonl
Sync plan: ./data -> hf://buckets/username/my-bucket
  Uploads: 3
  Downloads: 0
  Deletes: 0
  Skips: 1
Plan saved to: sync-plan.jsonl

# Step 2: Review the plan file (JSONL format)
>>> cat sync-plan.jsonl

# Step 3: Apply the plan
>>> hf buckets sync --apply sync-plan.jsonl

Ou via Python:

# Step 1: Generate a plan file (nothing is transferred)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")

# Step 2: Review the plan file (JSONL format), then apply
>>> sync_bucket(apply="sync-plan.jsonl")

O arquivo de plano é um arquivo JSONL com uma linha de cabeçalho seguida por uma linha por operação. Cada operação inclui a ação (upload, download, delete ou skip), o caminho do arquivo e o motivo da ação. Você pode editar este arquivo manualmente antes de aplicá-lo, mas tenha cuidado com a sintaxe.

Execução de teste

Use --dry-run (ou dry_run=True em Python) para obter o plano de sincronização sem executar nada:

# Preview what would be synced
>>> hf buckets sync ./data hf://buckets/username/my-bucket --dry-run | jq '.action'

Ou via Python:

>>> plan = sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}

--dry-run exibe o mesmo formato JSONL que --plan, mas imprime no stdout em vez de salvar em um arquivo. Apenas o conteúdo JSONL é impresso, o que torna seguro usar pipe.

Modos detalhado e silencioso

# Show per-file operations
>>> hf buckets sync ./data hf://buckets/username/my-bucket --verbose

# Suppress all output
>>> hf buckets sync ./data hf://buckets/username/my-bucket --quiet

Ou via Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", verbose=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", quiet=True)

Avançado

Para casos de uso de nível mais baixo, os seguintes métodos também estão disponíveis:

  • get_bucket_paths_info(): Busca informações sobre caminhos específicos em um bucket em uma única solicitação em lote. Útil quando você sabe exatamente de quais arquivos precisa dos metadados.
>>> from huggingface_hub import get_bucket_paths_info
>>> for info in get_bucket_paths_info("username/my-bucket", ["file.txt", "models/model.safetensors"]):
...     print(info.path, info.size, info.xet_hash)
>>> from huggingface_hub import get_bucket_file_metadata
>>> metadata = get_bucket_file_metadata("username/my-bucket", "models/model.safetensors")
>>> metadata.size
42000
Update on GitHub