Files
2025-08-23 16:47:25 +08:00

98 lines
3.5 KiB
Python

import pickle
import numpy as np
from NormWear.pretrain_pipeline import dataset
import os
import tqdm
import torch
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed
def process_pkl_file(pkl_path):
"""处理单个 pkl 文件,生成并保存 CWT 特征"""
try:
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
torch.set_num_threads(1)
with open(pkl_path, 'rb') as f:
data_dict = pickle.load(f)
if 'cwt' in data_dict:
return (pkl_path, "skipped")
assert 'data' in data_dict, "缺少data字段"
assert data_dict['data'].ndim == 2, "数据应为二维数组"
raw_signal = torch.from_numpy(data_dict['data']).float()
cwt_output = dataset.cwt_wrap(raw_signal)
data_dict['cwt'] = cwt_output.numpy()
with open(pkl_path, 'wb') as f:
pickle.dump(data_dict, f, protocol=pickle.HIGHEST_PROTOCOL)
return (pkl_path, None)
except Exception as e:
return (pkl_path, str(e))
def process_pkl_chunk(chunk):
"""处理文件块,返回累积结果"""
return [process_pkl_file(pkl_path) for pkl_path in chunk]
def process_directory(input_dir, max_workers=None, chunk_size=100):
input_path = Path(input_dir)
pkl_files = list(input_path.rglob("*.pkl"))
if not pkl_files:
print(f"在目录 {input_dir} 中未找到.pkl文件")
return
print(f"找到 {len(pkl_files)} 个待处理文件 | 块大小: {chunk_size} | 并行进程数: {max_workers or '自动'}")
processed_count = 0
skipped_count = 0
error_files = []
# 分块处理
chunks = [pkl_files[i:i+chunk_size] for i in range(0, len(pkl_files), chunk_size)]
with ProcessPoolExecutor(max_workers=max_workers or os.cpu_count()//2) as executor:
futures = {executor.submit(process_pkl_chunk, chunk): chunk for chunk in chunks}
with tqdm.tqdm(total=len(pkl_files), desc="处理进度") as progress:
for future in as_completed(futures):
chunk = futures[future]
try:
chunk_results = future.result()
for (path, error) in chunk_results:
if error == "skipped":
skipped_count += 1
elif error is None:
processed_count += 1
else:
error_files.append((path, error))
progress.update(len(chunk_results))
except Exception as e:
for path in chunk:
error_files.append((path, f"Chunk处理异常: {str(e)}"))
progress.update(len(chunk))
# 统计输出
print(f"\n处理完成: {processed_count} 成功 | {skipped_count} 跳过 | {len(error_files)} 失败")
# 写入错误日志
if error_files:
error_log_path = input_path / "process_errors.log"
with open(error_log_path, "w") as f:
f.write("文件路径\t错误信息\n")
for path, err in error_files:
f.write(f"{path}\t{err}\n")
print(f"错误日志已保存至: {error_log_path}")
if __name__ == "__main__":
input_dir = r"data\pretrain\dalia"
process_directory(
input_dir,
max_workers=4,
chunk_size=100 # 根据实际情况调整块大小
)