Files
douyin_guaji-main/run_cli.py
T
Your Name 26df350755 feat: Implement 30-minute timeout protection and unify path configurations
- Introduced a 30-minute timeout mechanism to prevent the script from getting stuck in invalid states, with configurable timeout settings.
- Unified path configurations across the project to enhance maintainability and avoid hardcoded paths.
- Updated documentation and flowcharts to reflect the new timeout feature and improved path management.
- Fixed issues with template and screenshot path configurations to ensure consistency across the project.
2025-12-28 14:47:31 +08:00

480 lines
18 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 os
import shutil
import sys
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
try:
from douyin.logging import douyin_logging
douyin_logging.configure_logging()
except Exception:
# 日志配置失败不影响主流程,但会缺少文件日志
pass
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
# 当前 WebGUI 目录中没有完整版 douyin_fudai.py,而是在 Cursor 的工作树中存在完整实现。
# 同时,我们在本目录下放置了一些 shim 模块(如 douyin_text_utils、douyin_swipe_ops 等),
# 需要优先加载这些本地实现,再去加载完整逻辑模块。
_BASE_DIR = os.path.dirname(__file__)
# 使用环境变量或默认路径,避免硬编码用户路径
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
"EXTERNAL_DOUYIN_FUDAI_DIR",
os.path.join(
os.path.expanduser("~"),
".cursor",
"worktrees",
"douyin_guaji-main",
"axf"
)
)
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:
# shim 加载失败不影响主流程,后续仍可尝试外部模块
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")
_load_local_shim("douyin_reservation_ops", "douyin/reservation/douyin_reservation_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:
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
pass
# 在导入 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(无限运行)",
)
p.add_argument(
"--test-yanghao-flow",
action="store_true",
help="测试:只执行一次推荐页养号流程并退出",
)
p.add_argument(
"--test-yanghao-flow-seconds",
type=int,
default=10,
help="测试:推荐页养号停留秒数",
)
p.add_argument(
"--test-comment",
action="store_true",
help="测试:按配置坐标执行一次评论输入+键盘确认发送并退出",
)
p.add_argument("--test-comment-text", default="测试评论123", help="测试评论内容")
# 允许从 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="关闭切换次数阈值回退到第一个直播间",
)
# 高价值直播间回访运行时开关(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(
"--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(
"--reservation-preempt-min-value",
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="禁用福袋模板匹配(默认已禁用)",
)
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)
)
print(
"[TEST-COMMENT] device_id={} res={}x{}".format(
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
)
)
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))
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()
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 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 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, "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, "reservation_preempt_min_value", None) is not None:
try:
analyser.reservation_preempt_min_value_yuan = max(
0.0, float(args.reservation_preempt_min_value)
)
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
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 version import print_version_banner
print_version_banner("run_cli")
except Exception:
pass
raise SystemExit(main(sys.argv[1:]))