from __future__ import annotations """ 工具方法模块 ============ 职责:通用工具方法 - 点击操作封装 - OCR检查开奖结果 - 处理开奖结果 - 截图并诊断 - 读取像素阶段状态 """ import os import time import shutil import json from typing import Any, Optional, Tuple, Dict, Union from datetime import datetime from douyin.detection.douyin_pixel import read_pixel_stage_state_from_screenshot from douyin.handlers import douyin_screenshot_handler class HelperFunctions: """工具函数集合:通用工具方法""" @staticmethod def click(analyser: Any, x: int, y: int) -> None: """兼容原版 fudai_analyse.click:转发到底层 operation.click。 参数: analyser: 分析器对象 x: X坐标 y: Y坐标 """ start_time = time.time() try: analyser.operation.click(analyser.device_id, int(x), int(y)) elapsed = time.time() - start_time if elapsed > 0.1: # 只记录耗时较长的点击操作 analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "操作", "点击操作", log_type="OP", x=int(x), y=int(y), elapsed_seconds=round(elapsed, 2), ) except (AttributeError, TypeError, OSError): # 仅捕获调用/参数/IO相关的常见异常,避免吞掉所有异常 pass @staticmethod # type: ignore[misc] def read_pixel_stage_state( analyser: Any, return_details: bool = False ) -> Union[Dict[str, Any], Tuple[Dict[str, Any], Dict[str, Any]]]: """读取像素阶段状态(用于阶段诊断)。 参数: analyser: 分析器对象 return_details: 是否返回每个检测步骤的详细信息(包括分数) 返回: dict: 检测结果(return_details=False时) tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时) """ # 使用统一的截图路径配置 try: import path_config pic_path = path_config.get_screenshot_path() except (ImportError, ModuleNotFoundError, AttributeError): # 回退到旧路径(向后兼容) base_dir = os.path.dirname(__file__) pic_path = os.path.join(base_dir, "pic", "screenshot.png") # 获取分辨率比例和y偏移参数 resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) lucky_threshold = float( getattr(analyser, "lucky_draw_red_ratio_threshold", 0.9) or 0.9 ) # 获取模板匹配阈值(优先使用福袋详情页专用阈值) fudai_template_threshold = float( getattr(analyser, "fudai_detail_template_threshold", None) or getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) if fudai_template_threshold < 0.0: fudai_template_threshold = 0.0 if fudai_template_threshold > 1.0: fudai_template_threshold = 1.0 return read_pixel_stage_state_from_screenshot( pic_path, resolution_ratio_x, resolution_ratio_y, y_pianyi, lucky_threshold, fudai_template_threshold, return_details=return_details, analyser=analyser, ) @staticmethod # type: ignore[misc] def check_lottery_result_by_ocr(analyser: Any) -> Optional[str]: """通过OCR识别开奖结果按钮区域,返回识别到的文本类型。 参数: analyser: 分析器对象 返回: "我知道了" - 识别到"我知道了"按钮 "立即领取奖品" - 识别到"立即领取奖品"按钮 None - 未识别到相关文本 """ try: # OCR区域:(175, 1200) 到 (890, 1377) - 向上扩展了识别区域 # 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures) douyin_screenshot_handler.ScreenshotHandler.cut_pic( analyser, 175, 1200, 890, 1377, "", "开奖结果按钮", 0 ) # OCR识别 from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore name_res = preprocess_for_ocr(analyser, "开奖结果按钮") ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "") analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text, log_type="SCREENSHOT") # type: ignore[attr-defined, reportPrivateUsage] # 检查识别到的文本 if "我知道了" in ocr_text: return "我知道了" elif ( "立即领取奖品" in ocr_text or "领取奖品" in ocr_text or "立即领取" in ocr_text ): # 检查是否为误识别(检查相似字记录) if HelperFunctions._is_false_positive_prize_text(ocr_text): analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "识别到相似字,判定为误识别", text=ocr_text, log_type="SCREENSHOT", ) return None # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 if ocr_text.strip() != "立即领取奖品": HelperFunctions._save_false_positive(ocr_text) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "记录相似字文本", text=ocr_text, log_type="SCREENSHOT", ) return "立即领取奖品" else: # 尝试模式1识别 ocr_text_1 = str( analyser.operation.analyse_pic_word("开奖结果按钮", 1) or "" ) if "我知道了" in ocr_text_1: return "我知道了" elif ( "立即领取奖品" in ocr_text_1 or "领取奖品" in ocr_text_1 or "立即领取" in ocr_text_1 ): # 检查是否为误识别(检查相似字记录) if HelperFunctions._is_false_positive_prize_text(ocr_text_1): analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "识别到相似字,判定为误识别", text=ocr_text_1, log_type="SCREENSHOT", ) return None # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 if ocr_text_1.strip() != "立即领取奖品": HelperFunctions._save_false_positive(ocr_text_1) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "记录相似字文本", text=ocr_text_1, log_type="SCREENSHOT", ) return "立即领取奖品" return None except Exception as e: analyser._log_kv("开奖结果", "OCR识别异常", error=str(e), log_type="ERR") # type: ignore[attr-defined, reportPrivateUsage] return None @staticmethod # type: ignore[misc] def _get_false_positive_file_path() -> str: """获取误识别记录文件路径""" try: import path_config pic_dir = path_config.get_pic_dir() except (ImportError, ModuleNotFoundError, AttributeError): base_dir = os.path.dirname(__file__) pic_dir = os.path.join(base_dir, "pic") false_positive_file = os.path.join( pic_dir, "lottery_prize_captures", "false_positives.json" ) return false_positive_file @staticmethod # type: ignore[misc] def _load_false_positives() -> set[str]: """加载误识别文本记录""" false_positive_file = HelperFunctions._get_false_positive_file_path() if not os.path.exists(false_positive_file): return set() try: with open(false_positive_file, "r", encoding="utf-8") as f: data = json.load(f) return set(data.get("false_positives", [])) except (OSError, json.JSONDecodeError): return set() @staticmethod # type: ignore[misc] def _save_false_positive(text: str) -> None: """保存误识别文本到记录文件""" false_positive_file = HelperFunctions._get_false_positive_file_path() os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) false_positives = HelperFunctions._load_false_positives() false_positives.add(text.strip()) try: with open(false_positive_file, "w", encoding="utf-8") as f: json.dump( {"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2, ) except OSError: # 写文件失败时忽略(非关键路径) pass @staticmethod # type: ignore[misc] def _is_false_positive_prize_text(text: str) -> bool: """检查文本是否为误识别的"立即领取奖品"相似字""" false_positives = HelperFunctions._load_false_positives() text_clean = text.strip() # 检查是否在误识别列表中 if text_clean in false_positives: return True # 检查是否包含误识别文本 for fp_text in false_positives: if fp_text in text_clean or text_clean in fp_text: return True return False @staticmethod # type: ignore[misc] def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None: """根据OCR识别结果处理开奖结果。 参数: analyser: 分析器对象 result_type: "我知道了" 或 "立即领取奖品" """ start_time = time.time() try: if result_type == "我知道了": # 识别到"我知道了",点击按钮,切换下一个直播间 rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) # 按钮位置在OCR区域中心附近 (175+890)/2=532, (1200+1377)/2=1288.5≈1289 btn_x = int(532 * rx // 1080) btn_y = int(1289 * ry // 2400) # OCR识别到结果,执行实际点击并等待生效 try: HelperFunctions.click(analyser, btn_x, btn_y) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "已通过OCR执行点击", log_type="OP", x=btn_x, y=btn_y ) except Exception as e: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "OCR点击执行失败,继续后续处理", log_type="ERR", x=btn_x, y=btn_y, error=str(e), ) # 等待点击生效,优先使用配置项 fudai_click_wait_seconds 回退到 0.8 秒 try: delay_sec = float( getattr(analyser, "fudai_click_wait_seconds", 0.8) or 0.8 ) except Exception: delay_sec = 0.8 analyser.operation.delay(delay_sec) # 切换下一个直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "处理完开奖结果,切换直播间找新福袋", log_type="OP" ) analyser.swipe_up_to_next_live() # type: ignore[attr-defined] else: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间", log_type="OP", ) elif result_type == "立即领取奖品": # 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间 try: # 确保有最新截图 analyser.operation.get_screenshot( analyser.device_id, use_service=False ) # 使用统一的截图路径配置 try: import path_config src = path_config.get_screenshot_path() pic_dir = path_config.get_pic_dir() except Exception: # 回退到旧路径(向后兼容) base_dir = os.path.dirname(__file__) pic_dir = os.path.join(base_dir, "pic") src = os.path.join(pic_dir, "screenshot.png") if os.path.exists(src): # 创建单独的文件夹保存"立即领取奖品"的截图 prize_dir = os.path.join(pic_dir, "lottery_prize_captures") os.makedirs(prize_dir, exist_ok=True) # 保存截图,文件名包含时间戳 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") dst = os.path.join(prize_dir, f"prize_{timestamp}.png") shutil.copy(src, dst) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "已保存立即领取奖品截图", log_type="SCREENSHOT", path=dst, ) except Exception as e: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "保存截图失败", log_type="ERR", error=str(e) ) # 点击返回键 analyser.operation.click_back(analyser.device_id) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "点击返回键关闭开奖结果", log_type="OP" ) analyser.operation.delay(0.5) # 切换下一个直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "处理完开奖结果,切换直播间找新福袋", log_type="OP" ) analyser.swipe_up_to_next_live() # type: ignore[attr-defined] else: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间", log_type="OP", ) except Exception as e: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "开奖结果", "处理开奖结果失败", error=str(e), result_type=result_type, ) # 失败时尝试按返回键并切换 try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(0.5) analyser.swipe_up_to_next_live() # type: ignore[attr-defined] except (AttributeError, OSError): # 忽略点击/滑动中发生的常见错误 pass finally: elapsed = time.time() - start_time analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] "流程", "_handle_lottery_result_by_ocr完成", log_type="PERF", elapsed_seconds=round(elapsed, 2), result_type=result_type, ) @staticmethod # type: ignore[misc] def shot_and_diagnose( analyser: Any, tag: str, msg: str, device_id: str, diagnose: bool = True ) -> None: """截图并执行阶段诊断(兼容旧版调用方式)。 参数: analyser: 分析器对象 tag: 日志标签 msg: 日志消息 device_id: 设备ID diagnose: 是否执行阶段诊断(默认True) """ try: # 截图 ok = analyser.operation.get_screenshot(device_id) if not ok: analyser._log_kv(tag, f"{msg} - 获取截图失败", ok=0) # type: ignore[attr-defined] return # 如果启用诊断,执行阶段诊断 if diagnose: stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined] analyser._last_diag_stage = stage # type: ignore[attr-defined] analyser._last_diag_seen = seen # type: ignore[attr-defined] analyser._last_diag_ts = time.time() # type: ignore[attr-defined] # 使用位置参数调用,避免与关键字参数冲突 analyser._log_kv(tag, msg, **{"stage": stage, "seen": seen}) # type: ignore[attr-defined] else: analyser._log_kv(tag, msg) # type: ignore[attr-defined] except Exception as e: # 避免异常影响主流程 try: analyser._log_kv( # type: ignore[attr-defined] tag, f"{msg} - 异常: {type(e).__name__}" ) except Exception: pass