From 7fb0c3849ca96369a2b4c8f965cc372c73519967 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 21 May 2026 10:34:15 +0800 Subject: [PATCH] =?UTF-8?q?P0=20=E6=AD=BB=E4=BB=A3=E7=A0=81=E6=B8=85?= =?UTF-8?q?=E7=90=86=EF=BC=9A=E5=88=A0=20.backup=20/=20=E7=A9=BA=E6=96=87?= =?UTF-8?q?=E4=BB=B6=20/=20GUI=20=E5=8D=A0=E4=BD=8D=E6=A1=A9=20/=20?= =?UTF-8?q?=E5=8D=A0=E4=BD=8D=E7=9B=AE=E5=BD=95=20/=20=E5=A4=B1=E6=95=88?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A. 删除 3 个 .backup 文件(约 3.4K 行) - douyin/detection/douyin_pixel.py.backup - douyin/stage/douyin_stage_handler.py.backup - gui/components/log_color_config.py.backup B. 删除 0 字节文件 - douyin/other/douyin_stuck_guard.py - docs/功能差异对比.md - docs/archive/模块化代码对比说明.md C. 删除 9 个 TODO + pass 占位组件(全仓零外部引用) - gui/components/{config_manager,image_viewer,stats_display, reservation_display,high_value_rooms_display,ocr_panel,main_window}.py - gui/web_components/{proc_runner,http_handler}.py D. 删除占位目录与失效测试入口 - douyin/detection/core/ 仅 re-export 占位 - douyin/fudai/finder/ 仅 re-export 占位 - tests/run_test.py 指向已删的 deleted_tests_backup/ 附加:tools/diagnostics/check_web_gui_config_sync.py --help 字符串里 tools/web_gui_config_manifest.json 旧路径修正为 tools/dev/... 回归:154 → 141 个 .py,全量 compileall 通过;AST 扫描 0 处 import 残留; gui.gui_app/web_gui/gui_core 仍可加载;fudai_analyse / should_skip_fudai_by_config 业务函数链路正常;test_filter_logging / check_web_gui_config_sync 通过。 Co-Authored-By: Claude Opus 4.7 --- docs/archive/模块化代码对比说明.md | 0 docs/功能差异对比.md | 0 douyin/detection/core/__init__.py | 20 - douyin/detection/douyin_pixel.py.backup | 1129 -------------- douyin/fudai/finder/__init__.py | 24 - douyin/other/douyin_stuck_guard.py | 0 douyin/stage/douyin_stage_handler.py.backup | 1332 ----------------- gui/components/config_manager.py | 44 - gui/components/high_value_rooms_display.py | 42 - gui/components/image_viewer.py | 40 - gui/components/log_color_config.py.backup | 943 ------------ gui/components/main_window.py | 36 - gui/components/ocr_panel.py | 37 - gui/components/reservation_display.py | 42 - gui/components/stats_display.py | 46 - gui/web_components/http_handler.py | 12 - gui/web_components/proc_runner.py | 12 - tests/run_test.py | 52 - .../diagnostics/check_web_gui_config_sync.py | 2 +- 19 files changed, 1 insertion(+), 3812 deletions(-) delete mode 100644 docs/archive/模块化代码对比说明.md delete mode 100644 docs/功能差异对比.md delete mode 100644 douyin/detection/core/__init__.py delete mode 100644 douyin/detection/douyin_pixel.py.backup delete mode 100644 douyin/fudai/finder/__init__.py delete mode 100644 douyin/other/douyin_stuck_guard.py delete mode 100644 douyin/stage/douyin_stage_handler.py.backup delete mode 100644 gui/components/config_manager.py delete mode 100644 gui/components/high_value_rooms_display.py delete mode 100644 gui/components/image_viewer.py delete mode 100644 gui/components/log_color_config.py.backup delete mode 100644 gui/components/main_window.py delete mode 100644 gui/components/ocr_panel.py delete mode 100644 gui/components/reservation_display.py delete mode 100644 gui/components/stats_display.py delete mode 100644 gui/web_components/http_handler.py delete mode 100644 gui/web_components/proc_runner.py delete mode 100644 tests/run_test.py diff --git a/docs/archive/模块化代码对比说明.md b/docs/archive/模块化代码对比说明.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/功能差异对比.md b/docs/功能差异对比.md deleted file mode 100644 index e69de29..0000000 diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py deleted file mode 100644 index 304fd4b..0000000 --- a/douyin/detection/core/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -"""检测核心模块 - -本目录包含从 douyin_detection.py 模块化后的检测功能。 -""" - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后改为从子模块导入 -from ...detection.douyin_detection import ( - _ensure_detection_cache, - check_detail_height, - check_have_fudai_with_ready_screenshot, - check_in_fudai_detail, -) - -__all__ = [ - "_ensure_detection_cache", - "check_detail_height", - "check_have_fudai_with_ready_screenshot", - "check_in_fudai_detail", -] diff --git a/douyin/detection/douyin_pixel.py.backup b/douyin/detection/douyin_pixel.py.backup deleted file mode 100644 index b9a012d..0000000 --- a/douyin/detection/douyin_pixel.py.backup +++ /dev/null @@ -1,1129 +0,0 @@ -# pyright: reportGeneralTypeIssues=false -# pyright: reportAttributeAccessIssue=false -# pyright: reportMissingModuleSource=false -# pyright: reportUnknownMemberType=false -# pyright: reportUnknownVariableType=false -import os -from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import Any, Optional - -from PIL import Image - - -def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]: - try: - if not pic_path or (not os.path.exists(pic_path)): - return None - pic = Image.open(pic_path) - pic.load() # Force load to catch truncated files early - return pic.convert("RGB") - except (OSError, IOError, SyntaxError): - # Handle truncated image files - return None - except Exception as e: # type: ignore[general-exception] - return None - - -def detect_coupon_popup_background( - pic_rgb: Image.Image, - return_info: bool = False, - template_threshold: float | None = None, - analyser: Any = None, -) -> bool | tuple[bool, dict]: - """检测底部优惠券大弹窗(仅模板匹配)。 - - 模板匹配区域(基于1080x2400基准): - - 左上: (9, 1173) - - 右下: (1079, 2255) - 使用 `assets/coupon.png` 作为模板。 - - 参数: - pic_rgb: RGB格式的整屏截图 - return_info: 是否返回详细信息(包含检测分数) - template_threshold: 模板匹配阈值(默认0.75,如果提供则使用,否则从analyser读取) - analyser: analyser对象,用于读取配置阈值 - - 返回: - bool: 是否检测到优惠券背景(return_info=False时) - tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) - """ - try: - try: - import cv2 # type: ignore[import-untyped] - import numpy as np # type: ignore[import-untyped] - except Exception as e: # type: ignore[general-exception] - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "opencv_unavailable", - } - return False - - width, height = pic_rgb.size - scale_x = width / 1080.0 - scale_y = height / 2400.0 - - x1 = int(9 * scale_x) - y1 = int(1173 * scale_y) - x2 = int(1079 * scale_x) - y2 = int(2255 * scale_y) - - x1 = max(0, min(x1, width)) - y1 = max(0, min(y1, height)) - x2 = max(0, min(x2, width)) - y2 = max(0, min(y2, height)) - - if x1 >= x2 or y1 >= y2: - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "invalid_region", - } - return False - - bgr = cv2.cvtColor( # type: ignore[attr-defined] - np.array(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined] - ) - roi = bgr[y1:y2, x1:x2] # type: ignore[index] - if roi.size == 0: - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "empty_roi", - } - return False - - # 使用统一的模板路径配置 - try: - import path_config - template_path = path_config.get_assets_dir() + "/coupon.png" - except Exception: - # 回退到旧路径(向后兼容) - base_dir = os.path.dirname(__file__) - template_path = os.path.join(base_dir, "assets", "coupon.png") - if not os.path.exists(template_path): - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "template_not_found", - } - return False - - template = cv2.imread( # type: ignore[attr-defined,assignment] - template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] - ) - if template is None: - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "template_load_failed", - } - return False - if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]: - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": "template_too_large", - } - return False - - res = cv2.matchTemplate( # type: ignore[attr-defined] - roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _, max_val, _, _ = cv2.minMaxLoc(res) # type: ignore[attr-defined] - # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 - if template_threshold is not None: - threshold = float(template_threshold) - elif analyser is not None: - try: - threshold = float( - getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75 - ) - except Exception as e: # type: ignore[general-exception] - threshold = 0.75 - else: - threshold = 0.75 - result = max_val >= threshold - - if return_info: - reason_value: Optional[str] = None if result else "score_below_threshold" - return result, { - "method": "template_match", - "template_score": float(max_val), - "effective_threshold": threshold, - "reason": reason_value, - } - return result - except Exception as e: # type: ignore[general-exception] - if return_info: - return False, { - "method": "template_match", - "template_score": None, - "reason": f"exception: {str(e)}", - } - return False - - -def detect_redpacket_popup_background(_pic_rgb: Image.Image) -> bool: - """中央购物红包弹窗检测(暂时禁用,始终返回 False)。""" - return False - - -def detect_lucky_draw_result_popup( - pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False -) -> bool | tuple[bool, dict]: - """检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。 - - 使用基准 1080x2400 坐标的检测区域: - - 左上: (181, 1261) - - 右下: (890, 1389) - """ - try: - width, height = pic_rgb.size - scale_x = width / 1080.0 - scale_y = height / 2400.0 - - x1 = int(181 * scale_x) - y1 = int(1261 * scale_y) - x2 = int(890 * scale_x) - y2 = int(1389 * scale_y) - - # 边界与顺序 - x1, x2 = max(0, min(x1, width)), max(0, min(x2, width)) - y1, y2 = max(0, min(y1, height)), max(0, min(y2, height)) - if x1 > x2: - x1, x2 = x2, x1 - if y1 > y2: - y1, y2 = y2, y1 - - if x1 >= x2 or y1 >= y2: - return False - - # 双截图记录:保存实时操作截图(像素检测区域) - detect_roi = None - try: - from douyin.handlers import douyin_screenshot_manager - - detect_roi = pic_rgb.crop((x1, y1, x2, y2)) - douyin_screenshot_manager.save_latest_attempt( - detect_roi, operation_type="pixel_detect" - ) - - # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="lucky_draw_result", - step="before_detect", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={ - "threshold": red_ratio_threshold, - "region_size": f"{x2-x1}x{y2-y1}", - }, - ) - if debug_path: - try: - import logging - - logging.info( - "[调试图像] 像素检测前保存: %s, threshold=%s", - debug_path, - red_ratio_threshold, - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - red_count = 0 - total_samples = 0 - step_x = max(1, (x2 - x1) // 10) - step_y = max(1, (y2 - y1) // 10) - - for y in range(y1, y2, step_y): - for x in range(x1, x2, step_x): - try: - r, g, b = pic_rgb.getpixel((x, y)) - total_samples += 1 - # 根据实际检测结果:R: 245-255, G: 44-255, B: 85-255 - # 红色按钮检测:R >= 245 且 R 明显大于 G 和 B - if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50: - red_count += 1 - except Exception as e: # type: ignore[general-exception] - continue - - if total_samples == 0: - return False - - red_ratio = red_count / total_samples - result = red_ratio >= red_ratio_threshold - - # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 - try: - from douyin.handlers import douyin_screenshot_manager - - if result: - # 检测成功 - if detect_roi is None: - detect_roi = pic_rgb.crop((x1, y1, x2, y2)) - douyin_screenshot_manager.save_last_success( - detect_roi, operation_type="pixel_detect" - ) - - # 无论成功失败都保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="lucky_draw_result", - step="detected" if result else "not_detected", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={ - "red_ratio": round(red_ratio, 4), - "red_count": red_count, - "total_samples": total_samples, - "threshold": red_ratio_threshold, - "result": "success" if result else "failed", - }, - ) - if debug_path: - try: - import logging - - logging.info( - "[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f", - debug_path, - red_ratio, - red_ratio_threshold, - red_ratio, - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - # 如果请求详细信息,返回包含red_ratio的字典 - if return_info: - reason_value: Optional[str] = ( - None if result else "red_ratio_below_threshold" - ) - return result, { - "method": "pixel_detect", - "red_ratio": red_ratio, - "red_count": red_count, - "total_samples": total_samples, - "effective_threshold": red_ratio_threshold, - "reason": reason_value, - } - - return result - except Exception as e: # type: ignore[general-exception] - return False - - -def detect_attend_button_red_area( - pic_rgb: Image.Image, - return_info: bool = False, - red_ratio_threshold: float | None = None, - analyser: Any = None, -) -> bool | tuple[bool, dict]: - """检测参与按钮:大片红色区域。 - - 参与按钮通常在屏幕底部,有大片红色背景。 - 检测区域:(306,2030)-(780,2110) 基准1080x2400,但实际可能更宽 - 扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮 - """ - try: - width, height = pic_rgb.size - # 缩放坐标到实际尺寸 - scale_x = width / 1080.0 - scale_y = height / 2400.0 - - # 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮) - x1 = int(200 * scale_x) # 扩展左侧 - y1 = int(2000 * scale_y) # 稍微上移 - x2 = int(880 * scale_x) # 扩展右侧 - y2 = int(2120 * scale_y) # 稍微下移 - - # 确保坐标在范围内 - x1 = max(0, min(x1, width)) - y1 = max(0, min(y1, height)) - x2 = max(0, min(x2, width)) - y2 = max(0, min(y2, height)) - - if x1 >= x2 or y1 >= y2: - return False - - # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 - try: - from douyin.handlers import douyin_screenshot_manager - - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="attend_button", - step="before_detect", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={"region_size": f"{x2-x1}x{y2-y1}"}, - ) - if debug_path: - try: - import logging - - logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - # 采样检测点:检测大片红色区域 - red_count = 0 - step_x = max(1, (x2 - x1) // 15) - step_y = max(1, (y2 - y1) // 10) - - for y in range(y1, y2, step_y): - for x in range(x1, x2, step_x): - try: - r, g, b = pic_rgb.getpixel((x, y)) - # 检测红色:R值高,G和B相对较低 - if r > 200 and (r - g) > 50 and (r - b) > 50: - red_count += 1 - except Exception as e: # type: ignore[general-exception] - continue - - # 如果红色像素占比足够高(至少25%),认为有大片红色背景 - total_samples = len(list(range(y1, y2, step_y))) * len( - list(range(x1, x2, step_x)) - ) - if total_samples == 0: - return False - - red_ratio = red_count / total_samples if total_samples > 0 else 0 - # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 - if red_ratio_threshold is not None: - threshold = float(red_ratio_threshold) - elif analyser is not None: - try: - threshold = float( - getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - threshold = 0.25 - else: - threshold = 0.25 - result = red_ratio >= threshold - - # 如果请求详细信息,返回包含red_ratio的字典 - if return_info: - reason_value: Optional[str] = ( - None if result else "red_ratio_below_threshold" - ) - return result, { - "method": "pixel_detect", - "red_ratio": red_ratio, - "red_count": red_count, - "total_samples": total_samples, - "effective_threshold": threshold, - "reason": reason_value, - } - - # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 - # 无论成功失败都保存debug截图 - try: - from douyin.handlers import douyin_screenshot_manager - - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="attend_button", - step="detected" if result else "not_detected", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={ - "red_ratio": round(red_ratio, 4), - "red_count": red_count, - "total_samples": total_samples, - "threshold": threshold, - "result": "success" if result else "failed", - }, - ) - if debug_path: - try: - import logging - - logging.info( - "[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", - debug_path, - red_ratio, - threshold, - "success" if result else "failed", - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - return result - except Exception: - if return_info: - return False, { - "method": "pixel_detect", - "red_ratio": None, - "reason": "exception", - } - return False - - -def detect_fansclub_join_red_area( - pic_rgb: Image.Image, - return_info: bool = False, - red_ratio_threshold: float | None = None, - analyser: Any = None, -) -> bool | tuple[bool, dict]: - """检测粉丝团加入:大片红色区域。 - - 粉丝团加入按钮通常在屏幕中下部,有大片红色背景。 - 检测区域:(200,1940)-(880,2140) 基准1080x2400 - """ - try: - width, height = pic_rgb.size - # 缩放坐标到实际尺寸 - scale_x = width / 1080.0 - scale_y = height / 2400.0 - - # 检测区域(基准1080x2400) - x1 = int(200 * scale_x) - y1 = int(1940 * scale_y) - x2 = int(880 * scale_x) - y2 = int(2140 * scale_y) - - # 确保坐标在范围内 - x1 = max(0, min(x1, width)) - y1 = max(0, min(y1, height)) - x2 = max(0, min(x2, width)) - y2 = max(0, min(y2, height)) - - if x1 >= x2 or y1 >= y2: - if return_info: - return False, { - "method": "pixel_detect", - "red_ratio": None, - "reason": "invalid_region", - } - return False - - # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 - try: - from douyin.handlers import douyin_screenshot_manager - - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="fansclub_join", - step="before_detect", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={"region_size": f"{x2-x1}x{y2-y1}"}, - ) - if debug_path: - try: - import logging - - logging.info( - "[调试图像] 粉丝团加入检测前保存: %s", - debug_path, - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - # 采样检测点:检测大片红色区域 - red_count = 0 - step_x = max(1, (x2 - x1) // 15) - step_y = max(1, (y2 - y1) // 10) - - for y in range(y1, y2, step_y): - for x in range(x1, x2, step_x): - try: - r, g, b = pic_rgb.getpixel((x, y)) - # 检测红色:R值高,G和B相对较低 - if r > 200 and (r - g) > 50 and (r - b) > 50: - red_count += 1 - except Exception: - continue - - # 如果红色像素占比足够高(至少25%),认为有大片红色背景 - total_samples = len(list(range(y1, y2, step_y))) * len( - list(range(x1, x2, step_x)) - ) - if total_samples == 0: - if return_info: - return False, { - "method": "pixel_detect", - "red_ratio": None, - "reason": "no_samples", - } - return False - - red_ratio = red_count / total_samples if total_samples > 0 else 0 - # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 - if red_ratio_threshold is not None: - threshold = float(red_ratio_threshold) - elif analyser is not None: - try: - threshold = float( - getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - threshold = 0.25 - else: - threshold = 0.25 - result = red_ratio >= threshold - - # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 - try: - from douyin.handlers import douyin_screenshot_manager - - # 无论成功失败都保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="fansclub_join", - step="detected" if result else "not_detected", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={ - "red_ratio": round(red_ratio, 4), - "red_count": red_count, - "total_samples": total_samples, - "threshold": threshold, - "result": "success" if result else "failed", - }, - ) - if debug_path: - try: - import logging - - logging.info( - "[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", - debug_path, - red_ratio, - threshold, - "success" if result else "failed", - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - if return_info: - reason_value: Optional[str] = ( - None if result else "red_ratio_below_threshold" - ) - return result, { - "method": "pixel_detect", - "red_ratio": red_ratio, - "red_count": red_count, - "total_samples": total_samples, - "effective_threshold": threshold, - "reason": reason_value, - } - - return result - except Exception: - if return_info: - return False, { - "method": "pixel_detect", - "red_ratio": None, - "reason": "exception", - } - return False - - -def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: - """通过像素检测直播间图标区域的白色像素比例,判断是否在直播间。 - - 使用指定的多边形区域检测白色像素: - - 顶点坐标:基于1080x2400分辨率 - - 检测白色像素比例(RGB值都≥240) - - 阈值:白色像素比例≥0.8认为在直播间 - - 返回: - (detected, confidence) 其中 confidence 为置信度(0.0~1.0) - """ - try: - width, height = pic_rgb.size - # 缩放坐标到实际尺寸(基于1080x2400) - scale_x = width / 1080.0 - scale_y = height / 2400.0 - - # 多边形顶点坐标(基于1080x2400分辨率) - polygon_points = [ - (1002, 172), (999, 174), (1011, 186), (999, 199), - (1002, 202), (1013, 190), (1025, 201), (1028, 198), - (1017, 187), (1028, 174), (1025, 172), (1014, 184) - ] - - # 缩放到实际尺寸 - scaled_points = [(int(x * scale_x), int(y * scale_y)) for x, y in polygon_points] - - # 创建多边形mask - from PIL import ImageDraw - mask = Image.new('L', (width, height), 0) - draw = ImageDraw.Draw(mask) - draw.polygon(scaled_points, fill=255) - - # 转换为numpy数组进行高效计算 - import numpy as np - mask_array = np.array(mask) - img_array = np.array(pic_rgb) - - # 计算多边形内部的总像素数和白色像素数 - total_pixels = np.sum(mask_array > 0) - white_pixels = 0 - - if total_pixels > 0: - # 只检查多边形内部的像素 - for y in range(height): - for x in range(width): - if mask_array[y, x] > 0: # 在多边形内部 - r, g, b = img_array[y, x] - if r >= 240 and g >= 240 and b >= 240: # 白色阈值 - white_pixels += 1 - - white_ratio = white_pixels / total_pixels - else: - white_ratio = 0.0 - - # 判断是否在直播间:白色像素比例≥0.8 - detected = white_ratio >= 0.8 - confidence = white_ratio # 直接使用白色比例作为置信度 - - # 保存调试图像 - try: - from douyin.handlers import douyin_screenshot_manager - - # 计算多边形的边界框用于调试图像显示 - min_x = min(x for x, y in scaled_points) - max_x = max(x for x, y in scaled_points) - min_y = min(y for y, y in scaled_points) - max_y = max(y for y, y in scaled_points) - - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="pixel_detect", - picname="live_room_icons", - step="detected" if detected else "not_detected", - coords=(min_x, min_y, max_x, max_y), # 使用边界框 - extra_info={ - "white_ratio": round(white_ratio, 4), - "white_count": white_pixels, - "total_pixels": total_pixels, - "confidence": round(confidence, 4), - "result": "success" if detected else "failed", - "polygon_points": scaled_points, # 保存缩放后的多边形点 - }, - ) - if debug_path: - try: - import logging - logging.info( - "[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s", - debug_path, - white_ratio, - white_pixels, - total_pixels, - confidence, - "success" if detected else "failed", - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass - - return detected, confidence - except Exception as e: # type: ignore[general-exception] - return False, 0.0 - - -def detect_fudai_detail_page( - _pic_rgb: Image.Image, - _resolution_ratio_x: int = 1080, - _resolution_ratio_y: int = 2400, - _y_pianyi: int = 0, - _template_threshold: float = 0.7, - return_info: bool = False, - analyser: Any = None, -) -> bool | tuple[bool, dict]: - """检测是否处于福袋详情页。 - - 检测策略:任务数量检测 - 1. 通过检测任务数量来判断是否在福袋详情页 - 2. 如果任务数量 <= 0,则认为不在福袋详情页 - 3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量 - - 参数: - pic_rgb: RGB格式的整屏截图(保留用于兼容性,实际不使用) - resolution_ratio_x: 分辨率X比例(默认1080,保留用于兼容性) - resolution_ratio_y: 分辨率Y比例(默认2400,保留用于兼容性) - y_pianyi: Y轴偏移(默认0,保留用于兼容性) - template_threshold: 模板匹配阈值(保留用于兼容性,不再使用) - return_info: 是否返回详细信息(包含任务数量) - analyser: 分析器对象(必需,用于任务数量检测) - - 返回: - bool: 是否检测到福袋详情页(return_info=False时) - tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) - 详细信息包含: - - method: 检测方法("task_count") - - task_count: 任务数量(0/1/2/3) - """ - # ---------- 任务数量检测 ---------- - if analyser is None: - # analyser 参数必需 - if return_info: - return False, { - "method": "task_count", - "task_count": 0, - "reason": "analyser_required", - } - return False - - try: - from .douyin_detection import check_detail_height - - # 执行任务数量检测 - task_count = int(check_detail_height(analyser) or 0) - - # 判断是否在福袋详情页 - # 如果任务数量 <= 0,则认为不在福袋详情页 - # 如果任务数量 >= 1,则认为在福袋详情页 - is_in_detail = task_count >= 1 - - if return_info: - return is_in_detail, { - "method": "task_count", - "task_count": task_count, - } - return is_in_detail - except Exception as e: # type: ignore[general-exception] - # 检测异常 - if return_info: - return False, { - "method": "task_count", - "task_count": 0, - "reason": f"detection_exception: {str(e)}", - } - return False - - -def read_pixel_stage_state_from_screenshot( - pic_path: str, - resolution_ratio_x: int = 1080, - resolution_ratio_y: int = 2400, - y_pianyi: int = 0, - lucky_draw_red_ratio_threshold: float = 0.8, - fudai_template_threshold: float = 0.7, - return_details: bool = False, - analyser: Any = None, -) -> dict[str, bool] | tuple[dict[str, bool], dict[str, dict]]: - """从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。 - - 使用多线程并行执行所有检测函数以提高性能。 - - 参数: - pic_path: 截图路径 - resolution_ratio_x: 分辨率X比例(默认1080) - resolution_ratio_y: 分辨率Y比例(默认2400) - y_pianyi: Y轴偏移(默认0) - lucky_draw_red_ratio_threshold: 抽奖结果红色比例阈值(默认0.8) - fudai_template_threshold: 福袋详情模板匹配阈值(默认0.7) - return_details: 是否返回每个检测步骤的详细信息(包括分数) - - 返回: - dict[str, bool]: 检测结果(return_details=False时) - tuple[dict[str, bool], dict[str, dict]]: (检测结果, 详细信息)(return_details=True时) - """ - state: dict[str, bool] = { - "has_coupon_bg": False, - "has_redpacket_bg": False, - "has_lucky_draw_result": False, - "has_attend_button_red": False, - "has_fansclub_join_red": False, - "has_fudai_detail": False, - "has_live_room_pixel": False, # 直播间图标像素检测 - "has_live_room_template": False, # 直播间图标模板匹配 - } - details: dict[str, dict] = {} - - pic_rgb = _safe_open_screenshot_rgb(pic_path) - if pic_rgb is None: - if return_details: - return state, details - return state - - # 并行执行所有检测函数 - # 注意:优惠券检测需要额外参数,使用lambda包装 - # 注意:福袋详情检测使用任务数量检测,需要analyser参数 - # 从analyser读取阈值(如果可用) - coupon_threshold = None - attend_button_threshold = None - fansclub_threshold = None - live_room_pixel_threshold = None - if analyser is not None: - try: - coupon_threshold = float( - getattr(analyser, "coupon_template_match_threshold", None) or 0.75 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - attend_button_threshold = float( - getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - fansclub_threshold = float( - getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - live_room_pixel_threshold = float( - getattr(analyser, "live_room_match_threshold", None) or 0.8 - ) - except Exception as e: # type: ignore[general-exception] - pass - - # 定义直播间图标像素检测包装函数 - def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: - """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" - try: - detected, confidence = detect_live_room_icons_by_pixel(pic) - threshold = live_room_pixel_threshold or 0.8 - is_detected = detected and confidence >= threshold - return is_detected, { - "method": "pixel_detection", - "confidence": confidence, - "effective_threshold": threshold, - } - except Exception as e: # type: ignore[general-exception] - return False, {"method": "pixel_detection", "error": str(e)} - - # 定义直播间图标模板匹配包装函数 - - detection_tasks = { - "has_coupon_bg": lambda pic: detect_coupon_popup_background( - pic, - return_info=True, - template_threshold=coupon_threshold, - analyser=analyser, - ), - "has_redpacket_bg": detect_redpacket_popup_background, - "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( - pic, lucky_draw_red_ratio_threshold, return_info=True - ), - "has_attend_button_red": lambda pic: detect_attend_button_red_area( - pic, - return_info=True, - red_ratio_threshold=attend_button_threshold, - analyser=analyser, - ), - "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( - pic, - return_info=True, - red_ratio_threshold=fansclub_threshold, - analyser=analyser, - ), - "has_fudai_detail": lambda pic: detect_fudai_detail_page( - pic, - resolution_ratio_x, - resolution_ratio_y, - y_pianyi, - fudai_template_threshold, - return_info=True, - analyser=analyser, - ), - "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测 - } - - # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) - with ThreadPoolExecutor(max_workers=8) as executor: - # 提交所有任务 - future_to_key = { - executor.submit(detect_func, pic_rgb): key - for key, detect_func in detection_tasks.items() - } - - # 收集结果 - for future in as_completed(future_to_key): - key = future_to_key[future] - try: - result = future.result() - - # 处理结果 - if isinstance(result, tuple): - # 检测函数返回 (bool, dict) 格式 - is_detected, info = result - state[key] = bool(is_detected) - if return_details: - details[key] = { - "detected": bool(is_detected), - "method": info.get("method", "unknown"), - "template_score": info.get("template_score"), - "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) - "task_count": info.get("task_count"), # 添加task_count支持 - "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 - "effective_threshold": info.get("effective_threshold"), - "reason": info.get("reason"), - } - else: - # 其他检测返回 bool(不应该发生,因为所有检测都支持return_info) - state[key] = bool(result) - if return_details: - details[key] = { - "detected": bool(result), - "method": "unknown", - } - except Exception as e: # type: ignore[general-exception] - # 如果某个检测失败,保持默认值 False - state[key] = False - if return_details: - details[key] = { - "detected": False, - "error": str(e), - } - - if return_details: - return state, details - return state - coupon_threshold = float( - getattr(analyser, "coupon_template_match_threshold", None) or 0.75 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - attend_button_threshold = float( - getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - fansclub_threshold = float( - getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25 - ) - except Exception as e: # type: ignore[general-exception] - pass - try: - live_room_pixel_threshold = float( - getattr(analyser, "live_room_match_threshold", None) or 0.8 - ) - except Exception as e: # type: ignore[general-exception] - pass - - # 定义直播间图标像素检测包装函数 - def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: - """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" - try: - detected, confidence = detect_live_room_icons_by_pixel(pic) - threshold = live_room_pixel_threshold or 0.8 - is_detected = detected and confidence >= threshold - return is_detected, { - "method": "pixel_detection", - "confidence": confidence, - "effective_threshold": threshold, - } - except Exception as e: # type: ignore[general-exception] - return False, {"method": "pixel_detection", "error": str(e)} - - # 定义直播间图标模板匹配包装函数 - - detection_tasks = { - "has_coupon_bg": lambda pic: detect_coupon_popup_background( - pic, - return_info=True, - template_threshold=coupon_threshold, - analyser=analyser, - ), - "has_redpacket_bg": detect_redpacket_popup_background, - "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( - pic, lucky_draw_red_ratio_threshold, return_info=True - ), - "has_attend_button_red": lambda pic: detect_attend_button_red_area( - pic, - return_info=True, - red_ratio_threshold=attend_button_threshold, - analyser=analyser, - ), - "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( - pic, - return_info=True, - red_ratio_threshold=fansclub_threshold, - analyser=analyser, - ), - "has_fudai_detail": lambda pic: detect_fudai_detail_page( - pic, - resolution_ratio_x, - resolution_ratio_y, - y_pianyi, - fudai_template_threshold, - return_info=True, - analyser=analyser, - ), - "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测 - } - - # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) - with ThreadPoolExecutor(max_workers=8) as executor: - # 提交所有任务 - future_to_key = { - executor.submit(detect_func, pic_rgb): key - for key, detect_func in detection_tasks.items() - } - - # 收集结果 - for future in as_completed(future_to_key): - key = future_to_key[future] - try: - result = future.result() - - # 处理结果 - if isinstance(result, tuple): - # 检测函数返回 (bool, dict) 格式 - is_detected, info = result - state[key] = bool(is_detected) - if return_details: - details[key] = { - "detected": bool(is_detected), - "method": info.get("method", "unknown"), - "template_score": info.get("template_score"), - "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) - "task_count": info.get("task_count"), # 添加task_count支持 - "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 - "effective_threshold": info.get("effective_threshold"), - "reason": info.get("reason"), - } - else: - # 其他检测返回 bool(不应该发生,因为所有检测都支持return_info) - state[key] = bool(result) - if return_details: - details[key] = { - "detected": bool(result), - "method": "unknown", - } - except Exception as e: # type: ignore[general-exception] - # 如果某个检测失败,保持默认值 False - state[key] = False - if return_details: - details[key] = { - "detected": False, - "error": str(e), - } - - if return_details: - return state, details - return state \ No newline at end of file diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py deleted file mode 100644 index 4c3a743..0000000 --- a/douyin/fudai/finder/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -"""福袋查找器模块 - -本目录包含从 douyin_fudai_finder.py 模块化后的福袋查找器功能。 -""" - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后改为从子模块导入 -from ...fudai.douyin_fudai_finder import ( - FudaiImageAcquirer, - FudaiDetector, - FudaiClickExecutor, - FudaiDetailVerifier, - FudaiFinder, - check_have_fudai_with_ready_screenshot_optimized, -) - -__all__ = [ - "FudaiImageAcquirer", - "FudaiDetector", - "FudaiClickExecutor", - "FudaiDetailVerifier", - "FudaiFinder", - "check_have_fudai_with_ready_screenshot_optimized", -] diff --git a/douyin/other/douyin_stuck_guard.py b/douyin/other/douyin_stuck_guard.py deleted file mode 100644 index e69de29..0000000 diff --git a/douyin/stage/douyin_stage_handler.py.backup b/douyin/stage/douyin_stage_handler.py.backup deleted file mode 100644 index 9483699..0000000 --- a/douyin/stage/douyin_stage_handler.py.backup +++ /dev/null @@ -1,1332 +0,0 @@ -from __future__ import annotations - -""" -阶段处理模块 -============ - -职责:处理不同阶段的业务逻辑 -- 处理福袋详情页 -- 处理直播间福袋检测 -- 直播间图标检测 -""" - -import time -from typing import Any, Tuple, List, Optional - -from douyin.stage import douyin_stage -from douyin.fudai import douyin_fudai_detail -from douyin.fudai import douyin_fudai_core -from douyin.core import douyin_flow_control -from douyin.reservation import douyin_reservation_logic -from douyin.handlers import douyin_swipe_handler - - -class StageHandler: - """阶段处理器:统一管理阶段处理""" - - @staticmethod # type: ignore[misc] - def diagnose_stage_from_current_screen(analyser: Any) -> Tuple[str, str]: - """封装到子模块的阶段诊断入口。 - - 参数: - analyser: 分析器对象 - - 返回: - Tuple[str, str]: (阶段, 识别结果) - """ - result = douyin_stage.diagnose_stage_from_current_screen(analyser) - if result is None: - return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") - return result - - @staticmethod # type: ignore[misc] - def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: - """通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。 - - 参数: - analyser: 分析器对象 - - 返回: - Tuple[bool, float]: (detected, score) 其中 score 为匹配得分(0.0~1.0) - """ - # 为了兼容没有 cv2/numpy 的环境,这里做降级处理 - try: - import cv2 # type: ignore[import-untyped, attr-defined] - import numpy as np # type: ignore - import os - - # 抑制OpenCV的文件读取警告 - os.environ["OPENCV_LOG_LEVEL"] = "ERROR" - try: - cv2.setLogLevel(0) # type: ignore[attr-defined] # 0 = SILENT - except (AttributeError, Exception): - try: - if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"): - cv2.utils.logging.setLogLevel( # type: ignore[attr-defined] - cv2.utils.logging.LOG_LEVEL_SILENT # type: ignore[attr-defined] - ) - except Exception: - pass - try: - import logging - - logging.getLogger("cv2").setLevel(logging.ERROR) - except Exception: - pass - except Exception: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别", - ) - except Exception: - pass - return False, 0.0 - - base_dir = os.path.dirname(__file__) - - # 使用统一的模板路径配置 - try: - import path_config - assets_dir = path_config.get_assets_dir() - except Exception: - # 回退到旧路径(向后兼容) - assets_dir = os.path.join(base_dir, "assets") - - # 使用统一的截图路径配置 - try: - import path_config - screenshot_path = path_config.get_screenshot_path() - except Exception: - # 回退到旧路径(向后兼容) - pic_dir = os.path.join(base_dir, "pic") - screenshot_path = os.path.join(pic_dir, "screenshot.png") - - # 确保有最新截图 - try: - analyser.operation.get_screenshot(analyser.device_id) - except Exception as e: - # 记录截图获取失败,但不立即返回,继续检查文件是否存在 - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 获取截图失败", - error=str(e), - ) - except Exception: - pass - - # 如果预期路径不存在,尝试从其他可能的位置查找截图 - if not os.path.exists(screenshot_path): - # 尝试从项目根目录的 pic 目录查找 - try: - import path_config - alt_path = path_config.get_screenshot_path() - if os.path.exists(alt_path) and alt_path != screenshot_path: - # 如果找到备用路径,使用它 - screenshot_path = alt_path - except Exception: - pass - - # 如果仍然不存在,记录错误 - if not os.path.exists(screenshot_path): - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 截图不存在", - path=screenshot_path, - ) - except Exception: - pass - return False, 0.0 - - try: - # 同时读取灰度图和彩色图,灰度图用于模板匹配,彩色图用于颜色特征过滤 - img = cv2.imread( # type: ignore[attr-defined] - screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] - ) - img_color = cv2.imread( # type: ignore[attr-defined] - screenshot_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] - ) - if img is None or img_color is None: - raise RuntimeError("cv2.imread 返回 None") - except Exception as e: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e) - ) - except Exception: - pass - return False, 0.0 - - # 获取可配置的匹配阈值 - threshold = float( - getattr(analyser, "live_room_match_threshold", 0.8) or 0.8 - ) - template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90% - threshold = max(0.0, min(1.0, threshold)) - template_threshold = max(0.0, min(1.0, template_threshold)) - - # 第一步:裁剪右上角图标区域(使用固定坐标,基于1080x2400基准分辨率) - # 直播间图标区域:(972, 147) 到 (1047, 216) - 与像素检测区域一致 - ih, iw = img.shape[:2] - - # 基准分辨率 - base_width = 1080 - base_height = 2400 - - # 固定坐标(基于1080x2400) - base_x1 = 972 - base_y1 = 147 - base_x2 = 1047 - base_y2 = 216 - - # 缩放坐标到实际分辨率 - scale_x = iw / base_width - scale_y = ih / base_height - - roi_x1 = max(0, int(base_x1 * scale_x)) - roi_y1 = max(0, int(base_y1 * scale_y)) - roi_x2 = min(iw, int(base_x2 * scale_x)) - roi_y2 = min(ih, int(base_y2 * scale_y)) - - # 确保区域有效 - if roi_x1 >= roi_x2 or roi_y1 >= roi_y2: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon ROI区域无效", - roi_x1=roi_x1, roi_y1=roi_y1, roi_x2=roi_x2, roi_y2=roi_y2, - img_width=iw, img_height=ih - ) - except Exception: - pass - return False, 0.0 - - roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] - - # 同步裁剪彩色 ROI,用于后续颜色特征检测(白色比例等) - roi_color = None - try: - if img_color is not None: - roi_color = img_color[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] - except Exception: - roi_color = None - - if roi.size == 0: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon ROI区域为空" - ) - except Exception: - pass - return False, 0.0 - - # 保存裁剪的ROI区域 - # 使用统一的 pic 目录配置 - try: - import path_config - pic_dir = path_config.get_pic_dir() - except Exception: - # 回退到旧路径(向后兼容) - pic_dir = os.path.join(base_dir, "pic") - ocr_dir = os.path.join(pic_dir, "ocr") - os.makedirs(ocr_dir, exist_ok=True) - x_roi_path = os.path.join(ocr_dir, "xx.png") - xin_roi_path = os.path.join(ocr_dir, "xxin.png") - - try: - cv2.imwrite(x_roi_path, roi) # type: ignore[attr-defined] - cv2.imwrite(xin_roi_path, roi) # type: ignore[attr-defined] - except Exception as e: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e) - ) - except Exception: - pass - - # 第二步:使用模板匹配 - template_roi_pairs = [ - (os.path.join(assets_dir, "x.png"), x_roi_path, "x"), - (os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"), - ] - - best_score = 0.0 - best_name = "" - detected = False - - # 预计算颜色特征:白色像素比例(仅对 x 图标有效,用于过滤推荐页等误判) - # 直播间关闭 x 一般是“白色 x + 略暗背景”,因此需要一定的白色比例 - x_white_ratio = None - if roi_color is not None: - try: - roi_gray_for_white = cv2.cvtColor(roi_color, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined] - # 阈值 210:偏亮即视为白色像素 - _, white_bin = cv2.threshold( # type: ignore[attr-defined] - roi_gray_for_white, 210, 255, cv2.THRESH_BINARY # type: ignore[attr-defined] - ) - white_pixels = float((white_bin == 255).sum()) - total_pixels = float(white_bin.size or 1.0) - x_white_ratio = max(0.0, min(1.0, white_pixels / total_pixels)) - except Exception: - x_white_ratio = None - - for template_path, roi_path, icon_name in template_roi_pairs: - try: - # 调试日志:检查文件存在性 - template_exists = os.path.exists(template_path) and os.path.isfile(template_path) - roi_exists = os.path.exists(roi_path) and os.path.isfile(roi_path) - - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 检查文件", - icon_name=icon_name, - template_exists=template_exists, - template_path=template_path, - roi_exists=roi_exists, - roi_path=roi_path, - ) - except Exception: - pass - - if not template_exists: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 模板文件不存在", - icon_name=icon_name, - template_path=template_path, - ) - except Exception: - pass - continue - - try: - if os.path.getsize(template_path) == 0: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 模板文件为空", - icon_name=icon_name, - template_path=template_path, - ) - except Exception: - pass - continue - except (OSError, IOError): - continue - - if not roi_exists: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon ROI文件不存在", - icon_name=icon_name, - roi_path=roi_path, - ) - except Exception: - pass - continue - - try: - tpl = cv2.imread( # type: ignore[attr-defined] - template_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] - ) - roi_img = cv2.imread( # type: ignore[attr-defined] - roi_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] - ) - except Exception: - continue - - if tpl is None or roi_img is None: - continue - - # 图像预处理:根据图标类型选择不同的预处理方法 - # x图标:使用二值化+边缘检测(提高匹配准确性) - # xin图标:使用直方图均衡化(保持原有方法) - if icon_name == "x": - try: - # x图标特点:白色x在深灰色背景上,对比度明显 - # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) - # 先尝试多个阈值,选择最佳 - best_binary_score = 0.0 - best_binary_thresh = 160 - roi_binary_fixed = None - tpl_binary_fixed = None - - for thresh_val in [140, 160, 180, 200]: - try: - _, roi_bin = cv2.threshold(roi_img, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] - _, tpl_bin = cv2.threshold(tpl, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] - # 快速测试分数 - res_test = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) # type: ignore[attr-defined] - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res_test) # type: ignore[attr-defined] - if max_val > best_binary_score: - best_binary_score = max_val - best_binary_thresh = thresh_val - roi_binary_fixed = roi_bin - tpl_binary_fixed = tpl_bin - except: - continue - - # 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度) - roi_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] - roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] - ) - tpl_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] - tpl, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] - ) - - # 方法3:Otsu二值化(全局阈值) - _, roi_binary_otsu = cv2.threshold(roi_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] - _, tpl_binary_otsu = cv2.threshold(tpl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] - - # 方法4:边缘检测(Canny,针对白色x和深灰背景,调整参数) - # 降低低阈值以检测更多边缘,提高高阈值以减少噪声 - roi_edges = cv2.Canny(roi_img, 50, 150) # type: ignore[attr-defined] # 提高阈值,减少噪声 - tpl_edges = cv2.Canny(tpl, 50, 150) # type: ignore[attr-defined] - - # 方法5:边缘检测(更激进的参数,检测更多边缘) - roi_edges_aggressive = cv2.Canny(roi_img, 30, 80) # type: ignore[attr-defined] # 更低的阈值,检测更多边缘 - tpl_edges_aggressive = cv2.Canny(tpl, 30, 80) # type: ignore[attr-defined] - - # 方法6:形态学处理(去除噪声,增强边缘) - kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # type: ignore[attr-defined] - roi_edges_morph = cv2.morphologyEx(roi_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] - tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] - - # 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化) - if roi_binary_fixed is not None and tpl_binary_fixed is not None: - roi_img_enhanced = roi_binary_fixed - tpl_enhanced = tpl_binary_fixed - else: - # 回退到自适应二值化 - roi_img_enhanced = roi_binary_adaptive - tpl_enhanced = tpl_binary_adaptive - - # 保存所有预处理图像用于多方法匹配 - roi_binary_adaptive_backup = roi_binary_adaptive - tpl_binary_adaptive_backup = tpl_binary_adaptive - roi_binary_otsu_backup = roi_binary_otsu - tpl_binary_otsu_backup = tpl_binary_otsu - roi_edges_backup = roi_edges - tpl_edges_backup = tpl_edges - roi_edges_aggressive_backup = roi_edges_aggressive - tpl_edges_aggressive_backup = tpl_edges_aggressive - roi_edges_morph_backup = roi_edges_morph - tpl_edges_morph_backup = tpl_edges_morph - - # 方法7:强对比度增强(针对实际测试中表现较好的配置) - # alpha=2.0, beta=30:整体拉高对比度和亮度,突出白色 x - roi_contrast = cv2.convertScaleAbs(roi_img_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] - tpl_contrast = cv2.convertScaleAbs(tpl_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] - roi_contrast_backup = roi_contrast - tpl_contrast_backup = tpl_contrast - roi_edges_morph_backup = roi_edges_morph - tpl_edges_morph_backup = tpl_edges_morph - - use_edges = True # 标记使用边缘检测 - except Exception: - # 如果预处理失败,使用原图 - roi_img_enhanced = roi_img - tpl_enhanced = tpl - use_edges = False - else: - # xin图标:使用直方图均衡化(保持原有方法) - try: - # 直方图均衡化(增强对比度,提高匹配稳定性) - roi_img_enhanced = cv2.equalizeHist(roi_img) # type: ignore[attr-defined] - tpl_enhanced = cv2.equalizeHist(tpl) # type: ignore[attr-defined] - use_edges = False - except Exception: - # 如果预处理失败,使用原图 - roi_img_enhanced = roi_img - tpl_enhanced = tpl - use_edges = False - - th, tw = tpl_enhanced.shape[:2] - rh, rw = roi_img_enhanced.shape[:2] - - # 模板必须小于或等于ROI - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - if scale <= 0: - continue - tpl_enhanced = cv2.resize( # type: ignore[attr-defined] - tpl_enhanced, (max(1, int(tw * scale)), max(1, int(th * scale))) - ) - th, tw = tpl_enhanced.shape[:2] - - # 如果使用边缘检测,也需要缩放所有预处理模板 - if icon_name == "x" and use_edges: - try: - tpl_binary_adaptive_backup = cv2.resize( # type: ignore[attr-defined] - tpl_binary_adaptive_backup, (max(1, int(tw)), max(1, int(th))) - ) - tpl_binary_otsu_backup = cv2.resize( # type: ignore[attr-defined] - tpl_binary_otsu_backup, (max(1, int(tw)), max(1, int(th))) - ) - tpl_edges_backup = cv2.resize( # type: ignore[attr-defined] - tpl_edges_backup, (max(1, int(tw)), max(1, int(th))) - ) - tpl_edges_aggressive_backup = cv2.resize( # type: ignore[attr-defined] - tpl_edges_aggressive_backup, (max(1, int(tw)), max(1, int(th))) - ) - tpl_edges_morph_backup = cv2.resize( # type: ignore[attr-defined] - tpl_edges_morph_backup, (max(1, int(tw)), max(1, int(th))) - ) - except Exception: - pass - - # 多方法模板匹配,取最高分(提高稳定性) - scores = [] - - # 对于x图标,使用多种预处理方法进行匹配 - if icon_name == "x" and use_edges: - # x图标:方法1 - 固定阈值二值化匹配(针对白色x和深灰背景优化) - try: - res1_fixed = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1_fixed) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0))) - except Exception: - pass - - # x图标:方法2 - 自适应二值化匹配 - try: - res2_adaptive = cv2.matchTemplate( # type: ignore[attr-defined] - roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) - except Exception: - pass - - # x图标:方法3 - Otsu二值化匹配 - try: - res3_otsu = cv2.matchTemplate( # type: ignore[attr-defined] - roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) - except Exception: - pass - - # x图标:方法4 - 边缘检测匹配(标准参数) - try: - res4_edges = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) - except Exception: - pass - - # x图标:方法5 - 边缘检测匹配(激进参数) - try: - res5_edges_agg = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) - except Exception: - pass - - # x图标:方法6 - 形态学处理后的边缘检测匹配 - try: - res6_morph = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) - except Exception: - pass - - # x图标:方法7 - 强对比度 + TM_CCORR_NORMED(实验中表现较好) - try: - res7_contrast = cv2.matchTemplate( # type: ignore[attr-defined] - roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] - ) - _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) # type: ignore[attr-defined] - scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) - except Exception: - pass - - # x图标:方法8 - 原始图像匹配(作为对比和备用) - try: - res8_original = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) - except Exception: - pass - else: - # xin图标或其他:使用原有方法 - # 方法1: TM_CCOEFF_NORMED(归一化相关系数,对光照变化不敏感) - try: - res1 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) - except Exception: - pass - - # 方法2: TM_CCORR_NORMED(归一化相关,对亮度变化不敏感) - try: - res2 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) # type: ignore[attr-defined] - scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) - except Exception: - pass - - # 方法3: TM_SQDIFF_NORMED(归一化平方差,值越小越好,需要转换) - try: - res3 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED # type: ignore[attr-defined] - ) - min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) # type: ignore[attr-defined] - # 转换为相似度分数(1 - 归一化平方差) - score3 = 1.0 - float(min_val3 or 0.0) - scores.append(("TM_SQDIFF_NORMED", score3)) - except Exception: - pass - - # 选择最高分(如果多个方法都可用,使用加权平均) - if scores: - if icon_name == "x" and use_edges: - # x图标:优先使用最高分的方法,然后计算加权平均 - max_val = 0.0 - best_method = "" - - # 混合策略:优先使用 TM_CCOEFF_NORMED 系列,但如果分数太低,考虑使用 TM_CCORR_NORMED 系列 - # 1. 先找 TM_CCOEFF_NORMED 系列的最高分 - ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] - ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None - - # 2. 找 TM_CCORR_NORMED 系列的最高分 - ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] - ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None - - # 3. 决策:如果 CCOEFF 分数 >= 0.50,优先使用它(更稳定) - # 否则,如果 CCORR 分数 >= 0.75,使用它(需要根据白色比例调整颜色过滤阈值) - # 否则,使用 CCOEFF(即使分数低,也比误判好) - if ccoeff_max and ccoeff_max[1] >= 0.50: - best_method, max_val = ccoeff_max - elif ccorr_max and ccorr_max[1] >= 0.75: - # CCORR 分数较高,可以使用 - best_method, max_val = ccorr_max - elif ccoeff_max: - best_method, max_val = ccoeff_max - elif ccorr_max: - best_method, max_val = ccorr_max - else: - # 回退到最高分 - best_method, max_val = max(scores, key=lambda x: x[1]) - - # 如果多个方法都可用,计算加权平均(提高稳定性) - # 优先使用二值化方法的加权平均 - if len(scores) >= 2: - sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) - top_score = sorted_scores[0][1] - second_score = sorted_scores[1][1] - - # 如果最高分明显高于次高分(差距>0.15),使用最高分 - # 否则使用加权平均(最高分权重0.7,次高分权重0.3) - if top_score - second_score > 0.15: - max_val = top_score - best_method = sorted_scores[0][0] - else: - # 优先选择 TM_CCOEFF_NORMED 系列方法进行加权(避免 CCORR 系列误判) - ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] - if len(ccoeff_scores) >= 2: - max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 - best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" - elif len(ccoeff_scores) >= 1: - # 如果只有一个 CCOEFF 方法,用它和次高分加权 - max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 - best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" - else: - # 回退到二值化方法加权 - binary_scores = [s for s in sorted_scores if "二值化" in s[0]] - if len(binary_scores) >= 2: - max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 - best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" - else: - max_val = top_score * 0.7 + second_score * 0.3 - best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" - elif len(scores) == 1: - # 只有一个方法可用,直接使用 - best_method, max_val = scores[0] - else: - # xin图标或其他:使用原有逻辑 - # 优先使用 TM_CCOEFF_NORMED(最稳定) - max_val = 0.0 - best_method = "" - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - max_val = score - best_method = method - break - elif score > max_val: - max_val = score - best_method = method - - # 如果 TM_CCOEFF_NORMED 可用,使用它;否则使用最高分 - if best_method == "" and scores: - best_method, max_val = max(scores, key=lambda x: x[1]) - - # 如果多个方法都可用,计算加权平均(提高稳定性) - if len(scores) > 1: - # TM_CCOEFF_NORMED 权重最高(0.5),其他方法各0.25 - weighted_sum = 0.0 - total_weight = 0.0 - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - weight = 0.5 - else: - weight = 0.25 - weighted_sum += score * weight - total_weight += weight - if total_weight > 0: - max_val = weighted_sum / total_weight - else: - # 回退到原始方法 - res = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined] - max_val = float(max_val or 0.0) - best_method = "TM_CCOEFF_NORMED" - - # 对 x 图标额外应用颜色特征过滤:白色比例过低/过高都认为不是关闭按钮 - passed_color_filter = True - if icon_name == "x" and x_white_ratio is not None: - # 根据实际测试:直播间 x 图标的白色比例通常在 0.05~0.20 之间 - # 推荐页这类画面通常白色比例在 0.10~0.15 之间,但结合模板匹配分数可以区分 - # 如果白色比例过低(<0.05)或过高(>0.25),直接过滤 - # 如果白色比例在 0.10~0.15 之间,需要根据使用的匹配方法调整阈值 - if x_white_ratio < 0.05 or x_white_ratio > 0.25: - passed_color_filter = False - elif 0.10 <= x_white_ratio <= 0.15: - # 这个范围内的白色比例可能是推荐页,需要更高的模板匹配分数 - # 根据测试:推荐页分数约 0.8143,直播间分数约 0.76~0.86 - # 如果使用 TM_CCORR_NORMED 系列,需要 >= 0.82(推荐页 < 0.82,直播间 >= 0.82) - # 如果使用 TM_CCOEFF_NORMED 系列,需要 >= 0.50 - if "TM_CCORR_NORMED" in best_method: - if max_val < 0.82: - passed_color_filter = False - else: - if max_val < 0.50: - passed_color_filter = False - - if max_val > best_score and passed_color_filter: - best_score = float(max_val or 0.0) - best_name = ( - f"assets/{icon_name}.png -> " - f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png" - f" (方法:{best_method})" - ) - - if max_val >= template_threshold and passed_color_filter: - detected = True - except Exception: - continue - - if not detected and best_score == 0.0: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件" - ) - except Exception: - pass - - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 结果", - detected=int(bool(detected)), - score=round(best_score, 4), # 提高精度到4位小数 - template=best_name or "-", - threshold=round(template_threshold, 4), - 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, - 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", - ) - except Exception: - pass - - return bool(detected), float(best_score or 0.0) - - @staticmethod # type: ignore[misc] - def handle_in_fudai_detail(analyser: Any) -> None: - """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。 - - 参数: - analyser: 分析器对象 - """ - # 这个方法非常长,直接调用原方法,保持兼容性 - # 注意:由于方法过于复杂(900+行),暂时保持原实现 - # 后续可以进一步拆分 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - - @staticmethod # type: ignore[misc] - def handle_live_room_has_or_not_fudai(analyser: Any) -> None: - """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。 - - 参数: - analyser: 分析器对象 - """ - start_time = time.time() - # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) - try: - already_verified = bool( - getattr(analyser, "_fudai_detail_verified", False) or False - ) - if already_verified: - try: - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", - ) - except Exception: - pass - # 直接调用详情处理逻辑,不查找福袋 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(已验证详情页)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - - # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 - try: - now_ts = time.time() - focus_until = float( - getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 - ) - queue_full_waiting = bool( - getattr(analyser, "queue_full_waiting_at_earliest", False) or False - ) - - if focus_until > 0 and now_ts < focus_until and queue_full_waiting: - if analyser.reservations and len(analyser.reservations) > 0: - earliest = analyser.reservations[0] - try: - ft = float(earliest.get("future_ts") or 0.0) - if ft > 0: - join_ahead = float( - getattr( - analyser, "high_value_fudai_join_ahead_seconds", 120 - ) - or 120 - ) - poll_before = float( - getattr(analyser, "poll_before_open_seconds", 10.0) - or 10.0 - ) - time_window_start_ts = ft - join_ahead - time_window_end_ts = ft + max(0.0, poll_before) - - if now_ts < time_window_start_ts: - try: - analyser._log_kv( # type: ignore[attr-defined] - "预约", - "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", - focus_until=int(focus_until), - now_ts=int(now_ts), - time_window_start=int(time_window_start_ts), - remain_seconds=int( - time_window_start_ts - now_ts - ), - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - except Exception: - pass - - room_pos_ref: List[int] = [0] - opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) - if not opened: - # 无福袋,交给 flow_control 的"无福袋处理"逻辑 - try: - needswitch_cfg = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch_cfg = True - - wait_times_ref = [0] - swipe_times_ref = [0] - reservation_focus_until_ts_ref = [0.0] - reset_to_list_after_reservations_ref = [False] - douyin_flow_control.handle_no_fudai_situation( - analyser, - x=0, - swipe_times=0, - wait_times_ref=wait_times_ref, - needswitch=needswitch_cfg, - reservation_focus_until_ts=0.0, - reservations=[], - room_pos=room_pos_ref[0], - post_switch_delay_s=1.5, - swipe_up_switch_callback=analyser.swipe_up_to_next_live, # type: ignore[attr-defined] - swipe_down_back_callback=lambda: None, - sort_reservations_callback=lambda: None, - clear_reservations_callback=lambda: None, - write_state_callback=lambda: None, - back_to_list_callback=lambda: None, - into_list_callback=lambda: None, - reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, - reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, - swipe_times_ref=swipe_times_ref, - ) - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(无福袋)", - elapsed_seconds=round(elapsed, 2), - ) - return - - # 成功打开详情:调用同一套详情处理逻辑 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(成功打开详情)", - elapsed_seconds=round(elapsed, 2), - ) - - except Exception: - pass - - # x图标:方法2 - 自适应二值化匹配 - try: - res2_adaptive = cv2.matchTemplate( # type: ignore[attr-defined] - roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) - except Exception: - pass - - # x图标:方法3 - Otsu二值化匹配 - try: - res3_otsu = cv2.matchTemplate( # type: ignore[attr-defined] - roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) - except Exception: - pass - - # x图标:方法4 - 边缘检测匹配(标准参数) - try: - res4_edges = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) - except Exception: - pass - - # x图标:方法5 - 边缘检测匹配(激进参数) - try: - res5_edges_agg = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) - except Exception: - pass - - # x图标:方法6 - 形态学处理后的边缘检测匹配 - try: - res6_morph = cv2.matchTemplate( # type: ignore[attr-defined] - roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) - except Exception: - pass - - # x图标:方法7 - 强对比度 + TM_CCORR_NORMED(实验中表现较好) - try: - res7_contrast = cv2.matchTemplate( # type: ignore[attr-defined] - roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] - ) - _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) # type: ignore[attr-defined] - scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) - except Exception: - pass - - # x图标:方法8 - 原始图像匹配(作为对比和备用) - try: - res8_original = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) - except Exception: - pass - else: - # xin图标或其他:使用原有方法 - # 方法1: TM_CCOEFF_NORMED(归一化相关系数,对光照变化不敏感) - try: - res1 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) # type: ignore[attr-defined] - scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) - except Exception: - pass - - # 方法2: TM_CCORR_NORMED(归一化相关,对亮度变化不敏感) - try: - res2 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) # type: ignore[attr-defined] - scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) - except Exception: - pass - - # 方法3: TM_SQDIFF_NORMED(归一化平方差,值越小越好,需要转换) - try: - res3 = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED # type: ignore[attr-defined] - ) - min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) # type: ignore[attr-defined] - # 转换为相似度分数(1 - 归一化平方差) - score3 = 1.0 - float(min_val3 or 0.0) - scores.append(("TM_SQDIFF_NORMED", score3)) - except Exception: - pass - - # 选择最高分(如果多个方法都可用,使用加权平均) - if scores: - if icon_name == "x" and use_edges: - # x图标:优先使用最高分的方法,然后计算加权平均 - max_val = 0.0 - best_method = "" - - # 混合策略:优先使用 TM_CCOEFF_NORMED 系列,但如果分数太低,考虑使用 TM_CCORR_NORMED 系列 - # 1. 先找 TM_CCOEFF_NORMED 系列的最高分 - ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] - ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None - - # 2. 找 TM_CCORR_NORMED 系列的最高分 - ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] - ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None - - # 3. 决策:如果 CCOEFF 分数 >= 0.50,优先使用它(更稳定) - # 否则,如果 CCORR 分数 >= 0.75,使用它(需要根据白色比例调整颜色过滤阈值) - # 否则,使用 CCOEFF(即使分数低,也比误判好) - if ccoeff_max and ccoeff_max[1] >= 0.50: - best_method, max_val = ccoeff_max - elif ccorr_max and ccorr_max[1] >= 0.75: - # CCORR 分数较高,可以使用 - best_method, max_val = ccorr_max - elif ccoeff_max: - best_method, max_val = ccoeff_max - elif ccorr_max: - best_method, max_val = ccorr_max - else: - # 回退到最高分 - best_method, max_val = max(scores, key=lambda x: x[1]) - - # 如果多个方法都可用,计算加权平均(提高稳定性) - # 优先使用二值化方法的加权平均 - if len(scores) >= 2: - sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) - top_score = sorted_scores[0][1] - second_score = sorted_scores[1][1] - - # 如果最高分明显高于次高分(差距>0.15),使用最高分 - # 否则使用加权平均(最高分权重0.7,次高分权重0.3) - if top_score - second_score > 0.15: - max_val = top_score - best_method = sorted_scores[0][0] - else: - # 优先选择 TM_CCOEFF_NORMED 系列方法进行加权(避免 CCORR 系列误判) - ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] - if len(ccoeff_scores) >= 2: - max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 - best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" - elif len(ccoeff_scores) >= 1: - # 如果只有一个 CCOEFF 方法,用它和次高分加权 - max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 - best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" - else: - # 回退到二值化方法加权 - binary_scores = [s for s in sorted_scores if "二值化" in s[0]] - if len(binary_scores) >= 2: - max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 - best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" - else: - max_val = top_score * 0.7 + second_score * 0.3 - best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" - elif len(scores) == 1: - # 只有一个方法可用,直接使用 - best_method, max_val = scores[0] - else: - # xin图标或其他:使用原有逻辑 - # 优先使用 TM_CCOEFF_NORMED(最稳定) - max_val = 0.0 - best_method = "" - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - max_val = score - best_method = method - break - elif score > max_val: - max_val = score - best_method = method - - # 如果 TM_CCOEFF_NORMED 可用,使用它;否则使用最高分 - if best_method == "" and scores: - best_method, max_val = max(scores, key=lambda x: x[1]) - - # 如果多个方法都可用,计算加权平均(提高稳定性) - if len(scores) > 1: - # TM_CCOEFF_NORMED 权重最高(0.5),其他方法各0.25 - weighted_sum = 0.0 - total_weight = 0.0 - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - weight = 0.5 - else: - weight = 0.25 - weighted_sum += score * weight - total_weight += weight - if total_weight > 0: - max_val = weighted_sum / total_weight - else: - # 回退到原始方法 - res = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined] - max_val = float(max_val or 0.0) - best_method = "TM_CCOEFF_NORMED" - - # 对 x 图标额外应用颜色特征过滤:白色比例过低/过高都认为不是关闭按钮 - passed_color_filter = True - if icon_name == "x" and x_white_ratio is not None: - # 根据实际测试:直播间 x 图标的白色比例通常在 0.05~0.20 之间 - # 推荐页这类画面通常白色比例在 0.10~0.15 之间,但结合模板匹配分数可以区分 - # 如果白色比例过低(<0.05)或过高(>0.25),直接过滤 - # 如果白色比例在 0.10~0.15 之间,需要根据使用的匹配方法调整阈值 - if x_white_ratio < 0.05 or x_white_ratio > 0.25: - passed_color_filter = False - elif 0.10 <= x_white_ratio <= 0.15: - # 这个范围内的白色比例可能是推荐页,需要更高的模板匹配分数 - # 根据测试:推荐页分数约 0.8143,直播间分数约 0.76~0.86 - # 如果使用 TM_CCORR_NORMED 系列,需要 >= 0.82(推荐页 < 0.82,直播间 >= 0.82) - # 如果使用 TM_CCOEFF_NORMED 系列,需要 >= 0.50 - if "TM_CCORR_NORMED" in best_method: - if max_val < 0.82: - passed_color_filter = False - else: - if max_val < 0.50: - passed_color_filter = False - - if max_val > best_score and passed_color_filter: - best_score = float(max_val or 0.0) - best_name = ( - f"assets/{icon_name}.png -> " - f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png" - f" (方法:{best_method})" - ) - - if max_val >= template_threshold and passed_color_filter: - detected = True - except Exception: - continue - - if not detected and best_score == 0.0: - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件" - ) - except Exception: - pass - - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 结果", - detected=int(bool(detected)), - score=round(best_score, 4), # 提高精度到4位小数 - template=best_name or "-", - threshold=round(template_threshold, 4), - 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, - 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", - ) - except Exception: - pass - - return bool(detected), float(best_score or 0.0) - - @staticmethod # type: ignore[misc] - def handle_in_fudai_detail(analyser: Any) -> None: - """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。 - - 参数: - analyser: 分析器对象 - """ - # 这个方法非常长,直接调用原方法,保持兼容性 - # 注意:由于方法过于复杂(900+行),暂时保持原实现 - # 后续可以进一步拆分 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - - @staticmethod # type: ignore[misc] - def handle_live_room_has_or_not_fudai(analyser: Any) -> None: - """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。 - - 参数: - analyser: 分析器对象 - """ - start_time = time.time() - # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) - try: - already_verified = bool( - getattr(analyser, "_fudai_detail_verified", False) or False - ) - if already_verified: - try: - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", - ) - except Exception: - pass - # 直接调用详情处理逻辑,不查找福袋 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(已验证详情页)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - - # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 - try: - now_ts = time.time() - focus_until = float( - getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 - ) - queue_full_waiting = bool( - getattr(analyser, "queue_full_waiting_at_earliest", False) or False - ) - - if focus_until > 0 and now_ts < focus_until and queue_full_waiting: - if analyser.reservations and len(analyser.reservations) > 0: - earliest = analyser.reservations[0] - try: - ft = float(earliest.get("future_ts") or 0.0) - if ft > 0: - join_ahead = float( - getattr( - analyser, "high_value_fudai_join_ahead_seconds", 120 - ) - or 120 - ) - poll_before = float( - getattr(analyser, "poll_before_open_seconds", 10.0) - or 10.0 - ) - time_window_start_ts = ft - join_ahead - time_window_end_ts = ft + max(0.0, poll_before) - - if now_ts < time_window_start_ts: - try: - analyser._log_kv( # type: ignore[attr-defined] - "预约", - "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", - focus_until=int(focus_until), - now_ts=int(now_ts), - time_window_start=int(time_window_start_ts), - remain_seconds=int( - time_window_start_ts - now_ts - ), - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - except Exception: - pass - - room_pos_ref: List[int] = [0] - opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) - if not opened: - # 无福袋,交给 flow_control 的"无福袋处理"逻辑 - try: - needswitch_cfg = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch_cfg = True - - wait_times_ref = [0] - swipe_times_ref = [0] - reservation_focus_until_ts_ref = [0.0] - reset_to_list_after_reservations_ref = [False] - douyin_flow_control.handle_no_fudai_situation( - analyser, - x=0, - swipe_times=0, - wait_times_ref=wait_times_ref, - needswitch=needswitch_cfg, - reservation_focus_until_ts=0.0, - reservations=[], - room_pos=room_pos_ref[0], - post_switch_delay_s=1.5, - swipe_up_switch_callback=analyser.swipe_up_to_next_live, # type: ignore[attr-defined] - swipe_down_back_callback=lambda: None, - sort_reservations_callback=lambda: None, - clear_reservations_callback=lambda: None, - write_state_callback=lambda: None, - back_to_list_callback=lambda: None, - into_list_callback=lambda: None, - reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, - reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, - swipe_times_ref=swipe_times_ref, - ) - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(无福袋)", - elapsed_seconds=round(elapsed, 2), - ) - return - - # 成功打开详情:调用同一套详情处理逻辑 - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(成功打开详情)", - elapsed_seconds=round(elapsed, 2), - ) \ No newline at end of file diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py deleted file mode 100644 index a5928fa..0000000 --- a/gui/components/config_manager.py +++ /dev/null @@ -1,44 +0,0 @@ -"""配置管理组件 - -包含配置加载、保存等功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable -import tkinter as tk -from tkinter import ttk - -from gui.gui_core import read_config, write_config - - -def load_config_to_ui( - cfg: dict[str, Any], - vars_dict: dict[str, Any], - on_line: Callable[[str], None], -) -> None: - """从配置文件加载到UI变量。 - - 参数: - cfg: 配置字典 - vars_dict: UI变量字典 - on_line: 日志输出回调 - """ - # TODO: 实现配置加载逻辑 - # 临时从原文件导入 - pass - - -def save_ui_to_config( - vars_dict: dict[str, Any], - on_line: Callable[[str], None], -) -> None: - """将UI变量保存到配置文件。 - - 参数: - vars_dict: UI变量字典 - on_line: 日志输出回调 - """ - # TODO: 实现配置保存逻辑 - # 临时从原文件导入 - pass diff --git a/gui/components/high_value_rooms_display.py b/gui/components/high_value_rooms_display.py deleted file mode 100644 index e0902e9..0000000 --- a/gui/components/high_value_rooms_display.py +++ /dev/null @@ -1,42 +0,0 @@ -"""高价值房间显示组件 - -包含高价值房间显示和刷新功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable, Tuple -from tkinter.scrolledtext import ScrolledText - -try: - from ttkbootstrap.scrolled import ScrolledText as TBSrolledText - ScrolledText = TBSrolledText -except ImportError: - from tkinter.scrolledtext import ScrolledText - - -def create_high_value_rooms_display( - parent: Any -): - """创建高价值房间显示组件。 - - 参数: - parent: 父容器 - - 返回: - (high_value_text, refresh_high_value_rooms_func) - """ - high_value_text = ScrolledText(parent) - high_value_text.pack(fill="both", expand=True, padx=10, pady=10) - - try: - high_value_text.configure(font=("Consolas", 10)) - except Exception: - pass - - def refresh_high_value_rooms() -> None: - """刷新高价值房间。""" - # TODO: 从原文件迁移函数实现 - pass - - return high_value_text, refresh_high_value_rooms diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py deleted file mode 100644 index 7f66666..0000000 --- a/gui/components/image_viewer.py +++ /dev/null @@ -1,40 +0,0 @@ -"""图像查看组件 - -包含图像预览、列表等功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable -import os -import tkinter as tk -from tkinter import ttk -from PIL import Image, ImageTk - - -def create_image_viewer( - parent: Any, - on_line: Callable[[str], None], -) -> tuple[Any, Callable[[], None], Callable[[], None]]: - """创建图像查看器组件。 - - 参数: - parent: 父容器 - on_line: 日志输出回调 - - 返回: - (image_var, update_image_list_func, refresh_preview_func) - """ - image_var = tk.StringVar() - - def update_image_list(refresh_after: bool = True) -> None: - """更新图像列表。""" - # TODO: 从原文件迁移函数实现 - pass - - def refresh_preview() -> None: - """刷新图像预览。""" - # TODO: 从原文件迁移函数实现 - pass - - return image_var, update_image_list, refresh_preview diff --git a/gui/components/log_color_config.py.backup b/gui/components/log_color_config.py.backup deleted file mode 100644 index 47cf14b..0000000 --- a/gui/components/log_color_config.py.backup +++ /dev/null @@ -1,943 +0,0 @@ -""" -日志颜色配置模块 -================ - -为不同的操作类型定义颜色标签,支持明亮和暗色主题。 -""" - -from typing import Dict, Optional - - -# 操作类型关键词映射(用于识别日志中的操作类型) -OPERATION_KEYWORDS: Dict[str, list] = { - "ocr": [ - "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", - "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" - ], - "click": [ - "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", - "返回", "确认", "关闭", "发送", "加入" - ], - "swipe": [ - "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", - "回退", "切换直播间", "切换房间" - ], - "screenshot": [ - "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" - ], - "detection": [ - "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", - "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" - ], - "decision": [ - "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", - "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" - ], - "reservation": [ - "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", - "高价值预约", "预约回退", "预约校验" - ], - "fansclub": [ - "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" - ], - "lottery": [ - "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" - ], - "stage": [ - "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", - "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" - ], - "performance": [ - "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" - ], - "error": [ - "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" - ], - "success": [ - "成功", "SUCCESS", "完成", "完成", "已", "完成" - ], - "info": [ - "信息", "INFO", "提示", "注意", "开始", "启动", "停止" - ], - "flow": [ - "流程", "flow", "处理", "执行", "运行", "完成" - ], - "operation": [ - "操作", "operation", "动作", "行为" - ] -} - - -def get_operation_type(line: str) -> Optional[str]: - """ - 根据日志行内容识别操作类型 - - 日志格式通常是: [时间] [GUI] - 操作类型 内容 - 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) - - Args: - line: 日志行内容 - - Returns: - 操作类型名称,如果无法识别则返回None - """ - line_lower = line.lower() - - # 优先级1: 识别日志内容开头的操作类型(最精确) - # 日志格式: [时间] [GUI] - 操作类型 内容 - # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 - # [GUI] - 滑动上滑切换直播间 - # [GUI] - 阶段诊断开始阶段诊断 - # [GUI] - 预约[预约]记录直播间标题 - - import re - # 提取日志内容部分(去掉时间戳和标签) - # 匹配格式: [时间] [标签] - 内容 - content_match = re.search(r'\]\s*-\s*(.+)$', line) - if content_match: - content = content_match.group(1).strip() - content_lower = content.lower() - - # 操作类型关键词映射(按优先级排序,更具体的在前) - operation_type_map = [ - # 检测相关(最具体) - ("阶段诊断", "detection"), - ("阶段检测", "detection"), - ("并行检测", "detection"), - ("像素检测", "detection"), - ("模板匹配", "detection"), - ("检测", "detection"), - # 滑动相关 - ("滑动", "swipe"), - ("上滑", "swipe"), - ("下滑", "swipe"), - ("切换直播间", "swipe"), - # 预约相关 - ("预约", "reservation"), - # OCR相关 - ("OCR", "ocr"), - ("ocr识别", "ocr"), - ("识别", "ocr"), - # 点击相关 - ("点击", "click"), - # 截图相关 - ("截图", "screenshot"), - # 流程相关 - ("流程", "flow"), - # 决策相关 - ("决策", "decision"), - ("行为识别", "decision"), - # 开奖相关 - ("开奖", "lottery"), - ("抽奖结果", "lottery"), - # 粉丝团相关 - ("粉丝团", "fansclub"), - # 操作相关(通用,放后面) - ("操作", "operation"), - # 自救相关 - ("自救", "info"), - # 错误相关 - ("错误", "error"), - ("异常", "error"), - # 成功相关 - ("成功", "success"), - # 信息相关(最通用,放最后) - ("信息", "info"), - ] - - # 检查内容开头是否匹配操作类型 - for keyword, op_type in operation_type_map: - # 检查是否在内容开头(更精确) - if content_lower.startswith(keyword.lower()): - return op_type - # 或者检查是否紧跟在 " - " 后面 - if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: - return op_type - - # 优先级2: 使用日志标签识别(如果内容中没有匹配到) - tag_match = re.search(r'\[([^\]]+)\]', line) - if tag_match: - tag = tag_match.group(1).lower() - - # 标签到操作类型的映射(精确匹配) - tag_to_op_type = { - "阶段诊断": "detection", - "阶段检测": "detection", - "截图": "screenshot", - "ocr": "ocr", - "ocr识别": "ocr", - "点击": "click", - "滑动": "swipe", - "预约": "reservation", - "找福袋图标": "detection", - "福袋查找": "detection", - "自救": "info", - "流程": "flow", - "行为识别": "decision", - "决策": "decision", - "错误": "error", - "异常": "error", - "成功": "success", - "信息": "info", - "提示": "info", - } - - # 精确匹配标签 - if tag in tag_to_op_type: - return tag_to_op_type[tag] - - # 部分匹配标签(用于更灵活的匹配) - for tag_key, op_type in tag_to_op_type.items(): - if tag_key in tag or tag in tag_key: - return op_type - - # 优先级2: 使用关键词匹配(更具体的短语优先) - # 定义更具体的关键词短语(按优先级排序) - specific_patterns = [ - # 检测相关(更具体的短语优先) - ("阶段诊断", "detection"), - ("阶段检测", "detection"), - ("像素检测", "detection"), - ("模板匹配", "detection"), - ("并行检测", "detection"), - # OCR相关 - ("OCR识别", "ocr"), - ("OCR模式", "ocr"), - ("识别成功", "ocr"), - ("识别失败", "ocr"), - # 点击相关 - ("点击成功", "click"), - ("点击失败", "click"), - ("参与按钮", "click"), - # 滑动相关 - ("向上滑动", "swipe"), - ("向下滑动", "swipe"), - ("切换直播间", "swipe"), - # 预约相关 - ("记录预约", "reservation"), - ("预约窗口", "reservation"), - ("预约队列", "reservation"), - # 开奖相关 - ("抽奖结果", "lottery"), - ("等待开奖", "lottery"), - ("开奖时间", "lottery"), - # 粉丝团相关 - ("加入粉丝团", "fansclub"), - ("粉丝团失败", "fansclub"), - ("粉丝团成功", "fansclub"), - ] - - # 先检查更具体的短语 - for pattern, op_type in specific_patterns: - if pattern.lower() in line_lower: - return op_type - - # 优先级3: 使用通用关键词匹配(按操作类型优先级) - # 调整顺序,让更具体的操作类型优先 - priority_order = [ - "lottery", # 开奖相关(更具体) - "fansclub", # 粉丝团(更具体) - "reservation", # 预约(更具体) - "decision", # 决策(更具体) - "detection", # 检测(较具体) - "ocr", # OCR(较具体) - "click", # 点击(较具体) - "swipe", # 滑动(较具体) - "flow", # 流程(较具体) - "operation", # 操作(较具体) - "screenshot", # 截图(较通用,放后面) - "stage", # 阶段(较通用) - "performance", # 性能(较通用) - "error", # 错误(较通用) - "success", # 成功(较通用) - "info", # 信息(最通用,放最后) - ] - - # 按优先级顺序检查 - for op_type in priority_order: - if op_type in OPERATION_KEYWORDS: - for keyword in OPERATION_KEYWORDS[op_type]: - # 避免过于宽泛的关键词误匹配 - if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]: - # 这些关键词太宽泛,只在特定上下文中使用 - # 检查是否在更具体的上下文中 - if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line): - return op_type - elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower): - return op_type - elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower): - return op_type - # 其他宽泛关键词跳过,避免误匹配 - continue - - if keyword.lower() in line_lower: - return op_type - - return None - - -def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: - """ - 获取颜色配置(根据主题) - - Args: - theme: 主题名称("litera", "darkly" 等) - - Returns: - 颜色配置字典,包含每种操作类型的颜色设置 - """ - light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} - is_light = theme.lower() in light_themes - - if is_light: - # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) - return { - "ocr": { - "foreground": "#0052CC", # 鲜明蓝色 - OCR识别 - "background": "#D6E8FF", # 浅蓝色背景 - }, - "click": { - "foreground": "#D32F2F", # 鲜明红色 - 点击操作 - "background": "#FFE0E0", # 浅红色背景 - }, - "swipe": { - "foreground": "#2E7D32", # 鲜明绿色 - 滑动操作 - "background": "#E0F2E8", # 浅绿色背景 - }, - "screenshot": { - "foreground": "#7B1FA2", # 鲜明紫色 - 截图操作 - "background": "#F3E5F5", # 浅紫色背景 - }, - "detection": { - "foreground": "#F57C00", # 鲜明橙色 - 检测操作 - "background": "#FFF3E0", # 浅橙色背景 - }, - "decision": { - "foreground": "#C2185B", # 鲜明品红色 - 决策操作 - "background": "#FCE4EC", # 浅品红色背景 - }, - "reservation": { - "foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色) - "background": "#E0F2F1", # 浅青色背景 - }, - "fansclub": { - "foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色) - "background": "#F3E5F5", # 浅紫红色背景 - }, - "lottery": { - "foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色) - "background": "#FFEBEE", # 浅橙红色背景 - }, - "stage": { - "foreground": "#616161", # 深灰色 - 阶段信息 - "background": "#F5F5F5", # 浅灰色背景 - }, - "performance": { - "foreground": "#00796B", # 鲜明青绿色 - 性能信息 - "background": "#E0F2F1", # 浅青绿色背景 - }, - "error": { - "foreground": "#C62828", # 鲜明深红色 - 错误 - "background": "#FFCDD2", # 浅红色背景 - }, - "success": { - "foreground": "#2E7D32", # 鲜明深绿色 - 成功 - "background": "#C8E6C9", # 浅绿色背景 - }, - "info": { - "foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色) - "background": "#BBDEFB", # 浅天蓝色背景 - }, - "flow": { - "foreground": "#5D4037", # 深棕色 - 流程操作 - "background": "#EFEBE9", # 浅棕色背景 - }, - "operation": { - "foreground": "#455A64", # 深蓝灰色 - 操作动作 - "background": "#ECEFF1", # 浅蓝灰色背景 - }, - } - else: - # 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度) - return { - "ocr": { - "foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别 - "background": "#0D47A1", # 深蓝色背景 - }, - "click": { - "foreground": "#EF5350", # 鲜明亮红色 - 点击操作 - "background": "#B71C1C", # 深红色背景 - }, - "swipe": { - "foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作 - "background": "#1B5E20", # 深绿色背景 - }, - "screenshot": { - "foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作 - "background": "#4A148C", # 深紫色背景 - }, - "detection": { - "foreground": "#FFA726", # 鲜明亮橙色 - 检测操作 - "background": "#E65100", # 深橙色背景 - }, - "decision": { - "foreground": "#EC407A", # 鲜明亮品红色 - 决策操作 - "background": "#880E4F", # 深品红色背景 - }, - "reservation": { - "foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色) - "background": "#004D40", # 深青色背景 - }, - "fansclub": { - "foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色) - "background": "#4A148C", # 深紫红色背景 - }, - "lottery": { - "foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色) - "background": "#BF360C", # 深橙红色背景 - }, - "stage": { - "foreground": "#90A4AE", # 亮灰色 - 阶段信息 - "background": "#263238", # 深灰色背景 - }, - "performance": { - "foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息 - "background": "#004D40", # 深青绿色背景 - }, - "error": { - "foreground": "#F44336", # 鲜明亮红色 - 错误 - "background": "#B71C1C", # 深红色背景 - }, - "success": { - "foreground": "#66BB6A", # 鲜明亮绿色 - 成功 - "background": "#1B5E20", # 深绿色背景 - }, - "info": { - "foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色) - "background": "#01579B", # 深天蓝色背景 - }, - "flow": { - "foreground": "#A1887F", # 亮棕色 - 流程操作 - "background": "#3E2723", # 深棕色背景 - }, - "operation": { - "foreground": "#78909C", # 亮蓝灰色 - 操作动作 - "background": "#263238", # 深蓝灰色背景 - }, - } - - -def apply_operation_color( - text_widget, - start_pos: str, - end_pos: str, - line: str, - theme: str = "litera" -) -> None: - """ - 为日志行应用操作类型颜色 - - Args: - text_widget: tkinter Text 组件 - start_pos: 起始位置 - end_pos: 结束位置 - line: 日志行内容 - theme: 主题名称 - """ - try: - # 识别操作类型 - op_type = get_operation_type(line) - if not op_type: - return - - # 获取颜色配置 - color_config = get_color_config(theme) - if op_type not in color_config: - return - - colors = color_config[op_type] - tag_name = f"op_{op_type}" - - # 配置标签(总是重新配置,确保主题改变时颜色也会更新) - text_widget.tag_configure( - tag_name, - foreground=colors["foreground"], - background=colors["background"], - ) - - # 应用标签 - text_widget.tag_add(tag_name, start_pos, end_pos) - except Exception: - # 忽略颜色应用失败,不影响日志显示 - pass - - -""" -为不同的操作类型定义颜色标签,支持明亮和暗色主题。 -""" - -from typing import Dict, Optional - - -# 操作类型关键词映射(用于识别日志中的操作类型) -OPERATION_KEYWORDS: Dict[str, list] = { - "ocr": [ - "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", - "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" - ], - "click": [ - "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", - "返回", "确认", "关闭", "发送", "加入" - ], - "swipe": [ - "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", - "回退", "切换直播间", "切换房间" - ], - "screenshot": [ - "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" - ], - "detection": [ - "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", - "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" - ], - "decision": [ - "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", - "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" - ], - "reservation": [ - "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", - "高价值预约", "预约回退", "预约校验" - ], - "fansclub": [ - "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" - ], - "lottery": [ - "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" - ], - "stage": [ - "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", - "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" - ], - "performance": [ - "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" - ], - "error": [ - "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" - ], - "success": [ - "成功", "SUCCESS", "完成", "完成", "已", "完成" - ], - "info": [ - "信息", "INFO", "提示", "注意", "开始", "启动", "停止" - ], - "flow": [ - "流程", "flow", "处理", "执行", "运行", "完成" - ], - "operation": [ - "操作", "operation", "动作", "行为" - ] -} - - -def get_operation_type(line: str) -> Optional[str]: - """ - 根据日志行内容识别操作类型 - - 日志格式通常是: [时间] [GUI] - 操作类型 内容 - 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) - - Args: - line: 日志行内容 - - Returns: - 操作类型名称,如果无法识别则返回None - """ - line_lower = line.lower() - - # 优先级1: 识别日志内容开头的操作类型(最精确) - # 日志格式: [时间] [GUI] - 操作类型 内容 - # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 - # [GUI] - 滑动上滑切换直播间 - # [GUI] - 阶段诊断开始阶段诊断 - # [GUI] - 预约[预约]记录直播间标题 - - import re - # 提取日志内容部分(去掉时间戳和标签) - # 匹配格式: [时间] [标签] - 内容 - content_match = re.search(r'\]\s*-\s*(.+)$', line) - if content_match: - content = content_match.group(1).strip() - content_lower = content.lower() - - # 操作类型关键词映射(按优先级排序,更具体的在前) - operation_type_map = [ - # 检测相关(最具体) - ("阶段诊断", "detection"), - ("阶段检测", "detection"), - ("并行检测", "detection"), - ("像素检测", "detection"), - ("模板匹配", "detection"), - ("检测", "detection"), - # 滑动相关 - ("滑动", "swipe"), - ("上滑", "swipe"), - ("下滑", "swipe"), - ("切换直播间", "swipe"), - # 预约相关 - ("预约", "reservation"), - # OCR相关 - ("OCR", "ocr"), - ("ocr识别", "ocr"), - ("识别", "ocr"), - # 点击相关 - ("点击", "click"), - # 截图相关 - ("截图", "screenshot"), - # 流程相关 - ("流程", "flow"), - # 决策相关 - ("决策", "decision"), - ("行为识别", "decision"), - # 开奖相关 - ("开奖", "lottery"), - ("抽奖结果", "lottery"), - # 粉丝团相关 - ("粉丝团", "fansclub"), - # 操作相关(通用,放后面) - ("操作", "operation"), - # 自救相关 - ("自救", "info"), - # 错误相关 - ("错误", "error"), - ("异常", "error"), - # 成功相关 - ("成功", "success"), - # 信息相关(最通用,放最后) - ("信息", "info"), - ] - - # 检查内容开头是否匹配操作类型 - for keyword, op_type in operation_type_map: - # 检查是否在内容开头(更精确) - if content_lower.startswith(keyword.lower()): - return op_type - # 或者检查是否紧跟在 " - " 后面 - if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: - return op_type - - # 优先级2: 使用日志标签识别(如果内容中没有匹配到) - tag_match = re.search(r'\[([^\]]+)\]', line) - if tag_match: - tag = tag_match.group(1).lower() - - # 标签到操作类型的映射(精确匹配) - tag_to_op_type = { - "阶段诊断": "detection", - "阶段检测": "detection", - "截图": "screenshot", - "ocr": "ocr", - "ocr识别": "ocr", - "点击": "click", - "滑动": "swipe", - "预约": "reservation", - "找福袋图标": "detection", - "福袋查找": "detection", - "自救": "info", - "流程": "flow", - "行为识别": "decision", - "决策": "decision", - "错误": "error", - "异常": "error", - "成功": "success", - "信息": "info", - "提示": "info", - } - - # 精确匹配标签 - if tag in tag_to_op_type: - return tag_to_op_type[tag] - - # 部分匹配标签(用于更灵活的匹配) - for tag_key, op_type in tag_to_op_type.items(): - if tag_key in tag or tag in tag_key: - return op_type - - # 优先级2: 使用关键词匹配(更具体的短语优先) - # 定义更具体的关键词短语(按优先级排序) - specific_patterns = [ - # 检测相关(更具体的短语优先) - ("阶段诊断", "detection"), - ("阶段检测", "detection"), - ("像素检测", "detection"), - ("模板匹配", "detection"), - ("并行检测", "detection"), - # OCR相关 - ("OCR识别", "ocr"), - ("OCR模式", "ocr"), - ("识别成功", "ocr"), - ("识别失败", "ocr"), - # 点击相关 - ("点击成功", "click"), - ("点击失败", "click"), - ("参与按钮", "click"), - # 滑动相关 - ("向上滑动", "swipe"), - ("向下滑动", "swipe"), - ("切换直播间", "swipe"), - # 预约相关 - ("记录预约", "reservation"), - ("预约窗口", "reservation"), - ("预约队列", "reservation"), - # 开奖相关 - ("抽奖结果", "lottery"), - ("等待开奖", "lottery"), - ("开奖时间", "lottery"), - # 粉丝团相关 - ("加入粉丝团", "fansclub"), - ("粉丝团失败", "fansclub"), - ("粉丝团成功", "fansclub"), - ] - - # 先检查更具体的短语 - for pattern, op_type in specific_patterns: - if pattern.lower() in line_lower: - return op_type - - # 优先级3: 使用通用关键词匹配(按操作类型优先级) - # 调整顺序,让更具体的操作类型优先 - priority_order = [ - "lottery", # 开奖相关(更具体) - "fansclub", # 粉丝团(更具体) - "reservation", # 预约(更具体) - "decision", # 决策(更具体) - "detection", # 检测(较具体) - "ocr", # OCR(较具体) - "click", # 点击(较具体) - "swipe", # 滑动(较具体) - "flow", # 流程(较具体) - "operation", # 操作(较具体) - "screenshot", # 截图(较通用,放后面) - "stage", # 阶段(较通用) - "performance", # 性能(较通用) - "error", # 错误(较通用) - "success", # 成功(较通用) - "info", # 信息(最通用,放最后) - ] - - # 按优先级顺序检查 - for op_type in priority_order: - if op_type in OPERATION_KEYWORDS: - for keyword in OPERATION_KEYWORDS[op_type]: - # 避免过于宽泛的关键词误匹配 - if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]: - # 这些关键词太宽泛,只在特定上下文中使用 - # 检查是否在更具体的上下文中 - if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line): - return op_type - elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower): - return op_type - elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower): - return op_type - # 其他宽泛关键词跳过,避免误匹配 - continue - - if keyword.lower() in line_lower: - return op_type - - return None - - -def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: - """ - 获取颜色配置(根据主题) - - Args: - theme: 主题名称("litera", "darkly" 等) - - Returns: - 颜色配置字典,包含每种操作类型的颜色设置 - """ - light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} - is_light = theme.lower() in light_themes - - if is_light: - # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) - return { - "ocr": { - "foreground": "#0052CC", # 鲜明蓝色 - OCR识别 - "background": "#D6E8FF", # 浅蓝色背景 - }, - "click": { - "foreground": "#D32F2F", # 鲜明红色 - 点击操作 - "background": "#FFE0E0", # 浅红色背景 - }, - "swipe": { - "foreground": "#2E7D32", # 鲜明绿色 - 滑动操作 - "background": "#E0F2E8", # 浅绿色背景 - }, - "screenshot": { - "foreground": "#7B1FA2", # 鲜明紫色 - 截图操作 - "background": "#F3E5F5", # 浅紫色背景 - }, - "detection": { - "foreground": "#F57C00", # 鲜明橙色 - 检测操作 - "background": "#FFF3E0", # 浅橙色背景 - }, - "decision": { - "foreground": "#C2185B", # 鲜明品红色 - 决策操作 - "background": "#FCE4EC", # 浅品红色背景 - }, - "reservation": { - "foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色) - "background": "#E0F2F1", # 浅青色背景 - }, - "fansclub": { - "foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色) - "background": "#F3E5F5", # 浅紫红色背景 - }, - "lottery": { - "foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色) - "background": "#FFEBEE", # 浅橙红色背景 - }, - "stage": { - "foreground": "#616161", # 深灰色 - 阶段信息 - "background": "#F5F5F5", # 浅灰色背景 - }, - "performance": { - "foreground": "#00796B", # 鲜明青绿色 - 性能信息 - "background": "#E0F2F1", # 浅青绿色背景 - }, - "error": { - "foreground": "#C62828", # 鲜明深红色 - 错误 - "background": "#FFCDD2", # 浅红色背景 - }, - "success": { - "foreground": "#2E7D32", # 鲜明深绿色 - 成功 - "background": "#C8E6C9", # 浅绿色背景 - }, - "info": { - "foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色) - "background": "#BBDEFB", # 浅天蓝色背景 - }, - "flow": { - "foreground": "#5D4037", # 深棕色 - 流程操作 - "background": "#EFEBE9", # 浅棕色背景 - }, - "operation": { - "foreground": "#455A64", # 深蓝灰色 - 操作动作 - "background": "#ECEFF1", # 浅蓝灰色背景 - }, - } - else: - # 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度) - return { - "ocr": { - "foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别 - "background": "#0D47A1", # 深蓝色背景 - }, - "click": { - "foreground": "#EF5350", # 鲜明亮红色 - 点击操作 - "background": "#B71C1C", # 深红色背景 - }, - "swipe": { - "foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作 - "background": "#1B5E20", # 深绿色背景 - }, - "screenshot": { - "foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作 - "background": "#4A148C", # 深紫色背景 - }, - "detection": { - "foreground": "#FFA726", # 鲜明亮橙色 - 检测操作 - "background": "#E65100", # 深橙色背景 - }, - "decision": { - "foreground": "#EC407A", # 鲜明亮品红色 - 决策操作 - "background": "#880E4F", # 深品红色背景 - }, - "reservation": { - "foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色) - "background": "#004D40", # 深青色背景 - }, - "fansclub": { - "foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色) - "background": "#4A148C", # 深紫红色背景 - }, - "lottery": { - "foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色) - "background": "#BF360C", # 深橙红色背景 - }, - "stage": { - "foreground": "#90A4AE", # 亮灰色 - 阶段信息 - "background": "#263238", # 深灰色背景 - }, - "performance": { - "foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息 - "background": "#004D40", # 深青绿色背景 - }, - "error": { - "foreground": "#F44336", # 鲜明亮红色 - 错误 - "background": "#B71C1C", # 深红色背景 - }, - "success": { - "foreground": "#66BB6A", # 鲜明亮绿色 - 成功 - "background": "#1B5E20", # 深绿色背景 - }, - "info": { - "foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色) - "background": "#01579B", # 深天蓝色背景 - }, - "flow": { - "foreground": "#A1887F", # 亮棕色 - 流程操作 - "background": "#3E2723", # 深棕色背景 - }, - "operation": { - "foreground": "#78909C", # 亮蓝灰色 - 操作动作 - "background": "#263238", # 深蓝灰色背景 - }, - } - - -def apply_operation_color( - text_widget, - start_pos: str, - end_pos: str, - line: str, - theme: str = "litera" -) -> None: - """ - 为日志行应用操作类型颜色 - - Args: - text_widget: tkinter Text 组件 - start_pos: 起始位置 - end_pos: 结束位置 - line: 日志行内容 - theme: 主题名称 - """ - try: - # 识别操作类型 - op_type = get_operation_type(line) - if not op_type: - return - - # 获取颜色配置 - color_config = get_color_config(theme) - if op_type not in color_config: - return - - colors = color_config[op_type] - tag_name = f"op_{op_type}" - - # 配置标签(总是重新配置,确保主题改变时颜色也会更新) - text_widget.tag_configure( - tag_name, - foreground=colors["foreground"], - background=colors["background"], - ) - - # 应用标签 - text_widget.tag_add(tag_name, start_pos, end_pos) - except Exception: - # 忽略颜色应用失败,不影响日志显示 - pass \ No newline at end of file diff --git a/gui/components/main_window.py b/gui/components/main_window.py deleted file mode 100644 index 3d7c1ec..0000000 --- a/gui/components/main_window.py +++ /dev/null @@ -1,36 +0,0 @@ -"""主窗口组件 - -包含主窗口布局和事件绑定的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable -import tkinter as tk -from tkinter import ttk - - -def create_main_window( - title: str = "抖音福袋挂机 - 可视化控制台", - geometry: str = "1400x900", -) -> Any: - """创建主窗口。 - - 参数: - title: 窗口标题 - geometry: 窗口尺寸 - - 返回: - root窗口对象 - """ - # ttkbootstrap 优先(更美观);没装则回退到原生 tkinter - try: - import ttkbootstrap as tb - root = tb.Window(themename="darkly") - except Exception: - root = tk.Tk() - - root.title(title) - root.geometry(geometry) - - return root diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py deleted file mode 100644 index d4bc3f6..0000000 --- a/gui/components/ocr_panel.py +++ /dev/null @@ -1,37 +0,0 @@ -"""OCR面板组件 - -包含OCR区域配置、截图OCR等功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable -import tkinter as tk -from tkinter import ttk - - -def create_ocr_panel( - parent: Any, - device_var: tk.StringVar, - y_var: tk.IntVar, - on_line: Callable[[str], None], -) -> tuple[Any, Callable[[], None]]: - """创建OCR面板组件。 - - 参数: - parent: 父容器 - device_var: 设备ID变量 - y_var: Y偏移变量 - on_line: 日志输出回调 - - 返回: - (ocr_results_var, do_screenshot_func) - """ - ocr_results_var = {"results": []} - - def do_screenshot() -> None: - """执行截图和OCR识别。""" - # TODO: 从原文件迁移函数实现 - pass - - return ocr_results_var, do_screenshot diff --git a/gui/components/reservation_display.py b/gui/components/reservation_display.py deleted file mode 100644 index a26b644..0000000 --- a/gui/components/reservation_display.py +++ /dev/null @@ -1,42 +0,0 @@ -"""预约显示组件 - -包含预约队列显示和刷新功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable, Tuple -from tkinter.scrolledtext import ScrolledText - -try: - from ttkbootstrap.scrolled import ScrolledText as TBSrolledText - ScrolledText = TBSrolledText -except ImportError: - from tkinter.scrolledtext import ScrolledText - - -def create_reservation_display( - parent: Any -): - """创建预约显示组件。 - - 参数: - parent: 父容器 - - 返回: - (reservation_text, refresh_reservations_func) - """ - reservation_text = ScrolledText(parent) - reservation_text.pack(fill="both", expand=True, padx=10, pady=10) - - try: - reservation_text.configure(font=("Consolas", 10)) - except Exception: - pass - - def refresh_reservations() -> None: - """刷新预约队列。""" - # TODO: 从原文件迁移函数实现 - pass - - return reservation_text, refresh_reservations diff --git a/gui/components/stats_display.py b/gui/components/stats_display.py deleted file mode 100644 index 1a2614d..0000000 --- a/gui/components/stats_display.py +++ /dev/null @@ -1,46 +0,0 @@ -"""统计显示组件 - -包含统计信息显示和刷新功能的GUI组件。 -""" - -from __future__ import annotations - -from typing import Any, Callable, Tuple -from tkinter.scrolledtext import ScrolledText - -try: - from ttkbootstrap.scrolled import ScrolledText as TBSrolledText - ScrolledText = TBSrolledText -except ImportError: - from tkinter.scrolledtext import ScrolledText - - -def create_stats_display( - parent: Any, - runner: Any, - status_var: Any -): - """创建统计显示组件。 - - 参数: - parent: 父容器 - runner: 运行器对象 - status_var: 状态变量 - - 返回: - (stats_text, refresh_stats_func) 统计文本框和刷新函数 - """ - stats_text = ScrolledText(parent) - stats_text.pack(fill="both", expand=True, padx=10, pady=10) - - try: - stats_text.configure(font=("Consolas", 10)) - except Exception: - pass - - def refresh_stats() -> None: - """刷新统计信息。""" - # TODO: 从原文件迁移函数实现 - pass - - return stats_text, refresh_stats diff --git a/gui/web_components/http_handler.py b/gui/web_components/http_handler.py deleted file mode 100644 index 27b8f34..0000000 --- a/gui/web_components/http_handler.py +++ /dev/null @@ -1,12 +0,0 @@ -"""HTTP请求处理器组件 - -包含HTTP请求处理和路由功能。 -""" - -from __future__ import annotations - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后,移除此导入并在此文件中实现 -from gui.web_gui import Handler - -__all__ = ["Handler"] diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py deleted file mode 100644 index 6e4a5d0..0000000 --- a/gui/web_components/proc_runner.py +++ /dev/null @@ -1,12 +0,0 @@ -"""进程运行器组件 - -包含进程管理、日志收集等功能。 -""" - -from __future__ import annotations - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后,移除此导入并在此文件中实现 -from ..web_gui import ProcRunner - -__all__ = ["ProcRunner"] diff --git a/tests/run_test.py b/tests/run_test.py deleted file mode 100644 index d9b50ee..0000000 --- a/tests/run_test.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -import os -import sys -import subprocess - -# 查找目标文件 -PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -target_dir = os.path.join(PROJECT_ROOT, "pic", "debug_captures", "2025-12-31") -if os.path.exists(target_dir): - files = os.listdir(target_dir) - # 查找包含关键字的文件 - target_file = None - for f in files: - if "152118" in f and "福袋倒计时_分钟" in f and "识别后" in f and "390,1110" in f: - target_file = f - break - - if target_file: - # 使用绝对路径,避免编码问题 - full_path = os.path.abspath(os.path.join(target_dir, target_file)) - print(f"找到文件: {target_file}") - print(f"完整路径: {full_path}") - print(f"文件存在: {os.path.exists(full_path)}") - print("\n开始运行测试...\n") - - # 运行测试脚本 - cmd = [ - sys.executable, - "-u", - os.path.join(PROJECT_ROOT, "deleted_tests_backup", "test_real_parallel_ocr.py"), - full_path, - ] - env = os.environ.copy() - env['PYTHONIOENCODING'] = 'utf-8' - env['PYTHONUNBUFFERED'] = '1' - # 实时显示输出 - process = subprocess.Popen(cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - text=True, env=env, bufsize=1, universal_newlines=True) - if process.stdout: - for line in process.stdout: - print(line, end='') - process.wait() - print(f"\n退出码: {process.returncode}") - else: - print("未找到目标文件") - print("可用文件列表(前10个):") - for f in files[:10]: - if "152118" in f: - print(f" {f}") -else: - print(f"目录不存在: {target_dir}") diff --git a/tools/diagnostics/check_web_gui_config_sync.py b/tools/diagnostics/check_web_gui_config_sync.py index bbca2b2..d3f0625 100644 --- a/tools/diagnostics/check_web_gui_config_sync.py +++ b/tools/diagnostics/check_web_gui_config_sync.py @@ -200,7 +200,7 @@ def main() -> int: parser.add_argument( "--sync", action="store_true", - help="Regenerate tools/web_gui_config_manifest.json from current code.", + help="Regenerate tools/dev/web_gui_config_manifest.json from current code.", ) args = parser.parse_args()