ama_data / download_files.py
wangrongsheng's picture
Add files using upload-large-folder tool
c988237 verified
#!/usr/bin/env python3
"""
下载MC-MED数据集所有文件
1. 读取file_list.txt中的文件列表
2. 并行下载每个文件,支持断点续传
3. 记录下载失败的文件以便重试
"""
# ============== 可修改参数 ==============
NUM_WORKERS = 8 # 并行下载线程数
# ========================================
import os
import subprocess
import configparser
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
# 线程安全的锁
completed_lock = threading.Lock()
failed_lock = threading.Lock()
progress_lock = threading.Lock()
# 全局计数器
progress_counter = {'done': 0, 'total': 0, 'start_time': 0}
def format_time(seconds):
"""格式化时间为可读字符串"""
if seconds < 60:
return f"{seconds:.0f}秒"
elif seconds < 3600:
minutes = seconds // 60
secs = seconds % 60
return f"{minutes:.0f}{secs:.0f}秒"
else:
hours = seconds // 3600
minutes = (seconds % 3600) // 60
return f"{hours:.0f}{minutes:.0f}分"
def load_config(config_path='config.ini'):
"""加载配置文件"""
config = configparser.ConfigParser()
config.read(config_path)
return {
'username': config.get('credentials', 'username'),
'password': config.get('credentials', 'password'),
'base_url': config.get('settings', 'base_url').rstrip('/'),
'output_dir': config.get('settings', 'output_dir')
}
def download_file(url, output_path, username, password):
"""
下载单个文件
返回: True成功, False失败
"""
# 确保目录存在
os.makedirs(os.path.dirname(output_path), exist_ok=True)
cmd = [
'wget',
'--user', username,
'--password', password,
'-c', # 断点续传
'-q', # 静默模式
'-O', output_path,
url
]
try:
result = subprocess.run(cmd, timeout=300, capture_output=True) # 5分钟超时
return result.returncode == 0
except subprocess.TimeoutExpired:
return False
except Exception as e:
return False
def download_task(file_path, base_url, output_dir, username, password):
"""
单个下载任务,供线程池调用
返回: (file_path, success)
"""
url = f"{base_url}/{file_path}"
output_path = os.path.join(output_dir, file_path)
success = download_file(url, output_path, username, password)
# 更新进度
with progress_lock:
progress_counter['done'] += 1
done = progress_counter['done']
total = progress_counter['total']
start_time = progress_counter['start_time']
# 每100个文件或完成时打印进度
if done % 100 == 0 or done == total:
elapsed = time.time() - start_time
speed = done / elapsed if elapsed > 0 else 0
remaining = total - done
eta = remaining / speed if speed > 0 else 0
percent = done * 100 // total
speed_str = f"{speed:.1f} 文件/秒"
eta_str = format_time(eta)
elapsed_str = format_time(elapsed)
print(f"[进度] {done}/{total} ({percent}%) | 速度: {speed_str} | 已用: {elapsed_str} | 剩余: {eta_str}")
return (file_path, success)
def load_file_list(file_list_path='file_list.txt'):
"""加载文件列表"""
if not os.path.exists(file_list_path):
return []
with open(file_list_path, 'r') as f:
return [line.strip() for line in f if line.strip()]
def load_completed(completed_path='completed.txt'):
"""加载已完成的文件列表"""
if not os.path.exists(completed_path):
return set()
with open(completed_path, 'r') as f:
return set(line.strip() for line in f if line.strip())
def main():
# 加载配置
config = load_config()
base_url = config['base_url']
username = config['username']
password = config['password']
output_dir = config['output_dir']
print("=" * 60)
print("MC-MED 数据下载工具 (并行版)")
print("=" * 60)
# 加载文件列表
print("[信息] 正在加载文件列表...")
file_list = load_file_list()
if not file_list:
print("[错误] file_list.txt 不存在或为空,请先运行 get_file_list.py")
return
# 加载已完成列表(用于断点续传)
print("[信息] 正在加载已完成列表...")
completed = load_completed()
# 过滤掉已完成的
pending = [f for f in file_list if f not in completed]
print(f"[信息] 总文件数: {len(file_list)}")
print(f"[信息] 已完成: {len(completed)}")
print(f"[信息] 待下载: {len(pending)}")
print(f"[信息] 并行线程数: {NUM_WORKERS}")
print(f"[信息] 输出目录: {output_dir}")
print("=" * 60)
if not pending:
print("[完成] 所有文件已下载完成!")
return
# 记录结果
completed_files = []
failed_files = []
start_time = time.time()
# 设置进度计数器
progress_counter['total'] = len(pending)
progress_counter['done'] = 0
progress_counter['start_time'] = start_time
# 使用线程池并行下载
print(f"[开始] 启动 {NUM_WORKERS} 个下载线程...")
with ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor:
# 提交所有任务
futures = {
executor.submit(download_task, file_path, base_url, output_dir, username, password): file_path
for file_path in pending
}
# 处理完成的任务
for future in as_completed(futures):
file_path, success = future.result()
if success:
completed_files.append(file_path)
# 立即记录完成(线程安全)
with completed_lock:
with open('completed.txt', 'a') as f:
f.write(file_path + '\n')
else:
failed_files.append(file_path)
elapsed_time = time.time() - start_time
print("=" * 60)
print(f"[完成] 本次下载完成")
print(f"[完成] 耗时: {elapsed_time:.1f} 秒")
print(f"[完成] 成功: {len(completed_files)}")
print(f"[完成] 失败: {len(failed_files)}")
if len(completed_files) > 0:
avg_speed = len(completed_files) / elapsed_time
print(f"[完成] 平均速度: {avg_speed:.1f} 文件/秒")
# 保存失败列表
if failed_files:
with open('failed_files.txt', 'w') as f:
for file_path in failed_files:
f.write(file_path + '\n')
print(f"[信息] 失败列表已保存到: failed_files.txt")
print("[提示] 重新运行此脚本可自动重试未完成的文件")
print("=" * 60)
if __name__ == '__main__':
main()