File size: 4,495 Bytes
c988237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
获取MC-MED数据集所有需要下载的文件列表
1. 读取本地主RECORDS文件获取所有子目录
2. 下载每个子目录的RECORDS文件
3. 解析并生成完整的文件列表(包含.hea和.dat后缀)
"""

import os
import subprocess
import configparser
from pathlib import Path


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'),
        'main_records': config.get('settings', 'main_records')
    }


def download_sub_records(base_url, sub_dir, username, password, temp_dir='./temp_records'):
    """
    下载子目录的RECORDS文件
    sub_dir: 如 data/waveforms/000/
    返回: RECORDS文件内容的行列表,失败返回None
    """
    os.makedirs(temp_dir, exist_ok=True)
    
    # 构建URL: base_url/data/waveforms/000/RECORDS
    sub_dir = sub_dir.rstrip('/')
    records_url = f"{base_url}/{sub_dir}/RECORDS"
    
    # 本地保存路径
    local_path = os.path.join(temp_dir, sub_dir.replace('/', '_') + '_RECORDS')
    
    # 使用wget下载
    cmd = [
        'wget',
        '--user', username,
        '--password', password,
        '-q',  # 静默模式
        '-O', local_path,
        records_url
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        if result.returncode == 0 and os.path.exists(local_path):
            with open(local_path, 'r') as f:
                lines = [line.strip() for line in f if line.strip()]
            return lines
        else:
            print(f"  [警告] 下载失败: {records_url}")
            return None
    except subprocess.TimeoutExpired:
        print(f"  [警告] 下载超时: {records_url}")
        return None
    except Exception as e:
        print(f"  [错误] {e}")
        return None


def main():
    # 加载配置
    config = load_config()
    base_url = config['base_url']
    username = config['username']
    password = config['password']
    main_records_path = config['main_records']
    
    print("=" * 60)
    print("MC-MED 文件列表获取工具")
    print("=" * 60)
    
    # 读取主RECORDS文件
    if not os.path.exists(main_records_path):
        print(f"[错误] 主RECORDS文件不存在: {main_records_path}")
        return
    
    with open(main_records_path, 'r') as f:
        sub_dirs = [line.strip() for line in f if line.strip()]
    
    print(f"[信息] 共有 {len(sub_dirs)} 个子目录需要处理")
    
    # 存储所有文件URL
    all_files = []
    failed_dirs = []
    
    # 遍历每个子目录
    for i, sub_dir in enumerate(sub_dirs):
        print(f"[{i+1}/{len(sub_dirs)}] 处理: {sub_dir}")
        
        # 下载子目录的RECORDS
        entries = download_sub_records(base_url, sub_dir, username, password)
        
        if entries is None:
            failed_dirs.append(sub_dir)
            continue
        
        # 解析条目,生成完整文件路径
        # 条目格式如: 99013000/Pleth/99013000_1
        # 需要生成: data/waveforms/000/99013000/Pleth/99013000_1.hea
        #          data/waveforms/000/99013000/Pleth/99013000_1.dat
        sub_dir_clean = sub_dir.rstrip('/')
        for entry in entries:
            entry = entry.strip()
            if not entry:
                continue
            # 添加 .hea 和 .dat 后缀
            all_files.append(f"{sub_dir_clean}/{entry}.hea")
            all_files.append(f"{sub_dir_clean}/{entry}.dat")
    
    # 保存文件列表
    file_list_path = 'file_list.txt'
    with open(file_list_path, 'w') as f:
        for file_path in all_files:
            f.write(file_path + '\n')
    
    print("=" * 60)
    print(f"[完成] 共获取 {len(all_files)} 个文件")
    print(f"[完成] 文件列表已保存到: {file_list_path}")
    
    # 保存失败的目录列表
    if failed_dirs:
        failed_path = 'failed_dirs.txt'
        with open(failed_path, 'w') as f:
            for d in failed_dirs:
                f.write(d + '\n')
        print(f"[警告] {len(failed_dirs)} 个目录获取失败,已保存到: {failed_path}")
    
    print("=" * 60)


if __name__ == '__main__':
    main()