Download data/pack_aia_2014_2016.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 7.5 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/data/pack_aia_2014_2016.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/data/pack_aia_2014_2016.py
-
curl -L -o pack_aia_2014_2016.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/data/pack_aia_2014_2016.py
7.5 kB
| import argparse | |
| def _parse_args(): | |
| parser = argparse.ArgumentParser(description='Pack original FITS images to HDF5 using the published experiment preprocessing.') | |
| parser.add_argument('--input-dir', required=True, help='Directory containing original FITS files (nonrecursive).') | |
| parser.add_argument('--output', required=True, help='Output HDF5 path.') | |
| parser.add_argument('--log-file', default=None, help='Optional log path; otherwise log to the console only.') | |
| parser.add_argument('--resume', action='store_true', help='Append using the original 2014-2016 AIA resume logic.') | |
| parser.add_argument('--overwrite', action='store_true', help='Explicitly allow replacement for non-resumable packers.') | |
| return parser.parse_args() | |
| if __name__ == '__main__': | |
| _args = _parse_args() | |
| import os | |
| import glob | |
| import h5py | |
| import numpy as np | |
| import cv2 | |
| from datetime import datetime | |
| from tqdm import tqdm | |
| import logging | |
| import warnings | |
| import gc | |
| import multiprocessing | |
| from astropy.utils.iers import conf | |
| conf.auto_download = False | |
| warnings.filterwarnings('ignore') | |
| BASE_DIR = None | |
| OUTPUT_H5 = None | |
| TARGET_SIZE = (512, 512) | |
| CHANNELS = ['94', '193', '304'] | |
| LOG_FILE = None | |
| def get_time_from_filename(fname): | |
| try: | |
| time_str = os.path.basename(fname).split('.')[2] | |
| return datetime.strptime(time_str, '%Y-%m-%dT%H%M%SZ') | |
| except: | |
| return None | |
| def read_single_fits(file_path, target_size, return_dict): | |
| try: | |
| import sunpy.map | |
| smap = sunpy.map.Map(file_path, memmap=False) | |
| img = np.nan_to_num(smap.data, nan=0.0, posinf=0.0, neginf=0.0) | |
| img_resized = cv2.resize(img, (target_size[1], target_size[0]), interpolation=cv2.INTER_AREA) | |
| return_dict['data'] = img_resized.astype(np.float32) | |
| except Exception as e: | |
| return_dict['error'] = str(e) | |
| def pack_data(): | |
| logging.info(f'🚀 开始扫描 {BASE_DIR} 中的 FITS 文件...') | |
| all_fits = glob.glob(os.path.join(BASE_DIR, '*.fits')) | |
| data_groups = {} | |
| for f in all_fits: | |
| wave = os.path.basename(f).split('.')[3] | |
| if wave in CHANNELS: | |
| dt = get_time_from_filename(f) | |
| if dt: | |
| hour_key = dt.replace(minute=0, second=0) | |
| if hour_key not in data_groups: | |
| data_groups[hour_key] = {} | |
| data_groups[hour_key][wave] = f | |
| valid_hours = sorted([h for (h, waves) in data_groups.items() if len(waves) == len(CHANNELS)]) | |
| logging.info(f'✅ 扫描完成!共发现 {len(valid_hours)} 个完整的跨模态样本组。') | |
| with h5py.File(OUTPUT_H5, 'a') as h5f: | |
| if 'images' not in h5f: | |
| dataset = h5f.create_dataset('images', shape=(0, 3, *TARGET_SIZE), maxshape=(None, 3, *TARGET_SIZE), dtype=np.float32, chunks=(1, 3, *TARGET_SIZE), compression='gzip') | |
| times_db = h5f.create_dataset('times', shape=(0,), maxshape=(None,), dtype='S20') | |
| existing_times = set() | |
| logging.info('🆕 创建新的 HDF5 数据集结构...') | |
| else: | |
| dataset = h5f['images'] | |
| times_db = h5f['times'] | |
| existing_times = set([t.decode('ascii') for t in times_db[:]]) | |
| logging.info(f'📂 发现已有数据集,当前已包含 {len(existing_times)} 个样本。') | |
| remaining_hours = [h for h in valid_hours if h.isoformat() not in existing_times] | |
| if not remaining_hours: | |
| logging.info('🎉 所有数据此前已全部打包完成!') | |
| return | |
| logging.info(f'🔄 剩余 {len(remaining_hours)} 个样本待处理。') | |
| start_idx = dataset.shape[0] | |
| total_to_add = len(remaining_hours) | |
| logging.info('⏳ 正在预分配 HDF5 存储空间,请稍候...') | |
| dataset.resize((start_idx + total_to_add, 3, *TARGET_SIZE)) | |
| times_db.resize((start_idx + total_to_add,)) | |
| success_count = 0 | |
| pbar = tqdm(remaining_hours, desc='打包进度', dynamic_ncols=True) | |
| for (i, hour) in enumerate(pbar): | |
| if i > 0 and i % 100 == 0: | |
| logging.info(f'当前进度: {i}/{len(remaining_hours)} - 正在处理: {hour.isoformat()}') | |
| success = True | |
| temp_img_array = np.zeros((3, *TARGET_SIZE), dtype=np.float32) | |
| for (c_idx, wave) in enumerate(CHANNELS): | |
| file_path = data_groups[hour][wave] | |
| if os.path.getsize(file_path) < 102400: | |
| logging.error(f'🗑️ 文件过小疑似损坏,跳过: {file_path}') | |
| success = False | |
| break | |
| manager = multiprocessing.Manager() | |
| return_dict = manager.dict() | |
| p = multiprocessing.Process(target=read_single_fits, args=(file_path, TARGET_SIZE, return_dict)) | |
| p.start() | |
| p.join(timeout=15) | |
| if p.is_alive(): | |
| p.terminate() | |
| p.join() | |
| logging.error(f'💀 捕捉到底层死锁!已强制猎杀并跳过文件: {file_path}') | |
| success = False | |
| break | |
| if 'error' in return_dict: | |
| logging.error(f"⚠️ 读取 {wave} 失败 ({hour.isoformat()}): {return_dict['error']}") | |
| success = False | |
| break | |
| elif 'data' in return_dict: | |
| temp_img_array[c_idx, :, :] = return_dict['data'] | |
| else: | |
| logging.error(f'⚠️ 子进程未知崩溃 ({hour.isoformat()} - {wave})') | |
| success = False | |
| break | |
| if success: | |
| current_write_idx = start_idx + success_count | |
| dataset[current_write_idx, :, :, :] = temp_img_array | |
| times_db[current_write_idx] = hour.isoformat().encode('ascii') | |
| success_count += 1 | |
| if i % 50 == 0: | |
| gc.collect() | |
| final_len = start_idx + success_count | |
| if final_len < dataset.shape[0]: | |
| logging.info(f'✂️ 剔除了 {dataset.shape[0] - final_len} 个损坏或读取失败的样本空间。') | |
| dataset.resize((final_len, 3, *TARGET_SIZE)) | |
| times_db.resize((final_len,)) | |
| h5f.flush() | |
| logging.info(f'🎉 任务结束!实际新增成功样本: {success_count} 个。文件已更新至:{OUTPUT_H5}') | |
| if __name__ == '__main__': | |
| from pathlib import Path | |
| _input = Path(_args.input_dir).expanduser().resolve() | |
| _output = Path(_args.output).expanduser().resolve() | |
| if not _input.is_dir(): | |
| raise SystemExit('Input FITS directory does not exist: ' + str(_input)) | |
| if _args.resume and _args.overwrite: | |
| raise SystemExit('Use either --resume or --overwrite, not both.') | |
| if _args.overwrite: | |
| raise SystemExit('This packer appends; use a new output file or --resume.') | |
| if _output.exists() and (not _args.resume): | |
| raise SystemExit('Output exists; specify --resume to append.') | |
| BASE_DIR = str(_input) | |
| OUTPUT_H5 = str(_output) | |
| LOG_FILE = _args.log_file | |
| _output.parent.mkdir(parents=True, exist_ok=True) | |
| _handlers = [logging.StreamHandler()] | |
| if LOG_FILE: | |
| _log = Path(LOG_FILE).expanduser().resolve() | |
| _log.parent.mkdir(parents=True, exist_ok=True) | |
| _handlers.append(logging.FileHandler(_log)) | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=_handlers) | |
| pack_data() | |