Hub Python 库文档

通过文件系统 API 与 Hub 交互

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始

通过文件系统 API 与 Hub 交互

除了 HfApi 之外,`huggingface_hub` 库还提供了 HfFileSystem,这是一个 pythonic 的、兼容 fsspec 的文件接口,用于 Hugging Face Hub。HfFileSystem 构建于 HfApi 之上,并提供典型的文件系统风格操作,如 cpmvlsduglobget_fileput_file

HfFileSystem 提供 fsspec 兼容性,这对于需要它的库很有用(例如,使用 pandas 直接读取 Hugging Face 数据集)。但是,由于此兼容性层,它会引入额外的开销。为了获得更好的性能和可靠性,建议在可能的情况下使用 HfApi 方法。

用法

>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem()

>>> # List all files in a directory
>>> fs.ls("datasets/my-username/my-dataset-repo/data", detail=False)
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv']

>>> # List all ".csv" files in a repo
>>> fs.glob("datasets/my-username/my-dataset-repo/**/*.csv")
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv']

>>> # Read a remote file
>>> with fs.open("datasets/my-username/my-dataset-repo/data/train.csv", "r") as f:
...     train_data = f.readlines()

>>> # Read the content of a remote file as a string
>>> train_data = fs.read_text("datasets/my-username/my-dataset-repo/data/train.csv", revision="dev")

>>> # Write a remote file
>>> with fs.open("datasets/my-username/my-dataset-repo/data/validation.csv", "w") as f:
...     f.write("text,label")
...     f.write("Fantastic movie!,good")

可选的 revision 参数可以传递,以从特定提交(例如分支、标签名称或提交哈希)运行操作。

与 Python 内置的 open 不同,fsspec 的 open 默认使用二进制模式 "rb"。这意味着您必须显式将模式设置为文本模式下的读取 "r" 和写入 "w"。尚不支持附加到文件(模式 "a""ab")。

集成

HfFileSystem 可以与任何集成 fsspec 的库一起使用,前提是 URL 遵循以下方案

hf://[<repo_type_prefix>]<repo_id>[@<revision>]/<path/in/repo>

`repo_type_prefix` 对于数据集是 `datasets/`,对于 spaces 是 `spaces/`,模型在 URL 中不需要前缀。

下面列出了一些有趣的集成,其中 HfFileSystem 简化了与 Hub 的交互

  • 从/向 Hub 仓库读取/写入 Pandas DataFrame

    >>> import pandas as pd
    
    >>> # Read a remote CSV file into a dataframe
    >>> df = pd.read_csv("hf://datasets/my-username/my-dataset-repo/train.csv")
    
    >>> # Write a dataframe to a remote CSV file
    >>> df.to_csv("hf://datasets/my-username/my-dataset-repo/test.csv")

相同的工作流程也可以用于 DaskPolars DataFrame。

  • 使用 DuckDB 查询(远程)Hub 文件

    >>> from huggingface_hub import HfFileSystem
    >>> import duckdb
    
    >>> fs = HfFileSystem()
    >>> duckdb.register_filesystem(fs)
    >>> # Query a remote file and get the result back as a dataframe
    >>> fs_query_file = "hf://datasets/my-username/my-dataset-repo/data_dir/data.parquet"
    >>> df = duckdb.query(f"SELECT * FROM '{fs_query_file}' LIMIT 10").df()
  • 将 Hub 用作 Zarr 的数组存储

    >>> import numpy as np
    >>> import zarr
    
    >>> embeddings = np.random.randn(50000, 1000).astype("float32")
    
    >>> # Write an array to a repo
    >>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="w") as root:
    ...    foo = root.create_group("embeddings")
    ...    foobar = foo.zeros('experiment_0', shape=(50000, 1000), chunks=(10000, 1000), dtype='f4')
    ...    foobar[:] = embeddings
    
    >>> # Read an array from a repo
    >>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="r") as root:
    ...    first_row = root["embeddings/experiment_0"][0]

身份验证

在许多情况下,您必须登录 Hugging Face 帐户才能与 Hub 交互。请参阅文档的身份验证部分,以了解有关 Hub 上的身份验证方法的更多信息。

也可以通过以编程方式将您的 token 作为参数传递给 HfFileSystem 来登录

>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem(token=token)

如果您以这种方式登录,请注意在共享源代码时不要意外泄露令牌!

< > 在 GitHub 上更新