- Updated `config.json` to include new settings for `enable_ocr_mode1` and `fudai_template_match_threshold`. - Refactored `douyin_detection.py` to implement template matching for 福袋 detection, replacing the previous pixel-based method. - Improved error handling and logging for template matching operations. - Added GUI options for enabling OCR mode and adjusting template matching threshold. - Enhanced command-line interface to support new OCR and template matching parameters.
658 lines
28 KiB
Python
658 lines
28 KiB
Python
from __future__ import annotations
|
||
|
||
"""
|
||
本地完整版 douyin_fudai(模块化调度器)
|
||
======================================
|
||
|
||
目标:
|
||
- 不再依赖外部 axf 目录;
|
||
- 保持 `from douyin_fudai import fudai_analyse` 导入方式不变;
|
||
- 将核心逻辑拆分到各子模块,仅在此做“组装 + 调度”。
|
||
"""
|
||
|
||
from typing import Any, List, Tuple
|
||
import os
|
||
import time
|
||
|
||
from Underlying_Operations import underlying_operations
|
||
|
||
import douyin_stage
|
||
import douyin_detection
|
||
import douyin_fudai_detail
|
||
import douyin_fudai_core
|
||
import douyin_flow_control
|
||
import douyin_live_room
|
||
import douyin_lottery
|
||
import douyin_popups
|
||
import douyin_robot
|
||
import douyin_swipe_ops
|
||
import douyin_text_utils
|
||
import douyin_utils
|
||
import douyin_yanghao
|
||
import douyin_pixel
|
||
|
||
|
||
class fudai_analyse:
|
||
"""福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。"""
|
||
|
||
def __init__(self) -> None:
|
||
# 设备与分辨率
|
||
self.device_id: str = "XXXXXXXXX"
|
||
self.y_pianyi: int = 0
|
||
self.resolution_ratio_x: int = 1080
|
||
self.resolution_ratio_y: int = 2400
|
||
|
||
# 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部)
|
||
self.operation = underlying_operations()
|
||
self.config_path = "config.json"
|
||
|
||
# 日志相关字段:沿用原 fudai1.py 的 _log_kv 实现
|
||
from 原始代码.fudai1 import fudai_analyse as _Orig # type: ignore
|
||
|
||
# 直接复用原始实现中的 _log_kv,以保持统一格式
|
||
self._run_id = getattr(_Orig(), "_run_id", str(int(time.time())))
|
||
self._log_seq = 0
|
||
self._log_kv = _Orig._log_kv.__get__(self, fudai_analyse) # type: ignore[attr-defined]
|
||
|
||
# 进入直播间后诊断与阶段流转所需的一些状态
|
||
self._last_diag_stage: str = "INIT"
|
||
self._last_diag_seen: str = "-"
|
||
self._last_diag_ts: float = 0.0
|
||
|
||
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
|
||
self.contains_not_want: list[str] = []
|
||
self.contains_want: list[str] = []
|
||
self.min_prize_value_yuan: float = 0.0
|
||
self.min_participants: int = 0
|
||
self.max_participants: int = 0
|
||
self.skip_if_countdown_lt_seconds: int = 15
|
||
self.no_fudai_watchdog_enabled: bool = False
|
||
# 福袋图标检测节流相关默认值
|
||
# 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整
|
||
# 注意:已改为使用时间限制(fudai_icon_max_wait_seconds),不再使用尝试次数限制
|
||
self.fudai_icon_retry_delay_seconds: float = 0.6
|
||
self.fudai_icon_max_wait_seconds: float = 5.0
|
||
# fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用
|
||
self.fudai_find_max_attempts: int = 10
|
||
self.screenshot_diagnose_min_interval_seconds: float = 8.0
|
||
|
||
# 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8)
|
||
self.live_room_match_threshold: float = 0.8
|
||
# 福袋模板匹配阈值(0.0~1.0,默认0.7)
|
||
self.fudai_template_match_threshold: float = 0.7
|
||
|
||
# 初次加载配置
|
||
self.load_config()
|
||
|
||
def load_config(self) -> None:
|
||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||
import json
|
||
import os
|
||
|
||
path = getattr(self, "config_path", "config.json")
|
||
try:
|
||
if not os.path.exists(path):
|
||
return
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
config = json.load(f)
|
||
except Exception:
|
||
return
|
||
|
||
try:
|
||
self.contains_not_want = list(config.get("contains_not_want", []) or [])
|
||
except Exception:
|
||
self.contains_not_want = []
|
||
try:
|
||
self.contains_want = list(config.get("contains_want", []) or [])
|
||
except Exception:
|
||
self.contains_want = []
|
||
|
||
def _float(name: str, default: float) -> float:
|
||
try:
|
||
return float(config.get(name, default) or default)
|
||
except Exception:
|
||
return default
|
||
|
||
def _int(name: str, default: int) -> int:
|
||
try:
|
||
return int(config.get(name, default) or default)
|
||
except Exception:
|
||
return default
|
||
|
||
self.min_prize_value_yuan = _float("min_prize_value_yuan", self.min_prize_value_yuan)
|
||
self.min_participants = _int("min_participants", self.min_participants)
|
||
self.max_participants = _int("max_participants", self.max_participants)
|
||
self.skip_if_countdown_lt_seconds = _int("skip_if_countdown_lt_seconds", self.skip_if_countdown_lt_seconds)
|
||
|
||
try:
|
||
self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", self.no_fudai_watchdog_enabled))
|
||
except Exception:
|
||
pass
|
||
|
||
self.fudai_icon_retry_delay_seconds = _float(
|
||
"fudai_icon_retry_delay_seconds",
|
||
self.fudai_icon_retry_delay_seconds,
|
||
)
|
||
self.fudai_icon_max_wait_seconds = _float(
|
||
"fudai_icon_max_wait_seconds",
|
||
self.fudai_icon_max_wait_seconds,
|
||
)
|
||
self.fudai_find_max_attempts = _int(
|
||
"fudai_find_max_attempts",
|
||
self.fudai_find_max_attempts,
|
||
)
|
||
self.screenshot_diagnose_min_interval_seconds = _float(
|
||
"screenshot_diagnose_min_interval_seconds",
|
||
self.screenshot_diagnose_min_interval_seconds,
|
||
)
|
||
self.live_room_match_threshold = _float(
|
||
"live_room_match_threshold",
|
||
self.live_room_match_threshold,
|
||
)
|
||
# 确保阈值在合理范围内
|
||
if self.live_room_match_threshold < 0.0:
|
||
self.live_room_match_threshold = 0.0
|
||
if self.live_room_match_threshold > 1.0:
|
||
self.live_room_match_threshold = 1.0
|
||
|
||
self.fudai_template_match_threshold = _float(
|
||
"fudai_template_match_threshold",
|
||
self.fudai_template_match_threshold,
|
||
)
|
||
# 确保阈值在合理范围内
|
||
if self.fudai_template_match_threshold < 0.0:
|
||
self.fudai_template_match_threshold = 0.0
|
||
if self.fudai_template_match_threshold > 1.0:
|
||
self.fudai_template_match_threshold = 1.0
|
||
|
||
# ========== 兼容旧入口:主循环 ==========
|
||
def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15) -> None:
|
||
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
|
||
self.device_id = device_id or self.device_id
|
||
self.y_pianyi = int(y_pianyi or 0)
|
||
try:
|
||
rx, ry = self.operation.get_device_resolution(self.device_id)
|
||
self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int(ry or 2400)
|
||
except Exception:
|
||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||
|
||
self._log_kv(
|
||
"启动",
|
||
"fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)",
|
||
分辨率=f"{self.resolution_ratio_x}x{self.resolution_ratio_y}",
|
||
needswitch=int(bool(needswitch)),
|
||
wait_minutes=int(wait_minutes),
|
||
)
|
||
|
||
# 基础循环:在限定时间内反复执行单轮逻辑
|
||
# 如果 wait_minutes <= 0,则无限循环运行
|
||
if wait_minutes and wait_minutes > 0:
|
||
end_ts = time.time() + int(wait_minutes) * 60
|
||
while time.time() < end_ts:
|
||
try:
|
||
self.run_once_basic()
|
||
except Exception as e:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv("循环", "run_once_basic 异常", error=str(e), error_type=type(e).__name__)
|
||
except Exception:
|
||
pass
|
||
# 异常后稍作延迟再继续
|
||
try:
|
||
self.operation.delay(2.0)
|
||
except Exception:
|
||
time.sleep(2.0)
|
||
continue
|
||
|
||
# 为避免过于频繁截图,增加少量间隔
|
||
try:
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
time.sleep(1.0)
|
||
else:
|
||
# 无限循环模式(wait_minutes <= 0)
|
||
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
|
||
while True:
|
||
try:
|
||
self.run_once_basic()
|
||
except KeyboardInterrupt:
|
||
# 允许 Ctrl+C 退出
|
||
self._log_kv("循环", "收到中断信号,退出循环")
|
||
raise
|
||
except Exception as e:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv("循环", "run_once_basic 异常", error=str(e), error_type=type(e).__name__)
|
||
except Exception:
|
||
pass
|
||
# 异常后稍作延迟再继续
|
||
try:
|
||
self.operation.delay(2.0)
|
||
except Exception:
|
||
time.sleep(2.0)
|
||
continue
|
||
|
||
# 为避免过于频繁截图,增加少量间隔
|
||
try:
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
time.sleep(1.0)
|
||
|
||
# ========== 阶段诊断 ==========
|
||
def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]:
|
||
"""封装到子模块的阶段诊断入口。"""
|
||
return douyin_stage.diagnose_stage_from_current_screen(self)
|
||
|
||
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
|
||
def cut_pic(
|
||
self,
|
||
x_top: int = 1,
|
||
y_top: int = 1,
|
||
x_bottom: int = 2,
|
||
y_bottom: int = 2,
|
||
target: str = "",
|
||
cut_pic_name: str = "",
|
||
y_pianyi: int = 0,
|
||
) -> None:
|
||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||
try:
|
||
x1 = x_top * self.resolution_ratio_x // 1080
|
||
y1 = y_top * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||
x2 = x_bottom * self.resolution_ratio_x // 1080
|
||
y2 = y_bottom * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||
self.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"截图",
|
||
"cut_pic 失败",
|
||
error=str(e),
|
||
x_top=x_top,
|
||
y_top=y_top,
|
||
x_bottom=x_bottom,
|
||
y_bottom=y_bottom,
|
||
y_pianyi=y_pianyi,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
def _read_pixel_stage_state(self) -> dict:
|
||
"""读取像素阶段状态(用于阶段诊断)。"""
|
||
import os
|
||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||
return douyin_pixel.read_pixel_stage_state_from_screenshot(pic_path)
|
||
|
||
def _check_in_live_room_by_icon(self) -> Tuple[bool, float]:
|
||
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
|
||
|
||
返回:
|
||
(detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。
|
||
"""
|
||
# 为了兼容没有 cv2/numpy 的环境,这里做降级处理
|
||
try:
|
||
import cv2 # type: ignore
|
||
import numpy as np # type: ignore
|
||
import os
|
||
# 抑制OpenCV的文件读取警告(多种方法组合)
|
||
# 方法1:设置环境变量
|
||
os.environ['OPENCV_LOG_LEVEL'] = 'ERROR'
|
||
# 方法2:使用cv2.setLogLevel(OpenCV 4.x+)
|
||
try:
|
||
cv2.setLogLevel(0) # 0 = SILENT
|
||
except (AttributeError, Exception):
|
||
# 如果setLogLevel不存在(旧版本OpenCV),尝试其他方法
|
||
try:
|
||
# OpenCV 3.x 使用 cv2.utils.logging.setLogLevel
|
||
if hasattr(cv2, 'utils') and hasattr(cv2.utils, 'logging'):
|
||
cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_SILENT)
|
||
except Exception:
|
||
pass
|
||
# 方法3:通过logging抑制Python层的警告
|
||
try:
|
||
import logging
|
||
logging.getLogger('cv2').setLevel(logging.ERROR)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别")
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
base_dir = os.path.dirname(__file__)
|
||
pic_dir = os.path.join(base_dir, "pic")
|
||
assets_dir = os.path.join(base_dir, "assets")
|
||
screenshot_path = os.path.join(pic_dir, "screenshot.png")
|
||
|
||
# 确保有最新截图
|
||
try:
|
||
self.operation.get_screenshot(self.device_id)
|
||
except Exception:
|
||
# 若截图失败则尝试继续使用旧图
|
||
pass
|
||
|
||
if not os.path.exists(screenshot_path):
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon 截图不存在", path=screenshot_path)
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
try:
|
||
img = cv2.imread(screenshot_path, cv2.IMREAD_GRAYSCALE)
|
||
if img is None:
|
||
raise RuntimeError("cv2.imread 返回 None")
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e))
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
# 获取可配置的匹配阈值(用于模板匹配,像素检测使用不同的阈值)
|
||
# 注意:live_room_match_threshold 主要用于像素检测,模板匹配可以使用稍低的阈值
|
||
threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
|
||
# 模板匹配可以使用稍低的阈值(像素检测优先,模板匹配作为补充)
|
||
template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90%
|
||
# 确保阈值在合理范围内
|
||
if threshold < 0.0:
|
||
threshold = 0.0
|
||
if threshold > 1.0:
|
||
threshold = 1.0
|
||
if template_threshold < 0.0:
|
||
template_threshold = 0.0
|
||
if template_threshold > 1.0:
|
||
template_threshold = 1.0
|
||
|
||
# 第一步:裁剪右上角图标区域,保存到 pic/ocr/ 目录
|
||
ih, iw = img.shape[:2]
|
||
roi_x1 = max(0, int(iw * 0.60)) # 60%宽度开始
|
||
roi_y1 = 0
|
||
roi_x2 = iw # 100%宽度
|
||
roi_y2 = min(ih, int(ih * 0.40)) # 40%高度
|
||
roi = img[roi_y1:roi_y2, roi_x1:roi_x2]
|
||
|
||
if roi.size == 0:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon ROI区域为空")
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
# 保存裁剪的ROI区域到 pic/ocr/ 目录
|
||
ocr_dir = os.path.join(pic_dir, "ocr")
|
||
os.makedirs(ocr_dir, exist_ok=True)
|
||
x_roi_path = os.path.join(ocr_dir, "xx.png")
|
||
xin_roi_path = os.path.join(ocr_dir, "xxin.png")
|
||
|
||
try:
|
||
# 保存ROI区域(两个文件保存相同的内容,因为x和xin图标在同一区域)
|
||
cv2.imwrite(x_roi_path, roi)
|
||
cv2.imwrite(xin_roi_path, roi)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e))
|
||
except Exception:
|
||
pass
|
||
|
||
# 第二步:使用 assets/ 目录下的模板去匹配 pic/ocr/ 目录下的裁剪图片
|
||
# assets/x.png 和 assets/xin.png 是模板
|
||
# pic/ocr/xx.png 和 pic/ocr/xxin.png 是要匹配的图片
|
||
template_roi_pairs = [
|
||
(os.path.join(assets_dir, "x.png"), x_roi_path, "x"),
|
||
(os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"),
|
||
]
|
||
|
||
best_score = 0.0
|
||
best_name = ""
|
||
detected = False
|
||
|
||
for template_path, roi_path, icon_name in template_roi_pairs:
|
||
try:
|
||
# 检查模板文件是否存在
|
||
if not os.path.exists(template_path) or not os.path.isfile(template_path):
|
||
continue
|
||
try:
|
||
if os.path.getsize(template_path) == 0:
|
||
continue
|
||
except (OSError, IOError):
|
||
continue
|
||
|
||
# 检查ROI文件是否存在(应该刚保存的)
|
||
if not os.path.exists(roi_path) or not os.path.isfile(roi_path):
|
||
continue
|
||
|
||
# 读取模板和ROI图片
|
||
try:
|
||
tpl = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
|
||
roi_img = cv2.imread(roi_path, cv2.IMREAD_GRAYSCALE)
|
||
except Exception:
|
||
continue
|
||
|
||
if tpl is None or roi_img is None:
|
||
continue
|
||
|
||
th, tw = tpl.shape[:2]
|
||
rh, rw = roi_img.shape[:2]
|
||
|
||
# 模板必须小于或等于ROI
|
||
if th > rh or tw > rw:
|
||
# 如果模板比ROI大,缩小模板
|
||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||
if scale <= 0:
|
||
continue
|
||
tpl = cv2.resize(tpl, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||
th, tw = tpl.shape[:2]
|
||
|
||
# 在ROI中匹配模板
|
||
res = cv2.matchTemplate(roi_img, tpl, cv2.TM_CCOEFF_NORMED)
|
||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||
|
||
# 记录最佳匹配分数和模板名称
|
||
if max_val > best_score:
|
||
best_score = float(max_val or 0.0)
|
||
best_name = f"assets/{icon_name}.png -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png"
|
||
|
||
# 如果匹配分数达到阈值,标记为检测成功
|
||
# 使用 template_threshold(模板匹配阈值),而不是 threshold(像素检测阈值)
|
||
if max_val >= template_threshold:
|
||
detected = True
|
||
except Exception:
|
||
continue
|
||
|
||
if not detected and best_score == 0.0:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件")
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断",
|
||
"_check_in_live_room_by_icon 结果",
|
||
detected=int(bool(detected)),
|
||
score=round(best_score, 3),
|
||
template=best_name or "-",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
return bool(detected), float(best_score or 0.0)
|
||
|
||
def check_in_fudai_detail(self) -> bool:
|
||
"""判断当前是否处于福袋详情页:委托给 douyin_detection.check_in_fudai_detail。"""
|
||
try:
|
||
return bool(douyin_detection.check_in_fudai_detail(self))
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv("检测", "check_in_fudai_detail 异常", error=str(e))
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
# 供像素/检测模块记录子步骤耗时使用
|
||
def _log_step_time(self, step_name: str, start_time: float, extra_info: dict | None = None) -> None:
|
||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。"""
|
||
try:
|
||
elapsed = time.time() - float(start_time or 0.0)
|
||
except Exception:
|
||
elapsed = 0.0
|
||
fields: dict[str, Any] = {"seconds": elapsed}
|
||
if extra_info:
|
||
for k, v in extra_info.items():
|
||
fields[str(k)] = v
|
||
try:
|
||
self._log_kv("步骤耗时", step_name, **fields)
|
||
except Exception:
|
||
pass
|
||
|
||
# ========== 弹窗 / 人机校验 ==========
|
||
def _check_coupon_popup(self) -> bool:
|
||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的“看门狗”中使用)。"""
|
||
return douyin_popups.check_coupon_popup(self)
|
||
|
||
def _check_shopping_redpacket_popup(self) -> bool:
|
||
"""购物红包中央弹窗。"""
|
||
return douyin_popups.check_shopping_redpacket_popup(self)
|
||
|
||
# ========== 主循环骨架(基础抢福袋,暂不启用预约) ==========
|
||
def run_once_basic(self) -> None:
|
||
"""单轮基础抢福袋流程(不包含预约队列、高价值房间等高阶功能)。"""
|
||
# 1. 截图 + 阶段诊断
|
||
ok = self.operation.get_screenshot(self.device_id)
|
||
if not ok:
|
||
self._log_kv("截图", "获取截图失败", ok=0)
|
||
return
|
||
|
||
stage, seen = self._diagnose_stage_from_current_screen()
|
||
self._last_diag_stage = stage
|
||
self._last_diag_seen = seen
|
||
self._last_diag_ts = time.time()
|
||
self._log_kv("截图", "截图+阶段诊断", stage=stage, seen=seen)
|
||
|
||
# 2. 诊断后分支(弹窗检测已合并到阶段诊断中)
|
||
# 处理弹窗阶段
|
||
if stage == "COUPON_POPUP":
|
||
# 优惠券弹窗:按返回键关闭
|
||
self._log_kv("弹窗处理", "检测到优惠券弹窗,按返回键关闭")
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(0.5)
|
||
self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗")
|
||
except Exception as e:
|
||
self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e))
|
||
return
|
||
elif stage == "SHOPPING_REDPACKET_POPUP":
|
||
# 购物红包弹窗:点击关闭按钮
|
||
self._log_kv("弹窗处理", "检测到购物红包弹窗,点击关闭按钮")
|
||
try:
|
||
close_x = int(530 * self.resolution_ratio_x // 1080)
|
||
close_y = int(1647 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, close_x, close_y)
|
||
self.operation.delay(0.5)
|
||
self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y)
|
||
except Exception as e:
|
||
self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e))
|
||
return
|
||
elif stage == "FUDai_DETAIL":
|
||
# 已经在详情页:直接读详情并决定是否参与
|
||
self._handle_in_fudai_detail()
|
||
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
|
||
# 在直播间:寻找福袋图标并尝试点开
|
||
self._handle_live_room_has_or_not_fudai()
|
||
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
|
||
# 处理推荐/关注/直播列表页:回到直播间或切换
|
||
if stage == "RECOMMEND_PAGE":
|
||
# 识别到推荐页面:点击关注标签,然后点击进入直播间
|
||
self._log_kv("流程", "检测到推荐页面,点击关注标签并进入直播间", stage=stage, seen=seen)
|
||
try:
|
||
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
|
||
follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
|
||
follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
|
||
self._log_kv("流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
|
||
self.operation.delay(2.0)
|
||
|
||
# 点击进入直播间的位置 (103, 385),连点两次
|
||
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
|
||
enter_live_y = int(385 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self.operation.delay(0.6)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self._log_kv("流程", "点击进入直播间位置", x=enter_live_x, y=enter_live_y, 次数=2)
|
||
self.operation.delay(2.0)
|
||
except Exception as e:
|
||
self._log_kv("流程", "处理推荐页面时出错", error=str(e))
|
||
# 如果出错,尝试回退
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 其他列表页:使用原有逻辑
|
||
douyin_live_room.reflash_zhibo(self)
|
||
elif stage in ("LIVE_CLOSED",):
|
||
# 直播结束:下滑/切下一个
|
||
self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
|
||
self.swipe_up_to_next_live()
|
||
else:
|
||
# 未识别出特殊阶段:尽量保持原地,交给上层循环
|
||
self._log_kv("阶段", "未匹配到特定阶段", stage=stage)
|
||
|
||
# ========== 基础动作封装 ==========
|
||
def swipe_up_to_next_live(self) -> None:
|
||
"""上滑切换直播间(简单版封装)。"""
|
||
douyin_swipe_ops.swipe_up_switch_live(self)
|
||
|
||
# ========== 福袋相关 ==========
|
||
def _handle_in_fudai_detail(self) -> None:
|
||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||
# 这里不做预约,只根据当前详情是否满足门槛决定参与与否
|
||
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
|
||
self,
|
||
fudai_x=0,
|
||
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
|
||
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
|
||
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
|
||
)
|
||
douyin_fudai_core.basic_join_decision(self, detail)
|
||
|
||
def _handle_live_room_has_or_not_fudai(self) -> None:
|
||
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定“继续找/切换/养号”."""
|
||
room_pos_ref: List[int] = [0]
|
||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||
if not opened:
|
||
# 无福袋,交给 flow_control 的“无福袋处理”逻辑(暂时只做简单滑动/等待)
|
||
wait_times_ref = [0]
|
||
swipe_times_ref = [0]
|
||
reservation_focus_until_ts_ref = [0.0]
|
||
reset_to_list_after_reservations_ref = [False]
|
||
douyin_flow_control.handle_no_fudai_situation(
|
||
self,
|
||
x=0,
|
||
swipe_times=0,
|
||
wait_times_ref=wait_times_ref,
|
||
needswitch=True,
|
||
reservation_focus_until_ts=0.0,
|
||
reservations=[],
|
||
room_pos=room_pos_ref[0],
|
||
post_switch_delay_s=1.5,
|
||
swipe_up_switch_callback=self.swipe_up_to_next_live,
|
||
swipe_down_back_callback=lambda: None,
|
||
sort_reservations_callback=lambda: None,
|
||
clear_reservations_callback=lambda: None,
|
||
write_state_callback=lambda: None,
|
||
back_to_list_callback=lambda: None,
|
||
into_list_callback=lambda: None,
|
||
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
|
||
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
|
||
swipe_times_ref=swipe_times_ref,
|
||
)
|
||
return
|
||
|
||
# 成功打开详情:调用同一套详情处理逻辑
|
||
self._handle_in_fudai_detail()
|
||
|