from __future__ import annotations """ Functional fudai detection (WebGUI version) =========================================== This module reimplements the key detection helpers used in `douyin_fudai`: - check_detail_height(analyser) -> int - check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) -> bool - check_in_fudai_detail(analyser) -> bool The logic is adapted from the original `axf/douyin_detection.py`, with extra defensive checks to avoid crashes when certain analyser attributes are missing. """ from typing import Any import os import time from PIL import Image def _ensure_detection_cache(analyser: Any) -> None: """Ensure analyser has a simple detection cache structure.""" if not hasattr(analyser, "_detection_cache"): analyser._detection_cache = {} if not hasattr(analyser, "_detection_cache_ttl"): analyser._detection_cache_ttl = 2.0 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). """ path = os.path.join(os.path.dirname(__file__), "pic") pic1_path = os.path.join(path, "screenshot.png") pic = None for attempt in range(3): try: 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) analyser.operation.delay(0.2) except Exception: pass pic = None if pic is None: try: analyser._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN") 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 try: for base_y, dy, task_count in check_points: y = base_y * ry // 2400 + dy if _check_pixel_color(y): try: analyser._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count) except Exception: pass return task_count except Exception: pass # 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: analyser._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0) except Exception: pass return 0 def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False): """Check whether the live-room screen currently has a fudai icon. 使用模板匹配进行检测(暂时关闭像素检测): - 使用 assets/fudai.png 作为模板进行匹配 - 在指定区域内搜索福袋图标 """ func_start = time.time() path = os.path.join(os.path.dirname(__file__), "pic") pic1_path = os.path.join(path, "screenshot.png") attempt_count = 0 # 仅用于日志记录,不影响循环控制 try: retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3) except Exception: retry_delay_s = 0.3 try: max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5) except Exception: max_wait_s = 2.5 if retry_delay_s < 0.15: retry_delay_s = 0.15 if max_wait_s < 0: max_wait_s = 0.0 try: analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配") except Exception: pass detected_any = False detected_x = None # 检查OpenCV是否可用 try: import cv2 import numpy as np except Exception: try: analyser._log_kv("[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配") except Exception: pass return False # 获取模板路径 base_dir = os.path.dirname(__file__) template_path = os.path.join(base_dir, "assets", "fudai.png") if not os.path.exists(template_path): try: analyser._log_kv("[找福袋图标] 错误", f"模板文件不存在: {template_path}") except Exception: pass return False # 获取匹配阈值 try: template_threshold = float(getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7) except Exception: template_threshold = 0.7 # 完全基于时间限制,不使用次数限制 while (time.time() - func_start) < max_wait_s: attempt_start = time.time() attempt_count += 1 # Reuse external screenshot only on first attempt if provided if not (screenshot_ready and attempt_count == 1): try: analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False) except Exception: pass try: screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) if screenshot_img is None: try: analyser.operation.get_screenshot(analyser.device_id) screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) except Exception: pass if screenshot_img is None: elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) continue except Exception: elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) continue # Resolution ratios 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 try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) except Exception: y_pianyi_val = 0 # 定义搜索区域 # X范围:34-382(1080基准) # Y范围:357-451(2400基准),福袋图标所在高度 search_x1 = max(0, 34 * rx // 1080) search_x2 = min(screenshot_img.shape[1], 382 * rx // 1080) search_y1_base = 357 * ry // 2400 + y_pianyi_val search_y2_base = 451 * ry // 2400 + y_pianyi_val search_y1 = max(0, search_y1_base) search_y2 = min(screenshot_img.shape[0], search_y2_base) if search_x1 >= search_x2 or search_y1 >= search_y2: elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) continue # 裁剪搜索区域 search_roi = screenshot_img[search_y1:search_y2, search_x1:search_x2] # 读取模板 try: template = cv2.imread(template_path, cv2.IMREAD_COLOR) if template is None: try: analyser._log_kv("[找福袋图标] 错误", f"无法读取模板文件: {template_path}") except Exception: pass elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) continue except Exception as e: try: analyser._log_kv("[找福袋图标] 错误", f"读取模板文件异常: {str(e)}") except Exception: pass elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) continue # 检查模板和搜索区域尺寸 th, tw = template.shape[:2] rh, rw = search_roi.shape[:2] if th > rh or tw > rw: # 模板太大,缩小模板 scale = min(rh / max(th, 1), rw / max(tw, 1)) if scale > 0: template = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale)))) th, tw = template.shape[:2] # 执行模板匹配(使用彩色匹配) try: template_match_start = time.time() # 详细日志:记录搜索区域和模板信息 try: analyser._log_kv( "[找福袋图标] 模板匹配开始", f"搜索区域", search_x1=search_x1, search_x2=search_x2, search_y1=search_y1, search_y2=search_y2, search_width=search_x2 - search_x1, search_height=search_y2 - search_y1, template_width=tw, template_height=th, template_path=template_path, 阈值=template_threshold, 匹配模式="彩色(BGR)", ) except Exception: pass # 使用彩色匹配(BGR三通道) res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) template_match_elapsed = (time.time() - template_match_start) * 1000 # 详细日志:记录匹配结果 try: analyser._log_kv( "[找福袋图标] 模板匹配结果", f"匹配分数={round(max_val, 4)},阈值={template_threshold}", 耗时毫秒=round(template_match_elapsed, 2), 是否通过=bool(max_val >= template_threshold), 最小分数=round(_min_val, 4), 最佳位置=f"({max_loc[0]}, {max_loc[1]})", ) except Exception: pass if max_val >= template_threshold: # 计算检测到的X坐标(1080基准) detected_x_in_roi = max_loc[0] detected_x = int((search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) detected_y_in_roi = max_loc[1] detected_y = int((search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry)) detected_any = True # 保存匹配位置的图片 try: # 计算匹配区域在原图中的坐标(扩大一些范围以便查看上下文) margin = 20 # 扩大20像素的边距 match_x1 = max(0, search_x1 + detected_x_in_roi - margin) match_y1 = max(0, search_y1 + detected_y_in_roi - margin) match_x2 = min(screenshot_img.shape[1], search_x1 + detected_x_in_roi + tw + margin) match_y2 = min(screenshot_img.shape[0], search_y1 + detected_y_in_roi + th + margin) # 裁剪匹配区域 match_roi = screenshot_img[match_y1:match_y2, match_x1:match_x2] # 保存到 pic/template_match/ 目录 base_dir = os.path.dirname(__file__) pic_base = os.path.join(base_dir, 'pic') match_dir = os.path.join(pic_base, 'template_match') os.makedirs(match_dir, exist_ok=True) # 文件名包含时间戳和匹配分数 timestamp = int(time.time() * 1000) score_str = f"{max_val:.4f}".replace('.', '_') match_filename = f"fudai_match_{timestamp}_score_{score_str}.png" match_path = os.path.join(match_dir, match_filename) # 检查裁剪区域是否有效 if match_roi.size == 0: analyser._log_kv( "[找福袋图标] 警告", "匹配区域裁剪后为空,跳过保存", 区域坐标=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", ) else: # 保存图片 save_success = cv2.imwrite(match_path, match_roi) # 验证文件是否真的保存成功 file_exists = os.path.exists(match_path) file_size = os.path.getsize(match_path) if file_exists else 0 analyser._log_kv( "[找福袋图标] 已保存匹配位置图片", f"路径: {match_path}", 匹配区域=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", 区域大小=f"{match_x2 - match_x1}x{match_y2 - match_y1}", ROI尺寸=f"{match_roi.shape[1]}x{match_roi.shape[0]}", cv2保存返回值=save_success, 文件存在=file_exists, 文件大小字节=file_size, ) if not file_exists or file_size == 0: analyser._log_kv( "[找福袋图标] 警告", "保存的图片文件不存在或大小为0", 路径=match_path, ) else: # 保存成功,输出绝对路径方便查看 abs_path = os.path.abspath(match_path) analyser._log_kv( "[找福袋图标] 图片保存成功", f"绝对路径: {abs_path}", ) except Exception as e: try: analyser._log_kv( "[找福袋图标] 保存匹配位置图片失败", f"异常: {str(e)}", ) except Exception: pass try: analyser.last_find_fudai_time = time.time() analyser._log_kv( "[找福袋图标] 模板匹配命中", f"检测到福袋图标", x=detected_x, y=detected_y, 匹配分数=round(max_val, 4), x_in_roi=detected_x_in_roi, y_in_roi=detected_y_in_roi, 模板中心偏移=f"({tw//2}, {th//2})", 实际屏幕坐标=f"({detected_x}, {detected_y})", ) except Exception: pass break else: # 未命中时也记录日志 try: analyser._log_kv( "[找福袋图标] 模板匹配未命中", f"匹配分数={round(max_val, 4)} < 阈值={template_threshold}", 差值=round(template_threshold - max_val, 4), ) except Exception: pass except Exception as e: try: analyser._log_kv( "[找福袋图标] 模板匹配异常", f"异常: {str(e)}", 异常类型=type(e).__name__, ) except Exception: pass # 检查是否还有剩余时间 elapsed = time.time() - func_start if elapsed < max_wait_s: remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: try: analyser.operation.delay(sleep_time) except Exception: time.sleep(sleep_time) try: total_elapsed = time.time() - func_start analyser._log_kv( "[找福袋图标] 结束", "检测完成", detected=bool(detected_any and detected_x is not None), elapsed_ms=int(total_elapsed * 1000), ) except Exception: pass # 与原始 fudai.py 的 check_have_fudai 行为保持一致: # 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。 return int(detected_x) if detected_x is not None else False # ========== 以下为旧的像素检测代码,已暂时禁用 ========== # 像素检测代码已删除,使用模板匹配替代 # 如需恢复像素检测,请参考 git 历史记录 def check_in_fudai_detail(analyser: Any) -> bool: """Detect whether we are currently on the 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) path = os.path.join(os.path.dirname(__file__), "pic") pic1_path = os.path.join(path, "screenshot.png") try: try: pic0 = Image.open(pic1_path) pic0.load() pic = pic0.convert("RGBA") except Exception: try: analyser.operation.get_screenshot(analyser.device_id) pic0 = Image.open(pic1_path) pic0.load() pic = pic0.convert("RGBA") except Exception: analyser._detection_cache[cache_key] = (now, False) return False pix = pic.load() width, height = pic.size 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 try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) except Exception: y_pianyi_val = 0 x = 536 * rx // 1080 if not (0 <= x < width): analyser._detection_cache[cache_key] = (now, False) return False base_ys = (883, 983, 1058) offsets = (0, y_pianyi_val, -y_pianyi_val) for base_y in base_ys: y0 = base_y * ry // 2400 for dy in offsets: y = y0 + dy if not (0 <= y < height): continue try: p = pix[x, y] if not (isinstance(p, tuple) and len(p) >= 3): continue r, g, b = int(p[0]), int(p[1]), int(p[2]) if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84: analyser._detection_cache[cache_key] = (now, True) return True except Exception: continue except Exception: pass # OCR fallback (lighter version of original implementation) try: try: min_interval = float(getattr(analyser, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0) except Exception: min_interval = 8.0 last = float(getattr(analyser, "_last_detail_ocr_check_ts", 0.0) or 0.0) if min_interval > 0 and (now - last) < min_interval: analyser._detection_cache[cache_key] = (now, False) return False analyser._last_detail_ocr_check_ts = now analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看") if not t_btn or not any(k in t_btn for k in keywords): t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "") if any(k in t_btn for k in keywords): analyser._detection_cache[cache_key] = (now, True) return True except Exception: pass analyser._detection_cache[cache_key] = (now, False) return False