- Removed excessive blank lines from various markdown and Python files to enhance readability and maintainability. - Ensured consistent formatting across documentation and code files, improving overall project clarity.
2882 lines
118 KiB
Python
2882 lines
118 KiB
Python
import json
|
||
import os
|
||
import queue
|
||
import re
|
||
import sys
|
||
import threading
|
||
import warnings
|
||
from datetime import datetime
|
||
from typing import Any, Callable
|
||
|
||
from PIL import Image, ImageTk
|
||
|
||
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
|
||
from gui_core import (
|
||
RunParams,
|
||
Runner,
|
||
find_adb_executable,
|
||
list_adb_devices,
|
||
read_config,
|
||
write_config,
|
||
)
|
||
from path_config import get_logs_dir
|
||
|
||
# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)
|
||
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
|
||
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
|
||
|
||
|
||
def main():
|
||
# ttkbootstrap 优先(更美观);没装则回退到原生 tkinter
|
||
try:
|
||
import ttkbootstrap as tb
|
||
from ttkbootstrap.scrolled import ScrolledText
|
||
|
||
import tkinter as tk
|
||
from tkinter import ttk
|
||
from ttkbootstrap.constants import LEFT, RIGHT, BOTH, X, Y
|
||
|
||
root = tb.Window(themename="darkly")
|
||
except Exception:
|
||
import tkinter as tk
|
||
from tkinter import ttk
|
||
from tkinter.constants import LEFT, RIGHT, BOTH, X, Y # type: ignore[assignment]
|
||
from tkinter.scrolledtext import ScrolledText
|
||
|
||
root = tk.Tk()
|
||
|
||
root.title("抖音福袋挂机 - 可视化控制台")
|
||
root.geometry("1400x900") # 增大窗口尺寸,提供更多空间
|
||
|
||
q: queue.Queue[str] = queue.Queue()
|
||
|
||
# ========== 线程安全的日志文件写入器 ==========
|
||
class ThreadSafeLogWriter:
|
||
"""线程安全的日志文件写入器,确保日志能稳定写入文件"""
|
||
|
||
def __init__(self, log_dir: str | None = None):
|
||
self._lock = threading.Lock()
|
||
self._log_dir = log_dir or get_logs_dir()
|
||
self._log_file_path: str = ""
|
||
self._log_file_enabled: bool = True
|
||
self._init_log_file()
|
||
self._write_error_warned = False
|
||
|
||
def _init_log_file(self) -> None:
|
||
"""初始化日志文件路径(按日期)"""
|
||
try:
|
||
# 确保日志目录存在
|
||
os.makedirs(self._log_dir, exist_ok=True)
|
||
|
||
# 读取配置,检查是否启用日志文件
|
||
cfg = read_config()
|
||
self._log_file_enabled = bool(cfg.get("log_unified_enabled", True))
|
||
|
||
# 获取日志文件路径配置
|
||
log_path = cfg.get("log_unified_path") or "logs/unified.log"
|
||
if not os.path.isabs(log_path):
|
||
from path_config import PROJECT_ROOT
|
||
|
||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||
|
||
# 如果配置了按日期分割,使用日期后缀
|
||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||
if use_dated_logs:
|
||
# 提取基础文件名(移除扩展名)
|
||
base_name = os.path.splitext(log_path)[0]
|
||
today = datetime.now().strftime("%Y-%m-%d")
|
||
self._log_file_path = f"{base_name}_{today}.log"
|
||
else:
|
||
self._log_file_path = log_path
|
||
except Exception as e:
|
||
# 如果配置读取失败,使用默认路径
|
||
today = datetime.now().strftime("%Y-%m-%d")
|
||
self._log_file_path = os.path.join(
|
||
self._log_dir, f"unified_{today}.log"
|
||
)
|
||
if not self._write_error_warned:
|
||
print(f"[GUI日志] 配置读取失败,使用默认路径: {e}", file=sys.stderr)
|
||
|
||
def write(self, line: str) -> None:
|
||
"""线程安全地写入日志行到文件"""
|
||
if not self._log_file_enabled:
|
||
return
|
||
|
||
if not line or not line.strip():
|
||
return
|
||
|
||
with self._lock:
|
||
try:
|
||
# 检查日期是否变化(如果使用日期日志)
|
||
cfg = read_config()
|
||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||
if use_dated_logs:
|
||
today = datetime.now().strftime("%Y-%m-%d")
|
||
current_base = os.path.splitext(self._log_file_path)[0]
|
||
if not current_base.endswith(today):
|
||
# 日期变化,更新文件路径
|
||
base_name = (
|
||
current_base.rsplit("_", 1)[0]
|
||
if "_" in os.path.basename(current_base)
|
||
else current_base
|
||
)
|
||
self._log_file_path = f"{base_name}_{today}.log"
|
||
|
||
# 确保目录存在
|
||
log_dir = os.path.dirname(self._log_file_path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
|
||
# 写入文件(追加模式,UTF-8编码,带BOM避免Windows乱码)
|
||
with open(
|
||
self._log_file_path, "a", encoding="utf-8-sig", errors="replace"
|
||
) as f:
|
||
# 如果行已经包含时间戳(格式:YYYY-MM-DD HH:MM:SS),直接写入
|
||
# 否则添加时间戳
|
||
if line.strip() and not (line[0].isdigit() and " - [" in line):
|
||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[
|
||
:-3
|
||
]
|
||
formatted_line = f"{timestamp} - [GUI] - {line}\n"
|
||
else:
|
||
formatted_line = f"{line}\n"
|
||
|
||
f.write(formatted_line)
|
||
f.flush() # 立即刷新缓冲区,确保日志及时写入磁盘
|
||
|
||
except PermissionError as e:
|
||
if not self._write_error_warned:
|
||
print(
|
||
f"[GUI日志] 权限错误,无法写入日志文件: {self._log_file_path}",
|
||
file=sys.stderr,
|
||
)
|
||
print(f"[GUI日志] 错误详情: {e}", file=sys.stderr)
|
||
self._write_error_warned = True
|
||
except Exception as e:
|
||
if not self._write_error_warned:
|
||
print(
|
||
f"[GUI日志] 写入日志文件失败: {self._log_file_path}",
|
||
file=sys.stderr,
|
||
)
|
||
print(f"[GUI日志] 错误详情: {e}", file=sys.stderr)
|
||
self._write_error_warned = True
|
||
|
||
# 创建日志写入器实例
|
||
log_writer = ThreadSafeLogWriter()
|
||
|
||
def _format_gui_log_line(line: str) -> str:
|
||
"""
|
||
将“完整日志行”转换为 GUI 显示用的精简版本。
|
||
|
||
需求:
|
||
- 文件中:仍然写入完整统一日志(含时间戳 / 级别 / 模块等信息);
|
||
- GUI 中:保留【时间戳 + 业务日志】;
|
||
- 如果该行包含识别/匹配的分数(如 `匹配度=0.87` / `相似度=0.95` / `score=0.83`),
|
||
需要在 GUI 文本中一并保留/补充出来。
|
||
|
||
精简规则(兼容统一日志格式):
|
||
- 统一日志通常形如:
|
||
YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - [线程] - [模块:函数:行号] - [traceId:xxx] - 业务内容
|
||
- GUI 只展示:
|
||
YYYY-MM-DD HH:MM:SS.xxx 业务内容(末尾可追加“(匹配度=..., 相似度=..., score=...)”)
|
||
- 其他不符合该模式的行保持原样。
|
||
"""
|
||
s = (line or "").rstrip("\n")
|
||
if not s:
|
||
return s
|
||
|
||
ts_part: str | None = None
|
||
msg_part: str | None = None
|
||
|
||
# 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...
|
||
m = re.match(r"^\[(\d{4}-\d{2}-\d{2} [0-9:.]+)\]\s+\[[A-Z]+\]\s+(.*)$", s)
|
||
if m:
|
||
ts_part = m.group(1).strip()
|
||
msg_part = m.group(2).strip()
|
||
# 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容
|
||
elif s[0].isdigit() and " - " in s:
|
||
parts = s.split(" - ")
|
||
if len(parts) >= 3:
|
||
ts_part = parts[0].strip()
|
||
msg_part = parts[-1].strip()
|
||
|
||
# 如果没解析出“时间戳 + 业务文案”,原样返回
|
||
if not ts_part or msg_part is None:
|
||
return s
|
||
|
||
# 从业务文案中拆分出 字段_xxx=yyy,非 score 类字段在 GUI 中隐藏
|
||
keep_tokens: list[str] = []
|
||
|
||
def _is_score_field(k: str) -> bool:
|
||
kl = k.lower()
|
||
return (
|
||
"score" in kl
|
||
or "match" in kl
|
||
or "匹配" in k
|
||
or "相似" in k
|
||
)
|
||
|
||
for m2 in re.finditer(r"字段_([^\s=]+)=([^\s]+)", msg_part):
|
||
key = m2.group(1)
|
||
val = m2.group(2)
|
||
if _is_score_field(key):
|
||
keep_tokens.append(f"{key}={val}")
|
||
|
||
# 先把所有 字段_xxx=yyy 从业务文案中移除
|
||
clean_msg = re.sub(r"\s*字段_[^\s=]+=[^\s]+", "", msg_part).strip()
|
||
|
||
# 追加需要展示的分数字段
|
||
if keep_tokens:
|
||
clean_msg = f"{clean_msg} ({', '.join(keep_tokens)})"
|
||
|
||
return f"{ts_part} {clean_msg}"
|
||
|
||
# 不符合“完整格式”的行,原样返回
|
||
return s
|
||
|
||
def on_line(line: str):
|
||
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
|
||
# GUI 显示:使用精简后的版本
|
||
try:
|
||
display_line = _format_gui_log_line(line)
|
||
except Exception:
|
||
display_line = line
|
||
q.put(display_line)
|
||
|
||
# 文件:写入完整日志行(不做精简处理)
|
||
try:
|
||
log_writer.write(line)
|
||
except Exception:
|
||
pass # 文件写入失败不应影响GUI显示
|
||
|
||
runner = Runner(on_line=on_line)
|
||
|
||
# 顶部:设备选择 + Y偏移(其余运行参数放到左侧分组,避免重复)
|
||
top = ttk.Frame(root)
|
||
top.pack(fill=X, padx=12, pady=10)
|
||
|
||
adb_exe = find_adb_executable()
|
||
devices = list_adb_devices(adb_exe)
|
||
device_var = tk.StringVar(value=(devices[0] if devices else ""))
|
||
|
||
ttk.Label(top, text="设备:").pack(side=LEFT)
|
||
device_combo = ttk.Combobox(top, textvariable=device_var, values=devices, width=28)
|
||
device_combo.pack(side=LEFT, padx=(0, 10))
|
||
|
||
def refresh_devices():
|
||
nonlocal adb_exe
|
||
adb_exe = find_adb_executable()
|
||
devs = list_adb_devices(adb_exe)
|
||
device_combo["values"] = devs
|
||
if devs and not device_var.get():
|
||
device_var.set(devs[0])
|
||
if not adb_exe:
|
||
on_line("[设备] 未找到 adb.exe(请确认已安装 platform-tools)")
|
||
elif not devs:
|
||
on_line("[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)")
|
||
|
||
ttk.Button(top, text="刷新设备", command=refresh_devices).pack(
|
||
side=LEFT, padx=(0, 20)
|
||
)
|
||
|
||
# 配置区(提前读取配置,供后续使用)
|
||
cfg = read_config()
|
||
|
||
y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0))
|
||
ttk.Label(top, text="Y偏移:").pack(side=LEFT)
|
||
ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(
|
||
side=LEFT, padx=(0, 12)
|
||
)
|
||
|
||
# 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度)
|
||
mid = ttk.PanedWindow(root, orient="horizontal")
|
||
mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))
|
||
|
||
left_wrap = ttk.Frame(mid)
|
||
right = ttk.Frame(mid)
|
||
mid.add(left_wrap, weight=0) # 左侧配置区域
|
||
mid.add(right, weight=1) # 右侧日志/预览区域
|
||
|
||
# 左侧使用Notebook标签页组织配置
|
||
left_notebook = ttk.Notebook(left_wrap)
|
||
left_notebook.pack(fill=BOTH, expand=True)
|
||
needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True)))
|
||
infinite_loop_var = tk.BooleanVar(
|
||
value=bool(cfg.get("infinite_loop_enabled", False))
|
||
)
|
||
wait_minutes_var = tk.IntVar(value=int(cfg.get("wait_minutes", 5) or 5))
|
||
|
||
min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||
min_participants_var = tk.IntVar(value=int(cfg.get("min_participants", 0) or 0))
|
||
max_participants_var = tk.IntVar(value=int(cfg.get("max_participants", 0) or 0))
|
||
skip_gt_seconds_var = tk.IntVar(
|
||
value=int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||
)
|
||
reset_after_swipes_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("reset_after_swipes_enabled", False))
|
||
)
|
||
reset_after_swipes_var = tk.IntVar(
|
||
value=int(cfg.get("reset_after_swipes", 10) or 10)
|
||
)
|
||
# 按需求:删除"自动养号/随机等待/轻微扰动/定时休息"等设置,仅保留"推荐页养号(爱心/收藏/评论)"配置。
|
||
auto_join_var = tk.BooleanVar(value=bool(cfg.get("auto_join_fansclub", False)))
|
||
fansclub_action_var = tk.StringVar(
|
||
value=str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||
)
|
||
|
||
# Web端新增配置变量 - 高价值预约相关
|
||
high_value_fudai_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("high_value_fudai_enabled", False))
|
||
)
|
||
high_value_fudai_threshold_yuan_var = tk.DoubleVar(
|
||
value=float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||
)
|
||
high_value_fudai_join_ahead_seconds_var = tk.IntVar(
|
||
value=int(cfg.get("high_value_fudai_join_ahead_seconds", 120) or 120)
|
||
)
|
||
high_value_fudai_max_swipe_back_var = tk.IntVar(
|
||
value=int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||
)
|
||
high_value_fudai_max_reservations_var = tk.IntVar(
|
||
value=int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||
)
|
||
high_value_fudai_after_action_var = tk.StringVar(
|
||
value=str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||
)
|
||
high_value_room_revisit_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("high_value_room_revisit_enabled", True))
|
||
)
|
||
high_value_room_revisit_only_current_run_var = tk.BooleanVar(
|
||
value=bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||
)
|
||
reservation_back_verify_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("reservation_back_verify_enabled", True))
|
||
)
|
||
reservation_back_swipe_delay_var = tk.DoubleVar(
|
||
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||
)
|
||
reservation_preempt_min_value_var = tk.DoubleVar(
|
||
value=float(cfg.get("reservation_preempt_min_value", 0) or 0)
|
||
)
|
||
fudai_find_max_attempts_var = tk.IntVar(
|
||
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
|
||
)
|
||
fudai_icon_retry_delay_seconds_var = tk.DoubleVar(
|
||
value=float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||
)
|
||
fudai_icon_max_wait_seconds_var = tk.DoubleVar(
|
||
value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||
)
|
||
fudai_click_wait_seconds_var = tk.DoubleVar(
|
||
value=float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0)
|
||
)
|
||
switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(
|
||
value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||
)
|
||
live_room_match_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||
)
|
||
|
||
# 推荐页养号:爱心/收藏/评论(基于图标模板匹配 + 坐标点击)
|
||
yg_enabled_var = tk.BooleanVar(value=bool(cfg.get("yanghao_enabled", True)))
|
||
yg_actions_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("yanghao_enable_actions", True))
|
||
)
|
||
yg_recommend_duration_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||
)
|
||
yg_recommend_interval_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||
)
|
||
yg_like_prob_var = tk.DoubleVar(
|
||
value=float(cfg.get("yanghao_like_prob", 0.0) or 0.0)
|
||
)
|
||
yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||
yg_comment_prob_var = tk.DoubleVar(
|
||
value=float(cfg.get("yanghao_comment_prob", 0.0) or 0.0)
|
||
)
|
||
yg_icon_roi_size_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_icon_roi_size", 240) or 240)
|
||
)
|
||
yg_icon_match_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||
)
|
||
yg_step_screenshot_var = tk.BooleanVar(
|
||
value=bool(cfg.get("yanghao_step_screenshot", False))
|
||
)
|
||
yg_like_roi_offset_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_like_roi_offset_x", 0) or 0)
|
||
)
|
||
yg_like_roi_offset_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_like_roi_offset_y", 0) or 0)
|
||
)
|
||
yg_fav_roi_offset_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0)
|
||
)
|
||
yg_fav_roi_offset_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0)
|
||
)
|
||
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||
yg_like_template_path_var = tk.StringVar(
|
||
value=str(
|
||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||
or "assets/like.png"
|
||
)
|
||
)
|
||
yg_fav_template_path_var = tk.StringVar(
|
||
value=str(
|
||
cfg.get("yanghao_fav_template_path", "assets/fav.png") or "assets/fav.png"
|
||
)
|
||
)
|
||
yg_after_dwell_direction_var = tk.StringVar(
|
||
value=str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||
)
|
||
yg_after_dwell_distance_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||
)
|
||
yg_comment_btn_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_btn_x", 0) or 0)
|
||
)
|
||
yg_comment_btn_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_btn_y", 0) or 0)
|
||
)
|
||
yg_comment_input_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_input_x", 0) or 0)
|
||
)
|
||
yg_comment_input_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_input_y", 0) or 0)
|
||
)
|
||
yg_comment_send_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_send_x", 0) or 0)
|
||
)
|
||
yg_comment_send_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_send_y", 0) or 0)
|
||
)
|
||
yg_comment_close_x_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_close_x", 0) or 0)
|
||
)
|
||
yg_comment_close_y_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_comment_close_y", 0) or 0)
|
||
)
|
||
fudai_quiet_hours_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||
)
|
||
fudai_quiet_start_hour_var = tk.IntVar(
|
||
value=int(cfg.get("fudai_quiet_start_hour", 2) or 2)
|
||
)
|
||
fudai_quiet_end_hour_var = tk.IntVar(
|
||
value=int(cfg.get("fudai_quiet_end_hour", 7) or 7)
|
||
)
|
||
|
||
# 阶段诊断时间参数(用于调试)
|
||
stage_diag_max_time_var = tk.DoubleVar(
|
||
value=float(cfg.get("stage_diag_max_time", 10.0) or 10.0)
|
||
)
|
||
stage_diag_max_step_time_var = tk.DoubleVar(
|
||
value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||
)
|
||
enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False)))
|
||
# 福袋模板匹配开关和阈值
|
||
fudai_template_match_enabled_var = tk.BooleanVar(
|
||
value=bool(cfg.get("fudai_template_match_enabled", False))
|
||
)
|
||
fudai_template_match_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||
)
|
||
# 福袋详情页模板匹配阈值(0.0~1.0,默认0.7)
|
||
fudai_detail_template_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||
)
|
||
# 开奖页面红色占比阈值(0.0~1.0,默认0.9)
|
||
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||
)
|
||
# 优惠券模板匹配阈值(0.0~1.0,默认0.75)
|
||
coupon_template_match_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||
)
|
||
# 参与按钮红色占比阈值(0.0~1.0,默认0.25)
|
||
attend_button_red_ratio_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||
)
|
||
# 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)
|
||
fansclub_join_red_ratio_threshold_var = tk.DoubleVar(
|
||
value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||
)
|
||
|
||
# 调试图像清理相关变量
|
||
debug_captures_auto_cleanup_var = tk.BooleanVar(
|
||
value=bool(
|
||
cfg.get("debug_captures", {}).get("auto_cleanup", True)
|
||
if isinstance(cfg.get("debug_captures"), dict)
|
||
else True
|
||
)
|
||
)
|
||
debug_captures_keep_days_var = tk.IntVar(
|
||
value=int(
|
||
cfg.get("debug_captures", {}).get("keep_days", 7)
|
||
if isinstance(cfg.get("debug_captures"), dict)
|
||
else 7
|
||
)
|
||
)
|
||
debug_captures_max_files_var = tk.IntVar(
|
||
value=int(
|
||
cfg.get("debug_captures", {}).get("max_files", 2000)
|
||
if isinstance(cfg.get("debug_captures"), dict)
|
||
else 2000
|
||
)
|
||
)
|
||
|
||
# 倒计时小于阈值参数
|
||
skip_lt_seconds_var = tk.IntVar(
|
||
value=int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5)
|
||
)
|
||
|
||
# 创建左侧配置标签页
|
||
# 标签页1:运行设置
|
||
run_tab = ttk.Frame(left_notebook)
|
||
left_notebook.add(run_tab, text="运行设置")
|
||
|
||
run_box = ttk.LabelFrame(run_tab, text="基本运行参数")
|
||
run_box.pack(fill=X, padx=10, pady=(10, 10))
|
||
|
||
r0 = ttk.Frame(run_box)
|
||
r0.pack(fill=X, padx=10, pady=(10, 6))
|
||
ttk.Checkbutton(r0, text="允许切换直播间", variable=needswitch_var).pack(side=LEFT)
|
||
|
||
r1 = ttk.Frame(run_box)
|
||
r1.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Checkbutton(r1, text="无限循环模式", variable=infinite_loop_var).pack(side=LEFT)
|
||
ttk.Label(r1, text="运行时长(分钟):").pack(side=LEFT, padx=(10, 0))
|
||
wait_minutes_spinbox = ttk.Spinbox(
|
||
r1, from_=1, to=60, textvariable=wait_minutes_var, width=6
|
||
)
|
||
wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12))
|
||
|
||
# 根据无限循环开关状态,启用/禁用运行时长输入框
|
||
def update_wait_minutes_state(*args):
|
||
if infinite_loop_var.get():
|
||
wait_minutes_spinbox.config(state="disabled")
|
||
else:
|
||
wait_minutes_spinbox.config(state="normal")
|
||
|
||
infinite_loop_var.trace("w", update_wait_minutes_state)
|
||
update_wait_minutes_state() # 初始化状态
|
||
|
||
ttk.Label(r1, text="倒计时大于(秒)时不参与(高价值可预约):").pack(side=LEFT)
|
||
ttk.Spinbox(r1, from_=0, to=3600, textvariable=skip_gt_seconds_var, width=6).pack(
|
||
side=LEFT
|
||
)
|
||
|
||
r2 = ttk.Frame(run_box)
|
||
r2.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Checkbutton(
|
||
r2, text="切换N次后回到第一个", variable=reset_after_swipes_enabled_var
|
||
).pack(side=LEFT)
|
||
ttk.Label(r2, text="次数:").pack(side=LEFT, padx=(10, 0))
|
||
ttk.Spinbox(
|
||
r2, from_=1, to=9999, textvariable=reset_after_swipes_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(r2, text="(触发后会向上回退)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
# 标签页2:筛选设置
|
||
filter_tab = ttk.Frame(left_notebook)
|
||
left_notebook.add(filter_tab, text="筛选设置")
|
||
|
||
cfg_box = ttk.LabelFrame(filter_tab, text="福袋筛选条件")
|
||
cfg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||
|
||
row = ttk.Frame(cfg_box)
|
||
row.pack(fill=X, padx=10, pady=(10, 8))
|
||
ttk.Label(row, text="最低价值(元):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row, from_=0, to=99999, increment=1, textvariable=min_value_var, width=10
|
||
).pack(side=LEFT)
|
||
|
||
rowp = ttk.Frame(cfg_box)
|
||
rowp.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(rowp, text="参与人数范围:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
rowp,
|
||
from_=0,
|
||
to=99999999,
|
||
increment=1,
|
||
textvariable=min_participants_var,
|
||
width=10,
|
||
).pack(side=LEFT)
|
||
ttk.Label(rowp, text=" ~ ").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
rowp,
|
||
from_=0,
|
||
to=99999999,
|
||
increment=1,
|
||
textvariable=max_participants_var,
|
||
width=10,
|
||
).pack(side=LEFT)
|
||
ttk.Label(rowp, text="(填0表示不限制)").pack(side=LEFT)
|
||
|
||
row2 = ttk.Frame(cfg_box)
|
||
row2.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(row2, text="倒计时小于(秒)时不参与:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row2, from_=0, to=300, increment=1, textvariable=skip_lt_seconds_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(row2, text="(剩余时间太短,不参与)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
row3 = ttk.Frame(cfg_box)
|
||
row3.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Checkbutton(
|
||
row3, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=auto_join_var
|
||
).pack(side=LEFT)
|
||
|
||
row4 = ttk.Frame(cfg_box)
|
||
row4.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(row4, text="粉丝团失败策略:").pack(side=LEFT)
|
||
ttk.Combobox(
|
||
row4,
|
||
textvariable=fansclub_action_var,
|
||
values=["stay", "switch"],
|
||
width=10,
|
||
state="readonly",
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4, text="(stay=停留,switch=切换直播间)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
# 标签页3:高价值预约
|
||
reservation_tab_left = ttk.Frame(left_notebook)
|
||
left_notebook.add(reservation_tab_left, text="高价值预约")
|
||
|
||
reservation_box = ttk.LabelFrame(reservation_tab_left, text="高价值福袋预约参与")
|
||
reservation_box.pack(fill=X, padx=10, pady=(10, 10))
|
||
|
||
# 预约启用开关
|
||
res_r0 = ttk.Frame(reservation_box)
|
||
res_r0.pack(fill=X, padx=10, pady=(10, 8))
|
||
ttk.Checkbutton(
|
||
res_r0, text="启用预约(价值≥阈值)", variable=high_value_fudai_enabled_var
|
||
).pack(side=LEFT)
|
||
|
||
# 价值阈值和提前参与时间
|
||
res_r1 = ttk.Frame(reservation_box)
|
||
res_r1.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(res_r1, text="价值阈值(元):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
res_r1,
|
||
from_=0,
|
||
to=99999,
|
||
increment=100,
|
||
textvariable=high_value_fudai_threshold_yuan_var,
|
||
width=10,
|
||
).pack(side=LEFT)
|
||
ttk.Label(res_r1, text="提前参与(秒):").pack(side=LEFT, padx=(20, 0))
|
||
ttk.Spinbox(
|
||
res_r1,
|
||
from_=5,
|
||
to=900,
|
||
increment=10,
|
||
textvariable=high_value_fudai_join_ahead_seconds_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
|
||
# 最多回退次数
|
||
res_r2 = ttk.Frame(reservation_box)
|
||
res_r2.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(res_r2, text="最多回退直播间次数:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
res_r2,
|
||
from_=0,
|
||
to=300,
|
||
increment=5,
|
||
textvariable=high_value_fudai_max_swipe_back_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(res_r2, text="(0=不限制)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
# 最多记录数量和完成后策略
|
||
res_r3 = ttk.Frame(reservation_box)
|
||
res_r3.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(res_r3, text="最多记录数量:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
res_r3,
|
||
from_=1,
|
||
to=50,
|
||
increment=1,
|
||
textvariable=high_value_fudai_max_reservations_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(res_r3, text="完成后策略:").pack(side=LEFT, padx=(20, 0))
|
||
ttk.Combobox(
|
||
res_r3,
|
||
textvariable=high_value_fudai_after_action_var,
|
||
values=["continue", "stay"],
|
||
width=10,
|
||
state="readonly",
|
||
).pack(side=LEFT)
|
||
ttk.Label(res_r3, text="(stay=停留,continue=继续)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
# 高价值房间回访
|
||
res_r4 = ttk.Frame(reservation_box)
|
||
res_r4.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Checkbutton(
|
||
res_r4, text="启用高价值房间回访", variable=high_value_room_revisit_enabled_var
|
||
).pack(side=LEFT)
|
||
ttk.Checkbutton(
|
||
res_r4, text="仅当前运行", variable=high_value_room_revisit_only_current_run_var
|
||
).pack(side=LEFT, padx=(20, 0))
|
||
|
||
# 预约回退校验
|
||
res_r5 = ttk.Frame(reservation_box)
|
||
res_r5.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Checkbutton(
|
||
res_r5, text="预约回退校验", variable=reservation_back_verify_enabled_var
|
||
).pack(side=LEFT)
|
||
|
||
# 回退滑延迟和预约抢占最小价值
|
||
res_r6 = ttk.Frame(reservation_box)
|
||
res_r6.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(res_r6, text="回退滑延迟(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
res_r6,
|
||
from_=0.0,
|
||
to=10.0,
|
||
increment=0.1,
|
||
textvariable=reservation_back_swipe_delay_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(res_r6, text="预约抢占最小价值(元):").pack(side=LEFT, padx=(20, 0))
|
||
ttk.Spinbox(
|
||
res_r6,
|
||
from_=0,
|
||
to=99999,
|
||
increment=100,
|
||
textvariable=reservation_preempt_min_value_var,
|
||
width=10,
|
||
).pack(side=LEFT)
|
||
|
||
# 标签页4:养号设置
|
||
yanghao_tab = ttk.Frame(left_notebook)
|
||
left_notebook.add(yanghao_tab, text="养号设置")
|
||
|
||
yg_box = ttk.LabelFrame(yanghao_tab, text="推荐页养号(爱心/收藏/评论)")
|
||
yg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||
|
||
yg_switch = ttk.Frame(yg_box)
|
||
yg_switch.pack(fill=X, padx=10, pady=(10, 6))
|
||
ttk.Checkbutton(
|
||
yg_switch, text="养号总开关(关闭则跳过推荐页养号)", variable=yg_enabled_var
|
||
).pack(side=LEFT)
|
||
ttk.Checkbutton(
|
||
yg_switch,
|
||
text="启用养号动作(爱心/收藏/评论)",
|
||
variable=yg_actions_enabled_var,
|
||
).pack(side=LEFT, padx=(10, 0))
|
||
|
||
yg0 = ttk.Frame(yg_box)
|
||
yg0.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Checkbutton(
|
||
yg0,
|
||
text="逐步截图(调试用,生成 pic/*/latest.png)",
|
||
variable=yg_step_screenshot_var,
|
||
).pack(side=LEFT)
|
||
|
||
yg_time = ttk.Frame(yg_box)
|
||
yg_time.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(yg_time, text="养号时长(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
yg_time,
|
||
from_=1,
|
||
to=3600,
|
||
increment=5,
|
||
textvariable=yg_recommend_duration_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg_time, text="养号间隔(秒):").pack(side=LEFT, padx=(12, 0))
|
||
ttk.Spinbox(
|
||
yg_time,
|
||
from_=0,
|
||
to=3600,
|
||
increment=10,
|
||
textvariable=yg_recommend_interval_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg_time, text="(0=每次触发都执行)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
yg1 = ttk.Frame(yg_box)
|
||
yg1.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(yg1, text="爱心概率:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg1, text="收藏概率:").pack(side=LEFT, padx=(10, 0))
|
||
ttk.Spinbox(
|
||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg1, text="评论概率:").pack(side=LEFT, padx=(10, 0))
|
||
ttk.Spinbox(
|
||
yg1,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.05,
|
||
textvariable=yg_comment_prob_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg1, text="(0~1)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
yg2 = ttk.Frame(yg_box)
|
||
yg2.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(yg2, text="图标ROI大小(px):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(yg2, text="匹配阈值:").pack(side=LEFT, padx=(10, 0))
|
||
ttk.Spinbox(
|
||
yg2,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=yg_icon_match_threshold_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
|
||
yg_texts = ttk.Frame(yg_box)
|
||
yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||
ttk.Label(yg_texts, text="评论文案库(每行一条):").pack(anchor="w")
|
||
yg_comment_texts = ScrolledText(yg_texts, height=4)
|
||
yg_comment_texts.pack(fill=X, pady=(0, 6))
|
||
yg_kw = ttk.Frame(yg_texts)
|
||
yg_kw.pack(fill=BOTH, expand=True)
|
||
ttk.Label(yg_kw, text="爱心关键词(每行一条):").pack(anchor="w")
|
||
yg_like_keywords_text = ScrolledText(yg_kw, height=3)
|
||
yg_like_keywords_text.pack(fill=X, pady=(0, 6))
|
||
ttk.Label(yg_kw, text="收藏关键词(每行一条):").pack(anchor="w")
|
||
yg_fav_keywords_text = ScrolledText(yg_kw, height=3)
|
||
yg_fav_keywords_text.pack(fill=X)
|
||
|
||
quiet_box = ttk.LabelFrame(yanghao_tab, text="定时禁抢(仅养号)")
|
||
quiet_box.pack(fill=X, padx=10, pady=(0, 10))
|
||
quiet_r0 = ttk.Frame(quiet_box)
|
||
quiet_r0.pack(fill=X, padx=10, pady=(10, 6))
|
||
ttk.Checkbutton(
|
||
quiet_r0, text="启用定时禁抢", variable=fudai_quiet_hours_enabled_var
|
||
).pack(side=LEFT)
|
||
quiet_r1 = ttk.Frame(quiet_box)
|
||
quiet_r1.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(quiet_r1, text="开始小时:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
quiet_r1, from_=0, to=23, textvariable=fudai_quiet_start_hour_var, width=6
|
||
).pack(side=LEFT)
|
||
ttk.Label(quiet_r1, text="结束小时:").pack(side=LEFT, padx=(12, 0))
|
||
ttk.Spinbox(
|
||
quiet_r1, from_=0, to=23, textvariable=fudai_quiet_end_hour_var, width=6
|
||
).pack(side=LEFT)
|
||
|
||
# 标签页5:调试参数
|
||
debug_tab = ttk.Frame(left_notebook)
|
||
left_notebook.add(debug_tab, text="调试参数")
|
||
|
||
# 调试图像清理
|
||
debug_captures_box = ttk.LabelFrame(debug_tab, text="调试图像清理")
|
||
debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))
|
||
|
||
debug_r0 = ttk.Frame(debug_captures_box)
|
||
debug_r0.pack(fill=X, padx=10, pady=(10, 8))
|
||
ttk.Checkbutton(
|
||
debug_r0, text="启用自动清理调试图像", variable=debug_captures_auto_cleanup_var
|
||
).pack(side=LEFT)
|
||
|
||
debug_r1 = ttk.Frame(debug_captures_box)
|
||
debug_r1.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(debug_r1, text="保留天数:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
debug_r1,
|
||
from_=1,
|
||
to=30,
|
||
increment=1,
|
||
textvariable=debug_captures_keep_days_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(debug_r1, text="最大文件数量:").pack(side=LEFT, padx=(20, 0))
|
||
ttk.Spinbox(
|
||
debug_r1,
|
||
from_=100,
|
||
to=10000,
|
||
increment=100,
|
||
textvariable=debug_captures_max_files_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(debug_r1, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
# 找福袋参数
|
||
fudai_find_box = ttk.LabelFrame(debug_tab, text="找福袋参数")
|
||
fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))
|
||
|
||
row4 = ttk.Frame(fudai_find_box)
|
||
row4.pack(fill=X, padx=10, pady=(10, 8))
|
||
ttk.Label(row4, text="找福袋最大尝试次数:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row4,
|
||
from_=0,
|
||
to=50,
|
||
increment=1,
|
||
textvariable=fudai_find_max_attempts_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4, text="(0=使用默认值)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
row4b = ttk.Frame(fudai_find_box)
|
||
row4b.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(row4b, text="找福袋重试间隔(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row4b,
|
||
from_=0.1,
|
||
to=3.0,
|
||
increment=0.1,
|
||
textvariable=fudai_icon_retry_delay_seconds_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4b, text=" 最大等待时间(秒):").pack(side=LEFT, padx=(10, 0))
|
||
ttk.Spinbox(
|
||
row4b,
|
||
from_=0.0,
|
||
to=30.0,
|
||
increment=0.5,
|
||
textvariable=fudai_icon_max_wait_seconds_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4b, text="(实际识别常见 4-6 秒)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
row4d = ttk.Frame(fudai_find_box)
|
||
row4d.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(row4d, text="点击福袋后等待时间(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row4d,
|
||
from_=0.5,
|
||
to=10.0,
|
||
increment=0.1,
|
||
textvariable=fudai_click_wait_seconds_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4d, text="(等待福袋详情页加载,默认2.0秒)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
row4e = ttk.Frame(fudai_find_box)
|
||
row4e.pack(fill=X, padx=10, pady=(0, 8))
|
||
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row4e,
|
||
from_=0.0,
|
||
to=30.0,
|
||
increment=0.5,
|
||
textvariable=switch_room_wait_after_stage_diag_seconds_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
row4c = ttk.Frame(fudai_find_box)
|
||
row4c.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(row4c, text="直播间检测阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
row4c,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=live_room_match_threshold_var,
|
||
width=6,
|
||
).pack(side=LEFT)
|
||
ttk.Label(row4c, text="(0.0~1.0,默认0.7,值越高越严格)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
# 阶段诊断时间参数(用于调试)
|
||
diag_time_box = ttk.LabelFrame(debug_tab, text="阶段诊断时间参数")
|
||
diag_time_box.pack(fill=X, padx=10, pady=(0, 10))
|
||
diag_time_r1 = ttk.Frame(diag_time_box)
|
||
diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||
ttk.Label(diag_time_r1, text="最大诊断时间(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
diag_time_r1,
|
||
from_=1.0,
|
||
to=60.0,
|
||
increment=1.0,
|
||
textvariable=stage_diag_max_time_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r1, text="每步最大耗时(秒):").pack(side=LEFT, padx=(12, 0))
|
||
ttk.Spinbox(
|
||
diag_time_r1,
|
||
from_=0.5,
|
||
to=30.0,
|
||
increment=0.5,
|
||
textvariable=stage_diag_max_step_time_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r1, text="(用于调试,延长检测时间)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
diag_time_r2 = ttk.Frame(diag_time_box)
|
||
diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))
|
||
ttk.Checkbutton(
|
||
diag_time_r2, text="启用OCR模式1(二值化)", variable=enable_ocr_mode1_var
|
||
).pack(side=LEFT)
|
||
diag_time_r2b = ttk.Frame(diag_time_box)
|
||
diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))
|
||
ttk.Checkbutton(
|
||
diag_time_r2b,
|
||
text="启用福袋模板匹配",
|
||
variable=fudai_template_match_enabled_var,
|
||
).pack(side=LEFT)
|
||
diag_time_r3 = ttk.Frame(diag_time_box)
|
||
diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(diag_time_r3, text="福袋模板匹配阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
diag_time_r3,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=fudai_template_match_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0))
|
||
|
||
diag_time_r3b = ttk.Frame(diag_time_box)
|
||
diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(diag_time_r3b, text="福袋详情页模板匹配阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
diag_time_r3b,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=fudai_detail_template_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))").pack(side=LEFT, padx=(6, 0))
|
||
|
||
diag_time_r4 = ttk.Frame(diag_time_box)
|
||
diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(diag_time_r4, text="开奖页红色占比阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
diag_time_r4,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=lucky_draw_red_ratio_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r4, text="(默认0.90,≥此占比判定开奖页)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
# 更多模板匹配阈值
|
||
diag_time_r5 = ttk.Frame(diag_time_box)
|
||
diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))
|
||
ttk.Label(diag_time_r5, text="优惠券模板匹配阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
diag_time_r5,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=coupon_template_match_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(diag_time_r5, text="(默认0.75,用于检测优惠券弹窗)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
# 像素检测阈值
|
||
pixel_detect_box = ttk.LabelFrame(debug_tab, text="像素检测阈值")
|
||
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
|
||
|
||
pixel_r1 = ttk.Frame(pixel_detect_box)
|
||
pixel_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||
ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
pixel_r1,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=attend_button_red_ratio_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(pixel_r1, text="(默认0.25,用于检测参与按钮)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
pixel_r2 = ttk.Frame(pixel_detect_box)
|
||
pixel_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||
ttk.Label(pixel_r2, text="粉丝团加入红色占比阈值:").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
pixel_r2,
|
||
from_=0.0,
|
||
to=1.0,
|
||
increment=0.01,
|
||
textvariable=fansclub_join_red_ratio_threshold_var,
|
||
width=8,
|
||
).pack(side=LEFT)
|
||
ttk.Label(pixel_r2, text="(默认0.25,用于检测粉丝团加入按钮)").pack(
|
||
side=LEFT, padx=(6, 0)
|
||
)
|
||
|
||
# 标签页6:关键词
|
||
keywords_tab = ttk.Frame(left_notebook)
|
||
left_notebook.add(keywords_tab, text="关键词")
|
||
|
||
kw_box = ttk.LabelFrame(keywords_tab, text="关键词(每行一个,仅黑名单)")
|
||
kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
|
||
|
||
ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(
|
||
anchor="w", padx=10, pady=(10, 4)
|
||
)
|
||
not_want_text = ScrolledText(kw_box, height=8)
|
||
not_want_text.pack(fill=X, padx=10, pady=(0, 10))
|
||
|
||
def load_config_to_ui():
|
||
nonlocal cfg
|
||
cfg = read_config()
|
||
needswitch_var.set(bool(cfg.get("needswitch", True)))
|
||
infinite_loop_var.set(bool(cfg.get("infinite_loop_enabled", False)))
|
||
wait_minutes_var.set(int(cfg.get("wait_minutes", 5) or 5))
|
||
yg_enabled_var.set(bool(cfg.get("yanghao_enabled", True)))
|
||
yg_actions_enabled_var.set(bool(cfg.get("yanghao_enable_actions", True)))
|
||
yg_recommend_duration_var.set(
|
||
int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||
)
|
||
yg_recommend_interval_var.set(
|
||
int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||
)
|
||
min_value_var.set(float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||
min_participants_var.set(int(cfg.get("min_participants", 0) or 0))
|
||
max_participants_var.set(int(cfg.get("max_participants", 0) or 0))
|
||
skip_gt_seconds_var.set(
|
||
int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||
)
|
||
reset_after_swipes_enabled_var.set(
|
||
bool(cfg.get("reset_after_swipes_enabled", False))
|
||
)
|
||
reset_after_swipes_var.set(int(cfg.get("reset_after_swipes", 10) or 10))
|
||
auto_join_var.set(bool(cfg.get("auto_join_fansclub", False)))
|
||
fansclub_action_var.set(
|
||
str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||
)
|
||
lucky_draw_red_ratio_threshold_var.set(
|
||
float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||
)
|
||
y_var.set(int(cfg.get("y_pianyi", 0) or 0))
|
||
|
||
# Web端新增配置 - 高价值预约相关
|
||
high_value_fudai_enabled_var.set(
|
||
bool(cfg.get("high_value_fudai_enabled", False))
|
||
)
|
||
high_value_fudai_threshold_yuan_var.set(
|
||
float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||
)
|
||
high_value_fudai_join_ahead_seconds_var.set(
|
||
int(cfg.get("high_value_fudai_join_ahead_seconds", 120) or 120)
|
||
)
|
||
high_value_fudai_max_swipe_back_var.set(
|
||
int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||
)
|
||
high_value_fudai_max_reservations_var.set(
|
||
int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||
)
|
||
high_value_fudai_after_action_var.set(
|
||
str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||
)
|
||
high_value_room_revisit_enabled_var.set(
|
||
bool(cfg.get("high_value_room_revisit_enabled", True))
|
||
)
|
||
high_value_room_revisit_only_current_run_var.set(
|
||
bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||
)
|
||
reservation_back_verify_enabled_var.set(
|
||
bool(cfg.get("reservation_back_verify_enabled", True))
|
||
)
|
||
reservation_back_swipe_delay_var.set(
|
||
float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||
)
|
||
reservation_preempt_min_value_var.set(
|
||
float(cfg.get("reservation_preempt_min_value", 0) or 0)
|
||
)
|
||
fudai_find_max_attempts_var.set(int(cfg.get("fudai_find_max_attempts", 0) or 0))
|
||
fudai_icon_retry_delay_seconds_var.set(
|
||
float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||
)
|
||
fudai_icon_max_wait_seconds_var.set(
|
||
float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||
)
|
||
fudai_click_wait_seconds_var.set(
|
||
float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0)
|
||
)
|
||
switch_room_wait_after_stage_diag_seconds_var.set(
|
||
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||
)
|
||
live_room_match_threshold_var.set(
|
||
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||
)
|
||
fudai_quiet_hours_enabled_var.set(
|
||
bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||
)
|
||
fudai_quiet_start_hour_var.set(int(cfg.get("fudai_quiet_start_hour", 2) or 2))
|
||
fudai_quiet_end_hour_var.set(int(cfg.get("fudai_quiet_end_hour", 7) or 7))
|
||
stage_diag_max_time_var.set(float(cfg.get("stage_diag_max_time", 10.0) or 10.0))
|
||
stage_diag_max_step_time_var.set(
|
||
float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||
)
|
||
enable_ocr_mode1_var.set(bool(cfg.get("enable_ocr_mode1", False)))
|
||
fudai_template_match_enabled_var.set(
|
||
bool(cfg.get("fudai_template_match_enabled", False))
|
||
)
|
||
fudai_template_match_threshold_var.set(
|
||
float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||
)
|
||
fudai_detail_template_threshold_var.set(
|
||
float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||
)
|
||
coupon_template_match_threshold_var.set(
|
||
float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||
)
|
||
attend_button_red_ratio_threshold_var.set(
|
||
float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||
)
|
||
fansclub_join_red_ratio_threshold_var.set(
|
||
float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||
)
|
||
skip_lt_seconds_var.set(int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5))
|
||
|
||
# 调试图像清理配置
|
||
debug_captures_config = cfg.get("debug_captures", {})
|
||
if isinstance(debug_captures_config, dict):
|
||
debug_captures_auto_cleanup_var.set(
|
||
bool(debug_captures_config.get("auto_cleanup", True))
|
||
)
|
||
debug_captures_keep_days_var.set(
|
||
int(debug_captures_config.get("keep_days", 7) or 7)
|
||
)
|
||
debug_captures_max_files_var.set(
|
||
int(debug_captures_config.get("max_files", 2000) or 2000)
|
||
)
|
||
else:
|
||
debug_captures_auto_cleanup_var.set(True)
|
||
debug_captures_keep_days_var.set(7)
|
||
debug_captures_max_files_var.set(2000)
|
||
|
||
yg_like_prob_var.set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
|
||
yg_fav_prob_var.set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||
yg_comment_prob_var.set(float(cfg.get("yanghao_comment_prob", 0.0) or 0.0))
|
||
yg_icon_roi_size_var.set(int(cfg.get("yanghao_icon_roi_size", 240) or 240))
|
||
yg_icon_match_threshold_var.set(
|
||
float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||
)
|
||
yg_step_screenshot_var.set(bool(cfg.get("yanghao_step_screenshot", False)))
|
||
yg_like_roi_offset_x_var.set(int(cfg.get("yanghao_like_roi_offset_x", 0) or 0))
|
||
yg_like_roi_offset_y_var.set(int(cfg.get("yanghao_like_roi_offset_y", 0) or 0))
|
||
yg_fav_roi_offset_x_var.set(int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0))
|
||
yg_fav_roi_offset_y_var.set(int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0))
|
||
yg_like_icon_x_var.set(int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||
yg_like_icon_y_var.set(int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||
yg_fav_icon_x_var.set(int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||
yg_fav_icon_y_var.set(int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||
yg_like_template_path_var.set(
|
||
str(
|
||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||
or "assets/like.png"
|
||
)
|
||
)
|
||
yg_fav_template_path_var.set(
|
||
str(
|
||
cfg.get("yanghao_fav_template_path", "assets/fav.png")
|
||
or "assets/fav.png"
|
||
)
|
||
)
|
||
yg_after_dwell_direction_var.set(
|
||
str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||
)
|
||
yg_after_dwell_distance_var.set(
|
||
int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||
)
|
||
yg_comment_btn_x_var.set(int(cfg.get("yanghao_comment_btn_x", 0) or 0))
|
||
yg_comment_btn_y_var.set(int(cfg.get("yanghao_comment_btn_y", 0) or 0))
|
||
yg_comment_input_x_var.set(int(cfg.get("yanghao_comment_input_x", 0) or 0))
|
||
yg_comment_input_y_var.set(int(cfg.get("yanghao_comment_input_y", 0) or 0))
|
||
yg_comment_send_x_var.set(int(cfg.get("yanghao_comment_send_x", 0) or 0))
|
||
yg_comment_send_y_var.set(int(cfg.get("yanghao_comment_send_y", 0) or 0))
|
||
yg_comment_close_x_var.set(int(cfg.get("yanghao_comment_close_x", 0) or 0))
|
||
yg_comment_close_y_var.set(int(cfg.get("yanghao_comment_close_y", 0) or 0))
|
||
|
||
# 仅保留黑名单 contains_not_want
|
||
not_want = cfg.get("contains_not_want", []) or []
|
||
yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or []
|
||
yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or []
|
||
yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or []
|
||
not_want_text.delete("1.0", "end")
|
||
not_want_text.insert("1.0", "\n".join(not_want))
|
||
yg_comment_texts.delete("1.0", "end")
|
||
yg_comment_texts.insert("1.0", "\n".join(yg_comment_texts_list))
|
||
yg_like_keywords_text.delete("1.0", "end")
|
||
yg_like_keywords_text.insert("1.0", "\n".join(yg_like_keywords_list))
|
||
yg_fav_keywords_text.delete("1.0", "end")
|
||
yg_fav_keywords_text.insert("1.0", "\n".join(yg_fav_keywords_list))
|
||
|
||
def save_ui_to_config():
|
||
# 仅保存黑名单 contains_not_want
|
||
not_want_lines = [
|
||
x.strip() for x in not_want_text.get("1.0", "end").splitlines() if x.strip()
|
||
]
|
||
yg_comment_text_lines = [
|
||
x.strip()
|
||
for x in yg_comment_texts.get("1.0", "end").splitlines()
|
||
if x.strip()
|
||
]
|
||
yg_like_kw_lines = [
|
||
x.strip()
|
||
for x in yg_like_keywords_text.get("1.0", "end").splitlines()
|
||
if x.strip()
|
||
]
|
||
yg_fav_kw_lines = [
|
||
x.strip()
|
||
for x in yg_fav_keywords_text.get("1.0", "end").splitlines()
|
||
if x.strip()
|
||
]
|
||
|
||
cfg2 = read_config()
|
||
cfg2["needswitch"] = bool(needswitch_var.get())
|
||
cfg2["infinite_loop_enabled"] = bool(infinite_loop_var.get())
|
||
cfg2["wait_minutes"] = int(wait_minutes_var.get() or 5)
|
||
cfg2["y_pianyi"] = int(y_var.get() or 0)
|
||
cfg2["contains_not_want"] = not_want_lines
|
||
cfg2["min_prize_value_yuan"] = float(min_value_var.get() or 0)
|
||
cfg2["min_participants"] = int(min_participants_var.get() or 0)
|
||
cfg2["max_participants"] = int(max_participants_var.get() or 0)
|
||
cfg2["skip_if_countdown_gt_seconds"] = int(skip_gt_seconds_var.get() or 900)
|
||
cfg2["reset_after_swipes_enabled"] = bool(reset_after_swipes_enabled_var.get())
|
||
cfg2["reset_after_swipes"] = int(reset_after_swipes_var.get() or 10)
|
||
cfg2["auto_join_fansclub"] = bool(auto_join_var.get())
|
||
cfg2["fansclub_fail_action"] = str(fansclub_action_var.get() or "stay").lower()
|
||
cfg2["lucky_draw_red_ratio_threshold"] = float(
|
||
lucky_draw_red_ratio_threshold_var.get() or 0.9
|
||
)
|
||
|
||
# Web端新增配置 - 高价值预约相关
|
||
cfg2["high_value_fudai_enabled"] = bool(high_value_fudai_enabled_var.get())
|
||
cfg2["high_value_fudai_threshold_yuan"] = float(
|
||
high_value_fudai_threshold_yuan_var.get() or 1000
|
||
)
|
||
cfg2["high_value_fudai_join_ahead_seconds"] = int(
|
||
high_value_fudai_join_ahead_seconds_var.get() or 120
|
||
)
|
||
cfg2["high_value_fudai_max_swipe_back"] = int(
|
||
high_value_fudai_max_swipe_back_var.get() or 60
|
||
)
|
||
cfg2["high_value_fudai_max_reservations"] = int(
|
||
high_value_fudai_max_reservations_var.get() or 5
|
||
)
|
||
cfg2["high_value_fudai_after_action"] = str(
|
||
high_value_fudai_after_action_var.get() or "continue"
|
||
).lower()
|
||
cfg2["high_value_room_revisit_enabled"] = bool(
|
||
high_value_room_revisit_enabled_var.get()
|
||
)
|
||
cfg2["high_value_room_revisit_only_current_run"] = bool(
|
||
high_value_room_revisit_only_current_run_var.get()
|
||
)
|
||
cfg2["reservation_back_verify_enabled"] = bool(
|
||
reservation_back_verify_enabled_var.get()
|
||
)
|
||
cfg2["reservation_back_swipe_delay"] = float(
|
||
reservation_back_swipe_delay_var.get() or 0
|
||
)
|
||
cfg2["reservation_preempt_min_value"] = float(
|
||
reservation_preempt_min_value_var.get() or 0
|
||
)
|
||
cfg2["fudai_find_max_attempts"] = int(fudai_find_max_attempts_var.get() or 0)
|
||
cfg2["fudai_icon_retry_delay_seconds"] = float(
|
||
fudai_icon_retry_delay_seconds_var.get() or 0.6
|
||
)
|
||
cfg2["fudai_icon_max_wait_seconds"] = float(
|
||
fudai_icon_max_wait_seconds_var.get() or 5.0
|
||
)
|
||
cfg2["fudai_click_wait_seconds"] = float(
|
||
fudai_click_wait_seconds_var.get() or 2.0
|
||
)
|
||
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
|
||
switch_room_wait_after_stage_diag_seconds_var.get() or 7.0
|
||
)
|
||
cfg2["live_room_match_threshold"] = float(
|
||
live_room_match_threshold_var.get() or 0.8
|
||
)
|
||
cfg2["fudai_quiet_hours_enabled"] = bool(fudai_quiet_hours_enabled_var.get())
|
||
cfg2["fudai_quiet_start_hour"] = int(fudai_quiet_start_hour_var.get() or 0)
|
||
cfg2["fudai_quiet_end_hour"] = int(fudai_quiet_end_hour_var.get() or 0)
|
||
cfg2["stage_diag_max_time"] = float(stage_diag_max_time_var.get() or 10.0)
|
||
cfg2["stage_diag_max_step_time"] = float(
|
||
stage_diag_max_step_time_var.get() or 2.0
|
||
)
|
||
cfg2["enable_ocr_mode1"] = bool(enable_ocr_mode1_var.get())
|
||
cfg2["fudai_template_match_enabled"] = bool(
|
||
fudai_template_match_enabled_var.get()
|
||
)
|
||
cfg2["fudai_template_match_threshold"] = float(
|
||
fudai_template_match_threshold_var.get() or 0.7
|
||
)
|
||
cfg2["fudai_detail_template_threshold"] = float(
|
||
fudai_detail_template_threshold_var.get() or 0.7
|
||
)
|
||
cfg2["coupon_template_match_threshold"] = float(
|
||
coupon_template_match_threshold_var.get() or 0.75
|
||
)
|
||
cfg2["attend_button_red_ratio_threshold"] = float(
|
||
attend_button_red_ratio_threshold_var.get() or 0.25
|
||
)
|
||
cfg2["fansclub_join_red_ratio_threshold"] = float(
|
||
fansclub_join_red_ratio_threshold_var.get() or 0.25
|
||
)
|
||
cfg2["skip_if_countdown_lt_seconds"] = int(skip_lt_seconds_var.get() or 5)
|
||
|
||
# 调试图像清理配置
|
||
if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):
|
||
cfg2["debug_captures"] = {}
|
||
cfg2["debug_captures"]["auto_cleanup"] = bool(
|
||
debug_captures_auto_cleanup_var.get()
|
||
)
|
||
cfg2["debug_captures"]["keep_days"] = int(
|
||
debug_captures_keep_days_var.get() or 7
|
||
)
|
||
cfg2["debug_captures"]["max_files"] = int(
|
||
debug_captures_max_files_var.get() or 2000
|
||
)
|
||
|
||
cfg2["yanghao_enabled"] = bool(yg_enabled_var.get())
|
||
cfg2["yanghao_enable_actions"] = bool(yg_actions_enabled_var.get())
|
||
cfg2["yanghao_recommend_duration_seconds"] = int(
|
||
yg_recommend_duration_var.get() or 60
|
||
)
|
||
cfg2["yanghao_recommend_interval_seconds"] = int(
|
||
yg_recommend_interval_var.get() or 0
|
||
)
|
||
cfg2["yanghao_like_prob"] = float(yg_like_prob_var.get() or 0.0)
|
||
cfg2["yanghao_fav_prob"] = float(yg_fav_prob_var.get() or 0.0)
|
||
cfg2["yanghao_comment_prob"] = float(yg_comment_prob_var.get() or 0.0)
|
||
cfg2["yanghao_icon_roi_size"] = int(yg_icon_roi_size_var.get() or 240)
|
||
cfg2["yanghao_icon_match_threshold"] = float(
|
||
yg_icon_match_threshold_var.get() or 0.72
|
||
)
|
||
cfg2["yanghao_step_screenshot"] = bool(yg_step_screenshot_var.get())
|
||
cfg2["yanghao_like_roi_offset_x"] = int(yg_like_roi_offset_x_var.get() or 0)
|
||
cfg2["yanghao_like_roi_offset_y"] = int(yg_like_roi_offset_y_var.get() or 0)
|
||
cfg2["yanghao_fav_roi_offset_x"] = int(yg_fav_roi_offset_x_var.get() or 0)
|
||
cfg2["yanghao_fav_roi_offset_y"] = int(yg_fav_roi_offset_y_var.get() or 0)
|
||
cfg2["yanghao_like_icon_x"] = int(yg_like_icon_x_var.get() or 0)
|
||
cfg2["yanghao_like_icon_y"] = int(yg_like_icon_y_var.get() or 0)
|
||
cfg2["yanghao_fav_icon_x"] = int(yg_fav_icon_x_var.get() or 0)
|
||
cfg2["yanghao_fav_icon_y"] = int(yg_fav_icon_y_var.get() or 0)
|
||
cfg2["yanghao_like_template_path"] = str(
|
||
yg_like_template_path_var.get() or "assets/like.png"
|
||
)
|
||
cfg2["yanghao_fav_template_path"] = str(
|
||
yg_fav_template_path_var.get() or "assets/fav.png"
|
||
)
|
||
cfg2["yanghao_after_dwell_swipe_direction"] = str(
|
||
yg_after_dwell_direction_var.get() or "up"
|
||
)
|
||
cfg2["yanghao_after_dwell_swipe_distance_px"] = int(
|
||
yg_after_dwell_distance_var.get() or 900
|
||
)
|
||
cfg2["yanghao_comment_btn_x"] = int(yg_comment_btn_x_var.get() or 0)
|
||
cfg2["yanghao_comment_btn_y"] = int(yg_comment_btn_y_var.get() or 0)
|
||
cfg2["yanghao_comment_input_x"] = int(yg_comment_input_x_var.get() or 0)
|
||
cfg2["yanghao_comment_input_y"] = int(yg_comment_input_y_var.get() or 0)
|
||
cfg2["yanghao_comment_send_x"] = int(yg_comment_send_x_var.get() or 0)
|
||
cfg2["yanghao_comment_send_y"] = int(yg_comment_send_y_var.get() or 0)
|
||
cfg2["yanghao_comment_close_x"] = int(yg_comment_close_x_var.get() or 0)
|
||
cfg2["yanghao_comment_close_y"] = int(yg_comment_close_y_var.get() or 0)
|
||
cfg2["yanghao_comment_texts"] = yg_comment_text_lines
|
||
cfg2["yanghao_like_keywords"] = yg_like_kw_lines
|
||
cfg2["yanghao_fav_keywords"] = yg_fav_kw_lines
|
||
write_config(cfg2)
|
||
on_line("[配置] 已保存到 config.json")
|
||
|
||
load_config_to_ui()
|
||
|
||
# 顶部常驻按钮区域(与设备选择同一行,不随左侧滚动)
|
||
top_btns = ttk.Frame(top)
|
||
top_btns.pack(side=RIGHT, padx=(20, 0))
|
||
ttk.Button(top_btns, text="保存配置", command=save_ui_to_config).pack(
|
||
side=LEFT, padx=(0, 8)
|
||
)
|
||
# 截图+OCR 按钮也放在顶部,方便随时使用
|
||
# 具体回调在后文定义,这里先占位,通过 lambda 延迟绑定
|
||
screenshot_button_var = {"command": None}
|
||
|
||
def _bind_screenshot_button(btn):
|
||
# 在 do_screenshot 定义后调用,将真正的 command 绑定到按钮
|
||
screenshot_button_var["button"] = btn
|
||
|
||
screenshot_btn = ttk.Button(top_btns, text="截图+OCR")
|
||
screenshot_btn.pack(side=LEFT, padx=(0, 8))
|
||
_bind_screenshot_button(screenshot_btn)
|
||
|
||
# OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准)
|
||
OCR_REGIONS = [
|
||
# (区域名称, (x1, y1, x2, y2), 描述)
|
||
("福袋内容", (390, 1240, 980, 1470), "福袋内容详情"),
|
||
("福袋倒计时", (390, 1470, 980, 1580), "福袋倒计时"),
|
||
("福袋价值", (390, 1460, 1000, 1580), "奖品价值/价格"),
|
||
("抽奖结果", (380, 660, 720, 755), "抽奖结果弹窗"),
|
||
("推荐页标签栏", (400, 140, 900, 200), "推荐/关注/直播标签"),
|
||
("推荐页标签栏快速检测", (400, 140, 900, 200), "推荐页快速检测"),
|
||
("参与按钮", (306, 2030, 780, 2110), "参与福袋抽奖按钮"),
|
||
("无奖励确认", (340, 1195, 740, 1355), "无奖励确认弹窗"),
|
||
("奖励通知确认", (370, 1350, 680, 1440), "奖励通知确认"),
|
||
("订单确认", (370, 120, 700, 220), "订单确认页面"),
|
||
("关注列表标签", (658, 147, 765, 194), "关注列表标签"),
|
||
("直播列表标签", (400, 140, 900, 200), "直播列表标签"),
|
||
("直播广场", (400, 140, 900, 200), "直播广场标题"),
|
||
("直播间标题_中", (400, 140, 900, 200), "直播间标题中部"),
|
||
("诊断优惠券标题", (60, 1260, 1020, 1480), "优惠券弹窗标题"),
|
||
("诊断优惠券按钮", (400, 1600, 680, 1700), "优惠券按钮"),
|
||
("诊断购物红包", (400, 1400, 900, 1600), "购物红包弹窗"),
|
||
]
|
||
|
||
# 截图按钮
|
||
def do_screenshot():
|
||
device_id = device_var.get().strip()
|
||
if not device_id:
|
||
on_line("[截图] 请先选择设备")
|
||
return
|
||
|
||
# 在后台线程中执行截图和OCR识别,避免阻塞GUI
|
||
def screenshot_thread():
|
||
try:
|
||
from Underlying_Operations import underlying_operations
|
||
from PIL import Image
|
||
import os
|
||
|
||
# 使用 root.after 在主线程中更新日志
|
||
def log_msg(msg: str) -> Callable[[], None]:
|
||
def wrapper() -> None:
|
||
on_line(msg)
|
||
|
||
return wrapper
|
||
|
||
root.after(0, log_msg("[截图] 正在截图...")) # type: ignore[arg-type]
|
||
ops = underlying_operations()
|
||
result = ops.get_screenshot(device_id)
|
||
if not result:
|
||
root.after(0, log_msg("[截图] 截图失败")) # type: ignore[arg-type]
|
||
return
|
||
|
||
root.after(0, log_msg("[截图] 截图成功,已保存到 pic/screenshot.png")) # type: ignore[arg-type]
|
||
|
||
# 读取截图以获取实际尺寸
|
||
screenshot_path = os.path.join(
|
||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||
)
|
||
if not os.path.exists(screenshot_path):
|
||
root.after(0, log_msg("[OCR] 截图文件不存在")) # type: ignore[arg-type]
|
||
return
|
||
|
||
try:
|
||
img = Image.open(screenshot_path)
|
||
img.load() # Force load to catch truncated files early
|
||
img_width, img_height = img.size
|
||
# 计算缩放比例(基于1080x2400基准)
|
||
scale_x = img_width / 1080.0
|
||
scale_y = img_height / 2400.0
|
||
except (OSError, IOError, SyntaxError) as e:
|
||
# Handle truncated image files
|
||
root.after(0, log_msg(f"图片文件损坏或截断: {e}")) # type: ignore[arg-type]
|
||
return
|
||
except Exception as e:
|
||
root.after(0, log_msg(f"[OCR] 读取截图失败: {e}")) # type: ignore[arg-type]
|
||
return
|
||
|
||
# 获取Y偏移
|
||
y_offset = int(y_var.get() or 0)
|
||
|
||
# 执行所有OCR区域的识别
|
||
ocr_results = []
|
||
total_regions = len(OCR_REGIONS)
|
||
root.after(0, log_msg(f"[OCR] 开始识别 {total_regions} 个区域...")) # type: ignore[arg-type]
|
||
|
||
for idx, (region_name, (x1, y1, x2, y2), desc) in enumerate(
|
||
OCR_REGIONS, 1
|
||
):
|
||
try:
|
||
# 缩放坐标到实际截图尺寸
|
||
actual_x1 = int(x1 * scale_x)
|
||
actual_y1 = int(y1 * scale_y) + y_offset
|
||
actual_x2 = int(x2 * scale_x)
|
||
actual_y2 = int(y2 * scale_y) + y_offset
|
||
|
||
# 确保坐标在图片范围内
|
||
actual_x1 = max(0, min(actual_x1, img_width))
|
||
actual_y1 = max(0, min(actual_y1, img_height))
|
||
actual_x2 = max(0, min(actual_x2, img_width))
|
||
actual_y2 = max(0, min(actual_y2, img_height))
|
||
|
||
if actual_x1 >= actual_x2 or actual_y1 >= actual_y2:
|
||
root.after(0, log_msg(f"[OCR] {region_name}: 坐标无效,跳过")) # type: ignore[arg-type]
|
||
continue
|
||
|
||
# 截取区域
|
||
cut_result = ops.cut_pic(
|
||
(actual_x1, actual_y1),
|
||
(actual_x2, actual_y2),
|
||
"",
|
||
region_name,
|
||
)
|
||
if not cut_result:
|
||
root.after(0, log_msg(f"[OCR] {region_name}: 截图失败")) # type: ignore[arg-type]
|
||
ocr_results.append((region_name, desc, "", "截图失败"))
|
||
continue
|
||
|
||
# OCR识别(先尝试模式0,如果为空再尝试模式1)
|
||
text_result = ""
|
||
ocr_mode = 0
|
||
for mode in [0, 1]:
|
||
try:
|
||
text = str(
|
||
ops.analyse_pic_word(region_name, mode) or ""
|
||
).strip()
|
||
if text:
|
||
text_result = text
|
||
ocr_mode = mode
|
||
break
|
||
except Exception:
|
||
continue
|
||
|
||
ocr_results.append(
|
||
(region_name, desc, text_result, f"模式{ocr_mode}")
|
||
)
|
||
status_msg = f"[OCR] ({idx}/{total_regions}) {region_name}: {text_result[:50] if text_result else '(空)'}"
|
||
root.after(0, log_msg(status_msg)) # type: ignore[arg-type]
|
||
|
||
except Exception as e:
|
||
error_msg = f"[OCR] {region_name}: 异常 - {e}"
|
||
root.after(0, log_msg(error_msg)) # type: ignore[arg-type]
|
||
ocr_results.append((region_name, desc, "", f"异常: {e}"))
|
||
|
||
# 更新OCR结果标签页
|
||
def update_ocr_wrapper() -> None:
|
||
update_ocr_results(ocr_results)
|
||
|
||
root.after(0, update_ocr_wrapper) # type: ignore[arg-type]
|
||
root.after(0, log_msg(f"[OCR] 完成!共识别 {len(ocr_results)} 个区域")) # type: ignore[arg-type]
|
||
|
||
# 刷新截图预览(如果当前显示的是 screenshot.png)
|
||
def refresh_if_screenshot() -> None:
|
||
if image_var.get() == "screenshot.png":
|
||
refresh_preview()
|
||
|
||
root.after(0, refresh_if_screenshot) # type: ignore[arg-type]
|
||
|
||
except Exception as e:
|
||
import traceback
|
||
|
||
error_detail = traceback.format_exc()
|
||
root.after(0, log_msg(f"[截图] 截图异常: {e}\n{error_detail}")) # type: ignore[arg-type]
|
||
|
||
thread = threading.Thread(target=screenshot_thread, daemon=True)
|
||
thread.start()
|
||
|
||
# 将顶部“截图+OCR”按钮的回调绑定到 do_screenshot
|
||
try:
|
||
btn = screenshot_button_var.get("button")
|
||
if btn is not None:
|
||
btn.configure(command=do_screenshot)
|
||
except Exception:
|
||
pass
|
||
|
||
# 右侧:操作按钮区域(先创建,放在底部)
|
||
actions = ttk.Frame(right)
|
||
|
||
# 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
|
||
notebook = ttk.Notebook(right)
|
||
|
||
log_tab = ttk.Frame(notebook)
|
||
preview_tab = ttk.Frame(notebook)
|
||
stats_tab = ttk.Frame(notebook)
|
||
reservation_tab = ttk.Frame(notebook)
|
||
high_value_tab = ttk.Frame(notebook)
|
||
actions_log_tab = ttk.Frame(notebook)
|
||
ocr_results_tab = ttk.Frame(notebook)
|
||
notebook.add(log_tab, text="运行日志")
|
||
notebook.add(preview_tab, text="截图预览")
|
||
notebook.add(stats_tab, text="统计信息")
|
||
notebook.add(reservation_tab, text="预约队列")
|
||
notebook.add(high_value_tab, text="高价值房间")
|
||
notebook.add(actions_log_tab, text="行为日志")
|
||
notebook.add(ocr_results_tab, text="OCR结果")
|
||
|
||
# 日志区
|
||
log_box = ttk.Frame(log_tab)
|
||
log_box.pack(fill=BOTH, expand=True)
|
||
|
||
# 搜索工具栏
|
||
log_search_frame = ttk.Frame(log_box)
|
||
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
|
||
|
||
log_search_var = tk.StringVar(value="")
|
||
log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20)
|
||
log_search_entry.pack(side=LEFT, padx=(0, 5))
|
||
|
||
log_search_matches = [] # 存储所有匹配的位置
|
||
log_current_match_index = -1 # 当前匹配的索引
|
||
|
||
def search_in_log_text(direction=1):
|
||
"""在运行日志中搜索文本"""
|
||
nonlocal log_search_matches, log_current_match_index
|
||
|
||
search_text = log_search_var.get().strip()
|
||
if not search_text:
|
||
# 清除高亮
|
||
log_text.tag_remove("search_highlight", "1.0", "end")
|
||
log_search_matches = []
|
||
log_current_match_index = -1
|
||
return
|
||
|
||
# 获取所有文本
|
||
content = log_text.get("1.0", "end-1c")
|
||
if not content:
|
||
return
|
||
|
||
# 清除之前的高亮
|
||
log_text.tag_remove("search_highlight", "1.0", "end")
|
||
log_text.tag_remove("search_current", "1.0", "end")
|
||
|
||
# 配置高亮样式
|
||
log_text.tag_config("search_highlight", background="yellow")
|
||
log_text.tag_config("search_current", background="orange")
|
||
|
||
# 查找所有匹配项(不区分大小写)
|
||
log_search_matches = []
|
||
start_pos = 0 # 使用整数索引
|
||
search_text_lower = search_text.lower()
|
||
content_lower = content.lower()
|
||
|
||
while True:
|
||
# 在内容中查找
|
||
pos = content_lower.find(search_text_lower, start_pos)
|
||
if pos == -1:
|
||
break
|
||
|
||
# 计算行号和列号
|
||
line_start = content[:pos].rfind("\n") + 1
|
||
line_num = content[:pos].count("\n") + 1
|
||
col_num = pos - line_start
|
||
|
||
# 转换为 tkinter 索引格式
|
||
start_index = f"{line_num}.{col_num}"
|
||
end_index = f"{line_num}.{col_num + len(search_text)}"
|
||
|
||
log_search_matches.append((start_index, end_index))
|
||
start_pos = pos + 1
|
||
|
||
if not log_search_matches:
|
||
# 没有找到匹配项
|
||
log_current_match_index = -1
|
||
return
|
||
|
||
# 高亮所有匹配项
|
||
for start_idx, end_idx in log_search_matches:
|
||
log_text.tag_add("search_highlight", start_idx, end_idx)
|
||
|
||
# 根据方向更新当前匹配索引
|
||
if direction == 1: # 下一个
|
||
log_current_match_index = (log_current_match_index + 1) % len(log_search_matches)
|
||
else: # 上一个
|
||
log_current_match_index = (log_current_match_index - 1) % len(log_search_matches)
|
||
|
||
# 高亮当前匹配项并滚动到该位置
|
||
if log_current_match_index >= 0:
|
||
start_idx, end_idx = log_search_matches[log_current_match_index]
|
||
log_text.tag_add("search_current", start_idx, end_idx)
|
||
log_text.see(start_idx)
|
||
log_text.mark_set("insert", start_idx)
|
||
|
||
def search_next_in_log():
|
||
"""搜索下一个"""
|
||
search_in_log_text(1)
|
||
|
||
def search_prev_in_log():
|
||
"""搜索上一个"""
|
||
search_in_log_text(-1)
|
||
|
||
def clear_search_in_log():
|
||
"""清除搜索高亮"""
|
||
nonlocal log_search_matches, log_current_match_index
|
||
log_search_var.set("")
|
||
log_text.tag_remove("search_highlight", "1.0", "end")
|
||
log_text.tag_remove("search_current", "1.0", "end")
|
||
log_search_matches = []
|
||
log_current_match_index = -1
|
||
|
||
# 绑定回车键搜索
|
||
def on_log_search_entry_key(event):
|
||
if event.keysym == "Return":
|
||
search_next_in_log()
|
||
|
||
log_search_entry.bind("<KeyPress>", on_log_search_entry_key)
|
||
|
||
ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5))
|
||
|
||
log_text = ScrolledText(log_box)
|
||
try:
|
||
log_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||
|
||
# 截图预览
|
||
preview_top = ttk.Frame(preview_tab)
|
||
preview_top.pack(fill=X, padx=10, pady=10)
|
||
|
||
images_dir = os.path.join(os.path.dirname(__file__), "pic")
|
||
|
||
def scan_image_files():
|
||
"""扫描pic文件夹及其子文件夹中的所有图片文件"""
|
||
image_files = []
|
||
if os.path.exists(images_dir):
|
||
for root, dirs, files in os.walk(images_dir):
|
||
for file in files:
|
||
if file.lower().endswith(
|
||
(".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif")
|
||
):
|
||
# 获取相对路径
|
||
rel_path = os.path.relpath(os.path.join(root, file), images_dir)
|
||
# 统一使用正斜杠(Windows和Unix都支持)
|
||
rel_path = rel_path.replace("\\", "/")
|
||
image_files.append(rel_path)
|
||
# 按文件名排序
|
||
image_files.sort(key=lambda x: x.lower())
|
||
return image_files
|
||
|
||
image_var = tk.StringVar(value="")
|
||
|
||
ttk.Label(preview_top, text="选择图片:").pack(side=LEFT)
|
||
# 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图
|
||
image_combo = ttk.Combobox(
|
||
preview_top, textvariable=image_var, width=30, state="normal"
|
||
)
|
||
image_combo.pack(side=LEFT, padx=(0, 10))
|
||
|
||
def update_image_list(refresh_after=True):
|
||
"""更新图片列表"""
|
||
new_list = scan_image_files()
|
||
image_combo["values"] = new_list
|
||
current_value = image_var.get()
|
||
# 如果当前值不在新列表中,或列表为空,选择第一个
|
||
if new_list:
|
||
if not current_value or current_value not in new_list:
|
||
image_var.set(new_list[0])
|
||
else:
|
||
image_var.set("")
|
||
on_line(f"[预览] 扫描到 {len(new_list)} 个图片文件")
|
||
# 如果当前有选择的图片,刷新预览(如果refresh_after为True且refresh_preview已定义)
|
||
if refresh_after and image_var.get():
|
||
try:
|
||
refresh_preview()
|
||
except NameError:
|
||
# refresh_preview还没定义,忽略
|
||
pass
|
||
|
||
# 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)
|
||
def refresh_preview():
|
||
name = image_var.get().strip()
|
||
if not name:
|
||
preview_status.set("请选择图片")
|
||
image_label.configure(image="")
|
||
_img_ref["photo"] = None
|
||
return
|
||
# 处理相对路径(将正斜杠转换为系统路径分隔符)
|
||
name_normalized = name.replace("/", os.sep)
|
||
path = os.path.join(images_dir, name_normalized)
|
||
_load_and_fit_image(path)
|
||
|
||
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
|
||
|
||
preview_status = tk.StringVar(value="")
|
||
ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)
|
||
|
||
preview_body = ttk.Frame(preview_tab)
|
||
preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||
|
||
image_label = ttk.Label(preview_body)
|
||
image_label.pack(fill=BOTH, expand=True)
|
||
_img_ref: dict[str, Any] = {"photo": None} # 防止 PhotoImage 被回收
|
||
|
||
def _load_and_fit_image(img_path: str) -> None:
|
||
if not os.path.exists(img_path):
|
||
preview_status.set(f"未找到:{os.path.basename(img_path)}")
|
||
image_label.configure(image="")
|
||
_img_ref["photo"] = None
|
||
return
|
||
|
||
try:
|
||
img = Image.open(img_path)
|
||
img.load() # Force load to catch truncated files early
|
||
img = img.convert("RGB")
|
||
except (OSError, IOError, SyntaxError) as e:
|
||
# Handle truncated image files
|
||
preview_status.set(f"图片加载失败:{str(e)[:50]}")
|
||
image_label.configure(image="")
|
||
_img_ref["photo"] = None
|
||
return
|
||
except Exception as e:
|
||
preview_status.set(f"图片加载错误:{str(e)[:50]}")
|
||
image_label.configure(image="")
|
||
_img_ref["photo"] = None
|
||
return
|
||
|
||
# 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)
|
||
try:
|
||
preview_body.update_idletasks() # 强制更新布局
|
||
w = preview_body.winfo_width()
|
||
h = preview_body.winfo_height()
|
||
# 如果尺寸无效(窗口未初始化),使用默认值
|
||
if w <= 1 or h <= 1:
|
||
w, h = 900, 520
|
||
except Exception:
|
||
w, h = 900, 520
|
||
|
||
max_w = max(300, w - 20)
|
||
max_h = max(200, h - 20)
|
||
try:
|
||
resample = Image.Resampling.LANCZOS
|
||
except AttributeError:
|
||
# Fallback for older Pillow versions: LANCZOS constant value is 1
|
||
resample = 1 # type: ignore[assignment]
|
||
img.thumbnail((max_w, max_h), resample)
|
||
photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)
|
||
_img_ref["photo"] = photo # type: ignore[assignment]
|
||
image_label.configure(image=photo)
|
||
preview_status.set(f"{os.path.basename(img_path)} {img.width}x{img.height}")
|
||
|
||
ttk.Button(
|
||
preview_top,
|
||
text="刷新列表",
|
||
command=lambda: update_image_list(refresh_after=True),
|
||
).pack(side=LEFT, padx=(0, 5))
|
||
ttk.Button(preview_top, text="刷新预览", command=refresh_preview).pack(side=LEFT)
|
||
|
||
# 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)
|
||
def on_image_selected(*args):
|
||
"""当用户选择图片时自动刷新预览"""
|
||
try:
|
||
refresh_preview()
|
||
except Exception:
|
||
pass # 忽略错误,避免影响其他功能
|
||
|
||
image_var.trace("w", on_image_selected) # 监听变量变化
|
||
image_combo.bind(
|
||
"<<ComboboxSelected>>", lambda e: refresh_preview()
|
||
) # 监听下拉选择
|
||
|
||
def open_pic_folder():
|
||
try:
|
||
os.makedirs(images_dir, exist_ok=True)
|
||
os.startfile(images_dir) # type: ignore[attr-defined]
|
||
except Exception as e:
|
||
on_line(f"[预览] 打开图片目录失败:{e}")
|
||
|
||
ttk.Button(preview_top, text="打开pic目录", command=open_pic_folder).pack(
|
||
side=LEFT, padx=(10, 0)
|
||
)
|
||
|
||
status_var = tk.StringVar(value="就绪")
|
||
|
||
def get_params() -> RunParams:
|
||
# 如果启用无限循环,设置 wait_minutes=0
|
||
wait_minutes_value = (
|
||
0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5)
|
||
)
|
||
return RunParams(
|
||
enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),
|
||
device_id=device_var.get().strip(),
|
||
y_pianyi=int(y_var.get()),
|
||
needswitch=bool(needswitch_var.get()),
|
||
wait_minutes=wait_minutes_value,
|
||
skip_if_countdown_gt_seconds=int(skip_gt_seconds_var.get() or 900),
|
||
reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()),
|
||
reset_after_swipes=int(reset_after_swipes_var.get() or 10),
|
||
min_prize_value_yuan=float(min_value_var.get() or 0),
|
||
min_participants=int(min_participants_var.get() or 0),
|
||
max_participants=int(max_participants_var.get() or 0),
|
||
auto_join_fansclub=bool(auto_join_var.get()),
|
||
fansclub_fail_action=str(fansclub_action_var.get() or "stay").lower(),
|
||
# Web端新增参数
|
||
high_value_room_revisit_enabled=bool(
|
||
high_value_room_revisit_enabled_var.get()
|
||
),
|
||
high_value_room_revisit_only_current_run=bool(
|
||
high_value_room_revisit_only_current_run_var.get()
|
||
),
|
||
reservation_back_verify_enabled=bool(
|
||
reservation_back_verify_enabled_var.get()
|
||
),
|
||
reservation_back_swipe_delay=float(
|
||
reservation_back_swipe_delay_var.get() or 0
|
||
),
|
||
reservation_preempt_min_value=float(
|
||
reservation_preempt_min_value_var.get() or 0
|
||
),
|
||
fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0),
|
||
fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),
|
||
fudai_template_match_threshold=float(
|
||
fudai_template_match_threshold_var.get() or 0.7
|
||
),
|
||
)
|
||
|
||
def start_run():
|
||
if runner.is_running():
|
||
on_line("[运行] 已在运行中")
|
||
return
|
||
save_ui_to_config()
|
||
params = get_params()
|
||
|
||
wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m"
|
||
on_line(
|
||
f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} "
|
||
f"needswitch={params.needswitch} wait={wait_display} "
|
||
f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} "
|
||
f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] "
|
||
f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} "
|
||
f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only"
|
||
)
|
||
status_var.set("运行中")
|
||
try:
|
||
runner.start(params)
|
||
except Exception as e:
|
||
status_var.set("启动失败")
|
||
on_line(f"[错误] {e}")
|
||
|
||
def stop_run():
|
||
runner.stop()
|
||
status_var.set("已停止")
|
||
|
||
# 先打包 actions 到底部(不 expand,固定在底部)
|
||
actions.pack(fill=X, pady=(10, 0), padx=12, side="bottom")
|
||
|
||
# 然后打包 notebook 填充剩余空间(在 actions 之上)
|
||
notebook.pack(fill=BOTH, expand=True)
|
||
|
||
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
|
||
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
|
||
|
||
def force_stop_run():
|
||
"""强制终止后台进程(包括可能残留的子进程)。"""
|
||
runner.force_stop()
|
||
status_var.set("已停止(强制)")
|
||
|
||
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
|
||
side=LEFT, padx=(0, 8)
|
||
)
|
||
|
||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||
test_seconds_var = tk.IntVar(
|
||
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||
)
|
||
ttk.Label(actions, text="测试养号(秒):").pack(side=LEFT)
|
||
ttk.Spinbox(
|
||
actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8
|
||
).pack(side=LEFT, padx=(0, 8))
|
||
|
||
def start_test_yanghao():
|
||
if runner.is_running():
|
||
on_line("[运行] 已在运行中")
|
||
return
|
||
save_ui_to_config()
|
||
secs = int(test_seconds_var.get() or 90)
|
||
dev = device_var.get().strip()
|
||
on_line(f"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}")
|
||
status_var.set("运行中")
|
||
try:
|
||
runner.start_test_yanghao_flow(dev, secs)
|
||
except Exception as e:
|
||
status_var.set("启动失败")
|
||
on_line(f"[错误] {e}")
|
||
|
||
ttk.Button(actions, text="测试养号流程", command=start_test_yanghao).pack(side=LEFT)
|
||
|
||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||
test_comment_var = tk.StringVar(value="测试评论")
|
||
ttk.Label(actions, text="测试评论:").pack(side=LEFT)
|
||
ttk.Entry(actions, textvariable=test_comment_var, width=12).pack(
|
||
side=LEFT, padx=(0, 8)
|
||
)
|
||
|
||
def start_test_comment():
|
||
if runner.is_running():
|
||
on_line("[运行] 已在运行中")
|
||
return
|
||
save_ui_to_config()
|
||
text = test_comment_var.get().strip()
|
||
dev = device_var.get().strip()
|
||
on_line(f"[测试] 启动评论测试:device={dev or '(auto)'} text={text}")
|
||
status_var.set("运行中")
|
||
try:
|
||
runner.start_test_comment(dev, text)
|
||
except Exception as e:
|
||
status_var.set("启动失败")
|
||
on_line(f"[错误] {e}")
|
||
|
||
ttk.Button(actions, text="测试评论", command=start_test_comment).pack(side=LEFT)
|
||
|
||
ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3)
|
||
|
||
def send_back_key():
|
||
dev = device_var.get().strip()
|
||
try:
|
||
runner.send_back_key(dev)
|
||
except Exception as e:
|
||
on_line(f"[错误] 发送返回键失败: {e}")
|
||
|
||
ttk.Button(actions, text="发送返回键", command=send_back_key).pack(
|
||
side=LEFT, padx=(0, 8)
|
||
)
|
||
|
||
ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)
|
||
|
||
def pump_logs():
|
||
changed = False
|
||
try:
|
||
while True:
|
||
line = q.get_nowait()
|
||
try:
|
||
log_text.insert("end", line + "\n")
|
||
# 不再自动滚动到底部,让用户自由控制滚动位置
|
||
changed = True
|
||
except Exception as e:
|
||
# 如果插入日志失败,至少打印到控制台(调试用)
|
||
print(f"[GUI日志错误] 无法插入日志: {e}", file=sys.stderr)
|
||
except queue.Empty:
|
||
pass
|
||
except Exception as e:
|
||
# 捕获其他异常,确保日志循环不会中断
|
||
print(f"[GUI日志错误] pump_logs异常: {e}", file=sys.stderr)
|
||
|
||
try:
|
||
if changed and not runner.is_running() and status_var.get() == "运行中":
|
||
status_var.set("已结束")
|
||
except Exception:
|
||
pass
|
||
|
||
# 确保递归调用始终执行,即使前面出现异常
|
||
try:
|
||
root.after(100, pump_logs) # type: ignore[arg-type]
|
||
except Exception as e:
|
||
# 如果 root 已被销毁,停止日志循环
|
||
print(f"[GUI日志错误] 无法调度下次日志更新: {e}", file=sys.stderr)
|
||
|
||
# 统计信息显示
|
||
stats_top = ttk.Frame(stats_tab)
|
||
stats_top.pack(fill=X, padx=10, pady=(10, 0))
|
||
stats_text = ScrolledText(stats_tab)
|
||
stats_text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||
try:
|
||
stats_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
|
||
def refresh_stats():
|
||
try:
|
||
stats = runner.get_stats()
|
||
lines = []
|
||
|
||
# 基本信息
|
||
lines.append("=" * 60)
|
||
lines.append("运行状态信息")
|
||
lines.append("=" * 60)
|
||
lines.append(f"运行状态: {'运行中' if stats.get('running') else '未运行'}")
|
||
lines.append(f"PID: {stats.get('pid') or '-'}")
|
||
|
||
uptime_seconds = stats.get("uptime_seconds", 0)
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds // 3600
|
||
minutes = (uptime_seconds % 3600) // 60
|
||
seconds = uptime_seconds % 60
|
||
lines.append(f"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}")
|
||
else:
|
||
lines.append(f"运行时长: -")
|
||
|
||
last_log_ts = stats.get("last_log_ts")
|
||
if last_log_ts:
|
||
import datetime
|
||
|
||
dt = datetime.datetime.fromtimestamp(last_log_ts)
|
||
lines.append(f"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
else:
|
||
lines.append(f"最近日志时间: -")
|
||
|
||
exit_code = stats.get("exit_code")
|
||
lines.append(f"退出码: {exit_code if exit_code is not None else '-'}")
|
||
lines.append("")
|
||
|
||
# 计数器统计
|
||
counters = stats.get("counters", {})
|
||
|
||
# 快速汇总(关键指标)
|
||
fudai_seen = counters.get("fudai_seen", 0)
|
||
fudai_attend_ok = counters.get("fudai_attend_ok", 0)
|
||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||
|
||
if fudai_seen > 0 or fudai_attend_ok > 0 or fudai_result_win > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("快速汇总")
|
||
lines.append("=" * 60)
|
||
lines.append(f"识别福袋: {fudai_seen} 个")
|
||
lines.append(f"参与成功: {fudai_attend_ok} 次")
|
||
lines.append(f"中奖次数: {fudai_result_win} 次")
|
||
lines.append(f"下单成功: {fudai_order_success} 次")
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
lines.append(
|
||
f"运行效率: {fudai_attend_ok / hours:.1f} 次参与/小时"
|
||
)
|
||
lines.append("")
|
||
|
||
# 核心统计(总是显示,即使数据为0)
|
||
lines.append("=" * 60)
|
||
lines.append("核心统计")
|
||
lines.append("=" * 60)
|
||
|
||
# 福袋相关核心指标(重新获取,避免重复定义)
|
||
fudai_open_detail = counters.get("fudai_open_detail", 0)
|
||
fudai_click_attend = counters.get("fudai_click_attend", 0)
|
||
fudai_attend_ok = counters.get("fudai_attend_ok", 0)
|
||
fudai_attend_fail = counters.get("fudai_attend_fail", 0)
|
||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||
fudai_result_no_win = counters.get("fudai_result_no_win", 0)
|
||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||
|
||
lines.append(f"福袋识别次数: {fudai_seen}")
|
||
lines.append(f"打开详情: {fudai_open_detail}")
|
||
if fudai_seen > 0:
|
||
open_rate = (fudai_open_detail / fudai_seen) * 100
|
||
lines.append(f" 打开成功率: {open_rate:.1f}%")
|
||
|
||
lines.append(f"点击参与: {fudai_click_attend}")
|
||
if fudai_open_detail > 0:
|
||
click_rate = (fudai_click_attend / fudai_open_detail) * 100
|
||
lines.append(f" 点击率: {click_rate:.1f}%")
|
||
|
||
lines.append(f"参与成功: {fudai_attend_ok}")
|
||
lines.append(f"参与失败: {fudai_attend_fail}")
|
||
total_attend = fudai_attend_ok + fudai_attend_fail
|
||
if total_attend > 0:
|
||
success_rate = (fudai_attend_ok / total_attend) * 100
|
||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||
|
||
lines.append(f"中奖次数: {fudai_result_win}")
|
||
lines.append(f"未中奖次数: {fudai_result_no_win}")
|
||
total_results = fudai_result_win + fudai_result_no_win
|
||
if total_results > 0:
|
||
win_rate = (fudai_result_win / total_results) * 100
|
||
lines.append(f" 中奖率: {win_rate:.1f}%")
|
||
|
||
lines.append(f"下单成功: {fudai_order_success}")
|
||
|
||
# 效率统计
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
lines.append("")
|
||
lines.append("效率统计(每小时):")
|
||
if fudai_seen > 0:
|
||
lines.append(f" 识别福袋: {fudai_seen / hours:.1f} 个/小时")
|
||
if fudai_attend_ok > 0:
|
||
lines.append(
|
||
f" 参与成功: {fudai_attend_ok / hours:.1f} 次/小时"
|
||
)
|
||
if total_results > 0:
|
||
lines.append(f" 开奖次数: {total_results / hours:.1f} 次/小时")
|
||
if fudai_result_win > 0:
|
||
lines.append(
|
||
f" 中奖次数: {fudai_result_win / hours:.2f} 次/小时"
|
||
)
|
||
|
||
lines.append("")
|
||
|
||
# 跳过原因统计
|
||
skip_stats = [
|
||
("fudai_skip_value_low", "跳过-价值过低"),
|
||
("fudai_skip_participants_low", "跳过-人数过少"),
|
||
("fudai_skip_participants_high", "跳过-人数过多"),
|
||
("fudai_skip_content", "跳过-内容不理想"),
|
||
("fudai_skip_countdown_short", "跳过-倒计时太短"),
|
||
("fudai_skip_countdown_long", "跳过-倒计时太长"),
|
||
("fudai_skip_watch_required", "跳过-需要看播"),
|
||
]
|
||
skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)
|
||
if skip_total > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("跳过原因统计")
|
||
lines.append("=" * 60)
|
||
lines.append(f"总跳过次数: {skip_total}")
|
||
if fudai_seen > 0:
|
||
skip_rate = (skip_total / fudai_seen) * 100
|
||
lines.append(f"跳过率: {skip_rate:.1f}%")
|
||
lines.append("")
|
||
for key, label in skip_stats:
|
||
val = counters.get(key, 0)
|
||
if val > 0:
|
||
percentage = (val / skip_total) * 100 if skip_total > 0 else 0
|
||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||
lines.append("")
|
||
|
||
# 粉丝团统计
|
||
fansclub_stats = [
|
||
("fansclub_required", "需要粉丝团"),
|
||
("fansclub_manual_needed", "需手动加入"),
|
||
("fansclub_unresolved", "未解决"),
|
||
]
|
||
fansclub_total = sum(counters.get(key, 0) for key, _ in fansclub_stats)
|
||
if fansclub_total > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("粉丝团相关统计")
|
||
lines.append("=" * 60)
|
||
for key, label in fansclub_stats:
|
||
val = counters.get(key, 0)
|
||
if val > 0:
|
||
percentage = (
|
||
(val / fansclub_total) * 100 if fansclub_total > 0 else 0
|
||
)
|
||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||
lines.append("")
|
||
|
||
# 直播间切换统计
|
||
switch_val = counters.get("switch_room", 0)
|
||
if switch_val > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("直播间切换统计")
|
||
lines.append("=" * 60)
|
||
lines.append(f"总切换次数: {switch_val}")
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
lines.append(f"切换频率: {switch_val / hours:.1f} 次/小时")
|
||
lines.append("")
|
||
switch_reasons = [
|
||
("switch_room_no_fudai", "无福袋"),
|
||
("switch_room_participants", "人数不符合"),
|
||
("switch_room_value", "价值不符合"),
|
||
("switch_room_content", "内容不符合"),
|
||
("switch_room_countdown", "倒计时不符合"),
|
||
("switch_room_attend_fail", "参与失败"),
|
||
]
|
||
for key, label in switch_reasons:
|
||
val = counters.get(key, 0)
|
||
if val > 0:
|
||
percentage = (val / switch_val) * 100 if switch_val > 0 else 0
|
||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||
lines.append("")
|
||
|
||
# 预约相关统计
|
||
reservation_stats = [
|
||
("reservation_back_verify_ok", "预约回退校验成功"),
|
||
("reservation_back_verify_fail", "预约回退校验失败"),
|
||
("reservation_drop_low_value", "预约丢弃低价值"),
|
||
("reservation_clear", "清空预约队列"),
|
||
]
|
||
reservation_total = sum(
|
||
counters.get(key, 0) for key, _ in reservation_stats
|
||
)
|
||
if reservation_total > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("预约相关统计")
|
||
lines.append("=" * 60)
|
||
verify_ok = counters.get("reservation_back_verify_ok", 0)
|
||
verify_fail = counters.get("reservation_back_verify_fail", 0)
|
||
verify_total = verify_ok + verify_fail
|
||
if verify_total > 0:
|
||
verify_rate = (verify_ok / verify_total) * 100
|
||
lines.append(
|
||
f"回退校验成功率: {verify_rate:.1f}% ({verify_ok}/{verify_total})"
|
||
)
|
||
lines.append("")
|
||
for key, label in reservation_stats:
|
||
val = counters.get(key, 0)
|
||
if val > 0:
|
||
lines.append(f" {label}: {val}")
|
||
lines.append("")
|
||
|
||
# 错误统计
|
||
error_stats = [
|
||
("fudai_open_error", "打开福袋异常"),
|
||
("fudai_open_error_too_many", "打开失败次数过多"),
|
||
]
|
||
error_total = sum(counters.get(key, 0) for key, _ in error_stats)
|
||
if error_total > 0:
|
||
lines.append("=" * 60)
|
||
lines.append("错误统计")
|
||
lines.append("=" * 60)
|
||
for key, label in error_stats:
|
||
val = counters.get(key, 0)
|
||
if val > 0:
|
||
lines.append(f" {label}: {val}")
|
||
lines.append("")
|
||
|
||
# 价值统计(从事件中提取)
|
||
events = stats.get("events", [])
|
||
prize_values = []
|
||
for event in events:
|
||
meta = event.get("meta", {})
|
||
if "prize_value_yuan" in meta and meta["prize_value_yuan"] is not None:
|
||
try:
|
||
prize_values.append(float(meta["prize_value_yuan"]))
|
||
except (ValueError, TypeError):
|
||
pass
|
||
|
||
if prize_values:
|
||
lines.append("=" * 60)
|
||
lines.append("价值统计")
|
||
lines.append("=" * 60)
|
||
total_value = sum(prize_values)
|
||
avg_value = total_value / len(prize_values)
|
||
max_value = max(prize_values)
|
||
min_value = min(prize_values)
|
||
lines.append(f"识别到的福袋总数: {len(prize_values)}")
|
||
lines.append(f"总价值: {total_value:.2f} 元")
|
||
lines.append(f"平均价值: {avg_value:.2f} 元")
|
||
lines.append(f"最高价值: {max_value:.2f} 元")
|
||
lines.append(f"最低价值: {min_value:.2f} 元")
|
||
|
||
# 价值分布
|
||
high_value_count = sum(1 for v in prize_values if v >= 500)
|
||
medium_value_count = sum(1 for v in prize_values if 100 <= v < 500)
|
||
low_value_count = sum(1 for v in prize_values if v < 100)
|
||
lines.append("")
|
||
lines.append("价值分布:")
|
||
lines.append(
|
||
f" 高价值(≥500元): {high_value_count} ({high_value_count/len(prize_values)*100:.1f}%)"
|
||
)
|
||
lines.append(
|
||
f" 中价值(100-500元): {medium_value_count} ({medium_value_count/len(prize_values)*100:.1f}%)"
|
||
)
|
||
lines.append(
|
||
f" 低价值(<100元): {low_value_count} ({low_value_count/len(prize_values)*100:.1f}%)"
|
||
)
|
||
lines.append("")
|
||
|
||
# 最近一次福袋信息
|
||
fudai_last = stats.get("fudai_last", {})
|
||
if fudai_last.get("content") or fudai_last.get("countdown"):
|
||
lines.append("=" * 60)
|
||
lines.append("最近一次福袋信息")
|
||
lines.append("=" * 60)
|
||
lines.append(f"内容: {fudai_last.get('content') or '-'}")
|
||
lines.append(f"倒计时: {fudai_last.get('countdown') or '-'}")
|
||
participants = fudai_last.get("participants")
|
||
copies = fudai_last.get("copies")
|
||
if participants is not None and copies is not None:
|
||
lines.append(f"参与人数/份数: {participants} / {copies}")
|
||
if participants > 0 and copies > 0:
|
||
ratio = participants / copies
|
||
lines.append(f" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})")
|
||
prize_value = fudai_last.get("prize_value_yuan")
|
||
if prize_value is not None:
|
||
lines.append(f"奖品价值: {prize_value} 元")
|
||
updated_ts = fudai_last.get("updated_ts")
|
||
if updated_ts:
|
||
import datetime
|
||
|
||
dt = datetime.datetime.fromtimestamp(updated_ts)
|
||
lines.append(f"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
lines.append("")
|
||
|
||
# 中奖记录
|
||
wins = stats.get("wins", [])
|
||
if wins:
|
||
lines.append("=" * 60)
|
||
lines.append(f"最近中奖记录(显示最近 {len(wins)} 条)")
|
||
lines.append("=" * 60)
|
||
for i, win in enumerate(wins[-10:], 1): # 只显示最近10条
|
||
import datetime
|
||
|
||
ts = win.get("ts", 0)
|
||
dt_str = (
|
||
datetime.datetime.fromtimestamp(ts).strftime(
|
||
"%Y-%m-%d %H:%M:%S"
|
||
)
|
||
if ts
|
||
else "-"
|
||
)
|
||
lines.append(f"\n[{i}] 时间: {dt_str}")
|
||
if win.get("content"):
|
||
lines.append(f" 内容: {win.get('content')}")
|
||
if win.get("prize_value_yuan"):
|
||
lines.append(f" 价值: {win.get('prize_value_yuan')} 元")
|
||
if win.get("participants") and win.get("copies"):
|
||
lines.append(
|
||
f" 人数/份数: {win.get('participants')} / {win.get('copies')}"
|
||
)
|
||
|
||
# 确保至少显示基本信息
|
||
if not lines:
|
||
lines.append("=" * 60)
|
||
lines.append("统计信息")
|
||
lines.append("=" * 60)
|
||
lines.append("暂无统计数据")
|
||
lines.append("")
|
||
lines.append("提示:请先运行程序以收集统计数据")
|
||
|
||
stats_text.delete("1.0", "end")
|
||
stats_text.insert("1.0", "\n".join(lines))
|
||
except Exception as e:
|
||
import traceback
|
||
|
||
stats_text.delete("1.0", "end")
|
||
error_detail = traceback.format_exc()
|
||
stats_text.insert(
|
||
"1.0", f"刷新统计信息失败:{e}\n\n详细信息:\n{error_detail}"
|
||
)
|
||
|
||
ttk.Button(stats_top, text="刷新", command=refresh_stats).pack(side=LEFT)
|
||
|
||
# 预约队列显示
|
||
reservation_top = ttk.Frame(reservation_tab)
|
||
reservation_top.pack(fill=X, padx=10, pady=(10, 0))
|
||
reservation_text = ScrolledText(reservation_tab)
|
||
reservation_text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||
try:
|
||
reservation_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
|
||
def refresh_reservations():
|
||
path = os.path.join(os.path.dirname(__file__), "state", "reservations.json")
|
||
try:
|
||
if os.path.exists(path):
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
reservation_text.delete("1.0", "end")
|
||
reservation_text.insert(
|
||
"1.0", json.dumps(data, ensure_ascii=False, indent=2)
|
||
)
|
||
else:
|
||
reservation_text.delete("1.0", "end")
|
||
reservation_text.insert("1.0", "暂无预约队列数据")
|
||
except Exception as e:
|
||
reservation_text.delete("1.0", "end")
|
||
reservation_text.insert("1.0", f"读取预约队列失败:{e}")
|
||
|
||
ttk.Button(reservation_top, text="刷新", command=refresh_reservations).pack(
|
||
side=LEFT
|
||
)
|
||
|
||
# 高价值房间显示
|
||
high_value_top = ttk.Frame(high_value_tab)
|
||
high_value_top.pack(fill=X, padx=10, pady=(10, 0))
|
||
high_value_text = ScrolledText(high_value_tab)
|
||
high_value_text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||
try:
|
||
high_value_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
|
||
def refresh_high_value_rooms():
|
||
path = os.path.join(os.path.dirname(__file__), "state", "high_value_rooms.json")
|
||
try:
|
||
if os.path.exists(path):
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
high_value_text.delete("1.0", "end")
|
||
high_value_text.insert(
|
||
"1.0", json.dumps(data, ensure_ascii=False, indent=2)
|
||
)
|
||
else:
|
||
high_value_text.delete("1.0", "end")
|
||
high_value_text.insert("1.0", "暂无高价值房间数据")
|
||
except Exception as e:
|
||
high_value_text.delete("1.0", "end")
|
||
high_value_text.insert("1.0", f"读取高价值房间失败:{e}")
|
||
|
||
ttk.Button(high_value_top, text="刷新", command=refresh_high_value_rooms).pack(
|
||
side=LEFT
|
||
)
|
||
|
||
# 行为日志显示(点击/识别/耗时)
|
||
actions_log_top = ttk.Frame(actions_log_tab)
|
||
actions_log_top.pack(fill=X, padx=10, pady=(10, 0))
|
||
actions_log_text = ScrolledText(actions_log_tab)
|
||
actions_log_text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||
try:
|
||
actions_log_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
|
||
actions_filter_var = tk.StringVar(value="")
|
||
|
||
def refresh_actions_log():
|
||
"""读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。"""
|
||
path = os.path.join(os.path.dirname(__file__), "logs", "actions.log")
|
||
try:
|
||
if os.path.exists(path):
|
||
# 仿照 web_gui 的实现:只读最后一小段,避免文件巨大
|
||
size = os.path.getsize(path)
|
||
if size == 0:
|
||
actions_log_text.delete("1.0", "end")
|
||
actions_log_text.insert("1.0", "行为日志文件为空")
|
||
return
|
||
|
||
read_bytes = min(size, 65536)
|
||
with open(path, "rb") as f:
|
||
if read_bytes < size:
|
||
f.seek(-read_bytes, os.SEEK_END)
|
||
data = f.read()
|
||
# 尝试多种编码方式
|
||
try:
|
||
# 先尝试 utf-8-sig(带BOM)
|
||
text = data.decode("utf-8-sig", errors="replace")
|
||
except Exception:
|
||
try:
|
||
# 再尝试 utf-8
|
||
text = data.decode("utf-8", errors="replace")
|
||
except Exception:
|
||
# 最后尝试 gbk(Windows常见编码)
|
||
text = data.decode("gbk", errors="replace")
|
||
lines = text.splitlines()
|
||
# 只取最近 300 行
|
||
tail = lines[-300:]
|
||
|
||
# 关键字筛选:若填写了筛选词,只保留包含该关键字的行
|
||
kw = actions_filter_var.get().strip()
|
||
if kw:
|
||
tail = [ln for ln in tail if kw in ln]
|
||
|
||
# 保存当前滚动位置,避免刷新时自动置顶
|
||
try:
|
||
scroll_position = actions_log_text.yview()[0] # 获取当前滚动位置(顶部可见位置的比例)
|
||
except Exception:
|
||
scroll_position = 0.0
|
||
|
||
actions_log_text.delete("1.0", "end")
|
||
if tail:
|
||
actions_log_text.insert("1.0", "\n".join(tail))
|
||
else:
|
||
actions_log_text.insert("1.0", "暂无匹配的行为日志")
|
||
|
||
# 恢复之前的滚动位置,避免自动置顶
|
||
try:
|
||
actions_log_text.yview_moveto(scroll_position)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
actions_log_text.delete("1.0", "end")
|
||
actions_log_text.insert(
|
||
"1.0", "暂无行为日志(logs/actions.log 不存在)"
|
||
)
|
||
except Exception as e:
|
||
actions_log_text.delete("1.0", "end")
|
||
actions_log_text.insert("1.0", f"读取行为日志失败:{e}")
|
||
|
||
ttk.Label(actions_log_top, text="关键字筛选:").pack(side=LEFT)
|
||
ttk.Entry(actions_log_top, textvariable=actions_filter_var, width=16).pack(
|
||
side=LEFT, padx=(0, 8)
|
||
)
|
||
ttk.Button(actions_log_top, text="刷新", command=refresh_actions_log).pack(
|
||
side=LEFT, padx=(0, 10)
|
||
)
|
||
|
||
# 行为日志搜索功能
|
||
ttk.Separator(actions_log_top, orient="vertical").pack(side=LEFT, fill=Y, padx=5, pady=3)
|
||
ttk.Label(actions_log_top, text="搜索:").pack(side=LEFT)
|
||
|
||
actions_search_var = tk.StringVar(value="")
|
||
actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20)
|
||
actions_search_entry.pack(side=LEFT, padx=(0, 5))
|
||
|
||
actions_search_matches = []
|
||
actions_current_match_index = -1
|
||
|
||
def search_in_actions_log(direction=1):
|
||
"""在行为日志中搜索文本"""
|
||
nonlocal actions_search_matches, actions_current_match_index
|
||
|
||
search_text = actions_search_var.get().strip()
|
||
if not search_text:
|
||
actions_log_text.tag_remove("search_highlight", "1.0", "end")
|
||
actions_log_text.tag_remove("search_current", "1.0", "end")
|
||
actions_search_matches = []
|
||
actions_current_match_index = -1
|
||
return
|
||
|
||
content = actions_log_text.get("1.0", "end-1c")
|
||
if not content:
|
||
return
|
||
|
||
actions_log_text.tag_remove("search_highlight", "1.0", "end")
|
||
actions_log_text.tag_remove("search_current", "1.0", "end")
|
||
|
||
actions_log_text.tag_config("search_highlight", background="yellow")
|
||
actions_log_text.tag_config("search_current", background="orange")
|
||
|
||
actions_search_matches = []
|
||
start_pos = 0 # 使用整数索引
|
||
search_text_lower = search_text.lower()
|
||
content_lower = content.lower()
|
||
|
||
while True:
|
||
pos = content_lower.find(search_text_lower, start_pos)
|
||
if pos == -1:
|
||
break
|
||
|
||
line_start = content[:pos].rfind("\n") + 1
|
||
line_num = content[:pos].count("\n") + 1
|
||
col_num = pos - line_start
|
||
|
||
start_index = f"{line_num}.{col_num}"
|
||
end_index = f"{line_num}.{col_num + len(search_text)}"
|
||
|
||
actions_search_matches.append((start_index, end_index))
|
||
start_pos = pos + 1
|
||
|
||
if not actions_search_matches:
|
||
actions_current_match_index = -1
|
||
return
|
||
|
||
for start_idx, end_idx in actions_search_matches:
|
||
actions_log_text.tag_add("search_highlight", start_idx, end_idx)
|
||
|
||
if direction == 1:
|
||
actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches)
|
||
else:
|
||
actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches)
|
||
|
||
if actions_current_match_index >= 0:
|
||
start_idx, end_idx = actions_search_matches[actions_current_match_index]
|
||
actions_log_text.tag_add("search_current", start_idx, end_idx)
|
||
actions_log_text.see(start_idx)
|
||
actions_log_text.mark_set("insert", start_idx)
|
||
|
||
def search_next_in_actions():
|
||
search_in_actions_log(1)
|
||
|
||
def search_prev_in_actions():
|
||
search_in_actions_log(-1)
|
||
|
||
def clear_search_in_actions():
|
||
nonlocal actions_search_matches, actions_current_match_index
|
||
actions_search_var.set("")
|
||
actions_log_text.tag_remove("search_highlight", "1.0", "end")
|
||
actions_log_text.tag_remove("search_current", "1.0", "end")
|
||
actions_search_matches = []
|
||
actions_current_match_index = -1
|
||
|
||
def on_actions_search_entry_key(event):
|
||
if event.keysym == "Return":
|
||
search_next_in_actions()
|
||
|
||
actions_search_entry.bind("<KeyPress>", on_actions_search_entry_key)
|
||
|
||
ttk.Button(actions_log_top, text="搜索", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(actions_log_top, text="上一个", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(actions_log_top, text="下一个", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))
|
||
ttk.Button(actions_log_top, text="清除", command=clear_search_in_actions).pack(side=LEFT)
|
||
|
||
# OCR结果显示
|
||
ocr_results_top = ttk.Frame(ocr_results_tab)
|
||
ocr_results_top.pack(fill=X, padx=10, pady=(10, 0))
|
||
ocr_results_text = ScrolledText(ocr_results_tab)
|
||
ocr_results_text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||
try:
|
||
ocr_results_text.configure(font=("Consolas", 10))
|
||
except Exception:
|
||
pass
|
||
|
||
def update_ocr_results(results):
|
||
"""更新OCR结果标签页的显示"""
|
||
try:
|
||
lines = []
|
||
lines.append("=" * 80)
|
||
lines.append("OCR识别结果(基于最新截图)")
|
||
lines.append("=" * 80)
|
||
lines.append("")
|
||
|
||
if not results:
|
||
lines.append('暂无OCR结果,请先点击"截图+OCR"按钮')
|
||
else:
|
||
# 按区域名称分组显示
|
||
for region_name, desc, text_result, status in results:
|
||
lines.append(f"【{region_name}】{desc}")
|
||
lines.append(f" 状态: {status}")
|
||
if text_result:
|
||
# 如果文本较长,分行显示
|
||
if len(text_result) > 100:
|
||
lines.append(f" 识别文本: {text_result[:100]}...")
|
||
lines.append(f" (完整文本: {text_result})")
|
||
else:
|
||
lines.append(f" 识别文本: {text_result}")
|
||
else:
|
||
lines.append(" 识别文本: (空)")
|
||
lines.append("")
|
||
|
||
ocr_results_text.delete("1.0", "end")
|
||
ocr_results_text.insert("1.0", "\n".join(lines))
|
||
ocr_results_text.see("1.0")
|
||
except Exception as e:
|
||
ocr_results_text.delete("1.0", "end")
|
||
ocr_results_text.insert("1.0", f"更新OCR结果失败:{e}")
|
||
|
||
ttk.Button(
|
||
ocr_results_top, text="刷新", command=lambda: update_ocr_results([])
|
||
).pack(side=LEFT)
|
||
ttk.Label(ocr_results_top, text='(点击"截图+OCR"按钮自动更新)').pack(
|
||
side=LEFT, padx=(10, 0)
|
||
)
|
||
|
||
pump_logs()
|
||
|
||
def delayed_refresh_preview() -> None:
|
||
if image_var.get():
|
||
refresh_preview()
|
||
|
||
root.after(300, delayed_refresh_preview) # type: ignore[arg-type]
|
||
root.after(500, refresh_stats) # type: ignore[arg-type]
|
||
root.after(500, refresh_reservations) # type: ignore[arg-type]
|
||
root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]
|
||
root.after(500, refresh_actions_log) # type: ignore[arg-type]
|
||
|
||
# 定期刷新行为日志(每2秒)
|
||
def auto_refresh_actions_log() -> None:
|
||
refresh_actions_log()
|
||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||
|
||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||
|
||
# 定期刷新统计信息(每3秒)
|
||
def auto_refresh_stats() -> None:
|
||
if runner.is_running():
|
||
refresh_stats()
|
||
root.after(3000, auto_refresh_stats) # type: ignore[arg-type]
|
||
|
||
auto_refresh_stats()
|
||
|
||
def on_close():
|
||
try:
|
||
runner.stop()
|
||
except Exception:
|
||
pass
|
||
root.destroy()
|
||
|
||
root.protocol("WM_DELETE_WINDOW", on_close)
|
||
refresh_devices()
|
||
root.mainloop()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
from version import print_version_banner
|
||
|
||
print_version_banner("gui_app")
|
||
except Exception:
|
||
pass
|
||
main()
|