Files
douyin_guaji-main/douyin_stage.py
T
Your Name e68f1dd3de feat: Refactor coverage management and enhance logging functionality
- Removed the `.coverage` file from the repository to streamline coverage management.
- Updated `.gitignore` to exclude coverage-related files and directories, ensuring a cleaner project structure.
- Introduced new scripts for checking GPU availability and detecting GUI parameter conflicts, enhancing the overall functionality of the application.
- Improved logging mechanisms across various modules to support better debugging and monitoring.
- Added comprehensive documentation for new features and updated existing markdown files for clarity.
2025-12-23 02:38:51 +08:00

1184 lines
65 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import douyin_pixel
def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C901
"""完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。
日志輸出已從 print 改為 _log_kv,方便結構化查看。
当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。
注意:此函数复杂度较高,包含多个检测步骤和条件分支,这是设计上的权衡。
"""
import time
# 是否输出详细阶段诊断日志:
# - False:只保留最终结果等精简日志
# - True:输出完整步骤级诊断日志(便于排查问题)
verbose: bool = bool(getattr(self, "stage_diag_verbose", False))
def _log(msg: str, **fields):
"""阶段诊断详细日志入口:仅在 verbose=True 时输出。"""
if not verbose:
return
try:
self._log_kv("阶段诊断", msg, **fields)
except Exception:
# 兜底:避免任何日志异常影响主流程
pass
def _log_summary(msg: str, **fields):
"""阶段诊断精简日志入口:始终输出,用于记录最终结果等关键信息。"""
try:
self._log_kv("阶段诊断", msg, **fields)
except Exception:
# 兜底:避免任何日志异常影响主流程
pass
def _log_separator(title: str = "", char: str = "="):
"""输出简洁分隔符(仅在 verbose=True 时启用),方便阅读详细日志。"""
if not verbose:
return
try:
if title:
msg = f"\n{char * 3} {title} {char * 3}\n"
else:
msg = f"\n{char * 10}\n"
self._log_kv("阶段诊断", msg)
except Exception:
pass
diag_start = time.time()
max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒)
max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒)
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) # OCR模式1开关(二值化)
# 仅在详细模式下输出开始分隔符与起始信息
_log_separator("开始阶段诊断")
_log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time)
# ========== 步骤0:首先检测是否在直播间(最优先)==========
step_start = time.time()
_log("步骤0[检测直播间]-开始", 说明="优先像素检测,然后模板匹配,最后OCR回退")
in_live_room = False
live_room_score = 0.0
detection_method = ""
# 第一步:优先使用像素检测
# 获取像素检测阈值(用于判断置信度是否达到要求)
pixel_threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
if pixel_threshold < 0.0:
pixel_threshold = 0.0
if pixel_threshold > 1.0:
pixel_threshold = 1.0
try:
pixel_start = time.time()
import os
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
if os.path.exists(pic_path):
pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path)
if pic_rgb is not None:
detected, confidence = douyin_pixel.detect_live_room_icons_by_pixel(pic_rgb)
pixel_elapsed = (time.time() - pixel_start) * 1000
# 使用 live_room_match_threshold 判断像素检测的置信度是否达到阈值
if detected and confidence >= pixel_threshold:
in_live_room = True
live_room_score = float(confidence or 0.0)
detection_method = "像素检测"
_log(
"步骤0[检测直播间]-命中(像素检测)",
置信度=round(confidence, 3),
阈值=pixel_threshold,
耗时毫秒=pixel_elapsed,
)
else:
_log(
"步骤0[检测直播间]-像素检测未命中",
置信度=round(confidence, 3),
阈值=pixel_threshold,
耗时毫秒=pixel_elapsed,
)
except Exception as e:
pixel_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-像素检测异常", 耗时毫秒=pixel_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# 第二步:如果像素检测失败,使用模板匹配
if not in_live_room:
try:
template_start = time.time()
detected, score = self._check_in_live_room_by_icon()
template_elapsed = (time.time() - template_start) * 1000
if detected:
in_live_room = True
live_room_score = float(score or 0.0)
detection_method = "模板匹配"
_log("步骤0[检测直播间]-命中(模板匹配)", 分数=live_room_score, 耗时毫秒=template_elapsed)
else:
_log("步骤0[检测直播间]-模板匹配未命中", 分数=live_room_score, 耗时毫秒=template_elapsed)
except Exception as e:
template_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-模板匹配异常", 耗时毫秒=template_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed)
# 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)
if not in_live_room:
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before)
t_recommend = ""
t_follow = ""
t_list = ""
try:
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(400, 140, 900, 200, "", "推荐页标签栏")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and (
not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend)
):
ocr_start_1 = time.time()
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
elapsed_recommend = (time.time() - step_start) * 1000
# 如果识别到"推荐",直接返回推荐页面
if "推荐" in t_recommend:
total_elapsed = (time.time() - diag_start) * 1000
seen_text = t_recommend[:50] if t_recommend else "-"
_log(
"步骤3[OCR推荐页标签栏]-命中推荐",
耗时毫秒=elapsed_recommend,
总耗时毫秒=total_elapsed,
识别文本=seen_text,
)
_log_summary(
"阶段诊断完成",
阶段="RECOMMEND_PAGE",
原因=f"标题='{t_recommend}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:RECOMMEND_PAGE(推荐页)")
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果识别到"关注"但没有"推荐",可能是关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
_log("步骤3[OCR关注列表]-检测到关注关键词,准备精确确认", 精确区域="(658,147)-(765,194)")
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(658, 147, 765, 194, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("关注" not in t_follow):
ocr_start_1 = time.time()
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
except Exception as e:
import traceback
_log("步骤3[OCR关注列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed_follow = (time.time() - step_start_follow) * 1000
if "关注" in t_follow:
total_elapsed = (time.time() - diag_start) * 1000
follow_text = t_follow[:50] if t_follow else "-"
_log(
"步骤3[OCR关注列表]-命中",
耗时毫秒=elapsed_follow,
总耗时毫秒=total_elapsed,
识别文本=follow_text,
)
try:
self._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
self._last_follow_list_title_text = ""
_log_summary(
"阶段诊断完成",
阶段="FOLLOW_LIST",
原因=f"标题='{t_follow}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FOLLOW_LIST(关注列表)")
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 如果识别到"正在直播"标签,判定为直播列表
if "正在直播" in t_recommend or ("直播" in t_recommend and "推荐" not in t_recommend and "关注" not in t_recommend):
_log("步骤3[OCR直播列表]-检测到直播关键词,准备精确确认", 精确区域="(650,145)-(800,195)")
step_start_list = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(650, 145, 800, 195, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_list = str(self.operation.analyse_pic_word("直播列表标签", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list):
ocr_start_1 = time.time()
t_list = str(self.operation.analyse_pic_word("直播列表标签", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
except Exception as e:
import traceback
_log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed_list = (time.time() - step_start_list) * 1000
if "正在直播" in t_list:
total_elapsed = (time.time() - diag_start) * 1000
list_text = t_list[:50] if t_list else "-"
_log(
"步骤3[OCR直播列表]-命中",
耗时毫秒=elapsed_list,
总耗时毫秒=total_elapsed,
识别文本=list_text,
)
_log_summary(
"阶段诊断完成",
阶段="LIVE_LIST",
原因=f"标题='{t_list}'",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:LIVE_LIST(直播列表)")
return "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
try:
self._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
self._last_follow_list_title_text = ""
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
_log("步骤3[OCR推荐页/关注列表/直播列表]-步骤超时", 耗时毫秒=elapsed_total, 阈值毫秒=max_step_time * 1000)
else:
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
耗时毫秒=elapsed_total,
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
)
except Exception as e:
elapsed_total = (time.time() - step_start) * 1000
import traceback
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 如果不在直播间且OCR也未识别到特定页面,返回未知状态
total_elapsed = (time.time() - diag_start) * 1000
_log_summary(
"阶段诊断完成",
阶段="UNKNOWN",
原因="不在直播间且未识别到特定页面",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:UNKNOWN(未知状态)")
return "UNKNOWN", "不在直播间且未识别到特定页面"
# ========== 在直播间:继续执行像素检测 ==========
_log_separator("在直播间,继续执行像素检测")
_log("在直播间,继续执行像素检测")
# ========== 第一步:基于同一张截图并行采集所有像素特征 ==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
pixel_state = {}
pixel_detection_start = time.time()
try:
pixel_state = self._read_pixel_stage_state()
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed,
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log("像素状态读取异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
pixel_state = {}
# ========== 优先使用像素检测结果判断阶段(按优先级顺序)==========
# 根据像素检测结果,按优先级返回阶段
# 优先级1:抽奖结果弹窗(大片红色+我知道了)
if pixel_state.get("has_lucky_draw_result", False):
_log_separator("步骤1:检测抽奖结果弹窗")
# 像素检测到抽奖结果弹窗,使用OCR兜底确认
step_result_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1[检测抽奖结果弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到抽奖结果弹窗,OCR兜底确认")
result_verified = False
try:
# 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字
if time.time() - step_result_start < max_step_time:
cut_start = time.time()
self.cut_pic(300, 600, 800, 800, "", "抽奖结果")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_result_start < max_step_time:
ocr_start = time.time()
result_text = str(self.operation.analyse_pic_word("抽奖结果", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(result_text),
文本预览=result_text[:50] if result_text else "",
)
if enable_ocr_mode1 and (time.time() - step_result_start < max_step_time) and (not result_text or ("没有抽中" not in result_text and "抽中福袋" not in result_text)):
ocr_start_1 = time.time()
result_text = str(self.operation.analyse_pic_word("抽奖结果", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(result_text),
文本预览=result_text[:50] if result_text else "",
)
# 检测"我知道了"按钮区域 (181, 1261)-(890, 1389) - 与像素检测区域一致
if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text):
if time.time() - step_result_start < max_step_time:
cut_confirm_start = time.time()
self.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed)
if time.time() - step_result_start < max_step_time:
ocr_confirm_start = time.time()
confirm_text = str(self.operation.analyse_pic_word("无奖励确认", 0) or "")
ocr_confirm_elapsed = (time.time() - ocr_confirm_start) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-确认按钮OCR模式0",
耗时毫秒=ocr_confirm_elapsed,
文本长度=len(confirm_text),
文本预览=confirm_text[:50] if confirm_text else "",
)
if confirm_text and ("我知道了" in confirm_text or "领取并使用" in confirm_text):
result_verified = True
else:
# OCR未识别到确认按钮,即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到确认按钮", 说明="OCR未匹配,不判定为抽奖结果弹窗")
else:
# OCR未识别到结果文字("没有抽中"或"抽中福袋"),即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到结果文字", 说明="OCR未匹配关键词,不判定为抽奖结果弹窗")
except Exception as e:
result_elapsed = (time.time() - step_result_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-异常", 耗时毫秒=result_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# OCR异常时,不判定为抽奖结果弹窗(需要OCR确认)
_log("步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗", 说明="需要OCR确认才能判定")
if result_verified:
total_elapsed = (time.time() - diag_start) * 1000
result_elapsed = (time.time() - step_result_start) * 1000
_log_summary(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+OCR确认(抽奖结果弹窗)",
总耗时毫秒=total_elapsed,
结果检测耗时毫秒=result_elapsed,
)
_log_separator(f"最终结果:FUDai_RESULT(抽奖结果弹窗)")
return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)"
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
if pixel_state.get("has_redpacket_bg", False):
_log_separator("步骤1.5:检测购物红包弹窗")
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1.5[检测购物红包弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到购物红包背景")
redpacket_detected = False
try:
if time.time() - step_redpacket_start < max_step_time:
cut_start = time.time()
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_redpacket_start < max_step_time:
ocr_start = time.time()
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[检测购物红包弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
# 检查是否包含购物红包关键词
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
redpacket_detected = True
else:
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR未识别到关键词", 说明="OCR未匹配,不判定为购物红包弹窗")
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗", 说明="需要OCR确认才能判定")
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log_summary(
"阶段诊断完成(购物红包弹窗)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="检测到购物红包弹窗",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
# 优先级2:优惠券弹窗检测(使用参与按钮区域,检测"开心收下")
# 优惠券弹窗和参与福袋按钮在同一个位置,需要通过OCR区分
has_red_button_area = pixel_state.get("has_attend_button_red", False) or pixel_state.get("has_fansclub_join_red", False)
if has_red_button_area:
# 先检测是否是优惠券弹窗("开心收下")
step_coupon_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤2[检测优惠券弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="使用参与按钮区域检测优惠券弹窗")
coupon_text = ""
try:
if time.time() - step_coupon_start < max_step_time:
cut_start = time.time()
# 使用与参与按钮相同的区域 (200, 1940)-(880, 2140)
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤2[检测优惠券弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_coupon_start < max_step_time:
ocr_start = time.time()
# 如果启用模式1,并行执行两个OCR模式
if enable_ocr_mode1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0)
future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 1)
text_mode0 = str(future_mode0.result() or "")
text_mode1 = str(future_mode1.result() or "")
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
if text_mode0 and "开心收下" in text_mode0:
coupon_text = text_mode0
elif text_mode1 and "开心收下" in text_mode1:
coupon_text = text_mode1
elif text_mode0:
coupon_text = text_mode0
else:
coupon_text = text_mode1
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2[检测优惠券弹窗]-OCR并行模式0+1",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
else:
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2[检测优惠券弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
except Exception as e:
coupon_elapsed = (time.time() - step_coupon_start) * 1000
_log("步骤2[检测优惠券弹窗]-异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# 如果检测到"开心收下",判定为优惠券弹窗
if coupon_text and "开心收下" in coupon_text:
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_coupon_start) * 1000
_log_summary(
"阶段诊断完成(优惠券弹窗)",
阶段="COUPON_POPUP",
原因="检测到开心收下(优惠券弹窗)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
_log_separator(f"最终结果:COUPON_POPUP(优惠券弹窗)")
return "COUPON_POPUP", "OCR确认(开心收下)"
# 优先级3:参与按钮/粉丝团加入区域(大片红色,需要OCR区分)
# 注意:这两个检测区域重叠,检测到红色区域后需要用OCR区分是"加入粉丝团"还是"一键发表评论"
if has_red_button_area:
_log_separator("步骤2:OCR区分按钮类型(参与/粉丝团)")
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤2[OCR区分按钮类型]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到红色按钮区域,需OCR区分类型")
# 使用粉丝团加入的区域进行OCR(覆盖范围更广)
t_button = ""
ocr_mode_0_result = ""
ocr_mode_1_result = ""
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(200, 1940, 880, 2140, "", "粉丝团加入")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤2[OCR区分按钮类型]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_button = str(self.operation.analyse_pic_word("粉丝团加入", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
ocr_mode_0_result = t_button
_log(
"步骤2[OCR区分按钮类型]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_button),
文本预览=t_button[:50] if t_button else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and (not t_button or ("加入粉丝团" not in t_button and "一键" not in t_button and "发表" not in t_button and "评论" not in t_button)):
ocr_start_1 = time.time()
t_button = str(self.operation.analyse_pic_word("粉丝团加入", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
ocr_mode_1_result = t_button
_log(
"步骤2[OCR区分按钮类型]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_button),
文本预览=t_button[:50] if t_button else "",
)
except Exception as e:
import traceback
elapsed = (time.time() - step_start) * 1000
_log("步骤2[OCR区分按钮类型]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed = (time.time() - step_start) * 1000
total_elapsed = (time.time() - diag_start) * 1000
# 根据OCR结果判断阶段
if "加入粉丝团" in t_button:
_log(
"步骤2[OCR区分按钮类型]-命中粉丝团加入",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
识别文本=t_button[:50] if t_button else "",
)
_log_summary(
"阶段诊断完成(像素+OCR)",
阶段="FANSCLUB_JOIN",
原因=f"OCR识别:{t_button[:30]}",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FANSCLUB_JOIN(粉丝团加入)")
return "FANSCLUB_JOIN", f"像素检测+OCR确认(加入粉丝团)"
elif "一键" in t_button or "发表" in t_button or "评论" in t_button or "参与" in t_button:
_log(
"步骤2[OCR区分按钮类型]-命中参与按钮",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
识别文本=t_button[:50] if t_button else "",
)
_log_summary(
"阶段诊断完成(像素+OCR)",
阶段="FUDai_DETAIL",
原因=f"OCR识别:{t_button[:30]}",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FUDai_DETAIL(福袋详情页)")
return "FUDai_DETAIL", f"像素检测+OCR确认(参与按钮)"
else:
# OCR未识别到明确文字,不判定为任何阶段(以OCR为准)
_log(
"步骤2[OCR区分按钮类型]-OCR未识别到明确文字,不判定为任何阶段",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
OCR结果=t_button[:50] if t_button else "(空)",
)
# 不返回任何阶段,继续后续检测
# ========== 步骤1:像素检测福袋详情页(已合并到并行检测中)==========
# 优先使用并行检测的结果
detail_detected = pixel_state.get("has_fudai_detail", False)
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
_log("步骤1[像素检测福袋详情]-命中(并行检测)", 总耗时毫秒=total_elapsed)
_log_summary(
"阶段诊断完成(像素检测)",
阶段="FUDai_DETAIL",
原因="福袋详情页像素检测(并行)",
总耗时毫秒=total_elapsed,
)
return "FUDai_DETAIL", "像素检测确认(福袋详情页,并行检测)"
# 如果并行检测未命中,使用"超级福袋"模板匹配作为补充(不再使用 OCR 兜底)
step_start = time.time()
_log(
"步骤1[像素检测福袋详情]-并行检测未命中,使用模板匹配补充",
说明="assets/xiangqing.png(超级福袋)",
)
try:
# 为了兼容没有 cv2 的环境,这里做降级处理
try:
import cv2 # type: ignore
except Exception as e:
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-缺少opencv,跳过模板检测",
耗时毫秒=elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
else:
import os
base_dir = os.path.dirname(__file__)
pic_path = os.path.join(base_dir, "pic", "screenshot.png")
tpl_path = os.path.join(base_dir, "assets", "xiangqing.png")
# 仅在截图与模板都存在时才进行模板匹配
if os.path.exists(pic_path) and os.path.exists(tpl_path):
img = cv2.imread(pic_path)
tpl = cv2.imread(tpl_path)
if img is not None and tpl is not None:
ih, iw = img.shape[:2]
th, tw = tpl.shape[:2]
if ih >= th and iw >= tw:
# 使用 TM_CCOEFF_NORMED 做标准模板匹配
res = cv2.matchTemplate(img, tpl, cv2.TM_CCOEFF_NORMED)
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
# 使用 fudai_template_match_threshold 作为可配置阈值
threshold = float(
getattr(self, "fudai_template_match_threshold", 0.7) or 0.7
)
if threshold < 0.0:
threshold = 0.0
if threshold > 1.0:
threshold = 1.0
# 保存模板匹配分数,用于后续判断是否跳过OCR检测
template_match_score = float(max_val or 0.0)
setattr(self, "_last_template_match_score", template_match_score)
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-结果",
分数=round(template_match_score, 4),
阈值=threshold,
耗时毫秒=elapsed,
)
if max_val >= threshold:
detail_detected = True
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-命中",
分数=round(template_match_score, 4),
总耗时毫秒=total_elapsed,
)
_log_summary(
"阶段诊断完成(模板匹配)",
阶段="FUDai_DETAIL",
原因="超级福袋模板匹配命中",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:FUDai_DETAIL(福袋详情页-模板匹配)")
return "FUDai_DETAIL", "模板匹配确认(超级福袋)"
else:
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-模板尺寸大于截图,跳过",
截图尺寸=f"{iw}x{ih}",
模板尺寸=f"{tw}x{th}",
耗时毫秒=elapsed,
)
else:
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-文件不存在,跳过",
截图存在=os.path.exists(pic_path),
模板存在=os.path.exists(tpl_path),
耗时毫秒=elapsed,
)
# 文件不存在时设置默认值
if not hasattr(self, "_last_template_match_score"):
setattr(self, "_last_template_match_score", 0.0)
except Exception as e:
import traceback
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-异常",
耗时毫秒=elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 异常时设置默认值
setattr(self, "_last_template_match_score", 0.0)
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
_log("步骤1[像素检测福袋详情]-最终命中", 总耗时毫秒=total_elapsed)
_log_summary(
"阶段诊断完成(像素检测+OCR兜底)",
阶段="FUDai_DETAIL",
原因="福袋详情页检测",
总耗时毫秒=total_elapsed,
)
return "FUDai_DETAIL", "像素检测+OCR兜底确认(福袋详情页)"
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
enable_invite_redpacket_ocr = bool(getattr(self, "enable_invite_redpacket_ocr", True))
template_match_score_threshold = float(getattr(self, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4)
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
template_match_score = float(getattr(self, "_last_template_match_score", 0.0) or 0.0)
should_skip_redpacket_ocr = (not detail_detected and template_match_score > 0 and template_match_score < template_match_score_threshold)
if should_skip_redpacket_ocr:
_log(
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
模板匹配分数=template_match_score,
阈值=template_match_score_threshold,
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间"
)
if not detail_detected and enable_invite_redpacket_ocr and not should_skip_redpacket_ocr:
step_ocr_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
ocr_max_step_time = float(getattr(self, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0)
if remaining_time_before > ocr_max_step_time:
try:
_log("步骤1.5[OCR检测邀你抢红包]-开始", 剩余时间秒=remaining_time_before, 说明="在指定区域检测邀你抢红包文字")
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
cut_start = time.time()
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
# 保存完整截图并标注OCR区域
try:
import douyin_screenshot_manager
import path_config
import os
from PIL import Image
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry)
x1 = max(0, min(x1, width - 1))
y1 = max(0, min(y1, height - 1))
x2 = max(0, min(x2, width - 1))
y2 = max(0, min(y2, height - 1))
if x1 < x2 and y1 < y2:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="阶段诊断邀你抢红包区域",
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
}
)
if debug_path:
try:
_log("OCR识别前保存完整截图(阶段诊断邀你抢红包区域)", path=debug_path)
except Exception:
pass
except Exception:
pass
self.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi)
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
ocr_start = time.time()
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False))
if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))):
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 1) or "")
_log(
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
redpacket_keywords = ("邀你抢红包", "邀你抢手气红包", "邀你抢", "抢红包", "抢手气")
if ocr_text and any(kw in ocr_text for kw in redpacket_keywords):
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-命中",
耗时毫秒=redpacket_elapsed,
总耗时毫秒=total_elapsed,
OCR文本=ocr_text[:50],
)
_log_summary(
"阶段诊断完成(OCR检测邀你抢红包)",
阶段="FUDai_DETAIL",
原因="检测到邀你抢红包文字",
OCR文本=ocr_text[:50],
总耗时毫秒=total_elapsed,
)
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
else:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-未命中", 耗时毫秒=redpacket_elapsed, OCR文本=ocr_text[:50] if ocr_text else "")
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
has_suspicious_popup_pixel = (
pixel_state.get("has_coupon_bg", False) or
pixel_state.get("has_redpacket_bg", False)
)
if has_suspicious_popup_pixel:
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR确认弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认")
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
if pixel_state.get("has_coupon_bg", False):
coupon_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
# 如果启用模式1,并行执行两个OCR模式
if enable_ocr_mode1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0)
future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 1)
text_mode0 = str(future_mode0.result() or "")
text_mode1 = str(future_mode1.result() or "")
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
if text_mode0 and "开心收下" in text_mode0:
coupon_text = text_mode0
elif text_mode1 and "开心收下" in text_mode1:
coupon_text = text_mode1
elif text_mode0:
coupon_text = text_mode0
else:
coupon_text = text_mode1
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
else:
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if coupon_text and "开心收下" in coupon_text:
coupon_verified = True
except Exception as e:
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if coupon_verified:
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log_summary(
"阶段诊断完成(优惠券弹窗-OCR确认)",
阶段="COUPON_POPUP",
原因="像素检测到背景+OCR确认(开心收下)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return "COUPON_POPUP", "OCR确认(开心收下)"
# 检测购物红包弹窗
if pixel_state.get("has_redpacket_bg", False):
redpacket_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
redpacket_verified = True
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log_summary(
"阶段诊断完成(购物红包弹窗-OCR确认)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(购物红包)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-未匹配到弹窗", 耗时毫秒=ocr_verify_elapsed, 说明="OCR确认后未匹配,判定为直播间背景颜色")
# ========== 在返回"在直播间"之前:模板匹配"超级福袋"(点击福袋后需要时间加载)==========
if in_live_room:
step_template_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log(
"步骤最后[模板匹配超级福袋]-开始",
剩余时间秒=remaining_time_before,
说明="在返回直播间前,检测是否成功打开福袋详情页",
)
template_matched = False
template_match_score = None
try:
import cv2
import os
base_dir = os.path.dirname(__file__)
pic_path = os.path.join(base_dir, "pic", "screenshot.png")
tpl_path = os.path.join(base_dir, "assets", "xiangqing.png")
if os.path.exists(pic_path) and os.path.exists(tpl_path):
img = cv2.imread(pic_path)
tpl = cv2.imread(tpl_path)
if img is not None and tpl is not None:
ih, iw = img.shape[:2]
th, tw = tpl.shape[:2]
if ih >= th and iw >= tw:
# 使用 TM_CCOEFF_NORMED 做标准模板匹配
res = cv2.matchTemplate(img, tpl, cv2.TM_CCOEFF_NORMED)
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
template_match_score = float(max_val or 0.0)
# 使用 fudai_template_match_threshold 作为可配置阈值
threshold = float(
getattr(self, "fudai_template_match_threshold", 0.7) or 0.7
)
if threshold < 0.0:
threshold = 0.0
if threshold > 1.0:
threshold = 1.0
elapsed = (time.time() - step_template_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-结果",
分数=round(template_match_score, 4),
阈值=threshold,
耗时毫秒=elapsed,
)
if max_val >= threshold:
template_matched = True
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-命中",
分数=round(template_match_score, 4),
总耗时毫秒=total_elapsed,
)
_log(
"阶段诊断完成(模板匹配)",
阶段="FUDai_DETAIL",
原因="超级福袋模板匹配命中(返回直播间前检测)",
)
return "FUDai_DETAIL", "模板匹配确认(超级福袋,返回直播间前检测)"
else:
_log(
"步骤最后[模板匹配超级福袋]-未命中",
分数=round(template_match_score, 4),
阈值=threshold,
说明="未检测到福袋详情页,返回直播间",
)
else:
elapsed = (time.time() - step_template_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-模板尺寸大于截图,跳过",
截图尺寸=f"{iw}x{ih}",
模板尺寸=f"{tw}x{th}",
耗时毫秒=elapsed,
)
else:
elapsed = (time.time() - step_template_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-图片读取失败",
耗时毫秒=elapsed,
)
else:
elapsed = (time.time() - step_template_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-文件不存在,跳过",
截图存在=os.path.exists(pic_path),
模板存在=os.path.exists(tpl_path),
耗时毫秒=elapsed,
)
except Exception as e:
import traceback
elapsed = (time.time() - step_template_start) * 1000
_log(
"步骤最后[模板匹配超级福袋]-异常",
耗时毫秒=elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
total_elapsed = (time.time() - diag_start) * 1000
_log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log_summary(
"阶段诊断完成(在直播间)",
阶段="IN_LIVE_ROOM",
原因=f"识别到在直播间({detection_method}),其他阶段未识别",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(在直播间)")
return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别"
# 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM)
# 这种情况可能是检测失败,但为了流程继续,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
_log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log_summary(
"阶段诊断完成(像素检测)",
阶段="IN_LIVE_ROOM",
原因="像素检测未命中,默认直播间",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"