Files
douyi_guaji_main/douyin/detection/detection_pkg/finder.py
T
CodexandClaude Opus 4.7 273adbb677 refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"截图获取+加载+失败处理"块到 finder_screenshot
将循环每次的截图相关逻辑(约 78 行)抽到 3 个独立 helper:
- capture_screenshot_for_loop:每次循环开始时获取截图(_shot_and_diagnose + 文件验证 + 兜底)
- load_screenshot_with_retry:读取截图,失败时重新截图后重试,返回 PIL Image 或 None
- handle_screenshot_load_failure:连续失败超阈值返回 "break";否则等待后返回 "continue"

finder.py: 371 → 320 行 (-51)
新增 finder_screenshot.py: 111 行

finder.py 跌破 350 行(1438 → 320,本会话累计削减 1118 行 = -78%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:18:35 +08:00

321 lines
11 KiB
Python

"""detection_pkg.finder - 找福袋图标主入口(1420 行)。
包含 check_have_fudai_with_ready_screenshot:在直播间内通过模板匹配
定位福袋图标,并把找到的位置写到 analyser 上供后续点击使用。
"""
from __future__ import annotations
# pylint: disable=no-member
import os
import time
from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
def check_have_fudai_with_ready_screenshot(
analyser: Any, screenshot_ready: bool = False
):
"""判定直播页面福袋的小图标是否存在(优化版,优先使用模块化查找器)。
如果启用了优化查找器(fudai_finder_optimized_enabled=True),则使用新的模块化查找器。
否则使用原版像素检测实现。
"""
# 检查是否启用优化查找器
try:
use_optimized = bool(getattr(analyser, "fudai_finder_optimized_enabled", False))
except Exception:
use_optimized = False
if use_optimized:
try:
from douyin.fudai.douyin_fudai_finder import (
check_have_fudai_with_ready_screenshot_optimized,
)
return check_have_fudai_with_ready_screenshot_optimized(
analyser, screenshot_ready
)
except ImportError:
# 优化版不可用,回退到原版
try:
analyser._log_kv(
"[找福袋图标]", "优化查找器不可用,使用原版", error="ImportError"
)
except Exception:
pass
except Exception as e:
# 优化版异常,回退到原版
try:
analyser._log_kv(
"[找福袋图标]",
"优化查找器异常,使用原版",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 原版实现(像素检测版)
func_start = time.time()
# 使用统一的截图路径配置
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()
attempt_count = 0 # 仅用于日志记录,不影响循环控制
# ===== 像素检测版(优先使用),不依赖 OpenCV =====
# 改为按时间控制循环,而不是按次数限制
try:
retry_delay_s = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
except Exception:
retry_delay_s = 0.6
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0)
except Exception:
max_wait_s = 5.0
if retry_delay_s < 0.1:
retry_delay_s = 0.1 # 最小间隔改为0.1秒
if max_wait_s < 0:
max_wait_s = 0.0
# 防止无限等待:最大等待时间限制为30秒
if max_wait_s > 30.0:
max_wait_s = 30.0
loop = 0
max_loops = int(max_wait_s / retry_delay_s) + 10 # 额外的循环次数保护
consecutive_failures = 0 # 连续失败计数
max_consecutive_failures = 5 # 最大连续失败次数
# 额外的时间限制保护,防止死循环
absolute_timeout = func_start + max(
max_wait_s * 1.5, 15
) # 最长15秒,但不超过 max_wait_s * 1.5
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
# 额外的循环次数保护:防止无限循环
if loop >= max_loops:
try:
analyser._log_kv(
"[找福袋图标] 警告",
"达到最大循环次数限制,提前退出",
max_loops=max_loops,
elapsed_s=round(time.time() - func_start, 2),
)
except Exception:
pass
break
# 每次循环都重新截图(除了第一次如果已经提供了截图)
from douyin.detection.detection_pkg.finder_screenshot import (
capture_screenshot_for_loop,
handle_screenshot_load_failure,
load_screenshot_with_retry,
)
capture_screenshot_for_loop(analyser, screenshot_ready, loop, pic1_path)
# 读取截图
pic = load_screenshot_with_retry(analyser, pic1_path)
# 如果截图读取失败,等待后继续下一次循环
if pic is None:
loop += 1
consecutive_failures += 1
action = handle_screenshot_load_failure(
analyser,
consecutive_failures,
max_consecutive_failures,
func_start,
max_wait_s,
retry_delay_s,
)
if action == "break":
break
continue
pic_new = pic.convert("RGBA")
width, height = pic_new.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
detected = False
detected_x = None
# 初始化扫描范围变量(用于日志记录)
scan_x_start = 41 * rx // 1080
scan_x_end = min(410 * rx // 1080, width)
scan_y = 403 * ry // 2400 + y_pianyi_val
# 获取最优搜索起始位置(使用历史记录或默认值)
try:
# 尝试获取上次找到的福袋位置(1080基准)
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if last_fudai_x > 0 and scan_x_start <= last_fudai_x <= scan_x_end:
optimal_x_scaled = last_fudai_x * rx // 1080
else:
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
optimal_x_scaled = 169 * rx // 1080
except Exception:
# 使用默认最优位置
optimal_x_scaled = 169 * rx // 1080
# 确保最优位置在搜索范围内
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
# 保存完整截图用于调试(检测前)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb_full = pic_new.convert("RGB")
# 保存完整截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="before_detect",
coords=(
(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4)
if scan_y >= 3
else None
),
extra_info={
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"y_offset": y_pianyi_val,
"loop": loop,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]", "福袋图标检测前保存完整截图", path=debug_path
)
except Exception:
pass
except Exception:
pass
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
from douyin.detection.detection_pkg.finder_numpy_scan import (
numpy_band_scan,
)
detected, detected_x = numpy_band_scan(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, optimal_x_scaled,
)
# numpy 未命中/不可用时回退到原始逐像素检查
from douyin.detection.detection_pkg.finder_pixel_scan import (
pixel_scan_fallback,
)
detected, detected_x = pixel_scan_fallback(
analyser, detected, detected_x, pic_new, rx, ry, y_pianyi_val,
)
if detected:
break # 找到后退出外层 while 循环
# 像素检测未命中时,使用模板匹配作为兜底
from douyin.detection.detection_pkg.finder_template_match import (
template_match_fallback,
)
detected, detected_x = template_match_fallback(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, loop,
)
if detected and detected_x is not None:
# 重置连续失败计数
consecutive_failures = 0
# 记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
from douyin.detection.detection_pkg.finder_loop_logging import (
log_fudai_found_and_metrics,
)
log_fudai_found_and_metrics(
analyser, detected_x, func_start, loop, ry, y_pianyi_val
)
return int(detected_x or 0)
loop += 1
consecutive_failures += 1
# 如果连续失败太多次,提前退出(避免无效循环)
if consecutive_failures >= max_consecutive_failures:
try:
elapsed_ms = int((time.time() - func_start) * 1000)
analyser._log_kv(
"[找福袋图标] 警告",
"连续检测失败次数过多,提前退出",
consecutive_failures=consecutive_failures,
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y,
)
except Exception:
pass
break
# 每轮记录一次轻量调试信息(每 3 次循环一次,减少日志量)
from douyin.detection.detection_pkg.finder_loop_logging import (
log_loop_progress,
)
log_loop_progress(
analyser, loop, func_start, pic_new, width, height,
scan_x_start, scan_x_end, scan_y, consecutive_failures,
)
# 检查是否还有剩余时间
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)
else:
# 时间已到,退出循环
break
# 像素检测未找到时,返回 False,并记录总耗时与循环次数
from douyin.detection.detection_pkg.finder_loop_logging import (
log_no_fudai_found,
)
log_no_fudai_found(analyser, func_start, loop, max_wait_s, retry_delay_s)
return False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
# 像素检测代码已删除,使用模板匹配替代
# 如需恢复像素检测,请参考 git 历史记录