Commit f8cfcff7 by Yuhaibo

1

parent 2ac40d5e
......@@ -24,8 +24,6 @@ os.environ['ULTRALYTICS_CONFIG_DIR'] = os.path.join(current_dir, '.cache', 'ultr
# 修复 OpenMP 运行时冲突问题
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE' # 允许多个OpenMP库共存(临时解决方案)
print("[环境变量] ultralytics离线模式已启用")
print("[环境变量] OpenMP冲突已修复")
from qtpy import QtWidgets
......
......@@ -620,11 +620,10 @@ class MainWindow(
if os.path.exists(icon_path):
icon = QtGui.QIcon(icon_path)
self.setWindowIcon(icon)
print(f"[主窗口] 窗口图标已设置: {icon_path}")
else:
print(f"[主窗口] 图标文件不存在: {icon_path}")
pass
except Exception as e:
print(f"[主窗口] 设置窗口图标失败: {e}")
pass
def _loadDefaultConfig(self):
"""从 default_config.yaml 加载配置"""
......@@ -764,7 +763,6 @@ class MainWindow(
# 🔥 为每个通道面板的任务标签设置变量名(channel1mission, channel2mission, channel3mission, channel4mission)
mission_var_name = f'channel{i+1}mission'
setattr(self, mission_var_name, channelPanel.taskLabel)
print(f"[MainWindow] 已设置任务标签变量: {mission_var_name}")
if hasattr(self, '_connectChannelPanelSignals'):
self._connectChannelPanelSignals(channelPanel)
......@@ -795,7 +793,6 @@ class MainWindow(
history_panel.setObjectName(f"HistoryVideoPanel_{i+1}")
self.historyVideoPanels.append(history_panel)
print(f"[MainWindow] 已创建 {len(self.historyVideoPanels)} 个历史视频面板")
# 通过handler初始化通道面板数据
if hasattr(self, 'initializeChannelPanels'):
......@@ -822,7 +819,6 @@ class MainWindow(
# 🔥 设置曲线面板的任务选择下拉框变量名(curvemission)
self.curvemission = self.curvePanel.curvemission
print(f"[MainWindow] 已设置曲线任务变量: curvemission")
# 连接任务选择变化信号
self.curvemission.currentTextChanged.connect(self._onCurveMissionChanged)
......@@ -854,7 +850,6 @@ class MainWindow(
self.videoLayoutStack.addWidget(layout_widget)
print(f"[MainWindow] 曲线模式布局已创建:左侧子布局栈(实时/历史) + 右侧共用CurvePanel")
def _createRealtimeCurveSubLayout(self):
"""创建实时检测曲线子布局(索引0)- 左侧通道列表"""
......@@ -898,7 +893,6 @@ class MainWindow(
sublayout.addWidget(self.curve_scroll_area)
self.curveLayoutStack.addWidget(sublayout_widget)
print(f"[MainWindow] 实时检测曲线子布局已创建(索引0)- 基于CSV文件的动态通道系统")
def _createHistoryCurveSubLayout(self):
"""创建历史回放曲线子布局(索引1)- 使用历史视频面板容器"""
......@@ -942,7 +936,6 @@ class MainWindow(
sublayout.addWidget(self.history_scroll_area)
self.curveLayoutStack.addWidget(sublayout_widget)
print(f"[MainWindow] 历史回放曲线子布局已创建(索引1)- 历史视频面板容器系统")
def _onChannelCurveClicked(self, task_name):
"""
......@@ -951,15 +944,9 @@ class MainWindow(
Args:
task_name: 通道面板的任务名称
"""
print(f"🔄 [主窗口] 通道面板查看曲线按钮被点击,任务名称: {task_name}")
# 设置 curvemission 的值
if hasattr(self, 'curvePanel') and self.curvePanel:
success = self.curvePanel.setMissionFromTaskName(task_name)
if success:
print(f"✅ [主窗口] 已设置 curvemission 为: {task_name}")
else:
print(f"⚠️ [主窗口] 设置 curvemission 失败: {task_name}")
# 切换到曲线模式
self.toggleVideoPageMode()
......@@ -1260,7 +1247,6 @@ class MainWindow(
# ========== 通道管理按钮信号 ==========
# 🔥 已改为内嵌显示,由 MissionPanelHandler 处理,不再使用弹窗
# self.missionTable.channelManageClicked.connect(self.onChannelManage) # 旧的弹窗方式
print("[App] 通道管理已改为内嵌显示,不再使用弹窗")
# ========== 通道面板信号(为所有面板连接) ==========
# 注意:channelConnected, channelDisconnected, channelEdited, amplifyClicked, channelNameChanged
......@@ -1509,15 +1495,12 @@ class MainWindow(
def closeEvent(self, event):
"""窗口关闭事件"""
try:
print("[应用] 正在关闭应用...")
# 清理全局检测线程
if hasattr(self, 'view_handler') and self.view_handler:
video_handler = getattr(self.view_handler, 'video_handler', None)
if video_handler:
thread_manager = getattr(video_handler, 'thread_manager', None)
if thread_manager:
print("[应用] 清理全局检测线程...")
thread_manager.cleanup_global_detection_thread()
# 保存窗口状态
......@@ -1528,10 +1511,7 @@ class MainWindow(
# 保存当前页面索引
self.settings.setValue("window/last_page", self.getCurrentPageIndex())
print("[应用] 应用关闭清理完成")
except Exception as e:
print(f"[应用] 关闭清理失败: {e}")
import traceback
traceback.print_exc()
......
......@@ -519,18 +519,11 @@ class ModelSetHandler:
current_dir = Path(__file__).parent.parent.parent
model_dir = current_dir / "database" / "model" / "detection_model"
print(f"[模型扫描] 扫描目录: {model_dir}")
if not model_dir.exists():
print(f"[模型扫描] 目录不存在")
return models
print(f"[模型扫描] 目录存在: {model_dir.exists()}")
# 扫描所有子目录(数字和非数字)
all_subdirs = [d for d in model_dir.iterdir() if d.is_dir()]
print(f"[模型扫描] 找到子目录数量: {len(all_subdirs)}")
print(f"[模型扫描] 子目录列表: {[d.name for d in all_subdirs]}")
# 分离数字目录和非数字目录
digit_subdirs = [d for d in all_subdirs if d.name.isdigit()]
......@@ -542,10 +535,8 @@ class ModelSetHandler:
# 合并:数字目录在前,非数字目录在后
sorted_subdirs = sorted_digit_subdirs + sorted_non_digit_subdirs
print(f"[模型扫描] 排序后的子目录: {[d.name for d in sorted_subdirs]}")
for subdir in sorted_subdirs:
print(f"[模型扫描] 处理子目录: {subdir.name}")
# 检查是否有weights子目录(优先检查train/weights,然后weights)
train_weights_dir = subdir / "train" / "weights"
......@@ -553,15 +544,10 @@ class ModelSetHandler:
if train_weights_dir.exists():
search_dir = train_weights_dir
print(f"[模型扫描] 找到train/weights目录: {search_dir}")
elif weights_dir.exists():
search_dir = weights_dir
print(f"[模型扫描] 找到weights目录: {search_dir}")
else:
search_dir = subdir
print(f"[模型扫描] 使用根目录: {search_dir}")
print(f"[模型扫描] 搜索目录: {search_dir}")
# 按优先级查找模型文件:best > last > epoch1
# 支持的扩展名:.dat, .pt, .template_*, 无扩展名
......@@ -576,7 +562,6 @@ class ModelSetHandler:
# 检查文件名是否匹配模式
if file.name.startswith('best.') and not file.name.endswith('.pt'):
selected_model = file
print(f"[模型扫描] 找到best模型: {file.name}")
break
# 优先级2: last模型(如果没有best)
......@@ -584,7 +569,6 @@ class ModelSetHandler:
for file in search_dir.iterdir():
if file.is_file() and file.name.startswith('last.') and not file.name.endswith('.pt'):
selected_model = file
print(f"[模型扫描] 找到last模型: {file.name}")
break
# 优先级3: epoch1模型(如果没有best和last)
......@@ -592,7 +576,6 @@ class ModelSetHandler:
for file in search_dir.iterdir():
if file.is_file() and file.name.startswith('epoch1.') and not file.name.endswith('.pt'):
selected_model = file
print(f"[模型扫描] 找到epoch1模型: {file.name}")
break
# 如果都没找到,尝试查找任何非.pt文件
......@@ -600,7 +583,6 @@ class ModelSetHandler:
for file in search_dir.iterdir():
if file.is_file() and not file.name.endswith('.pt') and not file.name.endswith('.txt') and not file.name.endswith('.yaml'):
selected_model = file
print(f"[模型扫描] 找到其他模型: {file.name}")
break
# 如果找到了模型文件,添加到列表
......@@ -632,16 +614,11 @@ class ModelSetHandler:
'file_name': selected_model.name
}
models.append(model_info)
print(f"[模型扫描] 添加模型: {model_name} ({selected_model.name})")
else:
print(f"[模型扫描] 子目录 {subdir.name} 中未找到有效模型")
except Exception as e:
import traceback
traceback.print_exc()
print(f"[模型扫描] 扫描异常: {e}")
print(f"[模型扫描] 总共找到 {len(models)} 个模型")
return models
def _mergeModelInfo(self, channel_models, scanned_models):
......
# 自动标点功能模块使用说明
## 功能概述
`auto_dot.py` 模块实现了基于YOLO分割掩码的自动标点功能,可以自动检测容器的顶部和底部位置,替代人工手动标点。
## 核心特性
- **输入**: 图片 + 检测框
- **输出**: 点位置信息 + 标注后的图片
- **检测方法**:
1. **liquid底部 + air顶部** (最可靠)
2. **liquid底部 + liquid顶部** (次选)
3. **air底部 + air顶部** (备选)
## 独立调试
### 1. 准备测试数据
将测试图片放置到:
```
D:\restructure\liquid_level_line_detection_system\test_data\test_image.jpg
```
### 2. 配置检测框
编辑 `auto_dot.py` 中的 `test_auto_dot()` 函数,修改 `boxes` 参数:
```python
# 方式1: [x1, y1, x2, y2] 格式
boxes = [
[100, 200, 300, 600], # 第一个容器
[400, 200, 600, 600], # 第二个容器
]
# 方式2: [cx, cy, size] 格式
boxes = [
[200, 400, 400], # 中心点(200, 400), 尺寸400
]
```
### 3. 运行测试
```bash
cd D:\restructure\liquid_level_line_detection_system\handlers\videopage
python auto_dot.py
```
### 4. 查看结果
- **控制台输出**: 详细的检测过程和结果
- **标注图片**: `D:\restructure\liquid_level_line_detection_system\test_output\auto_dot_result.jpg`
## API 使用示例
```python
from handlers.videopage.auto_dot import AutoDotDetector
import cv2
# 1. 创建检测器
detector = AutoDotDetector(
model_path="path/to/model.dat",
device='cuda' # 或 'cpu'
)
# 2. 加载图片
image = cv2.imread("test_image.jpg")
# 3. 定义检测框
boxes = [
[100, 200, 300, 600], # [x1, y1, x2, y2]
]
# 4. 执行检测
result = detector.detect_container_boundaries(
image=image,
boxes=boxes,
conf_threshold=0.5
)
# 5. 获取结果
if result['success']:
for container in result['containers']:
print(f"容器 {container['index']}:")
print(f" 顶部: ({container['top_x']}, {container['top']})")
print(f" 底部: ({container['bottom_x']}, {container['bottom']})")
print(f" 高度: {container['height']}px")
print(f" 置信度: {container['confidence']:.3f}")
# 保存标注图片
cv2.imwrite("result.jpg", result['annotated_image'])
```
## 输出数据结构
```python
{
'success': bool, # 检测是否成功
'containers': [
{
'index': int, # 容器索引
'top': int, # 顶部y坐标
'bottom': int, # 底部y坐标
'top_x': int, # 顶部x坐标
'bottom_x': int, # 底部x坐标
'height': int, # 容器高度(像素)
'confidence': float, # 检测置信度
'method': str # 检测方法
},
...
],
'annotated_image': np.ndarray # 标注后的图片
}
```
## 检测方法说明
### 方法1: liquid_air (最可靠)
- **容器底部**: liquid掩码的最低点
- **容器顶部**: air掩码的最高点
- **适用场景**: 同时检测到液体和空气
### 方法2: liquid_only (次选)
- **容器底部**: liquid掩码的最低点
- **容器顶部**: liquid掩码的最高点
- **适用场景**: 只检测到液体,未检测到空气
### 方法3: air_only (备选)
- **容器底部**: air掩码的最低点
- **容器顶部**: air掩码的最高点
- **适用场景**: 只检测到空气,未检测到液体
## 可视化标注
标注图片包含:
- **绿色圆点**: 容器顶部
- **红色圆点**: 容器底部
- **青色连线**: 容器高度
- **水平参考线**: 顶部和底部的水平位置
- **文字标注**: Top-N, Bottom-N, 高度值
## 注意事项
1. **模型路径**: 确保模型文件存在且可访问
2. **检测框位置**: 检测框应覆盖完整的容器区域
3. **置信度阈值**: 默认0.5,可根据实际情况调整
4. **GPU加速**: 建议使用CUDA加速,提高检测速度
## 调试技巧
1. **查看控制台输出**: 详细的检测过程日志
2. **检查标注图片**: 验证检测结果的准确性
3. **调整检测框**: 如果检测失败,尝试调整检测框的位置和大小
4. **降低置信度**: 如果检测不到掩码,尝试降低 `conf_threshold`
## 接入系统
调试成功后,可以在主系统中调用:
```python
from handlers.videopage.auto_dot import AutoDotDetector
# 在标注页面添加"自动标点"按钮
# 点击后调用 detector.detect_container_boundaries()
# 将返回的 top/bottom 坐标填充到标注点位置
```
......@@ -1905,7 +1905,6 @@ class ChannelPanelHandler:
config_path = os.path.join(project_root, 'database', 'config', 'default_config.yaml')
if not os.path.exists(config_path):
print(f"[ConfigWatcher] 配置文件不存在: {config_path}")
return
# 创建文件系统监控器
......@@ -1915,61 +1914,43 @@ class ChannelPanelHandler:
# 连接文件变化信号
self._config_watcher.fileChanged.connect(self._onConfigFileChanged)
print(f"[ConfigWatcher] 已开始监控配置文件: {config_path}")
except Exception as e:
print(f"[ConfigWatcher] 初始化配置文件监控器失败: {e}")
import traceback
traceback.print_exc()
def _onConfigFileChanged(self, path):
"""配置文件变化时的回调"""
try:
print(f"🔄 [ConfigWatcher] 检测到配置文件变化: {path}")
# 延迟一小段时间,确保文件写入完成
QtCore.QTimer.singleShot(100, self._reloadChannelConfig)
except Exception as e:
print(f"[ConfigWatcher] 处理配置文件变化失败: {e}")
import traceback
traceback.print_exc()
def _reloadChannelConfig(self):
"""重新加载通道配置"""
try:
print("🔄 [ConfigWatcher] 开始重新加载通道配置...")
# 获取配置文件路径
project_root = get_project_root()
config_path = os.path.join(project_root, 'database', 'config', 'default_config.yaml')
print(f" 📂 [ConfigWatcher] 配置文件路径: {config_path}")
print(f" 📂 [ConfigWatcher] 文件是否存在: {os.path.exists(config_path)}")
if not os.path.exists(config_path):
print(f"[ConfigWatcher] 配置文件不存在: {config_path}")
return
# 读取配置文件
with open(config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f) or {}
print(f" 📄 [ConfigWatcher] 配置文件内容键: {list(config.keys())}")
print(f" 🗺️ [ConfigWatcher] 通道面板映射: {list(self._channel_panels_map.keys())}")
# 🔥 关键修复:更新 self._config,这样 _getChannelConfigFromFile 才能读取到最新配置
old_config = self._config
self._config = config
print(f" 🔄 [ConfigWatcher] 已更新内部配置缓存 (self._config)")
# 更新每个通道面板的名称和地址信息
for i in range(1, 5):
channel_id = f'channel{i}'
channel_key = f'channel{i}'
print(f" [ConfigWatcher] 处理 {channel_id}...")
# 获取通道面板
panel = self._channel_panels_map.get(channel_id)
if not panel:
......@@ -2015,15 +1996,10 @@ class ChannelPanelHandler:
# 重新添加监控(因为某些编辑器保存文件时会删除再创建,导致监控失效)
if hasattr(self, '_config_watcher'):
monitored_files = self._config_watcher.files()
print(f" 👀 [ConfigWatcher] 当前监控的文件: {monitored_files}")
if config_path not in monitored_files:
self._config_watcher.addPath(config_path)
print(f" 🔄 [ConfigWatcher] 重新添加文件监控: {config_path}")
print("[ConfigWatcher] 通道配置重新加载完成(包括地址配置)")
except Exception as e:
print(f"[ConfigWatcher] 重新加载通道配置失败: {e}")
import traceback
traceback.print_exc()
......
......@@ -117,6 +117,7 @@ class GeneralSetPanelHandler:
widget.annotationEngineRequested.connect(self._handleAnnotationEngineRequest)
widget.frameLoadRequested.connect(self._handleFrameLoadRequest)
widget.annotationDataRequested.connect(self._handleAnnotationDataRequest)
widget.liveFrameRequested.connect(self._handleLiveFrameRequest)
def _handleRefreshModelList(self, model_widget=None):
"""处理刷新模型列表请求"""
......@@ -264,7 +265,6 @@ class GeneralSetPanelHandler:
if self.general_set_panel:
self.general_set_panel.setTaskIdOptions(task_ids)
print(f"[Handler] 已加载 {len(task_ids)} 个任务编号选项")
except Exception as e:
print(f"[Handler] 加载任务ID选项失败: {e}")
import traceback
......@@ -405,10 +405,6 @@ class GeneralSetPanelHandler:
model_config = default_config.get('model', {}).copy()
model_config['model_path'] = absolute_path
print(f"[Handler] 加载通道 {channel_id} 的模型配置:")
print(f" 相对路径: {channel_model_path}")
print(f" 绝对路径: {absolute_path}")
# 调用widget的方法应用配置
if self.general_set_panel:
self.general_set_panel.applyModelConfigFromHandler(
......@@ -693,26 +689,15 @@ class GeneralSetPanelHandler:
channel_frame = None
if self.general_set_panel and self.general_set_panel.channel_id:
channel_frame = self.getLatestFrame(self.general_set_panel.channel_id)
if channel_frame is not None:
pass
# 如果没有获取到通道画面,使用测试图像
# 如果没有获取到通道画面,弹出提示框并返回
if channel_frame is None:
pass
import numpy as np
channel_frame = np.zeros((720, 1280, 3), dtype=np.uint8)
channel_frame[:] = (100, 120, 140) # 灰色背景
# 添加文字说明
cv2.putText(channel_frame, "Test Annotation Frame", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2)
cv2.putText(channel_frame, "Draw detection areas and mark liquid levels", (50, 100),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (200, 200, 200), 1)
# 添加测试区域
cv2.rectangle(channel_frame, (200, 200), (400, 400), (0, 255, 0), 2)
cv2.rectangle(channel_frame, (500, 300), (700, 500), (0, 0, 255), 2)
QtWidgets.QMessageBox.warning(
self.main_window,
"获取画面失败",
"获取通道画面失败,请先连接通道"
)
return
# 2. 保存原始帧用于标注结果显示
self._annotation_source_frame = channel_frame.copy() if channel_frame is not None else None
......@@ -724,6 +709,9 @@ class GeneralSetPanelHandler:
if self.general_set_panel and self.general_set_panel.channel_name:
annotation_widget.setChannelName(self.general_set_panel.channel_name)
# 3.5. 初始化物理变焦控制器
self._initPhysicalZoomForAnnotation(annotation_widget)
# 4. 连接标注完成信号
def on_annotation_completed(boxes, bottoms, tops):
print(f"\n[DEBUG] ========== 标注完成回调 ==========")
......@@ -789,6 +777,9 @@ class GeneralSetPanelHandler:
# 5. 加载图像并显示标注界面
if annotation_widget.loadFrame(channel_frame):
# 启用实时画面预览
annotation_widget.enableLivePreview(True)
# 🔥 关键修复:延迟显示窗口,确保全屏应用后再显示
# 这样可以确保标注帧在全屏模式下立即显示
QtCore.QTimer.singleShot(150, annotation_widget.show)
......@@ -1246,6 +1237,73 @@ class GeneralSetPanelHandler:
if self.annotation_widget:
self.annotation_widget.showAnnotationError(f"获取标注数据失败: {str(e)}")
def _handleLiveFrameRequest(self):
"""处理实时画面请求"""
try:
# 获取通道最新画面
if self.general_set_panel and self.general_set_panel.channel_id:
channel_frame = self.getLatestFrame(self.general_set_panel.channel_id)
# 更新标注界面的画面
if channel_frame is not None and self.annotation_widget:
self.annotation_widget.updateLiveFrame(channel_frame)
except Exception as e:
pass
def _initPhysicalZoomForAnnotation(self, annotation_widget):
"""为标注界面初始化物理变焦控制器"""
try:
# 尝试导入物理变焦控制器
try:
from handlers.videopage.physical_zoom_controller import PhysicalZoomController
except ImportError:
try:
from physical_zoom_controller import PhysicalZoomController
except ImportError:
return
# 获取通道配置
if not self.general_set_panel or not self.general_set_panel.channel_id:
return
channel_id = self.general_set_panel.channel_id
# 从配置文件获取设备IP
config = self._getChannelConfig(channel_id)
if not config:
return
device_ip = config.get('address', '')
if not device_ip or 'rtsp://' not in device_ip:
return
# 提取IP地址
import re
match = re.search(r'@(\d+\.\d+\.\d+\.\d+)', device_ip)
if not match:
return
device_ip = match.group(1)
# 创建物理变焦控制器
physical_zoom_controller = PhysicalZoomController(
device_ip=device_ip,
username='admin',
password='cei345678',
channel=1
)
# 尝试连接设备
if physical_zoom_controller.connect_device():
# 设置到标注界面
annotation_widget.setPhysicalZoomController(physical_zoom_controller)
print(f"[标注界面] 物理变焦已启用 ({device_ip})")
else:
print(f"[标注界面] 物理变焦设备连接失败")
except Exception as e:
print(f"[标注界面] 初始化物理变焦失败: {e}")
def showGeneralSetPanel(self):
"""显示常规设置面板"""
from widgets.videopage.general_set import GeneralSetPanel
......
......@@ -144,10 +144,6 @@ class ModelSettingHandler:
model_config['model_path'] = absolute_path
config_source = f"default_config.yaml → {channel_model_key} + model (全局参数)"
print(f"[Handler] 加载通道 {channel_id} 的模型配置")
print(f" 相对路径: {channel_model_path}")
print(f" 绝对路径: {absolute_path}")
print(f" model_config['model_path'] = {model_config.get('model_path', 'None')}")
else:
# 使用全局模型配置
model_config = default_config.get('model', {}).copy()
......
......@@ -334,12 +334,11 @@ class ModelSetPage(QtWidgets.QWidget):
QTextEdit {
border: 1px solid #ccc;
background-color: white;
font-family: Consolas, Monaco, monospace;
font-size: 10pt;
}
""")
self.model_info_text.setPlaceholderText("选择模型后将显示模型文件夹内的txt文件内容...")
FontManager.applyToWidget(self.model_info_text)
# 应用全局字体管理
FontManager.applyToWidget(self.model_info_text, size=10)
right_text_layout.addWidget(self.model_info_text)
# 将左右两部分添加到中间主布局(1:1比例)
......@@ -1467,6 +1466,76 @@ class ModelSetPage(QtWidgets.QWidget):
except Exception as e:
return False
def _loadModelTxtFiles(self, model_name):
"""读取并显示模型文件夹内的txt文件"""
try:
# 清空文本显示区域
self.model_info_text.clear()
# 获取模型信息
if model_name not in self._model_params:
self.model_info_text.setPlainText(f"未找到模型 '{model_name}' 的信息")
return
model_info = self._model_params[model_name]
model_path = model_info.get('path', '')
if not model_path:
self.model_info_text.setPlainText(f"模型 '{model_name}' 没有路径信息")
return
# 获取模型所在的目录
model_dir = Path(model_path).parent
if not model_dir.exists():
self.model_info_text.setPlainText(f"模型目录不存在:\n{model_dir}")
return
# 查找目录中的所有txt文件
txt_files = list(model_dir.glob("*.txt"))
if not txt_files:
self.model_info_text.setPlainText(f"模型目录中没有找到txt文件:\n{model_dir}")
return
# 读取并显示所有txt文件的内容
content_parts = []
content_parts.append(f"模型目录: {model_dir}\n")
content_parts.append("=" * 60 + "\n\n")
for txt_file in sorted(txt_files):
content_parts.append(f"【文件: {txt_file.name}】\n")
content_parts.append("-" * 60 + "\n")
try:
# 尝试使用UTF-8编码读取
with open(txt_file, 'r', encoding='utf-8') as f:
file_content = f.read()
except UnicodeDecodeError:
# 如果UTF-8失败,尝试GBK编码
try:
with open(txt_file, 'r', encoding='gbk') as f:
file_content = f.read()
except Exception as e:
file_content = f"无法读取文件(编码错误): {str(e)}"
except Exception as e:
file_content = f"读取文件时出错: {str(e)}"
content_parts.append(file_content)
content_parts.append("\n\n" + "=" * 60 + "\n\n")
# 显示所有内容
full_content = "".join(content_parts)
self.model_info_text.setPlainText(full_content)
# 滚动到顶部
cursor = self.model_info_text.textCursor()
cursor.movePosition(QtGui.QTextCursor.Start)
self.model_info_text.setTextCursor(cursor)
except Exception as e:
self.model_info_text.setPlainText(f"读取txt文件时出错:\n{str(e)}")
if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment