"""detection_pkg.detail - 福袋详情页相关检测。 - check_detail_height 识别详情页弹窗中"任务"数量(0/1/2/3) - check_in_fudai_detail 判断当前是否处于福袋详情页(综合多种特征) """ from __future__ import annotations # pylint: disable=no-member import os import re import time from typing import Any from ._common import _ensure_detection_cache def check_detail_height(analyser: Any, pic_rgb: Any = None) -> int: """Detect how many tasks are required in the fudai detail popup. Returns: 0 / 1 / 2 / 3 (number of tasks). """ try: from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode ui_mode = normalize_fudai_detail_ui_mode( getattr(analyser, "fudai_detail_ui_mode", "auto") ) except Exception: ui_mode = "auto" if ui_mode == "legacy": return _check_detail_task_count_legacy_pixels(analyser) detected_v2_template = _check_detail_task_count_v2(analyser, pic_rgb=pic_rgb) if detected_v2_template: return detected_v2_template return 0 def _check_detail_task_count_legacy_pixels(analyser: Any) -> int: """Legacy detail task-count detection. Kept separate from v2 UI height logic.""" # 使用统一的截图路径配置 try: from douyin.core import path_config pic1_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) from douyin.core import path_config pic1_path = path_config.get_screenshot_path() # 记录截图文件的时间戳(如果存在) screenshot_timestamp = None try: if os.path.exists(pic1_path): screenshot_timestamp = os.path.getmtime(pic1_path) except Exception: pass pic = None for attempt in range(3): try: from PIL import Image pic = Image.open(pic1_path) pic.load() # force load to catch truncated files early break except Exception: if attempt < 2: try: analyser.operation.get_screenshot( analyser.device_id, use_service=False ) analyser.operation.delay(0.2) # 重新获取截图后,更新时间戳 try: if os.path.exists(pic1_path): screenshot_timestamp = os.path.getmtime(pic1_path) except Exception: pass except Exception: pass pic = None if pic is None: try: analyser._log_kv( "检测", "读取截图失败,默认不需要任务", level="WARN", screenshot_timestamp=screenshot_timestamp, ) except Exception: pass return 0 pic_new = pic.convert("RGBA") pix = pic_new.load() width, height = pic_new.size # X of “参与” button try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) except Exception: rx = 1080 try: ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: ry = 2400 x = 536 * rx // 1080 if not (0 <= x < width): return 0 # (base_y, y_pianyi_offset, task_count) try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) except Exception: y_pianyi_val = 0 check_points = [ (983, 0, 2), (983, y_pianyi_val, 2), (983, -y_pianyi_val, 2), (883, 0, 3), (883, y_pianyi_val, 3), (883, -y_pianyi_val, 3), (1058, 0, 1), (1058, y_pianyi_val, 1), (1058, -y_pianyi_val, 1), ] def _check_pixel_color(y_coord: int) -> bool: if not (0 <= y_coord < height): return False try: p = pix[x, y_coord] if not (isinstance(p, tuple) and len(p) >= 3): return False r, g, b = int(p[0]), int(p[1]), int(p[2]) return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86 except Exception: return False detected_task_count = None detected_y = None try: for base_y, dy, task_count in check_points: y = base_y * ry // 2400 + dy if _check_pixel_color(y): detected_task_count = task_count detected_y = y try: import time current_time = time.time() analyser._log_kv( "检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count, detected_y=detected_y, screenshot_timestamp=screenshot_timestamp, current_time=current_time, time_diff=( round(current_time - screenshot_timestamp, 3) if screenshot_timestamp else None ), ) except Exception: pass break except Exception: pass # 保存调试图片:标注检测区域和检测点 try: from douyin.handlers import douyin_screenshot_manager # 计算检测区域(参与按钮附近的区域) check_region_x1 = max(0, x - 50) check_region_x2 = min(width, x + 50) check_region_y1 = max(0, (883 * ry // 2400) - 100) # 3个任务的Y坐标附近 check_region_y2 = min(height, (1058 * ry // 2400) + 100) # 1个任务的Y坐标附近 # 标注检测点 coords_list = [] for base_y, dy, task_count_val in check_points: check_y = base_y * ry // 2400 + dy if 0 <= check_y < height: # 标注检测点(小矩形区域) coords_list.append( ( max(0, x - 10), max(0, check_y - 5), min(width, x + 10), min(height, check_y + 5), ) ) # 保存调试图片 pic_rgb = pic.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, operation_type="detection", picname="福袋任务数量", step="task_count_detection", coords=(check_region_x1, check_region_y1, check_region_x2, check_region_y2), extra_info={ "task_count": ( detected_task_count if detected_task_count is not None else 0 ), "detected_y": detected_y, "check_x": x, "check_points_count": len(check_points), "region": f"({check_region_x1},{check_region_y1})-({check_region_x2},{check_region_y2})", }, ) if debug_path: try: analyser._log_kv( "[调试图像]", "福袋任务数量检测", path=debug_path, task_count=( detected_task_count if detected_task_count is not None else 0 ), log_type="DEBUG", ) except Exception: pass except Exception: pass if detected_task_count is not None: return detected_task_count # Optional robot-check path from original implementation try: if ( hasattr(analyser, "check_have_robot_analyse") and analyser.check_have_robot_analyse() ): analyser.deal_robot_analyse() except Exception: pass try: import time current_time = time.time() analyser._log_kv( "检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0, screenshot_timestamp=screenshot_timestamp, current_time=current_time, time_diff=( current_time - screenshot_timestamp if screenshot_timestamp else None ), ) except Exception: pass return 0 def _check_detail_task_count_v2_pixels(analyser: Any) -> int: """Fast v2 task-count decision from scanning the dark task-card top edge.""" try: from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode ui_mode = normalize_fudai_detail_ui_mode( getattr(analyser, "fudai_detail_ui_mode", "auto") ) if ui_mode == "legacy": return 0 except Exception: ui_mode = "auto" try: from douyin.core import path_config from PIL import Image pic_path = path_config.get_screenshot_path() pic = Image.open(pic_path).convert("RGB") width, height = pic.size except Exception: return 0 try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) except Exception: rx = 1080 try: ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: ry = 2400 # 快速区分 two-task:你提供的上方大横带在 two-task 样本里深色命中明显更多。 upper_x_start = 2 * rx // 1080 upper_x_end = 1075 * rx // 1080 upper_y_start = 1018 * ry // 2400 upper_y_end = 1080 * ry // 2400 # one-task 兜底:保留较低位置的任务卡顶部横带检测。 lower_x_start = 420 * rx // 1080 lower_x_end = 860 * rx // 1080 lower_y_band = 1866 * ry // 2400 legacy_two_task_y1 = 1686 * ry // 2400 legacy_two_task_y2 = 1788 * ry // 2400 if not ( 0 <= upper_x_start < width and 0 < upper_x_end <= width and upper_x_start < upper_x_end and 0 <= upper_y_start < height and 0 < upper_y_end <= height and upper_y_start < upper_y_end and 0 <= lower_x_start < width and 0 < lower_x_end <= width and lower_x_start < lower_x_end and 0 <= lower_y_band < height and 0 <= legacy_two_task_y1 < height and 0 <= legacy_two_task_y2 < height ): return 0 def _is_white_text(pixel: tuple[int, int, int]) -> bool: r, g, b = pixel return r >= 215 and g >= 215 and b >= 215 def _is_dark_card(pixel: tuple[int, int, int]) -> bool: r, g, b = pixel return 5 <= r <= 45 and 10 <= g <= 55 and 35 <= b <= 95 upper_sample_xs = [ int(v) for v in ( upper_x_start, upper_x_start + (upper_x_end - upper_x_start) * 0.2, upper_x_start + (upper_x_end - upper_x_start) * 0.4, upper_x_start + (upper_x_end - upper_x_start) * 0.6, upper_x_start + (upper_x_end - upper_x_start) * 0.8, upper_x_end - 1, ) ] upper_sample_xs = [x for x in upper_sample_xs if 0 <= x < width] lower_sample_xs = [ int(v) for v in ( lower_x_start, lower_x_start + (lower_x_end - lower_x_start) * 0.25, lower_x_start + (lower_x_end - lower_x_start) * 0.5, lower_x_start + (lower_x_end - lower_x_start) * 0.75, lower_x_end - 1, ) ] lower_sample_xs = [x for x in lower_sample_xs if 0 <= x < width] def _dark_hits_at_y(y_coord: int, xs: list[int]) -> int: hits = 0 for sx in xs: try: pixel = pic.getpixel((sx, y_coord)) except Exception: continue if _is_dark_card((int(pixel[0]), int(pixel[1]), int(pixel[2]))): hits += 1 return hits upper_band_dark_sum = 0 lower_band_dark_hits = 0 legacy_two_task_hits_1 = 0 legacy_two_task_hits_2 = 0 try: for y_coord in range(upper_y_start, upper_y_end + 1, max(1, 4 * ry // 2400)): upper_band_dark_sum += _dark_hits_at_y(y_coord, upper_sample_xs) lower_band_dark_hits = _dark_hits_at_y(lower_y_band, lower_sample_xs) legacy_two_task_hits_1 = _dark_hits_at_y(legacy_two_task_y1, lower_sample_xs) legacy_two_task_hits_2 = _dark_hits_at_y(legacy_two_task_y2, lower_sample_xs) except Exception: return 0 detected = 0 reason = "" if upper_band_dark_sum >= 36: detected = 2 reason = "upper_band_dark_sum_two_task" elif legacy_two_task_hits_1 >= 3 and legacy_two_task_hits_2 >= 3: detected = 2 reason = "legacy_two_task_band_hits" elif lower_band_dark_hits >= 3: detected = 1 reason = "lower_band_dark_hits_one_task" if detected: try: setattr(analyser, "_fudai_detail_task_count_source", "v2_pixels") analyser._log_kv( "检测", f"识别到福袋任务数量:{detected}个(v2像素高度)", task_count=detected, source="v2_pixels", ) analyser._log_kv( "检测", "福袋任务数量v2像素高度详情", task_count=detected, source="v2_pixels", reason=reason, upper_x_start=upper_x_start, upper_x_end=upper_x_end, upper_y_start=upper_y_start, upper_y_end=upper_y_end, upper_sample_xs=",".join(str(v) for v in upper_sample_xs), upper_band_dark_sum=upper_band_dark_sum, lower_x_start=lower_x_start, lower_x_end=lower_x_end, lower_y_band=lower_y_band, lower_sample_xs=",".join(str(v) for v in lower_sample_xs), lower_band_dark_hits=lower_band_dark_hits, legacy_two_task_y1=legacy_two_task_y1, legacy_two_task_y2=legacy_two_task_y2, legacy_two_task_hits_1=legacy_two_task_hits_1, legacy_two_task_hits_2=legacy_two_task_hits_2, ui_mode=ui_mode, log_type="DEBUG", ) except Exception: pass return detected def _check_detail_task_count_v2(analyser: Any, pic_rgb: Any = None) -> int: """Fast v2 detail task-count recognition by matching the task-count digit only.""" try: import cv2 # type: ignore[import-untyped] import numpy as np # type: ignore[import-untyped] from PIL import Image from douyin.core import path_config from douyin.fudai.core.coords import DETAIL_UI_V2_0, DETAIL_UI_V2_0_ONE_TASK if pic_rgb is not None: pic = pic_rgb.convert("RGB") if hasattr(pic_rgb, "convert") else Image.fromarray(pic_rgb).convert("RGB") else: pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): return 0 pic = Image.open(pic_path).convert("RGB") pic_rgb = np.asarray(pic) pic_gray = cv2.cvtColor(pic_rgb, cv2.COLOR_RGB2GRAY) def _pink_digit_mask(rgb_arr: Any) -> Any: r = rgb_arr[:, :, 0].astype(np.int16) g = rgb_arr[:, :, 1].astype(np.int16) b = rgb_arr[:, :, 2].astype(np.int16) return ( (r > 145) & (g > 25) & (g < 170) & (b > 60) & (b < 220) & ((r - g) > 45) & ((b - g) > 10) ) def _mask_iou(mask_a: Any, mask_b: Any) -> float: intersection = np.logical_and(mask_a, mask_b).sum() union = np.logical_or(mask_a, mask_b).sum() return float(intersection / union) if union else 0.0 assets_dir = path_config.get_assets_dir() candidates = ( ( 1, "one_task", tuple(DETAIL_UI_V2_0_ONE_TASK.get("task_count") or ()), os.path.join(assets_dir, "fudai_task_count_digit_1.png"), ), ( 2, "two_task", tuple(DETAIL_UI_V2_0.get("task_count") or ()), os.path.join(assets_dir, "fudai_task_count_digit_2.png"), ), ) best_count = 0 best_score = -1.0 best_variant = "" best_box = None best_passes = False for task_count, variant, box, template_path in candidates: if len(box) != 4 or not os.path.exists(template_path): continue digit_box = get_detail_task_count_digit_box(tuple(int(v) for v in box)) x1, y1, x2, y2 = digit_box roi_full = pic_gray[y1:y2, x1:x2] roi_rgb = pic_rgb[y1:y2, x1:x2] if roi_full.size == 0: continue template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) if template is None: continue template_rgb = np.asarray(Image.open(template_path).convert("RGB")) rh, rw = roi_full.shape[:2] th, tw = template.shape[:2] if th <= 0 or tw <= 0 or rh <= 0 or rw <= 0: continue w = min(rw, tw) h = min(rh, th) roi_resized = cv2.resize(roi_full, (w, h)) tpl_resized = cv2.resize(template, (w, h)) roi_rgb_resized = cv2.resize(roi_rgb, (w, h), interpolation=cv2.INTER_NEAREST) tpl_rgb_resized = cv2.resize(template_rgb, (w, h), interpolation=cv2.INTER_NEAREST) roi_eq = cv2.equalizeHist(roi_resized) tpl_eq = cv2.equalizeHist(tpl_resized) score_eq = float( cv2.matchTemplate(roi_eq, tpl_eq, cv2.TM_CCOEFF_NORMED)[0][0] ) roi_bin = cv2.threshold(roi_resized, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] tpl_bin = cv2.threshold(tpl_resized, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] score_bin = float( cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)[0][0] ) roi_mask = _pink_digit_mask(roi_rgb_resized) tpl_mask = _pink_digit_mask(tpl_rgb_resized) mask_score = _mask_iou(roi_mask, tpl_mask) roi_mask_pixels = int(roi_mask.sum()) tpl_mask_pixels = int(tpl_mask.sum()) score = max(score_eq, score_bin, mask_score) passes_digit_mask = ( mask_score >= 0.30 and roi_mask_pixels >= max(40, int(tpl_mask_pixels * 0.45)) ) passes_full_template = score >= 0.94 should_replace_best = ( (passes_full_template or passes_digit_mask) and not best_passes ) or ( (passes_full_template or passes_digit_mask) == best_passes and score > best_score ) if should_replace_best: best_score = score best_count = task_count best_variant = variant best_box = box best_passes = passes_full_template or passes_digit_mask try: analyser._log_kv( "任务数诊断", "[TASK_COUNT_DIAG] candidate_scored", task_count=task_count, variant=variant, digit_box=digit_box, score_eq=round(score_eq, 4), score_bin=round(score_bin, 4), score_mask=round(mask_score, 4), mask_pixels=roi_mask_pixels, score=max(round(score, 4), 0.0), ) except Exception: pass if best_count and best_passes: try: setattr(analyser, "_fudai_detail_task_count_source", "v2_template") analyser._log_kv( "检测", f"识别到福袋任务数量:{best_count}个(v2 数字模板匹配)", task_count=best_count, source="v2_digit_template", profile_variant=best_variant, template_score=round(best_score, 4), digit_box=get_detail_task_count_digit_box(tuple(int(v) for v in best_box)), ) analyser._log_kv( "任务数诊断", "[TASK_COUNT_DIAG] matched", task_count=best_count, variant=best_variant, template_score=round(best_score, 4), digit_box=get_detail_task_count_digit_box(tuple(int(v) for v in best_box)), ) except Exception: pass return best_count try: analyser._log_kv( "任务数诊断", "[TASK_COUNT_DIAG] no_match", best_count=best_count, best_variant=best_variant, best_score=round(best_score, 4) if best_score >= 0 else best_score, ) except Exception: pass except Exception: return 0 return 0 def get_detail_task_count_digit_box(task_count_box: tuple[int, int, int, int]) -> tuple[int, int, int, int]: """Extract the trailing task-count digit box inside the (0/1)/(1/2) badge.""" x1, y1, x2, y2 = [int(v) for v in task_count_box] # one-task and two-task badges have different anchors in current verified samples. if y1 >= 1830: digit_x1 = x1 + 86 digit_x2 = x1 + 98 digit_y1 = y1 + 16 digit_y2 = y1 + 46 else: digit_x1 = x1 + 114 digit_x2 = x1 + 135 digit_y1 = y1 + 44 digit_y2 = y1 + 75 if digit_x2 <= digit_x1: digit_x2 = min(x2, digit_x1 + 1) if digit_y2 <= digit_y1: digit_y2 = min(y2, digit_y1 + 1) return digit_x1, digit_y1, digit_x2, digit_y2 def check_in_fudai_detail(analyser: Any) -> bool: """Detect whether we are currently on the fudai detail page. 使用模板匹配检测,与 detect_fudai_detail_page 保持一致。 """ _ensure_detection_cache(analyser) cache_key = "check_in_fudai_detail" now = time.time() cached = analyser._detection_cache.get(cache_key) if cached: cached_ts, cached_result = cached ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0) if (now - cached_ts) < ttl: return bool(cached_result) # 使用模板匹配检测,与 detect_fudai_detail_page 保持一致 try: from douyin.detection import douyin_pixel from douyin.core import path_config # 获取截图 pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): try: analyser.operation.get_screenshot(analyser.device_id) except Exception: analyser._detection_cache[cache_key] = (now, False) return False pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): analyser._detection_cache[cache_key] = (now, False) return False from PIL import Image pic = Image.open(pic_path) try: pic.load() pic_rgb = pic.convert("RGB") finally: pic.close() # 获取分辨率比例和Y偏移 rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) # 获取模板匹配阈值(优先使用福袋详情页专用阈值) template_threshold = float( getattr(analyser, "fudai_detail_template_threshold", None) or getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) if template_threshold < 0.0: template_threshold = 0.0 if template_threshold > 1.0: template_threshold = 1.0 # 使用任务数量检测 result = douyin_pixel.detect_fudai_detail_page( pic_rgb, rx, ry, y_pianyi, template_threshold, return_info=False, # 不需要详细信息 analyser=analyser, ) is_in_detail = bool(result) analyser._detection_cache[cache_key] = (now, is_in_detail) return is_in_detail except Exception: analyser._detection_cache[cache_key] = (now, False) return False # ========== 以下为旧的像素检测代码,已暂时禁用 ========== # 像素检测代码已删除,使用模板匹配替代 # 如需恢复像素检测,请参考 git 历史记录