Files
douyin_guaji-main/douyin_fudai_detail.py
T
Your Name f92933641f feat: Enhance documentation and clean up code structure
- Added comprehensive documentation for the unified screenshot and score recording process in the new markdown file.
- Improved existing markdown files by adding spacing for better readability.
- Cleaned up code by removing unnecessary blank lines across various scripts, enhancing overall code clarity.
- Updated configuration settings to reflect recent changes and ensure consistency across the project.
- Enhanced logging mechanisms to support better debugging and monitoring.
2025-12-25 16:11:25 +08:00

1118 lines
44 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
"""
Fudai detail helpers shim (WebGUI version)
==========================================
Exports:
- close_fudai_detail
- ensure_fudai_detail_open
- read_live_room_title_core
- read_fudai_detail_once
- read_fudai_detail_with_retries
- is_abnormal_time_value
"""
from typing import Any, Dict, Tuple, List, Optional
import os
import time
import re
from PIL import Image
from douyin_detection import check_detail_height
from douyin_fudai_core import get_fudai_contain
# ============================================================================
# 直播间标题处理辅助函数(模块化)
# ============================================================================
def _room_title_has_ellipsis(s: str) -> bool:
"""检查是否包含省略号。"""
if "…" in s:
return True
if re.search(r"\.{3,}", s):
return True
return False
def _strip_room_noise_text(s: str) -> str:
"""移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。"""
try:
t = str(s or "")
except Exception:
return ""
t = t.replace("\r", "\n").replace("\t", " ")
t = re.sub(r"[\s\u3000]+", " ", t).strip()
# 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"):
t = t.replace(w, " ")
t = re.sub(r"\s+", " ", t).strip()
return t
def _extract_room_title_candidate(raw_text: str) -> str:
"""从 OCR 原文中提取更像"直播间名"的片段。"""
t = _strip_room_noise_text(raw_text)
if not t:
return ""
segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()]
best = ""
best_score = -999
for seg in segs:
if not seg:
continue
seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip()
if not seg2:
continue
seg = seg2
score = len(seg)
if _room_title_has_ellipsis(seg):
score += 30
if re.search(r"[\u4e00-\u9fffA-Za-z]", seg):
score += 5
if score > best_score:
best_score = score
best = seg
if best:
m = re.search(r"(.*?)(…|\.{3,})", best)
if m:
cand = (m.group(1) + m.group(2)).strip()
return cand if cand else best.strip()
return best.strip()
m2 = re.search(r"(.*?)(…|\.{3,})", t)
if m2:
cand2 = (m2.group(1) + m2.group(2)).strip()
if cand2:
return cand2
return t.strip()
def _normalize_room_title(t: str) -> str:
"""规范化直播间标题。"""
s = _extract_room_title_candidate(str(t or ""))
s = s.replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
s = s.replace(w, "")
s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s)
return s
def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]:
"""尝试 OCR 识别直播间标题。"""
try:
raw0 = analyser.operation.analyse_pic_word(cut_name, change_color)
except Exception:
raw0 = ""
raw_text0 = str(raw0 or "").replace("\r", "\n").strip()
cand_raw0 = _extract_room_title_candidate(raw_text0)
title0 = _normalize_room_title(cand_raw0)
return title0, cand_raw0
def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]:
"""从多个候选结果中选择最佳的一个。"""
best = ("", "")
best_score = -1
for t_norm, t_raw, tag in cands:
if not t_raw and not t_norm:
continue
ln = len(t_norm or "")
score = ln
if ln >= min_len:
score += 10
if ln == 1:
score -= 4
if ln == 2:
score -= 1
if _room_title_has_ellipsis(t_raw or ""):
score += 8
if tag.endswith("_cc0"):
score += 2
if tag.startswith("large"):
score += 2
if tag.startswith("mid"):
score += 1
if score > best_score:
best_score = score
best = (t_norm, t_raw)
return best
def close_fudai_detail(analyser: Any) -> None:
"""关闭福袋详情:当前实现直接按一次返回键。"""
try:
analyser._log_kv("详情", "close_fudai_detail:按返回键一次")
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser.operation.delay(0.5)
except Exception:
time.sleep(0.5)
def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool:
"""确保福袋详情已打开:当前实现只记录日志并假定已打开。
Args:
analyser: 分析器实例
fudai_x: 福袋的x坐标(可选,当前实现未使用)
"""
try:
analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开", fudai_x=fudai_x)
except Exception:
pass
return True
def _is_wrong_coupon_popup(analyser: Any) -> bool:
"""在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。
只在"点击详情后"调用,不在平时循环中使用,避免额外开销。
逻辑:
1. 对屏幕中部区域做颜色统计
2. 如果同时检测到福袋详情和优惠券特征,需要OCR确认"开心收下"字样
3. 只有OCR确认是"开心收下"时,才判定为优惠券弹窗
"""
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
return False
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
try:
pic = Image.open(path)
pic.load() # Force load to catch truncated files early
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return False
except Exception:
return False
pic = pic.convert("RGBA")
pix = pic.load()
w, h = pic.size
# 扫描区域:153,351 到 266,451(基于1080x2400基准坐标)
# 根据实际分辨率缩放坐标
scale_x = w / 1080.0
scale_y = h / 2400.0
x1 = int(153 * scale_x)
y1 = int(351 * scale_y)
x2 = int(266 * scale_x)
y2 = int(451 * scale_y)
# 边界检查
x1 = max(0, min(x1, w))
y1 = max(0, min(y1, h))
x2 = max(0, min(x2, w))
y2 = max(0, min(y2, h))
if x1 >= x2 or y1 >= y2:
return False
fudai_like = 0
coupon_like = 0
step_x = max(1, (x2 - x1) // 40)
step_y = max(1, (y2 - y1) // 40)
for yy in range(y1, y2, step_y):
for xx in range(x1, x2, step_x):
try:
p = pix[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])
# 福袋:粉/紫/粉蓝
if r >= 200 and b >= 210 and 80 <= g <= 230:
fudai_like += 1
# 券:偏橙色
if r >= 200 and 120 <= g <= 230 and b <= 180:
coupon_like += 1
try:
analyser._log_kv(
"弹窗",
"弹窗颜色统计",
fudai_like=fudai_like,
coupon_like=coupon_like,
)
except Exception:
pass
# 如果券像素明显多于粉袋像素,可能需要OCR确认
is_coupon_like_by_color = coupon_like > fudai_like * 1.2
# 检测是否同时有福袋详情特征(通过像素检测)
has_fudai_detail = False
try:
import douyin_pixel
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
pic_rgb = pic.convert("RGB")
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
template_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None) or
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
)
result = douyin_pixel.detect_fudai_detail_page(
pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi,
template_threshold=template_threshold, return_info=True, analyser=analyser
)
if isinstance(result, tuple):
has_fudai_detail, detect_info = result
# 记录检测信息到日志
try:
task_count = detect_info.get("task_count", 0)
detection_method = detect_info.get("method", "unknown")
method_name = "任务数量检测" if detection_method == "task_count" else "未知"
analyser._log_kv(
"弹窗",
f"检测福袋详情页({method_name})",
task_count=task_count,
method=detection_method,
)
except Exception:
pass
else:
has_fudai_detail = result
except Exception:
pass
# 如果颜色统计显示可能是优惠券,需要严格确认:
# 1. 先进行模板匹配确认(使用 detect_coupon_popup_background)
# 2. 如果模板匹配成功,再进行OCR确认"开心收下"按钮
# 3. 只有模板匹配和OCR都确认时,才判定为优惠券弹窗
# 这样可以避免因识别福袋位置失败而误判为优惠券弹窗
if is_coupon_like_by_color:
try:
# 步骤1:模板匹配确认
template_matched = False
try:
import douyin_pixel
pic_rgb = pic.convert("RGB")
template_matched = douyin_pixel.detect_coupon_popup_background(pic_rgb)
except Exception as e:
try:
analyser._log_kv("弹窗", "模板匹配确认异常", error=str(e))
except Exception:
pass
if not template_matched:
# 模板匹配失败,即使颜色统计偏向优惠券,也不判定为优惠券弹窗
# 可能是识别福袋位置失败,导致点击了错误位置
try:
analyser._log_kv(
"弹窗",
"颜色统计偏向优惠券,但模板匹配未命中,不判定为优惠券弹窗",
说明="可能是识别福袋位置失败,点击了错误位置",
)
except Exception:
pass
return False
# 步骤2:OCR确认"开心收下"按钮(模板匹配成功后)
if has_fudai_detail:
analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认")
else:
analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认")
# 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域)
# 保存完整截图并标注OCR区域
try:
import douyin_screenshot_manager
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
if os.path.exists(pic_path):
pic_check = Image.open(pic_path)
pic_check.load()
pic_rgb_check = pic_check.convert("RGB")
width, height = pic_rgb_check.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140
x1 = int(x1_base * width / rx)
y1 = int(y1_base * height / ry)
x2 = int(x2_base * width / rx)
y2 = int(y2_base * height / ry)
x1 = max(0, min(x1, width - 1))
y1 = max(0, min(y1, height - 1))
x2 = max(0, min(x2, width - 1))
y2 = max(0, min(y2, height - 1))
if x1 < x2 and y1 < y2:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_check,
operation_type="ocr",
picname="参与按钮",
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"purpose": "检测开心收下",
}
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"OCR识别前保存完整截图(参与按钮-检测开心收下)",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
# 并行执行模式0和模式1的OCR(如果启用模式1)
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
coupon_text = ""
if enable_ocr_mode1:
# 并行执行两个OCR模式
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 0)
future_mode1 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 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
else:
# 只使用模式0
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
if coupon_text and "开心收下" in coupon_text:
# 模板匹配 + OCR 都确认,判定为优惠券弹窗
analyser._log_kv("弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50])
return True
else:
# 模板匹配成功,但OCR未确认"开心收下"
# 如果同时检测到福袋详情,优先信任福袋详情
if has_fudai_detail:
analyser._log_kv("弹窗", "模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空")
return False
else:
# 模板匹配成功但OCR未确认,可能是识别福袋位置失败
# 不判定为优惠券弹窗,避免误点返回
analyser._log_kv(
"弹窗",
"模板匹配成功但OCR未确认'开心收下',不判定为优惠券弹窗",
OCR文本=coupon_text[:50] if coupon_text else "空",
说明="可能是识别福袋位置失败,点击了错误位置",
)
return False
except Exception as e:
# 确认过程异常,不判定为优惠券弹窗,避免误判
try:
analyser._log_kv("弹窗", "优惠券确认过程异常,不判定为优惠券弹窗", error=str(e))
except Exception:
pass
return False
# 否则判定为福袋详情页
return False
def read_live_room_title_core(
analyser: Any,
y_pianyi: int,
min_len: int = 3,
) -> Tuple[str, str]:
"""读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。
使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。
"""
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
cands: List[Tuple[str, str, str]] = []
# mid ROI:优先使用更大区域,减少"只截到尾巴1个字"
try:
analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi)
t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0)
cands.append((t, r, 'mid_cc0'))
if len(t or "") < min_len:
t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1)
cands.append((t1, r1, 'mid_cc1'))
except Exception:
pass
# large ROI:进一步扩大,兼容机型/系统字体/刘海偏移
if not cands or max(len(x[0] or "") for x in cands) < min_len:
try:
analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi)
t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0)
cands.append((t2, r2, 'large_cc0'))
if len(t2 or "") < min_len:
t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1)
cands.append((t3, r3, 'large_cc1'))
except Exception:
pass
# small ROI:最后兜底(历史区域),使用优化后的坐标
if not cands or max(len(x[0] or "") for x in cands) <= 1:
try:
analyser.cut_pic(147, 147, 320, 188, '', 'live_room_title_small', y_pianyi)
t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0)
cands.append((t4, r4, 'small_cc0'))
except Exception:
pass
title, raw_text = _pick_best_room_title(cands, min_len)
# 更新 analyser 的属性
try:
analyser.current_room_title_raw = raw_text
if title:
analyser.current_room_title = title
except Exception:
pass
return title, raw_text
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"""执行一次福袋详情识别(本地完整版实现)。
流程:
1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测);
2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage);
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
"""
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
task_count = 0
try:
task_count_from_stage = getattr(analyser, "_fudai_detail_task_count_from_stage", None)
if task_count_from_stage is not None:
task_count = int(task_count_from_stage or 0)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:从阶段检测获取任务数量(无需截图)",
task_count=task_count,
)
except Exception:
pass
else:
# 如果阶段检测未保存任务数量,记录警告日志
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)",
task_count_from_stage=task_count_from_stage,
)
except Exception:
pass
# 使用默认值
task_count = 2
# 清除标志,避免影响后续调用
try:
analyser._fudai_detail_task_count_from_stage = None
except Exception:
pass
# 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底)
# 在获取截图之前就返回错误,避免不必要的截图
if task_count <= 0:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR",
task_count=task_count,
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
except Exception as e:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:获取任务数量异常,使用默认值",
error=str(e),
)
except Exception:
pass
# 异常时使用默认值
task_count = 2
# 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量)
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
pic_rgb = None
try:
if os.path.exists(pic_path):
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
except Exception:
pass
if pic_rgb is None:
try:
analyser._log_kv("福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别")
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "error", tup_err, {"reason": "screenshot_failed"}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
# 识别福袋内容 / 倒计时 / 价值
try:
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
analyser, renwu=task_count
)
except Exception as e:
# 出现异常时,记录错误并返回占位结果
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "error", tup_err, {}
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
is_watch_task = False
try:
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
# 清除标志,避免影响后续调用
if is_watch_task:
try:
analyser._is_watch_task_detected = False
except Exception:
pass
except Exception:
pass
# 如果检测到观看任务,返回 watch_task 状态
if is_watch_task:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
)
except Exception:
pass
now = time.time()
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count}
# 解析倒计时 -> (剩余秒数, 未来时间戳)
countdown_start = time.time()
countdown_end = countdown_start + 60.0
try:
if time_text:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
total_seconds, future_ts = res
try:
total_seconds = int(total_seconds)
except Exception:
total_seconds = int(float(total_seconds or 0))
if total_seconds > 0 and isinstance(future_ts, (int, float)):
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
except Exception:
pass
detail_tuple = (
content or "",
time_text or "",
int(participants or 0),
int(copies or 0),
float(prize_value_yuan or 0.0),
(countdown_start, countdown_end),
)
extra: Dict[str, Any] = {
"task_count": task_count,
}
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="ok",
content=detail_tuple[0],
time_text=detail_tuple[1],
participants=detail_tuple[2],
copies=detail_tuple[3],
prize_value_yuan=detail_tuple[4],
countdown_start=countdown_start,
countdown_end=countdown_end,
task_count=task_count,
)
except Exception:
pass
return "ok", detail_tuple, extra
def read_fudai_detail_with_retries(
analyser: Any,
fudai_x: int,
read_once_callback,
close_detail_callback,
ensure_open_callback,
) -> Tuple:
"""多次重试读取福袋详情,返回 6 字段 detail tuple。
与原版保持兼容:总是返回
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
"""
# 首次识别前等待,确保详情页完全加载
# 如果优化查找器已经验证过详情页,可以减少等待时间
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
if already_verified:
# 已经验证过,只需要短暂等待确保界面稳定
initial_wait = 0.3
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries:优化查找器已验证详情页,缩短等待时间",
initial_wait=initial_wait,
)
except Exception:
pass
# 清除标志,避免影响后续调用
try:
analyser._fudai_detail_verified = False
except Exception:
pass
else:
initial_wait = float(
getattr(analyser, "fudai_detail_initial_wait_seconds", 1.2) or 1.2
)
if initial_wait < 0.8:
initial_wait = 0.8 # 最小0.8秒
try:
analyser.operation.delay(initial_wait)
except Exception:
time.sleep(initial_wait)
max_attempts = 2
try:
max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2)
except Exception:
max_attempts = 2
if max_attempts < 1:
max_attempts = 1
retry_delay = 0.8
try:
retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8)
except Exception:
retry_delay = 0.8
last_tuple: Optional[Tuple] = None
last_status: str = "error"
first_countdown_seconds: Optional[float] = None
first_tuple: Optional[Tuple] = None
first_attempt_time: float = 0.0
for attempt in range(max_attempts):
attempt_start_time = time.time()
status, tup, extra = read_fudai_detail_once(analyser)
last_status = status
if isinstance(tup, tuple) and len(tup) >= 6:
current_tuple = tup[:6]
# 计算当前倒计时秒数
current_countdown_seconds = None
try:
cd = current_tuple[5]
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
cd_start = float(cd[0] or 0.0)
cd_end = float(cd[1] or 0.0)
if cd_start > 0 and cd_end > cd_start:
current_countdown_seconds = cd_end - cd_start
except Exception:
pass
# 记录第一次成功读取的结果(作为基准)
if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok":
first_countdown_seconds = current_countdown_seconds
first_tuple = current_tuple
first_attempt_time = attempt_start_time
last_tuple = current_tuple
# 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误
elif first_countdown_seconds is not None and current_countdown_seconds is not None:
# 计算时间流逝(从第一次读取到现在的时间差)
time_elapsed = attempt_start_time - first_attempt_time
if time_elapsed < 0:
time_elapsed = 0.5 # 默认假设间隔0.5秒
# 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差)
expected_countdown = first_countdown_seconds - time_elapsed
# 计算实际差异(与第一次相比)
diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0)
# 计算与预期的差异(考虑时间流逝)
expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0
# 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误
# 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误
is_inconsistent = (
diff_ratio > 0.3 or
expected_diff_ratio > 0.2 or
current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加
)
if is_inconsistent:
try:
analyser._log_kv(
"福袋详情",
"倒计时识别不一致,判定为识别错误(拒绝本次结果,保留第一次结果)",
attempt=attempt + 1,
first_countdown_seconds=int(first_countdown_seconds),
current_countdown_seconds=int(current_countdown_seconds),
expected_countdown=int(expected_countdown),
time_elapsed=round(time_elapsed, 2),
diff_ratio=round(diff_ratio, 3),
expected_diff_ratio=round(expected_diff_ratio, 3),
)
except Exception:
pass
# 拒绝本次结果,继续使用第一次的结果
current_tuple = first_tuple
# 如果还有重试机会,继续重试
if attempt < max_attempts - 1:
try:
analyser.operation.delay(retry_delay)
except Exception:
time.sleep(retry_delay)
continue
else:
# 倒计时合理,更新为当前结果
last_tuple = current_tuple
# 如果没有第一次结果,直接使用当前结果
elif first_countdown_seconds is None:
last_tuple = current_tuple
# 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试
if status == "ok" or status == "coupon_popup" or status == "watch_task":
break
# 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开
if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero":
if attempt < max_attempts - 1:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries:任务数量为0,尝试重新打开福袋详情页",
attempt=attempt + 1,
max_attempts=max_attempts,
)
except Exception:
pass
# 调用回调函数重新打开福袋详情页
try:
if ensure_open_callback:
ensure_open_callback(analyser, fudai_x)
# 重新打开后等待一段时间,确保页面加载完成
try:
analyser.operation.delay(retry_delay + 0.5)
except Exception:
time.sleep(retry_delay + 0.5)
except Exception as e:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries:重新打开福袋详情页失败",
error=str(e),
)
except Exception:
pass
if attempt < max_attempts - 1:
try:
analyser.operation.delay(retry_delay)
except Exception:
time.sleep(retry_delay)
if last_tuple is None:
now = time.time()
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
cd_start, cd_end = None, None
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
cd_start, cd_end = cd[0], cd[1]
# 如果是优惠券弹窗,记录日志并明确标记
is_coupon_popup = (last_status == "coupon_popup")
is_watch_task = (last_status == "watch_task")
if is_coupon_popup:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理",
status=last_status,
fudai_x=fudai_x,
)
except Exception:
pass
elif is_watch_task:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果:观看X分钟任务,已跳过,关闭详情",
status=last_status,
fudai_x=fudai_x,
)
except Exception:
pass
# 关闭详情页
try:
close_detail_callback(analyser)
analyser.operation.delay(0.5)
except Exception:
pass
# 切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
analyser._log_kv(
"福袋详情",
"检测到观看任务后切换直播间",
)
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
analyser.operation.swipe(
analyser.device_id, start_x, start_y, end_x, end_y, 300
)
analyser.operation.delay(0.5)
except Exception:
pass
else:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果",
status=last_status,
content=content,
time_text=time_text,
participants=participants,
copies=copies,
prize_value_yuan=prize_value_yuan,
countdown_start=cd_start,
countdown_end=cd_end,
fudai_x=fudai_x,
)
except Exception:
pass
# 将状态信息存储在 analyser 中,供调用方检查
try:
analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined]
# 同时保存 extra 信息,用于检查错误原因
if isinstance(extra, dict):
analyser._last_fudai_detail_extra = extra # type: ignore[attr-defined]
else:
analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined]
except Exception:
pass
# 验证福袋详情数据的合理性(仅在成功读取时验证)
if last_status == "ok":
is_valid, reason = validate_fudai_detail(last_tuple, analyser)
if not is_valid:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries:数据验证失败,识别可能出错",
validation_reason=reason,
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
participants=participants,
copies=copies,
time_text=time_text[:30] if time_text else "",
)
# 标记为识别错误
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
except Exception:
pass
return last_tuple
def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]:
"""验证福袋详情数据的合理性。
返回:
(is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错
reason 为失败原因描述
"""
if not isinstance(detail, tuple) or len(detail) < 6:
return False, "detail_tuple_invalid"
content = str(detail[0] or "").strip()
time_text = str(detail[1] or "").strip()
try:
participants = int(detail[2] or 0)
except Exception:
participants = 0
try:
copies = int(detail[3] or 0)
except Exception:
copies = 0
try:
prize_value_yuan = float(detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
countdown_tuple = detail[5]
countdown_start, countdown_end = None, None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
countdown_start = float(countdown_tuple[0] or 0.0)
countdown_end = float(countdown_tuple[1] or 0.0)
except Exception:
pass
# 检查1:内容不能为空(至少要有一些文字)
if not content or len(content.strip()) < 2:
return False, "content_empty_or_too_short"
# 检查2:价值应该大于0(福袋至少应该有价值)
if prize_value_yuan <= 0:
return False, "prize_value_zero_or_negative"
# 检查3:价值应该合理(不能太大,比如超过100万)
if prize_value_yuan > 1000000:
return False, "prize_value_too_large"
# 检查4:倒计时应该合理
if countdown_end is not None and countdown_start is not None:
remain_seconds = countdown_end - countdown_start
# 倒计时不能是负数
if remain_seconds < 0:
return False, "countdown_negative"
# 倒计时不能太长(超过24小时)
if remain_seconds > 24 * 3600:
return False, "countdown_too_long"
# 倒计时不能为0(至少应该有几秒)
if remain_seconds == 0 and not time_text:
return False, "countdown_zero_and_no_time_text"
# 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致
if time_text:
try:
# 解析 time_text 为秒数
import re
m = re.search(r"(\d{1,2})[::](\d{1,2})", time_text)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
# 如果秒数>=60,尝试交换分秒
if ss >= 60 and mm < 60:
mm, ss = ss, mm
# 如果秒数仍然>=60,进行进位
if ss >= 60:
mm += ss // 60
ss = ss % 60
text_seconds = mm * 60 + ss
# 允许一定误差(±10%),但差异过大则判定为识别错误
if text_seconds > 0:
diff_ratio = abs(remain_seconds - text_seconds) / max(text_seconds, 1.0)
if diff_ratio > 0.15: # 差异超过15%视为不一致
return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)"
except Exception:
pass
# 检查5:参与人数应该合理(不能是负数)
if participants < 0:
return False, "participants_negative"
# 检查6:份数应该合理(不能是负数,至少应该是1)
if copies < 0:
return False, "copies_negative"
# 检查7:如果份数为0,但参与人数大于0,可能识别错误
if copies == 0 and participants > 0:
return False, "copies_zero_but_participants_positive"
# 检查8:时间文本应该存在(至少应该有倒计时信息)
if not time_text and (countdown_end is None or countdown_end <= 0):
return False, "no_time_text_and_no_countdown"
# 所有检查通过
return True, "ok"
def is_abnormal_time_value(v: float) -> bool:
"""Shim: treat clearly invalid time values as abnormal."""
if v <= 0:
return True
if v > 24 * 3600 * 7:
return True
return False