Files
douyi_guaji_main/bin/run_cli.py
T
CodexandClaude Opus 4.7 71f3653354 补回上次合并丢失的关键路径修复 + .gitignore 补强 + 依赖版本对齐
上次冲突解决时跳过了 982f57e (P0 清理) 和 b6ae970 (路径修复) 两个 commit,
本提交补回其中影响运行时正确性和文档一致性的 7 处。

E. 路径错位修复
  - douyin/core/douyin_fudai.py: _reservations_state_path 与 room_pos_map
    状态目录改为优先调用 path_config.get_reservations_path()
  - douyin/core/path_config.py: get_reservations_path 注释明确"实际位置 + 写入方"
  - gui/components/mapping_utils.py: 删除错误兜底 douyin/state/reservations.json
  - gui/components/mapping_table.py: 同步删除 douyin/state/room_pos_map.json 错误兜底
  - gui/web_gui.py: get_reservations() 内的兜底由 douyin/state/ 修正为 douyin/core/state/
  - bin/run_cli.py: 移除对已删空文件 douyin_reservation_ops.py 的 shim 加载
  - douyin/reservation/douyin_reservation_ops.py: 删除 0 字节空文件

F. .gitignore 补强
  - 新增 *.bak_* 拦截带日期后缀的备份命名(修复 *.bak 命中失败的场景)

G. 依赖版本对齐
  - requirements-minimal.txt: paddleocr/paddlepaddle 改为 >=3.0.0,与 requirements.txt 一致
  - README.md: 安装指引中 paddlepaddle==2.5.2 改为 >=3.0.0

回归:全量 .py compileall 通过;7 项断言(path_config 路径、douyin_fudai 切换、
3 处兜底已清、shim 已移除、空文件已删、.gitignore 补强、版本对齐)全部 PASS;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 10:18:17 +08:00

637 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import argparse
import importlib.util
import logging
import os
import shutil
import sys
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
if os.environ.get("PARAM_TRACK_ALL") == "1":
try:
from douyin.utils.param_usage_tracer import start_tracing
start_tracing()
except Exception as e:
logging.debug("参数追踪启用失败: %s", e)
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
try:
from douyin.logging import douyin_logging
douyin_logging.configure_logging()
except Exception as e:
# 日志配置失败,使用基础配置作为兜底
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - [%(levelname)s] - %(message)s'
)
logging.warning("日志系统配置失败,使用基础配置: %s", e)
# 尝试确保行为日志的异步 listener 在进程启动时就被启动,
# 以避免某些运行环境中模块未完整初始化导致日志未落盘的问题。
try:
# 直接以模块方式导入,避免 package 的 `__init__` 导出遮蔽(`from douyin.logging import action_logger`
# 会失败因为 package 只导出了 `ActionLogger` 等名字)。
import importlib
action_logger_mod = importlib.import_module("douyin.logging.action_logger")
try:
action_logger_mod._start_queue_listener_if_needed()
except Exception as e:
# 启动失败时不影响主流程,action_logger 有回退到同步 file handler 的逻辑
logging.debug("action_logger 启动失败: %s", e)
except Exception as e:
logging.debug("action_logger 模块导入失败: %s", e)
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 确保项目根在 sys.path 中(脚本从 bin/ 目录启动时)
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
def _load_local_shim(mod_name: str, rel_path: str) -> None:
"""从当前工程目录加载本地 shim 模块,并注册到 sys.modules。"""
if mod_name in sys.modules:
return
path = os.path.join(_BASE_DIR, rel_path)
if not os.path.isfile(path):
return
try:
spec = importlib.util.spec_from_file_location(mod_name, path)
if spec is None or spec.loader is None:
return
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[mod_name] = module
except Exception as e:
# shim 加载失败不影响主流程,后续仍可尝试外部模块
logging.debug("shim 模块加载失败 %s: %s", mod_name, e)
return
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
try:
if (
os.path.isdir(_EXTERNAL_DOUYIN_FUDAI_DIR)
and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path
):
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
except Exception as e:
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
logging.debug("外部模块路径配置失败: %s", e)
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
# GLOG_minloglevel: 2 -> ERROR 及以上,屏蔽 INFO/WARNING
# OMP_NUM_THREADS: 设为 1,避免 oneDNN 打印线程信息
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
os.environ.setdefault("GLOG_minloglevel", "2")
os.environ.setdefault("OMP_NUM_THREADS", "1")
from douyin.core.douyin_fudai import fudai_analyse
def ensure_adb_in_path() -> None:
if shutil.which("adb"):
return
localapp = os.environ.get("LOCALAPPDATA") or ""
candidates = []
if localapp:
candidates.append(os.path.join(localapp, "platform-tools"))
userprofile = os.environ.get("USERPROFILE") or ""
if userprofile:
candidates.append(
os.path.join(userprofile, "AppData", "Local", "platform-tools")
)
for d in candidates:
adb_exe = os.path.join(d, "adb.exe")
if os.path.exists(adb_exe):
os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "")
os.environ.setdefault("ADB_EXECUTABLE", adb_exe)
return
def parse_args(argv: list[str]) -> argparse.Namespace:
p = argparse.ArgumentParser(description="Douyin 福袋挂机运行器(供 GUI 调用)")
p.add_argument("--device-id", default="", help="ADB 设备 ID(为空则自动选择)")
p.add_argument("--y-pianyi", type=int, default=0, help="y 轴偏移(通常 -50~50)")
p.add_argument("--needswitch", action="store_true", help="是否允许上划切换直播间")
p.add_argument(
"--wait-minutes",
type=int,
default=0,
help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)",
)
# (已移除) 测试相关的命令行参数(测试养号、测试评论)
# 允许从 GUI 覆盖关键配置(不改动 config.json 也能生效)
p.add_argument(
"--min-prize-value-yuan",
type=float,
default=None,
help="最低奖品价值(元),低于则不参与",
)
p.add_argument(
"--min-participants",
type=int,
default=None,
help="最少参与人数(0/空表示不启用)",
)
p.add_argument(
"--max-participants",
type=int,
default=None,
help="最多参与人数(0/空表示不启用)",
)
p.add_argument(
"--skip-if-countdown-gt-seconds",
type=int,
default=None,
help="倒计时大于该秒数则不参与,高价值福袋可预约(needswitch 生效)",
)
p.add_argument(
"--skip-if-countdown-lt-seconds",
type=int,
default=None,
help="倒计时小于该秒数则不参与,高价值福袋可预约(needswitch 生效)",
)
p.add_argument(
"--reset-after-swipes",
type=int,
default=None,
help="切换直播间达到该次数后,在直播间页面下滑回退到本轮第一个直播间(需配合 --reset-after-swipes-enabled)",
)
p.add_argument(
"--reset-after-swipes-enabled",
action="store_true",
help="开启切换次数阈值回退到第一个直播间",
)
p.add_argument(
"--reset-after-swipes-disabled",
action="store_true",
help="关闭切换次数阈值回退到第一个直播间",
)
p.add_argument(
"--reset-after-swipes-action",
choices=["swipe", "back"],
default=None,
help="回退方式:swipe=滑动回退(默认),back=按返回键回退。",
)
p.add_argument(
"--swipe-down-back-count",
type=int,
default=None,
help="在直播间下滑达到该次数后按返回并重新进入直播间(需配合 --swipe-down-back-enabled)",
)
p.add_argument(
"--swipe-down-back-enabled",
action="store_true",
help="启用下滑达到阈值后按返回并重新进入直播间",
)
p.add_argument(
"--swipe-down-back-disabled",
action="store_true",
help="禁用下滑达到阈值后按返回并重新进入直播间",
)
# 高价值直播间回访运行时开关(GUI 可在启动时传参覆盖)
p.add_argument(
"--high-value-room-revisit-enabled",
action="store_true",
help="启用高价值直播间定时回访",
)
p.add_argument(
"--high-value-room-revisit-disabled",
action="store_true",
help="禁用高价值直播间定时回访",
)
p.add_argument(
"--high-value-room-revisit-only-current-run",
action="store_true",
help="仅回访本次运行记录的高价值直播间",
)
p.add_argument(
"--high-value-room-revisit-min-interval-seconds",
type=int,
default=300,
help="高价值房间重访最小间隔时间(秒,默认300)",
)
p.add_argument(
"--high-value-room-revisit-max-per-run",
type=int,
default=5,
help="每次运行最大重访次数(默认5)",
)
p.add_argument(
"--high-value-room-revisit-min-prize-value",
type=float,
default=0.0,
help="重访最低奖品价值阈值(元,默认0.0)",
)
p.add_argument(
"--high-value-room-revisit-max-age-days",
type=int,
default=30,
help="重访最大年龄天数(默认30)",
)
p.add_argument(
"--reservation-back-verify-enabled",
action="store_true",
help="启用回退后预约校验(默认启用)",
)
p.add_argument(
"--reservation-back-verify-disabled",
action="store_true",
help="禁用回退后预约校验",
)
p.add_argument(
"--reservation-back-swipe-delay",
type=float,
default=None,
help="运行时覆盖:回退后滑动等待(秒),仅在未启用回退校验时生效,可加快回退速度",
)
p.add_argument(
"--fudai-find-max-attempts",
type=int,
default=None,
help="运行时覆盖:找福袋图标最多尝试次数(整数)",
)
# 按需求:删除“自动养号/随机等待/轻微扰动”等参数,仅保留“推荐页养号流程”。
# 推荐页养号的动作/概率/阈值等由 config.json 控制(GUI 会保存)。
p.add_argument(
"--auto-join-fansclub",
action="store_true",
help="自动尝试加入粉丝团(可能消耗钻石)",
)
p.add_argument(
"--fansclub-fail-action",
choices=["stay", "switch"],
default=None,
help="粉丝团门槛无法处理时:stay=停留当前直播间;switch=切换下一个",
)
p.add_argument(
"--enable-ocr-mode1",
action="store_true",
help="启用OCR模式1(二值化模式,默认关闭)",
)
p.add_argument(
"--disable-ocr-mode1", action="store_true", help="禁用OCR模式1(默认已禁用)"
)
p.add_argument(
"--fudai-template-threshold",
type=float,
default=None,
help="福袋模板匹配阈值(0.0-1.0,默认0.7)",
)
p.add_argument(
"--fudai-template-enabled",
action="store_true",
help="启用福袋模板匹配(默认关闭)",
)
p.add_argument(
"--fudai-template-disabled",
action="store_true",
help="禁用福袋模板匹配(默认已禁用)",
)
p.add_argument(
"--enable-back-on-misses",
action="store_true",
help="启用:达到连续未找到福袋阈值时按返回键回退(GUI 优先配置)",
)
p.add_argument(
"--disable-back-on-misses",
action="store_true",
help="禁用:达到连续未找到福袋阈值时按返回键回退",
)
p.add_argument(
"--yanghao-only",
action="store_true",
help="只执行推荐页养号流程(运行完成后退出)",
)
p.add_argument(
"--yanghao-seconds",
type=int,
default=None,
help="仅在 --yanghao-only 时有效:覆盖推荐页养号停留秒数",
)
return p.parse_args(argv)
def main(argv: list[str]) -> int:
ensure_adb_in_path()
args = parse_args(argv)
# 让命令行输出更稳定(实时刷新 + UTF-8)
try:
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) # type: ignore[attr-defined]
except Exception:
pass
try:
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True) # type: ignore[attr-defined]
except Exception:
pass
if bool(getattr(args, "test_yanghao_flow", False)) or bool(
getattr(args, "test_comment", False)
):
os.environ.setdefault("SKIP_OCR_INIT", "1")
os.environ.setdefault("NO_TEE_STDOUT", "1")
os.environ.setdefault("FAST_UI", "1")
os.environ.setdefault("YANGHAO_STEP_SCREENSHOT", "1")
analyser = fudai_analyse()
# 测试模式:直接执行一次“评论输入+键盘确认发送”
if bool(getattr(args, "test_comment", False)):
device_id = (args.device_id or "").strip() or analyser.operation.select_device()
if not device_id:
print("未检测到设备,测试退出")
return 2
analyser.device_id = device_id
analyser.y_pianyi = int(args.y_pianyi or 0)
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
analyser.operation.get_device_resolution(device_id)
)
msg = str(getattr(args, "test_comment_text", "测试评论123") or "测试评论123")
# 逐步截图
analyser._save_step_screenshot("test_comment_start")
def _scaled_click(base_x: int, base_y: int) -> None:
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
analyser.operation.click(device_id, sx, sy)
try:
_scaled_click(
getattr(analyser, "yanghao_comment_btn_x", 540),
getattr(analyser, "yanghao_comment_btn_y", 2000),
)
analyser.operation.delay(1)
analyser._save_step_screenshot("test_comment_after_open")
_scaled_click(
getattr(analyser, "yanghao_comment_input_x", 540),
getattr(analyser, "yanghao_comment_input_y", 1900),
)
analyser.operation.delay(1)
analyser._save_step_screenshot("test_comment_after_focus")
ix, iy = analyser._scale_from_base(
int(getattr(analyser, "yanghao_comment_input_x", 540)),
int(getattr(analyser, "yanghao_comment_input_y", 1900)),
)
ok_input = bool(
analyser.operation.paste_text_at(
device_id, ix, iy, msg, ensure_focus=False
)
)
print("[TEST-COMMENT] input {}".format("OK" if ok_input else "FAIL"))
analyser.operation.delay(1)
analyser._save_step_screenshot("test_comment_after_input")
ok_send = bool(analyser.operation.confirm_from_keyboard(device_id))
print("[TEST-COMMENT] send {}".format("OK" if ok_send else "FAIL"))
analyser.operation.delay(1)
analyser._save_step_screenshot("test_comment_after_send")
_scaled_click(
getattr(analyser, "yanghao_comment_close_x", 900),
getattr(analyser, "yanghao_comment_close_y", 300),
)
analyser.operation.delay(1)
analyser._save_step_screenshot("test_comment_after_close")
except Exception as e:
print("[TEST-COMMENT] failed: {}".format(e))
return 3
print("[TEST-COMMENT] done")
return 0
# 测试模式:直接跑一次“推荐页养号流程”用于验证是否能点到关键按钮
if bool(getattr(args, "test_yanghao_flow", False)):
device_id = (args.device_id or "").strip() or analyser.operation.select_device()
if not device_id:
print("未检测到设备,测试退出")
return 2
analyser.device_id = device_id
analyser.y_pianyi = int(args.y_pianyi or 0)
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
analyser.operation.get_device_resolution(device_id)
)
setattr(analyser, "yanghao_use_recommend_flow", True)
# 加载配置(包括养号相关配置)
analyser.load_config()
# CLI 覆盖:启用/禁用 达到连续未找到福袋阈值时按返回键回退
try:
if getattr(args, "enable_back_on_misses", False):
setattr(analyser, "enable_back_on_misses", True)
elif getattr(args, "disable_back_on_misses", False):
setattr(analyser, "enable_back_on_misses", False)
except Exception:
pass
print(
"[TEST] device_id={} res={}x{}".format(
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
)
)
seconds = int(getattr(args, "test_yanghao_flow_seconds", 10) or 10)
if seconds < 1:
seconds = 1
getattr(analyser, "_yanghao_recommend_flow", lambda _: None)(seconds) # type: ignore[attr-defined]
print("[TEST] done")
return 0
# 命令行:只运行推荐页养号并退出(用于纯养号场景)
if getattr(args, "yanghao_only", False):
device_id = (args.device_id or "").strip() or analyser.operation.select_device()
if not device_id:
print("未检测到设备,退出。")
return 2
analyser.device_id = device_id
analyser.y_pianyi = int(args.y_pianyi or 0)
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
analyser.operation.get_device_resolution(device_id)
)
# 重新加载配置以确保养号配置生效
analyser.load_config()
print(
"[YANGHAO-ONLY] device_id={} res={}x{}".format(
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
)
)
seconds = (
int(args.yanghao_seconds)
if getattr(args, "yanghao_seconds", None)
else analyser._yanghao_get_recommend_seconds()
)
if seconds < 1:
seconds = 1
getattr(analyser, "_yanghao_recommend_flow", lambda _: None)(seconds) # type: ignore[attr-defined]
print("[YANGHAO-ONLY] done")
return 0
if args.min_prize_value_yuan is not None:
analyser.min_prize_value_yuan = float(args.min_prize_value_yuan)
if args.min_participants is not None:
analyser.min_participants = int(args.min_participants or 0)
if args.max_participants is not None:
analyser.max_participants = int(args.max_participants or 0)
if args.skip_if_countdown_gt_seconds is not None:
analyser.skip_if_countdown_gt_seconds = int(
args.skip_if_countdown_gt_seconds or 900
)
if (
hasattr(args, "skip_if_countdown_lt_seconds")
and args.skip_if_countdown_lt_seconds is not None
):
setattr(
analyser,
"skip_if_countdown_lt_seconds",
int(args.skip_if_countdown_lt_seconds or 10),
)
if args.reset_after_swipes is not None:
analyser.reset_after_swipes = max(1, int(args.reset_after_swipes or 0))
analyser.reset_after_swipes_enabled = True
if args.reset_after_swipes_enabled:
analyser.reset_after_swipes_enabled = True
if args.reset_after_swipes_disabled:
analyser.reset_after_swipes_enabled = False
if getattr(args, "reset_after_swipes_action", None) is not None:
try:
analyser.reset_after_swipes_action = str(
args.reset_after_swipes_action or "swipe"
)
except Exception:
pass
# 下滑后返回并重新进入直播间的命令行覆盖(优先级高于 config.json)
if getattr(args, "swipe_down_back_count", None) is not None:
try:
analyser.swipe_down_back_count = max(1, int(args.swipe_down_back_count))
analyser.swipe_down_back_enabled = True
except Exception:
pass
if getattr(args, "swipe_down_back_enabled", False):
analyser.swipe_down_back_enabled = True
if getattr(args, "swipe_down_back_disabled", False):
analyser.swipe_down_back_enabled = False
if args.auto_join_fansclub:
setattr(analyser, "auto_join_fansclub", True)
if args.fansclub_fail_action is not None:
setattr(analyser, "fansclub_fail_action", args.fansclub_fail_action)
# 高价值直播间回访开关(优先级:命令行 > config)
if getattr(args, "high_value_room_revisit_enabled", False):
analyser.high_value_room_revisit_enabled = True
if getattr(args, "high_value_room_revisit_disabled", False):
analyser.high_value_room_revisit_enabled = False
if getattr(args, "high_value_room_revisit_only_current_run", False):
analyser.high_value_room_revisit_only_current_run = True
if getattr(args, "high_value_room_revisit_min_interval_seconds", None) is not None:
analyser.high_value_room_revisit_min_interval_seconds = (
args.high_value_room_revisit_min_interval_seconds
)
if getattr(args, "high_value_room_revisit_max_per_run", None) is not None:
analyser.high_value_room_revisit_max_per_run = (
args.high_value_room_revisit_max_per_run
)
if getattr(args, "high_value_room_revisit_min_prize_value", None) is not None:
analyser.high_value_room_revisit_min_prize_value = (
args.high_value_room_revisit_min_prize_value
)
if getattr(args, "high_value_room_revisit_max_age_days", None) is not None:
analyser.high_value_room_revisit_max_age_days = (
args.high_value_room_revisit_max_age_days
)
# 预约回退校验开关(命令行优先)
if getattr(args, "reservation_back_verify_enabled", False):
analyser.reservation_back_verify_enabled = True
if getattr(args, "reservation_back_verify_disabled", False):
analyser.reservation_back_verify_enabled = False
# 运行时覆盖:回退后滑动等待(快速值,仅在未启用回退校验时使用)
if getattr(args, "reservation_back_swipe_delay", None) is not None:
try:
setattr(
analyser,
"reservation_back_swipe_delay_fast_seconds",
float(args.reservation_back_swipe_delay),
)
except Exception:
pass
# 运行时覆盖:找福袋最大尝试次数
if getattr(args, "fudai_find_max_attempts", None) is not None:
try:
analyser.fudai_find_max_attempts = max(1, int(args.fudai_find_max_attempts))
except Exception:
pass
# OCR模式1开关(命令行优先)
if getattr(args, "enable_ocr_mode1", False):
setattr(analyser, "enable_ocr_mode1", True)
if getattr(args, "disable_ocr_mode1", False):
setattr(analyser, "enable_ocr_mode1", False)
# 福袋模板匹配开关(命令行优先)
if getattr(args, "fudai_template_enabled", False):
setattr(analyser, "fudai_template_match_enabled", True)
if getattr(args, "fudai_template_disabled", False):
setattr(analyser, "fudai_template_match_enabled", False)
# 福袋模板匹配阈值(命令行优先)
if getattr(args, "fudai_template_threshold", None) is not None:
try:
threshold = float(args.fudai_template_threshold)
if 0.0 <= threshold <= 1.0:
analyser.fudai_template_match_threshold = threshold
except Exception:
pass
# CLI 覆盖:启用/禁用 达到连续未找到福袋阈值时按返回键回退
if getattr(args, "enable_back_on_misses", False):
try:
analyser.enable_back_on_misses = True
except Exception:
pass
if getattr(args, "disable_back_on_misses", False):
try:
analyser.enable_back_on_misses = False
except Exception:
pass
device_id = args.device_id.strip() if args.device_id else ""
if not device_id:
device_id = analyser.operation.select_device()
if not device_id:
print("未检测到设备,退出。")
return 2
analyser.fudai_choujiang(
device_id=device_id,
y_pianyi=args.y_pianyi,
needswitch=bool(args.needswitch),
wait_minutes=int(args.wait_minutes),
)
return 0
if __name__ == "__main__":
try:
from douyin.core.version import print_version_banner
print_version_banner("run_cli")
except Exception:
pass
raise SystemExit(main(sys.argv[1:]))