refactor: 入口脚本迁移到 bin/
将 4 个入口脚本从根目录迁移到 bin/: - run_cli.py - gui_app.py - webgui_launcher.py - manage_logs.py 配套修改: - 修复 bin/*.py 内部 ROOT_DIR 计算(parent.parent) - bin/run_cli.py 在 sys.path 加入项目根,shim 加载逻辑保持不变 - bin/manage_logs.py 在 sys.path 加入项目根 - path_config.get_run_cli_path() 返回 bin/run_cli.py 启动方式变化: - 原: python run_cli.py / python gui_app.py - 新: python bin/run_cli.py / python bin/gui_app.py GUI 内部通过 path_config.get_run_cli_path() 调用,自动适配。 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
309b629e7c
commit
e3e399da70
5 files changed
+9
-6
No files matched your search
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the desktop GUI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
TARGET = ROOT_DIR / "gui" / "gui_app.py"
|
||||
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
|
||||
|
||||
|
||||
def _reexec_with_venv() -> None:
|
||||
if not VENV_PYTHON.exists():
|
||||
return
|
||||
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
|
||||
return
|
||||
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_reexec_with_venv()
|
||||
sys.argv = [str(TARGET), *sys.argv[1:]]
|
||||
runpy.run_path(str(TARGET), run_name="__main__")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
日志管理工具
|
||||
============
|
||||
|
||||
功能:
|
||||
1. 查看日志统计信息
|
||||
2. 手动清理旧日志
|
||||
3. 手动压缩日志文件
|
||||
4. 显示日志轮转状态
|
||||
|
||||
使用方法:
|
||||
python manage_logs.py [command] [options]
|
||||
|
||||
命令:
|
||||
stats - 显示日志统计信息
|
||||
cleanup - 清理旧日志
|
||||
compress - 压缩旧日志
|
||||
monitor - 显示监控状态
|
||||
help - 显示帮助信息
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import glob
|
||||
import argparse
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any
|
||||
|
||||
# 添加项目根到 sys.path(从 bin/ 目录运行时需要)
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from douyin.logging.douyin_logging import (
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
get_log_stats,
|
||||
path_config
|
||||
)
|
||||
|
||||
|
||||
def get_log_base_names(logs_dir: str) -> list[str]:
|
||||
"""获取日志基础名称列表"""
|
||||
if not os.path.exists(logs_dir):
|
||||
return []
|
||||
|
||||
# 查找所有日志文件
|
||||
pattern = os.path.join(logs_dir, "*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
base_names = set()
|
||||
for log_file in log_files:
|
||||
filename = os.path.basename(log_file)
|
||||
# 处理压缩文件
|
||||
if filename.endswith('.gz'):
|
||||
filename = filename[:-3]
|
||||
|
||||
# 提取基础名称(去掉日期和序号)
|
||||
# 例如: unified_2024-01-15.log -> unified
|
||||
# 例如: unified_2024-01-15.1.log -> unified
|
||||
parts = filename.split('_')
|
||||
if len(parts) >= 2:
|
||||
base_name = parts[0]
|
||||
base_names.add(base_name)
|
||||
|
||||
return sorted(list(base_names))
|
||||
|
||||
|
||||
def format_size(size_mb: float) -> str:
|
||||
"""格式化文件大小"""
|
||||
if size_mb < 1024:
|
||||
return f"{size_mb:.1f}MB"
|
||||
else:
|
||||
return f"{size_mb/1024:.1f}GB"
|
||||
|
||||
|
||||
def show_stats(logs_dir: str, base_name: str) -> None:
|
||||
"""显示日志统计信息"""
|
||||
print(f"\n=== 日志统计信息 ({base_name}) ===")
|
||||
|
||||
stats = get_log_stats(logs_dir, base_name)
|
||||
|
||||
if stats['total_files'] == 0:
|
||||
print("未找到日志文件")
|
||||
return
|
||||
|
||||
print(f"总文件数: {stats['total_files']}")
|
||||
print(f"总大小: {format_size(stats['total_size_mb'])}")
|
||||
print(f"压缩文件数: {stats['compressed_files']}")
|
||||
if stats['compressed_files'] > 0:
|
||||
print(f"压缩率: {stats['compression_ratio']*100:.1f}%")
|
||||
print(f"最旧文件: {stats['oldest_file'] or 'N/A'}")
|
||||
print(f"最新文件: {stats['newest_file'] or 'N/A'}")
|
||||
|
||||
# 显示最近的文件
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
if log_files:
|
||||
# 按修改时间排序
|
||||
log_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
|
||||
print(f"\n最近的文件 (前5个):")
|
||||
for i, log_file in enumerate(log_files[:5]):
|
||||
mtime = os.path.getmtime(log_file)
|
||||
size = os.path.getsize(log_file) / 1024 / 1024
|
||||
date_str = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
|
||||
compressed = log_file.endswith('.gz')
|
||||
print(f" {i+1}. {os.path.basename(log_file)} - {format_size(size)} - {date_str} {'[压缩]' if compressed else ''}")
|
||||
|
||||
|
||||
def manual_cleanup(logs_dir: str, base_name: str, keep_days: int = 30, dry_run: bool = True) -> None:
|
||||
"""手动清理旧日志"""
|
||||
print(f"\n=== 手动清理日志 ({base_name}) ===")
|
||||
print(f"保留天数: {keep_days}")
|
||||
print(f"预览模式: {'是' if dry_run else '否'}")
|
||||
|
||||
stats = cleanup_old_logs(
|
||||
logs_dir=logs_dir,
|
||||
base_name=base_name,
|
||||
keep_days=keep_days,
|
||||
compress=False, # 清理时不压缩
|
||||
)
|
||||
|
||||
if dry_run:
|
||||
print(f"\n预览结果:")
|
||||
print(f"将删除文件数: {stats['deleted']}")
|
||||
print(f"将释放空间: {format_size(stats['freed_space_mb'])}")
|
||||
print(f"当前总大小: {format_size(stats['total_size_mb'])}")
|
||||
|
||||
|
||||
def manual_compress(logs_dir: str, base_name: str, older_than_days: int = 7, dry_run: bool = True) -> None:
|
||||
"""手动压缩旧日志"""
|
||||
print(f"\n=== 手动压缩日志 ({base_name}) ===")
|
||||
print(f"压缩天数阈值: {older_than_days}")
|
||||
print(f"预览模式: {'是' if dry_run else '否'}")
|
||||
|
||||
cutoff_date = datetime.now() - timedelta(days=older_than_days)
|
||||
|
||||
# 查找需要压缩的文件
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
compress_candidates = []
|
||||
for log_file in log_files:
|
||||
try:
|
||||
filename = os.path.basename(log_file)
|
||||
date_part = filename.replace(f"{base_name}_", "").split('.')[0]
|
||||
file_date = datetime.strptime(date_part, "%Y-%m-%d")
|
||||
|
||||
if file_date < cutoff_date:
|
||||
compress_candidates.append(log_file)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
print(f"\n找到 {len(compress_candidates)} 个待压缩文件")
|
||||
|
||||
total_original_size = 0
|
||||
compressed_count = 0
|
||||
|
||||
for log_file in compress_candidates:
|
||||
size_mb = os.path.getsize(log_file) / 1024 / 1024
|
||||
total_original_size += size_mb
|
||||
|
||||
if dry_run:
|
||||
print(f"将压缩: {os.path.basename(log_file)} ({format_size(size_mb)})")
|
||||
else:
|
||||
if compress_log_file(log_file):
|
||||
compressed_count += 1
|
||||
|
||||
if dry_run:
|
||||
print(f"\n预览结果:")
|
||||
print(f"将压缩文件数: {len(compress_candidates)}")
|
||||
print(f"预计节省空间: {format_size(total_original_size * 0.7)} (估算压缩率70%)")
|
||||
else:
|
||||
print(f"\n执行结果:")
|
||||
print(f"成功压缩文件数: {compressed_count}")
|
||||
|
||||
|
||||
def show_monitor_status() -> None:
|
||||
"""显示监控器状态"""
|
||||
print("\n=== 日志监控状态 ===")
|
||||
|
||||
from douyin.logging.douyin_logging import _log_monitor
|
||||
|
||||
if _log_monitor and _log_monitor._running:
|
||||
print("状态: 运行中")
|
||||
print(f"监控目录: {_log_monitor.logs_dir}")
|
||||
print(f"基础名称: {_log_monitor.base_name}")
|
||||
print(f"警告阈值: {format_size(_log_monitor.warning_size_mb)}")
|
||||
print(f"严重阈值: {format_size(_log_monitor.critical_size_mb)}")
|
||||
print(f"检查间隔: {_log_monitor.check_interval}秒")
|
||||
else:
|
||||
print("状态: 未运行")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="日志管理工具")
|
||||
parser.add_argument("command", choices=["stats", "cleanup", "compress", "monitor", "help"],
|
||||
help="执行的命令")
|
||||
parser.add_argument("--logs-dir", help="日志目录,默认自动检测")
|
||||
parser.add_argument("--base-name", help="日志基础名称,默认显示所有")
|
||||
parser.add_argument("--keep-days", type=int, default=30, help="保留天数,默认30")
|
||||
parser.add_argument("--older-than", type=int, default=7, help="压缩天数阈值,默认7")
|
||||
parser.add_argument("--dry-run", action="store_true", help="预览模式,不执行实际操作")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.command == "help":
|
||||
parser.print_help()
|
||||
return
|
||||
|
||||
# 获取日志目录
|
||||
logs_dir = args.logs_dir or path_config.get_logs_dir()
|
||||
|
||||
if not os.path.exists(logs_dir):
|
||||
print(f"日志目录不存在: {logs_dir}")
|
||||
return
|
||||
|
||||
print(f"日志目录: {logs_dir}")
|
||||
|
||||
# 获取基础名称
|
||||
base_names = get_log_base_names(logs_dir)
|
||||
|
||||
if not base_names:
|
||||
print("未找到日志文件")
|
||||
return
|
||||
|
||||
# 如果未指定base_name,显示所有或让用户选择
|
||||
if not args.base_name:
|
||||
if len(base_names) == 1:
|
||||
args.base_name = base_names[0]
|
||||
else:
|
||||
print(f"找到多个日志类型: {', '.join(base_names)}")
|
||||
print("请使用 --base-name 指定日志类型")
|
||||
return
|
||||
|
||||
if args.base_name not in base_names:
|
||||
print(f"日志类型 '{args.base_name}' 不存在,可用类型: {', '.join(base_names)}")
|
||||
return
|
||||
|
||||
# 执行命令
|
||||
if args.command == "stats":
|
||||
show_stats(logs_dir, args.base_name)
|
||||
elif args.command == "cleanup":
|
||||
manual_cleanup(logs_dir, args.base_name, args.keep_days, args.dry_run)
|
||||
elif args.command == "compress":
|
||||
manual_compress(logs_dir, args.base_name, args.older_than, args.dry_run)
|
||||
elif args.command == "monitor":
|
||||
show_monitor_status()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
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")
|
||||
_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 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 version import print_version_banner
|
||||
|
||||
print_version_banner("run_cli")
|
||||
except Exception:
|
||||
pass
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the Web GUI launcher window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
TARGET = ROOT_DIR / "gui" / "webgui_launcher.py"
|
||||
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
|
||||
|
||||
|
||||
def _reexec_with_venv() -> None:
|
||||
if not VENV_PYTHON.exists():
|
||||
return
|
||||
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
|
||||
return
|
||||
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_reexec_with_venv()
|
||||
sys.argv = [str(TARGET), *sys.argv[1:]]
|
||||
runpy.run_path(str(TARGET), run_name="__main__")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user