baba521's picture
test
f71610e
from huggingface_hub import HfApi, hf_hub_url
def get_hf_files_with_links(repo_id):
"""
获取Hugging Face仓库中的文件列表(文件名和完整链接),排除.gitattributes文件
Args:
repo_id (str): Hugging Face仓库ID,格式为"用户名/仓库名"
Returns:
list: 包含字典的列表,每个字典包含'title'和'link'键
例如: [{'title': 'model.bin', 'link': 'https://huggingface.co/...'}, ...]
Raises:
ValueError: 当获取文件列表失败时抛出异常
"""
try:
# 初始化Hugging Face API客户端
api = HfApi()
# 获取仓库中的所有文件
files = api.list_repo_files(repo_id=repo_id, repo_type="model")
# 过滤掉.gitattributes文件并生成完整链接
file_list = []
for file_path in files:
# 排除.gitattributes文件
if file_path != ".gitattributes":
# 生成文件的完整URL
file_url = hf_hub_url(repo_id=repo_id, filename=file_path)
file_list.append({
'title': file_path,
'link': file_url
})
return file_list
except Exception as e:
raise ValueError(f"获取文件列表失败: {str(e)}")