feat: Enhance documentation and improve code structure

- Added comprehensive documentation for the unified screenshot and score recording process in the new markdown file.
- Updated existing markdown files to include additional spacing for better readability.
- Improved code structure by adding type hints and comments for clarity in various Python scripts.
- Enhanced logging functionality to support better debugging and monitoring across modules.
- Streamlined configuration settings to ensure consistency and clarity in the project structure.
This commit is contained in:
Your Name committed 2025-12-25 16:12:13 +08:00
1 parent f92933641f
commit c30b73bbd3
40 files changed
+31955 -268

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -160,6 +160,8 @@ python cleanup_unused_files.py
+2
View File
@@ -171,6 +171,8 @@ except Exception as e:
+2
View File
@@ -374,6 +374,8 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
+2
View File
@@ -258,6 +258,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
+2
View File
@@ -229,6 +229,8 @@ python check_dependencies.py
+2
View File
@@ -208,6 +208,8 @@ douyin_guaji
+2
View File
@@ -149,6 +149,8 @@
+2
View File
@@ -361,6 +361,8 @@ douyin_fudai_finder.py
+2
View File
@@ -160,6 +160,8 @@ self.ocr = easyocr.Reader(
+2
View File
@@ -119,6 +119,8 @@ python 生成WPS流程图.py
+2
View File
@@ -133,6 +133,8 @@ else:
+10 -6
View File
@@ -1,5 +1,5 @@
{
"needswitch": false,
"needswitch": true,
"infinite_loop_enabled": true,
"wait_minutes": 5,
"min_prize_value_yuan": 200.0,
@@ -28,8 +28,8 @@
"yanghao_fallback_enter_live_x": 540,
"yanghao_fallback_enter_live_y": 1200,
"fudai_find_max_attempts": 99999,
"fudai_icon_retry_delay_seconds": 0.7,
"fudai_icon_max_wait_seconds": 10.0,
"fudai_icon_retry_delay_seconds": 0.3,
"fudai_icon_max_wait_seconds": 4.0,
"fudai_click_wait_seconds": 1.7,
"yanghao_recommend_duration_seconds": 206,
"yanghao_recommend_interval_seconds": 570,
@@ -69,9 +69,9 @@
"yanghao_comment_texts": [],
"yanghao_like_keywords": [],
"yanghao_fav_keywords": [],
"stage_diag_max_time": 8.0,
"stage_diag_max_time": 5.0,
"stage_diag_max_step_time": 2.0,
"live_room_match_threshold": 0.7,
"live_room_match_threshold": 0.6,
"enable_ocr_mode1": false,
"fudai_template_match_enabled": false,
"fudai_template_match_threshold": 0.7,
@@ -97,5 +97,9 @@
"max_files": 2000,
"auto_cleanup": true
},
"fudai_detail_template_threshold": 0.54
"fudai_detail_template_threshold": 0.54,
"switch_room_wait_after_stage_diag_seconds": 6.0,
"coupon_template_match_threshold": 0.75,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25
}
+7 -1
View File
@@ -177,7 +177,7 @@ def find_and_open_fudai_detail(
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage, reason = ("UNKNOWN", "阶段诊断返回 None")
stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
else:
stage, reason = result
try:
@@ -201,6 +201,12 @@ def find_and_open_fudai_detail(
)
except Exception:
pass
# 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
return True
else:
# 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间
+498 -121
View File
@@ -139,6 +139,8 @@ class fudai_analyse:
self.fudai_icon_max_wait_seconds: float = 5.0
# 点击福袋图标后等待详情页加载的时间(秒)
self.fudai_click_wait_seconds: float = 2.0
# 切换直播间后等待阶段诊断的时间(秒)
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
# fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用
self.fudai_find_max_attempts: int = 10
@@ -149,6 +151,12 @@ class fudai_analyse:
self.screenshot_diagnose_min_interval_seconds: float = 8.0
# 开奖页面检测红色占比阈值(0.0~1.0)
self.lucky_draw_red_ratio_threshold: float = 0.9
# 优惠券模板匹配阈值(0.0~1.0,默认0.75)
self.coupon_template_match_threshold: float = 0.75
# 参与按钮红色占比阈值(0.0~1.0,默认0.25)
self.attend_button_red_ratio_threshold: float = 0.25
# 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)
self.fansclub_join_red_ratio_threshold: float = 0.25
# 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8)
self.live_room_match_threshold: float = 0.8
@@ -299,6 +307,10 @@ class fudai_analyse:
"fudai_click_wait_seconds",
self.fudai_click_wait_seconds,
)
self.switch_room_wait_after_stage_diag_seconds = _float(
"switch_room_wait_after_stage_diag_seconds",
self.switch_room_wait_after_stage_diag_seconds,
)
self.fudai_find_max_attempts = _int(
"fudai_find_max_attempts",
self.fudai_find_max_attempts,
@@ -315,6 +327,32 @@ class fudai_analyse:
self.lucky_draw_red_ratio_threshold = 0.0
if self.lucky_draw_red_ratio_threshold > 1.0:
self.lucky_draw_red_ratio_threshold = 1.0
self.coupon_template_match_threshold = _float(
"coupon_template_match_threshold",
self.coupon_template_match_threshold,
)
if self.coupon_template_match_threshold < 0.0:
self.coupon_template_match_threshold = 0.0
if self.coupon_template_match_threshold > 1.0:
self.coupon_template_match_threshold = 1.0
self.attend_button_red_ratio_threshold = _float(
"attend_button_red_ratio_threshold",
self.attend_button_red_ratio_threshold,
)
if self.attend_button_red_ratio_threshold < 0.0:
self.attend_button_red_ratio_threshold = 0.0
if self.attend_button_red_ratio_threshold > 1.0:
self.attend_button_red_ratio_threshold = 1.0
self.fansclub_join_red_ratio_threshold = _float(
"fansclub_join_red_ratio_threshold",
self.fansclub_join_red_ratio_threshold,
)
if self.fansclub_join_red_ratio_threshold < 0.0:
self.fansclub_join_red_ratio_threshold = 0.0
if self.fansclub_join_red_ratio_threshold > 1.0:
self.fansclub_join_red_ratio_threshold = 1.0
if self.lucky_draw_red_ratio_threshold > 1.0:
self.lucky_draw_red_ratio_threshold = 1.0
self.live_room_match_threshold = _float(
"live_room_match_threshold",
self.live_room_match_threshold,
@@ -573,7 +611,7 @@ class fudai_analyse:
f.flush()
except Exception:
pass
self._log_kv(
"启动",
"fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)",
@@ -612,7 +650,7 @@ class fudai_analyse:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
# 记录运行结束(定时模式)
try:
from datetime import datetime
@@ -699,7 +737,7 @@ class fudai_analyse:
"""封装到子模块的阶段诊断入口。"""
result = douyin_stage.diagnose_stage_from_current_screen(self)
if result is None:
return ("UNKNOWN", "阶段诊断返回 None")
return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
return result
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
@@ -739,10 +777,10 @@ class fudai_analyse:
self, return_details: bool = False
) -> dict | tuple[dict, dict]:
"""读取像素阶段状态(用于阶段诊断)。
参数:
return_details: 是否返回每个检测步骤的详细信息(包括分数)
返回:
dict: 检测结果(return_details=False时)
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
@@ -827,15 +865,18 @@ class fudai_analyse:
except Exception:
pass
def _check_in_live_room_by_icon(self) -> Tuple[bool, float]:
def _check_in_live_room_by_icon(
self,
) -> Tuple[bool, float]: # pyright: ignore[reportAttributeAccessIssue]
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
返回:
(detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。
"""
# pyright: ignore[reportAttributeAccessIssue]
# 为了兼容没有 cv2/numpy 的环境,这里做降级处理
try:
import cv2 # type: ignore
import cv2 # type: ignore[import-untyped, attr-defined]
import numpy as np # type: ignore
import os
@@ -844,7 +885,7 @@ class fudai_analyse:
os.environ["OPENCV_LOG_LEVEL"] = "ERROR"
# 方法2:使用cv2.setLogLevel(OpenCV 4.x+)
try:
cv2.setLogLevel(0) # 0 = SILENT
cv2.setLogLevel(0) # type: ignore[attr-defined] # 0 = SILENT
except (AttributeError, Exception):
# 如果setLogLevel不存在(旧版本OpenCV),尝试其他方法
try:
@@ -896,9 +937,9 @@ class fudai_analyse:
return False, 0.0
try:
img = cv2.imread(
screenshot_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
img = cv2.imread( # type: ignore[attr-defined]
screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
)
if img is None:
raise RuntimeError("cv2.imread 返回 None")
except Exception as e:
@@ -948,10 +989,8 @@ class fudai_analyse:
try:
# 保存ROI区域(两个文件保存相同的内容,因为x和xin图标在同一区域)
cv2.imwrite(x_roi_path, roi) # pyright: ignore[reportAttributeAccessIssue]
cv2.imwrite(
xin_roi_path, roi
) # pyright: ignore[reportAttributeAccessIssue]
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:
self._log_kv(
@@ -991,12 +1030,12 @@ class fudai_analyse:
# 读取模板和ROI图片
try:
tpl = cv2.imread(
template_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
roi_img = cv2.imread(
roi_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
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
@@ -1012,18 +1051,18 @@ class fudai_analyse:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale <= 0:
continue
tpl = cv2.resize( # pyright: ignore[reportAttributeAccessIssue]
tpl = cv2.resize( # type: ignore[attr-defined]
tpl, (max(1, int(tw * scale)), max(1, int(th * scale)))
)
th, tw = tpl.shape[:2]
# 在ROI中匹配模板
res = cv2.matchTemplate(
roi_img, tpl, cv2.TM_CCOEFF_NORMED
) # pyright: ignore[reportAttributeAccessIssue]
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(
res = cv2.matchTemplate( # type: ignore[attr-defined]
roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined]
res
) # pyright: ignore[reportAttributeAccessIssue]
)
# 记录最佳匹配分数和模板名称
if max_val > best_score:
@@ -1231,7 +1270,7 @@ class fudai_analyse:
try:
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
should_log = True
# 过滤一些不需要记录的日志(避免噪音)
if tag:
# 跳过一些调试或详细日志
@@ -1240,14 +1279,14 @@ class fudai_analyse:
if tag.startswith(skip_tag):
should_log = False
break
if should_log:
# 获取时间戳
if not timestamp:
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
# 提取关键信息:做了什么、耗时、分数
# 如果msg为空,从tag中提取操作描述
if msg:
@@ -1290,7 +1329,7 @@ class fudai_analyse:
action_desc = "操作"
else:
action_desc = "操作"
# 提取耗时(从字段中查找,优先使用毫秒字段)
elapsed_str = ""
if "elapsed_ms" in fields:
@@ -1308,7 +1347,7 @@ class fudai_analyse:
elif "elapsed_seconds" in fields:
elapsed_seconds = float(fields.get("elapsed_seconds", 0))
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
# 提取分数(如果有)
score_str = ""
if "score" in fields and fields.get("score") is not None:
@@ -1332,7 +1371,7 @@ class fudai_analyse:
score_str = f"分数:{score_val:.3f}"
except (ValueError, TypeError):
pass
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
action_parts = [timestamp, "-", "[GUI]", "-"]
if tag:
@@ -1340,15 +1379,15 @@ class fudai_analyse:
else:
action_parts.append("[日志]")
action_parts.append(action_desc)
if elapsed_str:
action_parts.append(elapsed_str)
if score_str:
action_parts.append(score_str)
action_log_line = " ".join(action_parts)
# 写入 actions.log 文件
import os
@@ -1358,12 +1397,12 @@ class fudai_analyse:
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
# 检测标签变化,用====分隔不同步骤
# 使用实例变量记录上一个标签
if not hasattr(self, "_last_action_tag"):
self._last_action_tag = None
# 如果标签变化,添加分隔符
current_tag = tag or "[日志]"
if (
@@ -1376,10 +1415,10 @@ class fudai_analyse:
) as f:
f.write("=" * 80 + "\n")
f.flush()
# 更新上一个标签
self._last_action_tag = current_tag
# 写入日志行
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
@@ -1639,15 +1678,18 @@ class fudai_analyse:
# 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖)
should_preempt = False
try:
if getattr(self, "high_value_fudai_enabled", False) and getattr(self, "reservations", None):
if getattr(self, "high_value_fudai_enabled", False) and getattr(
self, "reservations", None
):
reservations = self.reservations
if reservations and len(reservations) > 0:
# 检查是否有预约需要立即处理
import douyin_reservation_logic
reservation_focus_until_ts_ref = [0.0]
reservation_after_action_pending_ref = [False]
room_pos_ref = [getattr(self, "room_pos", 0) or 0]
# 检查是否有预约需要抢占
preempted = douyin_reservation_logic.process_reservation_attend_window(
self,
@@ -1655,13 +1697,22 @@ class fudai_analyse:
room_pos_ref[0],
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
float(getattr(self, "reservation_back_swipe_delay_s", 0.5) or 0.5),
float(
getattr(self, "reservation_back_swipe_delay_s", 0.5)
or 0.5
),
lambda: self.swipe_down_back_from_live(),
lambda item: self._seek_reservation_room(item),
lambda: douyin_reservation_logic._sort_reservations_inplace(self.reservations) if self.reservations else None,
lambda: (
douyin_reservation_logic._sort_reservations_inplace(
self.reservations
)
if self.reservations
else None
),
lambda: None, # write_state_callback
)
if preempted:
# 有高价值预约需要处理,清除等待开奖标志,中断等待
self._waiting_for_lottery_result = False
@@ -1672,7 +1723,7 @@ class fudai_analyse:
)
except Exception as e:
self._log_kv("参与", "检查高价值预约时出错", error=str(e))
if should_preempt:
# 被高价值预约抢占,继续执行后续逻辑处理预约
pass
@@ -1964,18 +2015,18 @@ class fudai_analyse:
if needswitch_cfg:
preempted = (
douyin_reservation_logic.process_reservation_attend_window(
analyser=self,
reservations=self.reservations,
room_pos=int(getattr(self, "room_pos", 0) or 0),
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=after_action_ref,
reservation_back_swipe_delay_s=float(
self.reservation_back_swipe_delay or 0.6
),
swipe_down_back_callback=_swipe_down_once,
seek_reservation_room_callback=_seek_reservation_room,
sort_reservations_callback=_sort_reservations,
write_state_callback=_write_state,
analyser=self,
reservations=self.reservations,
room_pos=int(getattr(self, "room_pos", 0) or 0),
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=after_action_ref,
reservation_back_swipe_delay_s=float(
self.reservation_back_swipe_delay or 0.6
),
swipe_down_back_callback=_swipe_down_once,
seek_reservation_room_callback=_seek_reservation_room,
sort_reservations_callback=_sort_reservations,
write_state_callback=_write_state,
)
)
# 同步回写 ref 值
@@ -1993,7 +2044,9 @@ class fudai_analyse:
pass
# 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后)
skip_stage_diagnosis = getattr(self, "_skip_stage_diagnosis_and_find_fudai", False)
skip_stage_diagnosis = getattr(
self, "_skip_stage_diagnosis_and_find_fudai", False
)
if skip_stage_diagnosis:
try:
self._skip_stage_diagnosis_and_find_fudai = False # 清除标志
@@ -2131,6 +2184,23 @@ class fudai_analyse:
)
self.operation.delay(2.0)
# 加入粉丝团两次点击后,点击 (527, 567) 返回直播间
try:
return_x = int(527 * self.resolution_ratio_x // 1080)
return_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, return_x, return_y)
self._log_kv(
"粉丝团处理",
"两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
self.operation.delay(1.0) # 等待返回完成
except Exception as e:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
# 如果启用了自动加入,等待页面加载后再次点击(如果需要)
if getattr(self, "auto_join_fansclub", False):
self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载")
@@ -2143,12 +2213,16 @@ class fudai_analyse:
if stage_after == "FANSCLUB_JOIN":
# 仍在粉丝团加入页,再次点击(连续点击两次)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv("粉丝团处理", "仍在粉丝团加入页,再次第一次点击")
self._log_kv(
"粉丝团处理", "仍在粉丝团加入页,再次第一次点击"
)
self.operation.delay(0.5)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv("粉丝团处理", "仍在粉丝团加入页,再次第二次点击")
self._log_kv(
"粉丝团处理", "仍在粉丝团加入页,再次第二次点击"
)
self.operation.delay(2.0)
# 加入粉丝团成功后,点击 (527, 567) 返回直播间
try:
return_x = int(527 * self.resolution_ratio_x // 1080)
@@ -2164,7 +2238,9 @@ class fudai_analyse:
)
self.operation.delay(1.0) # 等待返回完成
except Exception as e:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
self._log_kv(
"粉丝团处理", "点击返回直播间失败", error=str(e)
)
except Exception:
pass
else:
@@ -2174,7 +2250,7 @@ class fudai_analyse:
wait_seconds=15,
)
self.operation.delay(15.0)
# 未启用自动加入时,也需要在等待后点击返回
# 加入粉丝团成功后,点击 (527, 567) 返回直播间
try:
@@ -2207,6 +2283,29 @@ class fudai_analyse:
# 已经在详情页:直接读详情并决定是否参与
self._handle_in_fudai_detail()
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
# 在直播间:如果刚刚切换了直播间,等待福袋加载
just_switched = getattr(self, "_just_switched_room", False)
if just_switched:
try:
self._just_switched_room = False # 清除标志
wait_seconds = float(
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0)
or 7.0
)
if wait_seconds > 0:
self._log_kv(
"流程",
"切换直播间后,阶段检测完成,等待福袋加载",
wait_seconds=wait_seconds,
)
self.operation.delay(wait_seconds)
except Exception as e:
try:
self._just_switched_room = False # 确保清除标志
self._log_kv("流程", "等待福袋加载时出错", error=str(e))
except Exception:
pass
# 在直播间:寻找福袋图标并尝试点开
self._handle_live_room_has_or_not_fudai()
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
@@ -2475,6 +2574,19 @@ class fudai_analyse:
except Exception:
pass
# 设置标志:刚刚切换了直播间,阶段检测后需要等待福袋加载
try:
self._just_switched_room = True
except Exception:
pass
# 清除第一次读取标志,确保新直播间的福袋会进行完整的OCR识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
def _return_to_recommend_and_reenter_live(self) -> None:
"""返回推荐页面并重新进入直播间。
@@ -2843,23 +2955,29 @@ class fudai_analyse:
def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
# 检查是否是第二次打开福袋详情(已经读取过详情)
# 如果是第二次打开,只需要验证参与按钮,不需要重新识别内容、倒计时、价值
is_second_open = getattr(self, "_fudai_detail_first_read", False)
if is_second_open:
# 第二次打开:只检测参与按钮,使用第一次读取的详情数据
try:
self._log_kv("流程", "_handle_in_fudai_detail:第二次打开,只验证参与按钮,跳过内容识别")
self._log_kv(
"流程",
"_handle_in_fudai_detail:第二次打开,只验证参与按钮,跳过内容识别",
)
except Exception:
pass
# 获取第一次读取的详情数据
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail is None or not isinstance(detail, tuple) or len(detail) < 6:
# 如果没有保存的详情数据,需要重新读取(兜底逻辑)
try:
self._log_kv("流程", "_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取")
self._log_kv(
"流程",
"_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取",
)
except Exception:
pass
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
@@ -2874,29 +2992,53 @@ class fudai_analyse:
try:
self.operation.get_screenshot(self.device_id)
self.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
# OCR识别参与按钮
attend_button_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 0) or ""
)
if not attend_button_text or not any(
k in attend_button_text
for k in ("参与成功", "还需看播", "评论", "参与抽奖", "开始观看", "参与")
for k in (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
)
):
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 1) or ""
)
self._log_kv("参与", "第二次打开:只验证参与按钮", text=attend_button_text)
self._log_kv(
"参与", "第二次打开:只验证参与按钮", text=attend_button_text
)
# 如果已参与,设置等待开奖标志并返回,不需要继续处理
if "参与成功" in attend_button_text or "还需看播" in attend_button_text or "等待开奖" in attend_button_text:
self._log_kv("参与", "第二次打开:已参与,无需再次点击", result="已参与")
if (
"参与成功" in attend_button_text
or "还需看播" in attend_button_text
or "等待开奖" in attend_button_text
):
self._log_kv(
"参与", "第二次打开:已参与,无需再次点击", result="已参与"
)
# 从第一次保存的详情数据中获取倒计时信息,设置等待开奖标志
try:
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail and isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5]
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
if (
detail
and isinstance(detail, tuple)
and len(detail) >= 6
):
countdown_tuple = detail[5] # type: ignore[index]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
):
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
current_time = time.time()
@@ -2905,8 +3047,10 @@ class fudai_analyse:
# 设置等待开奖标志和预期开奖时间
# 提前13秒,修正倒计时误差
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = future_ts - 13.0
self._lottery_result_expected_ts = (
future_ts - 13.0
)
self._log_kv(
"参与",
"第二次打开:已参与,设置等待开奖标志",
@@ -2914,16 +3058,31 @@ class fudai_analyse:
future_ts=int(future_ts),
)
else:
self._log_kv("参与", "第二次打开:已参与,但倒计时已过期,不设置等待标志")
self._log_kv(
"参与",
"第二次打开:已参与,但倒计时已过期,不设置等待标志",
)
else:
self._log_kv("参与", "第二次打开:已参与,但无法获取倒计时信息")
self._log_kv(
"参与",
"第二次打开:已参与,但无法获取倒计时信息",
)
else:
self._log_kv("参与", "第二次打开:已参与,但详情数据中无倒计时信息")
self._log_kv(
"参与",
"第二次打开:已参与,但详情数据中无倒计时信息",
)
else:
self._log_kv("参与", "第二次打开:已参与,但未找到保存的详情数据")
self._log_kv(
"参与", "第二次打开:已参与,但未找到保存的详情数据"
)
except Exception as e:
self._log_kv("参与", "第二次打开:设置等待开奖标志时出错", error=str(e))
self._log_kv(
"参与",
"第二次打开:设置等待开奖标志时出错",
error=str(e),
)
# 关闭详情页
self.click(500, 470)
# 清除第一次读取标志,下次打开新福袋时重新识别
@@ -2946,14 +3105,16 @@ class fudai_analyse:
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
# 在第一次打开时立即进行筛选检查,如果不符合要求则直接跳过
# 注意:这里只检查筛选条件,不执行参与操作
if detail and isinstance(detail, tuple) and len(detail) >= 6:
# 先进行数据验证
is_valid = True
try:
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self)
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(
detail, self
)
if not is_valid:
try:
self._log_kv(
@@ -2971,33 +3132,180 @@ class fudai_analyse:
return
except Exception:
pass
# 执行筛选检查(不执行参与操作,只检查是否符合筛选条件)
try:
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(self, detail)
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(
self, detail
)
if skip:
# 筛选不通过,直接跳过
# 检查是否是高价值福袋,如果是则记录预约或立即参与
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过",
skip_reason=skip_reason,
# 提取价值信息
prize_value_yuan = 0.0
countdown_tuple = None
if isinstance(detail, tuple) and len(detail) >= 6:
prize_value_yuan = float(detail[4] or 0.0)
countdown_tuple = detail[5]
# 检查是否启用高价值预约
high_value_enabled = bool(getattr(self, "high_value_fudai_enabled", False))
high_value_threshold = float(
getattr(self, "high_value_fudai_threshold_yuan", 500.0) or 500.0
)
except Exception:
pass
# 关闭详情页并返回
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
return
# 检查价值是否达到高价值阈值
is_high_value = (
high_value_enabled
and prize_value_yuan > 0
and prize_value_yuan >= high_value_threshold
and isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
and float(countdown_tuple[1] or 0.0) > 0.0
)
# 如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
if is_high_value and skip_reason.startswith("countdown_gt_"):
# 计算剩余秒数
remain_seconds = None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
now = time.time()
cd_start = float(countdown_tuple[0] or 0.0)
cd_end = float(countdown_tuple[1] or 0.0)
if cd_start > 0 and cd_end > cd_start:
remain_seconds = float(cd_end - now)
except Exception:
pass
# 获取"预约参与阈值"配置
join_ahead_seconds = int(
getattr(self, "high_value_fudai_join_ahead_seconds", 120) or 120
)
# 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与",
reason=skip_reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=int(remain_seconds),
join_ahead_threshold=join_ahead_seconds,
)
except Exception:
pass
# 不关闭详情,继续走立即参与逻辑(保存详情数据,标记为已读取)
skip = False
else:
# 剩余秒数大于"预约参与阈值",记录预约
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约",
reason=skip_reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=int(remain_seconds) if remain_seconds is not None else None,
join_ahead_threshold=join_ahead_seconds,
)
except Exception:
pass
# 调用 basic_join_decision 来记录预约
try:
douyin_fudai_core.basic_join_decision(self, detail)
except Exception as e:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:记录预约时出错",
error=str(e),
)
except Exception:
pass
# 关闭详情页并返回
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
return
except Exception as e:
# 高价值检查异常,记录日志但继续流程
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:高价值检查异常",
error=str(e),
)
except Exception:
pass
# 如果不是高价值福袋,或者不是倒计时原因,筛选不通过,直接跳过
if skip:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过",
skip_reason=skip_reason,
)
except Exception:
pass
# 关闭详情页
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
# 如果允许切换直播间,筛选不通过直接切换直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:筛选不通过后切换直播间",
skip_reason=skip_reason,
)
except Exception:
pass
try:
# 优先使用封装好的上滑切房方法
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
self.operation.swipe(
self.device_id, start_x, start_y, end_x, end_y, 300
)
except Exception:
pass
return
except Exception as e:
# 筛选检查异常,记录日志但继续流程
try:
self._log_kv("流程", "_handle_in_fudai_detail:筛选检查异常", error=str(e))
self._log_kv(
"流程",
"_handle_in_fudai_detail:筛选检查异常",
error=str(e),
)
except Exception:
pass
# 筛选通过,保存详情数据并标记为已读取
try:
self._last_fudai_detail_tuple = detail
@@ -3007,7 +3315,10 @@ class fudai_analyse:
else:
# 详情数据无效,不保存,不标记为已读取
try:
self._log_kv("流程", "_handle_in_fudai_detail:第一次打开时详情数据无效,跳过")
self._log_kv(
"流程",
"_handle_in_fudai_detail:第一次打开时详情数据无效,跳过",
)
except Exception:
pass
return
@@ -3147,17 +3458,20 @@ class fudai_analyse:
except Exception:
pass
else:
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self)
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(
detail, self
)
if not is_valid:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错",
validation_reason=reason,
)
except Exception:
pass
return
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错",
validation_reason=reason,
)
except Exception:
pass
douyin_fudai_detail.close_fudai_detail(self)
return
except Exception:
pass
@@ -3248,6 +3562,69 @@ class fudai_analyse:
future_ts=int(future_timestamp),
)
# 检查是否是预约福袋,如果是,清除锁定期并从预约队列中移除已完成的预约
try:
if getattr(self, "reservation_after_action_pending", False):
# 这是预约福袋,参与成功后需要清除锁定期和移除预约
try:
self._log_kv(
"预约",
"[预约] 参与成功,清除锁定期并移除预约",
future_ts=int(future_timestamp),
)
except Exception:
pass
# 清除锁定期
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
# 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差)
if hasattr(self, "reservations") and self.reservations:
import douyin_reservation_logic
reservations_to_remove = []
for idx, r in enumerate(self.reservations):
try:
r_ft = float(r.get("future_ts") or 0.0)
if r_ft > 0 and abs(r_ft - future_timestamp) < 5.0:
reservations_to_remove.append(idx)
except Exception:
continue
# 从后往前删除,避免索引变化
for idx in reversed(reservations_to_remove):
try:
removed = self.reservations.pop(idx)
try:
self._log_kv(
"预约",
"[预约] 已从队列中移除已完成的预约",
future_ts=int(removed.get("future_ts", 0)),
content=str(removed.get("content", ""))[:50],
)
except Exception:
pass
except Exception:
pass
# 重新排序预约队列
if self.reservations:
try:
douyin_reservation_logic._sort_reservations_inplace(
self.reservations
)
except Exception:
pass
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] 清除锁定期和移除预约时出错",
error=str(e),
)
except Exception:
pass
# 关闭详情页,返回直播间等待开奖
# 检查 attend_choujiang 是否已经关闭了详情,如果已关闭就不应该再点击返回键
detail_already_closed = getattr(
@@ -3268,7 +3645,7 @@ class fudai_analyse:
)
except Exception:
pass
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
@@ -3282,7 +3659,7 @@ class fudai_analyse:
self._last_fudai_detail_tuple = None
except Exception:
pass
# 返回,让主循环只检测开奖结果,不执行其他操作
return
else:
+76 -6
View File
@@ -859,6 +859,25 @@ def attend_choujiang(analyser) -> bool:
base_y=2006,
)
analyser.operation.delay(2)
# 加入粉丝团两次点击后,点击 (527, 567) 返回直播间
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(analyser.device_id, return_x, return_y)
analyser._log_kv(
"参与",
"两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
except Exception as e:
analyser._log_kv("参与", "点击返回直播间失败", error=str(e))
if not analyser.auto_join_fansclub:
analyser._log_kv(
@@ -926,6 +945,25 @@ def attend_choujiang(analyser) -> bool:
x=click_x,
y=click_y,
)
# 两次点击后,立即点击 (527, 567) 返回直播间
analyser.operation.delay(0.5) # 短暂等待
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(analyser.device_id, return_x, return_y)
analyser._log_kv(
"参与",
"恢复流程:两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
except Exception as e:
analyser._log_kv("参与", "恢复流程:点击返回直播间失败", error=str(e))
except Exception:
# 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮)
try:
@@ -1008,6 +1046,23 @@ def attend_choujiang(analyser) -> bool:
x=click_x,
y=click_y,
)
# 两次点击后,立即点击 (527, 567) 返回直播间
analyser.operation.delay(0.5) # 短暂等待
try:
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(analyser.device_id, return_x, return_y)
analyser._log_kv(
"参与",
"恢复流程:再次两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
except Exception as e:
analyser._log_kv("参与", "恢复流程:再次点击返回直播间失败", error=str(e))
analyser.operation.delay(3.0)
except Exception:
# 回退到优化后的坐标(粉丝团加入按钮)
@@ -1015,6 +1070,25 @@ def attend_choujiang(analyser) -> bool:
analyser.click(540, 2006) # 第一次点击
analyser.operation.delay(0.5)
analyser.click(540, 2006) # 第二次点击(连续点击两次确保成功)
# 两次点击后,立即点击 (527, 567) 返回直播间
analyser.operation.delay(0.5) # 短暂等待
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(analyser.device_id, return_x, return_y)
analyser._log_kv(
"参与",
"恢复流程:回退逻辑两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
except Exception as e:
analyser._log_kv("参与", "恢复流程:回退逻辑点击返回直播间失败", error=str(e))
analyser.operation.delay(3.0)
except Exception:
# 最后回退到旧坐标
@@ -2061,16 +2135,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
except Exception:
pass
# 如果允许切换直播间,则针对部分丢弃原因直接切房(黑名单/价值不达标/倒计时大于阈值)
# 如果允许切换直播间,筛选不通过直接切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch and (
reason == "content_not_wanted"
or reason.startswith("value_lt_")
or reason.startswith("countdown_gt_")
):
if needswitch:
try:
analyser._log_kv(
"参与", "basic_join_decision:丢弃后切换直播间", reason=reason
+199 -47
View File
@@ -19,18 +19,25 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
return None
def detect_coupon_popup_background(pic_rgb: Image.Image, return_info: bool = False) -> bool | tuple[bool, dict]:
def detect_coupon_popup_background(
pic_rgb: Image.Image,
return_info: bool = False,
template_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测底部优惠券大弹窗(仅模板匹配)。
模板匹配区域(基于1080x2400基准):
- 左上: (9, 1173)
- 右下: (1079, 2255)
使用 `assets/coupon.png` 作为模板。
参数:
pic_rgb: RGB格式的整屏截图
return_info: 是否返回详细信息(包含检测分数)
template_threshold: 模板匹配阈值(默认0.75,如果提供则使用,否则从analyser读取)
analyser: analyser对象,用于读取配置阈值
返回:
bool: 是否检测到优惠券背景(return_info=False时)
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
@@ -41,7 +48,11 @@ def detect_coupon_popup_background(pic_rgb: Image.Image, return_info: bool = Fal
import numpy as np # type: ignore
except Exception:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "opencv_unavailable"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "opencv_unavailable",
}
return False
width, height = pic_rgb.size
@@ -60,38 +71,69 @@ def detect_coupon_popup_background(pic_rgb: Image.Image, return_info: bool = Fal
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "invalid_region"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "invalid_region",
}
return False
bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
if roi.size == 0:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "empty_roi"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "empty_roi",
}
return False
base_dir = os.path.dirname(__file__)
template_path = os.path.join(base_dir, "assets", "coupon.png")
if not os.path.exists(template_path):
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "template_not_found"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_not_found",
}
return False
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "template_load_failed"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_load_failed",
}
return False
if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": "template_too_large"}
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_too_large",
}
return False
res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(res)
threshold = 0.75
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if template_threshold is not None:
threshold = float(template_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75
)
except Exception:
threshold = 0.75
else:
threshold = 0.75
result = max_val >= threshold
if return_info:
return result, {
"method": "template_match",
@@ -102,7 +144,11 @@ def detect_coupon_popup_background(pic_rgb: Image.Image, return_info: bool = Fal
return result
except Exception as e:
if return_info:
return False, {"method": "template_match", "template_score": None, "reason": f"exception: {str(e)}"}
return False, {
"method": "template_match",
"template_score": None,
"reason": f"exception: {str(e)}",
}
return False
@@ -150,7 +196,7 @@ def detect_lucky_draw_result_popup(
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -160,13 +206,16 @@ def detect_lucky_draw_result_popup(
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}"
}
"region_size": f"{x2-x1}x{y2-y1}",
},
)
if debug_path:
try:
import logging
logging.info(f"[调试图像] 像素检测前保存: {debug_path}, threshold={red_ratio_threshold}")
logging.info(
f"[调试图像] 像素检测前保存: {debug_path}, threshold={red_ratio_threshold}"
)
except Exception:
pass
except Exception:
@@ -198,6 +247,7 @@ def detect_lucky_draw_result_popup(
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
import douyin_screenshot_manager
if result:
# 检测成功
if detect_roi is None:
@@ -205,7 +255,7 @@ def detect_lucky_draw_result_popup(
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
@@ -219,12 +269,15 @@ def detect_lucky_draw_result_popup(
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
}
},
)
if debug_path:
try:
import logging
logging.info(f"[调试图像] 抽奖结果检测保存: {debug_path}, red_ratio={red_ratio:.4f}, threshold={red_ratio_threshold}, score={red_ratio:.4f}")
logging.info(
f"[调试图像] 抽奖结果检测保存: {debug_path}, red_ratio={red_ratio:.4f}, threshold={red_ratio_threshold}, score={red_ratio:.4f}"
)
except Exception:
pass
except Exception:
@@ -246,7 +299,12 @@ def detect_lucky_draw_result_popup(
return False
def detect_attend_button_red_area(pic_rgb: Image.Image, return_info: bool = False) -> bool | tuple[bool, dict]:
def detect_attend_button_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测参与按钮:大片红色区域。
参与按钮通常在屏幕底部,有大片红色背景。
@@ -277,17 +335,19 @@ def detect_attend_button_red_area(pic_rgb: Image.Image, return_info: bool = Fals
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"}
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info(f"[调试图像] 参与按钮检测前保存: {debug_path}")
except Exception:
pass
@@ -318,9 +378,20 @@ def detect_attend_button_red_area(pic_rgb: Image.Image, return_info: bool = Fals
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
threshold = 0.25
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if red_ratio_threshold is not None:
threshold = float(red_ratio_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25
)
except Exception:
threshold = 0.25
else:
threshold = 0.25
result = red_ratio >= threshold
# 如果请求详细信息,返回包含red_ratio的字典
if return_info:
return result, {
@@ -331,11 +402,12 @@ def detect_attend_button_red_area(pic_rgb: Image.Image, return_info: bool = Fals
"effective_threshold": threshold,
"reason": None if result else "red_ratio_below_threshold",
}
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
if result:
try:
import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
@@ -346,26 +418,38 @@ def detect_attend_button_red_area(pic_rgb: Image.Image, return_info: bool = Fals
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"result": "success"
}
"result": "success",
},
)
if debug_path:
try:
import logging
logging.info(f"[调试图像] 参与按钮检测成功保存: {debug_path}, red_ratio={red_ratio:.4f}, score={red_ratio:.4f}")
logging.info(
f"[调试图像] 参与按钮检测成功保存: {debug_path}, red_ratio={red_ratio:.4f}, score={red_ratio:.4f}"
)
except Exception:
pass
except Exception:
pass
return result
except Exception:
if return_info:
return False, {"method": "pixel_detect", "red_ratio": None, "reason": "exception"}
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "exception",
}
return False
def detect_fansclub_join_red_area(pic_rgb: Image.Image, return_info: bool = False) -> bool | tuple[bool, dict]:
def detect_fansclub_join_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测粉丝团加入:大片红色区域。
粉丝团加入按钮通常在屏幕中下部,有大片红色背景。
@@ -391,7 +475,11 @@ def detect_fansclub_join_red_area(pic_rgb: Image.Image, return_info: bool = Fals
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {"method": "pixel_detect", "red_ratio": None, "reason": "invalid_region"}
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "invalid_region",
}
return False
# 采样检测点:检测大片红色区域
@@ -416,13 +504,28 @@ def detect_fansclub_join_red_area(pic_rgb: Image.Image, return_info: bool = Fals
)
if total_samples == 0:
if return_info:
return False, {"method": "pixel_detect", "red_ratio": None, "reason": "no_samples"}
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "no_samples",
}
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
threshold = 0.25
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if red_ratio_threshold is not None:
threshold = float(red_ratio_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25
)
except Exception:
threshold = 0.25
else:
threshold = 0.25
result = red_ratio >= threshold
if return_info:
return result, {
"method": "pixel_detect",
@@ -432,11 +535,15 @@ def detect_fansclub_join_red_area(pic_rgb: Image.Image, return_info: bool = Fals
"effective_threshold": threshold,
"reason": None if result else "red_ratio_below_threshold",
}
return result
except Exception:
if return_info:
return False, {"method": "pixel_detect", "red_ratio": None, "reason": "exception"}
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "exception",
}
return False
@@ -565,18 +672,18 @@ def detect_fudai_detail_page(
"reason": "analyser_required",
}
return False
try:
from douyin_detection import check_detail_height
# 执行任务数量检测
task_count = int(check_detail_height(analyser) or 0)
# 判断是否在福袋详情页
# 如果任务数量 <= 0,则认为不在福袋详情页
# 如果任务数量 >= 1,则认为在福袋详情页
is_in_detail = task_count >= 1
if return_info:
return is_in_detail, {
"method": "task_count",
@@ -616,7 +723,7 @@ def read_pixel_stage_state_from_screenshot(
lucky_draw_red_ratio_threshold: 抽奖结果红色比例阈值(默认0.8)
fudai_template_threshold: 福袋详情模板匹配阈值(默认0.7)
return_details: 是否返回每个检测步骤的详细信息(包括分数)
返回:
dict[str, bool]: 检测结果(return_details=False时)
tuple[dict[str, bool], dict[str, dict]]: (检测结果, 详细信息)(return_details=True时)
@@ -630,7 +737,7 @@ def read_pixel_stage_state_from_screenshot(
"has_fudai_detail": False,
}
details: dict[str, dict] = {}
pic_rgb = _safe_open_screenshot_rgb(pic_path)
if pic_rgb is None:
if return_details:
@@ -640,16 +747,61 @@ def read_pixel_stage_state_from_screenshot(
# 并行执行所有检测函数
# 注意:优惠券检测需要额外参数,使用lambda包装
# 注意:福袋详情检测使用任务数量检测,需要analyser参数
# 从analyser读取阈值(如果可用)
coupon_threshold = None
attend_button_threshold = None
fansclub_threshold = None
if analyser is not None:
try:
coupon_threshold = float(
getattr(analyser, "coupon_template_match_threshold", None) or 0.75
)
except Exception:
pass
try:
attend_button_threshold = float(
getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25
)
except Exception:
pass
try:
fansclub_threshold = float(
getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25
)
except Exception:
pass
detection_tasks = {
"has_coupon_bg": lambda pic: detect_coupon_popup_background(pic, return_info=True),
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
pic,
return_info=True,
template_threshold=coupon_threshold,
analyser=analyser,
),
"has_redpacket_bg": detect_redpacket_popup_background,
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
pic, lucky_draw_red_ratio_threshold, return_info=True
),
"has_attend_button_red": lambda pic: detect_attend_button_red_area(pic, return_info=True),
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(pic, return_info=True),
"has_attend_button_red": lambda pic: detect_attend_button_red_area(
pic,
return_info=True,
red_ratio_threshold=attend_button_threshold,
analyser=analyser,
),
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(
pic,
return_info=True,
red_ratio_threshold=fansclub_threshold,
analyser=analyser,
),
"has_fudai_detail": lambda pic: detect_fudai_detail_page(
pic, resolution_ratio_x, resolution_ratio_y, y_pianyi, fudai_template_threshold, return_info=True, analyser=analyser
pic,
resolution_ratio_x,
resolution_ratio_y,
y_pianyi,
fudai_template_threshold,
return_info=True,
analyser=analyser,
),
}
@@ -666,7 +818,7 @@ def read_pixel_stage_state_from_screenshot(
key = future_to_key[future]
try:
result = future.result()
# 处理结果
if isinstance(result, tuple):
# 检测函数返回 (bool, dict) 格式
+5 -1
View File
@@ -382,7 +382,11 @@ def handle_lottery_result_popup(analyser) -> None:
try:
analyser.operation.get_screenshot(analyser.device_id)
import douyin_stage
stage, _ = douyin_stage.diagnose_stage_from_current_screen(analyser)
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage = "UNKNOWN"
else:
stage, _ = result
if stage == "FUDai_RESULT":
# 仍在结果页,尝试按返回键
analyser.operation.click_back(analyser.device_id)
+153 -49
View File
@@ -48,7 +48,7 @@ def add_reservation_core_logic(
去重策略:
- key = (future_ts, content) 相同则视为同一条记录,保留价值更高的那条。
返回:
bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。
"""
@@ -59,7 +59,10 @@ def add_reservation_core_logic(
same_idx: Optional[int] = None
for idx, r in enumerate(reservations):
try:
if float(r.get("future_ts") or 0.0) == ft and str(r.get("content") or "") == content:
if (
float(r.get("future_ts") or 0.0) == ft
and str(r.get("content") or "") == content
):
same_idx = idx
break
except Exception:
@@ -80,7 +83,11 @@ def add_reservation_core_logic(
_sort_reservations_inplace(reservations)
queue_full = False
if max_reservations is not None and max_reservations > 0 and len(reservations) > max_reservations:
if (
max_reservations is not None
and max_reservations > 0
and len(reservations) > max_reservations
):
# 记录被丢弃的记录信息
dropped_items = reservations[max_reservations:]
for dropped in dropped_items:
@@ -90,10 +97,13 @@ def add_reservation_core_logic(
dropped_content = str(dropped.get("content") or "")[:50]
try:
from datetime import datetime
dropped_future_str = datetime.fromtimestamp(dropped_future_ts).strftime("%Y-%m-%d %H:%M:%S")
dropped_future_str = datetime.fromtimestamp(
dropped_future_ts
).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
dropped_future_str = str(dropped_future_ts)
if analyser:
try:
analyser._log_kv(
@@ -110,18 +120,18 @@ def add_reservation_core_logic(
pass
except Exception:
pass
# 按当前排序规则,队尾是"优先级最低"的记录
del reservations[max_reservations:]
queue_full = True
# 如果队列已满,写入状态文件
if write_state_callback:
try:
write_state_callback()
except Exception:
pass
return queue_full
@@ -154,9 +164,7 @@ def cleanup_expired_reservations(
now_ts_drop = _now_ts()
before = len(reservations)
reservations[:] = [
r
for r in reservations
if float(r.get("future_ts") or 0.0) > now_ts_drop
r for r in reservations if float(r.get("future_ts") or 0.0) > now_ts_drop
]
dropped = max(0, before - len(reservations))
@@ -193,33 +201,35 @@ def handle_queue_full_wait_at_earliest(
write_state_callback: Callable[[], None],
) -> bool:
"""队列满时,回到最早开奖的预约直播间等待。
返回:
bool: 如果已回退到最早开奖的预约直播间,返回 True;否则返回 False。
"""
if not reservations:
return False
# 排序确保取到最早开奖的
sort_reservations_callback()
# 取最早开奖的预约
earliest = reservations[0]
try:
ft = float(earliest.get("future_ts") or 0.0)
except Exception:
ft = 0.0
if ft <= 0:
return False
now_ts = _now_ts()
focus_until = float(reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0)
focus_until = float(
reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0
)
# 如果已经在锁定期内,不需要重复回退
if focus_until > 0 and now_ts < focus_until:
return False
try:
analyser._log_kv(
"预约",
@@ -230,7 +240,7 @@ def handle_queue_full_wait_at_earliest(
)
except Exception:
pass
# 先进行阶段诊断,处理弹窗等,避免卡死在某个页面
try:
# 确保有最新截图
@@ -238,12 +248,22 @@ def handle_queue_full_wait_at_earliest(
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
import douyin_stage
stage, reason = douyin_stage.diagnose_stage_from_current_screen(analyser)
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
else:
stage, reason = result
# 如果检测到需要处理的弹窗或异常状态,先处理
if stage in ("LUCKY_DRAW_RESULT", "COUPON_POPUP", "SHOPPING_REDPACKET_POPUP", "FANS_CLUB_JOIN"):
if stage in (
"LUCKY_DRAW_RESULT",
"COUPON_POPUP",
"SHOPPING_REDPACKET_POPUP",
"FANS_CLUB_JOIN",
):
try:
analyser._log_kv(
"预约",
@@ -253,7 +273,7 @@ def handle_queue_full_wait_at_earliest(
)
except Exception:
pass
# 处理弹窗:点击返回或关闭按钮
try:
analyser.operation.click_back(analyser.device_id)
@@ -263,7 +283,14 @@ def handle_queue_full_wait_at_earliest(
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
stage, reason = douyin_stage.diagnose_stage_from_current_screen(analyser)
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
except Exception:
pass
elif stage == "FUDai_DETAIL":
@@ -291,25 +318,27 @@ def handle_queue_full_wait_at_earliest(
)
except Exception:
pass
# 先轻微下滑一次,确保在直播列表中
try:
swipe_down_back_callback()
time.sleep(max(0.1, float(reservation_back_swipe_delay_s or 0.0)))
except Exception:
pass
# 回退到最早开奖的预约直播间
ok = False
try:
ok = bool(seek_reservation_room_callback(earliest))
except Exception:
ok = False
if ok:
# 设置锁定期:直到最早开奖时间 + 轮询时间
try:
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
poll_before = float(
getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0
)
except Exception:
poll_before = 10.0
focus_until_new = ft + max(0.0, poll_before)
@@ -317,7 +346,7 @@ def handle_queue_full_wait_at_earliest(
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
try:
analyser._log_kv(
"预约",
@@ -327,14 +356,14 @@ def handle_queue_full_wait_at_earliest(
)
except Exception:
pass
try:
write_state_callback()
except Exception:
pass
return True
return False
@@ -360,11 +389,9 @@ def process_reservation_attend_window(
return False
now_ts = _now_ts()
focus_until = float(reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0)
# 若当前仍处于“预约直播间锁定期”,则不再触发新的回退
if focus_until > 0 and now_ts < focus_until:
return False
focus_until = float(
reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0
)
# 按统一规则排序(防止外部遗漏 sort)
sort_reservations_callback()
@@ -387,12 +414,14 @@ def process_reservation_attend_window(
# 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退
try:
join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120)
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
)
except Exception:
join_ahead = 120.0
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
# 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过
dynamic_ahead = int(join_ahead)
est_back_times = 0
@@ -400,23 +429,89 @@ def process_reservation_attend_window(
target_pos = int(target.get("pos_seen") or 0)
est_back_times = max(0, int(room_pos) - target_pos)
try:
max_back = int(getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60)
max_back = int(
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
# 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲)
reservation_back_swipe_delay_s_val = float(reservation_back_swipe_delay_s or 0.6)
dynamic_ahead = int(max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18))
reservation_back_swipe_delay_s_val = float(
reservation_back_swipe_delay_s or 0.6
)
dynamic_ahead = int(
max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18)
)
except Exception:
dynamic_ahead = int(join_ahead)
# 添加调试日志:记录锁定期状态和时间窗口检查结果
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 检查",
now_ts=int(now_ts),
focus_until=int(focus_until) if focus_until > 0 else 0,
target_future_ts=int(ft),
dynamic_ahead=dynamic_ahead,
time_window_start=int(ft - dynamic_ahead),
in_lock_period=bool(focus_until > 0 and now_ts < focus_until),
in_time_window=bool(now_ts >= ft - dynamic_ahead),
)
except Exception:
pass
# 优化锁定期检查:如果预约时间已经到了(now_ts >= ft - dynamic_ahead),
# 即使锁定期还没结束,也应该允许回退(但需要检查是否是同一个预约)
# 如果锁定期还没结束,但当前预约的 future_ts 与锁定期匹配(说明是同一个预约),允许回退
# 如果锁定期还没结束,且当前预约的 future_ts 与锁定期不匹配,说明是新的预约,需要等待锁定期结束
if focus_until > 0 and now_ts < focus_until:
# 检查是否是同一个预约(允许5秒误差)
expected_focus_until = ft + max(0.0, poll_before)
if abs(focus_until - expected_focus_until) > 5.0:
# 不是同一个预约,锁定期还没结束,不允许回退
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束且不是当前预约,跳过回退",
focus_until=int(focus_until),
expected_focus_until=int(expected_focus_until),
target_future_ts=int(ft),
)
except Exception:
pass
return False
# 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退
# 但这里通常已经在目标直播间了,所以继续检查时间窗口
if now_ts < ft - dynamic_ahead:
# 还没到窗口
try:
analyser._log_kv(
"预约",
"[预约] 时间窗口未到,跳过回退",
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
remain_seconds=int((ft - dynamic_ahead) - now_ts),
)
except Exception:
pass
return False
if now_ts > ft + max(0.0, poll_before):
# 已明显错过开奖时间,交给统一清理逻辑
try:
analyser._log_kv(
"预约",
"[预约] 已明显错过开奖时间,清理过期预约",
future_ts=int(ft),
now_ts=int(now_ts),
poll_before=poll_before,
missed_seconds=int(now_ts - (ft + max(0.0, poll_before))),
)
except Exception:
pass
cleanup_expired_reservations(analyser, reservations, write_state_callback)
return False
@@ -431,6 +526,9 @@ def process_reservation_attend_window(
queue_len=len(reservations),
dynamic_ahead=int(dynamic_ahead),
est_back_times=int(est_back_times),
remain_seconds_to_open=int(ft - now_ts),
time_window_start=int(ft - dynamic_ahead),
time_window_end=int(ft + max(0.0, poll_before)),
)
except Exception:
pass
@@ -473,11 +571,13 @@ def process_reservation_attend_window(
"[预约] 已回退到目标直播间,等待详情识别与参与",
future_ts=int(ft),
focus_until=int(focus_until_new),
lock_period_seconds=int(focus_until_new - _now_ts()),
remain_seconds_to_open=int(ft - _now_ts()),
)
except Exception:
pass
# 不在这里弹出队列,等待真正“参与完毕”后由上层统一处理
# 不在这里弹出队列,等待真正"参与完毕"后由上层统一处理
try:
write_state_callback()
except Exception:
@@ -492,6 +592,9 @@ def process_reservation_attend_window(
"[预约] 回退到预约直播间失败,保留队列以便后续重试或清理",
future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts),
target_pos=int(target.get("pos_seen", 0)),
current_room_pos=int(room_pos),
)
except Exception:
pass
@@ -539,10 +642,13 @@ def record_high_value_reservation(
try:
if future_timestamp and future_timestamp > 0:
from datetime import datetime
future_str = datetime.fromtimestamp(float(future_timestamp)).strftime("%Y-%m-%d %H:%M:%S")
future_str = datetime.fromtimestamp(float(future_timestamp)).strftime(
"%Y-%m-%d %H:%M:%S"
)
except Exception:
pass
item: ReservationItem = {
"future_ts": float(future_timestamp or 0.0),
"future_str": future_str,
@@ -587,5 +693,3 @@ def record_high_value_reservation(
except Exception:
pass
return False
+5 -1
View File
@@ -281,7 +281,11 @@ def validate_back_to_reservation(
try:
import douyin_stage
analyser.operation.get_screenshot(analyser.device_id)
stage, _ = douyin_stage.diagnose_stage_from_current_screen(analyser)
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage = "IN_LIVE_ROOM"
else:
stage, _ = result
if stage != "FUDai_DETAIL":
try:
analyser._log_kv("预约", "回退校验失败:未能打开福袋详情", result="详情未打开", stage=stage)
+13 -16
View File
@@ -19,14 +19,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
# - True:输出完整步骤级诊断日志(便于排查问题)
verbose: bool = bool(getattr(self, "stage_diag_verbose", False))
def _log(msg: str, **fields):
def _log(msg: str, **fields): # type: ignore[misc]
"""阶段诊断详细日志入口:始终记录到行为日志,仅在 verbose=True 时输出到 stdout。"""
try:
# 始终记录到行为日志(通过 _log_kv),即使 verbose=False
# _log_kv 会同时写入 actions.log 和输出到 stdout
# 如果 verbose=False,我们需要控制 stdout 输出,但行为日志应该始终记录
# 由于 _log_kv 的设计,我们暂时让它始终调用,确保行为日志有完整记录
self._log_kv("阶段诊断", msg, **fields)
self._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined]
except Exception:
# 兜底:避免任何日志异常影响主流程
pass
@@ -332,16 +332,16 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
堆栈=traceback.format_exc(),
)
# 如果不在直播间且OCR也未识别到特定页面,返回未知状态
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
_log_summary(
"阶段诊断完成",
阶段="UNKNOWN",
原因="不在直播间且未识别到特定页面",
阶段="IN_LIVE_ROOM",
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:UNKNOWN(未知状态)")
return "UNKNOWN", "不在直播间且未识别到特定页面"
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
# ========== 在直播间:继续执行像素检测 ==========
_log_separator("在直播间,继续执行像素检测")
@@ -419,8 +419,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
# 如果任务数量存在但检测结果为False,记录警告
if task_count_val is not None and task_count_val > 0 and not detected:
try:
_log(
"阶段诊断",
_log( # type: ignore[misc]
"警告:检测到任务数量但 has_fudai_detail 为 False",
任务数量=task_count_val,
detected=detected,
@@ -626,8 +625,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
try:
self._fudai_detail_task_count_from_stage = detail_task_count
try:
_log(
"阶段诊断",
_log( # type: ignore[misc]
"保存任务数量到 analyser 对象",
任务数量=detail_task_count,
has_fudai_detail=detail_detected,
@@ -639,8 +637,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
else:
# detail_task_count 为 None,记录警告日志
try:
_log(
"阶段诊断",
_log( # type: ignore[misc]
"警告:任务数量为 None,无法保存到 analyser 对象",
任务数量=None,
has_fudai_detail=detail_detected,
@@ -650,8 +647,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
else:
# pixel_details 中没有 has_fudai_detail 信息,记录警告
try:
_log(
"阶段诊断",
_log( # type: ignore[misc]
"警告:pixel_details 中没有 has_fudai_detail 信息",
has_fudai_detail=detail_detected,
)
@@ -948,4 +944,5 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
原因="像素检测未命中,默认直播间",
总耗时毫秒=total_elapsed,
)
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
+2
View File
@@ -133,6 +133,8 @@ def extract_participants_count(text: Optional[str]) -> int:
+102
View File
@@ -370,6 +370,9 @@ def main():
fudai_click_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0)
)
switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(
value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
)
live_room_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
)
@@ -491,6 +494,18 @@ def main():
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
)
# 优惠券模板匹配阈值(0.0~1.0,默认0.75)
coupon_template_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
)
# 参与按钮红色占比阈值(0.0~1.0,默认0.25)
attend_button_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
)
# 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)
fansclub_join_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
)
# 调试图像清理相关变量
debug_captures_auto_cleanup_var = tk.BooleanVar(
@@ -947,6 +962,19 @@ def main():
).pack(side=LEFT)
ttk.Label(row4d, text="(等待福袋详情页加载,默认2.0秒)").pack(side=LEFT, padx=(6, 0))
row4e = ttk.Frame(fudai_find_box)
row4e.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
ttk.Spinbox(
row4e,
from_=0.0,
to=30.0,
increment=0.5,
textvariable=switch_room_wait_after_stage_diag_seconds_var,
width=6,
).pack(side=LEFT)
ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(side=LEFT, padx=(6, 0))
row4c = ttk.Frame(fudai_find_box)
row4c.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(row4c, text="直播间检测阈值:").pack(side=LEFT)
@@ -1041,6 +1069,56 @@ def main():
side=LEFT, padx=(6, 0)
)
# 更多模板匹配阈值
diag_time_r5 = ttk.Frame(diag_time_box)
diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))
ttk.Label(diag_time_r5, text="优惠券模板匹配阈值:").pack(side=LEFT)
ttk.Spinbox(
diag_time_r5,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=coupon_template_match_threshold_var,
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r5, text="(默认0.75,用于检测优惠券弹窗)").pack(
side=LEFT, padx=(6, 0)
)
# 像素检测阈值
pixel_detect_box = ttk.LabelFrame(debug_tab, text="像素检测阈值")
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
pixel_r1 = ttk.Frame(pixel_detect_box)
pixel_r1.pack(fill=X, padx=10, pady=(10, 6))
ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
pixel_r1,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=attend_button_red_ratio_threshold_var,
width=8,
).pack(side=LEFT)
ttk.Label(pixel_r1, text="(默认0.25,用于检测参与按钮)").pack(
side=LEFT, padx=(6, 0)
)
pixel_r2 = ttk.Frame(pixel_detect_box)
pixel_r2.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(pixel_r2, text="粉丝团加入红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
pixel_r2,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=fansclub_join_red_ratio_threshold_var,
width=8,
).pack(side=LEFT)
ttk.Label(pixel_r2, text="(默认0.25,用于检测粉丝团加入按钮)").pack(
side=LEFT, padx=(6, 0)
)
# 标签页6:关键词
keywords_tab = ttk.Frame(left_notebook)
left_notebook.add(keywords_tab, text="关键词")
@@ -1131,6 +1209,9 @@ def main():
fudai_click_wait_seconds_var.set(
float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0)
)
switch_room_wait_after_stage_diag_seconds_var.set(
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
)
live_room_match_threshold_var.set(
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
)
@@ -1153,6 +1234,15 @@ def main():
fudai_detail_template_threshold_var.set(
float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
)
coupon_template_match_threshold_var.set(
float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
)
attend_button_red_ratio_threshold_var.set(
float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
)
fansclub_join_red_ratio_threshold_var.set(
float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
)
skip_lt_seconds_var.set(int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5))
# 调试图像清理配置
@@ -1310,6 +1400,9 @@ def main():
cfg2["fudai_click_wait_seconds"] = float(
fudai_click_wait_seconds_var.get() or 2.0
)
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
switch_room_wait_after_stage_diag_seconds_var.get() or 7.0
)
cfg2["live_room_match_threshold"] = float(
live_room_match_threshold_var.get() or 0.8
)
@@ -1330,6 +1423,15 @@ def main():
cfg2["fudai_detail_template_threshold"] = float(
fudai_detail_template_threshold_var.get() or 0.7
)
cfg2["coupon_template_match_threshold"] = float(
coupon_template_match_threshold_var.get() or 0.75
)
cfg2["attend_button_red_ratio_threshold"] = float(
attend_button_red_ratio_threshold_var.get() or 0.25
)
cfg2["fansclub_join_red_ratio_threshold"] = float(
fansclub_join_red_ratio_threshold_var.get() or 0.25
)
cfg2["skip_if_countdown_lt_seconds"] = int(skip_lt_seconds_var.get() or 5)
# 调试图像清理配置
+2
View File
@@ -90,6 +90,8 @@ paddlepaddle>=2.5.0,<3.0.0
+2
View File
@@ -67,6 +67,8 @@ types-requests>=2.31.0
+2
View File
@@ -106,6 +106,8 @@ ttkbootstrap>=1.10.0
+2
View File
@@ -143,6 +143,8 @@ if __name__ == "__main__":
+20 -20
View File
@@ -1,29 +1,29 @@
{
"updated_ts": 1766552734.5879405,
"updated_ts": 1766649957.0628917,
"reason": "record_reservation",
"room_pos": 3,
"current_room_title": "孙坚",
"current_room_title_raw": "孙坚",
"room_pos": 9,
"current_room_title": "94万本坎",
"current_room_title_raw": "9.4万本坎",
"reservations": [
{
"prize_value_yuan": 5999.0,
"content": "18后开奖02(孙坚专属]jhone17256GB颜色随机发",
"future_ts": 1766552866.139606,
"future_str": "2025-12-24 13:07:46",
"pos_seen": 3,
"room_title": "孙坚",
"room_title_raw": "孙坚",
"created_ts": 1766552734.5879405
"prize_value_yuan": 4800.0,
"content": "45后开奖02(小北珠宝1古法金手镯约3.4克(假一罚三114348人巳参与",
"future_ts": 1766649930.969889,
"future_str": "2025-12-25 16:05:30",
"pos_seen": 0,
"room_title": "小北珠宝",
"room_title_raw": "小北珠宝",
"created_ts": 1766649768.5038307
},
{
"prize_value_yuan": 2999.0,
"content": "48后开奖03(千屿专属]新款电动滑板车迷你折叠电动上班校园",
"future_ts": 1766552917.478316,
"future_str": "2025-12-24 13:08:37",
"pos_seen": 2,
"room_title": "千Lsheila",
"room_title_raw": "千Lsheila",
"created_ts": 1766552692.1802008
"prize_value_yuan": 550.7,
"content": "30后开奖03时髦精8备铜电白Ayuko银长条梳子小众设计感-64.",
"future_ts": 1766650164.933606,
"future_str": "2025-12-25 16:09:24",
"pos_seen": 9,
"room_title": "94万本坎",
"room_title_raw": "9.4万本坎",
"created_ts": 1766649957.0618675
}
]
}
+2
View File
@@ -66,6 +66,8 @@ if os.path.exists(log_file):
+2
View File
@@ -79,6 +79,8 @@ if os.path.exists(log_file):
+2
View File
@@ -212,6 +212,8 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb
+2
View File
@@ -49,6 +49,8 @@ __version__ = "1.0.0"
+2
View File
@@ -38,6 +38,8 @@
+2
View File
@@ -38,6 +38,8 @@
+2
View File
@@ -128,6 +128,8 @@ python check_gpu_available.py
+2
View File
@@ -134,6 +134,8 @@
+2
View File
@@ -206,6 +206,8 @@ if __name__ == "__main__":
+2
View File
@@ -137,3 +137,5 @@