perf(integration): 为大数据文件处理添加流式处理以降低内存占用
- 新增流式转换函数 convert_txt_to_csv_streaming,将大 TXT 文件分块转换为临时 CSV - 新增流式滤波函数 apply_filter_csv_streaming,对 CSV 文件进行分块滤波处理 - 在处理 TXT 和 CSV 文件的主逻辑中集成流式处理,替代一次性加载 - 添加环境变量配置 CHUNKSIZE_CSV_FILTER 和 CHUNKSIZE_TXT_CONVERT 控制块大小 - 在处理完成后自动清理临时文件并显式调用垃圾回收
This commit is contained in:
1 parent
3b39dd7b9a
commit
1dfd138260
1 file changed
+197
-20
+197
-20
@@ -177,6 +177,8 @@ def run_filter_in_background(app, folder_ids, filter_type='bandpass_0.5_40'):
|
||||
processed_count = 0 # 计数
|
||||
|
||||
# 4. 处理 TXT 文件(转换为 CSV 并滤波)
|
||||
# 注意:由于 TXT 处理需要同步 PPG/ACC 数据,暂时保持原有逻辑
|
||||
# 对于超大 TXT 文件,建议先手动转换为 CSV 后再进行滤波处理
|
||||
for txt_path in txt_files:
|
||||
filename = os.path.basename(txt_path)
|
||||
base_name = os.path.splitext(filename)[0]
|
||||
@@ -188,8 +190,27 @@ def run_filter_in_background(app, folder_ids, filter_type='bandpass_0.5_40'):
|
||||
synced_segments = None
|
||||
|
||||
try:
|
||||
# 读取 TXT
|
||||
df = pd.read_csv(txt_path, sep='\t', on_bad_lines='warn', engine='c')
|
||||
# 读取 TXT(使用流式转换先转为 CSV 中间文件)
|
||||
# 对于大文件,这里可以先转换为临时 CSV,然后再处理
|
||||
csv_temp_path = os.path.join(processed_folder_path, f"{base_name}_temp.csv")
|
||||
|
||||
# 使用流式转换
|
||||
total_rows = convert_txt_to_csv_streaming(
|
||||
txt_path,
|
||||
csv_temp_path,
|
||||
chunksize=CHUNKSIZE_TXT_CONVERT
|
||||
)
|
||||
|
||||
if total_rows == 0:
|
||||
logger.warning(f"TXT conversion produced no output for {filename}")
|
||||
continue
|
||||
|
||||
logger.info(f"Converted TXT to CSV: {filename} ({total_rows} rows)")
|
||||
|
||||
# 现在从转换后的 CSV 读取(仍需要一次性加载以进行同步处理)
|
||||
# 注意:这里是瓶颈,大文件仍会占用较多内存
|
||||
# 未来优化:可以实现流式同步处理
|
||||
df = pd.read_csv(csv_temp_path)
|
||||
|
||||
# 分离 PPG 和 ACC 数据
|
||||
ppg_cols = [c for c in df.columns if c.startswith('PPG')]
|
||||
@@ -266,6 +287,13 @@ def run_filter_in_background(app, folder_ids, filter_type='bandpass_0.5_40'):
|
||||
del acc_df
|
||||
if synced_segments is not None:
|
||||
del synced_segments
|
||||
# 清理临时 CSV 文件
|
||||
if 'csv_temp_path' in locals() and os.path.exists(csv_temp_path):
|
||||
try:
|
||||
os.remove(csv_temp_path)
|
||||
logger.debug(f"Cleaned up temp CSV: {csv_temp_path}")
|
||||
except Exception as cleanup_err:
|
||||
logger.warning(f"Failed to clean up temp CSV {csv_temp_path}: {cleanup_err}")
|
||||
gc.collect()
|
||||
|
||||
# 5. 处理已有 CSV 文件(直接滤波)
|
||||
@@ -273,25 +301,30 @@ def run_filter_in_background(app, folder_ids, filter_type='bandpass_0.5_40'):
|
||||
filename = os.path.basename(csv_path)
|
||||
output_filename = filename.replace('.csv', '_filtered.csv')
|
||||
|
||||
df = None
|
||||
df_filtered = None
|
||||
|
||||
try:
|
||||
df = pd.read_csv(csv_path)
|
||||
|
||||
if 'PPG' not in df.columns:
|
||||
del df
|
||||
# 检查是否有 PPG 列
|
||||
test_chunk = pd.read_csv(csv_path, nrows=1)
|
||||
if 'PPG' not in test_chunk.columns:
|
||||
del test_chunk
|
||||
gc.collect()
|
||||
continue
|
||||
del test_chunk
|
||||
|
||||
# 应用滤波
|
||||
df_filtered = apply_filter(df, filter_params, INVERT_SIGNAL_FLAG)
|
||||
|
||||
# 保存到 processed_data_output 文件夹
|
||||
# 应用滤波(使用流式处理)
|
||||
output_path = os.path.join(processed_folder_path, output_filename)
|
||||
df_filtered.to_csv(output_path, index=False)
|
||||
total_rows, chunks = apply_filter_csv_streaming(
|
||||
csv_path,
|
||||
output_path,
|
||||
filter_params,
|
||||
invert_signal=INVERT_SIGNAL_FLAG,
|
||||
chunksize=CHUNKSIZE_CSV_FILTER
|
||||
)
|
||||
|
||||
# 记录成功保存的文件信息(暂不写入数据库)
|
||||
if total_rows == 0:
|
||||
logger.warning(f"Filtering produced no output for {filename}")
|
||||
continue
|
||||
|
||||
# 记录成功保存的文件信息
|
||||
uid = os.path.splitext(filename)[0]
|
||||
processed_files.append({
|
||||
'uid': uid,
|
||||
@@ -300,17 +333,14 @@ def run_filter_in_background(app, folder_ids, filter_type='bandpass_0.5_40'):
|
||||
'fs': FILTERING_SAMPLING_RATE,
|
||||
'inverted': INVERT_SIGNAL_FLAG
|
||||
})
|
||||
processed_count += 1
|
||||
processed_count += total_rows
|
||||
logger.info(f"Filtered {filename}: {total_rows} rows in {chunks} chunks")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Filter failed for {filename}: {e}")
|
||||
continue
|
||||
finally:
|
||||
# 确保清理每个文件的临时变量
|
||||
if df is not None:
|
||||
del df
|
||||
if df_filtered is not None:
|
||||
del df_filtered
|
||||
gc.collect()
|
||||
|
||||
# === 第二阶段:验证文件保存成功后再写入数据库 ===
|
||||
@@ -3422,3 +3452,150 @@ def cancel_zip_task(task_id):
|
||||
db.session.commit()
|
||||
|
||||
return success(msg=f'Task {task_id} cancelled')
|
||||
|
||||
|
||||
# ========== 流式处理辅助函数 ==========
|
||||
# 从环境变量读取配置
|
||||
CHUNKSIZE_CSV_FILTER = int(os.environ.get('CHUNKSIZE_CSV_FILTER', '50000'))
|
||||
CHUNKSIZE_TXT_CONVERT = int(os.environ.get('CHUNKSIZE_TXT_CONVERT', '100000'))
|
||||
|
||||
|
||||
def apply_filter_csv_streaming(
|
||||
input_path: str,
|
||||
output_path: str,
|
||||
filter_params: dict,
|
||||
invert_signal: bool = False,
|
||||
chunksize: int = None
|
||||
) -> tuple:
|
||||
"""
|
||||
流式处理 CSV 文件滤波,降低内存占用
|
||||
|
||||
Args:
|
||||
input_path: 输入 CSV 文件路径
|
||||
output_path: 输出 CSV 文件路径
|
||||
filter_params: 滤波器参数
|
||||
invert_signal: 是否反转信号
|
||||
chunksize: 每次处理的行数(默认使用配置值)
|
||||
|
||||
Returns:
|
||||
(total_rows, chunks_processed) 成功处理的行数和块数,失败返回 (0, 0)
|
||||
"""
|
||||
if chunksize is None:
|
||||
chunksize = CHUNKSIZE_CSV_FILTER
|
||||
|
||||
first_chunk = True
|
||||
total_rows = 0
|
||||
chunks_processed = 0
|
||||
|
||||
try:
|
||||
# 使用 chunksize 分块读取
|
||||
for chunk in pd.read_csv(input_path, chunksize=chunksize):
|
||||
# 检查是否有 PPG 列
|
||||
if 'PPG' not in chunk.columns:
|
||||
logger.warning(f"No PPG column found in chunk, skipping {input_path}")
|
||||
return (0, 0)
|
||||
|
||||
# 对当前块应用滤波
|
||||
chunk_filtered = chunk.copy()
|
||||
ppg_data = chunk['PPG'].values.astype(float)
|
||||
|
||||
# 应用滤波器(使用与原来相同的逻辑)
|
||||
from ..services.signal_processing.filters import apply_filter_to_dataframe
|
||||
chunk_filtered = apply_filter_to_dataframe(
|
||||
chunk_filtered,
|
||||
column='PPG',
|
||||
filter_params=filter_params,
|
||||
fs=100,
|
||||
output_column='PPG_Filtered'
|
||||
)
|
||||
|
||||
# 如果需要反转信号
|
||||
if invert_signal:
|
||||
chunk_filtered['PPG_Filtered'] = -chunk_filtered['PPG_Filtered']
|
||||
|
||||
# 写入文件(追加模式)
|
||||
chunk_filtered.to_csv(
|
||||
output_path,
|
||||
mode='a' if not first_chunk else 'w',
|
||||
index=False,
|
||||
header=first_chunk
|
||||
)
|
||||
|
||||
first_chunk = False
|
||||
total_rows += len(chunk_filtered)
|
||||
chunks_processed += 1
|
||||
|
||||
# 显式清理内存
|
||||
del chunk_filtered
|
||||
del chunk
|
||||
gc.collect()
|
||||
|
||||
if chunks_processed % 10 == 0:
|
||||
logger.info(f"Processed chunk {chunks_processed}, total rows: {total_rows}")
|
||||
|
||||
logger.info(f"Streaming filter completed: {total_rows} rows in {chunks_processed} chunks")
|
||||
return (total_rows, chunks_processed)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Streaming filter failed for {input_path}: {e}")
|
||||
# 清理部分写入的文件
|
||||
if os.path.exists(output_path):
|
||||
try:
|
||||
os.remove(output_path)
|
||||
except:
|
||||
pass
|
||||
return (0, 0)
|
||||
|
||||
|
||||
def convert_txt_to_csv_streaming(
|
||||
txt_path: str,
|
||||
csv_path: str,
|
||||
chunksize: int = None,
|
||||
sep: str = '\t'
|
||||
) -> int:
|
||||
"""
|
||||
流式转换 TXT 到 CSV,降低内存占用
|
||||
|
||||
Args:
|
||||
txt_path: 输入 TXT 文件路径
|
||||
csv_path: 输出 CSV 文件路径
|
||||
chunksize: 每次处理的行数(默认使用配置值)
|
||||
sep: TXT 文件分隔符
|
||||
|
||||
Returns:
|
||||
成功处理的总行数,失败返回 0
|
||||
"""
|
||||
if chunksize is None:
|
||||
chunksize = CHUNKSIZE_TXT_CONVERT
|
||||
|
||||
first_chunk = True
|
||||
total_rows = 0
|
||||
|
||||
try:
|
||||
for chunk in pd.read_csv(txt_path, sep=sep, chunksize=chunksize,
|
||||
on_bad_lines='warn', engine='c'):
|
||||
chunk.to_csv(
|
||||
csv_path,
|
||||
mode='a' if not first_chunk else 'w',
|
||||
index=False,
|
||||
header=first_chunk
|
||||
)
|
||||
|
||||
first_chunk = False
|
||||
total_rows += len(chunk)
|
||||
|
||||
del chunk
|
||||
gc.collect()
|
||||
|
||||
logger.info(f"TXT to CSV conversion completed: {total_rows} rows")
|
||||
return total_rows
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"TXT to CSV conversion failed for {txt_path}: {e}")
|
||||
# 清理部分写入的文件
|
||||
if os.path.exists(csv_path):
|
||||
try:
|
||||
os.remove(csv_path)
|
||||
except:
|
||||
pass
|
||||
return 0
|
||||
Reference in new issue
Block a user