Files
douyi_guaji_main/douyin/detection/detection_pkg/detail.py
T

704 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""detection_pkg.detail - 福袋详情页相关检测。
- check_detail_height 识别详情页弹窗中"任务"数量(0/1/2/3)
- check_in_fudai_detail 判断当前是否处于福袋详情页(综合多种特征)
"""
from __future__ import annotations
# pylint: disable=no-member
import os
import re
import time
from typing import Any
from ._common import _ensure_detection_cache
def check_detail_height(analyser: Any, pic_rgb: Any = None) -> int:
"""Detect how many tasks are required in the fudai detail popup.
Returns:
0 / 1 / 2 / 3 (number of tasks).
"""
try:
from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode
ui_mode = normalize_fudai_detail_ui_mode(
getattr(analyser, "fudai_detail_ui_mode", "auto")
)
except Exception:
ui_mode = "auto"
if ui_mode == "legacy":
return _check_detail_task_count_legacy_pixels(analyser)
detected_v2_template = _check_detail_task_count_v2(analyser, pic_rgb=pic_rgb)
if detected_v2_template:
return detected_v2_template
return 0
def _check_detail_task_count_legacy_pixels(analyser: Any) -> int:
"""Legacy detail task-count detection. Kept separate from v2 UI height logic."""
# 使用统一的截图路径配置
try:
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
# 记录截图文件的时间戳(如果存在)
screenshot_timestamp = None
try:
if os.path.exists(pic1_path):
screenshot_timestamp = os.path.getmtime(pic1_path)
except Exception:
pass
pic = None
for attempt in range(3):
try:
from PIL import Image
pic = Image.open(pic1_path)
pic.load() # force load to catch truncated files early
break
except Exception:
if attempt < 2:
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
analyser.operation.delay(0.2)
# 重新获取截图后,更新时间戳
try:
if os.path.exists(pic1_path):
screenshot_timestamp = os.path.getmtime(pic1_path)
except Exception:
pass
except Exception:
pass
pic = None
if pic is None:
try:
analyser._log_kv(
"检测",
"读取截图失败,默认不需要任务",
level="WARN",
screenshot_timestamp=screenshot_timestamp,
)
except Exception:
pass
return 0
pic_new = pic.convert("RGBA")
pix = pic_new.load()
width, height = pic_new.size
# X of “参与” button
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
x = 536 * rx // 1080
if not (0 <= x < width):
return 0
# (base_y, y_pianyi_offset, task_count)
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
check_points = [
(983, 0, 2),
(983, y_pianyi_val, 2),
(983, -y_pianyi_val, 2),
(883, 0, 3),
(883, y_pianyi_val, 3),
(883, -y_pianyi_val, 3),
(1058, 0, 1),
(1058, y_pianyi_val, 1),
(1058, -y_pianyi_val, 1),
]
def _check_pixel_color(y_coord: int) -> bool:
if not (0 <= y_coord < height):
return False
try:
p = pix[x, y_coord]
if not (isinstance(p, tuple) and len(p) >= 3):
return False
r, g, b = int(p[0]), int(p[1]), int(p[2])
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
except Exception:
return False
detected_task_count = None
detected_y = None
try:
for base_y, dy, task_count in check_points:
y = base_y * ry // 2400 + dy
if _check_pixel_color(y):
detected_task_count = task_count
detected_y = y
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{task_count}个",
task_count=task_count,
detected_y=detected_y,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=(
round(current_time - screenshot_timestamp, 3)
if screenshot_timestamp
else None
),
)
except Exception:
pass
break
except Exception:
pass
# 保存调试图片:标注检测区域和检测点
try:
from douyin.handlers import douyin_screenshot_manager
# 计算检测区域(参与按钮附近的区域)
check_region_x1 = max(0, x - 50)
check_region_x2 = min(width, x + 50)
check_region_y1 = max(0, (883 * ry // 2400) - 100) # 3个任务的Y坐标附近
check_region_y2 = min(height, (1058 * ry // 2400) + 100) # 1个任务的Y坐标附近
# 标注检测点
coords_list = []
for base_y, dy, task_count_val in check_points:
check_y = base_y * ry // 2400 + dy
if 0 <= check_y < height:
# 标注检测点(小矩形区域)
coords_list.append(
(
max(0, x - 10),
max(0, check_y - 5),
min(width, x + 10),
min(height, check_y + 5),
)
)
# 保存调试图片
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="detection",
picname="福袋任务数量",
step="task_count_detection",
coords=(check_region_x1, check_region_y1, check_region_x2, check_region_y2),
extra_info={
"task_count": (
detected_task_count if detected_task_count is not None else 0
),
"detected_y": detected_y,
"check_x": x,
"check_points_count": len(check_points),
"region": f"({check_region_x1},{check_region_y1})-({check_region_x2},{check_region_y2})",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋任务数量检测",
path=debug_path,
task_count=(
detected_task_count if detected_task_count is not None else 0
),
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
if detected_task_count is not None:
return detected_task_count
# Optional robot-check path from original implementation
try:
if (
hasattr(analyser, "check_have_robot_analyse")
and analyser.check_have_robot_analyse()
):
analyser.deal_robot_analyse()
except Exception:
pass
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
"识别福袋任务数量:0个(不需要任务)",
level="INFO",
task_count=0,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=(
current_time - screenshot_timestamp if screenshot_timestamp else None
),
)
except Exception:
pass
return 0
def _check_detail_task_count_v2_pixels(analyser: Any) -> int:
"""Fast v2 task-count decision from scanning the dark task-card top edge."""
try:
from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode
ui_mode = normalize_fudai_detail_ui_mode(
getattr(analyser, "fudai_detail_ui_mode", "auto")
)
if ui_mode == "legacy":
return 0
except Exception:
ui_mode = "auto"
try:
from douyin.core import path_config
from PIL import Image
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path).convert("RGB")
width, height = pic.size
except Exception:
return 0
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
# 快速区分 two-task:你提供的上方大横带在 two-task 样本里深色命中明显更多。
upper_x_start = 2 * rx // 1080
upper_x_end = 1075 * rx // 1080
upper_y_start = 1018 * ry // 2400
upper_y_end = 1080 * ry // 2400
# one-task 兜底:保留较低位置的任务卡顶部横带检测。
lower_x_start = 420 * rx // 1080
lower_x_end = 860 * rx // 1080
lower_y_band = 1866 * ry // 2400
legacy_two_task_y1 = 1686 * ry // 2400
legacy_two_task_y2 = 1788 * ry // 2400
if not (
0 <= upper_x_start < width
and 0 < upper_x_end <= width
and upper_x_start < upper_x_end
and 0 <= upper_y_start < height
and 0 < upper_y_end <= height
and upper_y_start < upper_y_end
and 0 <= lower_x_start < width
and 0 < lower_x_end <= width
and lower_x_start < lower_x_end
and 0 <= lower_y_band < height
and 0 <= legacy_two_task_y1 < height
and 0 <= legacy_two_task_y2 < height
):
return 0
def _is_white_text(pixel: tuple[int, int, int]) -> bool:
r, g, b = pixel
return r >= 215 and g >= 215 and b >= 215
def _is_dark_card(pixel: tuple[int, int, int]) -> bool:
r, g, b = pixel
return 5 <= r <= 45 and 10 <= g <= 55 and 35 <= b <= 95
upper_sample_xs = [
int(v)
for v in (
upper_x_start,
upper_x_start + (upper_x_end - upper_x_start) * 0.2,
upper_x_start + (upper_x_end - upper_x_start) * 0.4,
upper_x_start + (upper_x_end - upper_x_start) * 0.6,
upper_x_start + (upper_x_end - upper_x_start) * 0.8,
upper_x_end - 1,
)
]
upper_sample_xs = [x for x in upper_sample_xs if 0 <= x < width]
lower_sample_xs = [
int(v)
for v in (
lower_x_start,
lower_x_start + (lower_x_end - lower_x_start) * 0.25,
lower_x_start + (lower_x_end - lower_x_start) * 0.5,
lower_x_start + (lower_x_end - lower_x_start) * 0.75,
lower_x_end - 1,
)
]
lower_sample_xs = [x for x in lower_sample_xs if 0 <= x < width]
def _dark_hits_at_y(y_coord: int, xs: list[int]) -> int:
hits = 0
for sx in xs:
try:
pixel = pic.getpixel((sx, y_coord))
except Exception:
continue
if _is_dark_card((int(pixel[0]), int(pixel[1]), int(pixel[2]))):
hits += 1
return hits
upper_band_dark_sum = 0
lower_band_dark_hits = 0
legacy_two_task_hits_1 = 0
legacy_two_task_hits_2 = 0
try:
for y_coord in range(upper_y_start, upper_y_end + 1, max(1, 4 * ry // 2400)):
upper_band_dark_sum += _dark_hits_at_y(y_coord, upper_sample_xs)
lower_band_dark_hits = _dark_hits_at_y(lower_y_band, lower_sample_xs)
legacy_two_task_hits_1 = _dark_hits_at_y(legacy_two_task_y1, lower_sample_xs)
legacy_two_task_hits_2 = _dark_hits_at_y(legacy_two_task_y2, lower_sample_xs)
except Exception:
return 0
detected = 0
reason = ""
if upper_band_dark_sum >= 36:
detected = 2
reason = "upper_band_dark_sum_two_task"
elif legacy_two_task_hits_1 >= 3 and legacy_two_task_hits_2 >= 3:
detected = 2
reason = "legacy_two_task_band_hits"
elif lower_band_dark_hits >= 3:
detected = 1
reason = "lower_band_dark_hits_one_task"
if detected:
try:
setattr(analyser, "_fudai_detail_task_count_source", "v2_pixels")
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{detected}个(v2像素高度)",
task_count=detected,
source="v2_pixels",
)
analyser._log_kv(
"检测",
"福袋任务数量v2像素高度详情",
task_count=detected,
source="v2_pixels",
reason=reason,
upper_x_start=upper_x_start,
upper_x_end=upper_x_end,
upper_y_start=upper_y_start,
upper_y_end=upper_y_end,
upper_sample_xs=",".join(str(v) for v in upper_sample_xs),
upper_band_dark_sum=upper_band_dark_sum,
lower_x_start=lower_x_start,
lower_x_end=lower_x_end,
lower_y_band=lower_y_band,
lower_sample_xs=",".join(str(v) for v in lower_sample_xs),
lower_band_dark_hits=lower_band_dark_hits,
legacy_two_task_y1=legacy_two_task_y1,
legacy_two_task_y2=legacy_two_task_y2,
legacy_two_task_hits_1=legacy_two_task_hits_1,
legacy_two_task_hits_2=legacy_two_task_hits_2,
ui_mode=ui_mode,
log_type="DEBUG",
)
except Exception:
pass
return detected
def get_detail_task_status_search_box() -> tuple[int, int, int, int]:
"""Unified v2 task-status area; two-task height contains both status words."""
try:
from douyin.fudai.core.coords import get_pixel_region
return get_pixel_region("fudai_task_status", (820, 1815, 1050, 2035))
except Exception:
return (820, 1815, 1050, 2035)
def _check_detail_task_count_v2(analyser: Any, pic_rgb: Any = None) -> int:
"""Fast v2 task-count recognition by matching the shape of "达成"."""
try:
import cv2 # type: ignore[import-untyped]
import numpy as np # type: ignore[import-untyped]
from PIL import Image
from douyin.core import path_config
if pic_rgb is not None:
pic = pic_rgb.convert("RGB") if hasattr(pic_rgb, "convert") else Image.fromarray(pic_rgb).convert("RGB")
else:
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
return 0
pic = Image.open(pic_path).convert("RGB")
assets_dir = path_config.get_assets_dir()
template_path = os.path.join(assets_dir, "fudai_task_status_dacheng_shape.png")
if not os.path.exists(template_path):
return 0
width, height = pic.size
search_box = get_detail_task_status_search_box()
x1, y1, x2, y2 = _scale_box_to_image(search_box, width, height)
if x1 >= x2 or y1 >= y2:
return 0
template_rgb = Image.open(template_path).convert("RGB")
template_edges = _task_status_shape_edges(template_rgb, cv2, np)
roi = pic.crop((x1, y1, x2, y2))
roi_edges = _task_status_shape_edges(roi, cv2, np)
th, tw = template_edges.shape[:2]
rh, rw = roi_edges.shape[:2]
if th <= 0 or tw <= 0 or rh < th or rw < tw:
return 0
res = cv2.matchTemplate(roi_edges, template_edges, cv2.TM_CCOEFF_NORMED)
threshold = float(
getattr(analyser, "fudai_task_status_template_threshold", 0.26) or 0.26
)
threshold = max(0.0, min(1.0, threshold))
matches = _collect_task_status_matches(res, threshold, tw, th)
best_score = float(matches[0][0]) if matches else -1.0
task_count = min(2, len(matches))
try:
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] dacheng_shape_scored",
task_count=task_count,
source="v2_dacheng_shape",
search_box=(x1, y1, x2, y2),
template_path=template_path,
template_score=round(best_score, 4) if best_score >= 0 else best_score,
match_count=len(matches),
match_points=";".join(
f"{round(score, 3)}@{x1 + mx},{y1 + my}"
for score, mx, my in matches[:4]
),
threshold=threshold,
)
except Exception:
pass
if task_count in (1, 2):
try:
setattr(analyser, "_fudai_detail_task_count_source", "v2_dacheng_shape")
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{task_count}个(v2 达成形状模板)",
task_count=task_count,
source="v2_dacheng_shape",
template_score=round(best_score, 4),
)
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] matched",
task_count=task_count,
source="v2_dacheng_shape",
template_score=round(best_score, 4),
match_count=len(matches),
)
except Exception:
pass
return task_count
try:
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] no_match",
source="v2_dacheng_shape",
match_count=len(matches),
best_score=round(best_score, 4) if best_score >= 0 else best_score,
)
except Exception:
pass
except Exception:
return 0
return 0
def _scale_box_to_image(
box: tuple[int, int, int, int],
width: int,
height: int,
) -> tuple[int, int, int, int]:
sx = width / 1080.0
sy = height / 2400.0
x1, y1, x2, y2 = box
return (
max(0, min(int(x1 * sx), width)),
max(0, min(int(y1 * sy), height)),
max(0, min(int(x2 * sx), width)),
max(0, min(int(y2 * sy), height)),
)
def _task_status_shape_edges(image: Any, cv2: Any, np: Any) -> Any:
arr = np.asarray(image.convert("RGB"))
gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
return cv2.Canny(blur, 40, 120)
def _collect_task_status_matches(
result: Any,
threshold: float,
template_width: int,
template_height: int,
) -> list[tuple[float, int, int]]:
import numpy as np # type: ignore[import-untyped]
loc = np.where(result >= threshold)
candidates: list[tuple[float, int, int]] = []
for y, x in zip(*loc):
candidates.append((float(result[y, x]), int(x), int(y)))
candidates.sort(reverse=True)
kept: list[tuple[float, int, int]] = []
min_y_gap = max(38, int(template_height * 0.65))
for score, x, y in candidates:
cx = x + template_width / 2.0
cy = y + template_height / 2.0
duplicate = False
for _score, kept_x, kept_y in kept:
kept_cx = kept_x + template_width / 2.0
kept_cy = kept_y + template_height / 2.0
if abs(cy - kept_cy) < min_y_gap and abs(cx - kept_cx) < template_width * 0.75:
duplicate = True
break
if not duplicate:
kept.append((score, x, y))
if len(kept) >= 4:
break
return kept
def get_detail_task_count_digit_box(task_count_box: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
"""Extract the trailing task-count digit box inside the (0/1)/(1/2) badge."""
x1, y1, x2, y2 = [int(v) for v in task_count_box]
# one-task and two-task badges have different anchors in current verified samples.
if y1 >= 1830:
digit_x1 = x1 + 86
digit_x2 = x1 + 98
digit_y1 = y1 + 16
digit_y2 = y1 + 46
else:
digit_x1 = x1 + 114
digit_x2 = x1 + 135
digit_y1 = y1 + 44
digit_y2 = y1 + 75
if digit_x2 <= digit_x1:
digit_x2 = min(x2, digit_x1 + 1)
if digit_y2 <= digit_y1:
digit_y2 = min(y2, digit_y1 + 1)
return digit_x1, digit_y1, digit_x2, digit_y2
def check_in_fudai_detail(analyser: Any) -> bool:
"""Detect whether we are currently on the fudai detail page.
使用模板匹配检测,与 detect_fudai_detail_page 保持一致。
"""
_ensure_detection_cache(analyser)
cache_key = "check_in_fudai_detail"
now = time.time()
cached = analyser._detection_cache.get(cache_key)
if cached:
cached_ts, cached_result = cached
ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0)
if (now - cached_ts) < ttl:
return bool(cached_result)
# 使用模板匹配检测,与 detect_fudai_detail_page 保持一致
try:
from douyin.detection import douyin_pixel
from douyin.core import path_config
# 获取截图
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
analyser._detection_cache[cache_key] = (now, False)
return False
from PIL import Image
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
# 获取分辨率比例和Y偏移
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
template_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
if template_threshold < 0.0:
template_threshold = 0.0
if template_threshold > 1.0:
template_threshold = 1.0
# 使用任务数量检测
result = douyin_pixel.detect_fudai_detail_page(
pic_rgb,
rx,
ry,
y_pianyi,
template_threshold,
return_info=False, # 不需要详细信息
analyser=analyser,
)
is_in_detail = bool(result)
analyser._detection_cache[cache_key] = (now, is_in_detail)
return is_in_detail
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
# 像素检测代码已删除,使用模板匹配替代
# 如需恢复像素检测,请参考 git 历史记录