步骤五页面修改

This commit is contained in:
DXC
2026-06-26 13:54:09 +08:00
parent 7293ddd5ee
commit 5fb2db4a07

View File

@ -1,14 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Step4 面板 - 数据预处理
Step5 面板 - 数据清洗 (完美对齐无跳动重构版)
"""
import os
import sys
from pathlib import Path
# 路径归一化 helper(与 pipeline.get_step_output_dir 互为表里)
# 路径归一化 helper
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
@ -17,7 +17,7 @@ from _step_path_resolver import resolve_subdir
import pandas as pd
from PyQt5.QtWidgets import (
QWidget, QVBoxLayout, QGroupBox, QHBoxLayout, QLabel,
QSpinBox, QPushButton, QCheckBox, QTableView,
QSpinBox, QPushButton, QTableView, QSizePolicy,
QAbstractItemView, QHeaderView, QMessageBox,
)
from PyQt5.QtCore import Qt
@ -28,37 +28,77 @@ from src.gui.styles import ModernStylesheet
class Step5CleanPanel(QWidget):
"""步骤5:数据清洗"""
def __init__(self, parent=None):
super().__init__(parent)
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
# 1. 注入全局样式系统
self.setStyleSheet(ModernStylesheet.get_main_stylesheet())
# 标题
# 主布局:增加四周留白(24px)和模块间的呼吸间距(20px)
main_layout = QVBoxLayout()
main_layout.setContentsMargins(24, 24, 24, 24)
main_layout.setSpacing(20)
# ==========================================
# 卡片 1:输入数据
# ==========================================
input_group = QGroupBox("📁 输入数据")
input_layout = QVBoxLayout()
input_layout.setSpacing(16)
input_layout.setContentsMargins(20, 24, 20, 20)
step5_hint = QLabel("💡 提示: 选择包含水质参数或光谱特征的 CSV 文件,我们将对其进行异常值剔除和清洗。")
step5_hint.setWordWrap(True)
step5_hint.setStyleSheet(f"""
QLabel {{
color: {ModernStylesheet.COLORS['primary']};
background-color: {ModernStylesheet.COLORS['selected']};
border: 1px solid {ModernStylesheet.COLORS['border_light']};
border-radius: 6px;
padding: 10px 14px;
margin-bottom: 4px;
}}
""")
input_layout.addWidget(step5_hint)
# CSV文件
self.csv_file = FileSelectWidget(
"水质参数文件:",
"输入 CSV 文件:",
"CSV Files (*.csv);;All Files (*.*)"
)
layout.addWidget(self.csv_file)
self.csv_file.label.setMinimumWidth(100) # 绝对对齐
input_layout.addWidget(self.csv_file)
hint = QLabel("提示: 处理CSV文件,筛选剔除异常值")
hint.setStyleSheet("color: #666; font-size: 10px;")
layout.addWidget(hint)
input_group.setLayout(input_layout)
main_layout.addWidget(input_group)
preview_group = QGroupBox("CSV数据预览")
# ==========================================
# 卡片 2:数据预览
# ==========================================
preview_group = QGroupBox("🔍 数据预览")
preview_layout = QVBoxLayout()
preview_layout.setSpacing(16)
preview_layout.setContentsMargins(20, 24, 20, 20)
controls_layout = QHBoxLayout()
controls_layout.addWidget(QLabel("预览行数:"))
controls_layout.setContentsMargins(0, 0, 0, 0)
self.preview_rows_spin = QSpinBox()
self.preview_rows_spin.setRange(1, 200)
self.preview_rows_spin.setValue(10)
controls_layout.addWidget(self.preview_rows_spin)
self.preview_rows_spin.setSuffix(" 行")
self.preview_rows_spin.setButtonSymbols(QSpinBox.NoButtons)
self.preview_rows_spin.setMinimumWidth(80)
self.preview_btn = QPushButton("刷新预览")
self.preview_btn.setStyleSheet(ModernStylesheet.get_button_stylesheet('normal'))
self.preview_btn.setMinimumWidth(100)
self.preview_btn.clicked.connect(self.load_csv_preview)
# 使用封装的方法实现严格对齐的行
self._add_row_with_fixed_label(controls_layout, "加载预览行数:", self.preview_rows_spin)
controls_layout.addWidget(self.preview_btn)
controls_layout.addStretch()
@ -68,40 +108,61 @@ class Step5CleanPanel(QWidget):
self.preview_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.preview_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.preview_table.verticalHeader().setVisible(False)
self.preview_table.setMinimumHeight(200)
self.preview_table.setMinimumHeight(220)
self.preview_status_label = QLabel("请选择CSV文件并点击刷新预览")
self.preview_status_label.setStyleSheet("color: #666; font-size: 11px;")
self.preview_status_label = QLabel("等待加载数据...")
self.preview_status_label.setStyleSheet(f"color: {ModernStylesheet.COLORS['text_secondary']}; font-size: 12px;")
preview_layout.addLayout(controls_layout)
preview_layout.addWidget(self.preview_table)
preview_layout.addWidget(self.preview_status_label)
preview_group.setLayout(preview_layout)
layout.addWidget(preview_group)
main_layout.addWidget(preview_group)
# ==========================================
# 卡片 3:输出与执行
# ==========================================
output_group = QGroupBox("🚀 输出与执行")
output_layout = QVBoxLayout()
output_layout.setSpacing(16)
output_layout.setContentsMargins(20, 24, 20, 20)
# 输出文件路径
self.output_file = FileSelectWidget(
"输出处理后CSV:",
"CSV Files (*.csv);;All Files (*.*)"
"结果保存至:",
"CSV Files (*.csv);;All Files (*.*)",
mode="save"
)
self.output_file.label.setMinimumWidth(100)
self.output_file.line_edit.setPlaceholderText("processed_data.csv")
layout.addWidget(self.output_file)
output_layout.addWidget(self.output_file)
# 启用步骤
self.enable_checkbox = QCheckBox("启用此步骤")
self.enable_checkbox.setChecked(True)
layout.addWidget(self.enable_checkbox)
action_layout = QHBoxLayout()
action_layout.addStretch()
# 独立运行按钮
self.run_btn = QPushButton("独立运行此步骤")
self.run_btn.setStyleSheet(ModernStylesheet.get_button_stylesheet('success'))
self.run_btn = QPushButton("独立运行步骤")
self.run_btn.setStyleSheet(ModernStylesheet.get_button_stylesheet('primary'))
self.run_btn.setMinimumWidth(140)
self.run_btn.clicked.connect(self._on_run_single_clicked)
layout.addWidget(self.run_btn)
action_layout.addWidget(self.run_btn)
output_layout.addLayout(action_layout)
output_group.setLayout(output_layout)
main_layout.addWidget(output_group)
main_layout.addStretch()
self.setLayout(main_layout)
layout.addStretch()
self.setLayout(layout)
self.reset_preview()
def _add_row_with_fixed_label(self, layout, label_text, widget):
"""辅助方法:创建绝对锁死宽度的对齐行"""
lbl = QLabel(label_text)
lbl.setMinimumWidth(100)
layout.addWidget(lbl)
if hasattr(widget, 'setSizePolicy'):
widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
layout.addWidget(widget)
def get_config(self):
"""获取配置"""
config = {
@ -121,12 +182,7 @@ class Step5CleanPanel(QWidget):
self.output_file.set_path(config['output_path'])
def update_from_config(self, work_dir=None, pipeline=None):
"""从全局配置自动填充输出路径
Args:
work_dir: 工作目录路径
pipeline: Pipeline 实例(未使用,保留接口兼容性)
"""
"""从全局配置自动填充输出路径"""
if work_dir:
self.work_dir = work_dir
elif hasattr(self, 'work_dir') and self.work_dir:
@ -143,12 +199,12 @@ class Step5CleanPanel(QWidget):
self.output_file.set_path("")
def _on_run_single_clicked(self):
"""通过 EventBus 发布单步执行请求(解耦面板与 PipelineExecutor)。"""
"""通过 EventBus 发布单步执行请求"""
from src.gui.core.event_bus import global_event_bus
csv_path = self.csv_file.get_path()
if not csv_path:
QMessageBox.warning(self, "输入错误", "请选择水质参数文件!")
QMessageBox.warning(self, "输入错误", "请选择需要清洗的 CSV 数据文件!")
return
config = {'step5_clean': self.get_config()}
@ -157,41 +213,45 @@ class Step5CleanPanel(QWidget):
'config': config,
})
def run_step(self):
"""独立运行步骤5(旧版 parent 链上溯方式,保留兼容)。"""
csv_path = self.csv_file.get_path()
if not csv_path:
QMessageBox.warning(self, "输入错误", "请选择水质参数文件!")
return
main_window = self.window()
if hasattr(main_window, 'run_single_step'):
config = {'step5_clean': self.get_config()}
main_window.run_single_step('step5_clean', config)
def reset_preview(self, message="请选择CSV文件并点击刷新预览"):
def reset_preview(self, message="请选择 CSV 文件并点击刷新预览"):
"""重置预览表格"""
from src.gui.water_quality_gui import PandasTableModel
empty_model = PandasTableModel(pd.DataFrame())
self.preview_table.setModel(empty_model)
self.preview_status_label.setText(message)
try:
from src.gui.water_quality_gui import PandasTableModel
empty_model = PandasTableModel(pd.DataFrame())
self.preview_table.setModel(empty_model)
self.preview_status_label.setText(message)
except ImportError:
# 兼容水质软件 V2 版的重构包结构
try:
from src.new.main_view import PandasTableModel
empty_model = PandasTableModel(pd.DataFrame())
self.preview_table.setModel(empty_model)
self.preview_status_label.setText(message)
except ImportError:
self.preview_status_label.setText("数据预览模块加载失败,请检查 PandasTableModel 依赖")
def load_csv_preview(self):
"""加载CSV预览数据"""
from src.gui.water_quality_gui import PandasTableModel
"""加载 CSV 预览数据"""
csv_path = self.csv_file.get_path()
if not csv_path:
self.reset_preview("请先选择CSV文件")
self.reset_preview("请先选择 CSV 文件")
return
if not os.path.exists(csv_path):
self.reset_preview("文件不存在,请检查路径")
return
try:
from src.gui.water_quality_gui import PandasTableModel
except ImportError:
try:
from src.new.main_view import PandasTableModel
except ImportError:
self.reset_preview("数据预览模块加载失败")
return
try:
rows_to_preview = max(1, self.preview_rows_spin.value())
# dtype=object 确保所有列以字符串读取,避免空值/混合类型导致 dtype 报错
df = pd.read_csv(csv_path, nrows=rows_to_preview, dtype=object)
# fillna 在 PandasTableModel.__init__ 中已执行,此处再次防御性处理
df = df.fillna('')
if df.empty:
self.reset_preview("CSV文件为空")
@ -200,7 +260,7 @@ class Step5CleanPanel(QWidget):
model = PandasTableModel(df)
self.preview_table.setModel(model)
self.preview_status_label.setText(
f"预览 {len(df)} 行,{len(df.columns)} 列(总行数可能更多)"
f"预览前 {len(df)} 行,共 {len(df.columns)} 列"
)
except Exception as exc:
self.reset_preview(f"加载失败: {exc}")
self.reset_preview(f"加载数据失败: {exc}")