xiaomoguhzz's picture
Add files using upload-large-folder tool
eba0a14 verified
#!/usr/bin/env python3
"""
压缩数据集并上传到 HuggingFace
=====================================================
每个数据集单独压缩为 tar.gz 文件,便于下载和管理
=====================================================
"""
import os
import tarfile
import argparse
from pathlib import Path
from tqdm import tqdm
try:
from huggingface_hub import HfApi, login, upload_file
except ImportError:
print("请先安装 huggingface_hub: pip install huggingface_hub")
exit(1)
# HuggingFace 仓库
DATASET_REPO = "xiaomoguhzz/xiaomogu_pami_dataset"
# 数据集配置
DATASETS = {
"ade20k": {
"source": "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016",
"archive_name": "ADEChallengeData2016.tar.gz",
"description": "ADE20K Dataset (150 classes)"
},
"cityscapes": {
"source": "/mnt/SSD8T/home/wjj/dataset/cityscapes",
"archive_name": "cityscapes.tar.gz",
"description": "Cityscapes Dataset (19 classes)"
},
"coco_stuff": {
"source": "/mnt/SSD8T/home/wjj/dataset/standard_coco",
"archive_name": "coco_stuff_164k.tar.gz",
"description": "COCO-Stuff 164K Dataset (171 classes)"
},
"coco_obj": {
"source": "/mnt/SSD8T/home/wjj/dataset/coco_obj",
"archive_name": "coco_object.tar.gz",
"description": "COCO-Object Dataset (81 classes)"
},
"voc2012": {
"source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012",
"archive_name": "VOC2012.tar.gz",
"description": "PASCAL VOC 2012"
},
"voc2010": {
"source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010",
"archive_name": "VOC2010_context.tar.gz",
"description": "PASCAL Context (VOC2010)"
},
}
def get_dir_size(path: Path) -> int:
"""获取目录大小"""
total = 0
for f in path.rglob('*'):
if f.is_file():
total += f.stat().st_size
return total
def compress_dataset(name: str, config: dict, output_dir: Path, dry_run: bool = False) -> Path:
"""压缩单个数据集"""
source = Path(config["source"])
archive_name = config["archive_name"]
output_path = output_dir / archive_name
print(f"\n{'='*60}")
print(f"📦 [{name}] {config['description']}")
print(f"{'='*60}")
print(f"源路径: {source}")
print(f"输出文件: {output_path}")
if not source.exists():
print(f"⚠️ 源路径不存在,跳过")
return None
# 计算源目录大小
size_bytes = get_dir_size(source)
size_gb = size_bytes / (1024**3)
print(f"源目录大小: {size_gb:.2f} GB")
if dry_run:
print(f"🔍 [DRY RUN] 将压缩为: {archive_name}")
return output_path
if output_path.exists():
existing_size = output_path.stat().st_size / (1024**3)
print(f"✅ 已存在压缩文件 ({existing_size:.2f} GB)")
return output_path
# 创建 tar.gz 压缩文件
print(f"⏳ 正在压缩...")
try:
with tarfile.open(output_path, "w:gz") as tar:
# 使用 arcname 保持目录结构
tar.add(source, arcname=source.name)
compressed_size = output_path.stat().st_size / (1024**3)
compression_ratio = (1 - compressed_size / size_gb) * 100 if size_gb > 0 else 0
print(f"✅ 压缩完成: {compressed_size:.2f} GB (压缩率: {compression_ratio:.1f}%)")
return output_path
except Exception as e:
print(f"❌ 压缩失败: {e}")
return None
def upload_datasets(api: HfApi, archives: dict, dry_run: bool = False):
"""上传压缩的数据集到 HuggingFace"""
print(f"\n{'='*60}")
print(f"📤 上传到 HuggingFace: {DATASET_REPO}")
print(f"{'='*60}")
for name, archive_path in archives.items():
if archive_path is None or not archive_path.exists():
continue
size_gb = archive_path.stat().st_size / (1024**3)
print(f"\n[{name}] {archive_path.name} ({size_gb:.2f} GB)")
if dry_run:
print(f" 🔍 [DRY RUN] 将上传到: {archive_path.name}")
continue
try:
print(f" ⏳ 正在上传...")
api.upload_file(
path_or_fileobj=str(archive_path),
path_in_repo=archive_path.name,
repo_id=DATASET_REPO,
repo_type="dataset",
)
print(f" ✅ 上传完成")
except Exception as e:
print(f" ❌ 上传失败: {e}")
def main():
parser = argparse.ArgumentParser(description="压缩数据集并上传到 HuggingFace")
parser.add_argument("--compress-only", action="store_true", help="仅压缩,不上传")
parser.add_argument("--upload-only", action="store_true", help="仅上传已压缩的文件")
parser.add_argument("--output-dir", type=str, default="./dataset_archives", help="压缩文件输出目录")
parser.add_argument("--datasets", type=str, nargs="+",
choices=list(DATASETS.keys()) + ["all"],
default=["all"], help="要处理的数据集")
parser.add_argument("--dry-run", action="store_true", help="预览模式")
parser.add_argument("--token", type=str, help="HuggingFace token")
args = parser.parse_args()
# 输出目录
output_dir = Path(args.output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
# 确定要处理的数据集
if "all" in args.datasets:
datasets_to_process = DATASETS
else:
datasets_to_process = {k: v for k, v in DATASETS.items() if k in args.datasets}
print("="*60)
print("📊 数据集压缩与上传工具")
print("="*60)
print(f"输出目录: {output_dir}")
print(f"处理数据集: {list(datasets_to_process.keys())}")
if args.dry_run:
print("\n🔍 [DRY RUN] 预览模式\n")
archives = {}
# 压缩数据集
if not args.upload_only:
for name, config in datasets_to_process.items():
archive_path = compress_dataset(name, config, output_dir, dry_run=args.dry_run)
archives[name] = archive_path
else:
# 仅上传模式,查找已有的压缩文件
for name, config in datasets_to_process.items():
archive_path = output_dir / config["archive_name"]
if archive_path.exists():
archives[name] = archive_path
else:
print(f"⚠️ 未找到: {archive_path}")
# 上传到 HuggingFace
if not args.compress_only:
if not args.dry_run:
print("\n🔐 登录 HuggingFace...")
if args.token:
login(token=args.token)
else:
login()
api = HfApi()
else:
api = None
upload_datasets(api, archives, dry_run=args.dry_run)
print(f"\n{'='*60}")
print("✅ 操作完成!")
print("="*60)
if __name__ == "__main__":
main()