diff --git a/douyin/core/io_utils.py b/douyin/core/io_utils.py new file mode 100644 index 0000000..5f6dc18 --- /dev/null +++ b/douyin/core/io_utils.py @@ -0,0 +1,187 @@ +"""文件 IO 与截图镜像辅助函数。 + +从 douyin/core/underlying_operations.py 顶部抽离的模块级函数, +为多个模块提供共用的安全文件替换和截图镜像能力。 + +外部 import 路径已通过 underlying_operations 重新导出,保持向后兼容。 +""" + +from __future__ import annotations + +import logging +import os +import time as time_module +from typing import Optional + +# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 +# 仅在显式设置 EXTERNAL_DOUYIN_FUDAI_DIR 时启用。 +_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip() +_EXTERNAL_AXF_SCREENSHOT = ( + os.path.join(_EXTERNAL_DOUYIN_FUDAI_DIR, "pic", "screenshot.png") + if _EXTERNAL_DOUYIN_FUDAI_DIR + else "" +) + + +def _verify_png_integrity(path: str) -> bool: + """验证 PNG 文件头尾完整性,防止读取半写文件""" + try: + with open(path, "rb") as f: + header = f.read(8) + if len(header) < 8 or header[:4] != b"\x89PNG": + return False + f.seek(-12, 2) # IEND chunk 至少 12 字节 + tail = f.read(12) + return b"IEND" in tail + except Exception: + return False + + +def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool: + """安全地替换文件,处理 Windows 文件锁定问题。 + + 优先 os.replace 原子替换;失败时回退到 shutil.copy2,避免长时间等待。 + 对 PNG 文件会先校验完整性,避免发布半写文件。 + + Args: + tmp_file: 临时文件路径 + out_file: 目标文件路径 + max_retries: 最大重试次数(已优化为 2 次) + + Returns: + True if successful, False otherwise + """ + import shutil + + if not os.path.exists(tmp_file): + return False + + # PNG 完整性校验 + if tmp_file.lower().endswith(".png"): + if not _verify_png_integrity(tmp_file): + logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file) + return False + + # 方法 1:原子替换 + try: + os.replace(tmp_file, out_file) + return True + except (OSError, PermissionError): + pass + + # 方法 2:shutil.copy2(保留元数据) + try: + shutil.copy2(tmp_file, out_file) + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + pass + + # 方法 3:手动复制(最后手段) + try: + with open(tmp_file, "rb") as src, open(out_file, "wb") as dst: + while True: + chunk = src.read(1048576) # 1MB chunks + if not chunk: + break + dst.write(chunk) + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + return False + + +def _ensure_parent_dir(path: str) -> None: + """确保 path 的父目录存在。""" + try: + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + except Exception: + logging.exception("无法创建父目录: %s", path) + + +def _mirror_screenshot_to_external(src_file: str) -> None: + """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 + + 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 + 可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。 + """ + if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1": + return + + mirror_start = time_module.time() + try: + external_path = _EXTERNAL_AXF_SCREENSHOT + if not external_path: + return + external_dir = os.path.dirname(external_path) + if not external_dir: + return + + external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "") + is_network_path = False + if external_base: + if external_base.startswith("\\\\") or external_base.startswith("//"): + is_network_path = True + logging.warning( + "[截图] 检测到网络路径,镜像可能较慢: %s", external_base + ) + elif ":" in external_base and len(external_base) > 3: + logging.debug("[截图] 镜像目标路径: %s", external_path) + + os.makedirs(external_dir, exist_ok=True) + if not os.path.exists(src_file): + return + tmp = external_path + ".tmp" + import shutil + + copy_start = time_module.time() + shutil.copyfile(src_file, tmp) + copy_dur = (time_module.time() - copy_start) * 1000.0 + if copy_dur > 50.0 or is_network_path: + logging.info( + "[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", + copy_dur, + src_file, + tmp, + is_network_path, + ) + + replace_start = time_module.time() + _safe_replace_file(tmp, external_path) + replace_dur = (time_module.time() - replace_start) * 1000.0 + if replace_dur > 50.0 or is_network_path: + logging.info( + "[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", + replace_dur, + is_network_path, + ) + + mirror_total_dur = (time_module.time() - mirror_start) * 1000.0 + if mirror_total_dur > 100.0 or is_network_path: + logging.info( + "[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", + mirror_total_dur, + external_path, + is_network_path, + ) + except Exception: + # 任何错误都不应该影响截图主流程 + pass + + +__all__ = [ + "_verify_png_integrity", + "_safe_replace_file", + "_ensure_parent_dir", + "_mirror_screenshot_to_external", + "_EXTERNAL_DOUYIN_FUDAI_DIR", + "_EXTERNAL_AXF_SCREENSHOT", +] diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index 2fa7cc2..62c8dbe 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -40,183 +40,17 @@ except Exception: _RESAMPLE = Image # 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 -# 仅在显式设置 EXTERNAL_DOUYIN_FUDAI_DIR 时启用,避免绑定某台机器的旧路径。 -_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip() -_EXTERNAL_AXF_SCREENSHOT = ( - os.path.join(_EXTERNAL_DOUYIN_FUDAI_DIR, "pic", "screenshot.png") - if _EXTERNAL_DOUYIN_FUDAI_DIR - else "" +# 这些常量与文件 IO 辅助函数已抽离到 io_utils.py,此处仅为向后兼容重新导出。 +from douyin.core.io_utils import ( + _EXTERNAL_DOUYIN_FUDAI_DIR, + _EXTERNAL_AXF_SCREENSHOT, + _verify_png_integrity, + _safe_replace_file, + _ensure_parent_dir, + _mirror_screenshot_to_external, ) -def _verify_png_integrity(path: str) -> bool: - """验证 PNG 文件头尾完整性,防止读取半写文件""" - try: - with open(path, 'rb') as f: - header = f.read(8) - if len(header) < 8 or header[:4] != b'\x89PNG': - return False - f.seek(-12, 2) # IEND chunk 至少 12 字节 - tail = f.read(12) - return b'IEND' in tail - except Exception: - return False - - -def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool: - """安全地替换文件,处理Windows文件锁定问题。 - - 根本优化:优先使用直接复制而不是替换,避免文件锁定问题。 - 如果文件被占用,直接复制内容而不是等待释放。 - 对于 PNG 文件,会先验证完整性再替换。 - - Args: - tmp_file: 临时文件路径 - out_file: 目标文件路径 - max_retries: 最大重试次数(已优化为2次) - - Returns: - True if successful, False otherwise - """ - import shutil - - if not os.path.exists(tmp_file): - return False - - # 对于 PNG 文件,先验证完整性 - if tmp_file.lower().endswith('.png'): - if not _verify_png_integrity(tmp_file): - logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file) - return False - - # 根本优化:优先尝试原子替换(最快),如果失败则直接复制(避免等待) - try: - # 方法1: 直接使用 os.replace (原子操作,最快) - os.replace(tmp_file, out_file) - return True - except (OSError, PermissionError): - # 如果原子替换失败(文件被占用),直接使用复制方法(避免等待) - # 这样可以避免文件锁定导致的长时间等待 - pass - - # 方法2: 直接复制文件内容(避免文件锁定问题) - # 这是最可靠的方法,即使文件被占用也能成功 - try: - # 使用 shutil.copy2 保留元数据,但速度更快 - shutil.copy2(tmp_file, out_file) - # 复制成功后删除临时文件 - try: - os.remove(tmp_file) - except Exception: - pass - return True - except Exception: - # 如果 shutil.copy2 也失败,使用手动复制(最后手段) - try: - with open(tmp_file, "rb") as src, open(out_file, "wb") as dst: - # 使用更大的块大小提高复制速度(1MB) - while True: - chunk = src.read(1048576) # 1MB chunks - if not chunk: - break - dst.write(chunk) - # 复制成功后删除临时文件 - try: - os.remove(tmp_file) - except Exception: - pass - return True - except Exception: - return False - - -def _ensure_parent_dir(path: str) -> None: - """Ensure the parent directory for `path` exists.""" - try: - parent = os.path.dirname(path) - if parent: - os.makedirs(parent, exist_ok=True) - except Exception: - # 不应因目录创建失败阻塞主流程,记录以便排查 - logging.exception("无法创建父目录: %s", path) - - -def _mirror_screenshot_to_external(src_file: str) -> None: - """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 - - 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 - - 可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。 - """ - # 检查环境变量:是否禁用镜像功能(用于性能测试) - if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1": - return - - mirror_start = time_module.time() - try: - external_path = _EXTERNAL_AXF_SCREENSHOT - if not external_path: - return - external_dir = os.path.dirname(external_path) - if not external_dir: - return - - # 检查外部路径是否是网络路径或可能较慢的路径 - external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "") - is_network_path = False - if external_base: - # 检查是否是网络路径(UNC路径或网络驱动器) - if external_base.startswith("\\\\") or external_base.startswith("//"): - is_network_path = True - logging.warning( - "[截图] 检测到网络路径,镜像可能较慢: %s", external_base - ) - # 检查是否是远程挂载点(简单启发式:包含常见网络挂载标识) - elif ":" in external_base and len(external_base) > 3: - # 可能是网络驱动器,但无法确定,记录路径供诊断 - logging.debug("[截图] 镜像目标路径: %s", external_path) - - os.makedirs(external_dir, exist_ok=True) - if not os.path.exists(src_file): - return - tmp = external_path + ".tmp" - import shutil - - copy_start = time_module.time() - shutil.copyfile(src_file, tmp) - copy_dur = (time_module.time() - copy_start) * 1000.0 - if copy_dur > 50.0 or is_network_path: - logging.info( - "[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", - copy_dur, - src_file, - tmp, - is_network_path, - ) - - replace_start = time_module.time() - _safe_replace_file(tmp, external_path) - replace_dur = (time_module.time() - replace_start) * 1000.0 - if replace_dur > 50.0 or is_network_path: - logging.info( - "[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", - replace_dur, - is_network_path, - ) - - mirror_total_dur = (time_module.time() - mirror_start) * 1000.0 - if mirror_total_dur > 100.0 or is_network_path: - logging.info( - "[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", - mirror_total_dur, - external_path, - is_network_path, - ) - except Exception: - # 任何错误都不应该影响截图主流程 - pass - - class underlying_operations: """底层操作类""" diff --git a/fudai_detail_modules/fudai_detail_coupon_detection.py b/douyin/fudai/core/fudai_detail_coupon_detection.py similarity index 100% rename from fudai_detail_modules/fudai_detail_coupon_detection.py rename to douyin/fudai/core/fudai_detail_coupon_detection.py diff --git a/fudai_detail_modules/fudai_detail_operations.py b/douyin/fudai/core/fudai_detail_operations.py similarity index 100% rename from fudai_detail_modules/fudai_detail_operations.py rename to douyin/fudai/core/fudai_detail_operations.py diff --git a/fudai_detail_modules/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_orchestrator.py similarity index 99% rename from fudai_detail_modules/fudai_detail_reader.py rename to douyin/fudai/core/fudai_detail_orchestrator.py index 63729bf..510ebe8 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_orchestrator.py @@ -14,7 +14,7 @@ import time from PIL import Image from douyin.fudai.douyin_fudai_core import get_fudai_contain -from .fudai_detail_validator import validate_fudai_detail +from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py deleted file mode 100644 index 5e8c8fa..0000000 --- a/douyin/fudai/core/fudai_detail_reader.py +++ /dev/null @@ -1,1245 +0,0 @@ -"""福袋详情读取模块 - -包含获取福袋内容、倒计时、参与人数等详细信息的功能。 -""" - -from __future__ import annotations - -import re -import time -import os -from typing import Tuple, Any -from concurrent.futures import ThreadPoolExecutor - -from douyin.core import path_config -from douyin.fudai.core.fudai_debug_utils import _save_full_screenshot_with_ocr_region -from douyin.fudai.core.fudai_filter import is_watch_task_fudai -from douyin.utils.douyin_utils import extract_prize_value_yuan - - -# 更新:将福袋价值识别区域左下角调整为 (656, 1656) -# 格式: (left, top, right, bottom) -from douyin.fudai.core.coords import ( - VALUE_BOX_TARGET, - CONTENT_BOX, - COUNTDOWN_1110_1230, - COUNTDOWN_1140_1290, - COUNTDOWN_1010_1130, - COUNTDOWN_1460_1580, - TASK_LIST, -) - - -def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: - """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" - - def _parse_mm_ss(text: str): - m = re.search(r"(\d{1,2})[::](\d{2})", str(text or "")) - if not m: - return None - try: - return int(m.group(1)), int(m.group(2)) - except Exception as e: - try: - analyser._log_kv( - "验证", - "解析倒计时格式失败", - error=str(e), - error_type=type(e).__name__, - text=text[:50] if text else "", - level="WARNING", - ) - except Exception: - pass - return None - - def _extract_2digits(text: str) -> str: - digits = "".join(ch for ch in str(text or "") if ch.isdigit()) - if len(digits) >= 2: - return digits[:2] - if len(digits) == 1: - return "0" + digits - return "" - - def _read_countdown_split(box: tuple[int, int, int, int]) -> str: - """将倒计时区域分割成"分钟段"和"秒段",分别OCR识别,然后组合为 mm:ss。 - - 优化:更精确的分割方式,避免识别顺序错误。 - 倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。 - """ - try: - x1, y1, x2, y2 = box - w = max(1, int(x2 - x1)) - # h 变量保留用于将来可能的垂直分割优化 - # h = max(1, int(y2 - y1)) # 当前未使用,但保留以备将来使用 - - # 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖 - # 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和"后开奖") - # 这样可以更精确地定位到数字区域,避免识别到冒号或"后开奖"文字 - seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 - seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - - # 保存调试截图 - try: - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_分钟", - (x1, y1, x1 + seg1, y2), - analyser.y_pianyi, - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "保存倒计时调试截图失败", - error=str(e), - error_type=type(e).__name__, - box=box, - level="WARNING", - ) - except Exception: - pass - - # 切割分钟区域(左侧) - analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi - ) - # 切割秒区域(中间,跳过冒号) - analyser.cut_pic( - x1 + seg1, - y1, - x1 + seg1 + seg2, - y2, - "", - "福袋倒计时_秒", - analyser.y_pianyi, - ) - - # 并行执行两个OCR识别(使用轻量数字OCR),优先对裁剪图做预处理以提升识别率 - try: - from douyin.utils.ocr_preprocess import preprocess_for_ocr - - mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟") - ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒") - except Exception: - mm_name = "福袋倒计时_分钟" - ss_name = "福袋倒计时_秒" - - with ThreadPoolExecutor(max_workers=2) as executor: - future_mm = executor.submit( - analyser.operation.analyse_pic_digits, mm_name, 1 - ) - future_ss = executor.submit( - analyser.operation.analyse_pic_digits, ss_name, 1 - ) - mm_raw = future_mm.result() - ss_raw = future_ss.result() - - # 提取数字:分钟和秒都应该是1-2位数字 - def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位,智能处理前导零""" - digits = "".join(ch for ch in str(text or "") if ch.isdigit()) - if len(digits) > max_digits: - # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) - # 例如"002" -> "02" 而不是 "00" - candidate = digits[-max_digits:] - # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 - if candidate.startswith("0") and not digits.startswith( - "0" * len(digits) - ): - # 移除前导零后的长度 - actual_digits = digits.lstrip("0") or "0" - if len(actual_digits) <= max_digits: - return actual_digits.zfill(max_digits) - return candidate - if len(digits) == 1: - return "0" + digits - return digits - - mm = _extract_digits(mm_raw, max_digits=2) - ss = _extract_digits(ss_raw, max_digits=2) - - # 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正 - # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果) - try: - mm_int = int(mm) if mm else 0 - ss_int = int(ss) if ss else 0 - if ss_int >= 60: - try: - analyser._log_kv( - "验证", - "分割识别:检测到秒数>=60(可能是识别错误)", - mm=mm_int, - ss=ss_int, - mm_raw=mm_raw, - ss_raw=ss_raw, - level="WARNING", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "错误", - "验证倒计时数值失败", - error=str(e), - error_type=type(e).__name__, - mm=mm, - ss=ss, - level="WARNING", - ) - except Exception: - pass - - if mm and ss: - result = f"{mm}:{ss}" - try: - analyser._log_kv( - "福袋倒计时", - "分割识别成功", - mm_raw=mm_raw, - ss_raw=ss_raw, - result=result, - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录倒计时识别成功日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return result - except Exception as e: - try: - analyser._log_kv( - "福袋倒计时", - "分割识别失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - return "" - - def _extract_participants_and_clean(text: str): - if not text: - return 0, 0, "" - compact = re.sub(r"\s+", "", str(text)) - # 例如:共1份1173人已参与 - copies = 0 - participants = 0 - m = re.search(r"共(\d+)份", compact) - if m: - copies = int(m.group(1)) - m = re.search(r"(\d+)人已参与", compact) - if m: - participants = int(m.group(1)) - - # 清理掉份数/参与人数等尾巴,避免干扰关键词匹配 - cleaned = re.sub(r"共\d+份", "", compact) - cleaned = re.sub(r"\d+人已参与", "", cleaned) - return participants, copies, cleaned - - countdown_box = None - if renwu == 2: # 如果是2个任务的 - # 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等) - # 从1240向上扩展到1100,确保包含任务描述区域 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi - ) - analyser.cut_pic( - *CONTENT_BOX, "", "福袋内容", analyser.y_pianyi - ) # 福袋内容详情(包含任务描述) - # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 - countdown_box = COUNTDOWN_1110_1230 - # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 - x1, y1, x2, y2 = countdown_box - w = max(1, int(x2 - x1)) - seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 - seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) - analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - analyser.cut_pic( - x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi - ) - # 优化:向上扩大范围(1460->1440),防止识别不完整 - value_box = VALUE_BOX_TARGET - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", value_box, analyser.y_pianyi - ) - analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) - elif renwu == 1: # 如果是1个任务的 - # 优化:扩大Y范围向上,确保包含任务描述 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi - ) - analyser.cut_pic( - *CONTENT_BOX, "", "福袋内容", analyser.y_pianyi - ) # 福袋内容详情(包含任务描述) - # 优化:稍微扩大高度,确保完整 - # 优化:向上扩大区域,确保完整识别倒计时数字 - countdown_box = COUNTDOWN_1140_1290 - # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 - x1, y1, x2, y2 = countdown_box - w = max(1, int(x2 - x1)) - seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 - seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) - analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - analyser.cut_pic( - x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi - ) - # 优化:向上扩大范围(1520->1500),防止识别不完整 - value_box = VALUE_BOX_TARGET - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", value_box, analyser.y_pianyi - ) - analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) - elif renwu == 3: # 如果是3个任务的 - # 优化:扩大Y范围向上,确保包含任务描述 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi - ) - analyser.cut_pic( - *CONTENT_BOX, "", "福袋内容", analyser.y_pianyi - ) # 福袋内容详情(包含任务描述) - # 优化:稍微扩大高度 - countdown_box = COUNTDOWN_1010_1130 - # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 - x1, y1, x2, y2 = countdown_box - w = max(1, int(x2 - x1)) - seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 - seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) - analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - analyser.cut_pic( - x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi - ) - # 优化:向上扩大范围(1380->1360),防止识别不完整 - value_box = VALUE_BOX_TARGET - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", value_box, analyser.y_pianyi - ) - analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) - else: - # 优化:稍微缩小宽度,增加高度 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi - ) - analyser.cut_pic( - *CONTENT_BOX, "", "福袋内容", analyser.y_pianyi - ) # 福袋内容详情 - # 优化:稍微扩大高度 - countdown_box = COUNTDOWN_1460_1580 - # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 - x1, y1, x2, y2 = countdown_box - w = max(1, int(x2 - x1)) - seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 - seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) - analyser.cut_pic( - x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - analyser.cut_pic( - x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi - ) - # 优化:向上扩大范围(1820->1800),防止识别不完整 - value_box = VALUE_BOX_TARGET - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", value_box, analyser.y_pianyi - ) - analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) - - # 准备任务列表区域的截图(用于并行OCR) - # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 - try: - # 保存任务列表区域的调试截图 - _save_full_screenshot_with_ocr_region( - analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi - ) - analyser.cut_pic(*TASK_LIST, "", "福袋任务列表", analyser.y_pianyi) - except Exception as e: - # 任务列表截图失败不影响后续流程,记录日志即可 - try: - analyser._log_kv( - "福袋", - "任务列表截图失败,继续后续流程", - error=str(e), - ) - except Exception: - pass - - # 并行执行五个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值 - # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 - ocr_start_time = time.time() - task_list_raw = None - fudai_content_raw = None - countdown_mm_raw = None - countdown_ss_raw = None - value_raw = None - - # 读取配置开关:优先使用 analyser 属性覆盖,其次读取 config.json - try: - disable_content_recognition = bool( - getattr(analyser, "fudai_disable_content_recognition", False) - ) - except Exception: - disable_content_recognition = False - if not disable_content_recognition: - try: - import json - - cfg_path = path_config.get_config_path() - if cfg_path and os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) - disable_content_recognition = bool( - cfg.get("fudai_disable_content_recognition", False) - ) - except Exception: - pass - - # 读取任务列表OCR开关 - try: - disable_task_recognition = bool( - getattr(analyser, "fudai_disable_task_recognition", False) - ) - except Exception: - disable_task_recognition = False - if not disable_task_recognition: - try: - import json - - cfg_path = path_config.get_config_path() - if cfg_path and os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) - disable_task_recognition = bool( - cfg.get("fudai_disable_task_recognition", False) - ) - except Exception: - pass - - def ocr_task_list(): - """OCR识别任务列表(用于检测观看任务)""" - try: - from douyin.utils.ocr_preprocess import preprocess_for_ocr - - name_tl = preprocess_for_ocr(analyser, "福袋任务列表") - return analyser.operation.analyse_pic_word(name_tl, 0) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别任务列表失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_content(): - """OCR识别福袋内容""" - if disable_content_recognition: - try: - analyser._log_kv( - "福袋", - "跳过福袋内容OCR识别(配置启用)", - ) - except Exception: - pass - return None - try: - from douyin.utils.ocr_preprocess import preprocess_for_ocr - - name_fc = preprocess_for_ocr(analyser, "福袋内容") - return analyser.operation.analyse_pic_word(name_fc, 0) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别福袋内容失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_countdown_mm(): - """OCR识别福袋倒计时分钟(使用轻量数字OCR)""" - try: - return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别倒计时分钟失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_countdown_ss(): - """OCR识别福袋倒计时秒(使用轻量数字OCR)""" - try: - return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别倒计时秒失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_value(): - """OCR识别福袋价值(使用普通OCR)""" - try: - from douyin.utils.ocr_preprocess import preprocess_for_ocr - - name_val = preprocess_for_ocr(analyser, "福袋价值") - return analyser.operation.analyse_pic_word(name_val, 0) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别福袋价值失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) - # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 - try: - # 使用动态线程池大小,根据CPU核心数优化 - from operations.screenshot_service import get_optimal_workers - - optimal_workers = get_optimal_workers() - with ThreadPoolExecutor(max_workers=optimal_workers) as executor: - if disable_task_recognition: - future_task_list = None - else: - future_task_list = executor.submit(ocr_task_list) - # 有条件地提交 content OCR,避免在配置启用时仍然调度任务 - if disable_content_recognition: - future_content = None - else: - future_content = executor.submit(ocr_content) - future_countdown_mm = executor.submit(ocr_countdown_mm) - future_countdown_ss = executor.submit(ocr_countdown_ss) - future_value = executor.submit(ocr_value) - - # 等待所有操作完成 - task_list_raw = future_task_list.result() if future_task_list else None - fudai_content_raw = future_content.result() if future_content else None - countdown_mm_raw = future_countdown_mm.result() - countdown_ss_raw = future_countdown_ss.result() - value_raw = future_value.result() - - # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) - if task_list_raw: - try: - analyser._log_kv( - "福袋", - "OCR识别任务列表区域", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录任务列表OCR结果日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 检查任务列表中是否包含"观看X分钟"任务 - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: - try: - analyser._log_kv( - "福袋", - "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录观看任务检测日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e: - try: - analyser._log_kv( - "错误", - "设置观看任务标志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - - ocr_elapsed = time.time() - ocr_start_time - try: - analyser._log_kv( - "性能", - "并行OCR识别完成(任务数量已在前置检测中获取)", - elapsed_seconds=round(ocr_elapsed, 3), - task_count=renwu, - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录OCR性能日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - except Exception as e: - # 如果并行执行失败,回退到备用并行执行(使用新的线程池) - try: - analyser._log_kv( - "错误", - "并行OCR失败,使用备用并行执行", - error=str(e), - error_type=type(e).__name__, - level="ERROR", - ) - except Exception: - pass - # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) - try: - - def ocr_task_list_fallback(): - try: - return analyser.operation.analyse_pic_word("福袋任务列表", 0) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "备用OCR识别任务列表失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_content_fallback(): - if disable_content_recognition: - try: - analyser._log_kv( - "福袋", - "跳过备用福袋内容OCR识别(配置启用)", - ) - except Exception: - pass - return None - try: - return analyser.operation.analyse_pic_word("福袋内容", 0) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "备用OCR识别福袋内容失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_countdown_mm_fallback(): - try: - return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "备用OCR识别倒计时分钟失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_countdown_ss_fallback(): - try: - return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "备用OCR识别倒计时秒失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - def ocr_value_fallback(): - try: - return analyser.operation.analyse_pic_word("福袋价值", 0) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "备用OCR识别福袋价值失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return None - - # 使用动态线程池大小,根据CPU核心数优化 - from operations.screenshot_service import get_optimal_workers - - optimal_workers = get_optimal_workers() - with ThreadPoolExecutor(max_workers=optimal_workers) as executor: - if disable_task_recognition: - future_task_list = None - else: - future_task_list = executor.submit(ocr_task_list_fallback) - future_content = executor.submit(ocr_content_fallback) - future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) - future_countdown_ss = executor.submit(ocr_countdown_ss_fallback) - future_value = executor.submit(ocr_value_fallback) - - # 等待所有操作完成 - task_list_raw = future_task_list.result() if future_task_list else None - fudai_content_raw = future_content.result() if future_content else None - countdown_mm_raw = future_countdown_mm.result() - countdown_ss_raw = future_countdown_ss.result() - value_raw = future_value.result() - - # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) - if task_list_raw: - try: - analyser._log_kv( - "福袋", - "OCR识别任务列表区域(备用并行)", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录备用任务列表OCR结果日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 检查任务列表中是否包含"观看X分钟"任务 - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: - try: - analyser._log_kv( - "福袋", - "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", - task_list_text=( - task_list_raw[:200] if task_list_raw else "" - ), - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录备用观看任务检测日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "设置备用观看任务标志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - except Exception as fallback_error: - # 如果备用并行执行也失败,使用串行执行作为最后兜底 - try: - analyser._log_kv( - "错误", - "备用并行OCR也失败,使用串行执行作为最后兜底", - error=str(fallback_error), - error_type=type(fallback_error).__name__, - level="ERROR", - ) - except Exception: - pass - # 串行执行所有OCR(包括任务列表OCR) - try: - task_list_raw = analyser.operation.analyse_pic_word("福袋任务列表", 0) - # 检查任务列表中是否包含"观看X分钟"任务 - if task_list_raw: - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: - try: - analyser._is_watch_task_detected = True - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "设置串行观看任务标志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - return "", "", 0, 0, 0.0 - except Exception as e_serial: - try: - analyser._log_kv( - "错误", - "串行OCR识别任务列表失败", - error=str(e_serial), - error_type=type(e_serial).__name__, - level="ERROR", - ) - except Exception: - pass - fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0) - countdown_mm_raw = analyser.operation.analyse_pic_digits( - "福袋倒计时_分钟", 1 - ) - countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) - value_raw = analyser.operation.analyse_pic_word("福袋价值", 0) - - # 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息) - is_watch_task = False - if fudai_content_raw: - try: - is_watch_task = is_watch_task_fudai(str(fudai_content_raw)) - if is_watch_task: - try: - analyser._log_kv( - "福袋", - "OCR识别到'观看X分钟'类任务,直接跳过后续处理", - raw_content=( - fudai_content_raw[:100] if fudai_content_raw else "" - ), - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录观看任务检测日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e: - try: - analyser._log_kv( - "错误", - "设置观看任务标志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - except Exception as e: - try: - analyser._log_kv( - "错误", - "检查观看任务失败", - error=str(e), - error_type=type(e).__name__, - raw_content=fudai_content_raw[:100] if fudai_content_raw else "", - level="WARNING", - ) - except Exception: - pass - - participants, copies, fudai_content_text = _extract_participants_and_clean( - fudai_content_raw if fudai_content_raw is not None else "" - ) - - # 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认 - if not is_watch_task and fudai_content_text: - try: - is_watch_task = is_watch_task_fudai(fudai_content_text) - if is_watch_task: - try: - analyser._log_kv( - "福袋", - "OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理", - content=fudai_content_text[:100] if fudai_content_text else "", - ) - except Exception: - pass - # 设置标志 - try: - analyser._is_watch_task_detected = True - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - except Exception: - pass - - # 输出福袋内容(使用明确的格式,便于GUI解析) - content_for_log = fudai_content_text if fudai_content_text else "未识别到" - analyser._log_kv( - "福袋", - f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见 - level="INFO", - content=content_for_log, # 同时作为字段输出 - ) - - # 记录进入直播间到识别到福袋的耗时(仅记录一次) - try: - if getattr(analyser, "_enter_live_ts", 0.0) and not getattr( - analyser, "_enter_live_fudai_logged", False - ): - try: - secs = float(time.time() - float(analyser._enter_live_ts or 0.0)) - except Exception: - secs = -1.0 - reason = str(getattr(analyser, "_enter_live_reason", "") or "") - analyser._log_kv( - "性能", - "进入直播间到识别福袋耗时", - seconds=round(secs, 2), - enter_reason=reason, - ) - try: - analyser._enter_live_fudai_logged = True - except Exception: - pass - if copies: - analyser._log_kv( - "福袋", - "识别福袋信息", - copies=copies, - participants=participants if participants else 0, - ) - except Exception: - pass - - # 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR - time_text = "" # 初始化为空字符串,确保类型为 str - try: - # 提取数字:分钟和秒都应该是1-2位数字 - def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位,智能处理前导零""" - digits = "".join(ch for ch in str(text or "") if ch.isdigit()) - if len(digits) > max_digits: - # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) - # 例如"002" -> "02" 而不是 "00" - candidate = digits[-max_digits:] - # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 - if candidate.startswith("0") and not digits.startswith( - "0" * len(digits) - ): - # 移除前导零后的长度 - actual_digits = digits.lstrip("0") or "0" - if len(actual_digits) <= max_digits: - return actual_digits.zfill(max_digits) - return candidate - if len(digits) == 1: - return "0" + digits - return digits - - mm = _extract_digits(countdown_mm_raw, max_digits=2) if countdown_mm_raw else "" - ss = _extract_digits(countdown_ss_raw, max_digits=2) if countdown_ss_raw else "" - - # OCR结果验证:检查倒计时识别结果是否为空 - if not countdown_mm_raw and not countdown_ss_raw: - try: - analyser._log_kv( - "验证", - "倒计时OCR结果完全为空", - level="WARNING", - ) - except Exception: - pass - elif not mm or not ss: - try: - analyser._log_kv( - "验证", - "倒计时OCR结果不完整", - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - mm_extracted=mm, - ss_extracted=ss, - level="WARNING", - ) - except Exception: - pass - - # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果) - try: - mm_int = int(mm) if mm else 0 - ss_int = int(ss) if ss else 0 - - # 数值范围验证 - if mm_int < 0 or mm_int >= 60: - try: - analyser._log_kv( - "验证", - "倒计时分钟数值超出合理范围", - mm=mm_int, - mm_raw=countdown_mm_raw, - level="WARNING", - ) - except Exception: - pass - - if ss_int >= 60: - try: - analyser._log_kv( - "验证", - "倒计时秒数>=60(可能是识别错误)", - mm=mm_int, - ss=ss_int, - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - level="WARNING", - ) - except Exception: - pass - elif ss_int < 0: - try: - analyser._log_kv( - "验证", - "倒计时秒数<0(可能是识别错误)", - ss=ss_int, - ss_raw=countdown_ss_raw, - level="WARNING", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "错误", - "验证倒计时数值失败", - error=str(e), - error_type=type(e).__name__, - mm=mm, - ss=ss, - level="WARNING", - ) - except Exception: - pass - - if mm and ss: - time_text = f"{mm}:{ss}" - try: - analyser._log_kv( - "福袋倒计时", - "分割识别成功", - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - result=time_text, - ) - except Exception: - pass - else: - # 识别失败,time_text 保持为空字符串 - try: - analyser._log_kv( - "福袋倒计时", - "分割识别失败(分钟或秒为空)", - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - ) - except Exception: - pass - except Exception as e: - # 异常时,time_text 保持为空字符串 - try: - analyser._log_kv( - "福袋倒计时", - "分割识别异常", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - analyser._log_kv( - "福袋", "识别倒计时", countdown=time_text if time_text else "未识别到" - ) - - prize_value_yuan = extract_prize_value_yuan( - value_raw if value_raw is not None else "" - ) - - # OCR结果验证:检查价值识别结果 - if not value_raw: - try: - analyser._log_kv( - "验证", - "价值OCR结果为空", - level="WARNING", - ) - except Exception: - pass - elif prize_value_yuan: - # 验证价值数值是否合理 - try: - value_float = float(prize_value_yuan) - if value_float < 0: - try: - analyser._log_kv( - "验证", - "价值数值<0(可能是识别错误)", - value_yuan=prize_value_yuan, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - elif value_float > 100000: # 价值超过10万可能不合理 - try: - analyser._log_kv( - "验证", - "价值数值异常大(可能是识别错误)", - value_yuan=prize_value_yuan, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "错误", - "验证价值数值失败", - error=str(e), - error_type=type(e).__name__, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - - if float(prize_value_yuan).is_integer(): - show_value = int(prize_value_yuan) - else: - show_value = prize_value_yuan - analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value) - else: - # value_raw不为空但提取失败 - try: - analyser._log_kv( - "验证", - "价值OCR结果无法解析", - value_raw=value_raw[:100] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - - return fudai_content_text, time_text, participants, copies, prize_value_yuan diff --git a/fudai_detail_modules/fudai_detail_room_title.py b/douyin/fudai/core/fudai_detail_room_title.py similarity index 100% rename from fudai_detail_modules/fudai_detail_room_title.py rename to douyin/fudai/core/fudai_detail_room_title.py diff --git a/fudai_detail_modules/fudai_detail_utils.py b/douyin/fudai/core/fudai_detail_utils.py similarity index 100% rename from fudai_detail_modules/fudai_detail_utils.py rename to douyin/fudai/core/fudai_detail_utils.py diff --git a/fudai_detail_modules/fudai_detail_validator.py b/douyin/fudai/core/fudai_detail_validator.py similarity index 100% rename from fudai_detail_modules/fudai_detail_validator.py rename to douyin/fudai/core/fudai_detail_validator.py diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index ca1bb08..6c4a0f7 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -5,10 +5,33 @@ from __future__ import annotations +import re import time from typing import Any, Tuple +def _is_short_countdown_text(time_text: str) -> bool: + """检查倒计时文本是否表示剩余时间很短(应跳过)""" + if not time_text: + return False + + time_text = time_text.strip() + + # 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒 + if re.match(r"^00:0[0-2]$", time_text): + return True + + # 匹配 0:00, 0:01, 0:02 等(有时没有前导零) + if re.match(r"^0:0[0-2]$", time_text): + return True + + # 匹配 "00秒", "01秒", "02秒" 等 + if re.match(r"^0[0-2]秒$", time_text): + return True + + return False + + def check_contain(analyser, contains: str = "") -> bool: """检查福袋内容是否命中"黑名单"关键词(只保留黑名单逻辑,不再使用白名单)。 diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 50d12e4..d3fab38 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -1,17 +1,25 @@ from __future__ import annotations +import os import re import time -import os import threading from typing import Tuple, Any, Optional, Dict -from PIL import Image # type: ignore[import] from concurrent.futures import ThreadPoolExecutor -import numpy as np # type: ignore[import] from douyin.utils.douyin_utils import extract_prize_value_yuan -from douyin.reservation import douyin_reservation_logic from douyin.core import path_config +from douyin.fudai.core.fudai_filter import ( + is_watch_task_fudai, + _is_short_countdown_text, + check_contain, +) +from douyin.fudai.core.fudai_result_checker import ( + check_lucky_draw_result, + check_have_reward_notice_confirm, + check_in_order_confirm_page, + get_reward, +) # 从新模块导入调试工具函数 from douyin.fudai.core.fudai_debug_utils import ( @@ -97,34 +105,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo force_light = ocr_mode == "light" force_heavy = ocr_mode == "heavy" - def _parse_mm_ss(text: str): - m = re.search(r"(\d{1,2})[::](\d{2})", str(text or "")) - if not m: - return None - try: - return int(m.group(1)), int(m.group(2)) - except Exception as e_inner: # pyright: ignore - try: - analyser._log_kv( # pyright: ignore - "验证", - "解析倒计时格式失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - text=text[:50] if text else "", - level="WARNING", - ) - except Exception: # pyright: ignore - pass - return None - - def _extract_2digits(text: str) -> str: - digits = "".join(ch for ch in str(text or "") if ch.isdigit()) - if len(digits) >= 2: - return digits[:2] - if len(digits) == 1: - return "0" + digits - return "" - def _read_countdown_split(box: tuple[int, int, int, int]) -> str: """将倒计时区域分割成"分钟段"和"秒段",分别OCR识别,然后组合为 mm:ss。 @@ -1010,7 +990,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo start = time.time() try: # 导入直播间标题识别函数 - from fudai_detail_modules.fudai_detail_room_title import _ocr_try_room_title + from douyin.fudai.core.fudai_detail_room_title import _ocr_try_room_title # 使用已切割的图片进行OCR识别 title, raw_text = _ocr_try_room_title(analyser, "live_room_title_mid", 0) @@ -2148,4274 +2128,78 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo return fudai_content_text, time_text, participants, copies, prize_value_yuan -def check_contain(analyser, contains: str = "") -> bool: - """检查福袋内容是否命中“黑名单”关键词(只保留黑名单逻辑,不再使用白名单)。 +# check_contain 已迁移到 douyin.fudai.core.fudai_filter(顶部导入)。 +# 此处保留模块级名称以兼容历史 from douyin_fudai_core import check_contain。 - 返回值语义(调整后): - - True : “建议丢弃”(内容命中黑名单 contains_not_want) - - False : “可以保留”(未命中黑名单) - """ - # 以下抑制为静态检查方便添加: - # - W0212: protected-access(许多地方访问分析器/底层对象的受保护属性,运行时可用) - # - W0718: broad-exception-caught(代码中大量使用 broad except 用于鲁棒性) - # 这些抑制只影响静态检查,不改变运行时行为。 - # pylint: disable=W0212,W0718 - try: - for contain in getattr(analyser, "contains_not_want", []) or []: - if contain and contain in (contains or ""): - try: - analyser._log_kv( - "筛选", - "福袋内容命中黑名单,将丢弃", - keyword=contain, - contains=contains[:80] if contains else "", - ) - except Exception: - pass - return True +def attend_choujiang(analyser) -> bool: # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_attend。""" + from douyin.fudai.core.fudai_attend import attend_choujiang as _impl - try: - analyser._log_kv( - "筛选", - "福袋内容未命中黑名单,保留", - contains=contains[:80] if contains else "", - ) - except Exception: - pass - return False - except Exception: - # 容错:异常时不过滤 - try: - analyser._log_kv( - "筛选", - "check_contain 异常,默认保留", - contains=contains[:80] if contains else "", - ) - except Exception: - pass - return False + return _impl(analyser) -def attend_choujiang(analyser) -> bool: - """点击参与抽奖。""" - # 优先委派到 core/fudai_attend.py 中的实现(该实现包含预处理与增强OCR) - try: - from douyin.fudai.core.fudai_attend import attend_choujiang as external_attend # type: ignore - - # 如果外部实现存在,直接调用并返回结果 - return external_attend(analyser) - except Exception: - # 无法委派时回退到本地实现(保持向后兼容) - pass - - analyser.last_attend_fail_reason = "" - click_times = 0 - while click_times < 2: - from douyin.fudai.core.coords import PARTICIPATE_BUTTON - - analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮") # 参与福袋抽奖的文字 - # 优化:尝试多种OCR模式提高精准度(优先保证精准) - name_part0b = preprocess_for_ocr(analyser, "参与按钮") - attend_button_text = str( - analyser.operation.analyse_pic_word(name_part0b, 0) or "" - ) - if not attend_button_text or not any( - k in attend_button_text - for k in ( - "参与成功", - "还需看播", - "评论", - "参与抽奖", - "开始观看", - "参与", - "加入粉丝团", - "粉丝团", - ) - ): - name_part1b = preprocess_for_ocr(analyser, "参与按钮") - attend_button_text = str( - analyser.operation.analyse_pic_word(name_part1b, 1) or "" - ) - analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) - if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖 - analyser._log_kv("参与", "已参与,等待开奖", result="已参与") - - # 记录统计:检测到已参与也算作成功参与一次,但避免同一个直播间同一个福袋重复记录 - try: - room_title = getattr(analyser, "current_room_title", "") - fudai_content = getattr(analyser, "_current_fudai_content", "") - key = (room_title, fudai_content) - if key not in getattr(analyser, "_recorded_fudai_stats", set()): - analyser._recorded_fudai_stats.add(key) - analyser._log_kv( - "统计", - "metric", - metric="fudai_attend", - metric_type="success", - run_id=getattr(analyser, "_run_id", ""), - source="already_attended", - future_ts=int( - getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - ), - ) - except Exception: - pass - - # 记录最后一次成功参与的时间 - try: - analyser._last_successful_attend_ts = time.time() - except Exception: - pass - - # 记录已参与的福袋(通过 future_ts 标识),避免重复参与 - future_ts = 0.0 - try: - # 从 detail 中获取 future_ts(如果可用) - future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - if future_ts > 0: - participated_fudai_ts = getattr( - analyser, "_participated_fudai_future_ts", set() - ) - if not isinstance(participated_fudai_ts, set): - participated_fudai_ts = set() - participated_fudai_ts.add(future_ts) - analyser._participated_fudai_future_ts = participated_fudai_ts - analyser._log_kv( - "参与", - "记录已参与福袋", - future_ts=future_ts, - total_participated=len(participated_fudai_ts), - ) - except Exception: - pass - - # 设置开奖等待状态(如果 future_ts 可用) - if future_ts > 0: - try: - current_time = time.time() - remain_seconds = max(0, future_ts - current_time) - if remain_seconds > 0: - # 设置等待开奖标志和预期开奖时间 - analyser._waiting_for_lottery_result = True - analyser._lottery_result_expected_ts = future_ts - analyser._lottery_wait_start_ts = current_time - analyser._log_kv( - "参与", - "参与成功,设置等待开奖标志", - remain_seconds=int(remain_seconds), - future_ts=int(future_ts), - lottery_result_expected_ts=int( - analyser._lottery_result_expected_ts - ), - ) - else: - analyser._log_kv( - "参与", - "参与成功,但倒计时已过期,不设置等待标志", - future_ts=int(future_ts), - remain_seconds=int(remain_seconds), - ) - except Exception as e_inner: - analyser._log_kv( - "参与", - "设置开奖等待状态时出错", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - - # 设置标志:已经关闭了详情,避免后续再次点击返回键 - try: - analyser._detail_closed_by_attend = True - except Exception: - pass - - analyser.click(500, 470) # 点击刚才打开福袋的旁边位置 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - return True - elif ("活动已结束" in attend_button_text) or ( - "活动己结束" in attend_button_text - ): - # 活动结束:按一次返回键退出详情 - analyser.last_attend_fail_reason = "activity_ended" - try: - analyser._log_kv( - "参与", "活动已结束:按返回键退出详情", result="activity_ended" - ) - analyser._log_kv("参与", "参与抽奖失败", result="失败") - except Exception: - pass - try: - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(0.5) - except Exception: - try: - analyser.click(500, 470) - except Exception: - pass - return False - elif "还需看播" in attend_button_text: # 如果识别到需要看播 - analyser.last_attend_fail_reason = "watch_required" - analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛") - analyser._log_kv("参与", "参与抽奖失败", result="失败") - analyser.click(500, 470) - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - return False - elif "无法参与" in attend_button_text: - analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与") - analyser._log_kv("参与", "参与抽奖失败", result="失败") - analyser.click(500, 470) - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - return False - elif "时长不足" in attend_button_text: - analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足") - analyser._log_kv("参与", "参与抽奖失败", result="失败") - analyser.click(500, 470) - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - return False - elif "评论" in attend_button_text: - # 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80 - # 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070 - analyser.click(543, 2070) - analyser._log_kv( - "参与", - "点击参与抽奖(基于截图优化坐标)", - action="点击参与", - mode="评论", - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", - ) - - # 记录参与成功日志,用于GUI统计 - analyser._log_kv("参与", "参与成功", result="参与成功") - - # 记录统计:成功参与抽奖(评论模式),避免同一个直播间同一个福袋重复记录 - try: - room_title = getattr(analyser, "current_room_title", "") - fudai_content = getattr(analyser, "_current_fudai_content", "") - key = (room_title, fudai_content) - if key not in getattr(analyser, "_recorded_fudai_stats", set()): - analyser._recorded_fudai_stats.add(key) - analyser._log_kv( - "统计", - "metric", - metric="fudai_attend", - metric_type="success", - run_id=getattr(analyser, "_run_id", ""), - source="comment_attend", - future_ts=int( - getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - ), - ) - except Exception: - pass - - return True - elif "参与抽奖" in attend_button_text: - # 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80 - # 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070 - analyser.click(543, 2070) - analyser._log_kv( - "参与", - "点击参与抽奖(基于截图优化坐标)", - action="点击参与", - mode="普通", - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", - ) - - # 记录参与成功日志,用于GUI统计 - analyser._log_kv("参与", "参与成功", result="参与成功") - - # 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测 - # 注意:点击参与按钮后会自动关闭详情页,返回直播间 - try: - analyser._skip_stage_diagnosis_and_find_fudai = True - except Exception: - pass - - # 设置等待开奖标志,避免参与后立即切换直播间 - try: - # 从 detail 中获取 future_ts(如果可用) - future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - if future_ts > 0: - current_time = time.time() - remain_seconds = int(future_ts - current_time) - if remain_seconds > 0: - # 设置等待开奖标志和预期开奖时间 - analyser._waiting_for_lottery_result = True - analyser._lottery_result_expected_ts = future_ts - analyser._lottery_wait_start_ts = current_time - analyser._log_kv( - "参与", - "点击参与抽奖后,设置等待开奖标志", - future_ts=int(future_ts), - remain_seconds=remain_seconds, - expected_result_ts=int( - analyser._lottery_result_expected_ts - ), - ) - except Exception as e_inner: - try: - analyser._log_kv( - "参与", - "点击参与抽奖后,设置等待开奖标志时出错", - error=str(e_inner), - ) - except Exception: - pass - - analyser._log_kv( - "参与", - "点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测", - ) - - # 记录统计:成功参与抽奖,避免同一个直播间同一个福袋重复记录 - try: - room_title = getattr(analyser, "current_room_title", "") - fudai_content = getattr(analyser, "_current_fudai_content", "") - key = (room_title, fudai_content) - if key not in getattr(analyser, "_recorded_fudai_stats", set()): - analyser._recorded_fudai_stats.add(key) - analyser._log_kv( - "统计", - "metric", - metric="fudai_attend", - metric_type="success", - run_id=getattr(analyser, "_run_id", ""), - source="new_attend", - future_ts=int( - getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - ), - ) - except Exception: - pass - - return True - elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text: - # 需要粉丝团门槛:先点击参与按钮,再使用OCR识别"加入粉丝团"按钮位置并点击,最后关闭详情页 - analyser.last_attend_fail_reason = "fansclub_required" - - # 保存debug截图:标注OCR识别区域(参与按钮区域) - try: - import importlib - - douyin_screenshot_manager = importlib.import_module( - "douyin.handlers.douyin_screenshot_manager" - ) - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - width, height = pic_rgb.size - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(306 * width / rx) - ocr_y1 = int(2030 * height / ry) - ocr_x2 = int(780 * width / rx) - ocr_y2 = int(2110 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="参与按钮", - step="识别参与按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": attend_button_text[:50], - "region": "(306,2030)-(780,2110)", - "result": "需要粉丝团", - }, - ) - except Exception: - pass - - # 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) - analyser.click(543, 2070) - analyser._log_kv( - "参与", - "粉丝团门槛:先点击参与按钮", - result="需要粉丝团", - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", - ) - analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快 - - # 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置) - try: - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - - # OCR识别区域(扩大范围以便更容易识别) - ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = ( - 150, - 1900, - 950, - 2200, - ) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - # 尝试模式0 - try: - # 获取裁剪后的图片路径 - pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") - if pic_path and os.path.exists(pic_path): - img = Image.open(pic_path) - img = img.convert("RGB") - img_np = np.array(img) - - # 调用OCR获取原始结果 - if getattr(analyser.operation, "ocr_type", None) == "easyocr": - ocr_result = analyser.operation.ocr.readtext(img_np) - else: - ocr_result = analyser.operation.ocr.ocr(img_np) - if ocr_result == [None]: - ocr_result = [] - - # 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox - if isinstance(ocr_result, list) and ocr_result: - # PaddleOCR格式:[[[box], (text, score)], ...] - # EasyOCR格式:[(bbox, text, confidence), ...] - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - # 提取文本和bbox - if isinstance(item, (list, tuple)): - if len(item) >= 2: - # EasyOCR格式:[(bbox, text, confidence), ...] - if ( - isinstance(item[0], (list, tuple)) - and len(item[0]) >= 2 - ): - bbox = item[0] # bbox是第一个元素 - if isinstance(item[1], str): - text = item[1] - # PaddleOCR格式:[box, (text, score)] - elif ( - isinstance(item[1], (list, tuple)) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance(item[0], (list, tuple)) - else None - ) - if isinstance(item[1][0], str): - text = item[1][0] - - # 检查是否包含"加入粉丝团"或"粉丝团" - if ( - text - and ("加入粉丝团" in text or "粉丝团" in text) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception as e_inner: - analyser._log_kv( - "参与", - "获取OCR原始结果失败", - error=str(e_inner), - level="WARNING", - ) - - # 如果模式0没有找到,尝试模式1(使用analyse_pic_word) - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "" - ) - - # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) - try: - import importlib - - douyin_screenshot_manager = importlib.import_module( - "douyin.handlers.douyin_screenshot_manager" - ) - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - width, height = pic_rgb.size - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(ocr_region_x1 * width / rx) - ocr_y1 = int(ocr_region_y1 * height / ry) - ocr_x2 = int(ocr_region_x2 * width / rx) - ocr_y2 = int(ocr_region_y2 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="加入粉丝团按钮", - step="识别加入粉丝团按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": fansclub_text[:50] if fansclub_text else "", - "region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - "result": ( - "识别成功" - if fansclub_text - and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ) - else "识别失败" - ), - "has_bbox": fansclub_bbox is not None, - }, - ) - except Exception: - pass - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - # 提取bbox的坐标点 - xs = [] - ys = [] - for p in fansclub_bbox: - if isinstance(p, (list, tuple)) and len(p) >= 2: - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - # 计算bbox中心(在裁剪图片中的坐标) - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - - # 将裁剪图片坐标转换为全屏坐标 - # 需要加上OCR区域的偏移 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - - # 缩放到实际分辨率 - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception as e_inner: - analyser._log_kv( - "参与", - "计算bbox中心失败", - error=str(e_inner), - level="WARNING", - ) - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) - click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) - - analyser.operation.click(analyser.device_id, click_x, click_y) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - base_x=( - int((ocr_region_x1 + ocr_region_x2) / 2) - if click_x is None - else None - ), - base_y=( - int((ocr_region_y1 + ocr_region_y2) / 2) - if click_y is None - else None - ), - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - else: - # OCR未识别到"加入粉丝团",使用OCR区域中心作为备选 - region_center_x = int( - (ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080 - ) - region_center_y = int( - (ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400 - ) - analyser.operation.click( - analyser.device_id, region_center_x, region_center_y - ) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)", - ocr_text=fansclub_text[:50] if fansclub_text else "", - x=region_center_x, - y=region_center_y, - base_x=(ocr_region_x1 + ocr_region_x2) // 2, - base_y=(ocr_region_y1 + ocr_region_y2) // 2, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - ) - analyser.operation.delay(1.2) # 等待点击完成(适当延长) - except Exception as e_inner: - analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e_inner)) - - # 第三步:关闭详情页 - analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - - if not analyser.auto_join_fansclub: - analyser._log_kv( - "参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15 - ) - analyser.operation.delay(15) - - # 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。 - def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool: - for i in range(int(max_steps or 4)): - try: - analyser._shot_and_diagnose( - "粉丝团", - "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), - analyser.device_id, - ) - except Exception: - pass - try: - st, seen = analyser._diagnose_stage_from_current_screen() - except Exception: - st, seen = "", "" - - if st == "FUDai_DETAIL": - return True - - if st == "FANSCLUB_JOIN": - # 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置) - analyser._log_kv( - "参与", - "粉丝团加入页:点击加入粉丝团", - stage=st, - seen=seen, - attempt=i + 1, - ) - try: - # 点击加入粉丝团按钮 - # 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200 - # 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素 - # 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006 - # 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心) - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - # 点击红色文字区域的中心(基于截图分析优化) - click_x = int(540 * rx // 1080) # 区域中心X - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y(基于截图:1940+132/2=2006) - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_x=540, - base_y=2006, - region="(200,1940)-(880,2140)", - red_area_center_y=2006, - ) - analyser.operation.delay(0.5) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200) - ocr_click_success = False - try: - from douyin.fudai.core.coords import ( - JOIN_FANSCLUB_REGION, - ) - - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = JOIN_FANSCLUB_REGION - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - try: - pic_path = analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - if pic_path and os.path.exists(pic_path): - img = Image.open(pic_path) - img = img.convert("RGB") - img_np = np.array(img) - - if ( - getattr( - analyser.operation, "ocr_type", None - ) - == "easyocr" - ): - ocr_result = ( - analyser.operation.ocr.readtext(img_np) - ) - else: - ocr_result = analyser.operation.ocr.ocr( - img_np - ) - if ocr_result == [None]: - ocr_result = [] - - if isinstance(ocr_result, list) and ocr_result: - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance(item, (list, tuple)): - if len(item) >= 2: - if ( - isinstance( - item[0], (list, tuple) - ) - and len(item[0]) >= 2 - ): - bbox = item[0] - if isinstance(item[1], str): - text = item[1] - elif ( - isinstance( - item[1], (list, tuple) - ) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - (list, tuple), - ) - else None - ) - if isinstance( - item[1][0], str - ): - text = item[1][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - xs = [] - ys = [] - for p in fansclub_bbox: - if ( - isinstance(p, (list, tuple)) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x, - click_y, - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - ocr_click_success = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text[:50] - if fansclub_text - else "空" - ), - level="WARNING", - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败,使用坐标点击", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) - or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay(1.0) # 等待返回完成 - except Exception as e_inner: - analyser._log_kv( - "参与", - "恢复流程:点击返回直播间失败", - error=str(e_inner), - ) - except Exception: - # 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮) - try: - analyser.click(540, 2006) # 粉丝团加入按钮优化坐标 - except Exception: - # 最后回退到旧坐标 - try: - analyser.click(500, 2060) - except Exception: - pass - - # 等待加入流程完成(根据是否启用自动加入决定等待时间) - auto_join_enabled = getattr( - analyser, "auto_join_fansclub", False - ) - if auto_join_enabled: - # 启用自动加入:等待更长时间,让加入流程完成 - analyser.operation.delay(5.0) - analyser._log_kv( - "参与", - "已启用自动加入粉丝团,等待加入流程完成", - wait_seconds=5.0, - ) - else: - # 未启用自动加入:等待较短时间后返回 - analyser.operation.delay(3.0) - analyser._log_kv( - "参与", - "未启用自动加入粉丝团,等待后返回", - wait_seconds=3.0, - ) - - # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - return_x = int(545 * rx // 1080) - return_y = int(1995 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "加入粉丝团成功后,点击指定位置", - x=return_x, - y=return_y, - base_x=545, - base_y=1995, - ) - analyser.operation.delay(1.0) # 等待点击完成 - - # 关闭详情页 - analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - analyser.operation.delay(1.0) # 等待关闭完成 - except Exception as e_inner: - analyser._log_kv( - "参与", - "点击指定位置或关闭详情页失败", - error=str(e_inner), - ) - - # 重新诊断阶段,确认是否还在粉丝团加入页 - try: - analyser.operation.get_screenshot( - analyser.device_id, use_service=False - ) - st_after, seen_after = ( - analyser._diagnose_stage_from_current_screen() - ) - analyser._log_kv( - "参与", - "点击加入粉丝团后重新诊断阶段", - stage_before=st, - stage_after=st_after, - seen_after=seen_after, - ) - - if st_after == "FANSCLUB_JOIN": - # 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间 - if auto_join_enabled: - # 如果启用了自动加入,尝试再次点击 - analyser._log_kv( - "参与", "仍在粉丝团加入页,尝试再次点击" - ) - try: - # 基于截图优化坐标:红色区域中心Y=2006 - rx = int( - getattr( - analyser, "resolution_ratio_x", 1080 - ) - or 1080 - ) - ry = int( - getattr( - analyser, "resolution_ratio_y", 2400 - ) - or 2400 - ) - click_x = int(540 * rx // 1080) - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y=2006 - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_y=2006, - ) - analyser.operation.delay( - 0.5 - ) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION - from douyin.fudai.core.coords import ( - JOIN_FANSCLUB_REGION, - ) - - ocr_click_success_retry = False - try: - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = JOIN_FANSCLUB_REGION - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text_retry = "" - fansclub_bbox_retry = None - - try: - pic_path = ( - analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - ) - if pic_path and os.path.exists( - pic_path - ): - img = Image.open(pic_path) - img = img.convert("RGB") - img_np = np.array(img) - - if ( - getattr( - analyser.operation, - "ocr_type", - None, - ) - == "easyocr" - ): - ocr_result = analyser.operation.ocr.readtext( - img_np - ) - else: - ocr_result = ( - analyser.operation.ocr.ocr( - img_np - ) - ) - if ocr_result == [None]: - ocr_result = [] - - if ( - isinstance(ocr_result, list) - and ocr_result - ): - items = ( - ocr_result[0] - if ( - isinstance( - ocr_result, list - ) - and len(ocr_result) == 1 - and isinstance( - ocr_result[0], list - ) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance( - item, (list, tuple) - ): - if len(item) >= 2: - if ( - isinstance( - item[0], - ( - list, - tuple, - ), - ) - and len(item[0]) - >= 2 - ): - bbox = item[0] - if isinstance( - item[1], str - ): - text = item[ - 1 - ] - elif ( - isinstance( - item[1], - ( - list, - tuple, - ), - ) - and len(item[1]) - >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - ( - list, - tuple, - ), - ) - else None - ) - if isinstance( - item[1][0], - str, - ): - text = item[ - 1 - ][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text_retry = ( - text - ) - fansclub_bbox_retry = ( - bbox - ) - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text_retry: - fansclub_text_retry = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text_retry and ( - "加入粉丝团" in fansclub_text_retry - or "粉丝团" in fansclub_text_retry - ): - click_x_retry = None - click_y_retry = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox_retry: - try: - xs = [] - ys = [] - for p in fansclub_bbox_retry: - if ( - isinstance( - p, (list, tuple) - ) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = ( - min(xs) + max(xs) - ) / 2 - bbox_center_y = ( - min(ys) + max(ys) - ) / 2 - full_x = ( - ocr_region_x1 - + bbox_center_x - ) - full_y = ( - ocr_region_y1 - + bbox_center_y - ) - click_x_retry = int( - full_x * rx // 1080 - ) - click_y_retry = int( - full_y * ry // 2400 - ) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if ( - click_x_retry is None - or click_y_retry is None - ): - click_x_retry = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y_retry = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x_retry, - click_y_retry, - ) - analyser._log_kv( - "参与", - "恢复流程:再次第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text_retry[:50], - x=click_x_retry, - y=click_y_retry, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox_retry - is not None, - ) - ocr_click_success_retry = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text_retry[:50] - if fansclub_text_retry - else "空" - ), - level="WARNING", - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败(重试),使用坐标点击", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success_retry: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:再次第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:再次两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay( - 1.0 - ) # 等待返回完成 - except Exception as e_inner: - analyser._log_kv( - "参与", - "恢复流程:再次点击返回直播间失败", - error=str(e_inner), - ) - analyser.operation.delay(3.0) - except Exception: - # 回退到优化后的坐标(粉丝团加入按钮) - try: - analyser.click(540, 2006) # 第一次点击 - analyser.operation.delay(0.5) - analyser.click( - 540, 2006 - ) # 第二次点击(连续点击两次确保成功) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr( - analyser, - "resolution_ratio_x", - 1080, - ) - or 1080 - ) - ry = int( - getattr( - analyser, - "resolution_ratio_y", - 2400, - ) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, - return_x, - return_y, - ) - analyser._log_kv( - "参与", - "恢复流程:回退逻辑两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay( - 1.0 - ) # 等待返回完成 - except Exception as e_inner: - analyser._log_kv( - "参与", - "恢复流程:回退逻辑点击返回直播间失败", - error=str(e_inner), - ) - analyser.operation.delay(3.0) - except Exception: - # 最后回退到旧坐标 - try: - analyser.click(500, 2060) - analyser.operation.delay(3.0) - except Exception: - pass - else: - # 未启用自动加入,直接返回 - analyser._log_kv( - "参与", "仍在粉丝团加入页,未启用自动加入,返回" - ) - try: - analyser.operation.click_back( - analyser.device_id - ) - analyser.operation.delay(1) - except Exception: - pass - elif st_after == "FUDai_DETAIL": - # 已经回到福袋详情页,说明加入成功 - analyser._log_kv( - "参与", "已回到福袋详情页,加入流程可能已完成" - ) - return True - elif st_after in ( - "IN_LIVE_ROOM", - "FOLLOW_LIST", - "LIVE_LIST", - ): - # 如果之前是在粉丝团加入页,现在显示在直播间,可能是误判 - # 实际上可能还在加入成功的页面,需要点击返回键 - analyser._log_kv( - "参与", - "点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键", - stage_before="FANSCLUB_JOIN", - stage_after=st_after, - ) - try: - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(1.0) - # 点击返回后再次诊断,看是否回到福袋详情页 - try: - analyser.operation.get_screenshot( - analyser.device_id - ) - st_after_back, seen_after_back = ( - analyser._diagnose_stage_from_current_screen() - ) - analyser._log_kv( - "参与", - "点击返回后重新诊断阶段", - stage_after_back=st_after_back, - seen_after_back=seen_after_back, - ) - if st_after_back == "FUDai_DETAIL": - analyser._log_kv( - "参与", "点击返回后已回到福袋详情页" - ) - return True - elif st_after_back in ( - "IN_LIVE_ROOM", - "FOLLOW_LIST", - "LIVE_LIST", - ): - analyser._log_kv( - "参与", - "点击返回后确实回到直播间,停止继续返回", - stage=st_after_back, - ) - return False - except Exception: - pass - except Exception: - pass - return False - else: - # 其他阶段,尝试返回 - analyser._log_kv( - "参与", - "点击后进入其他阶段,尝试返回", - stage=st_after, - ) - try: - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(1) - except Exception: - pass - except Exception as e_inner: - # 诊断失败,保守处理:如果启用了自动加入,不返回;否则返回 - analyser._log_kv( - "参与", "重新诊断阶段失败", error=str(e_inner) - ) - if not auto_join_enabled: - try: - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(1) - except Exception: - pass - continue - - # 已经回到直播间/列表时:尝试重新打开福袋详情页 - if st in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"): - analyser._log_kv( - "参与", - "已离开福袋详情:尝试重新打开福袋详情页", - stage=st, - seen=seen, - ) - # 尝试重新打开福袋详情页 - try: - # 延迟导入避免循环导入 - import douyin.core.douyin_flow_control as douyin_flow_control - - room_pos_ref = [0] - opened = douyin_flow_control.find_and_open_fudai_detail( - analyser, room_pos_ref - ) - if opened: - # 验证是否成功打开福袋详情页 - analyser.operation.delay(0.5) - try: - analyser.operation.get_screenshot( - analyser.device_id - ) - st_after, seen_after = ( - analyser._diagnose_stage_from_current_screen() - ) - if st_after == "FUDai_DETAIL": - analyser._log_kv( - "参与", - "重新打开福袋详情页成功", - stage=st_after, - ) - return True - else: - analyser._log_kv( - "参与", - "重新打开福袋详情页后未在详情页", - stage=st_after, - seen=seen_after, - ) - except Exception as e_inner: - analyser._log_kv( - "参与", - "重新打开后验证阶段失败", - error=str(e_inner), - ) - except Exception as e_inner: - analyser._log_kv( - "参与", "重新打开福袋详情页失败", error=str(e_inner) - ) - # 如果重新打开失败,返回 False - return False - - # 其它未知弹窗:尝试一次返回 - analyser._log_kv( - "参与", "粉丝团流程:尝试返回", stage=st, seen=seen - ) - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - analyser.operation.delay(1) - return False - - ok = _recover_to_fudai_detail_after_fansclub() - if ok: - analyser._log_kv( - "参与", "粉丝团流程结束:已回到福袋详情", result="回到详情" - ) - return attend_choujiang(analyser) - - analyser._log_kv( - "参与", "粉丝团流程失败:未回到福袋详情", result="粉丝团门槛仍未解决" - ) - analyser.operation.delay(1.2) - try: - analyser.operation.get_screenshot(analyser.device_id, use_service=False) - except Exception: - pass - if analyser.check_in_fudai_detail(): - analyser._log_kv( - "参与", "粉丝团流程失败:仍在详情页,执行关闭", stage="FUDai_DETAIL" - ) - try: - analyser.click(500, 470) - except Exception: - pass - analyser.operation.delay(0.8) - else: - analyser._log_kv( - "参与", "粉丝团流程失败:已不在详情页,视为已退出", stage="UNKNOWN" - ) - try: - analyser._log_kv( - "参与", "粉丝团门槛仍未解决", result="粉丝团门槛仍未解决" - ) - except Exception: - pass - return False - else: - # 未识别到任何可用文案:再尝试一次 - analyser._log_kv( - "参与", "未识别到可用参与按钮文案", text=attend_button_text or "" - ) - click_times += 1 - analyser.operation.delay(1) - continue - analyser._log_kv("参与", "参与抽奖多次点击失败", result="多次失败") - return False - - -def check_lucky_draw_result(analyser): - """判定福袋抽奖的结果(简化)。 - - 统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr), - 不再对弹窗文字或其它区域进行OCR识别。 - 返回:1='我知道了', 2='立即领取奖品', False=未识别 - """ - try: - from douyin.utils.douyin_helpers import HelperFunctions - - detected = HelperFunctions.check_lottery_result_by_ocr(analyser) - if detected == "我知道了": - return 1 - if detected == "立即领取奖品": - return 2 - return False - except Exception: - return False - - -def check_have_reward_notice_confirm(analyser) -> bool: - """判断是否有领奖的二次确认提醒。""" - analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id) - analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认") - reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1) - if "我知道了" in (reward_notice_confirm or ""): - try: - analyser._log_kv( - "开奖诊断", - "存在奖品领取提醒", - text=(reward_notice_confirm or "")[:80], - ) - except Exception: - pass - return True - return False - - -def check_in_order_confirm_page(analyser) -> bool: - """判断是否在中奖下单后的购买成功的页面。""" - analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id) - analyser.cut_pic(370, 120, 700, 220, "", "订单确认") - order_confirm = analyser.operation.analyse_pic_word("订单确认") - if "购买成功" in (order_confirm or ""): - try: - analyser._log_kv( - "开奖诊断", - "订单确认页面:购买成功", - text=(order_confirm or "")[:80], - ) - except Exception: - pass - return True - return False - - -def get_reward(analyser, reward_y: int = 0) -> None: - """中奖后领奖然后返回。""" - analyser.operation.save_reward_pic(analyser.device_id) - try: - analyser._log_kv("领奖", "保存中奖截图", step="save_reward_pic") - except Exception: - pass - - analyser.click(243, reward_y) # 勾选协议 - analyser.operation.delay(1) - analyser.click(540, reward_y - 140) # 点击领取 - try: - analyser._log_kv("领奖", "勾选协议并点击领取", reward_y=reward_y) - except Exception: - pass - - analyser.operation.delay(5) - analyser.click(886, 2170) # 点击下单 - try: - analyser._log_kv("领奖", "点击下单") - except Exception: - pass - analyser.operation.delay(10) - - # 循环检查下单结果,增加保护避免极端死循环 - max_checks = 5 - checks = 0 - while checks < max_checks and check_in_order_confirm_page(analyser): - checks += 1 - analyser.operation.click_back(analyser.device_id) - try: - analyser._log_kv("领奖", "点击回退按钮", check_round=checks) - except Exception: - pass - analyser.operation.delay(4) - - try: - analyser._log_kv("领奖", "下完单返回到直播间", checks=checks) - except Exception: - pass - analyser.operation.delay(4) - - if check_lucky_draw_result(analyser): - try: - analyser._log_kv("领奖", "领奖弹窗未关闭,准备关闭") - except Exception: - pass - analyser.click(540, reward_y + 180) - try: - analyser._log_kv( - "领奖", - "点击关闭领奖弹窗", - x=540, - y=(reward_y + 180) * analyser.resolution_ratio_y // 2400, - ) - except Exception: - pass - analyser.operation.delay(2) - analyser.operation.save_reward_pic(analyser.device_id) - try: - analyser._log_kv("领奖", "保存关闭领奖弹窗后的截图") - except Exception: - pass - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(2) - - if check_have_reward_notice_confirm(analyser): - try: - analyser._log_kv("领奖", "提醒领奖弹窗未关闭,点击我知道了") - except Exception: - pass - analyser.click(540, 1400) - analyser.operation.delay(2) - - try: - analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30) - except Exception: - pass - analyser.operation.delay(30) - - -def is_watch_task_fudai(content: str) -> bool: - """检测是否为"观看X分钟"类任务福袋。 - - 参数: - content: 福袋内容文本 - - 返回: - True 表示是"观看X分钟"类任务,应放弃 - False 表示不是此类任务 - """ - if not content: - return False - - try: - - # 将内容转换为字符串并去除空白 - content_str = re.sub(r"\s+", "", str(content)) - - # 中文数字字符 - chinese_num_chars = "零一二三四五六七八九十百千两" - - # 匹配模式1:观看/看 + (可选"直播") + 数字或中文数字 + 分钟 - patt1 = rf"(?:观看|看)(?:直播)?(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" - - # 匹配模式2:需要观看/需要看 + 数字或中文数字 + 分钟 - patt2 = rf"需要(?:观看|看)(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" - - # 匹配模式3:观看时长 + 数字或中文数字 + 分钟 - patt3 = rf"观看时长(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" - - # 匹配模式4:看播 + 数字或中文数字 + 分钟 - patt4 = rf"看播(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟" - - # 检查是否匹配任一模式 - patterns = [patt1, patt2, patt3, patt4] - for patt in patterns: - if re.search(patt, content_str): - return True - - return False - except Exception: - return False - - -def _is_short_countdown_text(time_text: str) -> bool: - """检查倒计时文本是否表示剩余时间很短(应跳过)""" - if not time_text: - return False - - time_text = time_text.strip() - - # 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒 - if re.match(r"^00:0[0-2]$", time_text): - return True - - # 匹配 0:00, 0:01, 0:02 等(有时没有前导零) - if re.match(r"^0:0[0-2]$", time_text): - return True - - # 匹配 "00秒", "01秒", "02秒" 等 - if re.match(r"^0[0-2]秒$", time_text): - return True - - return False - - -def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: - """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 - - 返回: - (skip, reason) 其中 reason 为简单文字原因,便于日志查看。 - """ - start_time = time.time() - # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if not needswitch: - try: - analyser._log_kv( - "筛选", - "单间模式:忽略所有福袋阈值配置,直接参与", - needswitch=0, - ) - except Exception: - pass - return False, "single_room_mode" - - if not isinstance(detail, tuple) or len(detail) < 6: - return False, "detail_tuple_invalid" - - content = str(detail[0] or "") - - # 优先检查是否为"观看X分钟"类任务:若是,直接放弃 - if is_watch_task_fudai(content): - try: - analyser._log_kv( - "筛选", - "检测到'观看X分钟'类任务,自动放弃", - content=content[:80] if content else "", - reason="watch_task_detected", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(观看任务)", - elapsed_seconds=round(elapsed, 2), - ) - return True, "watch_task_detected" - time_text = str(detail[1] or "") - 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 - - cd_start, cd_end = None, None - if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2: - cd_start, cd_end = detail[5][0], detail[5][1] - now = time.time() - remain_seconds = None - try: - if isinstance(cd_end, (int, float)) and cd_end > now: - remain_seconds = float(cd_end - now) - try: - analyser._log_kv( - "筛选", - "倒计时计算成功", - cd_end=cd_end, - now=now, - 剩余秒数=remain_seconds, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时计算失败或已过期", - cd_end=cd_end, - now=now, - cd_end类型=type(cd_end).__name__, - cd_end大于now=( - bool(isinstance(cd_end, (int, float)) and cd_end > now) - if isinstance(cd_end, (int, float)) - else False - ), - ) - except Exception: - pass - except Exception as e_inner: - remain_seconds = None - try: - analyser._log_kv( - "筛选", - "倒计时计算异常", - 异常=str(e_inner), - 异常类型=type(e_inner).__name__, - ) - except Exception: - pass - - # 读取配置阈值 - try: - min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0) - except Exception: - min_value = 0.0 - try: - min_participants = int(getattr(analyser, "min_participants", 0) or 0) - except Exception: - min_participants = 0 - try: - max_participants = int(getattr(analyser, "max_participants", 0) or 0) - except Exception: - max_participants = 0 - skip_if_gt = 0 # Initialize before try block - try: - skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0) - except Exception: - skip_if_gt = 0 - skip_if_lt = 0 # Initialize before try block - try: - skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0) - except Exception: - skip_if_lt = 0 - - # 获取按钮文本,用于记录 - button_text = str(getattr(analyser, "button_text_raw", "") or "").strip() - - # 记录所有配置值和实际值,便于调试 - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config 开始检查", - ) - analyser._log_kv( - "筛选", - "配置参数", - 最小价值=min_value, - 最小参与人数=min_participants, - 最大参与人数=max_participants, - 倒计时大于秒数=skip_if_gt, - 倒计时小于秒数=skip_if_lt, - ) - analyser._log_kv( - "筛选", - "实际数据", - 价值=prize_value_yuan, - 参与人数=participants, - 份数=copies, - 剩余秒数=int(remain_seconds) if remain_seconds is not None else None, - 内容=content[:60] if content else "", - 按钮文本=button_text if button_text else "未识别", - ) - except Exception: - pass - - # 并行检查所有筛选条件,收集所有不符合的原因 - skip_reasons = [] - - # 1) 价值过滤 - if min_value > 0: - if prize_value_yuan > 0: - if prize_value_yuan < min_value: - skip_reasons.append(f"value_lt_{min_value}") - try: - analyser._log_kv( - "筛选", - "价值过滤:不符合(价值过低)", - 实际价值=prize_value_yuan, - 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} < {min_value} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "价值过滤:通过", - 实际价值=prize_value_yuan, - 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} >= {min_value} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "价值过滤:跳过(未识别到价值)", - 实际价值=prize_value_yuan, - ) - except Exception: - pass - - # 2) 参与人数过滤 - if min_participants > 0: - if participants > 0: - if participants < min_participants: - skip_reasons.append(f"participants_lt_{min_participants}") - try: - analyser._log_kv( - "筛选", - "参与人数过滤:不符合(小于最小值)", - 实际参与人数=participants, - 配置最小参与人数=min_participants, - 判断条件=f"{participants} < {min_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:通过(最小值检查)", - 实际参与人数=participants, - 配置最小参与人数=min_participants, - 判断条件=f"{participants} >= {min_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:跳过(未识别到参与人数)", - 实际参与人数=participants, - ) - except Exception: - pass - - if max_participants > 0: - if participants > 0: - if participants > max_participants: - skip_reasons.append(f"participants_gt_{max_participants}") - try: - analyser._log_kv( - "筛选", - "参与人数过滤:不符合(大于最大值)", - 实际参与人数=participants, - 配置最大参与人数=max_participants, - 判断条件=f"{participants} > {max_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:通过(最大值检查)", - 实际参与人数=participants, - 配置最大参与人数=max_participants, - 判断条件=f"{participants} <= {max_participants} = True", - ) - except Exception: - pass - - # 2.5) 倒计时文本过滤:如果OCR识别的倒计时文本表示剩余时间很短,直接跳过 - if _is_short_countdown_text(time_text): - skip_reasons.append("countdown_text_short") - try: - analyser._log_kv( - "筛选", - "倒计时文本过滤:不符合(OCR识别到剩余时间很短)", - 倒计时文本=time_text, - 实际剩余秒数=( - int(remain_seconds) if remain_seconds is not None else None - ), - ) - except Exception: - pass - - # 3) 倒计时过滤 - # 3.1) 倒计时小于阈值:直接丢弃(不参与) - if skip_if_lt > 0: - if remain_seconds is not None: - if remain_seconds < skip_if_lt: - skip_reasons.append(f"countdown_lt_{skip_if_lt}") - try: - analyser._log_kv( - "筛选", - "倒计时过滤:不符合(剩余秒数小于阈值)", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_lt, - 判断条件=f"{remain_seconds} < {skip_if_lt} = True", - ) - except Exception: - pass - - # 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约) - if skip_if_gt > 0: - if remain_seconds is not None: - if remain_seconds > skip_if_gt: - skip_reasons.append(f"countdown_gt_{skip_if_gt}") - try: - analyser._log_kv( - "筛选", - "倒计时过滤:不符合(剩余秒数大于阈值)", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} > {skip_if_gt} = True", - 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:通过", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} <= {skip_if_gt} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:跳过(未识别到倒计时或倒计时已过期)", - 剩余秒数=remain_seconds, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)", - 配置阈值秒数=skip_if_gt, - ) - except Exception: - pass - - # 4) 内容关键词过滤(复用 check_contain 逻辑) - content_check_result = check_contain(analyser, content) - if content_check_result: - skip_reasons.append("content_not_wanted") - try: - analyser._log_kv( - "筛选", - "内容关键词过滤:不符合", - 内容=content[:60] if content else "", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "内容关键词过滤:通过", - 内容=content[:60] if content else "", - ) - except Exception: - pass - - # 5) 按钮文本过滤:检查按钮是否显示无法参与、还需看播等状态 - try: - if button_text: - # 检查是否包含无法参与的关键词 - unable_to_participate_keywords = [ - "无法参与", - "不能参与", - "不可参与", - "还没到时间", - "活动已结束", - "活动结束", - "已结束", - "已过期", - "已截止", - "时长不足", - ] - watch_required_keywords = [ - "还需看播", - "观看", - "看播", - "观看时长", - "观看分钟", - ] - - # 检查无法参与关键词 - for keyword in unable_to_participate_keywords: - if keyword in button_text: - skip_reasons.append("button_unable_to_participate") - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:不符合(无法参与)", - 按钮文本=button_text, - 匹配关键词=keyword, - ) - except Exception: - pass - break - - # 检查观看要求关键词 - for keyword in watch_required_keywords: - if keyword in button_text: - skip_reasons.append("button_watch_required") - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:不符合(观看任务)", - 按钮文本=button_text, - 匹配关键词=keyword, - ) - except Exception: - pass - break - - if not any(reason.startswith("button_") for reason in skip_reasons): - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:通过", - 按钮文本=button_text, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:跳过(未识别到按钮文本)", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:异常", - 异常=str(e), - 异常类型=type(e).__name__, - ) - except Exception: - pass - - # 如果有任何不符合的条件,就跳过 - if skip_reasons: - elapsed = time.time() - start_time - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(不符合条件,跳过)", - 不符合原因=skip_reasons, - 总原因数=len(skip_reasons), - elapsed_seconds=round(elapsed, 2), - ) - except Exception: - pass - # 返回第一个原因作为主要原因 - return True, skip_reasons[0] - - # 所有条件都通过 - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config 通过(所有检查项均通过)", - content=content[:60] if content else "", - participants=participants, - copies=copies, - value_yuan=prize_value_yuan, - remain_seconds=int(remain_seconds) if remain_seconds is not None else None, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(通过)", - elapsed_seconds=round(elapsed, 2), - ) - return False, "ok" - - -def basic_join_decision( - analyser: Any, detail: Tuple, skip_result: Tuple[bool, str] = None -) -> bool: - """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 - - 参数: - analyser: 分析器对象 - detail: 福袋详情元组 - skip_result: 可选的筛选结果 (skip, reason),如果已知可以避免重复筛选 - - 返回: - True 表示已经参与或已处理完成; - False 表示未参与(例如被配置筛掉或参与失败)。 - """ - # time 模块在文件开头已导入 - start_time = time.time() - # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 - content = "" - prize_value_yuan = 0.0 - countdown_tuple = None - try: - if isinstance(detail, tuple) and len(detail) >= 6: - content = str(detail[0] or "") - prize_value_yuan = float(detail[4] or 0.0) - countdown_tuple = detail[5] - except Exception: - pass - - # 在福袋详情识别完成后,设置福袋信息并记录到映射表 - try: - analyser._current_fudai_content = content - analyser._last_fudai_detail_tuple = detail - - analyser._log_kv( - "福袋详情", - "basic_join_decision:设置福袋信息", - content=content[:50] if content else "", - prize_value_yuan=prize_value_yuan, - log_type="INFO", - ) - except Exception as e: - analyser._log_kv( - "福袋详情", - "basic_join_decision:设置福袋信息失败", - error=str(e), - log_type="WARNING", - ) - - # 强制参与标志已移除,始终按正常验证流程处理 - force_attend = False - - # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 - # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) - try: - last_status = getattr(analyser, "_last_fudai_detail_status", "") - if not force_attend: # 只有在非强制参与模式下才检查状态 - if last_status == "coupon_popup": - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(优惠券弹窗)", - elapsed_seconds=round(elapsed, 2), - ) - return False - elif last_status == "validation_failed": - try: - analyser._log_kv( - "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - pass - if force_attend: - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到强制参与标志(预约回退),跳过验证,直接参与", - ) - except Exception: - pass - # 跳过验证,直接进入参与逻辑 - else: - # 额外验证:使用验证函数检查数据合理性 - try: - # 在函数开头导入,避免作用域问题 - from douyin.fudai import douyin_fudai_detail as dfd_module - - is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser) - if not is_valid: - try: - analyser._log_kv( - "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错", - validation_reason=reason, - content=content[:50] if content else "", - prize_value_yuan=prize_value_yuan, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - pass - - # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 - if not content and prize_value_yuan == 0.0: - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", - content=content, - prize_value_yuan=prize_value_yuan, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(无效详情)", - elapsed_seconds=round(elapsed, 2), - ) - return False - - # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if not needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋", - ) - except Exception: - pass - result = attend_choujiang(analyser) - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(单间模式参与)", - elapsed_seconds=round(elapsed, 2), - result=result, - ) - return result - - # 检查是否启用高价值预约,以及价值是否达到阈值 - try: - high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False)) - except Exception: - high_value_enabled = False - - try: - high_value_threshold = float( - getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0 - ) - except Exception: - high_value_threshold = 500.0 - - # 添加调试日志:输出配置值 - try: - analyser._log_kv( - "参与", - "basic_join_decision:配置检查", - high_value_enabled=high_value_enabled, - high_value_threshold=high_value_threshold, - min_prize_value_yuan=getattr(analyser, "min_prize_value_yuan", 0), - needswitch=getattr(analyser, "needswitch", True), - log_type="DEBUG", - ) - except Exception: - pass - - # 计算 future_timestamp(预计开奖时间戳) - future_ts = 0.0 - if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: - try: - future_ts = float(countdown_tuple[1] or 0.0) - except Exception: - future_ts = 0.0 - - # 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与) - if future_ts > 0: - try: - participated_fudai_ts = getattr( - analyser, "_participated_fudai_future_ts", set() - ) - if not isinstance(participated_fudai_ts, set): - participated_fudai_ts = set() - - # 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化) - for participated_ts in participated_fudai_ts: - if abs(future_ts - participated_ts) < 5.0: - try: - analyser._log_kv( - "参与", - "basic_join_decision:已参与过此福袋,跳过重复参与", - future_ts=future_ts, - participated_ts=participated_ts, - ) - except Exception: - pass - # 已参与过,关闭详情页后返回 True(表示已处理完成) - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(重复参与)", - action="close_detail", - ) - except Exception: - pass - return True - except Exception: - pass - - # 检查价值是否达到高价值阈值 - is_high_value = ( - high_value_enabled - and prize_value_yuan > 0 - and prize_value_yuan >= high_value_threshold - and future_ts > 0.0 +def check_lucky_draw_result(analyser): # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。""" + from douyin.fudai.core.fudai_result_checker import ( + check_lucky_draw_result as _impl, ) - # 添加调试日志 - try: - analyser._log_kv( - "参与", - "basic_join_decision:高价值检查结果", - prize_value_yuan=prize_value_yuan, - high_value_threshold=high_value_threshold, - high_value_enabled=high_value_enabled, - future_ts=future_ts, - is_high_value=is_high_value, - content=content[:50] if content else "", - ) - except Exception: - pass + return _impl(analyser) - # 如果是高价值福袋,在进行任何可能切换房间的操作之前,先读取当前直播间标题 - # 这样可以确保记录的是原始的高价值直播间标题,而不是切换后的标题 - current_room_title = "" - current_room_title_raw = "" - if is_high_value: - try: - revisit_enabled = bool( - getattr(analyser, "high_value_room_revisit_enabled", False) - ) - if revisit_enabled: - # 直接使用并行OCR已缓存的直播间标题,避免重复截图和OCR - current_room_title = str( - getattr(analyser, "current_room_title", "") or "" - ).strip() - current_room_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ).strip() - # 无论缓存是否为空,都不再重新读取,直接使用并行OCR的结果 - # 这样可以避免重复识别,同时确保即使并行OCR失败也能有一致的处理 - try: - analyser._log_kv( - "预约", - "使用并行OCR已缓存的直播间标题", - title=current_room_title, - has_title=bool(current_room_title), - log_type="DEBUG", - ) - except Exception: - pass - else: - # 高价值房间回访未开启时,不读取标题以避免不必要的截图 - current_room_title = str( - getattr(analyser, "current_room_title", "") or "" - ) - current_room_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ) - except Exception as e: - try: - analyser._log_kv( - "预约", - "读取当前直播间标题失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 执行筛选检查 - if skip_result is not None: - skip, reason = skip_result - else: - skip, reason = should_skip_fudai_by_config(analyser, detail) - - # 记录原始筛选结果,避免后续分支覆盖后丢失上下文 - orig_skip = bool(skip) - orig_skip_reason = str(reason or "") - - # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 - # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约 - # 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected) - if skip and reason.startswith("countdown_gt_") and is_high_value: - # 再次检查是否是观看任务(双重保险) - is_watch_task = False - try: - is_watch_task = is_watch_task_fudai(content) - if is_watch_task: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - try: - # 在调用切换前再次检查:如果当前位置映射已经包含福袋信息, - # 则跳过切换以避免重复/多余的上滑操作(与 SwipeHandler 中的跳过保持一致) - room_pos = int(getattr(analyser, "room_pos", 0) or 0) - room_pos_map = ( - getattr(analyser, "_room_pos_to_title_map", {}) or {} - ) - entry = None - if isinstance(room_pos_map, dict): - entry = ( - room_pos_map.get(room_pos) - if room_pos in room_pos_map - else room_pos_map.get(str(room_pos)) - ) - if isinstance(entry, dict) and bool( - entry.get("has_fudai", False) - ): - try: - analyser._log_kv( - "预约", - "[预约] 切换前检测到当前位置已有福袋信息,跳过切换", - room_pos=room_pos, - ) - except Exception: - pass - else: - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 如果内部检查或调用失败,尝试直接调用封装方法或兜底 swipe - try: - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) - or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) - or 2400 - ) - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - pass - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) - pass - - # 计算剩余秒数 - remain_seconds = None - if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: - try: - now = time.time() - cd_start = float(countdown_tuple[0] or 0.0) - cd_end = float(countdown_tuple[1] or 0.0) - if cd_start > 0 and cd_end > cd_start: - remain_seconds = float(cd_end - now) - except Exception: - pass - - # 获取"预约参与阈值"配置 - try: - join_ahead_seconds = int( - getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 - ) - except Exception: - join_ahead_seconds = 100 - - # 如果剩余秒数在"预约参与阈值"内,则立即参与而不是预约 - if remain_seconds is not None and remain_seconds <= join_ahead_seconds: - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,即使倒计时在阈值内也不参与", - reason=orig_skip_reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - # 保持高价值预约逻辑,不走立即参与 - skip = False - reason = "high_value_reservation" - else: - try: - analyser._log_kv( - "参与", - "basic_join_decision:倒计时在预约参与阈值内,立即参与", - reason=reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - # 不关闭详情,继续走立即参与逻辑 - skip = False - reason = ( - "high_value_immediate_join" - if not force_attend - else "reservation_back_force_attend" - ) - # 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约) - # 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋 - if force_attend: - try: - # 设置 is_high_value = False,跳过后续的高价值处理逻辑 - is_high_value = False - analyser._log_kv( - "参与", - "basic_join_decision:强制参与模式,跳过后续高价值处理逻辑,直接参与", - force_attend=force_attend, - ) - except Exception: - pass - else: - # 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务 - is_watch_task_check = False - try: - is_watch_task_check = is_watch_task_fudai(content) - if is_watch_task_check: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) - pass - - # 剩余秒数大于"预约参与阈值",记录预约 - try: - analyser._log_kv( - "参与", - "basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约", - reason=reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - # 不关闭详情,继续走预约逻辑 - skip = False - reason = "high_value_reservation" - - if skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:按配置丢弃福袋", - reason=reason, - ) - except Exception: - pass - # 丢弃时,尽量关闭详情,避免停留在详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", "basic_join_decision:已关闭详情", action="close_detail" - ) - except Exception: - pass - - # 如果允许切换直播间,筛选不通过直接切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", "basic_join_decision:丢弃后切换直播间", reason=reason - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, start_x, start_y, end_x, end_y, 300 - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - - return False - - # 未被筛掉:根据配置决定"直接参与"或"记录为高价值预约" - # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取 - # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列 - if is_high_value: - # 添加调试日志:进入高价值处理逻辑 - try: - analyser._log_kv( - "预约", - "basic_join_decision:进入高价值处理逻辑", - prize_value_yuan=prize_value_yuan, - future_ts=future_ts, - content=content[:50] if content else "", - ) - except Exception: - pass - - # 价值达到高价值阈值:检查剩余秒数,如果在"预约参与阈值"内则立即参与,否则记录预约 - # 计算剩余秒数 - remain_seconds = None - if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: - try: - now = time.time() - cd_start = float(countdown_tuple[0] or 0.0) - cd_end = float(countdown_tuple[1] or 0.0) - if cd_start > 0 and cd_end > cd_start: - remain_seconds = float(cd_end - now) - except Exception: - pass - - # 添加调试日志:剩余秒数计算结果 - try: - analyser._log_kv( - "预约", - "basic_join_decision:剩余秒数计算结果", - countdown_tuple=countdown_tuple, - remain_seconds=remain_seconds, - now=int(time.time()), - ) - except Exception: - pass - - # 获取"预约参与阈值"配置(high_value_fudai_join_ahead_seconds) - # 如果剩余秒数 <= 这个阈值,立即参与;否则记录预约 - try: - join_ahead_seconds = int( - getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 - ) - except Exception: - join_ahead_seconds = 100 - - # 如果剩余秒数在"预约参与阈值"内(<= 阈值),立即参与而不是记录预约 - if remain_seconds is not None and remain_seconds <= join_ahead_seconds: - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,高价值不走立即参与", - reason=orig_skip_reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "参与", - "basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - # 不记录预约,继续执行后续的立即参与逻辑 - is_high_value = False - else: - # 剩余秒数大于"预约参与阈值",记录预约 - try: - analyser._log_kv( - "预约", - "basic_join_decision:价值达到高价值阈值,剩余秒数大于预约参与阈值,准备记录预约", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:价值达到高价值阈值,但剩余秒数大于预约参与阈值,记录预约", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - - if is_high_value: - # 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与 - # 在记录预约之前,先检查是否是观看任务 - is_watch_task = False - try: - is_watch_task = is_watch_task_fudai(content) - if is_watch_task: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception as e_inner: - # 如果检查观看任务时出错,记录日志但继续后续检查(容错处理) - try: - analyser._log_kv( - "预约", - "[预约] 检查观看任务时出错,继续后续检查", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - # 在记录预约之前,先检查福袋内容是否在黑名单中 - try: - # 检查内容是否命中黑名单 - content_hit_blacklist = check_contain(analyser, content) - if content_hit_blacklist: - # 命中黑名单,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 福袋内容命中黑名单,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(命中黑名单)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:命中黑名单后切换直播间", - reason="content_blacklist", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(命中黑名单,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception as e_inner: - # 如果检查黑名单时出错,记录日志但继续记录预约(容错处理) - try: - analyser._log_kv( - "预约", - "[预约] 检查黑名单时出错,继续记录预约", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - if is_high_value: - # 未命中黑名单,继续记录预约 - try: - # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务) - # 初始化预约队列容器 - reservations = getattr(analyser, "reservations", None) - if reservations is None: - reservations = [] - try: - analyser.reservations = reservations # type: ignore[attr-defined] - except Exception: - pass - else: - # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的 - try: - rl_cleanup = douyin_reservation_logic - - rl_cleanup.cleanup_expired_reservations( - analyser, - reservations, - write_state_callback=None, - ) - except Exception: - pass - - # room_pos:当前直播间位置计数 - try: - room_pos = int(getattr(analyser, "room_pos", 0) or 0) - except Exception: - room_pos = 0 - - # 使用预先读取的直播间标题(避免在可能切换房间后读取到错误的标题) - room_title = current_room_title - room_title_raw = current_room_title_raw - - # 优先使用映射表中刚刚记录的直播间标题(如果存在) - # 这样可以确保高价值预约使用的是当前直播间的正确标题 - try: - room_pos_to_title_map = getattr( - analyser, "_room_pos_to_title_map", {} - ) - if room_pos in room_pos_to_title_map: - map_info = room_pos_to_title_map[room_pos] - if isinstance(map_info, dict): - mapped_title = str(map_info.get("title", "")).strip() - mapped_title_raw = str( - map_info.get("title_raw", "") - ).strip() - if mapped_title: - room_title = mapped_title - room_title_raw = mapped_title_raw - try: - analyser._log_kv( - "预约", - "使用映射表中的直播间标题", - room_pos=room_pos, - room_title=room_title[:50], - room_title_raw=room_title_raw[:50], - ) - except Exception: - pass - except Exception as e: - # 如果从映射表获取失败,继续使用缓存的标题 - try: - analyser._log_kv( - "预约", - "从映射表获取标题失败,使用缓存标题", - error=str(e), - room_pos=room_pos, - ) - except Exception: - pass - - # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间) - # 使用全局导入的模块(已在文件顶部导入) - # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致) - def _write_reservation_state() -> None: - try: - import json - from datetime import datetime - - state_path = getattr( - analyser, "_reservations_state_path", None - ) - if not state_path: - # 使用path_config统一路径 - try: - state_path = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) - # 确保目录存在 - os.makedirs(os.path.dirname(state_path), exist_ok=True) - - # 格式化预约队列数据(与 douyin_reservation.py 格式一致) - items = [] - for r in reservations or []: - try: - ft = float(r.get("future_ts") or 0) - except Exception: - ft = 0.0 - try: - ft_str = ( - datetime.fromtimestamp(ft).strftime( - "%Y-%m-%d %H:%M:%S" - ) - if ft - else "" - ) - except Exception: - ft_str = str(r.get("future_str", "")) - - items.append( - { - "prize_value_yuan": float( - r.get("prize_value_yuan") or 0 - ), - "content": str(r.get("content") or ""), - "future_ts": ft, - "future_str": ft_str, - "pos_seen": int(r.get("pos_seen") or 0), - "room_title": str(r.get("room_title") or ""), - "room_title_raw": str( - r.get("room_title_raw") or "" - ), - "created_ts": float(r.get("created_ts") or 0), - "task_count": int(r.get("task_count") or 2), - "time_text": str(r.get("time_text") or ""), - "participants": int(r.get("participants") or 0), - "copies": int(r.get("copies") or 0), - } - ) - - # 获取当前直播间标题(用于状态文件) - current_title = str( - getattr(analyser, "current_room_title", "") - or room_title - or "" - ) - current_title_raw = str( - getattr(analyser, "current_room_title_raw", "") - or room_title_raw - or "" - ) - - # 写入完整的状态数据 - data = { - "updated_ts": time.time(), - "reason": "record_reservation", - "room_pos": int(room_pos), - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open(state_path, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - try: - analyser._log_kv( - "预约", - "已写入预约队列状态文件", - path=state_path, - queue_len=( - len(reservations) - if reservations is not None - else 0 - ), - ) - except Exception: - pass - except Exception as e_inner: - try: - analyser._log_kv( - "预约", - "写入预约队列状态文件失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - # 记录高价值直播间(在记录预约之前) - try: - from douyin.other import douyin_high_value_room - - if hasattr(douyin_high_value_room, "touch_high_value_room"): - douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined] - analyser=analyser, - title_norm=room_title, - title_raw=room_title_raw, - prize_value_yuan=prize_value_yuan, - reason="reservation", - increment=True, - content=content, - pos_seen=room_pos, - ) - - # 同时添加到本次运行的高价值房间列表 - try: - current_run_rooms = getattr( - analyser, "_current_run_high_value_rooms", [] - ) - room_info = { - "room_title": room_title, - "room_title_raw": room_title_raw, - "max_prize_value_yuan": prize_value_yuan, - "last_seen_ts": time.time(), - "pos_seen": room_pos, - "seen_count": 1, - } - current_run_rooms.append(room_info) - analyser._current_run_high_value_rooms = ( - current_run_rooms - ) - except Exception: - pass - except Exception: - pass - - # 记录预约,并检查队列是否已满 - queue_full_flag = [False] - - def _add_reservation_with_flag(res_list, item) -> None: - max_reservations = None - try: - max_reservations = int( - getattr( - analyser, "high_value_fudai_max_reservations", 3 - ) - or 3 - ) - except Exception: - max_reservations = 3 - queue_full = ( - douyin_reservation_logic.add_reservation_core_logic( - res_list, - item, - max_reservations=max_reservations, - analyser=analyser, - write_state_callback=_write_reservation_state, - ) - ) - try: - queue_full_flag[0] = bool(queue_full) - except Exception: - pass - - # 检查预约队列中是否已经存在相同的福袋 - existing_reservation = None - try: - if reservations: - for r in reservations: - r_ft = float(r.get("future_ts") or 0.0) - r_content = str(r.get("content") or "") - - # 检查是否是同一个福袋:开奖时间相同且内容相同 - if abs(r_ft - future_ts) < 5.0 and r_content == content: - existing_reservation = r - try: - analyser._log_kv( - "预约", - "basic_join_decision:福袋已在预约队列中,将更新为最新预约", - future_ts=int(future_ts), - content=content[:50] if content else "", - existing_future_ts=int(r_ft), - existing_content=( - r_content[:50] if r_content else "" - ), - ) - except Exception: - pass - break - except Exception as e: - try: - analyser._log_kv( - "预约", - "basic_join_decision:检查重复预约时出错,继续记录", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 如果已经预约过,更新现有预约;否则新增预约 - need_record = True - if existing_reservation is not None: - need_record = False - # 更新现有预约的信息 - try: - existing_reservation.update( - { - "prize_value_yuan": prize_value_yuan, - "content": content, - "future_ts": future_ts, - "pos_seen": room_pos, - "room_title": room_title, - "room_title_raw": room_title_raw, - "updated_ts": time.time(), - } - ) - # 重新排序预约队列 - douyin_reservation_logic._sort_reservations_inplace(reservations) # type: ignore[attr-defined] - # 写入状态文件 - _write_reservation_state() - try: - analyser._log_kv( - "预约", - "basic_join_decision:已更新预约队列中的福袋信息,继续进行决策", - value_yuan=prize_value_yuan, - future_ts=int(future_ts), - room_pos=room_pos, - queue_len=len(reservations), - ) - except Exception: - pass - - # 更新预约成功后,继续进行决策而不是直接返回 - # 设置标志表示预约已更新,后续决策会考虑这个信息 - reservation_updated = True - - # 即使更新预约,也设置标志强制切换,避免循环 - try: - analyser._just_recorded_reservation = True - except Exception: - pass - - # 更新预约后关闭详情页,避免影响后续预约回退 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(更新预约后)", - action="close_detail_after_reservation_update", - ) - except Exception: - pass - - # 更新预约后返回False,触发切换直播间 - return False - - except Exception as e: - try: - analyser._log_kv( - "预约", - "basic_join_decision:更新现有预约失败,继续新增", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - existing_reservation = None # 强制新增 - need_record = True - - time_text = "" - participants = 0 - copies = 0 - task_count = 2 - try: - # 优先从缓存的福袋详情中获取信息 - cached_detail = getattr( - analyser, "_last_fudai_detail_tuple", None - ) - if ( - cached_detail - and isinstance(cached_detail, tuple) - and len(cached_detail) >= 6 - ): - time_text = str(cached_detail[1] or "") - participants = int(cached_detail[2] or 0) - copies = int(cached_detail[3] or 0) - - # 从阶段检测结果获取任务数量(如果还没有被清除) - 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( - "福袋详情", - "douyin_fudai_core:从阶段检测获取任务数量", - log_type="OP", - 任务数量=task_count, - 原始值=task_count_from_stage, - ) - except Exception: - pass - # 清除标志,避免影响后续调用 - analyser._fudai_detail_task_count_from_stage = None - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:清除任务数量标志", - log_type="DEBUG", - ) - except Exception: - pass - else: - # 如果阶段检测结果已被清除,尝试从缓存的详情中获取任务数量 - try: - cached_extra = getattr( - analyser, "_last_fudai_detail_extra", None - ) - if cached_extra and isinstance(cached_extra, dict): - cached_task_count = cached_extra.get("task_count") - if cached_task_count is not None: - task_count = int(cached_task_count or 0) - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:从缓存详情获取任务数量", - log_type="OP", - 任务数量=task_count, - 来源="缓存详情", - ) - except Exception: - pass - else: - # 警告:未获取到任务数量,使用默认值0 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:警告:未从缓存获取任务数量,使用默认值0", - log_type="WARNING", - 可能原因="缓存详情不完整或任务数量缺失", - 建议="检查福袋详情识别是否正常", - ) - except Exception: - pass - else: - # 警告:未获取到任务数量,使用默认值0 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:警告:未从阶段检测获取任务数量,使用默认值0", - log_type="WARNING", - 可能原因="阶段检测未触发或像素检测失败", - 建议="检查点击验证阶段检测是否正常执行", - ) - except Exception: - pass - except Exception as e: - # 获取缓存失败,使用默认值 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:从缓存获取任务数量失败,使用默认值", - error=str(e), - 使用默认值=True, - ) - except Exception: - pass - - # 限制任务数量在合理范围内 - if task_count not in (1, 2, 3): - task_count = 2 - except Exception: - task_count = 2 - - if need_record: - douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined] - analyser=analyser, - fudai_content_text=content, - prize_value_yuan=prize_value_yuan, - lastsecond=0, - future_timestamp=future_ts, - x=0, - needswitch=True, - wait_minutes=0, - post_switch_delay_s=0.0, - room_pos=room_pos, - reservations=reservations, - reservation_focus_until_ts_ref=[ - float( - getattr(analyser, "reservation_focus_until_ts", 0.0) - or 0.0 - ) - ], - close_detail_callback=lambda: None, - swipe_up_switch_callback=lambda: None, - swipe_down_back_callback=lambda: None, - add_reservation_callback=_add_reservation_with_flag, - sort_reservations_callback=lambda: ( - douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined] - reservations if reservations is not None else [] # type: ignore[arg-type] - ) - ), - write_state_callback=_write_reservation_state, - room_title=room_title, - room_title_raw=room_title_raw, - task_count=task_count, - time_text=time_text, - participants=participants, - copies=copies, - ) - - # 如果队列已满,设置标志以便主循环处理 - if queue_full_flag[0]: - try: - analyser.queue_full_waiting_at_earliest = ( - False # 重置标志,让主循环处理 - ) - except Exception: - pass - - try: - analyser._log_kv( - "预约", - "basic_join_decision:命中高价值阈值,已记录为预约,不立即参与", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - future_ts=int(future_ts), - room_pos=room_pos, - queue_len=len(reservations), - ) - except Exception: - pass - - # 关闭当前详情,避免长时间停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情", - action="close_detail", - ) - except Exception: - pass - - # 记录预约后,切换直播间继续找别的福袋 - # 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - - # 检查是否在锁定期内 - in_lock_period = False - try: - focus_until = float( - getattr(analyser, "reservation_focus_until_ts", 0.0) - or 0.0 - ) - now_ts = time.time() - if focus_until > 0 and now_ts < focus_until: - in_lock_period = True - try: - analyser._log_kv( - "预约", - "[预约] 记录预约后:在锁定期内,不切换直播间", - focus_until=int(focus_until), - remain_seconds=int(focus_until - now_ts), - ) - except Exception: - pass - except Exception: - pass - - if needswitch and not in_lock_period: - try: - analyser._log_kv( - "参与", - "basic_join_decision:记录预约后切换直播间", - reason="high_value_reservation", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - 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 = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - elif in_lock_period: - # 在锁定期内,不切换直播间,但记录日志说明原因 - try: - analyser._log_kv( - "参与", - "basic_join_decision:记录预约后不切换直播间(锁定期内)", - reason="lock_period_active", - ) - except Exception: - pass - - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(记录预约)", - elapsed_seconds=round(elapsed, 2), - ) - - # 记录预约后关闭详情页,避免影响后续预约回退 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(记录预约后)", - action="close_detail_after_reservation", - ) - except Exception: - pass - - # 设置标志,强制下次 run_once_basic 切换直播间,避免在同一直播间循环 - try: - analyser._just_recorded_reservation = True - except Exception: - pass - - # 记录预约后返回False,触发切换直播间继续找别的福袋 - return False - except Exception as e: - # 若预约逻辑异常:对“倒计时>阈值”的原始筛选场景,避免退化为直接参与 - try: - analyser._log_kv( - "预约", - "basic_join_decision:记录预约时异常", - error=str(e), - error_type=type(e).__name__, - orig_skip=orig_skip, - orig_reason=orig_skip_reason, - ) - except Exception: - pass - if orig_skip and orig_skip_reason.startswith("countdown_gt_"): - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选为倒计时>阈值,预约异常时不参与", - reason=orig_skip_reason, - ) - except Exception: - pass - # 尽量关闭详情页,避免停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - return False - # 其它场景保持原行为:退化为直接参与抽奖 - try: - analyser._log_kv( - "预约", - "basic_join_decision:记录预约异常,继续尝试直接参与", - level="WARNING", - ) - except Exception: - pass - - # 默认分支:未进入预约路径或预约失败,直接参与抽奖 - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,放弃参与", - reason=orig_skip_reason, - ) - except Exception: - pass - # 尽量关闭详情页,避免停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - return False - try: - analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") - except Exception: - pass - - # 获取当前福袋的 future_ts(用于参与成功后从预约队列中移除) - current_future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - - result = attend_choujiang(analyser) - - # 更新连续参与失败计数器 - if result: - # 参与成功,重置计数器 - analyser._consecutive_attend_failures = 0 - else: - # 参与失败,增加计数器 - analyser._consecutive_attend_failures = ( - getattr(analyser, "_consecutive_attend_failures", 0) + 1 - ) - - # 如果参与成功,记录参与结果(不再使用已废弃的强制参与标志) - if result: - try: - analyser._log_kv( - "参与", - "basic_join_decision:参与成功", - ) - except Exception: - pass - - # 如果参与成功,从预约队列中移除该预约(如果存在) - if result and current_future_ts > 0: - try: - reservations = getattr(analyser, "reservations", None) - if ( - reservations - and isinstance(reservations, list) - and len(reservations) > 0 - ): - # 查找并移除匹配的预约(通过 future_ts 匹配,允许5秒误差) - removed_count = 0 - remaining_reservations = [] - for res in reservations: - try: - res_future_ts = float(res.get("future_ts") or 0.0) - if ( - res_future_ts > 0 - and abs(res_future_ts - current_future_ts) <= 5.0 - ): - # 匹配的预约,移除 - removed_count += 1 - analyser._log_kv( - "预约", - "[预约] 参与成功,从预约队列中移除该预约", - future_ts=int(res_future_ts), - value_yuan=res.get("prize_value_yuan", 0), - content=( - res.get("content", "")[:50] - if res.get("content") - else "" - ), - ) - else: - # 保留不匹配的预约 - remaining_reservations.append(res) - except Exception: - # 如果解析预约项时出错,保留该项(容错处理) - remaining_reservations.append(res) - - if removed_count > 0: - analyser.reservations = remaining_reservations - # 写入预约状态(供 GUI/Web 端查看) - # 使用内联的写入逻辑(与 _write_reservation_state 类似,但需要适配当前作用域) - try: - import json - from datetime import datetime - - state_path = getattr(analyser, "_reservations_state_path", None) - if not state_path: - # 使用path_config统一路径 - try: - state_path = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) - os.makedirs(os.path.dirname(state_path), exist_ok=True) - - # 格式化预约队列数据 - items = [] - for r in remaining_reservations or []: - try: - ft = float(r.get("future_ts") or 0) - except Exception: - ft = 0.0 - try: - ft_str = ( - datetime.fromtimestamp(ft).strftime( - "%Y-%m-%d %H:%M:%S" - ) - if ft - else "" - ) - except Exception: - ft_str = str(r.get("future_str", "")) - - items.append( - { - "prize_value_yuan": float( - r.get("prize_value_yuan") or 0 - ), - "content": str(r.get("content") or ""), - "future_ts": ft, - "future_str": ft_str, - "pos_seen": int(r.get("pos_seen") or 0), - "room_title": str(r.get("room_title") or ""), - "room_title_raw": str( - r.get("room_title_raw") or "" - ), - "created_ts": float(r.get("created_ts") or 0), - "task_count": int(r.get("task_count") or 2), - "time_text": str(r.get("time_text") or ""), - "participants": int(r.get("participants") or 0), - "copies": int(r.get("copies") or 0), - } - ) - - # 获取当前直播间标题 - current_title = str( - getattr(analyser, "current_room_title", "") or "" - ) - current_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ) - - # 写入完整的状态数据 - data = { - "updated_ts": time.time(), - "reason": "remove_reservation_after_attend", - "room_pos": 0, - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open(state_path, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - try: - analyser._log_kv( - "预约", - "已写入预约队列状态文件(移除预约后)", - path=state_path, - queue_len=len(remaining_reservations), - ) - except Exception: - pass - except Exception as e_inner: - analyser._log_kv( - "预约", - "[预约] 写入预约状态失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception as e_inner: - analyser._log_kv( - "预约", - "[预约] 从预约队列中移除预约时出错", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(参与抽奖)", - elapsed_seconds=round(elapsed, 2), - result=result, +def check_have_reward_notice_confirm(analyser) -> bool: # noqa: F811 + """[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。""" + from douyin.fudai.core.fudai_result_checker import ( + check_have_reward_notice_confirm as _impl, ) - return result + + return _impl(analyser) + + +def check_in_order_confirm_page(analyser) -> bool: # noqa: F811 + """[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。""" + from douyin.fudai.core.fudai_result_checker import ( + check_in_order_confirm_page as _impl, + ) + + return _impl(analyser) + + +def get_reward(analyser, reward_y: int = 0) -> None: # noqa: F811 + """[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。""" + from douyin.fudai.core.fudai_result_checker import get_reward as _impl + + return _impl(analyser, reward_y=reward_y) + + +def is_watch_task_fudai(content: str) -> bool: # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import is_watch_task_fudai as _impl + + return _impl(content) + + +def _is_short_countdown_text(time_text: str) -> bool: # noqa: F811 + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import ( + _is_short_countdown_text as _impl, + ) + + return _impl(time_text) + + +def should_skip_fudai_by_config(analyser, detail): # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import ( + should_skip_fudai_by_config as _impl, + ) + + return _impl(analyser, detail) + + +def basic_join_decision(analyser, detail): # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import basic_join_decision as _impl + + return _impl(analyser, detail) diff --git a/douyin/fudai/douyin_fudai_detail.py b/douyin/fudai/douyin_fudai_detail.py index dd70ccd..4eb46b1 100644 --- a/douyin/fudai/douyin_fudai_detail.py +++ b/douyin/fudai/douyin_fudai_detail.py @@ -16,29 +16,29 @@ Exports: """ # 从各子模块导入所有公共API -from fudai_detail_modules.fudai_detail_operations import ( +from douyin.fudai.core.fudai_detail_operations import ( close_fudai_detail, ensure_fudai_detail_open, ) -from fudai_detail_modules.fudai_detail_room_title import ( +from douyin.fudai.core.fudai_detail_room_title import ( read_live_room_title_core, ) -from fudai_detail_modules.fudai_detail_reader import ( +from douyin.fudai.core.fudai_detail_orchestrator import ( read_fudai_detail_once, read_fudai_detail_with_retries, ) -from fudai_detail_modules.fudai_detail_validator import ( +from douyin.fudai.core.fudai_detail_validator import ( validate_fudai_detail, ) -from fudai_detail_modules.fudai_detail_utils import ( +from douyin.fudai.core.fudai_detail_utils import ( is_abnormal_time_value, ) -from fudai_detail_modules.fudai_detail_coupon_detection import ( +from douyin.fudai.core.fudai_detail_coupon_detection import ( is_wrong_coupon_popup, ) diff --git a/douyin/handlers/douyin_swipe_handler.py b/douyin/handlers/douyin_swipe_handler.py index f83b905..cfa88f8 100644 --- a/douyin/handlers/douyin_swipe_handler.py +++ b/douyin/handlers/douyin_swipe_handler.py @@ -14,7 +14,7 @@ from __future__ import annotations import time import subprocess from typing import Any -from douyin.logging.action_tracker import track_action +from douyin.logging.action_logger import track_action from douyin.handlers import douyin_swipe_ops diff --git a/douyin/logging/__init__.py b/douyin/logging/__init__.py index e766934..55c38f4 100644 --- a/douyin/logging/__init__.py +++ b/douyin/logging/__init__.py @@ -25,17 +25,11 @@ from .log_formatter import ( # 性能追踪模块 from .performance_tracker import PerformanceTracker -# 错误日志模块 -from .error_logger import ErrorLogger +# 错误与调试日志(合并到 internal_loggers) +from .internal_loggers import ErrorLogger, DebugLogger, _get_debug_logger -# 调试日志模块 -from .debug_logger import DebugLogger, _get_debug_logger - -# 行为日志模块 -from .action_logger import ActionLogger - -# 操作追踪装饰器 -from .action_tracker import track_action +# 行为日志模块(含 track_action 装饰器) +from .action_logger import ActionLogger, track_action # 日志包装器 from .douyin_logging_wrapper import LoggingWrapper diff --git a/douyin/logging/action_logger.py b/douyin/logging/action_logger.py index 947668a..9b5edd5 100644 --- a/douyin/logging/action_logger.py +++ b/douyin/logging/action_logger.py @@ -107,4 +107,37 @@ class ActionLogger: def log_step(self, name: str, elapsed: Optional[float] = None) -> None: self.log_operation("Step", name, elapsed=elapsed) -__all__ = ["ActionLogger"] + +# ============================================================ +# track_action 装饰器(合并自 action_tracker.py) +# ============================================================ +from functools import wraps as _wraps # noqa: E402 + + +_action_logger_singleton = ActionLogger() + + +def track_action(name: str = ""): + """函数装饰器:自动记录函数耗时与操作信息。""" + + def decorator(func): + @_wraps(func) + def wrapper(*args, **kwargs): + timer = _perf.start_timer(name or func.__name__) + t0 = time.time() + try: + return func(*args, **kwargs) + finally: + elapsed = _perf.end_timer(timer) + if elapsed is None: + elapsed = time.time() - t0 + _action_logger_singleton.log_step( + name or func.__name__, elapsed=elapsed + ) + + return wrapper + + return decorator + + +__all__ = ["ActionLogger", "track_action"] diff --git a/douyin/logging/action_tracker.py b/douyin/logging/action_tracker.py deleted file mode 100644 index 675ff67..0000000 --- a/douyin/logging/action_tracker.py +++ /dev/null @@ -1,28 +0,0 @@ -"""操作追踪装饰器:自动记录函数耗时与操作信息""" -from __future__ import annotations - -import time -from functools import wraps - -from .performance_tracker import PerformanceTracker -from .action_logger import ActionLogger -_perf = PerformanceTracker() -_logger = ActionLogger() - -def track_action(name: str = ""): - def decorator(func): - @wraps(func) - def wrapper(*args, **kwargs): - timer = _perf.start_timer(name or func.__name__) - t0 = time.time() - try: - result = func(*args, **kwargs) - return result - finally: - elapsed = _perf.end_timer(timer) - elapsed = elapsed if elapsed is not None else time.time() - t0 - _logger.log_step(name or func.__name__, elapsed=elapsed) - return wrapper - return decorator - -__all__ = ["track_action"] diff --git a/douyin/logging/debug_logger.py b/douyin/logging/debug_logger.py deleted file mode 100644 index 80b3b8e..0000000 --- a/douyin/logging/debug_logger.py +++ /dev/null @@ -1,98 +0,0 @@ -"""调试日志记录器:在运行时输出详细信息,遇到错误时调用错误日志记录器。""" -from __future__ import annotations - -import time -import traceback -import logging -import os -from typing import Any, Dict, Optional -import threading - -from .log_formatter import format_debug_log -from .performance_tracker import PerformanceTracker -from .error_logger import ErrorLogger - -_perf = PerformanceTracker() -_err = ErrorLogger() - -# 初始化文件日志记录器 -_debug_logger = logging.getLogger("debug_logger") -if not _debug_logger.handlers: - _debug_logger.setLevel(logging.DEBUG) - - # 添加控制台处理器 - _console_handler = logging.StreamHandler() - _debug_logger.addHandler(_console_handler) - - # 添加文件处理器,写入到 debug.log - try: - # 获取日志目录 - log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "logs") - os.makedirs(log_dir, exist_ok=True) - - debug_log_path = os.path.join(log_dir, "debug.log") - - # 创建轮转文件处理器 - from logging.handlers import RotatingFileHandler - _file_handler = RotatingFileHandler( - debug_log_path, - maxBytes=10*1024*1024, # 10MB - backupCount=5, - encoding='utf-8' - ) - _file_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s')) - _debug_logger.addHandler(_file_handler) - except Exception: - # 如果文件处理器创建失败,至少保留控制台输出 - pass - -class DebugLogger: - def __init__(self, enabled: bool = True) -> None: - self.enabled = enabled - - def log_function_entry(self, func_name: str, *args: Any, **kwargs: Any) -> None: - if not self.enabled: - return - params = {"args": args, "kwargs": kwargs} - line = format_debug_log(f"FunctionEntry: {func_name}", level="DEBUG", **params) - _debug_logger.debug(line) - - def log_function_exit(self, func_name: str, retval: Any, elapsed: float) -> None: - if not self.enabled: - return - line = format_debug_log(f"FunctionExit: {func_name}", level="DEBUG", elapsed_seconds=elapsed, return_value=retval) - _debug_logger.debug(line) - - def log_variable(self, name: str, value: Any) -> None: - if not self.enabled: - return - line = format_debug_log(f"VariableSnapshot: {name}=", level="DEBUG", value=value) - _debug_logger.debug(line) - - def log_call_stack(self) -> None: - if not self.enabled: - return - stack = traceback.format_stack() - line = format_debug_log("CallStack", level="DEBUG", stack="".join(stack)) - _debug_logger.debug(line) - - def log_exception(self, exc: BaseException, context: Optional[Dict[str, Any]] = None) -> None: - if not self.enabled: - return - tb = traceback.format_exc() - line = format_debug_log("Exception", level="ERROR", exception=type(exc).__name__, traceback=tb, context=context or {}) - _debug_logger.error(line) - _err.log_exception(exc, context=context) - - def log_step(self, name: str, start_time: float, end_time: Optional[float] = None) -> None: - if not self.enabled: - return - t = (end_time if end_time is not None else time.time()) - start_time - line = format_debug_log("StepTiming", level="DEBUG", step=name, elapsed_seconds=t) - _debug_logger.debug(line) - _perf.get_elapsed(name) # update internal stats if used - -def _get_debug_logger() -> DebugLogger: - return DebugLogger(True) - -__all__ = ["DebugLogger", "_get_debug_logger"] diff --git a/douyin/logging/douyin_logger.py b/douyin/logging/douyin_logger.py deleted file mode 100644 index 051fbd4..0000000 --- a/douyin/logging/douyin_logger.py +++ /dev/null @@ -1,297 +0,0 @@ -""" -增强的日志系统配置模块 -==================== - -功能: -1. 标准 Python logging 模块集成 -2. 日志级别管理(DEBUG, INFO, WARNING, ERROR, CRITICAL) -3. 日志轮转(按大小和时间) -4. 清晰的日志格式(时间戳、级别、模块、函数、行号) -5. 异常堆栈完整记录 -6. 根据环境动态调整日志级别 -""" - -from __future__ import annotations - -import logging -import logging.handlers -import os -import sys -import json -from typing import Optional, Dict, Any -from douyin.core import path_config - - -# 日志配置默认值 -DEFAULT_LOG_LEVEL = "INFO" -DEFAULT_LOG_FILE = "logs/unified.log" -DEFAULT_MAX_BYTES = 10 * 1024 * 1024 # 10MB -DEFAULT_BACKUP_COUNT = 5 -DEFAULT_WHEN = "midnight" # 每天午夜轮转 -DEFAULT_INTERVAL = 1 # 每1天轮转一次 - - -def get_log_config() -> Dict[str, Any]: - """从 config.json 读取日志配置""" - try: - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - return config.get("logging", {}) - except Exception: - pass - return {} - - -def get_log_level() -> str: - """获取日志级别(从配置或环境变量)""" - # 优先检查环境变量(开发调试时使用) - env_level = os.environ.get("DOUYIN_LOG_LEVEL", "").upper() - if env_level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): - return env_level - - # 从配置文件读取 - log_config = get_log_config() - level = log_config.get("level", DEFAULT_LOG_LEVEL).upper() - if level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): - return level - - return DEFAULT_LOG_LEVEL - - -def get_log_file_path() -> str: - """获取日志文件路径""" - log_config = get_log_config() - path = log_config.get("file_path", DEFAULT_LOG_FILE) - if not os.path.isabs(path): - path = os.path.join(path_config.PROJECT_ROOT, path) - return path - - -def get_rotation_config() -> Dict[str, Any]: - """获取日志轮转配置""" - log_config = get_log_config() - rotation = log_config.get("rotation", {}) - - return { - "enabled": rotation.get("enabled", True), - "max_bytes": rotation.get("max_bytes", DEFAULT_MAX_BYTES), - "backup_count": rotation.get("backup_count", DEFAULT_BACKUP_COUNT), - "when": rotation.get("when", DEFAULT_WHEN), - "interval": rotation.get("interval", DEFAULT_INTERVAL), - } - - -def setup_logging( - logger_name: str = "douyin", - log_file: Optional[str] = None, - log_level: Optional[str] = None, - enable_console: bool = True, - enable_file: bool = True, -) -> logging.Logger: - """ - 配置并返回一个增强的 logger 实例 - - 参数: - logger_name: logger 名称 - log_file: 日志文件路径(None 则从配置读取) - log_level: 日志级别(None 则从配置读取) - enable_console: 是否启用控制台输出 - enable_file: 是否启用文件输出 - - 返回: - 配置好的 logger 实例 - """ - logger = logging.getLogger(logger_name) - - # 避免重复配置 - if logger.handlers: - return logger - - # 设置日志级别 - if log_level is None: - log_level = get_log_level() - level = getattr(logging, log_level.upper(), logging.INFO) - logger.setLevel(level) - - # 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息 - detailed_format = ( - "%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s" - ) - - formatter = logging.Formatter(detailed_format, datefmt="%Y-%m-%d %H:%M:%S") - - # 控制台处理器 - if enable_console: - console_handler = logging.StreamHandler(sys.stdout) - console_handler.setLevel(level) - console_handler.setFormatter(formatter) - logger.addHandler(console_handler) - - # 文件处理器(带轮转) - if enable_file: - if log_file is None: - log_file = get_log_file_path() - - # 确保日志目录存在 - log_dir = os.path.dirname(log_file) - if log_dir: - os.makedirs(log_dir, exist_ok=True) - - rotation_config = get_rotation_config() - - if rotation_config.get("enabled", True): - # 使用 TimedRotatingFileHandler(按时间轮转) - try: - file_handler = logging.handlers.TimedRotatingFileHandler( - log_file, - when=rotation_config.get("when", DEFAULT_WHEN), - interval=rotation_config.get("interval", DEFAULT_INTERVAL), - backupCount=rotation_config.get( - "backup_count", DEFAULT_BACKUP_COUNT - ), - encoding="utf-8-sig", # 使用 BOM 避免 Windows 乱码 - errors="replace", - ) - except Exception: - # 如果时间轮转失败,回退到大小轮转 - try: - file_handler = logging.handlers.RotatingFileHandler( - log_file, - maxBytes=rotation_config.get("max_bytes", DEFAULT_MAX_BYTES), - backupCount=rotation_config.get( - "backup_count", DEFAULT_BACKUP_COUNT - ), - encoding="utf-8-sig", - errors="replace", - ) - except Exception: - # 如果都失败,使用普通 FileHandler - file_handler = logging.FileHandler( - log_file, - encoding="utf-8-sig", - errors="replace", - ) - else: - # 不使用轮转,直接使用 FileHandler - file_handler = logging.FileHandler( - log_file, - encoding="utf-8-sig", - errors="replace", - ) - - file_handler.setLevel(level) - file_handler.setFormatter(formatter) - logger.addHandler(file_handler) - - return logger - - -def get_logger(name: str = "douyin") -> logging.Logger: - """获取或创建 logger 实例(单例模式)""" - logger = logging.getLogger(name) - if not logger.handlers: - # 如果还没有配置,进行初始化 - setup_logging(name) - return logger - - -class LogContext: - """日志上下文管理器,用于记录函数调用、参数、返回值、耗时等""" - - def __init__( - self, - logger: logging.Logger, - func_name: str, - level: int = logging.DEBUG, - log_args: bool = True, - log_result: bool = True, - log_duration: bool = True, - ): - self.logger = logger - self.func_name = func_name - self.level = level - self.log_args = log_args - self.log_result = log_result - self.log_duration = log_duration - self.start_time: Optional[float] = None - self.args: tuple = () - self.kwargs: dict = {} - - def __enter__(self): - import time - - self.start_time = time.time() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - import time - - duration = time.time() - self.start_time if self.start_time else 0 - - # 记录函数调用信息 - if self.log_args and (self.args or self.kwargs): - args_str = ", ".join([repr(a) for a in self.args]) - kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in self.kwargs.items()]) - params_str = ", ".join(filter(None, [args_str, kwargs_str])) - self.logger.log(self.level, f"[函数调用] {self.func_name}({params_str})") - - # 记录异常 - if exc_type is not None: - self.logger.exception( - f"[函数异常] {self.func_name} 发生异常: {exc_type.__name__}", - exc_info=(exc_type, exc_val, exc_tb), - ) - # 记录耗时 - elif self.log_duration: - self.logger.log( - self.level, f"[函数完成] {self.func_name} 耗时: {duration:.3f}秒" - ) - - return False # 不抑制异常 - - -def log_function_call( - logger: logging.Logger, - func_name: str, - args: tuple = (), - kwargs: Optional[dict] = None, - result: Any = None, - duration: Optional[float] = None, - level: int = logging.DEBUG, -): - """记录函数调用的详细信息""" - if kwargs is None: - kwargs = {} - - parts = [f"[函数调用] {func_name}"] - - # 参数 - if args or kwargs: - args_str = ", ".join([repr(a) for a in args]) - kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in kwargs.items()]) - params_str = ", ".join(filter(None, [args_str, kwargs_str])) - parts.append(f"参数: {params_str}") - - # 返回值 - if result is not None: - parts.append(f"返回值: {repr(result)}") - - # 耗时 - if duration is not None: - parts.append(f"耗时: {duration:.3f}秒") - - logger.log(level, " | ".join(parts)) - - -# 全局 logger 实例(延迟初始化) -_global_logger: Optional[logging.Logger] = None - - -def get_global_logger() -> logging.Logger: - """获取全局 logger 实例""" - global _global_logger - if _global_logger is None: - _global_logger = setup_logging("douyin") - return _global_logger diff --git a/douyin/logging/douyin_logging_wrapper.py b/douyin/logging/douyin_logging_wrapper.py index 1537e90..8604ebc 100644 --- a/douyin/logging/douyin_logging_wrapper.py +++ b/douyin/logging/douyin_logging_wrapper.py @@ -51,8 +51,7 @@ except ImportError: # 导入所有日志模块 try: - from .error_logger import ErrorLogger # type: ignore[assignment] - from .debug_logger import DebugLogger # type: ignore[assignment] + from .internal_loggers import ErrorLogger, DebugLogger # type: ignore[assignment] from .action_logger import ActionLogger # type: ignore[assignment] from .performance_tracker import PerformanceTracker # type: ignore[assignment] @@ -1017,9 +1016,9 @@ class LoggingWrapper: analyser._std_logger = get_unified_logger("douyin.fudai") except ImportError: try: - from douyin.logging import douyin_logger + from douyin.logging import douyin_logging - analyser._std_logger = douyin_logger.get_logger("douyin") + analyser._std_logger = douyin_logging.get_logger("douyin") except Exception: analyser._std_logger = logging.getLogger("douyin.fudai") diff --git a/douyin/logging/error_logger.py b/douyin/logging/error_logger.py deleted file mode 100644 index b242ef6..0000000 --- a/douyin/logging/error_logger.py +++ /dev/null @@ -1,62 +0,0 @@ -"""错误日志记录模块:记录详细错误、上下文与推荐恢复建议""" -from __future__ import annotations - -import logging -import traceback -import os -from typing import Any, Dict, Optional -from douyin.core import path_config - -logger = None - -def _init_logger(): - global logger - if logger is not None: - return - log_path = path_config.get_error_log_path() if hasattr(path_config, "get_error_log_path") else os.path.join(path_config.get_logs_dir(), "error.log") - os.makedirs(os.path.dirname(log_path), exist_ok=True) - import logging.handlers - logger = logging.getLogger("error_logger") - if not logger.handlers: - handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=5*1024*1024, backupCount=5, encoding="utf-8") - formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.INFO) - -class ErrorLogger: - def __init__(self) -> None: - _init_logger() - def log_exception(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None: - if not logger: - _init_logger() - if logger is None: - # 如果仍然无法初始化 logger,则退回到标准输出,避免抛出异常 - print(f"[ErrorLogger] {type(exc).__name__}: {exc}") - return - tb = traceback.format_exc() - ctx = ", ".join(f"{k}={v}" for k, v in (context or {}).items()) if context else "" - msg = f"Exception: {type(exc).__name__}: {exc}" - if ctx: - msg += f" | context: {ctx}" - if tb: - msg += f"\nTraceback:\n{tb}" - logger.log(getattr(logging, level, logging.ERROR), msg) - def log_error(self, msg: str, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None: - if not logger: - _init_logger() - if logger is None: - print(f"[ErrorLogger] {msg}") - return - full = msg - if context: - full += " | " + ", ".join(f"{k}={v}" for k, v in context.items()) - logger.log(getattr(logging, level, logging.ERROR), full) - def log_warning(self, msg: str, context: Optional[Dict[str, Any]] = None) -> None: - self.log_error(msg, context=context, level="WARNING") - def capture_error_context(self, **ctx) -> Dict[str, Any]: - return dict(ctx) - def log_error_with_context(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None: - self.log_exception(exc, context=context, level=level) - -__all__ = ["ErrorLogger"] diff --git a/douyin/logging/internal_loggers.py b/douyin/logging/internal_loggers.py new file mode 100644 index 0000000..6733749 --- /dev/null +++ b/douyin/logging/internal_loggers.py @@ -0,0 +1,228 @@ +"""内部日志器:DebugLogger 和 ErrorLogger 合并到同一个文件。 + +这两个类只被 douyin_logging_wrapper 内部使用,外部不应直接引用。 +为减少模块数量,合并为单文件。 +""" +from __future__ import annotations + +import logging +import logging.handlers +import os +import time +import traceback +from typing import Any, Dict, Optional + +from douyin.core import path_config + +from .log_formatter import format_debug_log +from .performance_tracker import PerformanceTracker + + +# ============================================================ +# ErrorLogger +# ============================================================ + +_error_module_logger: Optional[logging.Logger] = None + + +def _init_error_logger() -> None: + """惰性初始化错误日志器,写入 logs/error.log""" + global _error_module_logger + if _error_module_logger is not None: + return + log_path = ( + path_config.get_error_log_path() + if hasattr(path_config, "get_error_log_path") + else os.path.join(path_config.get_logs_dir(), "error.log") + ) + os.makedirs(os.path.dirname(log_path), exist_ok=True) + _error_module_logger = logging.getLogger("error_logger") + if not _error_module_logger.handlers: + handler = logging.handlers.RotatingFileHandler( + log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8" + ) + formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") + handler.setFormatter(formatter) + _error_module_logger.addHandler(handler) + _error_module_logger.setLevel(logging.INFO) + + +class ErrorLogger: + def __init__(self) -> None: + _init_error_logger() + + def log_exception( + self, + exc: BaseException, + context: Optional[Dict[str, Any]] = None, + level: str = "ERROR", + ) -> None: + if not _error_module_logger: + _init_error_logger() + if _error_module_logger is None: + print(f"[ErrorLogger] {type(exc).__name__}: {exc}") + return + tb = traceback.format_exc() + ctx = ( + ", ".join(f"{k}={v}" for k, v in (context or {}).items()) + if context + else "" + ) + msg = f"Exception: {type(exc).__name__}: {exc}" + if ctx: + msg += f" | context: {ctx}" + if tb: + msg += f"\nTraceback:\n{tb}" + _error_module_logger.log(getattr(logging, level, logging.ERROR), msg) + + def log_error( + self, + msg: str, + context: Optional[Dict[str, Any]] = None, + level: str = "ERROR", + ) -> None: + if not _error_module_logger: + _init_error_logger() + if _error_module_logger is None: + print(f"[ErrorLogger] {msg}") + return + full = msg + if context: + full += " | " + ", ".join(f"{k}={v}" for k, v in context.items()) + _error_module_logger.log(getattr(logging, level, logging.ERROR), full) + + def log_warning( + self, msg: str, context: Optional[Dict[str, Any]] = None + ) -> None: + self.log_error(msg, context=context, level="WARNING") + + def capture_error_context(self, **ctx) -> Dict[str, Any]: + return dict(ctx) + + def log_error_with_context( + self, + exc: BaseException, + context: Optional[Dict[str, Any]] = None, + level: str = "ERROR", + ) -> None: + self.log_exception(exc, context=context, level=level) + + +# ============================================================ +# DebugLogger +# ============================================================ + +_debug_module_logger = logging.getLogger("debug_logger") +if not _debug_module_logger.handlers: + _debug_module_logger.setLevel(logging.DEBUG) + _debug_module_logger.addHandler(logging.StreamHandler()) + try: + log_dir = os.path.join( + os.path.dirname( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + ), + "logs", + ) + os.makedirs(log_dir, exist_ok=True) + _debug_log_path = os.path.join(log_dir, "debug.log") + _file_handler = logging.handlers.RotatingFileHandler( + _debug_log_path, + maxBytes=10 * 1024 * 1024, + backupCount=5, + encoding="utf-8", + ) + _file_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s")) + _debug_module_logger.addHandler(_file_handler) + except Exception: + # 文件处理器创建失败时退回到控制台输出 + pass + + +_perf = PerformanceTracker() +_err = ErrorLogger() + + +class DebugLogger: + def __init__(self, enabled: bool = True) -> None: + self.enabled = enabled + + def log_function_entry( + self, func_name: str, *args: Any, **kwargs: Any + ) -> None: + if not self.enabled: + return + line = format_debug_log( + f"FunctionEntry: {func_name}", + level="DEBUG", + args=args, + kwargs=kwargs, + ) + _debug_module_logger.debug(line) + + def log_function_exit( + self, func_name: str, retval: Any, elapsed: float + ) -> None: + if not self.enabled: + return + line = format_debug_log( + f"FunctionExit: {func_name}", + level="DEBUG", + elapsed_seconds=elapsed, + return_value=retval, + ) + _debug_module_logger.debug(line) + + def log_variable(self, name: str, value: Any) -> None: + if not self.enabled: + return + line = format_debug_log( + f"VariableSnapshot: {name}=", level="DEBUG", value=value + ) + _debug_module_logger.debug(line) + + def log_call_stack(self) -> None: + if not self.enabled: + return + stack = traceback.format_stack() + line = format_debug_log( + "CallStack", level="DEBUG", stack="".join(stack) + ) + _debug_module_logger.debug(line) + + def log_exception( + self, exc: BaseException, context: Optional[Dict[str, Any]] = None + ) -> None: + if not self.enabled: + return + tb = traceback.format_exc() + line = format_debug_log( + "Exception", + level="ERROR", + exception=type(exc).__name__, + traceback=tb, + context=context or {}, + ) + _debug_module_logger.error(line) + _err.log_exception(exc, context=context) + + def log_step( + self, + name: str, + start_time: float, + end_time: Optional[float] = None, + ) -> None: + if not self.enabled: + return + t = (end_time if end_time is not None else time.time()) - start_time + line = format_debug_log( + "StepTiming", level="DEBUG", step=name, elapsed_seconds=t + ) + _debug_module_logger.debug(line) + _perf.get_elapsed(name) + + +def _get_debug_logger() -> DebugLogger: + return DebugLogger(True) + + +__all__ = ["ErrorLogger", "DebugLogger", "_get_debug_logger"] diff --git a/douyin/utils/time_utils.py b/douyin/utils/time_utils.py index 90bb8fe..499cde0 100644 --- a/douyin/utils/time_utils.py +++ b/douyin/utils/time_utils.py @@ -3,7 +3,6 @@ 集中化以前散落在多个文件的重复实现: - douyin/fudai/douyin_fudai_core.py: _parse_mm_ss - douyin/fudai/core/fudai_detail_reader.py: _parse_mm_ss -- fudai_detail_modules/fudai_detail_reader.py: _parse_mm_ss 注意:normalize_countdown_text 仍在 douyin/utils/douyin_utils.py 中, 那里逻辑更复杂(包含 OCR 字符纠正等),不在此处重复。 diff --git a/fudai_detail_modules/README.md b/fudai_detail_modules/README.md deleted file mode 100644 index 196d4c5..0000000 --- a/fudai_detail_modules/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# 福袋详情模块目录 - -本目录包含 `douyin_fudai_detail.py` 的模块化子模块。 - -## 文件结构 - -- `fudai_detail_room_title.py` - 直播间标题处理模块 -- `fudai_detail_operations.py` - 福袋详情页操作模块(打开/关闭) -- `fudai_detail_coupon_detection.py` - 优惠券弹窗检测模块 -- `fudai_detail_reader.py` - 福袋详情读取模块 -- `fudai_detail_validator.py` - 数据验证模块 -- `fudai_detail_utils.py` - 工具函数模块 -- `__init__.py` - 包初始化文件 - -## 使用方式 - -所有功能通过主模块 `douyin_fudai_detail` 导出,使用方式保持不变: - -```python -import douyin_fudai_detail - -# 使用导出的函数 -douyin_fudai_detail.close_fudai_detail(analyser) -douyin_fudai_detail.read_fudai_detail_once(analyser) -# ... 等等 -``` - -## 模块说明 - -### fudai_detail_room_title.py -处理直播间标题的OCR识别、噪音过滤、规范化等功能。 - -### fudai_detail_operations.py -处理福袋详情页的打开和关闭操作。 - -### fudai_detail_coupon_detection.py -检测当前弹窗是否为优惠券弹窗,而非真正的福袋详情页。 - -### fudai_detail_reader.py -执行福袋详情的OCR识别和读取,包括单次读取和重试读取。 - -### fudai_detail_validator.py -验证福袋详情数据的合理性,检测识别错误。 - -### fudai_detail_utils.py -提供通用的工具函数。 - diff --git a/fudai_detail_modules/__init__.py b/fudai_detail_modules/__init__.py deleted file mode 100644 index 3597f72..0000000 --- a/fudai_detail_modules/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -""" -福袋详情模块包 -============== - -包含所有福袋详情相关的子模块。 -""" - -__all__ = [] diff --git a/gui/gui_app.py b/gui/gui_app.py index 7021f45..ccbb401 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -60,70 +60,17 @@ warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarnin def format_gui_log_line(line: str) -> str: - """ - 将完整日志行转换为GUI显示用的精简版本。 + """将完整日志行转换为 GUI 显示用的精简版本。 - 使用新的日志格式化模块进行美化和格式化处理。 + 实际实现位于 gui.components.log_viewer,此处仅作 re-export, + 失败时回退到原始字符串。 """ try: - # 尝试使用新的日志格式化模块 - from gui.components.log_viewer import format_gui_log_line as enhanced_formatter + from gui.components.log_viewer import format_gui_log_line as _impl - return enhanced_formatter(line) - except ImportError: - # 如果新模块不可用,回退到原来的实现 - pass - - # 回退到原来的精简规则(兼容统一日志格式) - s = (line or "").rstrip("\n") - if not s: - return s - - ts_part: str | None = None - msg_part: str | None = None - - # 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=... - m = re.match(r"^\[(\d{4}-\d{2}-\d{2} [0-9:.]+)\]\s+\[[A-Z]+\]\s+(.*)$", s) - if m: - ts_part = m.group(1).strip() - msg_part = m.group(2).strip() - # 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容 - elif s[0].isdigit() and " - " in s: - parts = s.split(" - ") - if len(parts) >= 3: - ts_part = parts[0].strip() - msg_part = parts[-1].strip() - - # 如果没解析出时间戳和消息,返回原字符串 - if not ts_part or msg_part is None: - return s - - # 从业务文案中拆分出字段_xxx=yyy,非score类字段在GUI中隐藏 - keep_tokens: list[str] = [] - - def _is_score_field(k: str) -> bool: - kl = k.lower() - return ( - "score" in kl or "match" in kl or "匹配" in k or "相似" in k or "耗时" in k - ) - - # 解析字段 - words = msg_part.split() - clean_words = [] - for word in words: - if "=" in word: - k, v = word.split("=", 1) - if _is_score_field(k): - keep_tokens.append(word) - # else: 其他字段在GUI中隐藏 - else: - clean_words.append(word) - - clean_msg = " ".join(clean_words) - if keep_tokens: - clean_msg = f"{clean_msg} ({', '.join(keep_tokens)})" - - return f"{ts_part} {clean_msg}" + return _impl(line) + except Exception: + return (line or "").rstrip("\n") def main(): diff --git a/operations/device_operations.py b/operations/device_operations.py deleted file mode 100644 index f999919..0000000 --- a/operations/device_operations.py +++ /dev/null @@ -1,16 +0,0 @@ -"""设备操作模块 - -包含ADB设备操作,如点击、滑动、输入等。 -""" - -from __future__ import annotations - -from typing import Any, Optional - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后,移除此导入并在此文件中实现 -from douyin.core.underlying_operations import underlying_operations - -# 导出设备操作相关方法 -# TODO: 实现这些函数后添加到__all__列表中 -__all__ = [] diff --git a/operations/image_operations.py b/operations/image_operations.py deleted file mode 100644 index ed273d4..0000000 --- a/operations/image_operations.py +++ /dev/null @@ -1,16 +0,0 @@ -"""图像处理操作模块 - -包含图像裁剪、处理等操作。 -""" - -from __future__ import annotations - -from typing import Any, Optional, Tuple - -# 临时导入:从原文件导入,后续会逐步迁移 -# TODO: 迁移完成后,移除此导入并在此文件中实现 -from douyin.core.underlying_operations import underlying_operations - -# 导出图像处理相关方法 -# TODO: 实现这些函数后添加到__all__列表中 -__all__ = [] diff --git a/operations/screenshot_service_new.py b/operations/screenshot_service_new.py deleted file mode 100644 index 8684781..0000000 --- a/operations/screenshot_service_new.py +++ /dev/null @@ -1,134 +0,0 @@ -"""简化版后台截图服务,避免文件中重复定义导致的 linter 错误。""" - -from __future__ import annotations - -import os -import threading -import time -from typing import Optional -from datetime import datetime -from douyin.core import path_config -from operations.screenshot_operations import ScreenshotOperations - - -class ScreenshotService: - """后台截图服务(简化实现)。""" - - _instance: Optional["ScreenshotService"] = None - _lock = threading.Lock() - - def __init__(self): - self._running = False - self._thread: Optional[threading.Thread] = None - self._screenshot_ops = ScreenshotOperations() - self._current_device_id: Optional[str] = None - self._last_screenshot_time = time.time() - 10.0 - self._screenshot_interval = 3.5 - self._cache_valid_duration = 4.0 - self._screenshot_path: Optional[str] = None - self._last_success = False - - @classmethod - def get_instance(cls) -> "ScreenshotService": - if cls._instance is None: - with cls._lock: - if cls._instance is None: - cls._instance = cls() - assert cls._instance is not None - return cls._instance - - def start(self, device_id: str, interval: float = 1.5): - with self._lock: - if self._running and self._current_device_id == device_id: - return - if self._running: - self.stop() - self._current_device_id = device_id - self._screenshot_interval = max(0.5, interval) - self._running = True - try: - self._screenshot_path = path_config.get_screenshot_path() - except Exception: - self._screenshot_path = os.path.join("pic", "screenshot.png") - self._thread = threading.Thread(target=self._screenshot_loop, daemon=True, name="ScreenshotService") - self._thread.start() - self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") - - def stop(self): - with self._lock: - if not self._running: - return - self._running = False - if self._thread and self._thread.is_alive(): - self._thread.join(timeout=2.0) - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已停止后台截图服务") - - def _screenshot_loop(self): - while self._running: - try: - if not self._current_device_id: - time.sleep(0.1) - continue - start = time.time() - success = self._screenshot_ops.get_screenshot(self._current_device_id, use_service=False) - elapsed = (time.time() - start) * 1000 - timetag = datetime.now().strftime("%H:%M:%S") - if success: - self._last_screenshot_time = time.time() - self._last_success = True - print(f"[{timetag}] [截图服务] 后台截图成功,耗时: {elapsed:.0f}ms") - else: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图失败,耗时: {elapsed:.0f}ms") - time.sleep(max(0.5, self._screenshot_interval - elapsed / 1000)) - except Exception as e: - print(f"[截图服务] 异常: {e}") - time.sleep(1.0) - - def get_screenshot(self, device_id: str, force: bool = False) -> bool: - # 优先使用缓存判断,简化版保留核心逻辑 - if self._current_device_id != device_id: - self.start(device_id) - time.sleep(0.1) - now = time.time() - if not force and now - self._last_screenshot_time < self._cache_valid_duration: - if self._screenshot_path and os.path.exists(self._screenshot_path): - try: - if os.path.getsize(self._screenshot_path) >= 1024: - return True - except Exception: - pass - # 回退到直接截图 - return self._screenshot_ops.get_screenshot(device_id, use_service=False) - - def is_running(self) -> bool: - return self._running - - def get_last_screenshot_time(self) -> float: - return self._last_screenshot_time - - def get_cache_info(self) -> dict: - return { - "running": self._running, - "device_id": self._current_device_id, - "last_screenshot_time": self._last_screenshot_time, - "interval": self._screenshot_interval, - "cache_valid_duration": self._cache_valid_duration, - "last_success": self._last_success, - } - - -def get_optimal_workers() -> int: - cpu_count = os.cpu_count() or 4 - if cpu_count >= 12: - return 10 - if cpu_count >= 8: - return 8 - if cpu_count >= 4: - return 6 - if cpu_count >= 2: - return 3 - return 2