Hub Python 库文档
通过文件系统API与Hub交互
并获得增强的文档体验
开始使用
通过文件系统API与Hub交互
除了 HfApi,huggingface_hub
库还提供了 HfFileSystem,这是一个与 Hugging Face Hub 兼容的 pythonic fsspec 文件接口。HfFileSystem 构建在 HfApi 之上,提供典型的文件系统风格操作,如 cp
、mv
、ls
、du
、glob
、get_file
和 put_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/
,而模型在 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")
同样的工作流程也适用于 Dask 和 Polars 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()
使用 Zarr 将 Hub 用作数组存储
>>> 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 上更新