diff --git a/assets/fudai_icon_purple_left_v20260618.png b/assets/fudai_icon_purple_left_v20260618.png new file mode 100644 index 0000000..1feca37 Binary files /dev/null and b/assets/fudai_icon_purple_left_v20260618.png differ diff --git a/assets/fudai_icon_red_left_v20260618.png b/assets/fudai_icon_red_left_v20260618.png new file mode 100644 index 0000000..6650e8a Binary files /dev/null and b/assets/fudai_icon_red_left_v20260618.png differ diff --git a/douyin/core/fudai_modules/run_once_basic_reservation.py b/douyin/core/fudai_modules/run_once_basic_reservation.py index 2d3a6c5..e23ded3 100644 --- a/douyin/core/fudai_modules/run_once_basic_reservation.py +++ b/douyin/core/fudai_modules/run_once_basic_reservation.py @@ -325,6 +325,17 @@ def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) -> self.reservation_after_action_pending = bool(after_action_ref[0]) if preempted: self._current_attending_reservation_fudai = True + elif not bool(getattr(self, "reservation_after_action_pending", False)): + if getattr(self, "_current_attending_reservation_fudai", False): + try: + self._log_kv( + "预约", + "[预约] 回退窗口未触发,清除旧的直接参与状态", + reason="attend_window_not_preempted_and_no_pending_action", + ) + except Exception: + pass + self._current_attending_reservation_fudai = False else: try: self._log_kv( diff --git a/douyin/fudai/douyin_fudai_finder_pkg/detector.py b/douyin/fudai/douyin_fudai_finder_pkg/detector.py index 61e50aa..52e9754 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/detector.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/detector.py @@ -38,6 +38,7 @@ class FudaiDetector: def __init__(self, analyser: Any): self.analyser = analyser self._current_icon_templates: Optional[Tuple[Tuple[str, Any], ...]] = None + self._fallback_icon_templates: Optional[Tuple[Tuple[str, Any], ...]] = None self._init_resolution() self._init_search_regions() @@ -63,15 +64,17 @@ class FudaiDetector: """初始化搜索区域 实际福袋出现区域按 2.0 直播间样式向左、向下扩展。 - 普通 finder 的调试样本已验证 icon 可能落在 x=20..430、y=403/503/354 三条带。 + 真机样本显示可点击入口集中在左侧;右侧福利/消费券横幅也会出现相同礼物色, + 不能进入福袋详情,避免纳入搜索。 """ - # 旧区域 X=153..561/Y=348..451 保留在扩展区域内;新版图标更靠左且高度可能下移。 + # 旧区域 X=153..561/Y=348..451 里右侧已被直播间营销券横幅污染。 + # 2026-06-18 真机 light6 成功点击集中在 x=83..209,失败券条候选出现在 x=366。 self.search_regions = [ { "name": "实际福袋区域", "priority": 1, "x1": 20 * self.rx // 1080, - "x2": 561 * self.rx // 1080, + "x2": 280 * self.rx // 1080, "y_top": 348 * self.ry // 2400 + self.y_pianyi, "y_bottom": 540 * self.ry // 2400 + self.y_pianyi, "y": (348 + 540) // 2 * self.ry // 2400 + self.y_pianyi, @@ -664,6 +667,132 @@ class FudaiDetector: except Exception: return True + def detect_by_icon_fallback_template(self, pic: Image.Image) -> Optional[int]: + """Fast fallback for live-room fudai entry variants missed by color seeds. + + This scans only the left fudai hot zone with small templates cropped from + current device samples. It intentionally avoids the right coupon strip. + """ + start_time = time.time() + try: + enabled = bool( + getattr(self.analyser, "fudai_icon_fallback_template_enabled", True) + ) + except Exception: + enabled = True + if not enabled: + return None + + try: + threshold = float( + getattr(self.analyser, "fudai_icon_fallback_template_threshold", 0.88) + or 0.88 + ) + except Exception: + threshold = 0.88 + + try: + import cv2 # type: ignore[import-untyped] + import numpy as np # type: ignore[import-untyped] + except Exception: + return None + + try: + template_dir = path_config.get_assets_dir() + except Exception: + template_dir = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "assets") + ) + + template_files = ( + ("red_left", os.path.join(template_dir, "fudai_icon_red_left_v20260618.png")), + ("purple_left", os.path.join(template_dir, "fudai_icon_purple_left_v20260618.png")), + ) + if self._fallback_icon_templates is None: + loaded_templates = [] + for name, template_path in template_files: + if not os.path.exists(template_path): + continue + try: + template = cv2.imread( # type: ignore[attr-defined] + template_path, + cv2.IMREAD_GRAYSCALE, # type: ignore[attr-defined] + ) + if template is not None: + loaded_templates.append((name, template)) + except Exception: + continue + self._fallback_icon_templates = tuple(loaded_templates) + + if not self._fallback_icon_templates: + return None + + try: + width, height = pic.size + x1 = max(0, int(20 * self.rx / 1080)) + y1 = max(0, int(300 * self.ry / 2400) + self.y_pianyi) + x2 = min(width, int(280 * self.rx / 1080)) + y2 = min(height, int(560 * self.ry / 2400) + self.y_pianyi) + if x1 >= x2 or y1 >= y2: + return None + roi_gray = cv2.cvtColor( # type: ignore[attr-defined] + np.asarray(pic.crop((x1, y1, x2, y2)).convert("RGB")), + cv2.COLOR_RGB2GRAY, # type: ignore[attr-defined] + ) + except Exception: + return None + + best_score = -1.0 + best_name = "" + best_loc: Optional[Tuple[int, int]] = None + best_size: Optional[Tuple[int, int]] = None + for name, template in self._fallback_icon_templates: + try: + th, tw = template.shape[:2] + if roi_gray.shape[0] < th or roi_gray.shape[1] < tw: + continue + res = cv2.matchTemplate( # type: ignore[attr-defined] + roi_gray, + template, + cv2.TM_CCOEFF_NORMED, # type: ignore[attr-defined] + ) + _, max_val, _, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined] + score = float(max_val) + if score > best_score: + best_score = score + best_name = name + best_loc = (x1 + int(max_loc[0]), y1 + int(max_loc[1])) + best_size = (tw, th) + except Exception: + continue + + elapsed = (time.time() - start_time) * 1000 + passed = best_score >= threshold and best_loc is not None and best_size is not None + try: + self.analyser._log_kv( + "[福袋查找] 兜底模板", + "左侧福袋入口兜底模板匹配完成", + passed=passed, + score=round(best_score, 4), + threshold=threshold, + template=best_name, + match_loc=best_loc, + roi=(x1, y1, x2, y2), + elapsed_ms=round(elapsed, 2), + ) + except Exception: + pass + if not passed or best_loc is None or best_size is None: + return None + + click_x_scaled = best_loc[0] + best_size[0] // 2 + detected_x = int(click_x_scaled * 1080.0 / max(1, self.rx)) + try: + self.analyser.last_fudai_x = detected_x + except Exception: + pass + return detected_x + def detect(self, pic: Image.Image) -> Tuple[Optional[int], str]: """检测福袋图标位置(按优先级搜索,像素检测后需模板匹配确认) @@ -822,6 +951,21 @@ class FudaiDetector: except Exception: pass + fallback_x = self.detect_by_icon_fallback_template(pic) + if fallback_x is not None: + overall_elapsed = (time.time() - overall_start) * 1000 + try: + self.analyser._log_kv( + "[福袋查找] 检测完成", + "左侧福袋入口兜底模板命中", + total_elapsed_ms=round(overall_elapsed, 2), + x=fallback_x, + method="icon_fallback_template", + ) + except Exception: + pass + return fallback_x, "icon_fallback_template" + overall_elapsed = (time.time() - overall_start) * 1000 try: self.analyser._log_kv( diff --git a/douyin/fudai/douyin_fudai_finder_pkg/finder.py b/douyin/fudai/douyin_fudai_finder_pkg/finder.py index e28e25b..8233a06 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/finder.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/finder.py @@ -58,33 +58,83 @@ def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool: setattr(analyser, "last_fudai_x", 0) except Exception: pass - close_sent = False + + now_ts = time.time() try: - operation = getattr(analyser, "operation", None) - click_back = getattr(operation, "click_back", None) - if callable(click_back): - click_back(getattr(analyser, "device_id", "")) - close_sent = True - delay = getattr(operation, "delay", None) - if callable(delay): - delay(0.2) - except Exception as close_error: - try: - analyser._log_kv( - "[福袋查找] 优惠券关闭异常", - "优惠券预检命中后返回关闭失败", - reason="coupon_popup_before_fudai_click", - error=str(close_error), + last_ts = float(getattr(analyser, "_last_coupon_guard_back_ts", 0.0) or 0.0) + except Exception: + last_ts = 0.0 + try: + window_s = float( + getattr(analyser, "fudai_coupon_guard_back_window_seconds", 8.0) + or 8.0 + ) + except Exception: + window_s = 8.0 + allow_back = (now_ts - last_ts) >= max(1.0, window_s) + + try: + if douyin_screenshot_manager is not None: + douyin_screenshot_manager.save_debug_image( + pic, + operation_type="pixel_detect", + picname="coupon_guard_before_back", + step="before_back", + extra_info={ + "reason": "coupon_popup_before_fudai_click", + "coupon_info": info, + "allow_back": allow_back, + }, + annotate=True, + background=True, + force=True, ) + except Exception: + pass + + close_sent = False + skipped_reason = None + if allow_back: + try: + operation = getattr(analyser, "operation", None) + click_back = getattr(operation, "click_back", None) + if callable(click_back): + click_back(getattr(analyser, "device_id", "")) + close_sent = True + try: + setattr(analyser, "_last_coupon_guard_back_ts", now_ts) + except Exception: + pass + delay = getattr(operation, "delay", None) + if callable(delay): + delay(0.2) + except Exception as close_error: + try: + analyser._log_kv( + "[福袋查找] 优惠券关闭异常", + "优惠券预检命中后返回关闭失败", + reason="coupon_popup_before_fudai_click", + error=str(close_error), + ) + except Exception: + pass + else: + skipped_reason = "coupon_guard_back_rate_limited" + try: + count = int(getattr(analyser, "_coupon_guard_back_rate_limited_count", 0) or 0) + 1 + setattr(analyser, "_coupon_guard_back_rate_limited_count", count) except Exception: pass try: analyser._log_kv( "[福袋查找] 跳过", - "当前截图已是优惠券弹窗,跳过福袋点击并尝试返回关闭", + "当前截图已是优惠券弹窗,跳过福袋点击", reason="coupon_popup_before_fudai_click", coupon_info=info, close_sent=close_sent, + skipped_reason=skipped_reason, + since_last_back_seconds=round(now_ts - last_ts, 2) if last_ts > 0 else None, + back_window_seconds=window_s, ) except Exception: pass diff --git a/douyin/reservation/douyin_reservation_handler_pkg/direct_attend.py b/douyin/reservation/douyin_reservation_handler_pkg/direct_attend.py index ce50f81..4fe7ab1 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/direct_attend.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/direct_attend.py @@ -188,11 +188,16 @@ def handle_reservation_direct_attend(analyser: Any) -> None: try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 未找到福袋图标,回退到正常流程", + "[预约] 未找到福袋图标,退出预约直接参与,等待正常直播间阶段重判", + reason="fudai_icon_not_found_before_detail_open", ) except Exception: pass - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + try: + analyser.reservation_after_action_pending = False + analyser._current_attending_reservation_fudai = False + except Exception: + pass return # 等待页面加载 @@ -227,11 +232,16 @@ def handle_reservation_direct_attend(analyser: Any) -> None: try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 无法读取截图,回退到正常流程", + "[预约] 无法读取截图,退出预约直接参与,等待正常直播间阶段重判", + reason="screenshot_open_failed_after_detail_open", ) except Exception: pass - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + try: + analyser.reservation_after_action_pending = False + analyser._current_attending_reservation_fudai = False + except Exception: + pass return from douyin.detection import douyin_pixel @@ -253,12 +263,17 @@ def handle_reservation_direct_attend(analyser: Any) -> None: try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 未检测到参与按钮,回退到正常流程", + "[预约] 未检测到参与按钮,退出预约直接参与,等待正常直播间阶段重判", button_info=button_info, + reason="attend_button_not_detected_after_detail_open", ) except Exception: pass - analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + try: + analyser.reservation_after_action_pending = False + analyser._current_attending_reservation_fudai = False + except Exception: + pass return # 步骤3:点击参与按钮 diff --git a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py index 9d7e0d5..7fb2af2 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py @@ -77,6 +77,14 @@ def seek_reservation_room( max_back = 100 if max_back < 0: max_back = 0 + try: + settle_delay = float( + getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6 + ) + except Exception: + settle_delay = 0.6 + if settle_delay < 0.1: + settle_delay = 0.1 # 获取目标直播间名字 target_room_title = str(item.get("room_title") or "").strip() @@ -247,6 +255,7 @@ def seek_reservation_room( current_room_pos=cur_pos, target_pos=target_pos, pos_diff=pos_diff, + settle_delay_s=round(settle_delay, 2), target_room_title=target_room_title, target_room_title_raw=target_room_title_raw, ) @@ -264,9 +273,9 @@ def seek_reservation_room( # 只在最后一次滑动后添加短暂延迟,确保页面稳定 if i == back_times - 1 and back_times > 0: try: - analyser.operation.delay(0.1) # 最后一次滑动后短暂等待 + analyser.operation.delay(settle_delay) except Exception: - time.sleep(0.1) + time.sleep(settle_delay) # 清除标志 try: analyser._skip_record_title_during_seek = False @@ -283,6 +292,7 @@ def seek_reservation_room( current_room_pos=cur_pos, target_pos=target_pos, pos_diff=pos_diff, + settle_delay_s=round(settle_delay, 2), target_room_title=target_room_title, target_room_title_raw=target_room_title_raw, ) @@ -300,9 +310,9 @@ def seek_reservation_room( # 只在最后一次滑动后添加短暂延迟,确保页面稳定 if i == forward_times - 1 and forward_times > 0: try: - analyser.operation.delay(0.1) # 最后一次滑动后短暂等待 + analyser.operation.delay(settle_delay) except Exception: - time.sleep(0.1) + time.sleep(settle_delay) # 清除标志 try: analyser._skip_record_title_during_seek = False @@ -312,6 +322,18 @@ def seek_reservation_room( # 回退过程中只执行回退操作,不进行校验;校验将在 process_reservation_attend_window 中统一进行。 # 只有在实际执行了滑动(moved=True)时返回 True,避免在未移动时被误判为“回退成功”。 if moved: + try: + analyser._log_kv( + operation_type, + f"[{operation_type}] _seek_reservation_room:滑动完成,等待后交由标题校验确认", + target_pos=target_pos, + start_room_pos=cur_pos, + current_room_pos=int(getattr(analyser, "room_pos", 0) or 0), + pos_diff=pos_diff, + settle_delay_s=round(settle_delay, 2), + ) + except Exception: + pass # 回退成功后,更新映射表文件以覆盖原本的 try: _dump_room_pos_map_to_state(analyser) diff --git a/douyin/reservation/douyin_reservation_verify.py b/douyin/reservation/douyin_reservation_verify.py index 0145423..4c3f8fc 100644 --- a/douyin/reservation/douyin_reservation_verify.py +++ b/douyin/reservation/douyin_reservation_verify.py @@ -322,7 +322,8 @@ def validate_back_to_reservation( except Exception: pass - # 如果映射表中的标题与预期标题匹配,增强验证信心 + # 如果映射表中的标题与预期标题匹配,只能说明目标位置记录可信。 + # 当前屏幕是否真的回到了目标直播间,必须以后续强制截图/OCR 标题为准。 if expected_title and recorded_title: try: from douyin.other import douyin_high_value_room @@ -338,8 +339,9 @@ def validate_back_to_reservation( try: analyser._log_kv( "预约", - "回退校验:运行时映射表验证通过,位置和标题匹配", + "回退校验:目标映射表记录匹配,等待当前屏幕标题校验", target_pos=target_pos_seen, + note="此处仅验证预约目标记录,不代表当前屏幕已回到目标直播间", ) except Exception: pass diff --git a/tests/test_fudai_finder_pkg.py b/tests/test_fudai_finder_pkg.py index 9475e72..a7aeb85 100644 --- a/tests/test_fudai_finder_pkg.py +++ b/tests/test_fudai_finder_pkg.py @@ -162,6 +162,103 @@ class TestFudaiDetector: assert not d.confirm_pixel_candidate_shape(Image.open(sample).convert("RGB"), 292) + def test_detect_rejects_right_coupon_strip_false_candidate(self): + from pathlib import Path + + sample = Path( + "pic/debug_captures/2026-06-18/" + "20260618_084818_591876_px_fdicon_ok_x336y373w60h60_" + "src_flow_on_detect_click_x_366_click_y_403_detected_x_scaled_366.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + analyser.last_fudai_x = 366 + d = FudaiDetector(analyser) + + detected_x, method = d.detect(Image.open(sample).convert("RGB")) + + assert detected_x is None + assert method == "" + + def test_detect_keeps_left_real_fudai_entry(self): + from pathlib import Path + + sample = Path( + "pic/debug_captures/2026-06-18/" + "20260618_084704_660058_px_fdicon_ok_x179y373w60h60_" + "src_flow_on_detect_click_x_209_click_y_403_detected_x_scaled_209.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + analyser.last_fudai_x = 209 + d = FudaiDetector(analyser) + + detected_x, method = d.detect(Image.open(sample).convert("RGB")) + + assert detected_x is not None + assert 150 <= detected_x <= 230 + assert method == "pixel" + + @pytest.mark.parametrize( + ("sample_name", "min_x", "max_x"), + [ + ( + "20260618_095900_710971_px_pxstage_ov_ok_1.png", + 40, + 120, + ), + ( + "20260618_100307_741261_px_pxstage_ov_ok_1.png", + 150, + 220, + ), + ], + ) + def test_detect_keeps_real_fudai_entries_from_light10_misses( + self, sample_name, min_x, max_x + ): + from pathlib import Path + + sample = Path("pic/debug_captures/2026-06-18") / sample_name + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + analyser.last_fudai_x = 83 + d = FudaiDetector(analyser) + + detected_x, method = d.detect(Image.open(sample).convert("RGB")) + + assert detected_x is not None + assert min_x <= detected_x <= max_x + assert method in {"pixel", "icon_fallback_template"} + + @pytest.mark.parametrize( + "sample_name", + [ + "20260618_084818_591876_px_fdicon_ok_x336y373w60h60_" + "src_flow_on_detect_click_x_366_click_y_403_detected_x_scaled_366.png", + "20260618_100333_464357_px_pxstage_ov_ok_1.png", + ], + ) + def test_icon_fallback_template_rejects_coupon_or_no_fudai_samples( + self, sample_name + ): + from pathlib import Path + + sample = Path("pic/debug_captures/2026-06-18") / sample_name + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + d = FudaiDetector(analyser) + + assert d.detect_by_icon_fallback_template(Image.open(sample).convert("RGB")) is None + # ============================================================ # FudaiClickExecutor @@ -223,6 +320,28 @@ class TestFudaiFinder: finder.detector.detect.assert_not_called() finder.executor.click.assert_not_called() + def test_coupon_popup_guard_does_not_press_back_repeatedly(self): + analyser = FakeAnalyser() + finder = FudaiFinder(analyser) + pic = Image.new("RGB", (1080, 2400), (255, 255, 255)) + finder.acquirer.acquire_screenshot = MagicMock(return_value=pic) + finder.detector.detect = MagicMock(return_value=(83, "pixel")) + finder.executor.click = MagicMock(return_value=True) + + with patch( + "douyin.detection.pixel.popups.detect_coupon_popup_background", + return_value=(True, {"template_score": 0.9}), + ), patch("douyin.fudai.douyin_fudai_finder_pkg.finder.time.time") as mock_time: + mock_time.side_effect = [100.0] * 10 + [101.0] * 10 + ok1, x1 = finder.find_and_open() + ok2, x2 = finder.find_and_open() + + assert (ok1, x1) == (False, None) + assert (ok2, x2) == (False, None) + analyser.operation.click_back.assert_called_once_with(analyser.device_id) + finder.detector.detect.assert_not_called() + finder.executor.click.assert_not_called() + # ============================================================ # 顶层函数 diff --git a/tests/test_reservation_direct_attend_markers.py b/tests/test_reservation_direct_attend_markers.py index 972e269..e0d2aff 100644 --- a/tests/test_reservation_direct_attend_markers.py +++ b/tests/test_reservation_direct_attend_markers.py @@ -81,3 +81,28 @@ def test_direct_attend_logs_fixed_failure_marker_when_button_still_exists(): if len(call.args) >= 2 and str(call.args[1]) == "预约回退 direct_attend 失败" ] assert marker_logs + + +def test_direct_attend_icon_not_found_does_not_enter_detail_handler(): + from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import ( + handle_reservation_direct_attend, + ) + + analyser = _mk_analyser() + analyser._current_attending_reservation_fudai = True + + with patch( + "douyin.core.douyin_flow_control.find_and_open_fudai_detail", + return_value=False, + ): + handle_reservation_direct_attend(analyser) + + analyser._handle_in_fudai_detail.assert_not_called() + assert analyser.reservation_after_action_pending is False + assert analyser._current_attending_reservation_fudai is False + + marker_logs = [ + call for call in analyser._log_kv.call_args_list + if len(call.args) >= 2 and str(call.args[1]) == "预约回退 direct_attend fallback" + ] + assert marker_logs diff --git a/tests/test_run_once_basic_helpers.py b/tests/test_run_once_basic_helpers.py index 65d91e0..ffb6752 100644 --- a/tests/test_run_once_basic_helpers.py +++ b/tests/test_run_once_basic_helpers.py @@ -404,6 +404,32 @@ class TestHandleReservationCheck: assert result is False mock_process.assert_called_once() + def test_time_window_not_reached_clears_stale_direct_attend_flag(self): + """process 返回 False 且待处理已清空时,不应继续保留 direct-attend 旧状态。""" + import time + + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s.reservations = [ + {"future_ts": time.time() + 100, "content": "X", "pos_seen": 0} + ] + s._current_attending_reservation_fudai = True + s.reservation_after_action_pending = False + + def _not_due(**kwargs): + kwargs["reservation_after_action_pending_ref"][0] = False + return False + + with patch( + "douyin.reservation.douyin_reservation_logic.process_reservation_attend_window", + side_effect=_not_due, + ): + result = ronce.handle_reservation_check(s, 0.0) + + assert result is False + assert s.reservation_after_action_pending is False + assert s._current_attending_reservation_fudai is False + def test_preempted_reservation_switches_to_direct_attend(self): import time