From 55d38c46ecc3a4e64ac25549264904865546cfe0 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 18 Jun 2026 08:35:04 +0800 Subject: [PATCH] Fix fudai coupon misclick detection --- assets/fudai_icon_countdown_v20260618.png | Bin 0 -> 5059 bytes assets/fudai_icon_pending_v20260618.png | Bin 0 -> 4776 bytes douyin/detection/pixel/popups.py | 342 ++++++++++++++++-- .../fudai/douyin_fudai_finder_pkg/detector.py | 217 +++++++++++ .../fudai/douyin_fudai_finder_pkg/finder.py | 73 ++++ .../optimized_entry.py | 4 + tests/test_detection_pixel.py | 44 +++ tests/test_fudai_finder_pkg.py | 134 ++++++- 8 files changed, 786 insertions(+), 28 deletions(-) create mode 100644 assets/fudai_icon_countdown_v20260618.png create mode 100644 assets/fudai_icon_pending_v20260618.png diff --git a/assets/fudai_icon_countdown_v20260618.png b/assets/fudai_icon_countdown_v20260618.png new file mode 100644 index 0000000000000000000000000000000000000000..00dac4a5d685dc4d64939b352e168551c3c7126f GIT binary patch literal 5059 zcmV;!6FlsRP)5pXBRX=xmul8PQx~FHRZI9z|l1btOh-?!GD1m%HLJmrhAi_w_2ZWH|zu-^Ezra`c zfC3@`2?-G^L>3Yd%Q3R!%+fQx*7o+h9(3+~RbAcFlLg0jdP=pty6>LtcYf!bV&DJ4 z_YfE&003u<0b}$uJY2QHh4J$Eg8p+R&aWu){Kp?0zxU(Gy?clE?=L2&D$5cEFWtR+ z=QE!g?>_@KZa}vSRi(=+o6Z-Dc~jP=sjX68X>T-IgVus`;2j_`?-7wp$%T+ zbUZzHSREbf`3$t_bi1R`V7z~8{IM5cIH1e(Y&MxJPA27amQQE4tZmbHqrjT*XVF=3 zp8n7?=RJB1cM(!BDWTIX#@oHEEp=Y(m#E4!}9NPE!{7(NXc>;n{-+(}M$?Ongxed)@1|ZtmW?F}`^NIMdVF zqAX@vo@bewXHYj#HBy-*n4LKio;gdF_Xy52M25jYqyhlz95c32N;S=7T2Cg&2M_yu z*Ejd~H}-G!_IB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2pjJ z&*P+*W7pk$^C%lWC_nqc*63Cb`mFzK=e2JnljF*i#({85xJ1|i%#Z!G!6ez+lh8O~ z=f;8Ikh&x_&&YSKrw8ww&mY+rEF?^XpWF#yjPuUQ(B&kETvoPA>#c?z7uI^y|HG_w zv~l8j2~c7L+nn@gacbwcez`b`dk@jP|iWcG3K10l?T`()DX3`Rpc9B@R1 z=mZU0neyJ!keA{_1Z%~CaVTZhx*hE=ME~C^Kwvjse&z0;ys`h~uQ+5T3hcRcH0Lpf zX~pV>RRu3{mS?;!nO2E+-G6_t{_lq;U%cD-^rtp)Q?S0=NQV8~oN2Q_j@@pVZ6@~? Z{|D6`KUqKs_k;id002ovPDHLkV1h3s^g;jt literal 0 HcmV?d00001 diff --git a/assets/fudai_icon_pending_v20260618.png b/assets/fudai_icon_pending_v20260618.png new file mode 100644 index 0000000000000000000000000000000000000000..ad0c3e877fe29612aa17cd89f747f5ac3191453c GIT binary patch literal 4776 zcmV;Z5?AesP)>YNl0{&nw#=%WUgu}#VV>sq=kz!9TTfP&l@b?hb0V-1q$rA#?dq^B%M^(v5bH&d z@IU|kUjV?Kp%4ONtXviUr6bij@yPUFI)Xo|O$QbNHN{0F&NJC z<^h=GOhACZLe*>t!3E|+aEHVGaME9Y+5P(Mc>3D(!@28w=e>{P=K#Q|yFB#!gD#)* z`FM=8PonVRbvSaI35_mJ16K(GW8Qn`94!^#!92-&Edp_$&I!Polw1f7z(Vjo_;kGP zDt1Go#qSp9F*};C|1{n)TAx=a@dQQ=C7JR*IEVA6qw$q4DSgsAG9iS(IiT1|0XzzH zVQbC#bR8Wg?nM?x`CsN|>Q9c>XVqJs)^pmuOf)QNXg2<`{PbOt59|^r5yb`-4njb7 zA`_ z&3pl^85crIGMIoiF$rY80vR9Ge`e!wY1XZBQuoi(*?V+n`iY{ED;kL`NTM~h0Z~bk zj@DOa?LbE$xRg>z!8j*%T^vnR%vnQgl-UaMefk(4eG97&VScRo1e^g!;Ym6h`8hv5 z3r_qqjs`De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;Jrri6}K_4>?)Q=(W5aU2fefBx8FEOYfWB_ zI?#LE@y&TRyVR5AU2kCx8K3Qt0`L~-n^L89S{h`M|GMD3X5O9FH&1s%Nc?Kk$h#fmf&q`UQzTzl_=7KtHAZRE zJU+^ciqr6ka*V3>UwXXAodM5%&i$LvtJ?Rcd%3$DFDSB9u5l`&0a(!yD_p2@Dm}=C zTrL?w$}A}L@K{4$4gLL0ya|DqvEq2jWT$6)4>>qkgaVUadS=X0{tMWjU{DsT^r-NR zG}V1&hl?0&Z~!7=SER|oVZGo@-ygHrGxcM$gHxRDhHonX=soFO`1&d7C?SCk+XzJj1v-{sOzqoK7#1HdV^-W-rJWo1Ju7jRS71A@&KAUo--9j-> zqUXcEsUfWm?fv9t;V1{|S!bd3zg&M+|1|m^Kf%(Hw>JE+`X@WVp2{DwERgJAQtE)r z+c3~4Xdd1z$j@vZx5Bw;qosNPaNZ; tuple[int, int, int, int]: + width, height = pic_rgb.size + scale_x = width / 1080.0 + scale_y = height / 2400.0 + x1, y1, x2, y2 = box + return ( + max(0, min(int(x1 * scale_x), width)), + max(0, min(int(y1 * scale_y), height)), + max(0, min(int(x2 * scale_x), width)), + max(0, min(int(y2 * scale_y), height)), + ) + + +def _detect_coupon_success_orange_panel( + pic_rgb: Image.Image, + return_info: bool = False, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测居中橙色"领券成功 / 立即用券"优惠券弹窗。""" + try: + import numpy as np # type: ignore[import-untyped] + + def _ratios(box: tuple[int, int, int, int]) -> dict[str, float]: + x1, y1, x2, y2 = _scaled_box(pic_rgb, box) + if x1 >= x2 or y1 >= y2: + return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0} + arr = np.asarray(pic_rgb.crop((x1, y1, x2, y2)).convert("RGB")) + if arr.size == 0: + return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0} + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + ri = r.astype(int) + gi = g.astype(int) + bi = b.astype(int) + orange = ( + (r >= 220) + & (g >= 80) + & (g <= 190) + & (b <= 130) + & ((ri - gi) >= 40) + & ((gi - bi) >= -5) + ) + warm_button = ( + (r >= 220) + & (g <= 180) + & (b <= 150) + & ((ri - gi) >= 40) + ) + white = (r >= 235) & (g >= 235) & (b >= 235) + total = orange.size + if total <= 0: + return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0} + return { + "orange_ratio": float(np.sum(orange) / total), + "warm_button_ratio": float(np.sum(warm_button) / total), + "white_ratio": float(np.sum(white) / total), + } + + panel = _ratios((150, 520, 930, 1580)) + button = _ratios((250, 1320, 830, 1485)) + try: + panel_threshold = float( + getattr(analyser, "coupon_success_panel_orange_ratio_threshold", 0.18) + or 0.18 + ) + except Exception: + panel_threshold = 0.18 + try: + button_threshold = float( + getattr(analyser, "coupon_success_button_warm_ratio_threshold", 0.20) + or 0.20 + ) + except Exception: + button_threshold = 0.20 + + result = ( + panel["orange_ratio"] >= panel_threshold + and button["warm_button_ratio"] >= button_threshold + ) + info = { + "method": "coupon_success_orange_panel", + "orange_ratio": panel["orange_ratio"], + "button_warm_ratio": button["warm_button_ratio"], + "white_ratio": panel["white_ratio"], + "effective_panel_threshold": panel_threshold, + "effective_button_threshold": button_threshold, + "reason": None if result else "orange_panel_or_button_below_threshold", + } + if return_info: + return result, info + return result + except Exception as e: # type: ignore[general-exception] + if return_info: + return False, { + "method": "coupon_success_orange_panel", + "orange_ratio": 0.0, + "button_warm_ratio": 0.0, + "reason": f"exception: {str(e)}", + } + return False + + +def _detect_coupon_bottom_panel_by_pixels( + pic_rgb: Image.Image, + return_info: bool = False, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测底部白底优惠券面板,覆盖模板低分但仍明显是券弹窗的样式。""" + try: + import numpy as np # type: ignore[import-untyped] + + x1, y1, x2, y2 = _scaled_box(pic_rgb, (9, 1173, 1079, 2255)) + if x1 >= x2 or y1 >= y2: + info = { + "method": "coupon_bottom_panel_pixels", + "white_ratio": 0.0, + "warm_ratio": 0.0, + "reason": "invalid_region", + } + return (False, info) if return_info else False + + arr = np.asarray(pic_rgb.crop((x1, y1, x2, y2)).convert("RGB")) + if arr.size == 0: + info = { + "method": "coupon_bottom_panel_pixels", + "white_ratio": 0.0, + "warm_ratio": 0.0, + "reason": "empty_region", + } + return (False, info) if return_info else False + + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + ri = r.astype(int) + gi = g.astype(int) + bi = b.astype(int) + white = (r >= 235) & (g >= 235) & (b >= 235) + warm = ( + (r >= 220) + & (g <= 190) + & (b <= 170) + & ((ri - gi) >= 35) + & ((ri - bi) >= 35) + ) + total = white.size + white_ratio = float(np.sum(white) / total) if total > 0 else 0.0 + warm_ratio = float(np.sum(warm) / total) if total > 0 else 0.0 + try: + white_threshold = float( + getattr(analyser, "coupon_bottom_panel_white_ratio_threshold", 0.40) + or 0.40 + ) + except Exception: + white_threshold = 0.40 + try: + warm_threshold = float( + getattr(analyser, "coupon_bottom_panel_warm_ratio_threshold", 0.08) + or 0.08 + ) + except Exception: + warm_threshold = 0.08 + result = white_ratio >= white_threshold and warm_ratio >= warm_threshold + info = { + "method": "coupon_bottom_panel_pixels", + "white_ratio": white_ratio, + "warm_ratio": warm_ratio, + "effective_white_threshold": white_threshold, + "effective_warm_threshold": warm_threshold, + "reason": None if result else "white_or_warm_ratio_below_threshold", + } + if return_info: + return result, info + return result + except Exception as e: # type: ignore[general-exception] + if return_info: + return False, { + "method": "coupon_bottom_panel_pixels", + "white_ratio": 0.0, + "warm_ratio": 0.0, + "reason": f"exception: {str(e)}", + } + return False + + +def _coupon_success_or_return( + pic_rgb: Image.Image, + return_info: bool, + analyser: Any, + fallback_info: dict, +) -> bool | tuple[bool, dict]: + detected, info = _detect_coupon_success_orange_panel( + pic_rgb, + return_info=True, + analyser=analyser, + ) + if detected: + return (True, info) if return_info else True + bottom_detected, bottom_info = _detect_coupon_bottom_panel_by_pixels( + pic_rgb, + return_info=True, + analyser=analyser, + ) + if bottom_detected: + return (True, bottom_info) if return_info else True + return (False, fallback_info) if return_info else False + def detect_coupon_popup_background( pic_rgb: Image.Image, @@ -26,7 +255,10 @@ def detect_coupon_popup_background( template_threshold: float | None = None, analyser: Any = None, ) -> bool | tuple[bool, dict]: - """检测底部优惠券大弹窗(仅模板匹配)。 + """检测优惠券弹窗。 + + 优先检测底部优惠券模板;模板未命中时,兜底检测居中橙色 + "领券成功 / 立即用券" 优惠券弹窗。 模板匹配区域(基于1080x2400基准): - 左上: (9, 1173) @@ -50,11 +282,43 @@ def detect_coupon_popup_background( import cv2 # type: ignore[import-untyped] import numpy as np # type: ignore[import-untyped] except Exception as e: # type: ignore[general-exception] - if return_info: - return False, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "method": "template_match", "template_score": None, "reason": "opencv_unavailable", + }, + ) + + success_detected, success_info = _detect_coupon_success_orange_panel( + pic_rgb, + return_info=True, + analyser=analyser, + ) + if success_detected: + return (True, success_info) if return_info else True + + bottom_detected, bottom_info = _detect_coupon_bottom_panel_by_pixels( + pic_rgb, + return_info=True, + analyser=analyser, + ) + if bottom_detected: + return (True, bottom_info) if return_info else True + if ( + success_info.get("orange_ratio", 0.0) < 0.04 + and bottom_info.get("white_ratio", 0.0) < 0.20 + ): + if return_info: + return False, { + "method": "coupon_fast_pixel_prefilter", + "orange_ratio": success_info.get("orange_ratio", 0.0), + "bottom_white_ratio": bottom_info.get("white_ratio", 0.0), + "bottom_warm_ratio": bottom_info.get("warm_ratio", 0.0), + "reason": "pixel_ratios_too_low_for_coupon", } return False @@ -74,26 +338,32 @@ def detect_coupon_popup_background( y2 = max(0, min(y2, height)) if x1 >= x2 or y1 >= y2: - if return_info: - return False, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "method": "template_match", "template_score": None, "reason": "invalid_region", - } - return False + }, + ) bgr = cv2.cvtColor( # type: ignore[attr-defined] np.asarray(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined] ) roi = bgr[y1:y2, x1:x2] # type: ignore[index] if roi.size == 0: - if return_info: - return False, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "method": "template_match", "template_score": None, "reason": "empty_roi", - } - return False + }, + ) # 使用统一的模板路径配置 try: @@ -105,33 +375,40 @@ def detect_coupon_popup_background( 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, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "method": "template_match", "template_score": None, "reason": "template_not_found", - } - return False + }, + ) - template = cv2.imread( # type: ignore[attr-defined,assignment] - template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] - ) + template = _read_coupon_template(template_path) if template is None: - if return_info: - return False, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "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, { + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { "method": "template_match", "template_score": None, "reason": "template_too_large", - } - return False + }, + ) res = cv2.matchTemplate( # type: ignore[attr-defined] roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] @@ -151,6 +428,19 @@ def detect_coupon_popup_background( threshold = 0.75 result = max_val >= threshold + if not result: + return _coupon_success_or_return( + pic_rgb, + return_info, + analyser, + { + "method": "template_match", + "template_score": float(max_val), + "effective_threshold": threshold, + "reason": "score_below_threshold", + }, + ) + if return_info: reason_value: Optional[str] = None if result else "score_below_threshold" return result, { diff --git a/douyin/fudai/douyin_fudai_finder_pkg/detector.py b/douyin/fudai/douyin_fudai_finder_pkg/detector.py index 542c800..61e50aa 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/detector.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/detector.py @@ -37,6 +37,7 @@ class FudaiDetector: def __init__(self, analyser: Any): self.analyser = analyser + self._current_icon_templates: Optional[Tuple[Tuple[str, Any], ...]] = None self._init_resolution() self._init_search_regions() @@ -463,6 +464,206 @@ class FudaiDetector: def detect_by_template(self, pic: Image.Image, region: Dict) -> Optional[int]: return _impl_detect_by_template(self.analyser, self.rx, pic, region) + + def confirm_current_icon_template(self, pic: Image.Image, detected_x: int) -> bool: + """Confirm a pixel hit with current live-room fudai icon templates. + + The icon has at least two text states ("倒计时" and "待参与"), so this + uses state-specific templates cropped from clean device screenshots. + Matching is local to the pixel candidate to keep it lightweight. + """ + start_time = time.time() + try: + enabled = bool( + getattr(self.analyser, "fudai_current_icon_template_enabled", True) + ) + except Exception: + enabled = True + if not enabled: + return True + + try: + threshold = float( + getattr(self.analyser, "fudai_current_icon_template_threshold", 0.80) + or 0.80 + ) + except Exception: + threshold = 0.80 + + try: + import cv2 # type: ignore[import-untyped] + import numpy as np # type: ignore[import-untyped] + except Exception: + try: + self.analyser._log_kv( + "[福袋查找] 图样确认", + "OpenCV或numpy不可用,跳过当前图样确认", + x=detected_x, + ) + except Exception: + pass + return True + + 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 = ( + ("countdown", os.path.join(template_dir, "fudai_icon_countdown_v20260618.png")), + ("pending", os.path.join(template_dir, "fudai_icon_pending_v20260618.png")), + ) + if self._current_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._current_icon_templates = tuple(loaded_templates) + + if not self._current_icon_templates: + try: + self.analyser._log_kv( + "[福袋查找] 图样确认", + "当前福袋图样模板不存在,跳过确认", + x=detected_x, + ) + except Exception: + pass + return True + + try: + width, height = pic.size + detected_x_scaled = int(detected_x * self.rx / 1080) + x1 = max(0, detected_x_scaled - 180) + x2 = min(width, detected_x_scaled + 180) + y1 = max(0, int(300 * self.ry / 2400) + self.y_pianyi) + y2 = min(height, int(540 * self.ry / 2400) + self.y_pianyi) + if x1 >= x2 or y1 >= y2: + return False + 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 as e: + try: + self.analyser._log_kv( + "[福袋查找] 图样确认", + "当前图样确认取图异常", + x=detected_x, + error=str(e), + ) + except Exception: + pass + return True + + best_score = -1.0 + best_name = "" + best_center_dx: Optional[int] = None + best_loc: Optional[Tuple[int, int]] = None + + for name, template in self._current_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) + left = x1 + int(max_loc[0]) + center = left + tw // 2 + center_dx = center - detected_x_scaled + if score > best_score: + best_score = score + best_name = name + best_center_dx = int(center_dx) + best_loc = (left, y1 + int(max_loc[1])) + except Exception: + continue + + elapsed = (time.time() - start_time) * 1000 + passed = best_score >= threshold + try: + self.analyser._log_kv( + "[福袋查找] 图样确认", + "当前福袋图样确认完成", + x=detected_x, + passed=passed, + score=round(best_score, 4), + threshold=threshold, + template=best_name, + center_dx=best_center_dx, + match_loc=best_loc, + elapsed_ms=round(elapsed, 2), + ) + except Exception: + pass + return bool(passed) + + def confirm_pixel_candidate_shape(self, pic: Image.Image, detected_x: int) -> bool: + """Validate that the pixel hit has the compact shape of a fudai badge.""" + try: + import numpy as np # type: ignore[import-untyped] + + width, height = pic.size + detected_x_scaled = int(detected_x * self.rx / 1080) + x1 = max(0, detected_x_scaled - 80) + x2 = min(width, detected_x_scaled + 80) + y1 = max(0, int(348 * self.ry / 2400) + self.y_pianyi) + y2 = min(height, int(540 * self.ry / 2400) + self.y_pianyi) + if x1 >= x2 or y1 >= y2: + return False + arr = np.asarray(pic.crop((x1, y1, x2, y2)).convert("RGB")) + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + mask = ( + (r >= 190) + & (r <= 206) + & (g >= 173) + & (g <= 196) + & (b >= 234) + & (b <= 250) + ) + cols = np.sum(mask, axis=0) + total = int(np.sum(mask)) + valid_cols = int(np.sum(cols >= 2)) + max_col = int(np.max(cols)) if cols.size else 0 + passed = ( + 20 <= total <= 120 + and 6 <= valid_cols <= 45 + and 2 <= max_col <= 10 + ) + try: + self.analyser._log_kv( + "[福袋查找] 形态确认", + "当前候选像素形态确认完成", + x=detected_x, + passed=passed, + target_pixels=total, + valid_cols=valid_cols, + max_col=max_col, + window=(x1, y1, x2, y2), + ) + except Exception: + pass + return bool(passed) + except Exception: + return True + def detect(self, pic: Image.Image) -> Tuple[Optional[int], str]: """检测福袋图标位置(按优先级搜索,像素检测后需模板匹配确认) @@ -484,6 +685,22 @@ class FudaiDetector: # 优先使用像素检测(更快) detected_x = self.detect_by_pixel(pic, region) if detected_x is not None: + template_ok = self.confirm_current_icon_template(pic, detected_x) + shape_ok = self.confirm_pixel_candidate_shape(pic, detected_x) + if not (template_ok or shape_ok): + try: + self.analyser._log_kv( + "[福袋查找] 检测完成", + "像素命中但图样和形态确认均失败,跳过", + region=region["name"], + x=detected_x, + method="pixel+current_icon_template", + template_ok=template_ok, + shape_ok=shape_ok, + ) + except Exception: + pass + continue # 如果模板匹配已关闭,直接返回像素检测结果 if not template_match_enabled: overall_elapsed = (time.time() - overall_start) * 1000 diff --git a/douyin/fudai/douyin_fudai_finder_pkg/finder.py b/douyin/fudai/douyin_fudai_finder_pkg/finder.py index 3d7ccef..e28e25b 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/finder.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/finder.py @@ -31,6 +31,76 @@ from .detector import FudaiDetector from .image_acquirer import FudaiImageAcquirer +def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool: + """Return True when the current screenshot is already a coupon popup. + + The fudai icon color detector scans the upper live-room hot zone. Coupon + popups can leave purple/pink activity badges visible there, so guard the + click path before trusting those pixels. + """ + try: + if not bool(getattr(analyser, "pixel_detect_coupon_popup_enabled", True)): + return False + except Exception: + return False + + try: + from douyin.detection.pixel.popups import detect_coupon_popup_background + + pic_rgb = pic.convert("RGB") + detected, info = detect_coupon_popup_background( + pic_rgb, + return_info=True, + analyser=analyser, + ) + if bool(detected): + try: + setattr(analyser, "last_fudai_x", 0) + except Exception: + pass + close_sent = False + 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), + ) + except Exception: + pass + try: + analyser._log_kv( + "[福袋查找] 跳过", + "当前截图已是优惠券弹窗,跳过福袋点击并尝试返回关闭", + reason="coupon_popup_before_fudai_click", + coupon_info=info, + close_sent=close_sent, + ) + except Exception: + pass + return True + except Exception as e: + try: + analyser._log_kv( + "[福袋查找] 优惠券预检异常", + "优惠券预检失败,继续正常福袋检测", + error=str(e), + ) + except Exception: + pass + return False + + class FudaiFinder: """福袋查找器:统一管理查找流程""" @@ -163,6 +233,9 @@ class FudaiFinder: self.analyser.operation.delay(sleep_time) continue + if is_coupon_popup_before_fudai_click(self.analyser, pic): + return False, None + # 保存完整截图用于调试(检测前) try: from douyin.handlers import douyin_screenshot_manager diff --git a/douyin/fudai/douyin_fudai_finder_pkg/optimized_entry.py b/douyin/fudai/douyin_fudai_finder_pkg/optimized_entry.py index 8f1dace..3b9fcce 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/optimized_entry.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/optimized_entry.py @@ -26,6 +26,7 @@ except ImportError: from .detector import FudaiDetector +from .finder import is_coupon_popup_before_fudai_click from .image_acquirer import FudaiImageAcquirer @@ -49,6 +50,9 @@ def check_have_fudai_with_ready_screenshot_optimized( if pic is None: return 0 + if is_coupon_popup_before_fudai_click(analyser, pic): + return 0 + detector = FudaiDetector(analyser) detected_x, _detect_method = detector.detect(pic) diff --git a/tests/test_detection_pixel.py b/tests/test_detection_pixel.py index 29717bb..eb6276f 100644 --- a/tests/test_detection_pixel.py +++ b/tests/test_detection_pixel.py @@ -30,6 +30,50 @@ class TestPixelPopups: params = list(sig.parameters.keys()) assert "pic_rgb" in params or len(params) >= 1 + def test_detect_coupon_success_orange_panel(self): + from douyin.detection.pixel.popups import detect_coupon_popup_background + + img = Image.new("RGB", (1080, 2400), (20, 20, 20)) + for y in range(560, 1540): + for x in range(180, 900): + img.putpixel((x, y), (250, 135, 40)) + for y in range(1320, 1480): + for x in range(250, 830): + img.putpixel((x, y), (245, 75, 55)) + + detected, info = detect_coupon_popup_background( + img, + return_info=True, + template_threshold=0.99, + ) + + assert detected is True + assert info["method"] == "coupon_success_orange_panel" + assert info["orange_ratio"] >= 0.18 + assert info["button_warm_ratio"] >= 0.20 + + def test_detect_coupon_bottom_panel_by_pixels(self): + from douyin.detection.pixel.popups import detect_coupon_popup_background + + img = Image.new("RGB", (1080, 2400), (20, 20, 20)) + for y in range(1173, 2255): + for x in range(9, 1079): + img.putpixel((x, y), (248, 248, 248)) + for y in range(1740, 2140): + for x in range(150, 930): + img.putpixel((x, y), (245, 80, 100)) + + detected, info = detect_coupon_popup_background( + img, + return_info=True, + template_threshold=0.99, + ) + + assert detected is True + assert info["method"] == "coupon_bottom_panel_pixels" + assert info["white_ratio"] >= 0.40 + assert info["warm_ratio"] >= 0.08 + def test_detect_redpacket_popup_exists(self): from douyin.detection.pixel.popups import detect_redpacket_popup_background diff --git a/tests/test_fudai_finder_pkg.py b/tests/test_fudai_finder_pkg.py index 4432e78..9475e72 100644 --- a/tests/test_fudai_finder_pkg.py +++ b/tests/test_fudai_finder_pkg.py @@ -8,8 +8,15 @@ check_have_fudai_with_ready_screenshot_optimized。 """ from __future__ import annotations +from unittest.mock import MagicMock, patch + import pytest +try: + from PIL import Image +except ImportError: + pytest.skip("PIL unavailable", allow_module_level=True) + from douyin.fudai.douyin_fudai_finder import ( FudaiClickExecutor, FudaiDetailVerifier, @@ -33,8 +40,18 @@ class FakeAnalyser: self.resolution_ratio_x = 1080 self.resolution_ratio_y = 2400 self.y_pianyi = 0 + self.last_fudai_x = 123 + self.pixel_detect_coupon_popup_enabled = True + self._log_kv = MagicMock(return_value=None) # FudaiClickExecutor 可能用 operation - class _Op: pass + class _Op: + def __init__(self): + self.click_back = MagicMock(return_value=None) + self.delay = MagicMock(return_value=None) + + def delay(self, _seconds): + return None + self.operation = _Op() @@ -70,9 +87,81 @@ class TestFudaiDetector: def test_detect_methods_callable(self): d = FudaiDetector(FakeAnalyser()) - for name in ("detect", "detect_by_pixel", "detect_by_template"): + for name in ( + "detect", + "detect_by_pixel", + "detect_by_template", + "confirm_current_icon_template", + "confirm_pixel_candidate_shape", + ): assert callable(getattr(d, name, None)), f"{name} 不可调用" + def test_current_icon_template_confirms_clean_countdown_sample(self): + from pathlib import Path + + sample = Path( + "artifacts/live_fudai_flow_20260618_0530_valid/snapshots/" + "screen_current_for_icon_template.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + analyser.fudai_current_icon_template_threshold = 0.80 + d = FudaiDetector(analyser) + + assert d.confirm_current_icon_template(Image.open(sample).convert("RGB"), 175) + + def test_current_icon_template_rejects_banner_edge_sample(self): + from pathlib import Path + + sample = Path( + "pic/debug_captures/2026-06-18/" + "20260618_074702_110140_px_fdicon_ok_x262y373w60h60_" + "src_flow_on_detect_click_x_292_click_y_403_detected_x_scaled_292.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + analyser = FakeAnalyser() + analyser.fudai_current_icon_template_threshold = 0.80 + d = FudaiDetector(analyser) + + assert not d.confirm_current_icon_template( + Image.open(sample).convert("RGB"), + 292, + ) + + def test_pixel_candidate_shape_accepts_other_real_icon_style(self): + from pathlib import Path + + sample = Path( + "pic/debug_captures/2026-06-18/" + "20260618_070004_938228_px_fdicon_ok_x53y373w60h60_" + "src_flow_on_detect_click_x_83_click_y_403_detected_x_scaled_83.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + d = FudaiDetector(FakeAnalyser()) + + assert d.confirm_pixel_candidate_shape(Image.open(sample).convert("RGB"), 83) + + def test_pixel_candidate_shape_rejects_banner_edge_sample(self): + from pathlib import Path + + sample = Path( + "pic/debug_captures/2026-06-18/" + "20260618_074702_110140_px_fdicon_ok_x262y373w60h60_" + "src_flow_on_detect_click_x_292_click_y_403_detected_x_scaled_292.png" + ) + if not sample.exists(): + pytest.skip("live debug sample unavailable") + + d = FudaiDetector(FakeAnalyser()) + + assert not d.confirm_pixel_candidate_shape(Image.open(sample).convert("RGB"), 292) + # ============================================================ # FudaiClickExecutor @@ -113,6 +202,27 @@ class TestFudaiFinder: assert finder.acquirer.analyser is analyser assert finder.detector.analyser is analyser + def test_coupon_popup_guard_skips_click(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}), + ): + ok, x = finder.find_and_open() + + assert ok is False + assert x is None + assert analyser.last_fudai_x == 0 + analyser.operation.click_back.assert_called_once_with(analyser.device_id) + finder.detector.detect.assert_not_called() + finder.executor.click.assert_not_called() + # ============================================================ # 顶层函数 @@ -122,6 +232,26 @@ class TestCheckHaveFudaiWithReadyScreenshotOptimized: def test_callable(self): assert callable(check_have_fudai_with_ready_screenshot_optimized) + def test_coupon_popup_guard_returns_zero(self): + analyser = FakeAnalyser() + pic = Image.new("RGB", (1080, 2400), (255, 255, 255)) + + with patch( + "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiImageAcquirer" + ) as acquirer_cls, patch( + "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiDetector" + ) as detector_cls, patch( + "douyin.detection.pixel.popups.detect_coupon_popup_background", + return_value=(True, {"template_score": 0.9}), + ): + acquirer_cls.return_value.acquire_screenshot.return_value = pic + result = check_have_fudai_with_ready_screenshot_optimized(analyser) + + assert result == 0 + assert analyser.last_fudai_x == 0 + analyser.operation.click_back.assert_called_once_with(analyser.device_id) + detector_cls.assert_not_called() + # ============================================================ # detect_by_template 已拆出为 module-level 函数