"""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) -> 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_pixels = _check_detail_task_count_v2_pixels(analyser) if detected_v2_pixels: return detected_v2_pixels 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 popup height pixels before OCR regions are chosen.""" 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 x = 536 * rx // 1080 y_task_text = 1970 * ry // 2400 y_task_card = 1955 * ry // 2400 if not (0 <= x < width and 0 <= y_task_text < height and 0 <= y_task_card < height): return 0 def _rgb_at(y_coord: int) -> tuple[int, int, int]: p = pic.getpixel((x, y_coord)) return int(p[0]), int(p[1]), int(p[2]) 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 try: task_text_pixel = _rgb_at(y_task_text) task_card_pixel = _rgb_at(y_task_card) except Exception: return 0 # 当前 2.0 UI:一个任务时中线 y=1970 命中任务文案白字; # 两个任务时同点仍是任务卡片深色背景。先用这个高度差选 profile。 detected = 0 reason = "" if _is_white_text(task_text_pixel): detected = 1 reason = "task_text_white_at_v2_one_task_y" elif _is_dark_card(task_text_pixel) and _is_dark_card(task_card_pixel): detected = 2 reason = "dark_card_continues_at_v2_two_task_y" 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, check_x=x, task_text_y=y_task_text, task_text_pixel=task_text_pixel, task_card_y=y_task_card, task_card_pixel=task_card_pixel, ui_mode=ui_mode, log_type="DEBUG", ) except Exception: pass return detected def _check_detail_task_count_v2(analyser: Any) -> int: """Fast v2 detail task-count OCR: parse denominator from '(1/2)'.""" try: from douyin.fudai.core.coords import DETAIL_UI_V2_0, DETAIL_UI_V2_0_ONE_TASK for name, profile in ( ("福袋任务数量_v2_1task", DETAIL_UI_V2_0_ONE_TASK), ("福袋任务数量_v2", DETAIL_UI_V2_0), ): box = tuple(profile.get("task_count") or ()) if len(box) != 4: continue if hasattr(analyser, "cut_pic"): analyser.cut_pic(*box, "", name, getattr(analyser, "y_pianyi", 0)) raw = "" try: raw = str(analyser.operation.analyse_pic_word(name, 0) or "") except Exception: raw = str(analyser.operation.analyse_pic_digits(name, 0) or "") m = re.search(r"[\(/(]\s*\d+\s*[//]\s*([1-3])\s*[\))]?", raw) if not m: m = re.search(r"\d+\s*[//]\s*([1-3])", raw) if not m: continue task_count = int(m.group(1)) try: analyser._log_kv( "检测", f"识别到福袋任务数量:{task_count}个(v2 OCR)", task_count=task_count, source="v2_ocr", profile_variant=str(profile.get("variant") or "default"), raw=raw[:50], ) except Exception: pass return task_count except Exception: return 0 return 0 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 历史记录