Files
douyin_guaji-main/douyin_stage.py
T
Your Name 8b47b506d6 feat: Enhance 福袋 detection and reservation logic
- Updated `config.json` to introduce new settings for infinite loop mode and adjust various thresholds for 福袋 detection.
- Refined the pixel detection logic in `douyin_detection.py` to improve error handling and retry mechanisms.
- Enhanced reservation handling in `douyin_flow_control.py` to prioritize high-value 福袋 and streamline the switching process.
- Improved the GUI in `gui_app.py` to support new configuration options and ensure better user experience.
- Added new tools for analyzing 福袋 colors and comparing them with coupon colors to aid in detection accuracy.
- Updated documentation to reflect changes in configuration and usage instructions.
2025-12-20 13:32:32 +08:00

821 lines
46 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):
"""完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。
日志輸出已從 print 改為 _log_kv,方便結構化查看。
当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。
"""
import time
def _log(msg: str, **fields):
"""阶段诊断统一日志入口,使用 self._log_kv 输出。"""
try:
self._log_kv("阶段诊断", msg, **fields)
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("开始阶段诊断", 最大诊断时间秒=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("阶段诊断完成", 阶段="RECOMMEND_PAGE", 原因=f"标题='{t_recommend}'")
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("阶段诊断完成", 阶段="FOLLOW_LIST", 原因=f"标题='{t_follow}'")
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("阶段诊断完成", 阶段="LIVE_LIST", 原因=f"标题='{t_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("不在直播间且OCR未识别到特定页面", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成", 阶段="UNKNOWN", 原因="不在直播间且未识别到特定页面")
return "UNKNOWN", "不在直播间且未识别到特定页面"
# ========== 在直播间:继续执行像素检测 ==========
_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):
# 像素检测到抽奖结果弹窗,使用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(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+OCR确认(抽奖结果弹窗)",
总耗时毫秒=total_elapsed,
结果检测耗时毫秒=result_elapsed,
)
return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)"
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
if pixel_state.get("has_redpacket_bg", False):
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(
"阶段诊断完成(购物红包弹窗)",
阶段="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()
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 "",
)
if enable_ocr_mode1 and (time.time() - step_coupon_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
ocr_start_1 = time.time()
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤2[检测优惠券弹窗]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=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(
"阶段诊断完成(优惠券弹窗)",
阶段="COUPON_POPUP",
原因="检测到开心收下(优惠券弹窗)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return "COUPON_POPUP", "OCR确认(开心收下)"
# 优先级3:参与按钮/粉丝团加入区域(大片红色,需要OCR区分)
# 注意:这两个检测区域重叠,检测到红色区域后需要用OCR区分是"加入粉丝团"还是"一键发表评论"
if has_red_button_area:
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("阶段诊断完成(像素+OCR)", 阶段="FANSCLUB_JOIN", 原因=f"OCR识别:{t_button[:30]}")
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("阶段诊断完成(像素+OCR)", 阶段="FUDai_DETAIL", 原因=f"OCR识别:{t_button[:30]}")
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("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测(并行)")
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
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-结果",
分数=round(float(max_val or 0.0), 4),
阈值=threshold,
耗时毫秒=elapsed,
)
if max_val >= threshold:
detail_detected = True
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-命中",
分数=round(float(max_val or 0.0), 4),
总耗时毫秒=total_elapsed,
)
_log(
"阶段诊断完成(模板匹配)",
阶段="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,
)
except Exception as e:
import traceback
elapsed = (time.time() - step_start) * 1000
_log(
"步骤1[福袋详情模板匹配]-异常",
耗时毫秒=elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
_log("步骤1[像素检测福袋详情]-最终命中", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成(像素检测+OCR兜底)", 阶段="FUDai_DETAIL", 原因="福袋详情页检测")
return "FUDai_DETAIL", "像素检测+OCR兜底确认(福袋详情页)"
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要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()
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 enable_ocr_mode1 and (time.time() - step_ocr_verify_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
ocr_start_1 = time.time()
coupon_text = 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(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(
"阶段诊断完成(优惠券弹窗-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(
"阶段诊断完成(购物红包弹窗-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:
total_elapsed = (time.time() - diag_start) * 1000
_log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log(
"阶段诊断完成(在直播间)",
阶段="IN_LIVE_ROOM",
原因=f"识别到在直播间({detection_method}),其他阶段未识别",
检测方法=detection_method,
分数=live_room_score,
)
return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别"
# 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM)
# 这种情况可能是检测失败,但为了流程继续,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
_log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成(像素检测)", 阶段="IN_LIVE_ROOM", 原因="像素检测未命中,默认直播间")
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"