File size: 5,158 Bytes
eba0a14 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | #!/usr/bin/env python3
"""
批量更新配置文件中的路径
=====================================================
使用方法:
python update_paths.py --dataset-root /new/dataset/path --checkpoint-root /new/checkpoint/path
=====================================================
"""
import os
import re
import argparse
from pathlib import Path
# 旧路径模式
OLD_PATTERNS = {
"dataset": [
r"/mnt/SSD8T/home/wjj/dataset",
],
"checkpoint": [
r"/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints",
r"/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs",
r"/mnt/SSD8T/home/wjj/code/DeCLIP/logs",
r"/mnt/SSD8T/home/wjj/code/DeCLIP/backup_bin/logs",
r"/mnt/SSD8T/home/wjj/code/my_CLIPSelf/logs",
r"/mnt/SSD8T/home/wjj/code/my_CLIPSelf/checkpoints",
],
"sam": [
r"/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts",
],
"hub": [
r"/mnt/SSD8T/home/wjj/.cache/torch/hub",
],
}
def update_file(filepath: Path, replacements: dict, dry_run: bool = False):
"""更新单个文件中的路径"""
try:
content = filepath.read_text(encoding='utf-8')
except Exception as e:
print(f" ⚠️ 无法读取文件: {e}")
return False
original_content = content
changes = []
for old_path, new_path in replacements.items():
if old_path in content:
content = content.replace(old_path, new_path)
changes.append((old_path, new_path))
if changes:
print(f"\n📝 {filepath}")
for old, new in changes:
print(f" {old}")
print(f" -> {new}")
if not dry_run and content != original_content:
try:
filepath.write_text(content, encoding='utf-8')
print(f" ✅ 已更新")
except Exception as e:
print(f" ❌ 写入失败: {e}")
return False
return True
def main():
parser = argparse.ArgumentParser(description="批量更新配置文件中的路径")
parser.add_argument("--dataset-root", type=str, required=True, help="新的数据集根路径")
parser.add_argument("--checkpoint-root", type=str, required=True, help="新的权重根路径")
parser.add_argument("--sam-root", type=str, help="SAM 权重路径 (默认: checkpoint-root/sam)")
parser.add_argument("--hub-root", type=str, help="torch.hub 缓存路径 (默认: ~/.cache/torch/hub)")
parser.add_argument("--config-dir", type=str, default="../configs", help="配置文件目录")
parser.add_argument("--dry-run", action="store_true", help="仅显示将要修改的内容,不实际修改")
args = parser.parse_args()
# 处理相对路径
script_dir = Path(__file__).parent
config_dir = (script_dir / args.config_dir).resolve()
if not config_dir.exists():
print(f"❌ 配置目录不存在: {config_dir}")
return
# 构建替换规则
dataset_root = Path(args.dataset_root).resolve()
checkpoint_root = Path(args.checkpoint_root).resolve()
sam_root = Path(args.sam_root).resolve() if args.sam_root else checkpoint_root / "sam"
hub_root = Path(args.hub_root).resolve() if args.hub_root else Path.home() / ".cache/torch/hub"
replacements = {}
# 数据集路径
for pattern in OLD_PATTERNS["dataset"]:
replacements[pattern] = str(dataset_root)
# 权重路径
for pattern in OLD_PATTERNS["checkpoint"]:
replacements[pattern] = str(checkpoint_root)
# SAM 路径
for pattern in OLD_PATTERNS["sam"]:
replacements[pattern] = str(sam_root)
# torch.hub 路径
for pattern in OLD_PATTERNS["hub"]:
replacements[pattern] = str(hub_root)
print("=" * 60)
print("🔧 批量更新配置文件路径")
print("=" * 60)
print(f"\n配置目录: {config_dir}")
print(f"数据集路径: {dataset_root}")
print(f"权重路径: {checkpoint_root}")
print(f"SAM 路径: {sam_root}")
print(f"Hub 缓存: {hub_root}")
if args.dry_run:
print("\n🔍 [DRY RUN] 仅显示将要修改的内容\n")
# 查找所有配置文件
config_files = list(config_dir.rglob("*.py"))
print(f"\n找到 {len(config_files)} 个配置文件")
# 更新每个文件
updated_count = 0
for filepath in config_files:
if update_file(filepath, replacements, dry_run=args.dry_run):
updated_count += 1
# 同时更新代码文件中的硬编码路径
code_files = [
script_dir.parent / "proxyclip_segmentor.py",
script_dir.parent / "tinyclip_proxy_segmentor.py",
]
print(f"\n检查代码文件中的硬编码路径...")
for filepath in code_files:
if filepath.exists():
update_file(filepath, replacements, dry_run=args.dry_run)
print("\n" + "=" * 60)
if args.dry_run:
print("🔍 [DRY RUN] 完成预览,未实际修改文件")
else:
print(f"✅ 路径更新完成!")
print("=" * 60)
if __name__ == "__main__":
main()
|