拆分 douyin_flow_control (706 → 4 个子模块 + 23 行 shim)

把 douyin/core/douyin_flow_control.py 4 个独立顶层函数拆成
douyin/core/douyin_flow_control_pkg/ 子包:

- stage_handler (34)  handle_stage_after_diagnosis 阶段后状态记录
- find_open (537)     find_and_open_fudai_detail 找福袋并打开详情(最大头)
- filter (85)         filter_fudai_detail 配置筛选决策
- no_fudai (94)       handle_no_fudai_situation 无福袋时的简单流程

原文件改为 23 行 re-export shim,4 个公共符号全部保留。
- find_and_open_fudai_detail 4 处外部引用,其他 0 处
全部不需修改。

回归:
- 5 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-21 19:03:43 +08:00
1 parent a6bbdcc400
commit badf64998d
6 files changed
+794 -702

No files matched your search

+19 -702
View File
@@ -1,706 +1,23 @@
"""
Flow control main helpers (本地模块化实现,基础版)
================================================
"""douyin_flow_control - 兼容入口(保留外部 import 路径)。
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
实际实现位于子包 ``douyin.core.douyin_flow_control_pkg``。
本文件仅 re-export 公共符号;详见各子模块文档:
- ``douyin_flow_control_pkg.stage_handler`` handle_stage_after_diagnosis
- ``douyin_flow_control_pkg.find_open`` find_and_open_fudai_detail(最大头 520 行)
- ``douyin_flow_control_pkg.filter`` filter_fudai_detail
- ``douyin_flow_control_pkg.no_fudai`` handle_no_fudai_situation
"""
from __future__ import annotations
from douyin.core.douyin_flow_control_pkg import (
filter_fudai_detail,
find_and_open_fudai_detail,
handle_no_fudai_situation,
handle_stage_after_diagnosis,
)
from typing import Any, Callable, List, Optional, Tuple
import logging
import time
import os
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
from douyin.core import path_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
func_start_time: float | None = None,
):
if func_start_time is None:
func_start_time = time.time()
return find_and_open_fudai_detail(
analyser=analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)
def find_and_open_fudai_detail(
analyser: Any,
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
if func_start_time is None:
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情
try:
if getattr(analyser, "_waiting_for_lottery_result", False):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
)
except Exception as e:
logging.debug("日志记录失败: %s", e)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
logging.debug("检查等待开奖状态失败: %s", e)
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
if remaining < 1.0:
break
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
# 再次检查时间,防止第二次调用导致超时
elapsed = time.time() - start_time
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
x = check_have_fudai_with_ready_screenshot(
analyser, screenshot_ready=False
)
if x:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标",
x=int(x or 0),
elapsed_seconds=round(time.time() - start_time, 2),
)
except Exception:
pass
# 结构化统计:检测到福袋(attempt)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_detected",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
break
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
if remaining <= 0:
break
wait_time = min(retry_delay_seconds, remaining)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
elapsed_seconds=round(elapsed, 2),
remaining_seconds=round(remaining, 2),
wait_seconds=round(wait_time, 2),
)
except Exception:
pass
try:
analyser.operation.delay(wait_time)
except Exception:
time.sleep(wait_time)
if not x:
try:
total_elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0),
max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(total_elapsed, 2),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(未找到福袋)",
elapsed_seconds=round(elapsed, 2),
)
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
try:
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
cur += 1
setattr(analyser, "_consecutive_no_fudai_count", cur)
threshold = (
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
)
if threshold is None or threshold <= 0:
# 如果未配置阈值,则尝试读取配置属性(兼容性)
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)
threshold = int(
cfg.get("fudai_exit_after_misses", 30) or 30
)
except Exception:
threshold = 30
# 如果计数达到阈值,执行返回键退出直播间并重置计数
if threshold and cur >= threshold:
try:
analyser._log_kv(
"流程",
"连续未找到福袋达到阈值:按返回键退出直播间",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
enabled = getattr(analyser, "enable_back_on_misses", None)
if enabled is None:
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)
enabled = bool(cfg.get("enable_back_on_misses", True))
else:
enabled = True
except Exception:
enabled = True
if enabled:
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
try:
import time as _time
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
try:
analyser._log_kv(
"流程",
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
)
except Exception:
pass
else:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
try:
# 兜底:使用通用 click 返回坐标
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
analyser.operation.click(
analyser.device_id, back_x, back_y
)
except Exception:
pass
except Exception:
# 在异常情况下保守地尝试按返回键
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
else:
try:
analyser._log_kv(
"流程",
"返回键回退已禁用,跳过按返回键",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 重置计数,避免重复触发
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
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
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 结构化统计:点击尝试
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_click_attempt",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image # type: ignore[import]
from douyin.handlers import douyin_screenshot_manager
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"流程检测到福袋图标后保存完整截图",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
)
except Exception:
pass
try:
analyser.operation.delay(wait_seconds)
except Exception:
time.sleep(wait_seconds)
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(device_id, use_service=False)
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
)
except Exception:
pass
return False
try:
result = douyin_stage.diagnose_stage_from_current_screen(
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
)
except Exception:
pass
try:
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
screenshot_ready_for_ocr=getattr(
analyser, "_screenshot_ready_for_ocr", False
),
)
except Exception:
pass
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 成功打开福袋详情:重置连续未找到计数
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
try:
# 结构化统计:成功打开详情(success)
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return True
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
)
except Exception:
pass
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
try:
back_click_x = int(520 * rx / 1080)
back_click_y = int(505 * ry / 2400)
except Exception:
back_click_x, back_click_y = 520, 505
try:
analyser.operation.click(device_id, back_click_x, back_click_y)
except Exception:
try:
analyser.click(back_click_x, back_click_y)
except Exception:
pass
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
analyser.last_fudai_x = 0
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="fail",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return False
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测异常",
error=str(e),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
try:
analyser.click(x, base_y)
wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
analyser.operation.delay(wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底成功)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
return False
def filter_fudai_detail(
analyser: Any,
detail: tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = (
str(detail[0] or "")
if isinstance(detail, tuple) and len(detail) >= 1
else ""
)
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选通过)",
elapsed_seconds=round(elapsed, 2),
)
return False
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选不通过)",
elapsed_seconds=round(elapsed, 2),
reason=reason,
)
return True
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback: Optional[Callable[[], None]],
swipe_down_back_callback: Callable[[], None],
sort_reservations_callback: Callable[[], None],
clear_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
back_to_list_callback: Callable[[], None],
into_list_callback: Callable[[], None],
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
reservation_after_action_pending_ref: Optional[List[bool]] = None,
reservation_back_swipe_delay_s: Optional[float] = None,
) -> bool:
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
handled_reservation = False
seek_callback = seek_reservation_room_callback or (lambda item: False)
reservation_after_action_pending_ref = (
reservation_after_action_pending_ref
if reservation_after_action_pending_ref
else [False]
)
reservation_back_swipe_delay_s = (
reservation_back_swipe_delay_s
if reservation_back_swipe_delay_s is not None
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
)
try:
from douyin.reservation import douyin_reservation_logic
handled_reservation = (
douyin_reservation_logic.process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
reservation_back_swipe_delay_s,
swipe_down_back_callback,
seek_callback,
sort_reservations_callback,
write_state_callback,
)
)
except Exception:
handled_reservation = False
if handled_reservation:
return True
if wait_times_ref:
wait_times_ref[0] += 1
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
except Exception:
pass
delay_seconds = float(post_switch_delay_s or 1.0)
try:
analyser.operation.delay(delay_seconds)
except Exception:
time.sleep(delay_seconds)
if swipe_times_ref:
swipe_times_ref[0] += 1
return False
__all__ = [
"handle_stage_after_diagnosis",
"find_and_open_fudai_detail",
"filter_fudai_detail",
"handle_no_fudai_situation",
]
@@ -0,0 +1,25 @@
"""douyin_flow_control_pkg - 流程控制子包。
原 douyin/core/douyin_flow_control.py 拆成 4 个子模块:
- stage_handler handle_stage_after_diagnosis 阶段后状态记录
- find_open find_and_open_fudai_detail 找福袋并打开详情(最大头 520 行)
- filter filter_fudai_detail 配置筛选决策
- no_fudai handle_no_fudai_situation 无福袋时的简单流程
外部 import 路径不变:
``from douyin.core.douyin_flow_control import find_and_open_fudai_detail``
仍可用(原文件改成 re-export shim)。
"""
from .stage_handler import handle_stage_after_diagnosis
from .find_open import find_and_open_fudai_detail
from .filter import filter_fudai_detail
from .no_fudai import handle_no_fudai_situation
__all__ = [
"handle_stage_after_diagnosis",
"find_and_open_fudai_detail",
"filter_fudai_detail",
"handle_no_fudai_situation",
]
@@ -0,0 +1,85 @@
"""douyin_flow_control_pkg.filter - 福袋详情筛选决策。
filter_fudai_detail:调用 should_skip_fudai_by_config 做配置层筛选,
返回是否参与的决策。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def filter_fudai_detail(
analyser: Any,
detail: tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = (
str(detail[0] or "")
if isinstance(detail, tuple) and len(detail) >= 1
else ""
)
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选通过)",
elapsed_seconds=round(elapsed, 2),
)
return False
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选不通过)",
elapsed_seconds=round(elapsed, 2),
reason=reason,
)
return True
@@ -0,0 +1,537 @@
"""douyin_flow_control_pkg.find_open - 主流程:找福袋图标并打开详情页。
find_and_open_fudai_detail:通过像素检测 / 模板匹配找到福袋图标位置,
点击进入详情页,处理打开失败、被弹窗遮挡等异常情况。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def find_and_open_fudai_detail(
analyser: Any,
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
if func_start_time is None:
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情
try:
if getattr(analyser, "_waiting_for_lottery_result", False):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
)
except Exception as e:
logging.debug("日志记录失败: %s", e)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
logging.debug("检查等待开奖状态失败: %s", e)
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
if remaining < 1.0:
break
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
# 再次检查时间,防止第二次调用导致超时
elapsed = time.time() - start_time
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
x = check_have_fudai_with_ready_screenshot(
analyser, screenshot_ready=False
)
if x:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标",
x=int(x or 0),
elapsed_seconds=round(time.time() - start_time, 2),
)
except Exception:
pass
# 结构化统计:检测到福袋(attempt)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_detected",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
break
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
if remaining <= 0:
break
wait_time = min(retry_delay_seconds, remaining)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
elapsed_seconds=round(elapsed, 2),
remaining_seconds=round(remaining, 2),
wait_seconds=round(wait_time, 2),
)
except Exception:
pass
try:
analyser.operation.delay(wait_time)
except Exception:
time.sleep(wait_time)
if not x:
try:
total_elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0),
max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(total_elapsed, 2),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(未找到福袋)",
elapsed_seconds=round(elapsed, 2),
)
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
try:
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
cur += 1
setattr(analyser, "_consecutive_no_fudai_count", cur)
threshold = (
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
)
if threshold is None or threshold <= 0:
# 如果未配置阈值,则尝试读取配置属性(兼容性)
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)
threshold = int(
cfg.get("fudai_exit_after_misses", 30) or 30
)
except Exception:
threshold = 30
# 如果计数达到阈值,执行返回键退出直播间并重置计数
if threshold and cur >= threshold:
try:
analyser._log_kv(
"流程",
"连续未找到福袋达到阈值:按返回键退出直播间",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
enabled = getattr(analyser, "enable_back_on_misses", None)
if enabled is None:
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)
enabled = bool(cfg.get("enable_back_on_misses", True))
else:
enabled = True
except Exception:
enabled = True
if enabled:
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
try:
import time as _time
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
try:
analyser._log_kv(
"流程",
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
)
except Exception:
pass
else:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
try:
# 兜底:使用通用 click 返回坐标
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
analyser.operation.click(
analyser.device_id, back_x, back_y
)
except Exception:
pass
except Exception:
# 在异常情况下保守地尝试按返回键
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
else:
try:
analyser._log_kv(
"流程",
"返回键回退已禁用,跳过按返回键",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 重置计数,避免重复触发
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
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
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 结构化统计:点击尝试
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_click_attempt",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image # type: ignore[import]
from douyin.handlers import douyin_screenshot_manager
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"流程检测到福袋图标后保存完整截图",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
)
except Exception:
pass
try:
analyser.operation.delay(wait_seconds)
except Exception:
time.sleep(wait_seconds)
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(device_id, use_service=False)
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
)
except Exception:
pass
return False
try:
result = douyin_stage.diagnose_stage_from_current_screen(
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
)
except Exception:
pass
try:
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
screenshot_ready_for_ocr=getattr(
analyser, "_screenshot_ready_for_ocr", False
),
)
except Exception:
pass
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 成功打开福袋详情:重置连续未找到计数
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
try:
# 结构化统计:成功打开详情(success)
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return True
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
)
except Exception:
pass
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
try:
back_click_x = int(520 * rx / 1080)
back_click_y = int(505 * ry / 2400)
except Exception:
back_click_x, back_click_y = 520, 505
try:
analyser.operation.click(device_id, back_click_x, back_click_y)
except Exception:
try:
analyser.click(back_click_x, back_click_y)
except Exception:
pass
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
analyser.last_fudai_x = 0
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="fail",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return False
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测异常",
error=str(e),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
try:
analyser.click(x, base_y)
wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
analyser.operation.delay(wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底成功)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
return False
@@ -0,0 +1,94 @@
"""douyin_flow_control_pkg.no_fudai - 无福袋情况的简单流程。
handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待 / 上滑切换。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback: Optional[Callable[[], None]],
swipe_down_back_callback: Callable[[], None],
sort_reservations_callback: Callable[[], None],
clear_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
back_to_list_callback: Callable[[], None],
into_list_callback: Callable[[], None],
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
reservation_after_action_pending_ref: Optional[List[bool]] = None,
reservation_back_swipe_delay_s: Optional[float] = None,
) -> bool:
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
handled_reservation = False
seek_callback = seek_reservation_room_callback or (lambda item: False)
reservation_after_action_pending_ref = (
reservation_after_action_pending_ref
if reservation_after_action_pending_ref
else [False]
)
reservation_back_swipe_delay_s = (
reservation_back_swipe_delay_s
if reservation_back_swipe_delay_s is not None
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
)
try:
from douyin.reservation import douyin_reservation_logic
handled_reservation = (
douyin_reservation_logic.process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
reservation_back_swipe_delay_s,
swipe_down_back_callback,
seek_callback,
sort_reservations_callback,
write_state_callback,
)
)
except Exception:
handled_reservation = False
if handled_reservation:
return True
if wait_times_ref:
wait_times_ref[0] += 1
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
except Exception:
pass
delay_seconds = float(post_switch_delay_s or 1.0)
try:
analyser.operation.delay(delay_seconds)
except Exception:
time.sleep(delay_seconds)
if swipe_times_ref:
swipe_times_ref[0] += 1
return False
@@ -0,0 +1,34 @@
"""douyin_flow_control_pkg.stage_handler - 阶段诊断后的状态记录。
handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转),
为基础抢福袋流程的状态机提供锚点。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
func_start_time: float | None = None,
):
if func_start_time is None:
func_start_time = time.time()
return find_and_open_fudai_detail(
analyser=analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)