fix: Clean up code by removing unnecessary blank lines

- Removed excessive blank lines from various markdown and Python files to enhance readability and maintainability.
- Ensured consistent formatting across documentation and code files, improving overall project clarity.
This commit is contained in:
Your Name committed 2025-12-25 16:55:44 +08:00
1 parent c30b73bbd3
commit 29f7b19916
35 files changed
+7731 -200

No files matched your search

File diff suppressed because it is too large. Load diff
+2
View File
@@ -162,6 +162,8 @@ python cleanup_unused_files.py
+2
View File
@@ -173,6 +173,8 @@ except Exception as e:
+2
View File
@@ -376,6 +376,8 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
+2
View File
@@ -260,6 +260,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
+2
View File
@@ -231,6 +231,8 @@ python check_dependencies.py
+2
View File
@@ -210,6 +210,8 @@ douyin_guaji
+2
View File
@@ -151,6 +151,8 @@
+2
View File
@@ -363,6 +363,8 @@ douyin_fudai_finder.py
+2
View File
@@ -162,6 +162,8 @@ self.ocr = easyocr.Reader(
+2
View File
@@ -121,6 +121,8 @@ python 生成WPS流程图.py
+2
View File
@@ -135,6 +135,8 @@ else:
+24 -2
View File
@@ -47,6 +47,7 @@ def find_and_open_fudai_detail(
room_pos_ref: List[int], room_pos_ref: List[int],
) -> bool: ) -> bool:
"""在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。""" """在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。"""
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情 # 如果正在等待开奖,不应该再次打开福袋详情
try: try:
if getattr(analyser, "_waiting_for_lottery_result", False): if getattr(analyser, "_waiting_for_lottery_result", False):
@@ -57,6 +58,8 @@ def find_and_open_fudai_detail(
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(等待开奖中)", elapsed_seconds=round(elapsed, 2))
return False return False
except Exception: except Exception:
pass pass
@@ -116,15 +119,18 @@ def find_and_open_fudai_detail(
if not x: if not x:
try: try:
total_elapsed = time.time() - start_time
analyser._log_kv( analyser._log_kv(
"流程", "流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标", "find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0), x=int(x or 0),
max_wait_seconds=max_wait_seconds, max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(time.time() - start_time, 2), total_elapsed_seconds=round(total_elapsed, 2),
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(未找到福袋)", elapsed_seconds=round(elapsed, 2))
return False return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度) # 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
@@ -207,6 +213,8 @@ def find_and_open_fudai_detail(
analyser._last_fudai_detail_tuple = None analyser._last_fudai_detail_tuple = None
except Exception: except Exception:
pass pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(成功打开详情)", elapsed_seconds=round(elapsed, 2))
return True return True
else: else:
# 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间 # 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间
@@ -249,6 +257,8 @@ def find_and_open_fudai_detail(
analyser.last_fudai_x = 0 analyser.last_fudai_x = 0
except Exception: except Exception:
pass pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(误点击)", elapsed_seconds=round(elapsed, 2))
return False return False
except Exception as e: except Exception as e:
# 阶段检测失败,返回False # 阶段检测失败,返回False
@@ -260,6 +270,8 @@ def find_and_open_fudai_detail(
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(阶段检测异常)", elapsed_seconds=round(elapsed, 2))
return False return False
except Exception: except Exception:
try: try:
@@ -269,8 +281,12 @@ def find_and_open_fudai_detail(
getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0 getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0
) )
analyser.operation.delay(fudai_click_wait_seconds) analyser.operation.delay(fudai_click_wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(兜底成功)", elapsed_seconds=round(elapsed, 2))
return True return True
except Exception: except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(兜底失败)", elapsed_seconds=round(elapsed, 2))
return False return False
@@ -396,6 +412,7 @@ def filter_fudai_detail(
add_reservation_callback, add_reservation_callback,
) -> bool: ) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。""" """福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail) skip, reason = should_skip_fudai_by_config(analyser, detail)
try: try:
content = ( content = (
@@ -416,6 +433,8 @@ def filter_fudai_detail(
pass pass
if not skip: if not skip:
elapsed = time.time() - start_time
analyser._log_kv("流程", "filter_fudai_detail完成(筛选通过)", elapsed_seconds=round(elapsed, 2))
return False return False
try: try:
@@ -435,6 +454,9 @@ def filter_fudai_detail(
time.sleep(post_switch_delay_s or 1.2) time.sleep(post_switch_delay_s or 1.2)
except Exception: except Exception:
pass pass
return True
elapsed = time.time() - start_time
analyser._log_kv("流程", "filter_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2), reason=reason)
return True
return False return False
+105 -4
View File
@@ -236,8 +236,12 @@ class fudai_analyse:
# ===== 兼容原始脚本的一些简单封装方法 ===== # ===== 兼容原始脚本的一些简单封装方法 =====
def click(self, x: int, y: int) -> None: def click(self, x: int, y: int) -> None:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。""" """兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
start_time = time.time()
try: try:
self.operation.click(self.device_id, int(x), int(y)) self.operation.click(self.device_id, int(x), int(y))
elapsed = time.time() - start_time
if elapsed > 0.1: # 只记录耗时较长的点击操作
self._log_kv("操作", "点击操作", x=int(x), y=int(y), elapsed_seconds=round(elapsed, 2))
except Exception: except Exception:
pass pass
@@ -1672,6 +1676,7 @@ class fudai_analyse:
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ========== # ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
def run_once_basic(self) -> None: def run_once_basic(self) -> None:
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。""" """单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。"""
start_time = time.time()
# 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果
if getattr(self, "_waiting_for_lottery_result", False): if getattr(self, "_waiting_for_lottery_result", False):
try: try:
@@ -1760,6 +1765,8 @@ class fudai_analyse:
self._log_kv("参与", "等待期间检测到开奖结果,开始处理") self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
# 处理开奖结果(根据OCR结果执行不同操作) # 处理开奖结果(根据OCR结果执行不同操作)
self._handle_lottery_result_by_ocr(result) self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2))
return return
else: else:
# 还未开奖,继续等待(每2秒检测一次) # 还未开奖,继续等待(每2秒检测一次)
@@ -1769,12 +1776,16 @@ class fudai_analyse:
剩余秒数=int(remain_seconds), 剩余秒数=int(remain_seconds),
) )
self.operation.delay(2.0) self.operation.delay(2.0)
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(等待开奖中)", elapsed_seconds=round(elapsed, 2))
return # 返回,不执行其他操作 return # 返回,不执行其他操作
else: else:
# 还未到开奖时间,短暂等待后继续检测 # 还未到开奖时间,短暂等待后继续检测
wait_s = min(2.0, remain_seconds) wait_s = min(2.0, remain_seconds)
self._log_kv("参与", "等待开奖中", 剩余秒数=int(remain_seconds)) self._log_kv("参与", "等待开奖中", 剩余秒数=int(remain_seconds))
self.operation.delay(wait_s) self.operation.delay(wait_s)
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(等待开奖中)", elapsed_seconds=round(elapsed, 2))
return # 返回,不执行其他操作 return # 返回,不执行其他操作
except Exception as e: except Exception as e:
self._log_kv("参与", "等待开奖检测时出错", error=str(e)) self._log_kv("参与", "等待开奖检测时出错", error=str(e))
@@ -1814,6 +1825,8 @@ class fudai_analyse:
self._last_successful_attend_ts = current_ts self._last_successful_attend_ts = current_ts
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2))
return return
else: else:
# 从未成功参与过,检查运行时间 # 从未成功参与过,检查运行时间
@@ -1831,6 +1844,8 @@ class fudai_analyse:
self._return_to_recommend_and_reenter_live() self._return_to_recommend_and_reenter_live()
# 重置运行开始时间(在成功重新进入直播间后重置,避免立即再次触发) # 重置运行开始时间(在成功重新进入直播间后重置,避免立即再次触发)
# 注意:重置逻辑已移至 _return_to_recommend_and_reenter_live() 方法中 # 注意:重置逻辑已移至 _return_to_recommend_and_reenter_live() 方法中
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2))
return return
except Exception as e: except Exception as e:
try: try:
@@ -1967,6 +1982,8 @@ class fudai_analyse:
if focus_ref: if focus_ref:
self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) self.reservation_focus_until_ts = float(focus_ref[0] or 0.0)
# 已回退到最早开奖的预约直播间,本轮结束 # 已回退到最早开奖的预约直播间,本轮结束
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(预约队列满等待)", elapsed_seconds=round(elapsed, 2))
return return
# 检查是否所有预约已完成,需要重置到第一个直播间 # 检查是否所有预约已完成,需要重置到第一个直播间
@@ -2006,13 +2023,15 @@ class fudai_analyse:
pass pass
return return
# 单间模式(needswitch=False)下不启用任何预约回退逻辑 # 单间模式(needswitch=False)下不启用预约回退逻辑
# 因为单间模式不会切换直播间,不需要回退,预约会在当前直播间自动识别和参与
try: try:
needswitch_cfg = bool(getattr(self, "needswitch", True)) needswitch_cfg = bool(getattr(self, "needswitch", True))
except Exception: except Exception:
needswitch_cfg = True needswitch_cfg = True
if needswitch_cfg: if needswitch_cfg:
# 多间模式:需要回退到预约直播间
preempted = ( preempted = (
douyin_reservation_logic.process_reservation_attend_window( douyin_reservation_logic.process_reservation_attend_window(
analyser=self, analyser=self,
@@ -2039,7 +2058,26 @@ class fudai_analyse:
if preempted: if preempted:
# 已触发预约回退,本轮直接结束,等待下一轮在目标直播间执行详情逻辑 # 已触发预约回退,本轮直接结束,等待下一轮在目标直播间执行详情逻辑
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(预约回退)", elapsed_seconds=round(elapsed, 2))
return return
else:
# 单间模式:不需要回退,预约会在当前直播间自动识别和参与
# 只需要清理过期的预约
try:
import douyin_reservation_logic
douyin_reservation_logic.cleanup_expired_reservations(
self, self.reservations, _write_state
)
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] 单间模式下清理过期预约时出错",
error=str(e),
)
except Exception:
pass
except Exception: except Exception:
pass pass
@@ -2055,12 +2093,17 @@ class fudai_analyse:
pass pass
# 直接查找福袋,跳过阶段检测 # 直接查找福袋,跳过阶段检测
self._handle_live_room_has_or_not_fudai() self._handle_live_room_has_or_not_fudai()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(跳过阶段检测)", elapsed_seconds=round(elapsed, 2))
return return
# 1. 截图 + 阶段诊断 # 1. 截图 + 阶段诊断
screenshot_start = time.time()
ok = self.operation.get_screenshot(self.device_id) ok = self.operation.get_screenshot(self.device_id)
screenshot_elapsed = time.time() - screenshot_start
if not ok: if not ok:
self._log_kv("截图", "获取截图失败", ok=0) elapsed = time.time() - start_time
self._log_kv("截图", "获取截图失败", ok=0, elapsed_seconds=round(elapsed, 2), screenshot_elapsed_seconds=round(screenshot_elapsed, 2))
return return
stage, seen = self._diagnose_stage_from_current_screen() stage, seen = self._diagnose_stage_from_current_screen()
@@ -2068,7 +2111,8 @@ class fudai_analyse:
self._last_diag_seen = seen self._last_diag_seen = seen
self._last_diag_ts = time.time() self._last_diag_ts = time.time()
# 简洁输出阶段诊断结果(不额外添加分隔符,避免日志噪音) # 简洁输出阶段诊断结果(不额外添加分隔符,避免日志噪音)
self._log_kv("截图", "截图+阶段诊断", stage=stage, seen=seen) elapsed = time.time() - start_time
self._log_kv("截图", "截图+阶段诊断", stage=stage, seen=seen, elapsed_seconds=round(elapsed, 2), screenshot_elapsed_seconds=round(screenshot_elapsed, 2))
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复 # 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
try: try:
@@ -2116,6 +2160,8 @@ class fudai_analyse:
except Exception: except Exception:
pass pass
# 重新开始下一轮判断 # 重新开始下一轮判断
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(恢复进入直播间)", elapsed_seconds=round(elapsed, 2))
return return
except Exception as e: except Exception as e:
try: try:
@@ -2136,6 +2182,8 @@ class fudai_analyse:
self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗") self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗")
except Exception as e: except Exception as e:
self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e)) self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e))
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理优惠券弹窗)", elapsed_seconds=round(elapsed, 2))
return return
elif stage == "SHOPPING_REDPACKET_POPUP": elif stage == "SHOPPING_REDPACKET_POPUP":
# 购物红包弹窗:点击关闭按钮 # 购物红包弹窗:点击关闭按钮
@@ -2148,6 +2196,8 @@ class fudai_analyse:
self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y) self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y)
except Exception as e: except Exception as e:
self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e)) self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e))
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理购物红包弹窗)", elapsed_seconds=round(elapsed, 2))
return return
elif stage == "FANSCLUB_JOIN": elif stage == "FANSCLUB_JOIN":
# 粉丝团加入阶段:点击加入粉丝团按钮 # 粉丝团加入阶段:点击加入粉丝团按钮
@@ -2278,10 +2328,14 @@ class fudai_analyse:
if fansclub_fail_action == "switch": if fansclub_fail_action == "switch":
self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间") self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间")
self.swipe_up_to_next_live() self.swipe_up_to_next_live()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理粉丝团)", elapsed_seconds=round(elapsed, 2))
return return
elif stage == "FUDai_DETAIL": elif stage == "FUDai_DETAIL":
# 已经在详情页:直接读详情并决定是否参与 # 已经在详情页:直接读详情并决定是否参与
self._handle_in_fudai_detail() self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理福袋详情)", elapsed_seconds=round(elapsed, 2))
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"): elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
# 在直播间:如果刚刚切换了直播间,等待福袋加载 # 在直播间:如果刚刚切换了直播间,等待福袋加载
just_switched = getattr(self, "_just_switched_room", False) just_switched = getattr(self, "_just_switched_room", False)
@@ -2308,6 +2362,8 @@ class fudai_analyse:
# 在直播间:寻找福袋图标并尝试点开 # 在直播间:寻找福袋图标并尝试点开
self._handle_live_room_has_or_not_fudai() self._handle_live_room_has_or_not_fudai()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理直播间)", elapsed_seconds=round(elapsed, 2))
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"): elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
# 处理推荐/关注/直播列表页:回到直播间或切换 # 处理推荐/关注/直播列表页:回到直播间或切换
if stage == "RECOMMEND_PAGE": if stage == "RECOMMEND_PAGE":
@@ -2369,14 +2425,19 @@ class fudai_analyse:
self.swipe_up_to_next_live() self.swipe_up_to_next_live()
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理开奖结果)", elapsed_seconds=round(elapsed, 2))
return return
elif stage in ("LIVE_CLOSED",): elif stage in ("LIVE_CLOSED",):
# 直播结束:下滑/切下一个 # 直播结束:下滑/切下一个
self._log_kv("阶段", "当前直播已结束,尝试切换下一个") self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
self.swipe_up_to_next_live() self.swipe_up_to_next_live()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(直播结束)", elapsed_seconds=round(elapsed, 2))
else: else:
# 未识别出特殊阶段:尽量保持原地,交给上层循环 # 未识别出特殊阶段:尽量保持原地,交给上层循环
self._log_kv("阶段", "未匹配到特定阶段", stage=stage) elapsed = time.time() - start_time
self._log_kv("阶段", "未匹配到特定阶段", stage=stage, elapsed_seconds=round(elapsed, 2))
def _check_lottery_result_by_ocr(self) -> Optional[str]: def _check_lottery_result_by_ocr(self) -> Optional[str]:
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。 """通过OCR识别开奖结果按钮区域,返回识别到的文本类型。
@@ -2430,6 +2491,7 @@ class fudai_analyse:
参数: 参数:
result_type: "我知道了" 或 "立即领取奖品" result_type: "我知道了" 或 "立即领取奖品"
""" """
start_time = time.time()
try: try:
if result_type == "我知道了": if result_type == "我知道了":
# 识别到"我知道了",点击按钮,切换下一个直播间 # 识别到"我知道了",点击按钮,切换下一个直播间
@@ -2514,6 +2576,9 @@ class fudai_analyse:
self.swipe_up_to_next_live() self.swipe_up_to_next_live()
except Exception: except Exception:
pass pass
finally:
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_lottery_result_by_ocr完成", elapsed_seconds=round(elapsed, 2), result_type=result_type)
def _shot_and_diagnose( def _shot_and_diagnose(
self, tag: str, msg: str, device_id: str, diagnose: bool = True self, tag: str, msg: str, device_id: str, diagnose: bool = True
@@ -2553,12 +2618,15 @@ class fudai_analyse:
# ========== 基础动作封装 ========== # ========== 基础动作封装 ==========
def swipe_up_to_next_live(self) -> None: def swipe_up_to_next_live(self) -> None:
"""上滑切换直播间(简单版封装)。""" """上滑切换直播间(简单版封装)。"""
start_time = time.time()
douyin_swipe_ops.swipe_up_switch_live(self) douyin_swipe_ops.swipe_up_switch_live(self)
# 记录直播间位置:上滑 +1 # 记录直播间位置:上滑 +1
try: try:
self.room_pos += 1 self.room_pos += 1
except Exception: except Exception:
self.room_pos = 0 self.room_pos = 0
elapsed = time.time() - start_time
self._log_kv("操作", "上滑切换直播间", elapsed_seconds=round(elapsed, 2))
# 记录滑动次数(用于滑动次数重置功能) # 记录滑动次数(用于滑动次数重置功能)
try: try:
@@ -2737,6 +2805,7 @@ class fudai_analyse:
def swipe_down_back_from_live(self) -> None: def swipe_down_back_from_live(self) -> None:
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。""" """上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
start_time = time.time()
try: try:
douyin_swipe_ops.swipe_down_back_live(self) douyin_swipe_ops.swipe_down_back_live(self)
except Exception: except Exception:
@@ -2954,6 +3023,7 @@ class fudai_analyse:
# ========== 福袋相关 ========== # ========== 福袋相关 ==========
def _handle_in_fudai_detail(self) -> None: def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。""" """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
start_time = time.time()
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋 # 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
# 检查是否是第二次打开福袋详情(已经读取过详情) # 检查是否是第二次打开福袋详情(已经读取过详情)
@@ -3091,6 +3161,8 @@ class fudai_analyse:
self._last_fudai_detail_tuple = None self._last_fudai_detail_tuple = None
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(第二次打开已参与)", elapsed_seconds=round(elapsed, 2))
return return
# 如果还需要参与,继续后续的参与决策流程 # 如果还需要参与,继续后续的参与决策流程
except Exception as e: except Exception as e:
@@ -3129,6 +3201,8 @@ class fudai_analyse:
douyin_fudai_detail.close_fudai_detail(self) douyin_fudai_detail.close_fudai_detail(self)
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(数据验证失败)", elapsed_seconds=round(elapsed, 2))
return return
except Exception: except Exception:
pass pass
@@ -3231,6 +3305,8 @@ class fudai_analyse:
douyin_fudai_detail.close_fudai_detail(self) douyin_fudai_detail.close_fudai_detail(self)
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(记录预约)", elapsed_seconds=round(elapsed, 2))
return return
except Exception as e: except Exception as e:
# 高价值检查异常,记录日志但继续流程 # 高价值检查异常,记录日志但继续流程
@@ -3294,6 +3370,8 @@ class fudai_analyse:
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2))
return return
except Exception as e: except Exception as e:
# 筛选检查异常,记录日志但继续流程 # 筛选检查异常,记录日志但继续流程
@@ -3334,6 +3412,8 @@ class fudai_analyse:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(优惠券弹窗)", elapsed_seconds=round(elapsed, 2))
return return
elif last_status == "watch_task": elif last_status == "watch_task":
try: try:
@@ -3343,6 +3423,8 @@ class fudai_analyse:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(观看任务)", elapsed_seconds=round(elapsed, 2))
return return
elif last_status == "validation_failed": elif last_status == "validation_failed":
try: try:
@@ -3352,6 +3434,8 @@ class fudai_analyse:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(验证失败)", elapsed_seconds=round(elapsed, 2))
return return
elif last_status == "error": elif last_status == "error":
# 检查是否是任务数量为0的错误 # 检查是否是任务数量为0的错误
@@ -3427,6 +3511,8 @@ class fudai_analyse:
self._fudai_detail_consecutive_failures = 0 self._fudai_detail_consecutive_failures = 0
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(连续失败)", elapsed_seconds=round(elapsed, 2))
return return
else: else:
try: try:
@@ -3437,6 +3523,8 @@ class fudai_analyse:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(任务数量为0)", elapsed_seconds=round(elapsed, 2))
return return
except Exception: except Exception:
pass pass
@@ -3471,6 +3559,8 @@ class fudai_analyse:
except Exception: except Exception:
pass pass
douyin_fudai_detail.close_fudai_detail(self) douyin_fudai_detail.close_fudai_detail(self)
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(验证失败)", elapsed_seconds=round(elapsed, 2))
return return
except Exception: except Exception:
pass pass
@@ -3490,6 +3580,8 @@ class fudai_analyse:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(无效详情)", elapsed_seconds=round(elapsed, 2))
return return
except Exception: except Exception:
pass pass
@@ -3523,6 +3615,8 @@ class fudai_analyse:
self._log_kv("参与", "详情数据为 None,无法执行参与决策") self._log_kv("参与", "详情数据为 None,无法执行参与决策")
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(详情为None)", elapsed_seconds=round(elapsed, 2))
return return
join_result = douyin_fudai_core.basic_join_decision(self, detail) join_result = douyin_fudai_core.basic_join_decision(self, detail)
@@ -3669,6 +3763,7 @@ class fudai_analyse:
def _handle_live_room_has_or_not_fudai(self) -> None: def _handle_live_room_has_or_not_fudai(self) -> None:
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号".""" """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"."""
start_time = time.time()
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
# 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋 # 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋
try: try:
@@ -3685,6 +3780,8 @@ class fudai_analyse:
pass pass
# 直接调用详情处理逻辑,不查找福袋 # 直接调用详情处理逻辑,不查找福袋
self._handle_in_fudai_detail() self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(已验证详情页)", elapsed_seconds=round(elapsed, 2))
return return
except Exception: except Exception:
pass pass
@@ -3724,7 +3821,11 @@ class fudai_analyse:
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
swipe_times_ref=swipe_times_ref, swipe_times_ref=swipe_times_ref,
) )
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(无福袋)", elapsed_seconds=round(elapsed, 2))
return return
# 成功打开详情:调用同一套详情处理逻辑 # 成功打开详情:调用同一套详情处理逻辑
self._handle_in_fudai_detail() self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(成功打开详情)", elapsed_seconds=round(elapsed, 2))
+28 -2
View File
@@ -1551,6 +1551,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
返回: 返回:
(skip, reason) 其中 reason 为简单文字原因,便于日志查看。 (skip, reason) 其中 reason 为简单文字原因,便于日志查看。
""" """
start_time = time.time()
# 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过 # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过
try: try:
needswitch = bool(getattr(analyser, "needswitch", True)) needswitch = bool(getattr(analyser, "needswitch", True))
@@ -1583,6 +1584,8 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("筛选", "should_skip_fudai_by_config完成(观看任务)", elapsed_seconds=round(elapsed, 2))
return True, "watch_task_detected" return True, "watch_task_detected"
time_text = str(detail[1] or "") time_text = str(detail[1] or "")
try: try:
@@ -1832,6 +1835,8 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("筛选", "should_skip_fudai_by_config完成(倒计时大于阈值)", elapsed_seconds=round(elapsed, 2))
return True, f"countdown_gt_{skip_if_gt}" return True, f"countdown_gt_{skip_if_gt}"
else: else:
try: try:
@@ -1878,6 +1883,8 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("筛选", "should_skip_fudai_by_config完成(内容关键词过滤)", elapsed_seconds=round(elapsed, 2))
return True, "content_not_wanted" return True, "content_not_wanted"
else: else:
try: try:
@@ -1901,6 +1908,8 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("筛选", "should_skip_fudai_by_config完成(通过)", elapsed_seconds=round(elapsed, 2))
return False, "ok" return False, "ok"
@@ -1911,6 +1920,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
True 表示已经参与或已处理完成; True 表示已经参与或已处理完成;
False 表示未参与(例如被配置筛掉或参与失败)。 False 表示未参与(例如被配置筛掉或参与失败)。
""" """
start_time = time.time()
# 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值
content = "" content = ""
prize_value_yuan = 0.0 prize_value_yuan = 0.0
@@ -1934,6 +1944,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(优惠券弹窗)", elapsed_seconds=round(elapsed, 2))
return False return False
elif last_status == "validation_failed": elif last_status == "validation_failed":
try: try:
@@ -1943,6 +1955,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(验证失败)", elapsed_seconds=round(elapsed, 2))
return False return False
except Exception: except Exception:
pass pass
@@ -1964,6 +1978,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(验证失败)", elapsed_seconds=round(elapsed, 2))
return False return False
except Exception: except Exception:
pass pass
@@ -1979,6 +1995,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(无效详情)", elapsed_seconds=round(elapsed, 2))
return False return False
# 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋 # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋
@@ -1994,7 +2012,10 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
) )
except Exception: except Exception:
pass pass
return attend_choujiang(analyser) result = attend_choujiang(analyser)
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(单间模式参与)", elapsed_seconds=round(elapsed, 2), result=result)
return result
# 检查是否启用高价值预约,以及价值是否达到阈值 # 检查是否启用高价值预约,以及价值是否达到阈值
try: try:
@@ -2520,6 +2541,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
# 切房失败不影响主流程,直接返回 # 切房失败不影响主流程,直接返回
pass pass
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(记录预约)", elapsed_seconds=round(elapsed, 2))
return True return True
except Exception: except Exception:
# 若预约逻辑异常,退化为直接参与抽奖 # 若预约逻辑异常,退化为直接参与抽奖
@@ -2536,4 +2559,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖")
except Exception: except Exception:
pass pass
return attend_choujiang(analyser) result = attend_choujiang(analyser)
elapsed = time.time() - start_time
analyser._log_kv("参与", "basic_join_decision完成(参与抽奖)", elapsed_seconds=round(elapsed, 2), result=result)
return result
+14
View File
@@ -516,6 +516,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值; 3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。 4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
""" """
start_time = time.time()
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取) # 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage # 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
task_count = 0 task_count = 0
@@ -563,6 +564,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass pass
now = time.time() now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(任务数量为0)", elapsed_seconds=round(elapsed, 2))
return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count} return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理 # 如果任务数不在(1,2,3)范围内,默认按2个任务处理
@@ -603,6 +606,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass pass
now = time.time() now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(截图失败)", elapsed_seconds=round(elapsed, 2))
return "error", tup_err, {"reason": "screenshot_failed"} return "error", tup_err, {"reason": "screenshot_failed"}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理 # 如果任务数不在(1,2,3)范围内,默认按2个任务处理
@@ -626,6 +631,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass pass
now = time.time() now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2))
return "error", tup_err, {} return "error", tup_err, {}
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志) # 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
@@ -652,6 +659,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass pass
now = time.time() now = time.time()
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0)) tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2))
return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count} return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count}
# 解析倒计时 -> (剩余秒数, 未来时间戳) # 解析倒计时 -> (剩余秒数, 未来时间戳)
@@ -699,6 +708,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
) )
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2))
return "ok", detail_tuple, extra return "ok", detail_tuple, extra
@@ -714,6 +725,7 @@ def read_fudai_detail_with_retries(
与原版保持兼容:总是返回 与原版保持兼容:总是返回
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple) (content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
""" """
start_time = time.time()
# 首次识别前等待,确保详情页完全加载 # 首次识别前等待,确保详情页完全加载
# 如果优化查找器已经验证过详情页,可以减少等待时间 # 如果优化查找器已经验证过详情页,可以减少等待时间
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False) already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
@@ -1003,6 +1015,8 @@ def read_fudai_detail_with_retries(
except Exception: except Exception:
pass pass
elapsed = time.time() - start_time
analyser._log_kv("福袋详情", "read_fudai_detail_with_retries完成", elapsed_seconds=round(elapsed, 2), status=last_status, attempts=max_attempts)
return last_tuple return last_tuple
+176 -166
View File
@@ -99,76 +99,23 @@ class FudaiDetector:
self.rx, self.ry, self.y_pianyi = 1080, 2400, 0 self.rx, self.ry, self.y_pianyi = 1080, 2400, 0
def _init_search_regions(self): def _init_search_regions(self):
"""初始化搜索区域(按优先级排序,基于日志分析和实际区域优化) """初始化搜索区域
基于日志分析结果(1158条记录): 实际福袋出现区域:(34, 348) 到 (561, 451) [基于1080x2400基准]
- X=163 出现1060次(91.54%) 只在此区域内搜索,不扩大搜索范围
- X=166 出现48次(4.15%)
- 左上角区域(41-410)占100%
- 中间区域(156-269)占96.03%
- 平均位置:X=169.8,标准差:35.5
- 最热门区间:150-199(96.03%)
实际福袋出现区域:(34, 363) 到 (608, 451) [基于1080x2400基准]
优化后的优先级:
1. 实际福袋区域(X=34-608, Y=363-451):覆盖所有可能的福袋位置
2. 最热门区域(X=98-240,覆盖91%+):优先检测,最快命中
3. 扩展热门区域(X=41-410,覆盖100%):兜底检测
4. 右上角(X=670-1039):较少见,最后检测
""" """
base_y = 403 * self.ry // 2400 + self.y_pianyi # 实际福袋区域(X=34-561, Y=348-451)
# 这是用户确认的福袋实际出现区域,只在此区域内搜索
# 优先级1:实际福袋区域(X=34-608, Y=363-451)
# 这是用户确认的福袋实际出现区域,优先检测确保覆盖所有可能位置
self.search_regions = [ self.search_regions = [
{ {
"name": "实际福袋区域", "name": "实际福袋区域",
"priority": 1, "priority": 1,
"x1": 34 * self.rx // 1080, "x1": 34 * self.rx // 1080,
"x2": 608 * self.rx // 1080, "x2": 561 * self.rx // 1080,
"y_top": 363 * self.ry // 2400 + self.y_pianyi, "y_top": 348 * self.ry // 2400 + self.y_pianyi,
"y_bottom": 451 * self.ry // 2400 + self.y_pianyi,
"y": (363 + 451) // 2 * self.ry // 2400 + self.y_pianyi, # 中心Y坐标
"y_range": (451 - 363) // 2 + 1, # 覆盖整个Y范围
},
# 优先级2:最热门区域(X=98-240,基于日志分析,覆盖91%+的情况)
# 这是最集中的区域,优先检测可以最快命中
{
"name": "最热门区域",
"priority": 2,
"x1": 98 * self.rx // 1080,
"x2": 240 * self.rx // 1080,
"y": base_y,
"y_range": 7, # 上下3-4行
},
# 优先级3:扩展热门区域(X=41-410,覆盖100%的情况)
# 如果最热门区域没找到,扩大范围搜索
{
"name": "扩展热门区域",
"priority": 3,
"x1": 41 * self.rx // 1080,
"x2": 410 * self.rx // 1080,
"y": base_y,
"y_range": 7,
},
# 优先级4:右上角(较少见)
{
"name": "右上角",
"priority": 4,
"x1": 670 * self.rx // 1080,
"x2": 1039 * self.rx // 1080,
"y": base_y,
"y_range": 7,
},
# 优先级5:中间区域(模板匹配兜底,用于特殊情况)
{
"name": "中间区域",
"priority": 5,
"x1": 156 * self.rx // 1080,
"x2": 269 * self.rx // 1080,
"y_top": 351 * self.ry // 2400 + self.y_pianyi,
"y_bottom": 451 * self.ry // 2400 + self.y_pianyi, "y_bottom": 451 * self.ry // 2400 + self.y_pianyi,
"y": (348 + 451) // 2 * self.ry // 2400 + self.y_pianyi, # 中心Y坐标
"y_range": (451 - 348) // 2 + 1, # 覆盖整个Y范围
}, },
] ]
@@ -561,7 +508,7 @@ class FudaiDetector:
# 多种匹配方法(按优先级排序) # 多种匹配方法(按优先级排序)
match_methods = [ match_methods = [
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # 归一化相关系数(最常用) (cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # 归一化相关系数(最常用)
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # 归一化相关匹配 (cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # 归一化相关匹配
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # 归一化平方差(值越小越好) (cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # 归一化平方差(值越小越好)
] ]
@@ -576,13 +523,17 @@ class FudaiDetector:
# 缩放模板(彩色和灰度) # 缩放模板(彩色和灰度)
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th))
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th))
scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) scaled_template_gray_enhanced = cv2.resize(
template_gray_enhanced, (scaled_tw, scaled_th)
)
# 尝试多种匹配方法 # 尝试多种匹配方法
for method, method_name in match_methods: for method, method_name in match_methods:
try: try:
# 方法1:彩色匹配 # 方法1:彩色匹配
res_color = cv2.matchTemplate(search_roi_bgr, scaled_template_color, method) res_color = cv2.matchTemplate(
search_roi_bgr, scaled_template_color, method
)
if method == cv2.TM_SQDIFF_NORMED: if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_color) _min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_color)
score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好 score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好
@@ -597,7 +548,9 @@ class FudaiDetector:
best_method = f"{method_name}_color" best_method = f"{method_name}_color"
# 方法2:灰度匹配(更稳定,不受光照影响) # 方法2:灰度匹配(更稳定,不受光照影响)
res_gray = cv2.matchTemplate(search_roi_gray, scaled_template_gray, method) res_gray = cv2.matchTemplate(
search_roi_gray, scaled_template_gray, method
)
if method == cv2.TM_SQDIFF_NORMED: if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_gray) _min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_gray)
score = 1.0 - max_val score = 1.0 - max_val
@@ -612,12 +565,18 @@ class FudaiDetector:
best_method = f"{method_name}_gray" best_method = f"{method_name}_gray"
# 方法3:增强对比度后的灰度匹配 # 方法3:增强对比度后的灰度匹配
res_gray_enhanced = cv2.matchTemplate(search_roi_gray_enhanced, scaled_template_gray_enhanced, method) res_gray_enhanced = cv2.matchTemplate(
search_roi_gray_enhanced, scaled_template_gray_enhanced, method
)
if method == cv2.TM_SQDIFF_NORMED: if method == cv2.TM_SQDIFF_NORMED:
_min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_gray_enhanced) _min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(
res_gray_enhanced
)
score = 1.0 - max_val score = 1.0 - max_val
else: else:
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray_enhanced) _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(
res_gray_enhanced
)
score = max_val score = max_val
if score > best_score: if score > best_score:
@@ -636,16 +595,20 @@ class FudaiDetector:
scale = min(rh / max(th, 1), rw / max(tw, 1)) scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0: if scale > 0:
template_color = cv2.resize( template_color = cv2.resize(
template_color, (max(1, int(tw * scale)), max(1, int(th * scale))) template_color,
(max(1, int(tw * scale)), max(1, int(th * scale))),
) )
template_gray = cv2.resize( template_gray = cv2.resize(
template_gray, (max(1, int(tw * scale)), max(1, int(th * scale))) template_gray,
(max(1, int(tw * scale)), max(1, int(th * scale))),
) )
th, tw = template_color.shape[:2] th, tw = template_color.shape[:2]
if th <= rh and tw <= rw: if th <= rh and tw <= rw:
try: try:
res = cv2.matchTemplate(search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED) res = cv2.matchTemplate(
search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED
)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
best_score = max_val best_score = max_val
best_x = max_loc[0] best_x = max_loc[0]
@@ -695,6 +658,7 @@ class FudaiDetector:
if max_val >= threshold and best_x is not None: if max_val >= threshold and best_x is not None:
try: try:
from PIL import ImageDraw from PIL import ImageDraw
annotated_roi = search_roi_pil.copy() annotated_roi = search_roi_pil.copy()
draw = ImageDraw.Draw(annotated_roi) draw = ImageDraw.Draw(annotated_roi)
best_tw = int(tw * best_scale) if best_score >= 0 else tw best_tw = int(tw * best_scale) if best_score >= 0 else tw
@@ -705,7 +669,10 @@ class FudaiDetector:
match_x2 = best_x + best_tw match_x2 = best_x + best_tw
match_y2 = best_th match_y2 = best_th
rect_coords: Tuple[float, float, float, float] = ( rect_coords: Tuple[float, float, float, float] = (
float(match_x1), float(match_y1), float(match_x2), float(match_y2) float(match_x1),
float(match_y1),
float(match_x2),
float(match_y2),
) )
draw.rectangle(rect_coords, outline="green", width=2) draw.rectangle(rect_coords, outline="green", width=2)
search_roi_pil = annotated_roi search_roi_pil = annotated_roi
@@ -726,7 +693,7 @@ class FudaiDetector:
"best_scale": round(best_scale, 2) if best_score >= 0 else None, "best_scale": round(best_scale, 2) if best_score >= 0 else None,
"template_size": f"{tw}x{th}", "template_size": f"{tw}x{th}",
"search_size": f"{rw}x{rh}", "search_size": f"{rw}x{rh}",
} },
) )
if debug_path: if debug_path:
try: try:
@@ -736,7 +703,7 @@ class FudaiDetector:
path=debug_path, path=debug_path,
region=region.get("name", "unknown"), region=region.get("name", "unknown"),
score=round(max_val, 4), score=round(max_val, 4),
threshold=threshold threshold=threshold,
) )
except Exception: except Exception:
pass pass
@@ -807,7 +774,9 @@ class FudaiDetector:
# 确定Y范围(与检测区域相同) # 确定Y范围(与检测区域相同)
if "y_top" in region and "y_bottom" in region: if "y_top" in region and "y_bottom" in region:
confirm_y_top = max(0, min(int(region.get("y_top", 0)), height)) confirm_y_top = max(0, min(int(region.get("y_top", 0)), height))
confirm_y_bottom = max(0, min(int(region.get("y_bottom", height)), height)) confirm_y_bottom = max(
0, min(int(region.get("y_bottom", height)), height)
)
else: else:
scan_y = region.get("y", 0) scan_y = region.get("y", 0)
y_range = region.get("y_range", 7) y_range = region.get("y_range", 7)
@@ -849,14 +818,18 @@ class FudaiDetector:
# 检查配置:是否允许在模板匹配失败时信任像素检测 # 检查配置:是否允许在模板匹配失败时信任像素检测
try: try:
trust_pixel_when_template_fails = bool( trust_pixel_when_template_fails = bool(
getattr(self.analyser, "fudai_trust_pixel_when_template_fails", True) getattr(
self.analyser,
"fudai_trust_pixel_when_template_fails",
True,
)
) )
except Exception: except Exception:
trust_pixel_when_template_fails = True # 默认信任 trust_pixel_when_template_fails = True # 默认信任
# 如果配置允许,且像素检测在可信区域命中,信任像素检测 # 如果配置允许,且像素检测在可信区域命中,信任像素检测
if trust_pixel_when_template_fails: if trust_pixel_when_template_fails:
if region.get("name") in ["实际福袋区域", "最热门区域", "扩展热门区域"]: if region.get("name") == "实际福袋区域":
# 信任像素检测结果 # 信任像素检测结果
overall_elapsed = (time.time() - overall_start) * 1000 overall_elapsed = (time.time() - overall_start) * 1000
try: try:
@@ -873,18 +846,19 @@ class FudaiDetector:
pass pass
return detected_x, "pixel" return detected_x, "pixel"
# 不信任,继续搜索下一个区域 # 不信任,返回未找到(不再扩大搜索范围)
try: try:
self.analyser._log_kv( self.analyser._log_kv(
"[福袋查找] 像素检测命中但模板确认失败", "[福袋查找] 像素检测命中但模板确认失败",
f"{region['name']}", f"{region['name']}",
pixel_x=detected_x, pixel_x=detected_x,
confirm_region=f"({confirm_region['x1']},{confirm_y_top})-({confirm_region['x2']},{confirm_y_bottom})", confirm_region=f"({confirm_region['x1']},{confirm_y_top})-({confirm_region['x2']},{confirm_y_bottom})",
说明="在整个检测区域内未找到模板匹配,继续搜索", 说明="在整个检测区域内未找到模板匹配,不再扩大搜索范围",
) )
except Exception: except Exception:
pass pass
continue # 继续搜索下一个区域 # 不再继续搜索,直接返回未找到
break
except Exception as e: except Exception as e:
# 模板确认过程异常,信任像素检测结果 # 模板确认过程异常,信任像素检测结果
@@ -912,35 +886,17 @@ class FudaiDetector:
pass pass
return detected_x, "pixel" return detected_x, "pixel"
# 像素检测未命中时,使用模板匹配(仅对中间区域,且模板匹配已启用) # 像素检测未命中,记录日志
if template_match_enabled and region.get("name") == "中间区域": try:
detected_x = self.detect_by_template(pic, region) pixel_elapsed = (time.time() - overall_start) * 1000
if detected_x is not None: self.analyser._log_kv(
overall_elapsed = (time.time() - overall_start) * 1000 "[福袋查找] 像素检测",
try: f"{region['name']}未命中",
self.analyser._log_kv( elapsed_ms=round(pixel_elapsed, 2),
"[福袋查找] 检测完成", region=region["name"],
"模板匹配命中", )
total_elapsed_ms=round(overall_elapsed, 2), except Exception:
region=region["name"], pass
x=detected_x,
method="template",
)
except Exception:
pass
return detected_x, "template"
else:
# 记录像素检测未命中的区域(非中间区域)
try:
pixel_elapsed = (time.time() - overall_start) * 1000
self.analyser._log_kv(
"[福袋查找] 像素检测",
f"{region['name']}未命中",
elapsed_ms=round(pixel_elapsed, 2),
region=region["name"],
)
except Exception:
pass
overall_elapsed = (time.time() - overall_start) * 1000 overall_elapsed = (time.time() - overall_start) * 1000
try: try:
@@ -1003,6 +959,7 @@ class FudaiClickExecutor:
try: try:
# 检查是否有红包弹窗 # 检查是否有红包弹窗
import douyin_popups import douyin_popups
has_redpacket = douyin_popups.check_shopping_redpacket_popup(self.analyser) has_redpacket = douyin_popups.check_shopping_redpacket_popup(self.analyser)
if has_redpacket: if has_redpacket:
try: try:
@@ -1033,9 +990,12 @@ class FudaiClickExecutor:
# 截图检查区域 # 截图检查区域
self.analyser.cut_pic( self.analyser.cut_pic(
check_x1_base, check_y1_base, check_x1_base,
check_x2_base, check_y2_base, check_y1_base,
"", "檢查紅包特徵" check_x2_base,
check_y2_base,
"",
"檢查紅包特徵",
) )
# OCR识别 # OCR识别
@@ -1044,9 +1004,18 @@ class FudaiClickExecutor:
).strip() ).strip()
# 检查是否包含红包关键词 # 检查是否包含红包关键词
redpacket_keywords = ("最高金额", "开抢", "邀你抢", "抢红包", "购物红包", "手气红包") redpacket_keywords = (
"最高金额",
"开抢",
"邀你抢",
"抢红包",
"购物红包",
"手气红包",
)
if check_text and any(kw in check_text for kw in redpacket_keywords): if check_text and any(kw in check_text for kw in redpacket_keywords):
matched_keywords = [kw for kw in redpacket_keywords if kw in check_text] matched_keywords = [
kw for kw in redpacket_keywords if kw in check_text
]
try: try:
self.analyser._log_kv( self.analyser._log_kv(
"[福袋查找] 点击", "[福袋查找] 点击",
@@ -1094,7 +1063,7 @@ class FudaiClickExecutor:
"[福袋查找] 点击", "[福袋查找] 点击",
"成功", "成功",
elapsed_ms=round(elapsed, 2), elapsed_ms=round(elapsed, 2),
wait_seconds=click_wait_time wait_seconds=click_wait_time,
) )
except Exception: except Exception:
pass pass
@@ -1117,7 +1086,7 @@ class FudaiClickExecutor:
"[福袋查找] 点击", "[福袋查找] 点击",
"成功(回退模式)", "成功(回退模式)",
elapsed_ms=round(elapsed, 2), elapsed_ms=round(elapsed, 2),
wait_seconds=click_wait_time wait_seconds=click_wait_time,
) )
except Exception: except Exception:
pass pass
@@ -1186,64 +1155,96 @@ class FudaiDetailVerifier:
# 保存完整截图并标注OCR区域 # 保存完整截图并标注OCR区域
try: try:
import douyin_screenshot_manager import douyin_screenshot_manager
pic_path = path_config.get_screenshot_path() pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path): if os.path.exists(pic_path):
pic = Image.open(pic_path) pic = Image.open(pic_path)
pic.load() pic.load()
pic_rgb = pic.convert("RGB") pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size width, height = pic_rgb.size
rx = int(getattr(self.analyser, "resolution_ratio_x", 1080) or 1080) rx = int(
ry = int(getattr(self.analyser, "resolution_ratio_y", 2400) or 2400) getattr(self.analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(self.analyser, "resolution_ratio_y", 2400)
or 2400
)
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545 x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
x1 = int(x1_base * width / rx) x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry) y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx) x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry) y2 = int((y2_base + y_pianyi) * height / ry)
x1 = max(0, min(x1, width - 1)) x1 = max(0, min(x1, width - 1))
y1 = max(0, min(y1, height - 1)) y1 = max(0, min(y1, height - 1))
x2 = max(0, min(x2, width - 1)) x2 = max(0, min(x2, width - 1))
y2 = max(0, min(y2, height - 1)) y2 = max(0, min(y2, height - 1))
if x1 < x2 and y1 < y2: if x1 < x2 and y1 < y2:
debug_path = douyin_screenshot_manager.save_debug_image( debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, pic_rgb,
operation_type="ocr", operation_type="ocr",
picname="验证邀你抢红包区域", picname="验证邀你抢红包区域",
step="before_ocr", step="before_ocr",
coords=(x1, y1, x2, y2), coords=(x1, y1, x2, y2),
extra_info={ extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}", "size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi, "y_offset": y_pianyi,
} },
)
if debug_path:
try:
self.analyser._log_kv(
"[调试图像]",
"OCR识别前保存完整截图(验证邀你抢红包区域)",
path=debug_path,
) )
if debug_path: except Exception:
try: pass
self.analyser._log_kv(
"[调试图像]",
"OCR识别前保存完整截图(验证邀你抢红包区域)",
path=debug_path,
)
except Exception:
pass
except Exception: except Exception:
pass pass
# cut_pic 方法内部会根据分辨率自动缩放,所以直接传入基准坐标 # cut_pic 方法内部会根据分辨率自动缩放,所以直接传入基准坐标
self.analyser.cut_pic(238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi) self.analyser.cut_pic(
ocr_text = str(self.analyser.operation.analyse_pic_word("验证邀你抢红包区域", 0) or "") 238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi
)
ocr_text = str(
self.analyser.operation.analyse_pic_word(
"验证邀你抢红包区域", 0
)
or ""
)
# 如果模式0未识别到,尝试模式1 # 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(getattr(self.analyser, "enable_ocr_mode1", False)) enable_ocr_mode1 = bool(
if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))): getattr(self.analyser, "enable_ocr_mode1", False)
ocr_text = str(self.analyser.operation.analyse_pic_word("验证邀你抢红包区域", 1) or "") )
if enable_ocr_mode1 and (
not ocr_text
or not any(
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
)
):
ocr_text = str(
self.analyser.operation.analyse_pic_word(
"验证邀你抢红包区域", 1
)
or ""
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体) # 检测是否包含"邀你抢红包"相关关键词(支持变体)
# 关键词包括:"邀你抢红包"、"邀你抢手气红包"、"邀你抢"等 # 关键词包括:"邀你抢红包"、"邀你抢手气红包"、"邀你抢"等
redpacket_keywords = ("邀你抢红包", "邀你抢手气红包", "邀你抢", "抢红包", "抢手气") redpacket_keywords = (
"邀你抢红包",
"邀你抢手气红包",
"邀你抢",
"抢红包",
"抢手气",
)
if ocr_text and any(kw in ocr_text for kw in redpacket_keywords): if ocr_text and any(kw in ocr_text for kw in redpacket_keywords):
elapsed = (time.time() - start_time) * 1000 elapsed = (time.time() - start_time) * 1000
try: try:
@@ -1260,7 +1261,10 @@ class FudaiDetailVerifier:
# 额外等待,确保参与按钮加载完成 # 额外等待,确保参与按钮加载完成
# 验证时只检测了详情页是否打开,但参与按钮可能需要额外时间加载 # 验证时只检测了详情页是否打开,但参与按钮可能需要额外时间加载
button_wait_time = float( button_wait_time = float(
getattr(self.analyser, "fudai_button_load_wait_seconds", 0.5) or 0.5 getattr(
self.analyser, "fudai_button_load_wait_seconds", 0.5
)
or 0.5
) )
if button_wait_time > 0: if button_wait_time > 0:
try: try:
@@ -1438,11 +1442,16 @@ class FudaiFinder:
# 保存完整截图用于调试(检测前) # 保存完整截图用于调试(检测前)
try: try:
import douyin_screenshot_manager import douyin_screenshot_manager
pic_rgb_full = pic.convert("RGB") pic_rgb_full = pic.convert("RGB")
# 获取检测区域信息用于标注 # 获取检测区域信息用于标注
try: try:
first_region = self.detector.search_regions[0] if self.detector.search_regions else None first_region = (
self.detector.search_regions[0]
if self.detector.search_regions
else None
)
if first_region: if first_region:
if "y_top" in first_region: if "y_top" in first_region:
coords = ( coords = (
@@ -1476,7 +1485,7 @@ class FudaiFinder:
"method": "optimized_finder", "method": "optimized_finder",
"resolution": f"{self.detector.rx}x{self.detector.ry}", "resolution": f"{self.detector.rx}x{self.detector.ry}",
"y_offset": self.detector.y_pianyi, "y_offset": self.detector.y_pianyi,
} },
) )
if debug_path: if debug_path:
try: try:
@@ -1484,7 +1493,7 @@ class FudaiFinder:
"[调试图像]", "[调试图像]",
"福袋图标检测前保存完整截图(优化查找器)", "福袋图标检测前保存完整截图(优化查找器)",
path=debug_path, path=debug_path,
loop=loop loop=loop,
) )
except Exception: except Exception:
pass pass
@@ -1500,6 +1509,7 @@ class FudaiFinder:
# 保存完整截图(检测成功) # 保存完整截图(检测成功)
try: try:
import douyin_screenshot_manager import douyin_screenshot_manager
pic_rgb_full = pic.convert("RGB") pic_rgb_full = pic.convert("RGB")
# 获取检测区域信息用于标注 # 获取检测区域信息用于标注
@@ -1541,8 +1551,8 @@ class FudaiFinder:
"method": detect_method, "method": detect_method,
"loop": loop, "loop": loop,
"resolution": f"{self.detector.rx}x{self.detector.ry}", "resolution": f"{self.detector.rx}x{self.detector.ry}",
"result": "success" "result": "success",
} },
) )
if debug_path: if debug_path:
try: try:
@@ -1551,7 +1561,7 @@ class FudaiFinder:
"福袋图标检测成功保存完整截图(优化查找器)", "福袋图标检测成功保存完整截图(优化查找器)",
path=debug_path, path=debug_path,
detected_x=detected_x, detected_x=detected_x,
method=detect_method method=detect_method,
) )
except Exception: except Exception:
pass pass
+33 -5
View File
@@ -386,6 +386,13 @@ def process_reservation_attend_window(
让上层逻辑继续后续处理(例如识别详情并参与)。 让上层逻辑继续后续处理(例如识别详情并参与)。
""" """
if not reservations: if not reservations:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约队列为空,跳过",
)
except Exception:
pass
return False return False
now_ts = _now_ts() now_ts = _now_ts()
@@ -405,6 +412,15 @@ def process_reservation_attend_window(
# 没有合法 future_ts,则直接丢弃 # 没有合法 future_ts,则直接丢弃
if ft <= 0: if ft <= 0:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约 future_ts 无效,丢弃",
future_ts=ft,
target=target,
)
except Exception:
pass
reservations.pop(0) reservations.pop(0)
try: try:
write_state_callback() write_state_callback()
@@ -462,12 +478,14 @@ def process_reservation_attend_window(
except Exception: except Exception:
pass pass
# 优化锁定期检查:如果预约时间已经到了(now_ts >= ft - dynamic_ahead), # 优化锁定期检查:
# 即使锁定期还没结束,也应该允许回退(但需要检查是否是同一个预约) # 1. 如果没有锁定期(focus_until = 0),直接允许检查时间窗口
# 如果锁定期还没结束,但当前预约的 future_ts 与锁定期匹配(说明是同一个预约),允许回退 # 2. 如果锁定期已过期(now_ts >= focus_until),允许检查时间窗口
# 如果锁定期还没结束,且当前预约的 future_ts 与锁定期不匹配,说明是新的预约,需要等待锁定期结束 # 3. 如果锁定期还没结束,但预约时间已经到了,检查是否是同一个预约
# - 如果是同一个预约,允许回退(通常已经在目标直播间了)
# - 如果不是同一个预约,不允许回退(需要等待当前预约完成)
if focus_until > 0 and now_ts < focus_until: if focus_until > 0 and now_ts < focus_until:
# 检查是否是同一个预约(允许5秒误差) # 锁定期还没结束,检查是否是同一个预约(允许5秒误差)
expected_focus_until = ft + max(0.0, poll_before) expected_focus_until = ft + max(0.0, poll_before)
if abs(focus_until - expected_focus_until) > 5.0: if abs(focus_until - expected_focus_until) > 5.0:
# 不是同一个预约,锁定期还没结束,不允许回退 # 不是同一个预约,锁定期还没结束,不允许回退
@@ -478,12 +496,22 @@ def process_reservation_attend_window(
focus_until=int(focus_until), focus_until=int(focus_until),
expected_focus_until=int(expected_focus_until), expected_focus_until=int(expected_focus_until),
target_future_ts=int(ft), target_future_ts=int(ft),
lock_period_remain_seconds=int(focus_until - now_ts),
) )
except Exception: except Exception:
pass pass
return False return False
# 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退 # 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退
# 但这里通常已经在目标直播间了,所以继续检查时间窗口 # 但这里通常已经在目标直播间了,所以继续检查时间窗口
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,继续检查时间窗口",
focus_until=int(focus_until),
target_future_ts=int(ft),
)
except Exception:
pass
if now_ts < ft - dynamic_ahead: if now_ts < ft - dynamic_ahead:
# 还没到窗口 # 还没到窗口
+2
View File
@@ -135,6 +135,8 @@ def extract_participants_count(text: Optional[str]) -> int:
+210 -2
View File
@@ -1713,12 +1713,124 @@ def main():
# 日志区 # 日志区
log_box = ttk.Frame(log_tab) log_box = ttk.Frame(log_tab)
log_box.pack(fill=BOTH, expand=True) log_box.pack(fill=BOTH, expand=True)
# 搜索工具栏
log_search_frame = ttk.Frame(log_box)
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
log_search_var = tk.StringVar(value="")
log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20)
log_search_entry.pack(side=LEFT, padx=(0, 5))
log_search_matches = [] # 存储所有匹配的位置
log_current_match_index = -1 # 当前匹配的索引
def search_in_log_text(direction=1):
"""在运行日志中搜索文本"""
nonlocal log_search_matches, log_current_match_index
search_text = log_search_var.get().strip()
if not search_text:
# 清除高亮
log_text.tag_remove("search_highlight", "1.0", "end")
log_search_matches = []
log_current_match_index = -1
return
# 获取所有文本
content = log_text.get("1.0", "end-1c")
if not content:
return
# 清除之前的高亮
log_text.tag_remove("search_highlight", "1.0", "end")
log_text.tag_remove("search_current", "1.0", "end")
# 配置高亮样式
log_text.tag_config("search_highlight", background="yellow")
log_text.tag_config("search_current", background="orange")
# 查找所有匹配项(不区分大小写)
log_search_matches = []
start_pos = 0 # 使用整数索引
search_text_lower = search_text.lower()
content_lower = content.lower()
while True:
# 在内容中查找
pos = content_lower.find(search_text_lower, start_pos)
if pos == -1:
break
# 计算行号和列号
line_start = content[:pos].rfind("\n") + 1
line_num = content[:pos].count("\n") + 1
col_num = pos - line_start
# 转换为 tkinter 索引格式
start_index = f"{line_num}.{col_num}"
end_index = f"{line_num}.{col_num + len(search_text)}"
log_search_matches.append((start_index, end_index))
start_pos = pos + 1
if not log_search_matches:
# 没有找到匹配项
log_current_match_index = -1
return
# 高亮所有匹配项
for start_idx, end_idx in log_search_matches:
log_text.tag_add("search_highlight", start_idx, end_idx)
# 根据方向更新当前匹配索引
if direction == 1: # 下一个
log_current_match_index = (log_current_match_index + 1) % len(log_search_matches)
else: # 上一个
log_current_match_index = (log_current_match_index - 1) % len(log_search_matches)
# 高亮当前匹配项并滚动到该位置
if log_current_match_index >= 0:
start_idx, end_idx = log_search_matches[log_current_match_index]
log_text.tag_add("search_current", start_idx, end_idx)
log_text.see(start_idx)
log_text.mark_set("insert", start_idx)
def search_next_in_log():
"""搜索下一个"""
search_in_log_text(1)
def search_prev_in_log():
"""搜索上一个"""
search_in_log_text(-1)
def clear_search_in_log():
"""清除搜索高亮"""
nonlocal log_search_matches, log_current_match_index
log_search_var.set("")
log_text.tag_remove("search_highlight", "1.0", "end")
log_text.tag_remove("search_current", "1.0", "end")
log_search_matches = []
log_current_match_index = -1
# 绑定回车键搜索
def on_log_search_entry_key(event):
if event.keysym == "Return":
search_next_in_log()
log_search_entry.bind("<KeyPress>", on_log_search_entry_key)
ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))
ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2))
ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))
ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5))
log_text = ScrolledText(log_box) log_text = ScrolledText(log_box)
try: try:
log_text.configure(font=("Consolas", 10)) log_text.configure(font=("Consolas", 10))
except Exception: except Exception:
pass pass
log_text.pack(fill=BOTH, expand=True, padx=10, pady=10) log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
# 截图预览 # 截图预览
preview_top = ttk.Frame(preview_tab) preview_top = ttk.Frame(preview_tab)
@@ -2570,9 +2682,105 @@ def main():
side=LEFT, padx=(0, 8) side=LEFT, padx=(0, 8)
) )
ttk.Button(actions_log_top, text="刷新", command=refresh_actions_log).pack( ttk.Button(actions_log_top, text="刷新", command=refresh_actions_log).pack(
side=LEFT side=LEFT, padx=(0, 10)
) )
# 行为日志搜索功能
ttk.Separator(actions_log_top, orient="vertical").pack(side=LEFT, fill=Y, padx=5, pady=3)
ttk.Label(actions_log_top, text="搜索:").pack(side=LEFT)
actions_search_var = tk.StringVar(value="")
actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20)
actions_search_entry.pack(side=LEFT, padx=(0, 5))
actions_search_matches = []
actions_current_match_index = -1
def search_in_actions_log(direction=1):
"""在行为日志中搜索文本"""
nonlocal actions_search_matches, actions_current_match_index
search_text = actions_search_var.get().strip()
if not search_text:
actions_log_text.tag_remove("search_highlight", "1.0", "end")
actions_log_text.tag_remove("search_current", "1.0", "end")
actions_search_matches = []
actions_current_match_index = -1
return
content = actions_log_text.get("1.0", "end-1c")
if not content:
return
actions_log_text.tag_remove("search_highlight", "1.0", "end")
actions_log_text.tag_remove("search_current", "1.0", "end")
actions_log_text.tag_config("search_highlight", background="yellow")
actions_log_text.tag_config("search_current", background="orange")
actions_search_matches = []
start_pos = 0 # 使用整数索引
search_text_lower = search_text.lower()
content_lower = content.lower()
while True:
pos = content_lower.find(search_text_lower, start_pos)
if pos == -1:
break
line_start = content[:pos].rfind("\n") + 1
line_num = content[:pos].count("\n") + 1
col_num = pos - line_start
start_index = f"{line_num}.{col_num}"
end_index = f"{line_num}.{col_num + len(search_text)}"
actions_search_matches.append((start_index, end_index))
start_pos = pos + 1
if not actions_search_matches:
actions_current_match_index = -1
return
for start_idx, end_idx in actions_search_matches:
actions_log_text.tag_add("search_highlight", start_idx, end_idx)
if direction == 1:
actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches)
else:
actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches)
if actions_current_match_index >= 0:
start_idx, end_idx = actions_search_matches[actions_current_match_index]
actions_log_text.tag_add("search_current", start_idx, end_idx)
actions_log_text.see(start_idx)
actions_log_text.mark_set("insert", start_idx)
def search_next_in_actions():
search_in_actions_log(1)
def search_prev_in_actions():
search_in_actions_log(-1)
def clear_search_in_actions():
nonlocal actions_search_matches, actions_current_match_index
actions_search_var.set("")
actions_log_text.tag_remove("search_highlight", "1.0", "end")
actions_log_text.tag_remove("search_current", "1.0", "end")
actions_search_matches = []
actions_current_match_index = -1
def on_actions_search_entry_key(event):
if event.keysym == "Return":
search_next_in_actions()
actions_search_entry.bind("<KeyPress>", on_actions_search_entry_key)
ttk.Button(actions_log_top, text="搜索", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))
ttk.Button(actions_log_top, text="上一个", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2))
ttk.Button(actions_log_top, text="下一个", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))
ttk.Button(actions_log_top, text="清除", command=clear_search_in_actions).pack(side=LEFT)
# OCR结果显示 # OCR结果显示
ocr_results_top = ttk.Frame(ocr_results_tab) ocr_results_top = ttk.Frame(ocr_results_tab)
ocr_results_top.pack(fill=X, padx=10, pady=(10, 0)) ocr_results_top.pack(fill=X, padx=10, pady=(10, 0))
+2
View File
@@ -92,6 +92,8 @@ paddlepaddle>=2.5.0,<3.0.0
+2
View File
@@ -69,6 +69,8 @@ types-requests>=2.31.0
+2
View File
@@ -108,6 +108,8 @@ ttkbootstrap>=1.10.0
+2
View File
@@ -145,6 +145,8 @@ if __name__ == "__main__":
+2
View File
@@ -68,6 +68,8 @@ if os.path.exists(log_file):
+2
View File
@@ -81,6 +81,8 @@ if os.path.exists(log_file):
+2
View File
@@ -214,6 +214,8 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb
+2
View File
@@ -51,6 +51,8 @@ __version__ = "1.0.0"
+2
View File
@@ -40,6 +40,8 @@
+2
View File
@@ -40,6 +40,8 @@
+2
View File
@@ -130,6 +130,8 @@ python check_gpu_available.py
+2
View File
@@ -136,6 +136,8 @@
+2
View File
@@ -208,6 +208,8 @@ if __name__ == "__main__":
+2
View File
@@ -139,3 +139,5 @@