| |
| """ |
| 下载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) |
| 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'] |
| |
| |
| 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() |
|
|