diff --git a/douyin/stage/douyin_stage_handler.py b/douyin/stage/douyin_stage_handler.py index 01174bf..8b74392 100644 --- a/douyin/stage/douyin_stage_handler.py +++ b/douyin/stage/douyin_stage_handler.py @@ -1,1009 +1,26 @@ -from __future__ import annotations +"""douyin_stage_handler - 兼容入口(保留外部 import 路径)。 -""" -阶段处理模块 -============ - -职责:处理不同阶段的业务逻辑 -- 处理福袋详情页 -- 处理直播间福袋检测 -- 直播间图标检测 +实际实现位于子包 ``douyin.stage.douyin_stage_handler_pkg``。 +本文件仅 re-export 公共符号;详见各子模块文档: +- ``douyin_stage_handler_pkg.diagnose`` diagnose_stage_from_current_screen +- ``douyin_stage_handler_pkg.check_live`` check_in_live_room_by_icon(最大头) +- ``douyin_stage_handler_pkg.handle_detail`` handle_in_fudai_detail +- ``douyin_stage_handler_pkg.handle_room`` handle_live_room_has_or_not_fudai +- ``douyin_stage_handler_pkg.handler`` StageHandler 类(薄壳) """ -# pylint: disable=E1101 - -import time -from typing import Any, Tuple, List - -from douyin.stage import douyin_stage -import douyin.core.douyin_flow_control as douyin_flow_control - - -class StageHandler: - """阶段处理器:统一管理阶段处理""" - - @staticmethod # type: ignore[misc] - def diagnose_stage_from_current_screen( - analyser: Any, force_screenshot: bool = False, trigger_reason: str = "unknown" - ) -> Tuple[str, str]: - """封装到子模块的阶段诊断入口。 - - 参数: - analyser: 分析器对象 - force_screenshot: 是否强制重新截图(默认False,优先使用现有截图) - - 返回: - Tuple[str, str]: (阶段, 识别结果) - """ - # 如果需要强制截图,确保有最新截图 - if force_screenshot: - try: - analyser.operation.get_screenshot(analyser.device_id, use_service=False) - except Exception: - pass # 截图失败时继续使用现有截图 - - result = douyin_stage.diagnose_stage_from_current_screen( - analyser, trigger_reason - ) - 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,跳过图形识别", - log_type="DEBUG", - ) - except Exception: - pass - return False, 0.0 - - base_dir = os.path.dirname(__file__) - - # 使用统一的模板路径配置 - try: - from douyin.core import path_config - - assets_dir = path_config.get_assets_dir() - except Exception: - # 回退到旧路径(向后兼容) - assets_dir = os.path.join(base_dir, "assets") - - # 使用统一的截图路径配置 - try: - from douyin.core 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 获取截图失败", - log_type="SCREENSHOT", - error=str(e), - ) - except Exception: - pass - - # 如果预期路径不存在,尝试从其他可能的位置查找截图 - if not os.path.exists(screenshot_path): - # 尝试从项目根目录的 pic 目录查找 - try: - from douyin.core 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 截图不存在", - log_type="SCREENSHOT", - 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 读取截图失败", - log_type="SCREENSHOT", - 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区域无效", - log_type="DEBUG", - 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: - from douyin.core 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图标:使用直方图均衡化(保持原有方法) - - # 初始化备份变量 - tpl_binary_adaptive_backup = None - tpl_binary_otsu_backup = None - tpl_edges_backup = None - tpl_edges_aggressive_backup = None - tpl_edges_morph_backup = None - roi_binary_adaptive_backup = None - roi_binary_otsu_backup = None - roi_edges_backup = None - roi_edges_aggressive_backup = None - roi_edges_morph_backup = None - roi_contrast_backup = None - tpl_contrast_backup = None - - if icon_name == "x": - try: - # x图标特点:白色x在深灰色背景上,对比度明显 - # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) - # 先尝试多个阈值,选择最佳 - best_binary_score = 0.0 - 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 - roi_binary_fixed = roi_bin - tpl_binary_fixed = tpl_bin - except Exception: - 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:强对比度增强(针对实际测试中表现较好的配置) - 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: - 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( - 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( - tpl_binary_adaptive_backup, - (max(1, int(tw)), max(1, int(th))), - ) - tpl_binary_otsu_backup = cv2.resize( - tpl_binary_otsu_backup, - (max(1, int(tw)), max(1, int(th))), - ) - tpl_edges_backup = cv2.resize( - tpl_edges_backup, (max(1, int(tw)), max(1, int(th))) - ) - tpl_edges_aggressive_backup = cv2.resize( - tpl_edges_aggressive_backup, - (max(1, int(tw)), max(1, int(th))), - ) - tpl_edges_morph_backup = cv2.resize( - tpl_edges_morph_backup, - (max(1, int(tw)), max(1, int(th))), - ) - except Exception: - pass - - # 多方法模板匹配,取最高分(提高稳定性) - scores = [] - - if icon_name == "x" and use_edges: - try: - res1_fixed = cv2.matchTemplate( - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED - ) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc( - res1_fixed - ) - scores.append( - ("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0)) - ) - except Exception: - pass - - try: - res2_adaptive = cv2.matchTemplate( - roi_binary_adaptive_backup, - tpl_binary_adaptive_backup, - cv2.TM_CCOEFF_NORMED, - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc( - res2_adaptive - ) - scores.append( - ("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0)) - ) - except Exception: - pass - - try: - res3_otsu = cv2.matchTemplate( - roi_binary_otsu_backup, - tpl_binary_otsu_backup, - cv2.TM_CCOEFF_NORMED, - ) - _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc( - res3_otsu - ) - scores.append( - ("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0)) - ) - except Exception: - pass - - try: - res4_edges = cv2.matchTemplate( - roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED - ) - _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc( - res4_edges - ) - scores.append( - ("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0)) - ) - except Exception: - pass - - try: - res5_edges_agg = cv2.matchTemplate( - roi_edges_aggressive_backup, - tpl_edges_aggressive_backup, - cv2.TM_CCOEFF_NORMED, - ) - _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc( - res5_edges_agg - ) - scores.append( - ("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0)) - ) - except Exception: - pass - - try: - res6_morph = cv2.matchTemplate( - roi_edges_morph_backup, - tpl_edges_morph_backup, - cv2.TM_CCOEFF_NORMED, - ) - _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc( - res6_morph - ) - scores.append( - ("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0)) - ) - except Exception: - pass - - try: - res7_contrast = cv2.matchTemplate( - roi_contrast_backup, - tpl_contrast_backup, - cv2.TM_CCORR_NORMED, - ) - _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc( - res7_contrast - ) - scores.append( - ("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0)) - ) - except Exception: - pass - - try: - res8_original = cv2.matchTemplate( - roi_img, tpl, cv2.TM_CCOEFF_NORMED - ) - _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc( - res8_original - ) - scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) - except Exception: - pass - else: - try: - res1 = cv2.matchTemplate( - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED - ) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) - scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) - except Exception: - pass - - try: - res2 = cv2.matchTemplate( - roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED - ) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) - scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) - except Exception: - pass - - try: - res3 = cv2.matchTemplate( - roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED - ) - min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) - 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: - max_val = 0.0 - best_method = "" - 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 - ) - 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 - ) - if ccoeff_max and ccoeff_max[1] >= 0.50: - best_method, max_val = ccoeff_max - elif ccorr_max and ccorr_max[1] >= 0.75: - 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] - if top_score - second_score > 0.15: - max_val = top_score - best_method = sorted_scores[0][0] - else: - 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: - 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: - 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 - if best_method == "" and scores: - best_method, max_val = max(scores, key=lambda x: x[1]) - if len(scores) > 1: - 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( - roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED - ) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - max_val = float(max_val or 0.0) - best_method = "TM_CCOEFF_NORMED" - - passed_color_filter = True - if icon_name == "x" and x_white_ratio is not None: - if x_white_ratio < 0.05 or x_white_ratio > 0.25: - passed_color_filter = False - elif 0.10 <= x_white_ratio <= 0.15: - 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 -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png (方法:{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), - 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: 分析器对象 - """ - # 这个方法非常长,直接调用原方法,保持兼容性 - 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() - step_start = start_time - try: - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤1: 详情页复用检查开始", - ) - 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 - step1_elapsed = time.time() - step_start - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤1: 详情页复用检查完成", - elapsed_seconds=round(step1_elapsed, 3), - ) - except Exception: - pass - - # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 - step_start = time.time() - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤2: 预约锁定保护开始", - ) - 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 - ) - time_window_start_ts = ft - join_ahead - 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 - step2_elapsed = time.time() - step_start - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤2: 预约锁定保护完成", - elapsed_seconds=round(step2_elapsed, 3), - ) - - # 调用核心查找 find_and_open_fudai_detail - step_start = time.time() - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤3: 调用核心查找 find_and_open_fudai_detail 开始", - ) - room_pos_ref: List[int] = [0] - opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) - step3_elapsed = time.time() - step_start - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤3: 调用核心查找 find_and_open_fudai_detail 完成", - elapsed_seconds=round(step3_elapsed, 3), - ) - - if not opened: - step_start = time.time() - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤4: 未发现福袋的兜底判断开始", - ) - 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, - ) - step4_elapsed = time.time() - step_start - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤4: 未发现福袋的兜底判断完成", - elapsed_seconds=round(step4_elapsed, 3), - ) - 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 - - step_start = time.time() - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤5: 成功打开后的跳转开始", - ) - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - step5_elapsed = time.time() - step_start - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "步骤5: 成功打开后的跳转完成", - elapsed_seconds=round(step5_elapsed, 3), - ) - elapsed = time.time() - start_time - analyser._log_kv( # type: ignore[attr-defined] - "流程", - "_handle_live_room_has_or_not_fudai完成(成功打开详情)", - elapsed_seconds=round(elapsed, 2), - ) +from douyin.stage.douyin_stage_handler_pkg import ( + StageHandler, + check_in_live_room_by_icon, + diagnose_stage_from_current_screen, + handle_in_fudai_detail, + handle_live_room_has_or_not_fudai, +) + +__all__ = [ + "StageHandler", + "diagnose_stage_from_current_screen", + "check_in_live_room_by_icon", + "handle_in_fudai_detail", + "handle_live_room_has_or_not_fudai", +] diff --git a/douyin/stage/douyin_stage_handler_pkg/__init__.py b/douyin/stage/douyin_stage_handler_pkg/__init__.py new file mode 100644 index 0000000..9900bf5 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/__init__.py @@ -0,0 +1,28 @@ +"""douyin_stage_handler_pkg - 阶段处理子包。 + +原 douyin/stage/douyin_stage_handler.py 拆成 5 个子模块: + +- diagnose diagnose_stage_from_current_screen 阶段诊断分发 +- check_live check_in_live_room_by_icon 直播间图标检测(最大头) +- handle_detail handle_in_fudai_detail 福袋详情页处理 +- handle_room handle_live_room_has_or_not_fudai 直播间福袋检测分发 +- handler StageHandler 类(薄壳,每个方法 1 行 forwarding) + +外部 import 路径不变: +``from douyin.stage.douyin_stage_handler import StageHandler`` 仍可用 +(原文件改成 re-export shim)。 +""" + +from .diagnose import diagnose_stage_from_current_screen +from .check_live import check_in_live_room_by_icon +from .handle_detail import handle_in_fudai_detail +from .handle_room import handle_live_room_has_or_not_fudai +from .handler import StageHandler + +__all__ = [ + "StageHandler", + "diagnose_stage_from_current_screen", + "check_in_live_room_by_icon", + "handle_in_fudai_detail", + "handle_live_room_has_or_not_fudai", +] diff --git a/douyin/stage/douyin_stage_handler_pkg/check_live.py b/douyin/stage/douyin_stage_handler_pkg/check_live.py new file mode 100644 index 0000000..3237f36 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/check_live.py @@ -0,0 +1,774 @@ +"""douyin_stage_handler_pkg.check_live - check_in_live_room_by_icon 直播间图标检测(最大头)。""" +from __future__ import annotations + +# pylint: disable=E1101 + +import time +from typing import Any, List, Tuple + +from douyin.stage import douyin_stage +import douyin.core.douyin_flow_control as douyin_flow_control + + +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,跳过图形识别", + log_type="DEBUG", + ) + except Exception: + pass + return False, 0.0 + + base_dir = os.path.dirname(__file__) + + # 使用统一的模板路径配置 + try: + from douyin.core import path_config + + assets_dir = path_config.get_assets_dir() + except Exception: + # 回退到旧路径(向后兼容) + assets_dir = os.path.join(base_dir, "assets") + + # 使用统一的截图路径配置 + try: + from douyin.core 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 获取截图失败", + log_type="SCREENSHOT", + error=str(e), + ) + except Exception: + pass + + # 如果预期路径不存在,尝试从其他可能的位置查找截图 + if not os.path.exists(screenshot_path): + # 尝试从项目根目录的 pic 目录查找 + try: + from douyin.core 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 截图不存在", + log_type="SCREENSHOT", + 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 读取截图失败", + log_type="SCREENSHOT", + 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区域无效", + log_type="DEBUG", + 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: + from douyin.core 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图标:使用直方图均衡化(保持原有方法) + + # 初始化备份变量 + tpl_binary_adaptive_backup = None + tpl_binary_otsu_backup = None + tpl_edges_backup = None + tpl_edges_aggressive_backup = None + tpl_edges_morph_backup = None + roi_binary_adaptive_backup = None + roi_binary_otsu_backup = None + roi_edges_backup = None + roi_edges_aggressive_backup = None + roi_edges_morph_backup = None + roi_contrast_backup = None + tpl_contrast_backup = None + + if icon_name == "x": + try: + # x图标特点:白色x在深灰色背景上,对比度明显 + # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) + # 先尝试多个阈值,选择最佳 + best_binary_score = 0.0 + 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 + roi_binary_fixed = roi_bin + tpl_binary_fixed = tpl_bin + except Exception: + 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:强对比度增强(针对实际测试中表现较好的配置) + 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: + 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( + 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( + tpl_binary_adaptive_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_binary_otsu_backup = cv2.resize( + tpl_binary_otsu_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_edges_backup = cv2.resize( + tpl_edges_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_edges_aggressive_backup = cv2.resize( + tpl_edges_aggressive_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_edges_morph_backup = cv2.resize( + tpl_edges_morph_backup, + (max(1, int(tw)), max(1, int(th))), + ) + except Exception: + pass + + # 多方法模板匹配,取最高分(提高稳定性) + scores = [] + + if icon_name == "x" and use_edges: + try: + res1_fixed = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc( + res1_fixed + ) + scores.append( + ("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0)) + ) + except Exception: + pass + + try: + res2_adaptive = cv2.matchTemplate( + roi_binary_adaptive_backup, + tpl_binary_adaptive_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc( + res2_adaptive + ) + scores.append( + ("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0)) + ) + except Exception: + pass + + try: + res3_otsu = cv2.matchTemplate( + roi_binary_otsu_backup, + tpl_binary_otsu_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc( + res3_otsu + ) + scores.append( + ("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0)) + ) + except Exception: + pass + + try: + res4_edges = cv2.matchTemplate( + roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED + ) + _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc( + res4_edges + ) + scores.append( + ("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0)) + ) + except Exception: + pass + + try: + res5_edges_agg = cv2.matchTemplate( + roi_edges_aggressive_backup, + tpl_edges_aggressive_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc( + res5_edges_agg + ) + scores.append( + ("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0)) + ) + except Exception: + pass + + try: + res6_morph = cv2.matchTemplate( + roi_edges_morph_backup, + tpl_edges_morph_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc( + res6_morph + ) + scores.append( + ("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0)) + ) + except Exception: + pass + + try: + res7_contrast = cv2.matchTemplate( + roi_contrast_backup, + tpl_contrast_backup, + cv2.TM_CCORR_NORMED, + ) + _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc( + res7_contrast + ) + scores.append( + ("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0)) + ) + except Exception: + pass + + try: + res8_original = cv2.matchTemplate( + roi_img, tpl, cv2.TM_CCOEFF_NORMED + ) + _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc( + res8_original + ) + scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) + except Exception: + pass + else: + try: + res1 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) + scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) + except Exception: + pass + + try: + res2 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) + scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) + except Exception: + pass + + try: + res3 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED + ) + min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) + 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: + max_val = 0.0 + best_method = "" + 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 + ) + 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 + ) + if ccoeff_max and ccoeff_max[1] >= 0.50: + best_method, max_val = ccoeff_max + elif ccorr_max and ccorr_max[1] >= 0.75: + 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] + if top_score - second_score > 0.15: + max_val = top_score + best_method = sorted_scores[0][0] + else: + 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: + 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: + 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 + if best_method == "" and scores: + best_method, max_val = max(scores, key=lambda x: x[1]) + if len(scores) > 1: + 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( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) + max_val = float(max_val or 0.0) + best_method = "TM_CCOEFF_NORMED" + + passed_color_filter = True + if icon_name == "x" and x_white_ratio is not None: + if x_white_ratio < 0.05 or x_white_ratio > 0.25: + passed_color_filter = False + elif 0.10 <= x_white_ratio <= 0.15: + 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 -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png (方法:{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), + 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) diff --git a/douyin/stage/douyin_stage_handler_pkg/diagnose.py b/douyin/stage/douyin_stage_handler_pkg/diagnose.py new file mode 100644 index 0000000..2678e31 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/diagnose.py @@ -0,0 +1,37 @@ +"""douyin_stage_handler_pkg.diagnose - 阶段诊断主入口(薄壳分发到 douyin_stage 实现)。""" +from __future__ import annotations + +# pylint: disable=E1101 + +import time +from typing import Any, List, Tuple + +from douyin.stage import douyin_stage +import douyin.core.douyin_flow_control as douyin_flow_control + + +def diagnose_stage_from_current_screen( + analyser: Any, force_screenshot: bool = False, trigger_reason: str = "unknown" +) -> Tuple[str, str]: + """封装到子模块的阶段诊断入口。 + + 参数: + analyser: 分析器对象 + force_screenshot: 是否强制重新截图(默认False,优先使用现有截图) + + 返回: + Tuple[str, str]: (阶段, 识别结果) + """ + # 如果需要强制截图,确保有最新截图 + if force_screenshot: + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass # 截图失败时继续使用现有截图 + + result = douyin_stage.diagnose_stage_from_current_screen( + analyser, trigger_reason + ) + if result is None: + return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") + return result diff --git a/douyin/stage/douyin_stage_handler_pkg/handle_detail.py b/douyin/stage/douyin_stage_handler_pkg/handle_detail.py new file mode 100644 index 0000000..7edfa2b --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/handle_detail.py @@ -0,0 +1,20 @@ +"""douyin_stage_handler_pkg.handle_detail - handle_in_fudai_detail 福袋详情页处理。""" +from __future__ import annotations + +# pylint: disable=E1101 + +import time +from typing import Any, List, Tuple + +from douyin.stage import douyin_stage +import douyin.core.douyin_flow_control as douyin_flow_control + + +def handle_in_fudai_detail(analyser: Any) -> None: + """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。 + + 参数: + analyser: 分析器对象 + """ + # 这个方法非常长,直接调用原方法,保持兼容性 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] diff --git a/douyin/stage/douyin_stage_handler_pkg/handle_room.py b/douyin/stage/douyin_stage_handler_pkg/handle_room.py new file mode 100644 index 0000000..ddbf83f --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/handle_room.py @@ -0,0 +1,195 @@ +"""douyin_stage_handler_pkg.handle_room - handle_live_room_has_or_not_fudai 直播间福袋检测分发。""" +from __future__ import annotations + +# pylint: disable=E1101 + +import time +from typing import Any, List, Tuple + +from douyin.stage import douyin_stage +import douyin.core.douyin_flow_control as douyin_flow_control + + +def handle_live_room_has_or_not_fudai(analyser: Any) -> None: + """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。 + + 参数: + analyser: 分析器对象 + """ + start_time = time.time() + step_start = start_time + try: + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤1: 详情页复用检查开始", + ) + 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 + step1_elapsed = time.time() - step_start + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤1: 详情页复用检查完成", + elapsed_seconds=round(step1_elapsed, 3), + ) + except Exception: + pass + + # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 + step_start = time.time() + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤2: 预约锁定保护开始", + ) + 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 + ) + time_window_start_ts = ft - join_ahead + 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 + step2_elapsed = time.time() - step_start + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤2: 预约锁定保护完成", + elapsed_seconds=round(step2_elapsed, 3), + ) + + # 调用核心查找 find_and_open_fudai_detail + step_start = time.time() + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤3: 调用核心查找 find_and_open_fudai_detail 开始", + ) + room_pos_ref: List[int] = [0] + opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) + step3_elapsed = time.time() - step_start + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤3: 调用核心查找 find_and_open_fudai_detail 完成", + elapsed_seconds=round(step3_elapsed, 3), + ) + + if not opened: + step_start = time.time() + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤4: 未发现福袋的兜底判断开始", + ) + 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, + ) + step4_elapsed = time.time() - step_start + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤4: 未发现福袋的兜底判断完成", + elapsed_seconds=round(step4_elapsed, 3), + ) + 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 + + step_start = time.time() + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤5: 成功打开后的跳转开始", + ) + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + step5_elapsed = time.time() - step_start + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "步骤5: 成功打开后的跳转完成", + elapsed_seconds=round(step5_elapsed, 3), + ) + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(成功打开详情)", + elapsed_seconds=round(elapsed, 2), + ) diff --git a/douyin/stage/douyin_stage_handler_pkg/handler.py b/douyin/stage/douyin_stage_handler_pkg/handler.py new file mode 100644 index 0000000..4552f21 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/handler.py @@ -0,0 +1,32 @@ +"""douyin_stage_handler_pkg.handler - StageHandler 类(薄壳,每个方法 1 行 forwarding)。 + +外部 ``douyin_stage_handler.StageHandler.method(...)`` 完全不需要改。 +""" +from __future__ import annotations + +from typing import Any, Tuple + +from .diagnose import diagnose_stage_from_current_screen as _diagnose +from .check_live import check_in_live_room_by_icon as _check_live +from .handle_detail import handle_in_fudai_detail as _handle_detail +from .handle_room import handle_live_room_has_or_not_fudai as _handle_room + + +class StageHandler: + """阶段处理器(薄壳,转发到 module-level 函数)。""" + + @staticmethod # type: ignore[misc] + def diagnose_stage_from_current_screen(*args, **kwargs): + return _diagnose(*args, **kwargs) + + @staticmethod # type: ignore[misc] + def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: + return _check_live(analyser) + + @staticmethod # type: ignore[misc] + def handle_in_fudai_detail(analyser: Any) -> None: + return _handle_detail(analyser) + + @staticmethod # type: ignore[misc] + def handle_live_room_has_or_not_fudai(analyser: Any) -> None: + return _handle_room(analyser)