Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4b6a8e5f0 | ||
|
|
30a66e955c | ||
|
|
9423ddbfef | ||
|
|
d24bc85902 | ||
|
|
a391c21f47 | ||
|
|
27110446c2 | ||
|
|
3192c8b5c7 | ||
|
|
02e685ba20 | ||
|
|
f46f9dc23e | ||
|
|
daddabd8cf | ||
|
|
c2654d60aa | ||
|
|
4cb5daa79e | ||
|
|
feaf555657 | ||
|
|
89f001e5a4 | ||
|
|
e9e8e322c6 | ||
|
|
b8a35656a0 | ||
|
|
f075f94b31 | ||
|
|
df8424b706 | ||
|
|
e567948ec9 | ||
|
|
f3d4621686 | ||
|
|
cc164a192f | ||
|
|
be95d9c279 | ||
|
|
1b4dc477fd | ||
|
|
47d31d34fd | ||
|
|
9dee41b976 | ||
|
|
cdcabb665d | ||
|
|
9700813a33 | ||
|
|
c75635f519 | ||
|
|
25c7a0440d | ||
|
|
03e509ac25 | ||
|
|
28f91b2aaf | ||
|
|
970e9043cb | ||
|
|
c6a4d5fb99 | ||
|
|
a317b38b25 | ||
|
|
3473e2bd5e | ||
|
|
41fc4ecbe0 | ||
|
|
e6da24c2a6 | ||
|
|
6cf3ce9a72 | ||
|
|
992db1e161 | ||
|
|
1604ad1904 | ||
|
|
878a4c2fd9 | ||
|
|
9c823f4874 | ||
|
|
c5f2bbee9c | ||
|
|
17f1977a65 | ||
|
|
2d971ca7d8 | ||
|
|
b6cd3ac8a3 | ||
|
|
18c6f7b025 | ||
|
|
c7c6c51d20 | ||
|
|
189d24255d | ||
|
|
20e48d6a51 | ||
|
|
053ffa3469 | ||
|
|
9c1540b3ea | ||
|
|
0bdc378252 |
No files matched your search
+79
-3116
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,9 @@ from .fudai_popup_handler import PopupHandlerMixin
|
||||
from .fudai_lottery_result import LotteryResultMixin
|
||||
from .fudai_room_utils import RoomUtilsMixin
|
||||
from .fudai_main_logic import MainLogicMixin
|
||||
from . import fudai_run_blocks
|
||||
from . import fudai_detail_blocks
|
||||
from . import fudai_image_helpers
|
||||
|
||||
__all__ = [
|
||||
"BaseFudaiMixin",
|
||||
@@ -20,4 +23,7 @@ __all__ = [
|
||||
"LotteryResultMixin",
|
||||
"RoomUtilsMixin",
|
||||
"MainLogicMixin",
|
||||
"fudai_run_blocks",
|
||||
"fudai_detail_blocks",
|
||||
"fudai_image_helpers",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,279 @@
|
||||
"""douyin_fudai 实例方法的辅助函数(图片/截图等)。
|
||||
|
||||
把 fudai_analyse 里相对独立的图片处理逻辑抽出来,便于单测与复用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image # type: ignore[import]
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger("douyin.core.fudai_modules.fudai_image_helpers")
|
||||
|
||||
|
||||
def _read_screenshot_with_validation(
|
||||
analyser: Any, pic_path: str, max_attempts: int = 6
|
||||
) -> Optional[bytes]:
|
||||
"""以原子方式读取截图字节,最多重试 max_attempts 次。
|
||||
|
||||
每次读取后用 PNG 头/IEND 尾 + PIL.verify 做基本校验,避免读到半写入文件。
|
||||
返回完整字节,或 None(多次重试仍未读到完整文件)。
|
||||
"""
|
||||
data: Optional[bytes] = None
|
||||
for _attempt in range(max_attempts):
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(pic_path):
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
sz = os.path.getsize(pic_path)
|
||||
if sz < 1024:
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
with open(pic_path, "rb") as f:
|
||||
data = f.read()
|
||||
if not data or not data.startswith(b"\x89PNG"):
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
if b"IEND" not in data[-512:]:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
try:
|
||||
img_test = Image.open(io.BytesIO(data))
|
||||
img_test.verify()
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
break
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
return data
|
||||
|
||||
|
||||
def _open_image_or_retry(
|
||||
analyser: Any, data: bytes, pic_path: str
|
||||
) -> Optional[Image.Image]:
|
||||
"""先用 data 解析图片;失败则尝试重新读取一次 pic_path 再解析。"""
|
||||
from PIL import UnidentifiedImageError # type: ignore[import]
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
return img
|
||||
except UnidentifiedImageError:
|
||||
return None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
with open(pic_path, "rb") as f:
|
||||
data2 = f.read()
|
||||
if (
|
||||
data2
|
||||
and data2.startswith(b"\x89PNG")
|
||||
and b"IEND" in data2[-512:]
|
||||
):
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data2))
|
||||
img.load()
|
||||
return img
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def capture_roi_screenshot(
|
||||
analyser: Any,
|
||||
label: str,
|
||||
sx: int,
|
||||
sy: int,
|
||||
size: int,
|
||||
screenshot_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""捕获以 (sx,sy) 为中心、边长为 size 的 ROI 截图,保存到 ``pic/`` 并返回路径。
|
||||
|
||||
返回 ROI 图片路径(绝对路径),失败返回空字符串。
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
if screenshot_path is None:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
else:
|
||||
pic_path = screenshot_path
|
||||
if not os.path.exists(pic_path):
|
||||
return ""
|
||||
|
||||
half = int(size // 2)
|
||||
left = int(max(0, sx - half))
|
||||
top = int(max(0, sy - half))
|
||||
right = int(sx + half)
|
||||
bottom = int(sy + half)
|
||||
|
||||
data = _read_screenshot_with_validation(analyser, pic_path)
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
img = _open_image_or_retry(analyser, data, pic_path)
|
||||
if img is None:
|
||||
return ""
|
||||
|
||||
w, h = img.size
|
||||
left = max(0, min(left, w - 1))
|
||||
top = max(0, min(top, h - 1))
|
||||
right = max(1, min(right, w))
|
||||
bottom = max(1, min(bottom, h))
|
||||
|
||||
roi = img.crop((left, top, right, bottom))
|
||||
out_dir = path_config.get_pic_dir()
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
fname = (
|
||||
f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png"
|
||||
)
|
||||
out_path = os.path.join(out_dir, fname)
|
||||
roi.save(out_path)
|
||||
return out_path
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"截图",
|
||||
"_capture_roi_screenshot 失败",
|
||||
label=label,
|
||||
sx=sx,
|
||||
sy=sy,
|
||||
size=size,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def _correlation_score(a_flat, b_flat) -> float:
|
||||
"""计算两个等长 1D 数组的归一化相关系数(去均值后点积/范数乘积)。"""
|
||||
import numpy as np
|
||||
|
||||
a = a_flat - a_flat.mean()
|
||||
b = b_flat - b_flat.mean()
|
||||
denom = np.linalg.norm(a) * np.linalg.norm(b)
|
||||
if denom <= 1e-6:
|
||||
return -1.0
|
||||
return float(np.dot(a, b) / denom)
|
||||
|
||||
|
||||
def _sliding_search_best_score(roi_gray, tpl_gray) -> float:
|
||||
"""以 step ≈ 模板边长 // 6 的步长在 ROI 中滑动搜索最佳相关系数。"""
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
best = -1.0
|
||||
step_y = max(1, th // 6)
|
||||
step_x = max(1, tw // 6)
|
||||
for y in range(0, ih - th + 1, step_y):
|
||||
for x in range(0, iw - tw + 1, step_x):
|
||||
window = roi_gray[y : y + th, x : x + tw]
|
||||
score = _correlation_score(window.flatten(), tpl_gray.flatten())
|
||||
if score > best:
|
||||
best = score
|
||||
return best
|
||||
|
||||
|
||||
def match_icon_template(
|
||||
analyser: Any,
|
||||
roi_path: str,
|
||||
template_path: str,
|
||||
threshold: Optional[float] = None,
|
||||
):
|
||||
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
|
||||
|
||||
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
|
||||
threshold 不传时使用 analyser.yanghao_icon_match_threshold(默认 0.70)。
|
||||
出错或文件缺失返回 (False, 0.0)。
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
if not roi_path or not os.path.exists(roi_path):
|
||||
return False, 0.0
|
||||
if not template_path or not os.path.exists(template_path):
|
||||
return False, 0.0
|
||||
|
||||
roi_img = Image.open(roi_path).convert("RGB")
|
||||
tpl_img = Image.open(template_path).convert("RGB")
|
||||
|
||||
rw, rh = roi_img.size
|
||||
tw, th = tpl_img.size
|
||||
if tw > rw or th > rh:
|
||||
scale = min(rw / tw, rh / th, 1.0)
|
||||
new_w = max(1, int(tw * scale))
|
||||
new_h = max(1, int(th * scale))
|
||||
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
tw, th = tpl_img.size
|
||||
|
||||
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
|
||||
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
|
||||
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
)
|
||||
|
||||
# 同尺寸:直接计算
|
||||
if roi_gray.shape == tpl_gray.shape:
|
||||
score = _correlation_score(roi_gray.flatten(), tpl_gray.flatten())
|
||||
return bool(score >= used_thr), float(score)
|
||||
|
||||
# 模板小于 ROI:先尝试中心裁剪比对,分数足够好直接返回
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
if ih >= th and iw >= tw:
|
||||
cy = ih // 2 - th // 2
|
||||
cx = iw // 2 - tw // 2
|
||||
cy = max(0, min(cy, ih - th))
|
||||
cx = max(0, min(cx, iw - tw))
|
||||
window = roi_gray[cy : cy + th, cx : cx + tw]
|
||||
score = _correlation_score(window.flatten(), tpl_gray.flatten())
|
||||
if score >= 0.55:
|
||||
return bool(score >= used_thr), float(score)
|
||||
|
||||
# 退回到滑动搜索
|
||||
best = _sliding_search_best_score(roi_gray, tpl_gray)
|
||||
if best < -0.5:
|
||||
return False, 0.0
|
||||
return bool(best >= used_thr), float(best)
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
"_match_icon_template 异常",
|
||||
roi_path=roi_path,
|
||||
template_path=template_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,547 @@
|
||||
"""finder.py 的辅助函数:模板匹配兜底。
|
||||
|
||||
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行)
|
||||
抽出来,便于独立测试与维护。
|
||||
|
||||
同时包含 numpy 加速像素扫描 + 逐像素扫描兜底的辅助函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def numpy_pixel_scan(
|
||||
analyser: Any,
|
||||
pic_new: Any, # PIL.Image (RGBA)
|
||||
rx: int,
|
||||
ry: int,
|
||||
width: int,
|
||||
height: int,
|
||||
y_pianyi_val: int,
|
||||
optimal_x_scaled: int,
|
||||
) -> tuple[bool, Optional[int]]:
|
||||
"""先尝试 numpy 加速扫描水平带(性能优化:批量处理)。
|
||||
|
||||
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
|
||||
"""
|
||||
try:
|
||||
import numpy as _np
|
||||
|
||||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 157 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
|
||||
if not (x1 < x2 and y_top < y_bottom):
|
||||
return False, None
|
||||
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr = _np.array(roi)
|
||||
if arr.size == 0:
|
||||
return False, None
|
||||
|
||||
r = arr[:, :, 0]
|
||||
g = arr[:, :, 1]
|
||||
b = arr[:, :, 2]
|
||||
mask_center = (
|
||||
(r >= 190) & (r <= 206)
|
||||
& (g >= 173) & (g <= 196)
|
||||
& (b >= 234) & (b <= 250)
|
||||
)
|
||||
cols = _np.sum(mask_center, axis=0)
|
||||
valid_cols = cols >= 2
|
||||
if not valid_cols.any():
|
||||
return False, None
|
||||
|
||||
roi_width = x2 - x1
|
||||
optimal_col = max(0, min(optimal_x_scaled - x1, roi_width - 1))
|
||||
|
||||
# 从最优位置开始,向左右两侧交替搜索
|
||||
found_col = None
|
||||
search_range = max(optimal_col, roi_width - optimal_col)
|
||||
|
||||
if valid_cols[optimal_col]:
|
||||
found_col = optimal_col
|
||||
else:
|
||||
for offset in range(1, search_range + 1):
|
||||
right_col = optimal_col + offset
|
||||
if right_col < roi_width and valid_cols[right_col]:
|
||||
found_col = right_col
|
||||
break
|
||||
left_col = optimal_col - offset
|
||||
if left_col >= 0 and valid_cols[left_col]:
|
||||
found_col = left_col
|
||||
break
|
||||
|
||||
if found_col is None:
|
||||
found_col = int(_np.argmax(valid_cols))
|
||||
|
||||
col_idx = found_col
|
||||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||||
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
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="detected",
|
||||
coords=(x1, y_top, x2, y_bottom),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": x1 + col_idx,
|
||||
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True, detected_x
|
||||
except (ImportError, ValueError, IndexError, AttributeError):
|
||||
return False, None
|
||||
|
||||
|
||||
def _is_target_pixel(px: Any) -> bool:
|
||||
"""检查像素是否在目标颜色范围内。"""
|
||||
if not (isinstance(px, tuple) and len(px) >= 3):
|
||||
return False
|
||||
return (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
)
|
||||
|
||||
|
||||
def per_pixel_scan_fallback(
|
||||
analyser: Any,
|
||||
pic_new: Any,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> tuple[bool, Optional[int]]:
|
||||
"""numpy 不可用或未命中时的逐像素扫描兜底。"""
|
||||
try:
|
||||
pix = pic_new.load()
|
||||
pic_width, pic_height = pic_new.size
|
||||
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, pic_width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
try:
|
||||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||||
if (
|
||||
last_fudai_x > 0
|
||||
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
|
||||
):
|
||||
optimal_x_scaled = last_fudai_x * rx // 1080
|
||||
else:
|
||||
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))
|
||||
|
||||
if not (0 <= scan_y < pic_height):
|
||||
return False, None
|
||||
|
||||
for offset_y in [0, -1, 1, -2, 2]:
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < pic_height):
|
||||
continue
|
||||
|
||||
found_x = _scan_one_row(
|
||||
pix, check_y, scan_x_start, scan_x_end, optimal_x_scaled
|
||||
)
|
||||
|
||||
if found_x is not None:
|
||||
detected_x = int(found_x * 1080.0 / max(1, rx))
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_save_per_pixel_success(
|
||||
analyser, pic_new, scan_x_start, scan_y, scan_x_end,
|
||||
pic_height, detected_x, found_x, rx, ry,
|
||||
)
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
return True, detected_x
|
||||
return False, None
|
||||
except Exception:
|
||||
return False, None
|
||||
|
||||
|
||||
def _scan_one_row(
|
||||
pix: Any,
|
||||
check_y: int,
|
||||
scan_x_start: int,
|
||||
scan_x_end: int,
|
||||
optimal_x_scaled: int,
|
||||
) -> Optional[int]:
|
||||
"""在单行扫描目标像素:先查最优位置,然后左右交替,最后从左到右兜底。"""
|
||||
# 先检查最优位置
|
||||
try:
|
||||
if _is_target_pixel(pix[optimal_x_scaled, check_y]):
|
||||
return optimal_x_scaled
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# 向左右两侧交替搜索
|
||||
search_range = max(
|
||||
optimal_x_scaled - scan_x_start,
|
||||
scan_x_end - optimal_x_scaled,
|
||||
)
|
||||
for offset in range(1, search_range + 1):
|
||||
right_x = optimal_x_scaled + offset
|
||||
if right_x < scan_x_end:
|
||||
try:
|
||||
if _is_target_pixel(pix[right_x, check_y]):
|
||||
return right_x
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
left_x = optimal_x_scaled - offset
|
||||
if left_x >= scan_x_start:
|
||||
try:
|
||||
if _is_target_pixel(pix[left_x, check_y]):
|
||||
return left_x
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# 兜底:从左到右
|
||||
for x_scaled in range(scan_x_start, scan_x_end):
|
||||
try:
|
||||
if _is_target_pixel(pix[x_scaled, check_y]):
|
||||
return x_scaled
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _save_per_pixel_success(
|
||||
analyser: Any, pic_new: Any, scan_x_start: int, scan_y: int,
|
||||
scan_x_end: int, pic_height: int, detected_x: int, found_x: int,
|
||||
rx: int, ry: int,
|
||||
) -> None:
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))
|
||||
).convert("RGB")
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi, operation_type="pixel_detect",
|
||||
)
|
||||
|
||||
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="detected",
|
||||
coords=(
|
||||
scan_x_start, max(0, scan_y - 3),
|
||||
scan_x_end, min(pic_height, scan_y + 4),
|
||||
),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": found_x,
|
||||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def template_match_fallback(
|
||||
analyser: Any,
|
||||
pic_new: Any, # PIL.Image (RGBA)
|
||||
rx: int,
|
||||
ry: int,
|
||||
width: int,
|
||||
height: int,
|
||||
y_pianyi_val: int,
|
||||
loop: int,
|
||||
) -> tuple[bool, Optional[int]]:
|
||||
"""像素检测未命中时使用 OpenCV 模板匹配作为兜底。
|
||||
|
||||
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
|
||||
"""
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 获取模板路径
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
template_path = path_config.get_assets_dir() + "/fudai.png"
|
||||
except Exception:
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
template_path = os.path.join(base_dir, "assets", "fudai.png")
|
||||
|
||||
if not os.path.exists(template_path):
|
||||
return False, None
|
||||
|
||||
try:
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is None:
|
||||
return False, None
|
||||
|
||||
pic_rgb = pic_new.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
|
||||
# 搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
|
||||
x1 = max(0, 156 * rx // 1080)
|
||||
x2 = min(width, 269 * rx // 1080)
|
||||
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
|
||||
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
|
||||
|
||||
if not (x1 < x2 and y_top < y_bottom):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-坐标无效",
|
||||
loop=loop,
|
||||
x1=x1,
|
||||
x2=x2,
|
||||
y_top=y_top,
|
||||
y_bottom=y_bottom,
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2]
|
||||
if search_roi.size <= 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-搜索区域为空",
|
||||
loop=loop,
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = search_roi.shape[:2]
|
||||
|
||||
# 保存搜索区域截图到 last_match.png(仅用于调试)
|
||||
_save_last_match_debug(analyser, search_roi, loop, x1, x2, y_top, y_bottom, rw, rh)
|
||||
|
||||
# 如果模板太大,缩小模板
|
||||
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]
|
||||
|
||||
if not (th <= rh and tw <= rw):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-尺寸不匹配",
|
||||
loop=loop,
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
# 执行模板匹配
|
||||
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
|
||||
_save_template_match_attempt_log(analyser, search_roi)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配兜底",
|
||||
loop=loop,
|
||||
匹配分数=round(max_val, 4),
|
||||
阈值=template_threshold,
|
||||
是否通过=bool(max_val >= template_threshold),
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val < template_threshold:
|
||||
return False, None
|
||||
|
||||
_save_template_match_success(analyser, search_roi)
|
||||
|
||||
# 命中:计算 1080 基准 x 坐标
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx))
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
return True, detected_x
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配异常",
|
||||
loop=loop,
|
||||
错误类型=type(e).__name__,
|
||||
错误信息=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
|
||||
def _save_last_match_debug(
|
||||
analyser: Any, search_roi: Any, loop: int, x1: int, x2: int,
|
||||
y_top: int, y_bottom: int, rw: int, rh: int,
|
||||
) -> None:
|
||||
try:
|
||||
import cv2
|
||||
|
||||
base_dir = os.path.dirname(os.path.abspath(__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)
|
||||
last_match_path = os.path.join(match_dir, "last_match.png")
|
||||
save_success = cv2.imwrite(last_match_path, search_roi)
|
||||
if save_success:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 已保存搜索区域截图",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图失败",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as save_err:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图异常",
|
||||
loop=loop,
|
||||
错误类型=type(save_err).__name__,
|
||||
错误信息=str(save_err),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _save_template_match_attempt_log(analyser: Any, search_roi: Any) -> None:
|
||||
"""保存"实时尝试"截图(双截图记录用)。"""
|
||||
try:
|
||||
import cv2
|
||||
from PIL import Image as PILImage
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _save_template_match_success(analyser: Any, search_roi: Any) -> None:
|
||||
"""命中时保存成功识别存档截图。"""
|
||||
try:
|
||||
import cv2
|
||||
from PIL import Image as PILImage
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+71
-780
@@ -14,6 +14,15 @@ from douyin.fudai.core.coords import (
|
||||
STAGE_RED_PACKET_OCR,
|
||||
COUPON_PARTICIPATE_BUTTON_ALT,
|
||||
)
|
||||
from douyin.stage.douyin_stage_helpers import (
|
||||
detect_lottery_result_popup,
|
||||
detect_recommend_follow_live_tabs,
|
||||
detect_redpacket_ocr_recheck_outside_live,
|
||||
detect_shopping_redpacket_popup,
|
||||
detect_suspicious_popup_via_ocr,
|
||||
log_pixel_detection_details,
|
||||
summarize_pixel_state,
|
||||
)
|
||||
|
||||
# 模块级 logger:原代码用 print 输出阶段诊断起始信息,统一走 logging。
|
||||
_LOGGER = logging.getLogger("douyin.stage.douyin_stage")
|
||||
@@ -208,114 +217,9 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
)
|
||||
|
||||
# 记录每个检测步骤的详细信息
|
||||
for key, detail in pixel_details.items():
|
||||
step_name_map = {
|
||||
"has_coupon_bg": "优惠券背景",
|
||||
"has_redpacket_bg": "购物红包背景",
|
||||
"has_lucky_draw_result": "抽奖结果弹窗",
|
||||
"has_attend_button_red": "参与按钮红色区域",
|
||||
"has_fansclub_join_red": "粉丝团加入红色区域",
|
||||
"has_fudai_detail": "福袋详情页",
|
||||
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
|
||||
}
|
||||
step_name = step_name_map.get(key, key)
|
||||
detected = detail.get("detected", False)
|
||||
method = detail.get("method", "unknown")
|
||||
log_pixel_detection_details(pixel_details, analyser, _log)
|
||||
|
||||
log_fields = {
|
||||
"步骤": step_name,
|
||||
"检测结果": "命中" if detected else "未命中",
|
||||
"检测方法": method,
|
||||
}
|
||||
|
||||
# 添加耗时信息
|
||||
if "elapsed_ms" in detail:
|
||||
log_fields["耗时(ms)"] = detail["elapsed_ms"]
|
||||
|
||||
# 添加分数信息
|
||||
if "template_score" in detail and detail["template_score"] is not None:
|
||||
log_fields["分数"] = round(detail["template_score"], 4)
|
||||
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
|
||||
# 对于像素检测,添加置信度信息
|
||||
if "confidence" in detail and detail["confidence"] is not None:
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["confidence"], 4)
|
||||
log_fields["置信度"] = round(detail["confidence"], 4)
|
||||
# 如果是三部分识别,显示平均分和区域结果
|
||||
if "avg_score" in detail and detail["avg_score"] is not None:
|
||||
log_fields["平均分"] = round(detail["avg_score"], 4)
|
||||
if "detected_parts" in detail and detail["detected_parts"]:
|
||||
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
|
||||
if "best_region" in detail and detail["best_region"]:
|
||||
log_fields["最佳区域"] = detail["best_region"]
|
||||
if "region_results" in detail and detail["region_results"]:
|
||||
region_scores = detail["region_results"]
|
||||
if isinstance(region_scores, dict):
|
||||
log_fields["区域分数"] = (
|
||||
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
|
||||
)
|
||||
# 对于像素检测,red_ratio也作为分数显示
|
||||
if "red_ratio" in detail and detail["red_ratio"] is not None:
|
||||
log_fields["红色比例"] = round(detail["red_ratio"], 4)
|
||||
# 如果还没有分数,将red_ratio作为分数显示
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["red_ratio"], 4)
|
||||
# 显示阈值(无论是否为None都显示,方便调试)
|
||||
if "effective_threshold" in detail:
|
||||
threshold_val = detail["effective_threshold"]
|
||||
if threshold_val is not None:
|
||||
log_fields["阈值"] = round(threshold_val, 4)
|
||||
else:
|
||||
log_fields["阈值"] = "未设置"
|
||||
# 对于福袋详情页,额外显示配置的阈值(用于调试)
|
||||
if key == "has_fudai_detail":
|
||||
# 显示任务数量信息(无论是否为None都显示,便于调试)
|
||||
if "task_count" in detail:
|
||||
task_count_val = detail["task_count"]
|
||||
log_fields["任务数量"] = task_count_val
|
||||
# 如果任务数量存在但检测结果为False,记录警告
|
||||
if (
|
||||
task_count_val is not None
|
||||
and task_count_val > 0
|
||||
and not detected
|
||||
):
|
||||
try:
|
||||
_log( # type: ignore[misc]
|
||||
"警告:检测到任务数量但 has_fudai_detail 为 False",
|
||||
任务数量=task_count_val,
|
||||
detected=detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log_fields["任务数量"] = "未获取"
|
||||
try:
|
||||
configured_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
log_fields["配置阈值"] = round(configured_threshold, 4)
|
||||
except Exception:
|
||||
pass
|
||||
if "reason" in detail:
|
||||
log_fields["原因"] = detail["reason"]
|
||||
if "error" in detail:
|
||||
log_fields["错误"] = detail["error"]
|
||||
|
||||
_log(f"并行检测-{step_name}", **log_fields)
|
||||
|
||||
_log(
|
||||
"像素状态(并行检测完成)",
|
||||
耗时毫秒=pixel_detection_elapsed,
|
||||
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
|
||||
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
|
||||
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
|
||||
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
|
||||
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
|
||||
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
|
||||
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
|
||||
)
|
||||
summarize_pixel_state(pixel_state, pixel_detection_elapsed, _log)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
@@ -338,429 +242,37 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
|
||||
|
||||
# 购物红包像素命中:不在直播间也必须进行OCR复查
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
step_redpacket_ocr_start = time.time()
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
try:
|
||||
redpacket_detail = (
|
||||
pixel_details.get("has_redpacket_bg", {})
|
||||
if isinstance(pixel_details, dict)
|
||||
else {}
|
||||
)
|
||||
red_ratio = redpacket_detail.get("red_ratio")
|
||||
red_threshold = redpacket_detail.get("effective_threshold")
|
||||
except Exception:
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-开始",
|
||||
说明="不在直播间也执行红包OCR复查",
|
||||
红色比例=(
|
||||
round(float(red_ratio), 4) if red_ratio is not None else None
|
||||
),
|
||||
阈值=(
|
||||
round(float(red_threshold), 4)
|
||||
if red_threshold is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(
|
||||
*SHOPPING_REDPACKET_AREA,
|
||||
"",
|
||||
"診斷購物紅包-非直播间复查",
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp0 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result = analyser.operation.analyse_pic_word(
|
||||
name_rp0, 0, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result
|
||||
else:
|
||||
redpacket_text = str(ocr_result or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if enable_ocr_mode1 and (
|
||||
not redpacket_text
|
||||
or not any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
):
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start_1 = time.time()
|
||||
name_rp1 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result_1 = analyser.operation.analyse_pic_word(
|
||||
name_rp1, 1, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result_1, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result_1
|
||||
else:
|
||||
redpacket_text = str(ocr_result_1 or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=(
|
||||
redpacket_text[:50] if redpacket_text else ""
|
||||
),
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# 检查关键词匹配或置信度阈值
|
||||
has_keyword_match = redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
has_high_confidence = (
|
||||
ocr_confidence_info
|
||||
and ocr_confidence_info.get("max_confidence", 0)
|
||||
>= analyser.shopping_redpacket_ocr_confidence_threshold
|
||||
)
|
||||
|
||||
if has_keyword_match or has_high_confidence:
|
||||
redpacket_verified = True
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-命中",
|
||||
关键词匹配=has_keyword_match,
|
||||
高置信度匹配=has_high_confidence,
|
||||
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-非直播间复查)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(不在直播间)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
|
||||
else:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
|
||||
matched, stage, reason = detect_redpacket_ocr_recheck_outside_live(
|
||||
analyser,
|
||||
pixel_state,
|
||||
pixel_details,
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
diag_start,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
_log,
|
||||
_log_summary,
|
||||
)
|
||||
if matched:
|
||||
return stage, reason
|
||||
|
||||
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
|
||||
step_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
|
||||
matched, stage, reason = detect_recommend_follow_live_tabs(
|
||||
analyser,
|
||||
RECOMMEND_TAB,
|
||||
FOLLOW_TAB,
|
||||
LIVE_LIST_TAB,
|
||||
diag_start,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
_log,
|
||||
_log_summary,
|
||||
_log_separator,
|
||||
)
|
||||
t_recommend = ""
|
||||
t_follow = ""
|
||||
t_list = ""
|
||||
try:
|
||||
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
|
||||
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and (
|
||||
not t_recommend
|
||||
or (
|
||||
"推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
and "直播" not in t_recommend
|
||||
)
|
||||
)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
elapsed_recommend = (time.time() - step_start) * 1000
|
||||
|
||||
# 如果识别到"推荐",直接返回推荐页面
|
||||
if "推荐" in t_recommend:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
seen_text = t_recommend[:50] if t_recommend else "-"
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-命中推荐",
|
||||
耗时毫秒=elapsed_recommend,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 如果识别到"关注"但没有"推荐",可能是关注列表
|
||||
if "关注" in t_recommend and "推荐" not in t_recommend:
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
|
||||
精确区域="(658,147)-(765,194)",
|
||||
)
|
||||
step_start_follow = time.time()
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("关注" not in t_follow)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_follow = (time.time() - step_start_follow) * 1000
|
||||
if "关注" in t_follow:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
follow_text = t_follow[:50] if t_follow else "-"
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-命中",
|
||||
耗时毫秒=elapsed_follow,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(
|
||||
t_follow or ""
|
||||
).strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:FOLLOW_LIST(关注列表)")
|
||||
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 如果识别到"正在直播"标签,判定为直播列表
|
||||
if "正在直播" in t_recommend or (
|
||||
"直播" in t_recommend
|
||||
and "推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
):
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
|
||||
精确区域="(650,145)-(800,195)",
|
||||
)
|
||||
step_start_list = time.time()
|
||||
try:
|
||||
ocr_start = time.time() # 初始化ocr_start
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
# else分支不需要,因为ocr_start已经在上面初始化了
|
||||
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("正在直播" not in t_list)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(
|
||||
analyser.operation.analyse_pic_word(namel1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_list = (time.time() - step_start_list) * 1000
|
||||
if "正在直播" in t_list:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
list_text = t_list[:50] if t_list else "-"
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-命中",
|
||||
耗时毫秒=elapsed_list,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:LIVE_LIST(直播列表)")
|
||||
return "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
|
||||
耗时毫秒=elapsed_total,
|
||||
阈值毫秒=max_step_time * 1000,
|
||||
)
|
||||
else:
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
|
||||
耗时毫秒=elapsed_total,
|
||||
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
|
||||
)
|
||||
except Exception as e:
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
|
||||
耗时毫秒=elapsed_total,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
# 步骤3结束计时
|
||||
step3_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
|
||||
if matched:
|
||||
return stage, reason
|
||||
|
||||
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
@@ -782,109 +294,27 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
|
||||
# 优先级1:抽奖结果弹窗(像素检测 + 按钮OCR确认)
|
||||
if pixel_state.get("has_lucky_draw_result", False):
|
||||
step1_start = time.time()
|
||||
_log_separator("步骤1:检测抽奖结果弹窗(简化)")
|
||||
try:
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
|
||||
if detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(抽奖结果弹窗)",
|
||||
阶段="FUDai_RESULT",
|
||||
原因="像素检测+按钮OCR确认",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:FUDai_RESULT(抽奖结果弹窗)")
|
||||
return "FUDai_RESULT", "像素检测+按钮OCR确认"
|
||||
else:
|
||||
_log("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
|
||||
except Exception as e:
|
||||
_log(
|
||||
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
# 步骤1结束计时
|
||||
step1_elapsed = (time.time() - step1_start) * 1000
|
||||
_log("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
|
||||
matched, stage, reason = detect_lottery_result_popup(
|
||||
analyser, diag_start, _log, _log_summary, _log_separator
|
||||
)
|
||||
if matched:
|
||||
return stage, reason
|
||||
|
||||
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
_log_separator("步骤1.5:检测购物红包弹窗")
|
||||
step_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到购物红包背景",
|
||||
matched, stage, reason = detect_shopping_redpacket_popup(
|
||||
analyser,
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
diag_start,
|
||||
max_diag_time,
|
||||
max_step_time,
|
||||
preprocess_for_ocr,
|
||||
_log,
|
||||
_log_summary,
|
||||
_log_separator,
|
||||
)
|
||||
|
||||
redpacket_detected = False
|
||||
try:
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
# 检查是否包含购物红包关键词
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_detected = True
|
||||
else:
|
||||
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
|
||||
说明="OCR未匹配,不判定为购物红包弹窗",
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
|
||||
_log(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
|
||||
说明="需要OCR确认才能判定",
|
||||
)
|
||||
|
||||
if redpacket_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="检测到购物红包弹窗",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
|
||||
|
||||
# 步骤1.5结束计时
|
||||
step15_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
_log("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
|
||||
if matched:
|
||||
return stage, reason
|
||||
|
||||
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
|
||||
step1_fudai_start = time.time()
|
||||
@@ -1202,160 +632,21 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
|
||||
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
|
||||
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
|
||||
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
|
||||
has_suspicious_popup_pixel = pixel_state.get(
|
||||
"has_coupon_bg", False
|
||||
) or pixel_state.get("has_redpacket_bg", False)
|
||||
|
||||
if has_suspicious_popup_pixel:
|
||||
step_ocr_verify_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
|
||||
)
|
||||
|
||||
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
|
||||
if pixel_state.get("has_coupon_bg", False):
|
||||
coupon_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
# 如果启用模式1,并行执行两个OCR模式
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part0, 0
|
||||
)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part1, 1
|
||||
)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(
|
||||
analyser.operation.analyse_pic_word(pname, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
coupon_verified = True
|
||||
except Exception as e:
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券异常",
|
||||
耗时毫秒=coupon_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if coupon_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
return "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 检测购物红包弹窗
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_verified = True
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-购物红包异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
|
||||
|
||||
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
|
||||
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-未匹配到弹窗",
|
||||
耗时毫秒=ocr_verify_elapsed,
|
||||
说明="OCR确认后未匹配,判定为直播间背景颜色",
|
||||
)
|
||||
|
||||
# 步骤3结束计时(OCR确认弹窗)
|
||||
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
|
||||
matched, stage, reason = detect_suspicious_popup_via_ocr(
|
||||
analyser,
|
||||
pixel_state,
|
||||
COUPON_PARTICIPATE_BUTTON_ALT,
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
diag_start,
|
||||
max_diag_time,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
_log,
|
||||
_log_summary,
|
||||
)
|
||||
if matched:
|
||||
return stage, reason
|
||||
|
||||
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
|
||||
if in_live_room:
|
||||
|
||||
@@ -0,0 +1,930 @@
|
||||
"""douyin_stage.py 内部用到的辅助函数。
|
||||
|
||||
把 diagnose_stage_from_current_screen 中纯日志格式化、纯映射查询的子块抽出来:
|
||||
- log_pixel_detection_details:把 pixel_details 里每个 key 的检测详情格式化并写入日志
|
||||
- summarize_pixel_state:把 pixel_state 摘要写入日志(一次调用替代 9 行字段构造)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
|
||||
_STEP_NAME_MAP: Dict[str, str] = {
|
||||
"has_coupon_bg": "优惠券背景",
|
||||
"has_redpacket_bg": "购物红包背景",
|
||||
"has_lucky_draw_result": "抽奖结果弹窗",
|
||||
"has_attend_button_red": "参与按钮红色区域",
|
||||
"has_fansclub_join_red": "粉丝团加入红色区域",
|
||||
"has_fudai_detail": "福袋详情页",
|
||||
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
|
||||
}
|
||||
|
||||
|
||||
def _format_detail_log_fields(key: str, detail: Dict[str, Any], analyser: Any) -> Dict[str, Any]:
|
||||
"""把单个 detail 字典格式化成日志字段。"""
|
||||
step_name = _STEP_NAME_MAP.get(key, key)
|
||||
detected = detail.get("detected", False)
|
||||
method = detail.get("method", "unknown")
|
||||
|
||||
log_fields: Dict[str, Any] = {
|
||||
"步骤": step_name,
|
||||
"检测结果": "命中" if detected else "未命中",
|
||||
"检测方法": method,
|
||||
}
|
||||
|
||||
if "elapsed_ms" in detail:
|
||||
log_fields["耗时(ms)"] = detail["elapsed_ms"]
|
||||
|
||||
if "template_score" in detail and detail["template_score"] is not None:
|
||||
log_fields["分数"] = round(detail["template_score"], 4)
|
||||
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
|
||||
if "confidence" in detail and detail["confidence"] is not None:
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["confidence"], 4)
|
||||
log_fields["置信度"] = round(detail["confidence"], 4)
|
||||
if "avg_score" in detail and detail["avg_score"] is not None:
|
||||
log_fields["平均分"] = round(detail["avg_score"], 4)
|
||||
if "detected_parts" in detail and detail["detected_parts"]:
|
||||
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
|
||||
if "best_region" in detail and detail["best_region"]:
|
||||
log_fields["最佳区域"] = detail["best_region"]
|
||||
if "region_results" in detail and detail["region_results"]:
|
||||
region_scores = detail["region_results"]
|
||||
if isinstance(region_scores, dict):
|
||||
log_fields["区域分数"] = (
|
||||
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
|
||||
)
|
||||
if "red_ratio" in detail and detail["red_ratio"] is not None:
|
||||
log_fields["红色比例"] = round(detail["red_ratio"], 4)
|
||||
if "分数" not in log_fields:
|
||||
log_fields["分数"] = round(detail["red_ratio"], 4)
|
||||
if "effective_threshold" in detail:
|
||||
threshold_val = detail["effective_threshold"]
|
||||
if threshold_val is not None:
|
||||
log_fields["阈值"] = round(threshold_val, 4)
|
||||
else:
|
||||
log_fields["阈值"] = "未设置"
|
||||
|
||||
if key == "has_fudai_detail":
|
||||
if "task_count" in detail:
|
||||
log_fields["任务数量"] = detail["task_count"]
|
||||
else:
|
||||
log_fields["任务数量"] = "未获取"
|
||||
try:
|
||||
configured_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
log_fields["配置阈值"] = round(configured_threshold, 4)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if "reason" in detail:
|
||||
log_fields["原因"] = detail["reason"]
|
||||
if "error" in detail:
|
||||
log_fields["错误"] = detail["error"]
|
||||
|
||||
return log_fields
|
||||
|
||||
|
||||
def _ocr_with_dual_modes(
|
||||
analyser: Any,
|
||||
crop_name: str,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
enable_ocr_mode1: bool,
|
||||
step_start: float,
|
||||
max_step_time: float,
|
||||
keywords_for_mode1: tuple,
|
||||
log_callback: Callable[..., None],
|
||||
log_prefix: str,
|
||||
) -> str:
|
||||
"""对已经裁剪好的图片做双 OCR(mode 0 + 可选 mode 1)。
|
||||
|
||||
若 mode 0 文本含 ``keywords_for_mode1`` 中任意一个关键词,则不再跑 mode 1。
|
||||
返回 OCR 文本(mode 1 优先,缺失时退到 mode 0)。
|
||||
"""
|
||||
import time
|
||||
|
||||
if time.time() - step_start >= max_step_time:
|
||||
return ""
|
||||
|
||||
ocr_start = time.time()
|
||||
name0 = preprocess_for_ocr(analyser, crop_name)
|
||||
text = str(analyser.operation.analyse_pic_word(name0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
f"{log_prefix}-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(text),
|
||||
文本预览=text[:50] if text else "",
|
||||
)
|
||||
|
||||
# 是否需要 mode 1:mode 0 没匹配到任意关键词
|
||||
needs_mode1 = enable_ocr_mode1 and (
|
||||
time.time() - step_start < max_step_time
|
||||
) and (
|
||||
not text or not any(kw in text for kw in keywords_for_mode1)
|
||||
)
|
||||
|
||||
if needs_mode1:
|
||||
ocr_start_1 = time.time()
|
||||
name1 = preprocess_for_ocr(analyser, crop_name)
|
||||
text = str(analyser.operation.analyse_pic_word(name1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_callback(
|
||||
f"{log_prefix}-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(text),
|
||||
文本预览=text[:50] if text else "",
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
def _detect_coupon_popup_via_ocr(
|
||||
analyser: Any,
|
||||
coupon_button_area: tuple,
|
||||
step_ocr_verify_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
) -> bool:
|
||||
"""OCR 确认优惠券弹窗("开心收下" 关键词)。返回是否命中。"""
|
||||
import time
|
||||
|
||||
coupon_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start >= max_step_time:
|
||||
return False
|
||||
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*coupon_button_area, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start >= max_step_time:
|
||||
return False
|
||||
|
||||
ocr_start = time.time()
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part0, 0
|
||||
)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part1, 1
|
||||
)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(analyser.operation.analyse_pic_word(pname, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
coupon_verified = True
|
||||
except Exception as e:
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-优惠券异常",
|
||||
耗时毫秒=coupon_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
return coupon_verified
|
||||
|
||||
|
||||
def _detect_redpacket_popup_via_ocr_simple(
|
||||
analyser: Any,
|
||||
shopping_redpacket_area: tuple,
|
||||
step_ocr_verify_start: float,
|
||||
max_step_time: float,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
) -> bool:
|
||||
"""OCR 简单确认购物红包弹窗(仅 mode 0)。返回是否命中。"""
|
||||
import time
|
||||
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start >= max_step_time:
|
||||
return False
|
||||
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*shopping_redpacket_area, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start >= max_step_time:
|
||||
return False
|
||||
|
||||
ocr_start = time.time()
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp2, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
|
||||
redpacket_verified = True
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-购物红包异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
return redpacket_verified
|
||||
|
||||
|
||||
def detect_suspicious_popup_via_ocr(
|
||||
analyser: Any,
|
||||
pixel_state: Dict[str, Any],
|
||||
coupon_button_area: tuple,
|
||||
shopping_redpacket_area: tuple,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
log_summary_callback: Callable[..., None],
|
||||
) -> tuple[bool, str, str]:
|
||||
"""像素检测到弹窗背景但未匹配到弹窗阶段时,OCR 二次确认。
|
||||
|
||||
返回 (matched, stage, reason)。matched=True 时主流程应直接 return。
|
||||
"""
|
||||
import time
|
||||
|
||||
has_suspicious_popup_pixel = pixel_state.get(
|
||||
"has_coupon_bg", False
|
||||
) or pixel_state.get("has_redpacket_bg", False)
|
||||
if not has_suspicious_popup_pixel:
|
||||
return False, "", ""
|
||||
|
||||
step_ocr_verify_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
|
||||
)
|
||||
|
||||
# 优惠券弹窗确认
|
||||
if pixel_state.get("has_coupon_bg", False):
|
||||
if _detect_coupon_popup_via_ocr(
|
||||
analyser, coupon_button_area, step_ocr_verify_start,
|
||||
max_step_time, enable_ocr_mode1, preprocess_for_ocr, log_callback,
|
||||
):
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary_callback(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
return True, "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 购物红包弹窗确认
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
if _detect_redpacket_popup_via_ocr_simple(
|
||||
analyser, shopping_redpacket_area, step_ocr_verify_start,
|
||||
max_step_time, preprocess_for_ocr, log_callback,
|
||||
):
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary_callback(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return True, "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
|
||||
|
||||
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
|
||||
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-未匹配到弹窗",
|
||||
耗时毫秒=ocr_verify_elapsed,
|
||||
说明="OCR确认后未匹配,判定为直播间背景颜色",
|
||||
)
|
||||
log_callback(
|
||||
"步骤3[OCR确认弹窗]-完成", 总耗时毫秒=ocr_verify_elapsed
|
||||
)
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def detect_recommend_follow_live_tabs(
|
||||
analyser: Any,
|
||||
recommend_tab_area: tuple,
|
||||
follow_tab_area: tuple,
|
||||
live_list_tab_area: tuple,
|
||||
diag_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
log_summary_callback: Callable[..., None],
|
||||
log_separator_callback: Callable[..., None],
|
||||
) -> tuple[bool, str, str]:
|
||||
"""步骤3:OCR 检测推荐页/关注列表/直播列表标签栏。
|
||||
|
||||
返回 (matched, stage, reason):matched=True 时主流程应直接 return。
|
||||
matched=False 表示三个标签都没命中(main flow 会回退到默认 IN_LIVE_ROOM)。
|
||||
"""
|
||||
import time
|
||||
|
||||
step_start = time.time()
|
||||
remaining_time_before = float("inf") # 这里不强制超出 diag 时间限制
|
||||
log_callback(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
)
|
||||
|
||||
t_recommend = ""
|
||||
t_follow = ""
|
||||
t_list = ""
|
||||
|
||||
try:
|
||||
# 推荐页标签栏
|
||||
log_callback("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*recommend_tab_area, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
t_recommend = _ocr_with_dual_modes(
|
||||
analyser, "推荐页标签栏",
|
||||
preprocess_for_ocr, enable_ocr_mode1,
|
||||
step_start, max_step_time,
|
||||
keywords_for_mode1=("推荐", "关注", "直播"),
|
||||
log_callback=log_callback,
|
||||
log_prefix="步骤3[OCR推荐页标签栏]",
|
||||
)
|
||||
elapsed_recommend = (time.time() - step_start) * 1000
|
||||
|
||||
if "推荐" in t_recommend:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
seen_text = t_recommend[:50] if t_recommend else "-"
|
||||
log_callback(
|
||||
"步骤3[OCR推荐页标签栏]-命中推荐",
|
||||
耗时毫秒=elapsed_recommend,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
log_summary_callback(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_callback("最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return True, "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 关注列表
|
||||
if "关注" in t_recommend and "推荐" not in t_recommend:
|
||||
log_callback(
|
||||
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
|
||||
精确区域="(658,147)-(765,194)",
|
||||
)
|
||||
step_start_follow = time.time()
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*follow_tab_area, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
t_follow = _ocr_with_dual_modes(
|
||||
analyser, "关注列表标签",
|
||||
preprocess_for_ocr, enable_ocr_mode1,
|
||||
step_start, max_step_time,
|
||||
keywords_for_mode1=("关注",),
|
||||
log_callback=log_callback,
|
||||
log_prefix="步骤3[OCR关注列表]",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
log_callback(
|
||||
"步骤3[OCR关注列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_follow = (time.time() - step_start_follow) * 1000
|
||||
if "关注" in t_follow:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
follow_text = t_follow[:50] if t_follow else "-"
|
||||
log_callback(
|
||||
"步骤3[OCR关注列表]-命中",
|
||||
耗时毫秒=elapsed_follow,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
log_summary_callback(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_callback("最终结果:FOLLOW_LIST(关注列表)")
|
||||
return True, "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 直播列表
|
||||
if "正在直播" in t_recommend or (
|
||||
"直播" in t_recommend
|
||||
and "推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
):
|
||||
log_callback(
|
||||
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
|
||||
精确区域="(650,145)-(800,195)",
|
||||
)
|
||||
step_start_list = time.time()
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*live_list_tab_area, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback(
|
||||
"步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed
|
||||
)
|
||||
|
||||
t_list = _ocr_with_dual_modes(
|
||||
analyser, "直播列表标签",
|
||||
preprocess_for_ocr, enable_ocr_mode1,
|
||||
step_start, max_step_time,
|
||||
keywords_for_mode1=("正在直播",),
|
||||
log_callback=log_callback,
|
||||
log_prefix="步骤3[OCR直播列表]",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
log_callback(
|
||||
"步骤3[OCR直播列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_list = (time.time() - step_start_list) * 1000
|
||||
if "正在直播" in t_list:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
list_text = t_list[:50] if t_list else "-"
|
||||
log_callback(
|
||||
"步骤3[OCR直播列表]-命中",
|
||||
耗时毫秒=elapsed_list,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
log_summary_callback(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_callback("最终结果:LIVE_LIST(直播列表)")
|
||||
return True, "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
log_callback(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
|
||||
耗时毫秒=elapsed_total,
|
||||
阈值毫秒=max_step_time * 1000,
|
||||
)
|
||||
else:
|
||||
log_callback(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
|
||||
耗时毫秒=elapsed_total,
|
||||
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
|
||||
)
|
||||
except Exception as e:
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
import traceback
|
||||
log_callback(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
|
||||
耗时毫秒=elapsed_total,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
step3_elapsed = (time.time() - step_start) * 1000
|
||||
log_callback("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def detect_redpacket_ocr_recheck_outside_live(
|
||||
analyser: Any,
|
||||
pixel_state: Dict[str, Any],
|
||||
pixel_details: Dict[str, Any],
|
||||
shopping_redpacket_area: tuple,
|
||||
diag_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
log_summary_callback: Callable[..., None],
|
||||
) -> tuple[bool, str, str]:
|
||||
"""步骤2.5:不在直播间时的"购物红包"像素 + OCR 复查(含 mode0 / mode1 双 OCR + 置信度兜底)。
|
||||
|
||||
若 ``pixel_state.has_redpacket_bg`` 为 False,直接返回 (False, "", "")。
|
||||
返回 (matched, stage, reason):matched=True 时主流程应直接 return。
|
||||
"""
|
||||
import time
|
||||
|
||||
if not pixel_state.get("has_redpacket_bg", False):
|
||||
return False, "", ""
|
||||
|
||||
step_redpacket_ocr_start = time.time()
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
try:
|
||||
redpacket_detail = (
|
||||
pixel_details.get("has_redpacket_bg", {})
|
||||
if isinstance(pixel_details, dict)
|
||||
else {}
|
||||
)
|
||||
red_ratio = redpacket_detail.get("red_ratio")
|
||||
red_threshold = redpacket_detail.get("effective_threshold")
|
||||
except Exception:
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-开始",
|
||||
说明="不在直播间也执行红包OCR复查",
|
||||
红色比例=(
|
||||
round(float(red_ratio), 4) if red_ratio is not None else None
|
||||
),
|
||||
阈值=(
|
||||
round(float(red_threshold), 4)
|
||||
if red_threshold is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(
|
||||
*shopping_redpacket_area,
|
||||
"",
|
||||
"診斷購物紅包-非直播间复查",
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed
|
||||
)
|
||||
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp0 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result = analyser.operation.analyse_pic_word(
|
||||
name_rp0, 0, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result
|
||||
else:
|
||||
redpacket_text = str(ocr_result or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if enable_ocr_mode1 and (
|
||||
not redpacket_text
|
||||
or not any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
):
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start_1 = time.time()
|
||||
name_rp1 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result_1 = analyser.operation.analyse_pic_word(
|
||||
name_rp1, 1, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result_1, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result_1
|
||||
else:
|
||||
redpacket_text = str(ocr_result_1 or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=(
|
||||
redpacket_text[:50] if redpacket_text else ""
|
||||
),
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
has_keyword_match = redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
has_high_confidence = (
|
||||
ocr_confidence_info
|
||||
and ocr_confidence_info.get("max_confidence", 0)
|
||||
>= analyser.shopping_redpacket_ocr_confidence_threshold
|
||||
)
|
||||
|
||||
if has_keyword_match or has_high_confidence:
|
||||
redpacket_verified = True
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-命中",
|
||||
关键词匹配=has_keyword_match,
|
||||
高置信度匹配=has_high_confidence,
|
||||
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤2.5[购物红包OCR复查]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_summary_callback(
|
||||
"阶段诊断完成(购物红包弹窗-非直播间复查)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(不在直播间)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return True, "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
|
||||
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_callback("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def detect_lottery_result_popup(
|
||||
analyser: Any,
|
||||
diag_start: float,
|
||||
log_callback: Callable[..., None],
|
||||
log_summary_callback: Callable[..., None],
|
||||
log_separator_callback: Callable[..., None],
|
||||
) -> tuple[bool, str, str]:
|
||||
"""优先级1:通过 OCR 确认抽奖结果弹窗。
|
||||
|
||||
返回 (matched, stage, reason):
|
||||
- matched=True:已确认是 FUDai_RESULT,主流程应直接 return (stage, reason)
|
||||
- matched=False:继续后续检测
|
||||
"""
|
||||
import time
|
||||
|
||||
step1_start = time.time()
|
||||
log_separator_callback("步骤1:检测抽奖结果弹窗(简化)")
|
||||
try:
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
|
||||
if detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_summary_callback(
|
||||
"阶段诊断完成(抽奖结果弹窗)",
|
||||
阶段="FUDai_RESULT",
|
||||
原因="像素检测+按钮OCR确认",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator_callback("最终结果:FUDai_RESULT(抽奖结果弹窗)")
|
||||
return True, "FUDai_RESULT", "像素检测+按钮OCR确认"
|
||||
else:
|
||||
log_callback("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
|
||||
except Exception as e:
|
||||
log_callback(
|
||||
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
step1_elapsed = (time.time() - step1_start) * 1000
|
||||
log_callback("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def detect_shopping_redpacket_popup(
|
||||
analyser: Any,
|
||||
shopping_redpacket_area: tuple,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
max_step_time: float,
|
||||
preprocess_for_ocr: Callable[[Any, str], str],
|
||||
log_callback: Callable[..., None],
|
||||
log_summary_callback: Callable[..., None],
|
||||
log_separator_callback: Callable[..., None],
|
||||
) -> tuple[bool, str, str]:
|
||||
"""优先级1.5:通过 OCR 确认购物红包弹窗。
|
||||
|
||||
返回 (matched, stage, reason)。
|
||||
"""
|
||||
import time
|
||||
|
||||
log_separator_callback("步骤1.5:检测购物红包弹窗")
|
||||
step_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log_callback(
|
||||
"步骤1.5[检测购物红包弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到购物红包背景",
|
||||
)
|
||||
|
||||
redpacket_detected = False
|
||||
try:
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*shopping_redpacket_area, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log_callback("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log_callback(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_detected = True
|
||||
else:
|
||||
log_callback(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
|
||||
说明="OCR未匹配,不判定为购物红包弹窗",
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_callback(
|
||||
"步骤1.5[检测购物红包弹窗]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
log_callback(
|
||||
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
|
||||
说明="需要OCR确认才能判定",
|
||||
)
|
||||
|
||||
if redpacket_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_summary_callback(
|
||||
"阶段诊断完成(购物红包弹窗)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="检测到购物红包弹窗",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return True, "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
|
||||
|
||||
step15_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
log_callback("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def log_pixel_detection_details(
|
||||
pixel_details: Dict[str, Dict[str, Any]],
|
||||
analyser: Any,
|
||||
log_callback: Callable[..., None],
|
||||
) -> None:
|
||||
"""记录并行像素检测每个步骤的详细日志。"""
|
||||
for key, detail in (pixel_details or {}).items():
|
||||
log_fields = _format_detail_log_fields(key, detail, analyser)
|
||||
|
||||
# has_fudai_detail 单独保留任务数量与 detected 矛盾的告警分支
|
||||
if key == "has_fudai_detail":
|
||||
task_count_val = detail.get("task_count")
|
||||
detected = detail.get("detected", False)
|
||||
if (
|
||||
task_count_val is not None
|
||||
and task_count_val > 0
|
||||
and not detected
|
||||
):
|
||||
try:
|
||||
log_callback(
|
||||
"警告:检测到任务数量但 has_fudai_detail 为 False",
|
||||
任务数量=task_count_val,
|
||||
detected=detected,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
step_name = _STEP_NAME_MAP.get(key, key)
|
||||
try:
|
||||
log_callback(f"并行检测-{step_name}", **log_fields)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def summarize_pixel_state(
|
||||
pixel_state: Dict[str, Any],
|
||||
pixel_detection_elapsed_ms: float,
|
||||
log_callback: Callable[..., None],
|
||||
) -> None:
|
||||
"""把 pixel_state 摘要写到日志,方便排查命中/未命中分布。"""
|
||||
try:
|
||||
log_callback(
|
||||
"像素状态(并行检测完成)",
|
||||
耗时毫秒=pixel_detection_elapsed_ms,
|
||||
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
|
||||
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
|
||||
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
|
||||
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
|
||||
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
|
||||
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
|
||||
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
+30
-207
@@ -14,6 +14,11 @@ except Exception:
|
||||
except Exception:
|
||||
mapping_utils = None
|
||||
|
||||
try:
|
||||
from . import mapping_table_helpers as _mt_helpers
|
||||
except Exception:
|
||||
import gui.components.mapping_table_helpers as _mt_helpers
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
|
||||
@@ -278,14 +283,8 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
|
||||
canvas_w = canvas.winfo_width() or 800
|
||||
except Exception:
|
||||
canvas_w = 800
|
||||
min_card_w = 300
|
||||
columns, col_width = _mt_helpers.compute_card_layout(canvas_w)
|
||||
h_gap = 12
|
||||
try:
|
||||
columns = max(1, int((canvas_w + h_gap) / (min_card_w + h_gap)))
|
||||
except Exception:
|
||||
columns = 1
|
||||
# 限制最大列数以避免过窄(可根据实际需求调整)
|
||||
columns = min(columns, 3)
|
||||
|
||||
# 配置列权重
|
||||
try:
|
||||
@@ -326,88 +325,18 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 计算每列可用宽度用于 wraplength
|
||||
try:
|
||||
col_total_gap = columns * 12
|
||||
col_width = max(220, int((canvas_w - col_total_gap) / columns))
|
||||
card_wraplen = max(160, col_width - 40)
|
||||
except Exception:
|
||||
card_wraplen = wraplen
|
||||
|
||||
# 标题行(紧凑)
|
||||
try:
|
||||
lbl_title = tk.Label(
|
||||
card,
|
||||
text=lines[0],
|
||||
font=title_font,
|
||||
bg=normal_bg,
|
||||
fg="#0b3d91",
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=card_wraplen,
|
||||
)
|
||||
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
|
||||
except Exception:
|
||||
lbl_title = tk.Label(card, text=lines[0], bg=normal_bg)
|
||||
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
|
||||
|
||||
# 其余行逐行显示(meta/body 区分),行间距更小
|
||||
for li, ln in enumerate(lines[1:], start=1):
|
||||
try:
|
||||
if show_title_raw_var.get():
|
||||
if li in (1, 2, 3):
|
||||
lbl = tk.Label(
|
||||
card,
|
||||
text=ln,
|
||||
font=meta_font,
|
||||
fg="#555555",
|
||||
bg=normal_bg,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=card_wraplen,
|
||||
)
|
||||
else:
|
||||
lbl = tk.Label(
|
||||
card,
|
||||
text=ln,
|
||||
font=body_font,
|
||||
fg="#222222",
|
||||
bg=normal_bg,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=card_wraplen,
|
||||
)
|
||||
else:
|
||||
if li in (1, 2):
|
||||
lbl = tk.Label(
|
||||
card,
|
||||
text=ln,
|
||||
font=meta_font,
|
||||
fg="#555555",
|
||||
bg=normal_bg,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=card_wraplen,
|
||||
)
|
||||
else:
|
||||
lbl = tk.Label(
|
||||
card,
|
||||
text=ln,
|
||||
font=body_font,
|
||||
fg="#222222",
|
||||
bg=normal_bg,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=card_wraplen,
|
||||
)
|
||||
lbl.pack(fill="x", padx=10, pady=(0, 1))
|
||||
except Exception:
|
||||
try:
|
||||
tk.Label(card, text=ln, bg=normal_bg).pack(
|
||||
fill="x", padx=10, pady=(0, 1)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 渲染标题 + meta + body 行
|
||||
card_wraplen = max(160, col_width - 40)
|
||||
_mt_helpers.render_card_labels(
|
||||
card=card,
|
||||
lines=lines,
|
||||
title_font=title_font,
|
||||
meta_font=meta_font,
|
||||
body_font=body_font,
|
||||
bg=normal_bg,
|
||||
wraplength=card_wraplen,
|
||||
show_title_raw=show_title_raw_var.get(),
|
||||
)
|
||||
|
||||
# 分隔线
|
||||
try:
|
||||
@@ -420,108 +349,17 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
|
||||
mapping_entries_widgets.append(card)
|
||||
|
||||
# 绑定点击/双击以及 hover 事件
|
||||
def _make_bind_handlers(ci: int, cframe: tk.Widget):
|
||||
def _on_click(e: object | None = None) -> None:
|
||||
try:
|
||||
# 取消其他选中并高亮当前
|
||||
for i, w in enumerate(mapping_entries_widgets):
|
||||
bg = normal_bg if i != ci else selected_bg
|
||||
try:
|
||||
try:
|
||||
w.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
w.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
for ch in w.winfo_children():
|
||||
try:
|
||||
try:
|
||||
ch.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
ch.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
last_selected_entry["idx"] = ci
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _on_dbl(e: object | None = None) -> None:
|
||||
try:
|
||||
content = mapping_entries_text[ci]
|
||||
except Exception:
|
||||
content = ""
|
||||
if not content:
|
||||
return
|
||||
win = tk.Toplevel(root)
|
||||
win.title("条目详情")
|
||||
try:
|
||||
if ScrolledText:
|
||||
st = ScrolledText(win, width=100, height=20)
|
||||
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
st.insert("1.0", content)
|
||||
st.configure(state="disabled")
|
||||
else:
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
except Exception:
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
|
||||
def _on_enter(e: object | None = None) -> None:
|
||||
try:
|
||||
# 悬停时改变背景(若已选中则保持选中色)
|
||||
bg = (
|
||||
selected_bg
|
||||
if last_selected_entry.get("idx") == ci
|
||||
else hover_bg
|
||||
)
|
||||
try:
|
||||
try:
|
||||
cframe.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
cframe.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
for ch in cframe.winfo_children():
|
||||
try:
|
||||
try:
|
||||
ch.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
ch.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _on_leave(e: object | None = None) -> None:
|
||||
try:
|
||||
bg = (
|
||||
selected_bg
|
||||
if last_selected_entry.get("idx") == ci
|
||||
else normal_bg
|
||||
)
|
||||
try:
|
||||
try:
|
||||
cframe.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
cframe.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
for ch in cframe.winfo_children():
|
||||
try:
|
||||
try:
|
||||
ch.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
ch.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return _on_click, _on_dbl, _on_enter, _on_leave
|
||||
|
||||
on_click, on_dbl, on_enter, on_leave = _make_bind_handlers(
|
||||
len(mapping_entries_widgets) - 1, card
|
||||
on_click, on_dbl, on_enter, on_leave = _mt_helpers.make_card_event_handlers(
|
||||
card_index=len(mapping_entries_widgets) - 1,
|
||||
card=card,
|
||||
cards=mapping_entries_widgets,
|
||||
last_selected=last_selected_entry,
|
||||
entries_text=mapping_entries_text,
|
||||
root=root,
|
||||
normal_bg=normal_bg,
|
||||
hover_bg=hover_bg,
|
||||
selected_bg=selected_bg,
|
||||
scrolled_text_cls=ScrolledText,
|
||||
)
|
||||
try:
|
||||
card.bind("<Button-1>", on_click)
|
||||
@@ -594,22 +432,7 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
|
||||
content = mapping_entries_text[idx]
|
||||
except Exception:
|
||||
content = ""
|
||||
if not content:
|
||||
return
|
||||
win = tk.Toplevel(root)
|
||||
win.title("条目详情")
|
||||
try:
|
||||
if ScrolledText:
|
||||
st = ScrolledText(win, width=100, height=20)
|
||||
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
st.insert("1.0", content)
|
||||
st.configure(state="disabled")
|
||||
else:
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
except Exception:
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
_mt_helpers.open_entry_detail_window(root, content, ScrolledText)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""mapping_table 内部辅助函数。
|
||||
|
||||
把 mapping_table.create_mapping_tab 中重复或自包含的子块抽出来:
|
||||
- 弹出条目详情窗口(在两处出现,逻辑完全一致)
|
||||
- 计算自适应列数与卡片宽度
|
||||
- 卡片背景色批量切换
|
||||
- card hover/click/dbl 事件处理器工厂
|
||||
- 渲染单张卡片内的标题 + 多行 label
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable, List, Optional
|
||||
|
||||
|
||||
def open_entry_detail_window(
|
||||
root: tk.Tk,
|
||||
content: str,
|
||||
scrolled_text_cls: Optional[type] = None,
|
||||
) -> None:
|
||||
"""打开"条目详情"弹窗。如果 ScrolledText 不可用则退化成 Label。"""
|
||||
if not content:
|
||||
return
|
||||
win = tk.Toplevel(root)
|
||||
win.title("条目详情")
|
||||
try:
|
||||
if scrolled_text_cls is not None:
|
||||
st = scrolled_text_cls(win, width=100, height=20)
|
||||
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
st.insert("1.0", content)
|
||||
st.configure(state="disabled")
|
||||
return
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
except Exception:
|
||||
lbl = ttk.Label(win, text=content, justify="left")
|
||||
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
||||
|
||||
|
||||
def compute_card_layout(canvas_width: int, min_card_w: int = 300, h_gap: int = 12,
|
||||
max_columns: int = 3) -> tuple[int, int]:
|
||||
"""根据画布宽度计算列数与单卡片可用宽度。
|
||||
|
||||
返回 (columns, card_width)。
|
||||
"""
|
||||
try:
|
||||
columns = max(1, int((canvas_width + h_gap) / (min_card_w + h_gap)))
|
||||
except Exception:
|
||||
columns = 1
|
||||
columns = min(columns, max_columns)
|
||||
try:
|
||||
col_total_gap = columns * h_gap
|
||||
col_width = max(220, int((canvas_width - col_total_gap) / columns))
|
||||
except Exception:
|
||||
col_width = 800
|
||||
return columns, col_width
|
||||
|
||||
|
||||
def set_card_bg(widget: tk.Widget, bg: str) -> None:
|
||||
"""把 widget 自身和所有直接子 widget 的背景色改为 bg。"""
|
||||
try:
|
||||
try:
|
||||
widget.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
widget.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
for ch in widget.winfo_children():
|
||||
try:
|
||||
try:
|
||||
ch.configure(**{"bg": bg})
|
||||
except Exception:
|
||||
ch.configure(**{"background": bg})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def make_card_event_handlers(
|
||||
card_index: int,
|
||||
card: tk.Widget,
|
||||
cards: List[tk.Widget],
|
||||
last_selected: dict,
|
||||
entries_text: List[str],
|
||||
root: tk.Tk,
|
||||
normal_bg: str,
|
||||
hover_bg: str,
|
||||
selected_bg: str,
|
||||
scrolled_text_cls: Optional[type] = None,
|
||||
) -> tuple[Callable, Callable, Callable, Callable]:
|
||||
"""生成单张卡片的 click / dblclick / enter / leave 事件处理器。"""
|
||||
def on_click(_e: object | None = None) -> None:
|
||||
try:
|
||||
for i, w in enumerate(cards):
|
||||
bg = normal_bg if i != card_index else selected_bg
|
||||
set_card_bg(w, bg)
|
||||
last_selected["idx"] = card_index
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def on_dbl(_e: object | None = None) -> None:
|
||||
try:
|
||||
content = entries_text[card_index]
|
||||
except Exception:
|
||||
content = ""
|
||||
open_entry_detail_window(root, content, scrolled_text_cls)
|
||||
|
||||
def on_enter(_e: object | None = None) -> None:
|
||||
try:
|
||||
bg = (
|
||||
selected_bg if last_selected.get("idx") == card_index else hover_bg
|
||||
)
|
||||
set_card_bg(card, bg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def on_leave(_e: object | None = None) -> None:
|
||||
try:
|
||||
bg = (
|
||||
selected_bg if last_selected.get("idx") == card_index else normal_bg
|
||||
)
|
||||
set_card_bg(card, bg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return on_click, on_dbl, on_enter, on_leave
|
||||
|
||||
|
||||
def render_card_labels(
|
||||
card: tk.Widget,
|
||||
lines: List[str],
|
||||
title_font: Any,
|
||||
meta_font: Any,
|
||||
body_font: Any,
|
||||
bg: str,
|
||||
wraplength: int,
|
||||
show_title_raw: bool,
|
||||
) -> None:
|
||||
"""在单张 card 内逐行渲染 title + meta + body label。"""
|
||||
if not lines:
|
||||
return
|
||||
|
||||
# 标题行
|
||||
try:
|
||||
tk.Label(
|
||||
card,
|
||||
text=lines[0],
|
||||
font=title_font,
|
||||
bg=bg,
|
||||
fg="#0b3d91",
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=wraplength,
|
||||
).pack(fill="x", padx=10, pady=(6, 1))
|
||||
except Exception:
|
||||
try:
|
||||
tk.Label(card, text=lines[0], bg=bg).pack(fill="x", padx=10, pady=(6, 1))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
meta_line_count = 3 if show_title_raw else 2
|
||||
|
||||
for li, ln in enumerate(lines[1:], start=1):
|
||||
try:
|
||||
is_meta = li in tuple(range(1, meta_line_count + 1))
|
||||
font = meta_font if is_meta else body_font
|
||||
fg = "#555555" if is_meta else "#222222"
|
||||
tk.Label(
|
||||
card,
|
||||
text=ln,
|
||||
font=font,
|
||||
fg=fg,
|
||||
bg=bg,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=wraplength,
|
||||
).pack(fill="x", padx=10, pady=(0, 1))
|
||||
except Exception:
|
||||
try:
|
||||
tk.Label(card, text=ln, bg=bg).pack(fill="x", padx=10, pady=(0, 1))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,905 @@
|
||||
"""单元测试:douyin/reservation/reservation_logic/attend_window_helpers.py"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from douyin.reservation.reservation_logic import attend_window_helpers as h
|
||||
|
||||
|
||||
def _make_analyser(**overrides):
|
||||
a = MagicMock()
|
||||
a.high_value_fudai_join_ahead_seconds = 100
|
||||
a.high_value_fudai_max_swipe_back = 60
|
||||
for k, v in overrides.items():
|
||||
setattr(a, k, v)
|
||||
return a
|
||||
|
||||
|
||||
# ---- compute_dynamic_ahead ---- #
|
||||
|
||||
def test_compute_dynamic_ahead_zero_back_steps():
|
||||
"""target_pos == room_pos → 不需要回退,提前量保持 join_ahead"""
|
||||
a = _make_analyser()
|
||||
target = {"pos_seen": 5}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
|
||||
assert est == 0
|
||||
assert da == 100 # join_ahead 默认值
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_with_back_steps():
|
||||
"""需要回退 50 步,每步 0.6s → 50*0.6+18 = 48s,仍小于 join_ahead=100,所以保持 100"""
|
||||
a = _make_analyser()
|
||||
target = {"pos_seen": 0}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=50, reservation_back_swipe_delay_s=0.6)
|
||||
assert est == 50
|
||||
assert da == 100
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_back_steps_dominate():
|
||||
"""需要回退 200 步但被 max_back=60 截断 → 60*0.6+18 = 54,仍 < 100"""
|
||||
a = _make_analyser()
|
||||
target = {"pos_seen": 0}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=200, reservation_back_swipe_delay_s=0.6)
|
||||
assert est == 60 # 截断到 max_back
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_huge_delay_dominates():
|
||||
"""delay=5s 时 60*5+18=318 > join_ahead,dynamic_ahead 取大值"""
|
||||
a = _make_analyser()
|
||||
target = {"pos_seen": 0}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=60, reservation_back_swipe_delay_s=5.0)
|
||||
assert est == 60
|
||||
assert da == 318 # 60*5+18
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_no_max_back_uncapped():
|
||||
"""high_value_fudai_max_swipe_back=0 时,由于 `or 60` 会被兜底成 60"""
|
||||
a = _make_analyser(high_value_fudai_max_swipe_back=0)
|
||||
target = {"pos_seen": 0}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=100, reservation_back_swipe_delay_s=2.0)
|
||||
assert est == 60 # 0 被 `or 60` 兜底
|
||||
assert da == 138 # 60*2+18
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_handles_bad_target_pos():
|
||||
"""target.pos_seen 缺失时按 0 处理"""
|
||||
a = _make_analyser()
|
||||
target = {}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
|
||||
assert est == 10
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_negative_back_steps_clamped():
|
||||
"""target_pos > room_pos(不正常)时 est_back_times 被钳到 0"""
|
||||
a = _make_analyser()
|
||||
target = {"pos_seen": 100}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
|
||||
assert est == 0
|
||||
|
||||
|
||||
def test_compute_dynamic_ahead_handles_bad_join_ahead():
|
||||
"""getattr 抛错时回退到 100.0"""
|
||||
a = MagicMock()
|
||||
type(a).high_value_fudai_join_ahead_seconds = property(
|
||||
lambda self: (_ for _ in ()).throw(RuntimeError("boom"))
|
||||
)
|
||||
a.high_value_fudai_max_swipe_back = 60
|
||||
target = {"pos_seen": 5}
|
||||
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
|
||||
# join_ahead 兜底为 100.0
|
||||
assert da == 100
|
||||
|
||||
|
||||
# ---- _ts_to_str ---- #
|
||||
|
||||
def test_ts_to_str_invalid():
|
||||
assert h._ts_to_str(0) == "无效"
|
||||
assert h._ts_to_str(-100) == "无效"
|
||||
|
||||
|
||||
def test_ts_to_str_valid():
|
||||
s = h._ts_to_str(1700000000) # 2023-11-14 22:13:20 UTC, 本地时区
|
||||
assert len(s) == 19 # YYYY-MM-DD HH:MM:SS
|
||||
|
||||
|
||||
# ---- log_attend_window_check_details ---- #
|
||||
|
||||
def test_log_attend_window_check_details_writes_one_line():
|
||||
a = MagicMock()
|
||||
h.log_attend_window_check_details(
|
||||
a,
|
||||
now_ts=1700000000,
|
||||
focus_until=0,
|
||||
ft=1700000100,
|
||||
dynamic_ahead=100,
|
||||
join_ahead=100.0,
|
||||
poll_before=10.0,
|
||||
est_back_times=0,
|
||||
)
|
||||
assert a._log_kv.call_count == 1
|
||||
args, kwargs = a._log_kv.call_args
|
||||
assert args[0] == "预约"
|
||||
assert "process_reservation_attend_window 详细检查" in args[1]
|
||||
assert kwargs["target_future_ts"] == 1700000100
|
||||
assert kwargs["dynamic_ahead"] == 100
|
||||
assert kwargs["in_lock_period"] is False # focus_until=0
|
||||
|
||||
|
||||
def test_log_attend_window_check_details_in_lock_period():
|
||||
a = MagicMock()
|
||||
h.log_attend_window_check_details(
|
||||
a,
|
||||
now_ts=1700000000,
|
||||
focus_until=1700000050, # > now_ts
|
||||
ft=1700000100,
|
||||
dynamic_ahead=100,
|
||||
join_ahead=100.0,
|
||||
poll_before=10.0,
|
||||
est_back_times=0,
|
||||
)
|
||||
args, kwargs = a._log_kv.call_args
|
||||
assert kwargs["in_lock_period"] is True
|
||||
|
||||
|
||||
def test_log_attend_window_check_details_swallows_exceptions():
|
||||
bad = MagicMock()
|
||||
bad._log_kv.side_effect = RuntimeError("boom")
|
||||
h.log_attend_window_check_details(
|
||||
bad, now_ts=0, focus_until=0, ft=0, dynamic_ahead=0,
|
||||
join_ahead=0.0, poll_before=0.0, est_back_times=0,
|
||||
)
|
||||
|
||||
|
||||
# ---- check_waiting_for_reservation_lottery ---- #
|
||||
|
||||
def test_waiting_lottery_with_reservation_returns_true():
|
||||
a = MagicMock()
|
||||
a._waiting_for_lottery_result = True
|
||||
a._current_attending_reservation_fudai = True
|
||||
assert h.check_waiting_for_reservation_lottery(a) is True
|
||||
|
||||
|
||||
def test_waiting_lottery_only_one_flag_returns_false():
|
||||
a = MagicMock()
|
||||
a._waiting_for_lottery_result = True
|
||||
a._current_attending_reservation_fudai = False
|
||||
assert h.check_waiting_for_reservation_lottery(a) is False
|
||||
|
||||
a._waiting_for_lottery_result = False
|
||||
a._current_attending_reservation_fudai = True
|
||||
assert h.check_waiting_for_reservation_lottery(a) is False
|
||||
|
||||
|
||||
def test_waiting_lottery_neither_flag_returns_false():
|
||||
a = MagicMock()
|
||||
a._waiting_for_lottery_result = False
|
||||
a._current_attending_reservation_fudai = False
|
||||
assert h.check_waiting_for_reservation_lottery(a) is False
|
||||
|
||||
|
||||
# ---- maybe_promote_locked_reservation ---- #
|
||||
|
||||
def test_promote_locked_no_lock_period_returns_unchanged():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 100}]
|
||||
ref = [0.0]
|
||||
result = h.maybe_promote_locked_reservation(
|
||||
a, reservations, ref, focus_until=0.0, now_ts=200.0, poll_before=10.0
|
||||
)
|
||||
assert result == 0.0
|
||||
|
||||
|
||||
def test_promote_locked_expired_returns_unchanged():
|
||||
"""now_ts >= focus_until → 锁定期已过,不修改"""
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 100}]
|
||||
ref = [50.0]
|
||||
result = h.maybe_promote_locked_reservation(
|
||||
a, reservations, ref, focus_until=50.0, now_ts=100.0, poll_before=10.0
|
||||
)
|
||||
assert result == 50.0
|
||||
|
||||
|
||||
def test_promote_locked_target_not_in_queue_clears_focus():
|
||||
"""锁定期对应的预约已不在队列 → 清除锁定期"""
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 200}, {"future_ts": 300}]
|
||||
# focus_until = 1000,但队列里没有 ft+10 = 1000 的预约
|
||||
ref = [1000.0]
|
||||
now = 500.0
|
||||
result = h.maybe_promote_locked_reservation(
|
||||
a, reservations, ref, focus_until=1000.0, now_ts=now, poll_before=10.0
|
||||
)
|
||||
assert result == 0.0
|
||||
assert ref[0] == 0.0
|
||||
|
||||
|
||||
def test_promote_locked_already_at_head_no_swap():
|
||||
"""锁定预约已在队头 → 不调整顺序"""
|
||||
a = MagicMock()
|
||||
# focus_until = 200 + 10 = 210,正好是第一个预约的"预期 focus"
|
||||
reservations = [{"future_ts": 200}, {"future_ts": 300}]
|
||||
ref = [210.0]
|
||||
result = h.maybe_promote_locked_reservation(
|
||||
a, reservations, ref, focus_until=210.0, now_ts=100.0, poll_before=10.0
|
||||
)
|
||||
assert result == 210.0
|
||||
# 顺序未变
|
||||
assert reservations[0]["future_ts"] == 200
|
||||
|
||||
|
||||
def test_promote_locked_swaps_to_head():
|
||||
"""锁定预约不在队头 → 移到队头"""
|
||||
a = MagicMock()
|
||||
# focus_until = 300 + 10 = 310,对应队列中第二个预约
|
||||
reservations = [
|
||||
{"future_ts": 200},
|
||||
{"future_ts": 300},
|
||||
]
|
||||
ref = [310.0]
|
||||
result = h.maybe_promote_locked_reservation(
|
||||
a, reservations, ref, focus_until=310.0, now_ts=100.0, poll_before=10.0
|
||||
)
|
||||
assert result == 310.0
|
||||
# 锁定预约(300)已被移到队头
|
||||
assert reservations[0]["future_ts"] == 300
|
||||
|
||||
|
||||
# ---- check_already_participated ---- #
|
||||
|
||||
def test_already_participated_with_match_pops_and_returns_true():
|
||||
a = MagicMock()
|
||||
a._participated_fudai_future_ts = {100.0, 200.0}
|
||||
reservations = [{"future_ts": 100.0}, {"future_ts": 300.0}]
|
||||
target = reservations[0]
|
||||
write_cb = MagicMock()
|
||||
result = h.check_already_participated(a, reservations, target, 100.0, write_cb)
|
||||
assert result is True
|
||||
assert len(reservations) == 1 # 队头被弹出
|
||||
write_cb.assert_called_once()
|
||||
|
||||
|
||||
def test_already_participated_no_match_returns_false():
|
||||
a = MagicMock()
|
||||
a._participated_fudai_future_ts = {500.0}
|
||||
reservations = [{"future_ts": 100.0}]
|
||||
write_cb = MagicMock()
|
||||
result = h.check_already_participated(a, reservations, reservations[0], 100.0, write_cb)
|
||||
assert result is False
|
||||
assert len(reservations) == 1
|
||||
write_cb.assert_not_called()
|
||||
|
||||
|
||||
def test_already_participated_within_5s_tolerance():
|
||||
"""允许 5 秒误差 → 95-105 之间也算已参与"""
|
||||
a = MagicMock()
|
||||
a._participated_fudai_future_ts = {100.0}
|
||||
reservations = [{"future_ts": 103.0}]
|
||||
write_cb = MagicMock()
|
||||
result = h.check_already_participated(a, reservations, reservations[0], 103.0, write_cb)
|
||||
assert result is True
|
||||
|
||||
|
||||
def test_already_participated_outside_5s_returns_false():
|
||||
a = MagicMock()
|
||||
a._participated_fudai_future_ts = {100.0}
|
||||
reservations = [{"future_ts": 110.0}] # 差 10 秒,超出误差
|
||||
write_cb = MagicMock()
|
||||
result = h.check_already_participated(a, reservations, reservations[0], 110.0, write_cb)
|
||||
assert result is False
|
||||
|
||||
|
||||
def test_already_participated_non_set_attr_treated_as_empty():
|
||||
a = MagicMock()
|
||||
a._participated_fudai_future_ts = "not_a_set"
|
||||
reservations = [{"future_ts": 100.0}]
|
||||
write_cb = MagicMock()
|
||||
result = h.check_already_participated(a, reservations, reservations[0], 100.0, write_cb)
|
||||
assert result is False
|
||||
|
||||
|
||||
# ---- discard_invalid_future_ts ---- #
|
||||
|
||||
def test_discard_invalid_ft_zero_returns_true():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 0}, {"future_ts": 100}]
|
||||
write_cb = MagicMock()
|
||||
result = h.discard_invalid_future_ts(a, reservations, reservations[0], 0.0, write_cb)
|
||||
assert result is True
|
||||
assert len(reservations) == 1
|
||||
write_cb.assert_called_once()
|
||||
|
||||
|
||||
def test_discard_invalid_ft_negative_returns_true():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": -5}]
|
||||
write_cb = MagicMock()
|
||||
result = h.discard_invalid_future_ts(a, reservations, reservations[0], -5.0, write_cb)
|
||||
assert result is True
|
||||
|
||||
|
||||
def test_discard_invalid_ft_positive_returns_false():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 100}]
|
||||
write_cb = MagicMock()
|
||||
result = h.discard_invalid_future_ts(a, reservations, reservations[0], 100.0, write_cb)
|
||||
assert result is False
|
||||
assert len(reservations) == 1
|
||||
write_cb.assert_not_called()
|
||||
|
||||
|
||||
# ---- log_target_reservation_details ---- #
|
||||
|
||||
def test_log_target_reservation_details_writes_one_line():
|
||||
a = MagicMock()
|
||||
target = {"prize_value_yuan": 5.0, "pos_seen": 3, "content": "test"}
|
||||
h.log_target_reservation_details(a, target, ft=1700000000.0)
|
||||
a._log_kv.assert_called_once()
|
||||
args, kwargs = a._log_kv.call_args
|
||||
assert args[0] == "预约"
|
||||
assert kwargs["target_future_ts"] == 1700000000
|
||||
assert kwargs["target_value"] == 5.0
|
||||
|
||||
|
||||
def test_log_target_reservation_details_invalid_ft():
|
||||
a = MagicMock()
|
||||
h.log_target_reservation_details(a, {}, ft=0.0)
|
||||
a._log_kv.assert_called_once()
|
||||
_, kwargs = a._log_kv.call_args
|
||||
assert kwargs["target_future_str"] == "无效"
|
||||
|
||||
|
||||
def test_log_target_reservation_details_swallows_exception():
|
||||
a = MagicMock()
|
||||
a._log_kv.side_effect = RuntimeError("boom")
|
||||
# 不应抛错
|
||||
h.log_target_reservation_details(a, {}, ft=100.0)
|
||||
|
||||
|
||||
# ---- sort_reservations_with_logging ---- #
|
||||
|
||||
def test_sort_reservations_logs_before_and_after():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 200}, {"future_ts": 100}]
|
||||
sort_cb = MagicMock(side_effect=lambda lst: lst.sort(key=lambda x: x["future_ts"]))
|
||||
h.sort_reservations_with_logging(a, reservations, sort_cb)
|
||||
# 至少 2 次日志:开始排序 / 排序完成
|
||||
assert a._log_kv.call_count >= 2
|
||||
# 排序后队头是 100
|
||||
assert reservations[0]["future_ts"] == 100
|
||||
|
||||
|
||||
def test_sort_reservations_swallows_sort_exception():
|
||||
a = MagicMock()
|
||||
reservations = [{"future_ts": 100}]
|
||||
sort_cb = MagicMock(side_effect=RuntimeError("boom"))
|
||||
# 不应抛错
|
||||
h.sort_reservations_with_logging(a, reservations, sort_cb)
|
||||
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
|
||||
assert any("队列排序异常" in m for m in msgs)
|
||||
|
||||
|
||||
def test_sort_reservations_empty_queue():
|
||||
a = MagicMock()
|
||||
sort_cb = MagicMock()
|
||||
h.sort_reservations_with_logging(a, [], sort_cb)
|
||||
sort_cb.assert_called_once_with([])
|
||||
|
||||
|
||||
# ---- check_total_timeout ---- #
|
||||
|
||||
def test_check_timeout_not_exceeded_returns_false():
|
||||
a = MagicMock()
|
||||
now = time.time()
|
||||
assert h.check_total_timeout(a, now, total_timeout_s=10.0, stage="测试") is False
|
||||
|
||||
|
||||
def test_check_timeout_exceeded_returns_true():
|
||||
a = MagicMock()
|
||||
past = time.time() - 100
|
||||
assert h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试") is True
|
||||
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
|
||||
assert any("超时退出(测试)" in m for m in msgs)
|
||||
|
||||
|
||||
def test_check_timeout_swallows_exception():
|
||||
a = MagicMock()
|
||||
a._log_kv.side_effect = RuntimeError("boom")
|
||||
past = time.time() - 100
|
||||
# 应不抛错
|
||||
result = h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试")
|
||||
assert result is True
|
||||
|
||||
|
||||
# ---- check_queue_full_immediate_attend ---- #
|
||||
|
||||
def test_queue_full_immediate_attend_true():
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = True
|
||||
assert h.check_queue_full_immediate_attend(a) is True
|
||||
|
||||
|
||||
def test_queue_full_immediate_attend_false():
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = False
|
||||
assert h.check_queue_full_immediate_attend(a) is False
|
||||
|
||||
|
||||
def test_queue_full_immediate_swallows_attr_error():
|
||||
a = MagicMock()
|
||||
type(a).queue_full_waiting_at_earliest = property(
|
||||
lambda _self: (_ for _ in ()).throw(RuntimeError("boom"))
|
||||
)
|
||||
assert h.check_queue_full_immediate_attend(a) is False
|
||||
|
||||
|
||||
# ---- handle_time_window_early_returns ---- #
|
||||
|
||||
def test_time_window_not_yet_arrived_returns_false():
|
||||
a = MagicMock()
|
||||
cleanup = MagicMock()
|
||||
write_cb = MagicMock()
|
||||
now = 1700000000.0
|
||||
ft = now + 500 # 500s 后
|
||||
result = h.handle_time_window_early_returns(
|
||||
a, [], now, ft, dynamic_ahead=100,
|
||||
poll_before=10.0, is_queue_full_immediate_attend=False,
|
||||
cleanup_expired_callback=cleanup, write_state_callback=write_cb,
|
||||
)
|
||||
assert result is False
|
||||
cleanup.assert_not_called()
|
||||
|
||||
|
||||
def test_time_window_missed_calls_cleanup_and_returns_true():
|
||||
a = MagicMock()
|
||||
cleanup = MagicMock()
|
||||
write_cb = MagicMock()
|
||||
now = 1700000000.0
|
||||
ft = now - 1000 # 已过去
|
||||
result = h.handle_time_window_early_returns(
|
||||
a, [{"future_ts": ft}], now, ft, dynamic_ahead=100,
|
||||
poll_before=10.0, is_queue_full_immediate_attend=False,
|
||||
cleanup_expired_callback=cleanup, write_state_callback=write_cb,
|
||||
)
|
||||
assert result is True
|
||||
cleanup.assert_called_once()
|
||||
|
||||
|
||||
def test_time_window_in_range_returns_none():
|
||||
"""在窗口内 → 返回 None 让主流程继续"""
|
||||
a = MagicMock()
|
||||
cleanup = MagicMock()
|
||||
now = 1700000000.0
|
||||
ft = now + 50 # 50s 内
|
||||
result = h.handle_time_window_early_returns(
|
||||
a, [], now, ft, dynamic_ahead=100,
|
||||
poll_before=10.0, is_queue_full_immediate_attend=False,
|
||||
cleanup_expired_callback=cleanup, write_state_callback=MagicMock(),
|
||||
)
|
||||
assert result is None
|
||||
cleanup.assert_not_called()
|
||||
|
||||
|
||||
def test_time_window_queue_full_skips_not_yet_check():
|
||||
"""队列满立即参与模式 → 即使时间未到也不返回 False"""
|
||||
a = MagicMock()
|
||||
cleanup = MagicMock()
|
||||
now = 1700000000.0
|
||||
ft = now + 500 # 远未到
|
||||
result = h.handle_time_window_early_returns(
|
||||
a, [], now, ft, dynamic_ahead=100,
|
||||
poll_before=10.0, is_queue_full_immediate_attend=True,
|
||||
cleanup_expired_callback=cleanup, write_state_callback=MagicMock(),
|
||||
)
|
||||
# 队列满模式下时间未到也算"在窗口内"
|
||||
assert result is None
|
||||
|
||||
|
||||
# ---- handle_lock_period_same_reservation_check ---- #
|
||||
|
||||
def _make_lock_check_args(**overrides):
|
||||
"""构造 handle_lock_period_same_reservation_check 的默认参数。"""
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = False
|
||||
a.room_pos = 5
|
||||
target = {"pos_seen": 5, "future_ts": 1700000100}
|
||||
base = {
|
||||
"analyser": a,
|
||||
"target": target,
|
||||
"ft": 1700000100.0,
|
||||
"now_ts": 1700000000.0,
|
||||
"focus_until": 0.0,
|
||||
"poll_before": 10.0,
|
||||
"dynamic_ahead": 100,
|
||||
"room_pos": 5,
|
||||
"reservation_focus_until_ts_ref": [0.0],
|
||||
"reservation_after_action_pending_ref": [False],
|
||||
"write_state_callback": MagicMock(),
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def test_lock_check_no_lock_period_returns_none():
|
||||
args = _make_lock_check_args(focus_until=0.0)
|
||||
assert h.handle_lock_period_same_reservation_check(**args) is None
|
||||
|
||||
|
||||
def test_lock_check_queue_full_mode_returns_none():
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = True
|
||||
args = _make_lock_check_args(
|
||||
focus_until=1700000050.0, # 锁定期内
|
||||
analyser=a,
|
||||
)
|
||||
args["analyser"].room_pos = 5
|
||||
assert h.handle_lock_period_same_reservation_check(**args) is None
|
||||
|
||||
|
||||
def test_lock_check_different_reservation_returns_false():
|
||||
"""锁定期内但不是当前预约 → False"""
|
||||
args = _make_lock_check_args(
|
||||
focus_until=1700000050.0, # 远不是 1700000100 + 10 = 1700000110
|
||||
ft=1700000100.0,
|
||||
poll_before=10.0,
|
||||
)
|
||||
assert h.handle_lock_period_same_reservation_check(**args) is False
|
||||
|
||||
|
||||
def test_lock_check_same_reservation_at_target_in_window_returns_true():
|
||||
"""同一预约 + 已在目标位置 + 时间窗口内 → True"""
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = False
|
||||
a.room_pos = 5
|
||||
write_cb = MagicMock()
|
||||
args = _make_lock_check_args(
|
||||
analyser=a,
|
||||
focus_until=1700000110.0, # = ft + poll_before = 1700000100 + 10
|
||||
ft=1700000100.0,
|
||||
now_ts=1700000050.0, # 在窗口内 [ft-100=1700000000, ft+10=1700000110]
|
||||
write_state_callback=write_cb,
|
||||
)
|
||||
result = h.handle_lock_period_same_reservation_check(**args)
|
||||
assert result is True
|
||||
write_cb.assert_called_once()
|
||||
assert args["reservation_focus_until_ts_ref"][0] == 1700000110.0
|
||||
assert args["reservation_after_action_pending_ref"][0] is True
|
||||
|
||||
|
||||
def test_lock_check_same_reservation_at_target_window_not_yet_returns_false():
|
||||
"""同一预约 + 已在目标位置 + 时间窗口未到 → False(清除待处理标志)"""
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = False
|
||||
a.room_pos = 5
|
||||
args = _make_lock_check_args(
|
||||
analyser=a,
|
||||
focus_until=1700000110.0,
|
||||
ft=1700000100.0,
|
||||
now_ts=1699999800.0, # 在窗口前 [1700000000-100, 1700000110]
|
||||
reservation_after_action_pending_ref=[True],
|
||||
)
|
||||
result = h.handle_lock_period_same_reservation_check(**args)
|
||||
assert result is False
|
||||
assert args["reservation_after_action_pending_ref"][0] is False
|
||||
|
||||
|
||||
def test_lock_check_same_reservation_not_at_target_returns_none():
|
||||
"""同一预约 + 不在目标位置 → None(让主流程继续走时间窗口检查)"""
|
||||
a = MagicMock()
|
||||
a.queue_full_waiting_at_earliest = False
|
||||
a.room_pos = 10 # 不等于 target.pos_seen=5
|
||||
args = _make_lock_check_args(
|
||||
analyser=a,
|
||||
focus_until=1700000110.0,
|
||||
ft=1700000100.0,
|
||||
room_pos=10,
|
||||
)
|
||||
result = h.handle_lock_period_same_reservation_check(**args)
|
||||
assert result is None
|
||||
|
||||
|
||||
# ---- log_entering_attend_window ---- #
|
||||
|
||||
def test_log_entering_attend_window_writes_one_line():
|
||||
a = MagicMock()
|
||||
h.log_entering_attend_window(
|
||||
a, ft=1700000100.0, now_ts=1700000050.0,
|
||||
room_pos=5, queue_len=3, dynamic_ahead=100, est_back_times=2, poll_before=10.0,
|
||||
)
|
||||
a._log_kv.assert_called_once()
|
||||
_, kwargs = a._log_kv.call_args
|
||||
assert kwargs["queue_len"] == 3
|
||||
assert kwargs["est_back_times"] == 2
|
||||
|
||||
|
||||
def test_log_entering_attend_window_swallows_exception():
|
||||
a = MagicMock()
|
||||
a._log_kv.side_effect = RuntimeError("boom")
|
||||
h.log_entering_attend_window(
|
||||
a, ft=0, now_ts=0, room_pos=0, queue_len=0,
|
||||
dynamic_ahead=0, est_back_times=0, poll_before=0,
|
||||
)
|
||||
|
||||
|
||||
# ---- execute_seek_reservation_callback ---- #
|
||||
|
||||
def test_execute_seek_callback_returns_true():
|
||||
a = MagicMock()
|
||||
cb = MagicMock(return_value=True)
|
||||
target = {"pos_seen": 5}
|
||||
result = h.execute_seek_reservation_callback(
|
||||
a, target, current_room_pos=10, target_pos=5, pos_diff=5,
|
||||
seek_reservation_room_callback=cb,
|
||||
)
|
||||
assert result is True
|
||||
cb.assert_called_once_with(target)
|
||||
|
||||
|
||||
def test_execute_seek_callback_returns_false():
|
||||
a = MagicMock()
|
||||
cb = MagicMock(return_value=False)
|
||||
result = h.execute_seek_reservation_callback(
|
||||
a, {}, 0, 0, 0, cb,
|
||||
)
|
||||
assert result is False
|
||||
|
||||
|
||||
def test_execute_seek_callback_exception_returns_false():
|
||||
a = MagicMock()
|
||||
cb = MagicMock(side_effect=RuntimeError("boom"))
|
||||
result = h.execute_seek_reservation_callback(
|
||||
a, {}, 0, 0, 0, cb,
|
||||
)
|
||||
assert result is False
|
||||
# 应记录异常日志
|
||||
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
|
||||
assert any("执行回退时发生异常" in m for m in msgs)
|
||||
|
||||
|
||||
# ---- wait_for_live_room_load_after_back ---- #
|
||||
|
||||
def test_wait_for_live_room_load_uses_default(monkeypatch):
|
||||
a = MagicMock()
|
||||
a.reservation_back_verify_wait_seconds = 5.0
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
h.wait_for_live_room_load_after_back(a)
|
||||
a.operation.delay.assert_called_once_with(5.0)
|
||||
|
||||
|
||||
def test_wait_for_live_room_load_clamps_below_min(monkeypatch):
|
||||
a = MagicMock()
|
||||
a.reservation_back_verify_wait_seconds = 0.05 # < 0.1
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
h.wait_for_live_room_load_after_back(a)
|
||||
a.operation.delay.assert_called_once_with(0.1)
|
||||
|
||||
|
||||
def test_wait_for_live_room_load_clamps_above_max(monkeypatch):
|
||||
a = MagicMock()
|
||||
a.reservation_back_verify_wait_seconds = 100.0 # > 10
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
h.wait_for_live_room_load_after_back(a)
|
||||
a.operation.delay.assert_called_once_with(10.0)
|
||||
|
||||
|
||||
def test_wait_for_live_room_load_falls_back_to_sleep(monkeypatch):
|
||||
a = MagicMock()
|
||||
a.reservation_back_verify_wait_seconds = 5.0
|
||||
a.operation.delay.side_effect = RuntimeError("boom")
|
||||
sleep_called = []
|
||||
monkeypatch.setattr("time.sleep", lambda s: sleep_called.append(s))
|
||||
h.wait_for_live_room_load_after_back(a)
|
||||
# 异常时回退到 time.sleep
|
||||
assert 5.0 in sleep_called
|
||||
|
||||
|
||||
# ---- log_back_success_pre_verify ---- #
|
||||
|
||||
def test_log_back_success_pre_verify_writes_one_line():
|
||||
a = MagicMock()
|
||||
target = {"pos_seen": 5}
|
||||
h.log_back_success_pre_verify(
|
||||
a, target, "标题", "原始", "内容", 100.0, 7,
|
||||
)
|
||||
a._log_kv.assert_called_once()
|
||||
_, kwargs = a._log_kv.call_args
|
||||
assert kwargs["target_pos"] == 5
|
||||
assert kwargs["target_value_yuan"] == 100.0
|
||||
assert kwargs["current_room_pos"] == 7
|
||||
|
||||
|
||||
def test_log_back_success_swallows_exception():
|
||||
a = MagicMock()
|
||||
a._log_kv.side_effect = RuntimeError("boom")
|
||||
h.log_back_success_pre_verify(a, {}, "", "", "", 0.0, 0)
|
||||
|
||||
|
||||
# ---- log_back_failure_and_finish ---- #
|
||||
|
||||
def test_log_back_failure_writes_logs_and_calls_write_state():
|
||||
a = MagicMock()
|
||||
write_cb = MagicMock()
|
||||
h.log_back_failure_and_finish(
|
||||
a, {"pos_seen": 5}, ft=time.time() + 100, now_ts=time.time(),
|
||||
room_pos=3, start_time=time.time() - 1.0, write_state_callback=write_cb,
|
||||
)
|
||||
write_cb.assert_called_once()
|
||||
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
|
||||
assert any("回退到预约直播间失败" in m for m in msgs)
|
||||
assert any("返回结果" in m for m in msgs)
|
||||
|
||||
|
||||
def test_log_back_failure_swallows_write_state_exception():
|
||||
a = MagicMock()
|
||||
write_cb = MagicMock(side_effect=RuntimeError("boom"))
|
||||
h.log_back_failure_and_finish(
|
||||
a, {}, ft=0, now_ts=0, room_pos=0,
|
||||
start_time=time.time(), write_state_callback=write_cb,
|
||||
)
|
||||
|
||||
|
||||
# ---- handle_verify_failure_retry_via_mapping ---- #
|
||||
|
||||
def test_verify_retry_seek_callback_succeeds_returns_true():
|
||||
"""二次回退 seek 成功 → 设置锁定期 + return True"""
|
||||
a = MagicMock()
|
||||
target = {"pos_seen": 5, "future_ts": 1700000100}
|
||||
focus_ref = [0.0]
|
||||
pending_ref = [False]
|
||||
write_cb = MagicMock()
|
||||
seek_cb = MagicMock(return_value=True)
|
||||
|
||||
# _resolve_*_via_mapping 都返回 None → mapped_pos_diff 不计算 → should_retry_seek=True
|
||||
# 然后调用 seek_cb(updated_target) 返回 True
|
||||
result = h.handle_verify_failure_retry_via_mapping(
|
||||
a, target, "标题", "原始", ft=1700000100.0, poll_before=10.0,
|
||||
reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=pending_ref,
|
||||
seek_reservation_room_callback=seek_cb,
|
||||
write_state_callback=write_cb,
|
||||
)
|
||||
assert result is True
|
||||
assert focus_ref[0] == 1700000110.0
|
||||
assert pending_ref[0] is True
|
||||
seek_cb.assert_called_once()
|
||||
write_cb.assert_called_once()
|
||||
|
||||
|
||||
def test_verify_retry_seek_callback_fails_returns_false():
|
||||
"""二次回退 seek 失败 → 清理标志 + return False"""
|
||||
a = MagicMock()
|
||||
target = {"pos_seen": 5}
|
||||
focus_ref = [12345.0] # 已设置的锁定期
|
||||
pending_ref = [True]
|
||||
write_cb = MagicMock()
|
||||
seek_cb = MagicMock(return_value=False)
|
||||
|
||||
result = h.handle_verify_failure_retry_via_mapping(
|
||||
a, target, "标题", "原始", ft=1700000100.0, poll_before=10.0,
|
||||
reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=pending_ref,
|
||||
seek_reservation_room_callback=seek_cb,
|
||||
write_state_callback=write_cb,
|
||||
)
|
||||
assert result is False
|
||||
# 清理了标志
|
||||
assert focus_ref[0] == 0.0
|
||||
assert pending_ref[0] is False
|
||||
write_cb.assert_called_once()
|
||||
|
||||
|
||||
def test_verify_retry_seek_exception_returns_false():
|
||||
"""seek_callback 抛错 → ok2=False → return False"""
|
||||
a = MagicMock()
|
||||
target = {"pos_seen": 5}
|
||||
focus_ref = [0.0]
|
||||
pending_ref = [False]
|
||||
seek_cb = MagicMock(side_effect=RuntimeError("boom"))
|
||||
result = h.handle_verify_failure_retry_via_mapping(
|
||||
a, target, "", "", ft=1700000100.0, poll_before=10.0,
|
||||
reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=pending_ref,
|
||||
seek_reservation_room_callback=seek_cb,
|
||||
write_state_callback=MagicMock(),
|
||||
)
|
||||
assert result is False
|
||||
|
||||
|
||||
def test_verify_retry_no_seek_callback_returns_false():
|
||||
"""seek_callback=None → ok2=False → return False"""
|
||||
a = MagicMock()
|
||||
result = h.handle_verify_failure_retry_via_mapping(
|
||||
a, {"pos_seen": 0}, "", "", ft=0, poll_before=0,
|
||||
reservation_focus_until_ts_ref=[0.0],
|
||||
reservation_after_action_pending_ref=[False],
|
||||
seek_reservation_room_callback=None,
|
||||
write_state_callback=MagicMock(),
|
||||
)
|
||||
assert result is False
|
||||
|
||||
|
||||
# ---- _decide_retry_seek ---- #
|
||||
|
||||
def test_decide_retry_seek_no_mapping_returns_true():
|
||||
"""mapped_current_pos=None → 默认 True"""
|
||||
a = MagicMock()
|
||||
assert h._decide_retry_seek(a, {}, None, 5, 0) is True
|
||||
assert h._decide_retry_seek(a, {}, 5, None, 0) is True
|
||||
|
||||
|
||||
def test_decide_retry_seek_diff_nonzero_returns_true():
|
||||
a = MagicMock()
|
||||
assert h._decide_retry_seek(a, {}, 3, 7, 0) is True
|
||||
|
||||
|
||||
def test_decide_retry_seek_diff_zero_with_correction_returns_true():
|
||||
"""diff=0 但回退前位置 != 目标位置 → 启用方向提示并 return True"""
|
||||
a = MagicMock()
|
||||
target = {}
|
||||
# mapped_current=mapped_target=5,但 room_pos_before=10 != 5
|
||||
result = h._decide_retry_seek(a, target, 5, 5, 10)
|
||||
assert result is True
|
||||
assert target["_seek_direction_hint"] == "down" # 10 > 5
|
||||
|
||||
|
||||
def test_decide_retry_seek_diff_zero_at_correct_pos_returns_false():
|
||||
"""diff=0 且回退前位置 == 目标位置 → 跳过二次回退"""
|
||||
a = MagicMock()
|
||||
assert h._decide_retry_seek(a, {}, 5, 5, 5) is False
|
||||
|
||||
|
||||
def test_decide_retry_seek_correction_up_direction():
|
||||
"""room_pos_before < mapped_target → direction_hint = up"""
|
||||
a = MagicMock()
|
||||
target = {}
|
||||
h._decide_retry_seek(a, target, 5, 5, 2) # 2 < 5
|
||||
assert target["_seek_direction_hint"] == "up"
|
||||
|
||||
|
||||
# ---- enter_lock_period_and_log_success ---- #
|
||||
|
||||
def test_enter_lock_period_sets_focus_and_pending():
|
||||
a = MagicMock()
|
||||
focus_ref = [0.0]
|
||||
pending_ref = [False]
|
||||
write_cb = MagicMock()
|
||||
h.enter_lock_period_and_log_success(
|
||||
a, target={"pos_seen": 5}, target_room_title="标题", target_room_title_raw="raw",
|
||||
target_content="内容", target_value=99.9,
|
||||
ft=1700000100.0, now_ts=1700000050.0, poll_before=10.0,
|
||||
start_time=time.time(), reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=pending_ref,
|
||||
write_state_callback=write_cb, now_ts_func=lambda: 1700000050.0,
|
||||
)
|
||||
assert focus_ref[0] == 1700000110.0 # ft + poll_before
|
||||
assert pending_ref[0] is True
|
||||
write_cb.assert_called_once()
|
||||
|
||||
|
||||
def test_enter_lock_period_appends_to_empty_refs():
|
||||
a = MagicMock()
|
||||
focus_ref = []
|
||||
pending_ref = []
|
||||
h.enter_lock_period_and_log_success(
|
||||
a, target={}, target_room_title="", target_room_title_raw="", target_content="",
|
||||
target_value=0.0, ft=1700000100.0, now_ts=0, poll_before=10.0,
|
||||
start_time=time.time(), reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=pending_ref,
|
||||
write_state_callback=MagicMock(), now_ts_func=lambda: 0,
|
||||
)
|
||||
assert focus_ref == [1700000110.0]
|
||||
assert pending_ref == [True]
|
||||
|
||||
|
||||
def test_enter_lock_period_swallows_log_exception():
|
||||
a = MagicMock()
|
||||
a._log_kv.side_effect = RuntimeError("boom")
|
||||
h.enter_lock_period_and_log_success(
|
||||
a, target={}, target_room_title="", target_room_title_raw="", target_content="",
|
||||
target_value=0.0, ft=0, now_ts=0, poll_before=0,
|
||||
start_time=time.time(), reservation_focus_until_ts_ref=[0.0],
|
||||
reservation_after_action_pending_ref=[False],
|
||||
write_state_callback=MagicMock(), now_ts_func=lambda: 0,
|
||||
)
|
||||
@@ -0,0 +1,411 @@
|
||||
"""单元测试:douyin/stage/douyin_stage_helpers.py
|
||||
|
||||
只测纯日志格式化函数 _format_detail_log_fields 的输入→输出映射。
|
||||
更上层的 log_pixel_detection_details / summarize_pixel_state 用 callback
|
||||
桩做行为验证。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time as _time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from douyin.stage import douyin_stage_helpers as h
|
||||
|
||||
|
||||
def test_format_basic_detail():
|
||||
detail = {"detected": True, "method": "pixel"}
|
||||
fields = h._format_detail_log_fields("has_coupon_bg", detail, MagicMock())
|
||||
assert fields["步骤"] == "优惠券背景"
|
||||
assert fields["检测结果"] == "命中"
|
||||
assert fields["检测方法"] == "pixel"
|
||||
|
||||
|
||||
def test_format_unknown_key_falls_back_to_key():
|
||||
detail = {"detected": False, "method": "x"}
|
||||
fields = h._format_detail_log_fields("unknown_key", detail, MagicMock())
|
||||
assert fields["步骤"] == "unknown_key"
|
||||
assert fields["检测结果"] == "未命中"
|
||||
|
||||
|
||||
def test_format_with_template_score():
|
||||
detail = {"detected": True, "method": "tpl", "template_score": 0.876543}
|
||||
fields = h._format_detail_log_fields("has_lucky_draw_result", detail, MagicMock())
|
||||
assert fields["分数"] == 0.8765
|
||||
assert fields["模板匹配分数"] == 0.8765
|
||||
|
||||
|
||||
def test_format_with_confidence_only():
|
||||
detail = {"detected": True, "method": "px", "confidence": 0.5}
|
||||
fields = h._format_detail_log_fields("has_live_room_pixel", detail, MagicMock())
|
||||
assert fields["置信度"] == 0.5
|
||||
assert fields["分数"] == 0.5
|
||||
|
||||
|
||||
def test_format_threshold_none_shows_text():
|
||||
detail = {"detected": False, "method": "x", "effective_threshold": None}
|
||||
fields = h._format_detail_log_fields("has_redpacket_bg", detail, MagicMock())
|
||||
assert fields["阈值"] == "未设置"
|
||||
|
||||
|
||||
def test_format_fudai_detail_with_task_count():
|
||||
analyser = MagicMock()
|
||||
analyser.fudai_detail_template_threshold = 0.6
|
||||
analyser.fudai_template_match_threshold = 0.7
|
||||
detail = {"detected": True, "method": "tpl", "task_count": 3}
|
||||
fields = h._format_detail_log_fields("has_fudai_detail", detail, analyser)
|
||||
assert fields["任务数量"] == 3
|
||||
assert fields["配置阈值"] == 0.6
|
||||
|
||||
|
||||
def test_format_fudai_detail_missing_task_count():
|
||||
detail = {"detected": False, "method": "tpl"}
|
||||
fields = h._format_detail_log_fields("has_fudai_detail", detail, MagicMock())
|
||||
assert fields["任务数量"] == "未获取"
|
||||
|
||||
|
||||
def test_log_pixel_detection_details_iterates_all_keys():
|
||||
log = MagicMock()
|
||||
pixel_details = {
|
||||
"has_coupon_bg": {"detected": True, "method": "px"},
|
||||
"has_redpacket_bg": {"detected": False, "method": "px"},
|
||||
}
|
||||
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
|
||||
assert log.call_count == 2 # 一个 key 一次
|
||||
|
||||
|
||||
def test_log_pixel_detection_details_warns_on_task_count_mismatch():
|
||||
"""has_fudai_detail 检测为 False 但 task_count > 0 时应额外告警"""
|
||||
log = MagicMock()
|
||||
pixel_details = {
|
||||
"has_fudai_detail": {"detected": False, "method": "tpl", "task_count": 5},
|
||||
}
|
||||
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
|
||||
# 一次告警 + 一次普通日志 = 2 次
|
||||
assert log.call_count == 2
|
||||
|
||||
|
||||
def test_log_pixel_detection_details_handles_empty():
|
||||
log = MagicMock()
|
||||
h.log_pixel_detection_details({}, MagicMock(), log)
|
||||
assert log.call_count == 0
|
||||
|
||||
|
||||
def test_summarize_pixel_state_writes_one_log_line():
|
||||
log = MagicMock()
|
||||
h.summarize_pixel_state({"has_live_room_pixel": True}, 12.3, log)
|
||||
assert log.call_count == 1
|
||||
args, kwargs = log.call_args
|
||||
assert args[0] == "像素状态(并行检测完成)"
|
||||
assert kwargs["直播间图标像素检测"] is True
|
||||
|
||||
|
||||
def test_summarize_pixel_state_swallows_exceptions():
|
||||
"""log_callback 抛错也不应传播"""
|
||||
bad_log = MagicMock(side_effect=RuntimeError("boom"))
|
||||
h.summarize_pixel_state({}, 0.0, bad_log)
|
||||
|
||||
|
||||
# ---- detect_lottery_result_popup ---- #
|
||||
|
||||
def test_detect_lottery_result_matched_returns_true():
|
||||
a = MagicMock()
|
||||
log = MagicMock()
|
||||
log_summary = MagicMock()
|
||||
log_sep = MagicMock()
|
||||
from douyin.utils import douyin_helpers
|
||||
|
||||
with patch.object(
|
||||
douyin_helpers.HelperFunctions,
|
||||
"check_lottery_result_by_ocr",
|
||||
return_value=True,
|
||||
):
|
||||
matched, stage, reason = h.detect_lottery_result_popup(
|
||||
a, _time.time(), log, log_summary, log_sep
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "FUDai_RESULT"
|
||||
|
||||
|
||||
def test_detect_lottery_result_not_matched_returns_false():
|
||||
a = MagicMock()
|
||||
log = MagicMock()
|
||||
log_summary = MagicMock()
|
||||
log_sep = MagicMock()
|
||||
from douyin.utils import douyin_helpers
|
||||
|
||||
with patch.object(
|
||||
douyin_helpers.HelperFunctions,
|
||||
"check_lottery_result_by_ocr",
|
||||
return_value=False,
|
||||
):
|
||||
matched, _, _ = h.detect_lottery_result_popup(
|
||||
a, _time.time(), log, log_summary, log_sep
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
def test_detect_lottery_result_exception_returns_false():
|
||||
a = MagicMock()
|
||||
log = MagicMock()
|
||||
log_summary = MagicMock()
|
||||
log_sep = MagicMock()
|
||||
from douyin.utils import douyin_helpers
|
||||
|
||||
with patch.object(
|
||||
douyin_helpers.HelperFunctions,
|
||||
"check_lottery_result_by_ocr",
|
||||
side_effect=RuntimeError("boom"),
|
||||
):
|
||||
matched, _, _ = h.detect_lottery_result_popup(
|
||||
a, _time.time(), log, log_summary, log_sep
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
# ---- detect_shopping_redpacket_popup ---- #
|
||||
|
||||
def test_detect_shopping_redpacket_keyword_match():
|
||||
"""OCR 文本含关键词 → 命中"""
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = "邀你抢红包啦"
|
||||
log = MagicMock()
|
||||
log_summary = MagicMock()
|
||||
log_sep = MagicMock()
|
||||
matched, stage, _ = h.detect_shopping_redpacket_popup(
|
||||
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
|
||||
lambda _x, _y: "preprocessed", log, log_summary, log_sep,
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "SHOPPING_REDPACKET_POPUP"
|
||||
|
||||
|
||||
def test_detect_shopping_redpacket_no_keyword_returns_false():
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = "随便的文本"
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_shopping_redpacket_popup(
|
||||
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
|
||||
lambda _x, _y: "p", log, MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
def test_detect_shopping_redpacket_ocr_exception_returns_false():
|
||||
a = MagicMock()
|
||||
a.cut_pic.side_effect = RuntimeError("boom")
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_shopping_redpacket_popup(
|
||||
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
|
||||
lambda _x, _y: "p", log, MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
# ---- detect_redpacket_ocr_recheck_outside_live ---- #
|
||||
|
||||
def test_redpacket_recheck_no_pixel_bg_returns_false():
|
||||
"""像素未命中红包背景 → 直接返回 False,不做 OCR"""
|
||||
a = MagicMock()
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
|
||||
a, {"has_redpacket_bg": False}, {},
|
||||
(10, 20, 30, 40), _time.time(), 5.0, True,
|
||||
lambda _x, _y: "p", log, MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
a.cut_pic.assert_not_called()
|
||||
|
||||
|
||||
def test_redpacket_recheck_keyword_match_returns_true():
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = ("邀你抢红包", None)
|
||||
a.shopping_redpacket_ocr_confidence_threshold = 0.99
|
||||
log = MagicMock()
|
||||
matched, stage, _ = h.detect_redpacket_ocr_recheck_outside_live(
|
||||
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
|
||||
(10, 20, 30, 40), _time.time(), 30.0, True,
|
||||
lambda _x, _y: "p", log, MagicMock(),
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "SHOPPING_REDPACKET_POPUP"
|
||||
|
||||
|
||||
def test_redpacket_recheck_high_confidence_match():
|
||||
"""无关键词但置信度高 → 命中"""
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = (
|
||||
"无关文本",
|
||||
{"avg_confidence": 0.9, "max_confidence": 0.95},
|
||||
)
|
||||
a.shopping_redpacket_ocr_confidence_threshold = 0.9
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
|
||||
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
|
||||
(10, 20, 30, 40), _time.time(), 30.0, False,
|
||||
lambda _x, _y: "p", log, MagicMock(),
|
||||
)
|
||||
assert matched is True
|
||||
|
||||
|
||||
def test_redpacket_recheck_no_match_returns_false():
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = (
|
||||
"无关文本",
|
||||
{"avg_confidence": 0.3, "max_confidence": 0.4},
|
||||
)
|
||||
a.shopping_redpacket_ocr_confidence_threshold = 0.9
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
|
||||
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
|
||||
(10, 20, 30, 40), _time.time(), 30.0, False,
|
||||
lambda _x, _y: "p", log, MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
def test_redpacket_recheck_exception_returns_false():
|
||||
a = MagicMock()
|
||||
a.cut_pic.side_effect = RuntimeError("adb")
|
||||
log = MagicMock()
|
||||
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
|
||||
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
|
||||
(10, 20, 30, 40), _time.time(), 30.0, True,
|
||||
lambda _x, _y: "p", log, MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
# ---- detect_recommend_follow_live_tabs ---- #
|
||||
|
||||
def _make_tab_analyser(recommend_text="", follow_text="", live_text=""):
|
||||
"""构造一个 mock analyser,按 cut_pic 的 crop_name 返回不同 OCR 文本。"""
|
||||
a = MagicMock()
|
||||
text_map = {
|
||||
"推荐页标签栏": recommend_text,
|
||||
"关注列表标签": follow_text,
|
||||
"直播列表标签": live_text,
|
||||
}
|
||||
|
||||
def fake_analyse(name, mode):
|
||||
# name 经过 preprocess_for_ocr 处理后我们让它直接返回 crop_name
|
||||
return text_map.get(name, "")
|
||||
|
||||
a.operation.analyse_pic_word.side_effect = fake_analyse
|
||||
return a
|
||||
|
||||
|
||||
def test_recommend_follow_live_tabs_recommend_match():
|
||||
a = _make_tab_analyser(recommend_text="推荐 关注 直播")
|
||||
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
|
||||
matched, stage, _ = h.detect_recommend_follow_live_tabs(
|
||||
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
|
||||
_time.time(), 30.0, False,
|
||||
lambda _a, name: name, log, log_sum, log_sep,
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "RECOMMEND_PAGE"
|
||||
|
||||
|
||||
def test_recommend_follow_live_tabs_follow_match():
|
||||
a = _make_tab_analyser(recommend_text="关注", follow_text="关注")
|
||||
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
|
||||
matched, stage, _ = h.detect_recommend_follow_live_tabs(
|
||||
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
|
||||
_time.time(), 30.0, False,
|
||||
lambda _a, name: name, log, log_sum, log_sep,
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "FOLLOW_LIST"
|
||||
|
||||
|
||||
def test_recommend_follow_live_tabs_live_match():
|
||||
a = _make_tab_analyser(recommend_text="直播", live_text="正在直播")
|
||||
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
|
||||
matched, stage, _ = h.detect_recommend_follow_live_tabs(
|
||||
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
|
||||
_time.time(), 30.0, False,
|
||||
lambda _a, name: name, log, log_sum, log_sep,
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "LIVE_LIST"
|
||||
|
||||
|
||||
def test_recommend_follow_live_tabs_no_match_returns_false():
|
||||
a = _make_tab_analyser(recommend_text="无关文本")
|
||||
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
|
||||
matched, _, _ = h.detect_recommend_follow_live_tabs(
|
||||
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
|
||||
_time.time(), 30.0, False,
|
||||
lambda _a, name: name, log, log_sum, log_sep,
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
def test_recommend_follow_live_tabs_outer_exception_returns_false():
|
||||
a = MagicMock()
|
||||
a.cut_pic.side_effect = RuntimeError("boom")
|
||||
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
|
||||
matched, _, _ = h.detect_recommend_follow_live_tabs(
|
||||
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
|
||||
_time.time(), 30.0, False,
|
||||
lambda _a, name: name, log, log_sum, log_sep,
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
# ---- detect_suspicious_popup_via_ocr ---- #
|
||||
|
||||
def test_suspicious_popup_no_pixel_returns_false():
|
||||
"""has_coupon_bg=False 且 has_redpacket_bg=False → 直接返回 False"""
|
||||
a = MagicMock()
|
||||
matched, _, _ = h.detect_suspicious_popup_via_ocr(
|
||||
a, {"has_coupon_bg": False, "has_redpacket_bg": False},
|
||||
(1, 2, 3, 4), (5, 6, 7, 8),
|
||||
_time.time(), 30.0, 5.0, False,
|
||||
lambda _a, name: name,
|
||||
MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
|
||||
|
||||
def test_suspicious_popup_coupon_match():
|
||||
"""coupon_bg=True + OCR 命中"开心收下" → 返回 COUPON_POPUP"""
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = "请开心收下你的红包"
|
||||
matched, stage, _ = h.detect_suspicious_popup_via_ocr(
|
||||
a, {"has_coupon_bg": True, "has_redpacket_bg": False},
|
||||
(1, 2, 3, 4), (5, 6, 7, 8),
|
||||
_time.time(), 30.0, 5.0, False, # enable_ocr_mode1=False 走简单路径
|
||||
lambda _a, name: name,
|
||||
MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "COUPON_POPUP"
|
||||
|
||||
|
||||
def test_suspicious_popup_redpacket_match():
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = "邀你抢红包"
|
||||
matched, stage, _ = h.detect_suspicious_popup_via_ocr(
|
||||
a, {"has_coupon_bg": False, "has_redpacket_bg": True},
|
||||
(1, 2, 3, 4), (5, 6, 7, 8),
|
||||
_time.time(), 30.0, 5.0, False,
|
||||
lambda _a, name: name,
|
||||
MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is True
|
||||
assert stage == "SHOPPING_REDPACKET_POPUP"
|
||||
|
||||
|
||||
def test_suspicious_popup_no_keyword_returns_false():
|
||||
a = MagicMock()
|
||||
a.operation.analyse_pic_word.return_value = "无关文本"
|
||||
matched, _, _ = h.detect_suspicious_popup_via_ocr(
|
||||
a, {"has_coupon_bg": True, "has_redpacket_bg": True},
|
||||
(1, 2, 3, 4), (5, 6, 7, 8),
|
||||
_time.time(), 30.0, 5.0, False,
|
||||
lambda _a, name: name,
|
||||
MagicMock(), MagicMock(),
|
||||
)
|
||||
assert matched is False
|
||||
@@ -0,0 +1,37 @@
|
||||
"""单元测试:douyin/fudai/core/fudai_attend_fansclub.py
|
||||
|
||||
只做最小冒烟:能 import + 函数签名正确。
|
||||
完整业务测试需要大量 OCR / ADB / 截图桩,性价比低。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
from douyin.fudai.core import fudai_attend_fansclub
|
||||
|
||||
|
||||
def test_module_import():
|
||||
assert fudai_attend_fansclub is not None
|
||||
|
||||
|
||||
def test_handle_fansclub_branch_signature():
|
||||
fn = fudai_attend_fansclub.handle_fansclub_branch
|
||||
sig = inspect.signature(fn)
|
||||
params = list(sig.parameters.keys())
|
||||
assert params == ["analyser", "attend_button_text"]
|
||||
|
||||
|
||||
def test_handle_fansclub_branch_callable():
|
||||
assert callable(fudai_attend_fansclub.handle_fansclub_branch)
|
||||
|
||||
|
||||
def test_module_only_exports_one_public_fn():
|
||||
"""保持 API 最小化"""
|
||||
public = [
|
||||
x for x in dir(fudai_attend_fansclub)
|
||||
if not x.startswith("_") and not x[0].isupper()
|
||||
]
|
||||
# 排除 import 进来的模块
|
||||
own = [x for x in public if x not in {"os", "time", "path_config", "annotations"}]
|
||||
assert "handle_fansclub_branch" in own
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
"""单元测试:douyin/core/fudai_modules/fudai_image_helpers.py
|
||||
|
||||
只覆盖纯逻辑分支与异常吞噬路径;完整图片读取链路依赖 ADB + 真实 PNG 文件,
|
||||
不在单元测试范围内。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.core.fudai_modules import fudai_image_helpers
|
||||
|
||||
|
||||
def _make_analyser():
|
||||
a = MagicMock()
|
||||
a.device_id = "test"
|
||||
a._run_id = "test_run"
|
||||
a._log_kv = MagicMock()
|
||||
a.operation = MagicMock()
|
||||
a.operation.get_screenshot = MagicMock()
|
||||
return a
|
||||
|
||||
|
||||
def test_capture_roi_no_screenshot_path_returns_empty(monkeypatch):
|
||||
"""screenshot_path 不存在时直接返回空字符串"""
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("os.path.exists", lambda _p: False)
|
||||
result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50)
|
||||
assert result == ""
|
||||
|
||||
|
||||
def test_capture_roi_with_invalid_path_returns_empty(monkeypatch):
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("os.path.exists", lambda _p: False)
|
||||
result = fudai_image_helpers.capture_roi_screenshot(
|
||||
a, "label", 100, 100, 50, screenshot_path="/no/such/file.png"
|
||||
)
|
||||
assert result == ""
|
||||
|
||||
|
||||
def test_capture_roi_outer_exception_swallowed(monkeypatch):
|
||||
"""获取 path_config 抛错时也应吞噬异常并写日志"""
|
||||
a = _make_analyser()
|
||||
# 让 path_config 导入抛错
|
||||
monkeypatch.setattr("os.path.exists", lambda _p: True)
|
||||
with patch.object(
|
||||
fudai_image_helpers, "_read_screenshot_with_validation",
|
||||
side_effect=RuntimeError("boom"),
|
||||
):
|
||||
result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50)
|
||||
assert result == ""
|
||||
# 应记录失败日志
|
||||
a._log_kv.assert_called()
|
||||
|
||||
|
||||
def test_read_screenshot_returns_none_when_path_missing(monkeypatch, tmp_path):
|
||||
"""文件不存在时多次重试后返回 None"""
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
fake_path = str(tmp_path / "no.png")
|
||||
result = fudai_image_helpers._read_screenshot_with_validation(
|
||||
a, fake_path, max_attempts=2
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_read_screenshot_validates_png_header(monkeypatch, tmp_path):
|
||||
"""非 PNG 头时拒绝"""
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
bad_file = tmp_path / "bad.png"
|
||||
bad_file.write_bytes(b"\x00" * 2048)
|
||||
result = fudai_image_helpers._read_screenshot_with_validation(
|
||||
a, str(bad_file), max_attempts=2
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_read_screenshot_validates_iend_tail(monkeypatch, tmp_path):
|
||||
"""PNG 头但缺失 IEND 尾时拒绝"""
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
bad_file = tmp_path / "bad.png"
|
||||
# 有效 PNG header 但没 IEND
|
||||
bad_file.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 2048)
|
||||
result = fudai_image_helpers._read_screenshot_with_validation(
|
||||
a, str(bad_file), max_attempts=2
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_read_screenshot_skips_tiny_file(monkeypatch, tmp_path):
|
||||
"""文件 < 1024 字节时跳过"""
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
tiny = tmp_path / "tiny.png"
|
||||
tiny.write_bytes(b"\x89PNG\r\n\x1a\n") # 8 字节
|
||||
result = fudai_image_helpers._read_screenshot_with_validation(
|
||||
a, str(tiny), max_attempts=2
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_read_screenshot_returns_data_for_valid_png(monkeypatch, tmp_path):
|
||||
"""生成有效 PNG → _read_screenshot_with_validation 返回字节"""
|
||||
from PIL import Image
|
||||
import random
|
||||
|
||||
a = _make_analyser()
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
pic_path = tmp_path / "ok.png"
|
||||
# 用随机像素生成大于 1024 字节的 PNG(白色图压缩后过小被 size guard 拒绝)
|
||||
rng = random.Random(0)
|
||||
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(100 * 100)]
|
||||
img = Image.new("RGB", (100, 100))
|
||||
img.putdata(pixels)
|
||||
img.save(str(pic_path))
|
||||
assert pic_path.stat().st_size >= 1024
|
||||
result = fudai_image_helpers._read_screenshot_with_validation(
|
||||
a, str(pic_path), max_attempts=2
|
||||
)
|
||||
assert result is not None
|
||||
assert result.startswith(b"\x89PNG")
|
||||
assert b"IEND" in result[-512:]
|
||||
|
||||
|
||||
def test_open_image_or_retry_with_valid_data():
|
||||
a = _make_analyser()
|
||||
from PIL import Image
|
||||
|
||||
img = Image.new("RGB", (50, 50), color="white")
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
data = buf.getvalue()
|
||||
result = fudai_image_helpers._open_image_or_retry(a, data, "/tmp/x.png")
|
||||
assert result is not None
|
||||
|
||||
|
||||
def test_open_image_or_retry_unidentified_returns_none():
|
||||
a = _make_analyser()
|
||||
result = fudai_image_helpers._open_image_or_retry(a, b"not_a_png", "/no/path.png")
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_capture_roi_end_to_end_with_real_png(monkeypatch, tmp_path):
|
||||
"""端到端:写一个真实 PNG,capture_roi_screenshot 应返回有效 ROI 路径"""
|
||||
from PIL import Image
|
||||
import random
|
||||
|
||||
a = _make_analyser()
|
||||
|
||||
pic_path = tmp_path / "screenshot.png"
|
||||
rng = random.Random(42)
|
||||
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(200 * 200)]
|
||||
img = Image.new("RGB", (200, 200))
|
||||
img.putdata(pixels)
|
||||
img.save(str(pic_path))
|
||||
|
||||
out_dir = tmp_path / "out"
|
||||
out_dir.mkdir()
|
||||
|
||||
fake_path_config = MagicMock()
|
||||
fake_path_config.get_screenshot_path = lambda: str(pic_path)
|
||||
fake_path_config.get_pic_dir = lambda: str(out_dir)
|
||||
monkeypatch.setattr("douyin.core.path_config", fake_path_config)
|
||||
monkeypatch.setattr("time.sleep", lambda _s: None)
|
||||
|
||||
result = fudai_image_helpers.capture_roi_screenshot(a, "test", 100, 100, 50)
|
||||
assert result
|
||||
assert "roi_test_test_run" in result
|
||||
|
||||
|
||||
# ---- _correlation_score ---- #
|
||||
|
||||
def test_correlation_score_identical_arrays():
|
||||
import numpy as np
|
||||
|
||||
a = np.array([1.0, 2.0, 3.0, 4.0])
|
||||
score = fudai_image_helpers._correlation_score(a, a)
|
||||
assert abs(score - 1.0) < 1e-6
|
||||
|
||||
|
||||
def test_correlation_score_constant_arrays_returns_minus_one():
|
||||
"""相同常数数组 → 范数为 0 → 返回 -1.0"""
|
||||
import numpy as np
|
||||
|
||||
a = np.array([5.0, 5.0, 5.0])
|
||||
b = np.array([5.0, 5.0, 5.0])
|
||||
score = fudai_image_helpers._correlation_score(a, b)
|
||||
assert score == -1.0
|
||||
|
||||
|
||||
def test_correlation_score_anticorrelated():
|
||||
import numpy as np
|
||||
|
||||
a = np.array([1.0, 2.0, 3.0])
|
||||
b = np.array([3.0, 2.0, 1.0])
|
||||
score = fudai_image_helpers._correlation_score(a, b)
|
||||
assert abs(score - (-1.0)) < 1e-6
|
||||
|
||||
|
||||
# ---- match_icon_template ---- #
|
||||
|
||||
def test_match_icon_missing_roi_returns_false():
|
||||
a = _make_analyser()
|
||||
detected, score = fudai_image_helpers.match_icon_template(
|
||||
a, "/no/such/roi.png", "/no/such/tpl.png"
|
||||
)
|
||||
assert detected is False
|
||||
assert score == 0.0
|
||||
|
||||
|
||||
def test_match_icon_empty_paths_returns_false():
|
||||
a = _make_analyser()
|
||||
assert fudai_image_helpers.match_icon_template(a, "", "x") == (False, 0.0)
|
||||
assert fudai_image_helpers.match_icon_template(a, "x", "") == (False, 0.0)
|
||||
|
||||
|
||||
def test_match_icon_same_image_high_score(tmp_path):
|
||||
"""同一张图作为 ROI 与模板 → 完美匹配,score=1.0"""
|
||||
from PIL import Image
|
||||
import random
|
||||
|
||||
a = _make_analyser()
|
||||
rng = random.Random(0)
|
||||
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(60 * 60)]
|
||||
img = Image.new("RGB", (60, 60))
|
||||
img.putdata(pixels)
|
||||
same = tmp_path / "same.png"
|
||||
img.save(str(same))
|
||||
detected, score = fudai_image_helpers.match_icon_template(
|
||||
a, str(same), str(same), threshold=0.5
|
||||
)
|
||||
assert detected is True
|
||||
assert abs(score - 1.0) < 1e-3
|
||||
|
||||
|
||||
def test_match_icon_template_larger_than_roi_gets_resized(tmp_path):
|
||||
"""模板比 ROI 大 → 自动缩放,仍能比对"""
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
roi = Image.new("RGB", (50, 50), color="white")
|
||||
tpl = Image.new("RGB", (200, 200), color="white")
|
||||
roi_path = tmp_path / "roi.png"
|
||||
tpl_path = tmp_path / "tpl.png"
|
||||
roi.save(str(roi_path))
|
||||
tpl.save(str(tpl_path))
|
||||
# 不抛错就算通过;都是白色范数为 0,会回到 -1
|
||||
detected, score = fudai_image_helpers.match_icon_template(
|
||||
a, str(roi_path), str(tpl_path)
|
||||
)
|
||||
# 白色图分母为 0 → score=-1,detected=False
|
||||
assert detected is False
|
||||
|
||||
|
||||
def test_match_icon_threshold_param_overrides_attr(tmp_path):
|
||||
"""threshold=0 时即使分数较低也判定为 detected"""
|
||||
from PIL import Image
|
||||
import random
|
||||
|
||||
a = _make_analyser()
|
||||
a.yanghao_icon_match_threshold = 0.99 # 默认很高
|
||||
rng = random.Random(0)
|
||||
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(40 * 40)]
|
||||
img = Image.new("RGB", (40, 40))
|
||||
img.putdata(pixels)
|
||||
same = tmp_path / "same.png"
|
||||
img.save(str(same))
|
||||
# threshold=0 → 任何 score >= 0 都算命中
|
||||
detected, _ = fudai_image_helpers.match_icon_template(
|
||||
a, str(same), str(same), threshold=0.0
|
||||
)
|
||||
assert detected is True
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,65 @@
|
||||
"""单元测试:gui/components/mapping_table_helpers.py
|
||||
|
||||
只测 compute_card_layout(纯函数,无 tk 依赖),其他 tk-依赖函数靠
|
||||
mapping_table.py 整体 import 冒烟覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from gui.components import mapping_table_helpers as h
|
||||
|
||||
|
||||
def test_compute_card_layout_narrow_canvas_one_column():
|
||||
cols, w = h.compute_card_layout(canvas_width=400)
|
||||
assert cols == 1
|
||||
assert w >= 220
|
||||
|
||||
|
||||
def test_compute_card_layout_wide_canvas_three_columns_capped():
|
||||
cols, w = h.compute_card_layout(canvas_width=2000)
|
||||
assert cols == 3
|
||||
assert w >= 220
|
||||
|
||||
|
||||
def test_compute_card_layout_medium_canvas():
|
||||
cols, w = h.compute_card_layout(canvas_width=900)
|
||||
assert 1 <= cols <= 3
|
||||
assert w >= 220
|
||||
|
||||
|
||||
def test_compute_card_layout_zero_width_falls_back_to_one_column():
|
||||
cols, w = h.compute_card_layout(canvas_width=0)
|
||||
assert cols == 1
|
||||
|
||||
|
||||
def test_compute_card_layout_respects_max_columns_param():
|
||||
cols, _ = h.compute_card_layout(canvas_width=10000, max_columns=5)
|
||||
assert cols == 5
|
||||
|
||||
|
||||
def test_compute_card_layout_min_card_width_param():
|
||||
"""min_card_w 越大,能放下的列数越少"""
|
||||
cols_a, _ = h.compute_card_layout(canvas_width=900, min_card_w=200)
|
||||
cols_b, _ = h.compute_card_layout(canvas_width=900, min_card_w=600)
|
||||
assert cols_a >= cols_b
|
||||
|
||||
|
||||
def test_open_entry_detail_window_empty_content_no_crash():
|
||||
"""空 content 应直接 return 不创建窗口(不需要 tk root)"""
|
||||
h.open_entry_detail_window(root=None, content="", scrolled_text_cls=None)
|
||||
|
||||
|
||||
def test_module_public_api():
|
||||
"""API 表面:保护重命名/删除时主调用方能跟上"""
|
||||
public = {x for x in dir(h) if not x.startswith("_") and not x[0].isupper()}
|
||||
expected = {
|
||||
"compute_card_layout",
|
||||
"make_card_event_handlers",
|
||||
"open_entry_detail_window",
|
||||
"render_card_labels",
|
||||
"set_card_bg",
|
||||
}
|
||||
# 至少暴露这些
|
||||
assert expected.issubset(public)
|
||||
@@ -0,0 +1,287 @@
|
||||
"""单元测试:douyin/detection/detection_pkg/template_match_helpers.py
|
||||
|
||||
只覆盖纯逻辑路径与异常吞噬:
|
||||
- 模板文件不存在 → 返回 (False, None)
|
||||
- OpenCV 导入失败 / 模板读取失败 → 异常吞噬
|
||||
- 命中/未命中分数对比
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.detection.detection_pkg import template_match_helpers as h
|
||||
|
||||
|
||||
def _make_analyser():
|
||||
a = MagicMock()
|
||||
a._log_kv = MagicMock()
|
||||
a.fudai_template_match_threshold = 0.7
|
||||
return a
|
||||
|
||||
|
||||
def test_template_match_missing_template_file_returns_false(monkeypatch, tmp_path):
|
||||
a = _make_analyser()
|
||||
fake_assets = tmp_path / "no_assets"
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_assets_dir",
|
||||
lambda: str(fake_assets),
|
||||
)
|
||||
pic = MagicMock()
|
||||
detected, x = h.template_match_fallback(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0, loop=0,
|
||||
)
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
def test_template_match_outer_exception_swallowed(monkeypatch):
|
||||
a = _make_analyser()
|
||||
# 让 cv2 import 抛错触发外层 except
|
||||
monkeypatch.setitem(__import__("sys").modules, "cv2", None)
|
||||
pic = MagicMock()
|
||||
detected, x = h.template_match_fallback(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0, loop=0,
|
||||
)
|
||||
# cv2=None 时 .imread 调用抛 AttributeError → 被吞噬
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
def test_template_match_threshold_attr_not_a_number(monkeypatch, tmp_path):
|
||||
"""threshold 异常时回退到 0.7"""
|
||||
a = _make_analyser()
|
||||
a.fudai_template_match_threshold = "not_a_number"
|
||||
fake_assets = tmp_path / "assets"
|
||||
fake_assets.mkdir()
|
||||
(fake_assets / "fudai.png").write_bytes(b"not_a_real_png")
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_assets_dir",
|
||||
lambda: str(fake_assets),
|
||||
)
|
||||
pic = MagicMock()
|
||||
# cv2.imread 会返回 None(不是真 PNG),触发"模板读取失败"分支
|
||||
detected, x = h.template_match_fallback(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0, loop=0,
|
||||
)
|
||||
assert detected is False
|
||||
|
||||
|
||||
def test_template_match_full_pipeline_no_match(tmp_path, monkeypatch):
|
||||
"""阈值设到 1.01(不可达)→ 必然不匹配,验证阈值分支。"""
|
||||
cv2 = pytest.importorskip("cv2")
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
a.fudai_template_match_threshold = 1.01 # 不可达,必然不匹配
|
||||
|
||||
fake_assets = tmp_path / "assets"
|
||||
fake_assets.mkdir()
|
||||
np.random.seed(7)
|
||||
template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8)
|
||||
cv2.imwrite(str(fake_assets / "fudai.png"), template)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_assets_dir",
|
||||
lambda: str(fake_assets),
|
||||
)
|
||||
|
||||
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.template_match_fallback(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0, loop=0,
|
||||
)
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
def test_template_match_full_pipeline_perfect_match(tmp_path, monkeypatch):
|
||||
"""构造一张包含模板的图像 → 模板匹配应命中"""
|
||||
cv2 = pytest.importorskip("cv2")
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
|
||||
fake_assets = tmp_path / "assets"
|
||||
fake_assets.mkdir()
|
||||
# 创建一个 30x30 的明显图案作为模板
|
||||
np.random.seed(0)
|
||||
template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8)
|
||||
cv2.imwrite(str(fake_assets / "fudai.png"), template)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_assets_dir",
|
||||
lambda: str(fake_assets),
|
||||
)
|
||||
|
||||
# 构造一张图:把模板嵌入到搜索区域内(X=156-269, Y=351-451)
|
||||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||||
pic_arr[..., 3] = 255 # alpha
|
||||
embed_y, embed_x = 380, 200 # 都在搜索区域内
|
||||
# cv2 imread 是 BGR,put 时转回 RGB;这里直接用 numpy 嵌入相同 BGR 数组
|
||||
pic_arr[embed_y:embed_y + 30, embed_x:embed_x + 30, :3] = template[..., ::-1]
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.template_match_fallback(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0, loop=0,
|
||||
)
|
||||
assert detected is True
|
||||
# 检测到的 x 应当在嵌入位置附近(embed_x + tw//2 = 200 + 15 = 215,1080 基准下相同)
|
||||
assert x is not None
|
||||
assert abs(x - (embed_x + 15)) <= 5
|
||||
|
||||
|
||||
# ---- numpy_pixel_scan ---- #
|
||||
|
||||
def test_numpy_pixel_scan_no_match(tmp_path):
|
||||
"""全黑图像 → numpy 扫描不会命中目标颜色范围"""
|
||||
pytest.importorskip("numpy")
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||||
pic_arr[..., 3] = 255
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.numpy_pixel_scan(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0,
|
||||
optimal_x_scaled=169,
|
||||
)
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
def test_numpy_pixel_scan_with_match(tmp_path):
|
||||
"""构造目标颜色 → numpy 扫描命中"""
|
||||
pytest.importorskip("numpy")
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||||
pic_arr[..., 3] = 255
|
||||
# 目标颜色 R=200, G=185, B=240(在范围内:R[190-206], G[173-196], B[234-250])
|
||||
# 在搜索区域 X=157-410, Y=354 附近放一列像素(每列至少 2 个像素,valid_cols >= 2)
|
||||
target_x = 250
|
||||
pic_arr[353:355, target_x, 0] = 200
|
||||
pic_arr[353:355, target_x, 1] = 185
|
||||
pic_arr[353:355, target_x, 2] = 240
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.numpy_pixel_scan(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=1080, height=2400, y_pianyi_val=0,
|
||||
optimal_x_scaled=target_x,
|
||||
)
|
||||
assert detected is True
|
||||
assert x == target_x
|
||||
|
||||
|
||||
def test_numpy_pixel_scan_invalid_roi():
|
||||
"""搜索区域无效(width < 157)→ 直接返回 False"""
|
||||
a = _make_analyser()
|
||||
pic = MagicMock()
|
||||
detected, x = h.numpy_pixel_scan(
|
||||
a, pic, rx=1080, ry=2400,
|
||||
width=100, height=2400, y_pianyi_val=0, # width < 157
|
||||
optimal_x_scaled=169,
|
||||
)
|
||||
assert detected is False
|
||||
|
||||
|
||||
# ---- per_pixel_scan_fallback ---- #
|
||||
|
||||
def test_per_pixel_scan_no_match():
|
||||
"""全白图 → 像素逐行扫描找不到目标颜色"""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.per_pixel_scan_fallback(
|
||||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||||
)
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
def test_per_pixel_scan_with_match():
|
||||
"""构造目标像素 → 逐行扫描命中"""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||||
pic_arr[..., 3] = 255
|
||||
# 在 scan_y=403, scan_x=200 处放目标像素
|
||||
pic_arr[403, 200] = (200, 185, 240, 255)
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.per_pixel_scan_fallback(
|
||||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||||
)
|
||||
assert detected is True
|
||||
assert x == 200
|
||||
|
||||
|
||||
def test_per_pixel_scan_uses_last_fudai_x():
|
||||
"""analyser.last_fudai_x 设置时,从该位置开始搜索"""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
a = _make_analyser()
|
||||
a.last_fudai_x = 250
|
||||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||||
pic_arr[..., 3] = 255
|
||||
pic_arr[403, 250] = (200, 185, 240, 255)
|
||||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||||
|
||||
detected, x = h.per_pixel_scan_fallback(
|
||||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||||
)
|
||||
assert detected is True
|
||||
assert x == 250
|
||||
|
||||
|
||||
def test_per_pixel_scan_swallows_exception():
|
||||
"""pic.load() 抛错时不应崩"""
|
||||
a = _make_analyser()
|
||||
bad_pic = MagicMock()
|
||||
bad_pic.load.side_effect = RuntimeError("boom")
|
||||
detected, x = h.per_pixel_scan_fallback(
|
||||
a, bad_pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||||
)
|
||||
assert detected is False
|
||||
assert x is None
|
||||
|
||||
|
||||
# ---- _is_target_pixel ---- #
|
||||
|
||||
def test_is_target_pixel_in_range():
|
||||
assert h._is_target_pixel((200, 185, 240)) is True
|
||||
assert h._is_target_pixel((190, 173, 234)) is True
|
||||
assert h._is_target_pixel((206, 196, 250)) is True
|
||||
|
||||
|
||||
def test_is_target_pixel_out_of_range():
|
||||
assert h._is_target_pixel((189, 185, 240)) is False
|
||||
assert h._is_target_pixel((200, 197, 240)) is False
|
||||
assert h._is_target_pixel((200, 185, 233)) is False
|
||||
|
||||
|
||||
def test_is_target_pixel_non_tuple():
|
||||
assert h._is_target_pixel(None) is False
|
||||
assert h._is_target_pixel((100,)) is False # 长度不够
|
||||
assert h._is_target_pixel("not_tuple") is False
|
||||
Reference in new issue
Block a user