Files
douyin_guaji-main/douyin_detection.py
T
Your Name 836a31d817 refactor: Remove outdated files and enhance Web GUI functionality
- Deleted obsolete markdown files related to follow tab coordinates testing and results.
- Removed outdated batch scripts for launching the Web GUI.
- Updated `config.json` to improve reservation handling and adjust prize value settings.
- Enhanced logging and error handling in `web_gui.py` and `app.js` for better user experience.
- Added automatic screenshot functionality during Web GUI startup for improved monitoring.
2025-12-19 03:31:08 +08:00

501 lines
19 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.
from __future__ import annotations
"""
Functional fudai detection (WebGUI version)
===========================================
This module reimplements the key detection helpers used in `douyin_fudai`:
- check_detail_height(analyser) -> int
- check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) -> bool
- check_in_fudai_detail(analyser) -> bool
The logic is adapted from the original `axf/douyin_detection.py`, with extra
defensive checks to avoid crashes when certain analyser attributes are missing.
"""
from typing import Any
import os
import time
from PIL import Image
def _ensure_detection_cache(analyser: Any) -> None:
"""Ensure analyser has a simple detection cache structure."""
if not hasattr(analyser, "_detection_cache"):
analyser._detection_cache = {}
if not hasattr(analyser, "_detection_cache_ttl"):
analyser._detection_cache_ttl = 2.0
def check_detail_height(analyser: Any) -> int:
"""Detect how many tasks are required in the fudai detail popup.
Returns:
0 / 1 / 2 / 3 (number of tasks).
"""
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
pic = None
for attempt in range(3):
try:
pic = Image.open(pic1_path)
pic.load() # force load to catch truncated files early
break
except Exception:
if attempt < 2:
try:
analyser.operation.get_screenshot(analyser.device_id)
analyser.operation.delay(0.2)
except Exception:
pass
pic = None
if pic is None:
try:
analyser._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN")
except Exception:
pass
return 0
pic_new = pic.convert("RGBA")
pix = pic_new.load()
width, height = pic_new.size
# X of “参与” button
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
x = 536 * rx // 1080
if not (0 <= x < width):
return 0
# (base_y, y_pianyi_offset, task_count)
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
check_points = [
(983, 0, 2),
(983, y_pianyi_val, 2),
(983, -y_pianyi_val, 2),
(883, 0, 3),
(883, y_pianyi_val, 3),
(883, -y_pianyi_val, 3),
(1058, 0, 1),
(1058, y_pianyi_val, 1),
(1058, -y_pianyi_val, 1),
]
def _check_pixel_color(y_coord: int) -> bool:
if not (0 <= y_coord < height):
return False
try:
p = pix[x, y_coord]
if not (isinstance(p, tuple) and len(p) >= 3):
return False
r, g, b = int(p[0]), int(p[1]), int(p[2])
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
except Exception:
return False
try:
for base_y, dy, task_count in check_points:
y = base_y * ry // 2400 + dy
if _check_pixel_color(y):
try:
analyser._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count)
except Exception:
pass
return task_count
except Exception:
pass
# Optional robot-check path from original implementation
try:
if hasattr(analyser, "check_have_robot_analyse") and analyser.check_have_robot_analyse():
analyser.deal_robot_analyse()
except Exception:
pass
try:
analyser._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0)
except Exception:
pass
return 0
def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False):
"""Check whether the live-room screen currently has a fudai icon.
仅使用像素/颜色特征进行检测(无位置过滤、无 OCR):
- 先用 numpy/逐像素扫描找到疑似图标位置;
- 再通过颜色统计(粉紫/粉蓝 vs 橙色券)过滤误报。
"""
func_start = time.time()
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
attempt_count = 0 # 仅用于日志记录,不影响循环控制
try:
retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3)
except Exception:
retry_delay_s = 0.3
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5)
except Exception:
max_wait_s = 2.5
if retry_delay_s < 0.15:
retry_delay_s = 0.15
if max_wait_s < 0:
max_wait_s = 0.0
try:
analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready}")
except Exception:
pass
detected_any = False
# 完全基于时间限制,不使用次数限制
while (time.time() - func_start) < max_wait_s:
attempt_start = time.time()
attempt_count += 1
# Reuse external screenshot only on first attempt if provided
if not (screenshot_ready and attempt_count == 1):
try:
analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False)
except Exception:
pass
try:
pic = Image.open(pic1_path)
pic.load()
except Exception:
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
# 计算剩余时间,但至少等待 retry_delay_s
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
pic_new = pic.convert("RGBA")
detected = False
detected_x = None
# Resolution ratios
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
# First try numpy-accelerated scan over a horizontal band
numpy_scan_start = time.time()
try:
import numpy as _np
# 优惠券一般在左侧,这里将扫描区域整体右移:
# 原范围约为 x∈[41,410],现在改为 x∈[220,960](1080 基准),
# 既避开左侧券位,又覆盖更多右侧可能出现福袋的位置。
# Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率)
x1 = max(0, 220 * rx // 1080)
x2 = min(pic_new.size[0], 960 * rx // 1080)
y_top_base = 348 * ry // 2400 + y_pianyi_val
y_bottom_base = 448 * ry // 2400 + y_pianyi_val
y_top = max(0, y_top_base)
y_bottom = min(pic_new.size[1], y_bottom_base)
if x1 < x2 and y_top < y_bottom:
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
arr = _np.array(roi)
if arr.size > 0:
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 valid_cols.any():
col_idx = int(_np.argmax(valid_cols))
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
detected = True
detected_any = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
except Exception:
detected = False
numpy_scan_elapsed = time.time() - numpy_scan_start
if numpy_scan_elapsed > 0.01:
try:
elapsed_time = time.time() - func_start
analyser._log_step_time(
f"numpy像素扫描(已用时{elapsed_time:.2f}秒)", numpy_scan_start, {"结果": "命中" if detected else "未命中"}
)
except Exception:
pass
# Fallback: per-pixel scan(第一步:只做颜色/像素级粗检测)
if not detected:
pixel_scan_start = time.time()
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
# 与 numpy 扫描保持一致:整体右移,并尽量覆盖右侧大部分区域
# Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率)
scan_x_start = 220 * rx // 1080
scan_x_end = min(960 * rx // 1080, pic_width)
scan_y_start_base = 348 * ry // 2400 + y_pianyi_val
scan_y_end_base = 448 * ry // 2400 + y_pianyi_val
scan_y_start = max(0, scan_y_start_base)
scan_y_end = min(pic_height, scan_y_end_base)
# 并行检测348到448范围内的所有Y值
for check_y in range(scan_y_start, scan_y_end):
if not (0 <= check_y < pic_height):
continue
for x_scaled in range(scan_x_start, scan_x_end):
try:
px = pix[x_scaled, check_y]
if (
len(px) >= 3
and 190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
detected_x = int(x_scaled * 1080.0 / max(1, rx))
detected = True
detected_any = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break
except Exception:
continue
if detected:
break
except Exception:
pass
pixel_scan_elapsed = time.time() - pixel_scan_start
if pixel_scan_elapsed > 0.01:
try:
elapsed_time = time.time() - func_start
analyser._log_step_time(
f"逐像素扫描(已用时{elapsed_time:.2f}秒)", pixel_scan_start, {"结果": "命中" if detected else "未命中"}
)
except Exception:
pass
if detected and detected_x is not None:
# 颜色分布过滤:在候选区域统计“粉紫/粉蓝”(福袋) vs “橙色”(券) 像素数量
try:
base_y = 403 * ry // 2400 + y_pianyi_val
cx1 = max(0, int((detected_x - 45) * rx / 1080))
cx2 = min(pic_new.size[0], int((detected_x + 45) * rx / 1080))
cy1 = max(0, base_y - 45)
cy2 = min(pic_new.size[1], base_y + 45)
fudai_like = 0
coupon_like = 0
if cx1 < cx2 and cy1 < cy2:
pix2 = pic_new.load()
step = max(1, (cx2 - cx1) // 24) # 下采样防止太慢
for yy in range(cy1, cy2, step):
for xx in range(cx1, cx2, step):
try:
p = pix2[xx, yy]
except Exception:
continue
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 福袋:粉/紫/粉蓝:R 高、B 也高,G 中等
if r >= 200 and b >= 210 and 80 <= g <= 230:
fudai_like += 1
# 券:偏黄橙色:R 高、G 中等、B 明显偏低
if r >= 200 and 120 <= g <= 230 and b <= 180:
coupon_like += 1
# 如果“橙券像素”明显多于“粉袋像素”,判定为优惠券,丢弃
if coupon_like > fudai_like * 1.2:
try:
analyser._log_kv(
"[找福袋图标] 颜色过滤未通过",
"区域颜色更接近优惠券,视为非福袋",
fudai_like=fudai_like,
coupon_like=coupon_like,
x=detected_x,
)
except Exception:
pass
detected = False
detected_x = None
except Exception:
detected = False
detected_x = None
if detected and detected_x is not None:
# store last X if analyser expects it(此时已通过颜色过滤)
try:
analyser._last_fudai_icon_x = detected_x
except Exception:
pass
break
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
# 计算剩余时间,但至少等待 retry_delay_s
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
try:
total_elapsed = time.time() - func_start
analyser._log_kv(
"[找福袋图标] 结束",
"检测完成",
detected=bool(detected_any and detected_x is not None),
elapsed_ms=int(total_elapsed * 1000),
)
except Exception:
pass
# 与原始 fudai.py 的 check_have_fudai 行为保持一致:
# 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。
return int(detected_x) if detected_x is not None else False
def check_in_fudai_detail(analyser: Any) -> bool:
"""Detect whether we are currently on the fudai detail page."""
_ensure_detection_cache(analyser)
cache_key = "check_in_fudai_detail"
now = time.time()
cached = analyser._detection_cache.get(cache_key)
if cached:
cached_ts, cached_result = cached
ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0)
if (now - cached_ts) < ttl:
return bool(cached_result)
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
try:
try:
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert("RGBA")
except Exception:
try:
analyser.operation.get_screenshot(analyser.device_id)
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert("RGBA")
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
pix = pic.load()
width, height = pic.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
x = 536 * rx // 1080
if not (0 <= x < width):
analyser._detection_cache[cache_key] = (now, False)
return False
base_ys = (883, 983, 1058)
offsets = (0, y_pianyi_val, -y_pianyi_val)
for base_y in base_ys:
y0 = base_y * ry // 2400
for dy in offsets:
y = y0 + dy
if not (0 <= y < height):
continue
try:
p = pix[x, y]
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84:
analyser._detection_cache[cache_key] = (now, True)
return True
except Exception:
continue
except Exception:
pass
# OCR fallback (lighter version of original implementation)
try:
try:
min_interval = float(getattr(analyser, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0)
except Exception:
min_interval = 8.0
last = float(getattr(analyser, "_last_detail_ocr_check_ts", 0.0) or 0.0)
if min_interval > 0 and (now - last) < min_interval:
analyser._detection_cache[cache_key] = (now, False)
return False
analyser._last_detail_ocr_check_ts = now
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")
if not t_btn or not any(k in t_btn for k in keywords):
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
if any(k in t_btn for k in keywords):
analyser._detection_cache[cache_key] = (now, True)
return True
except Exception:
pass
analyser._detection_cache[cache_key] = (now, False)
return False