Files
douyin_guaji-main/gui/gui_app.py
T

2123 lines
86 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import logging
import os
import queue
import re
import sys
import threading
import warnings
from datetime import datetime
from typing import Any, Callable
# 确保项目根目录在 Python 路径中(支持直接运行 gui/gui_app.py)
_script_dir = os.path.dirname(os.path.abspath(__file__))
_project_root = os.path.dirname(_script_dir)
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
from PIL import Image, ImageTk # type: ignore[import]
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
from gui.gui_core import (
RunParams,
Runner,
find_adb_executable,
list_adb_devices,
enable_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
get_device_ip,
auto_connect_wifi_adb,
is_device_wifi_connected,
get_connected_wifi_devices,
read_config,
write_config,
)
from gui.gui_core_pkg import (
DiscoveredDevice,
clear_last_wifi_target,
discover_adb_devices,
get_last_wifi_target,
get_local_subnet,
pick_best_match,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target, query_device_model
from douyin.core.path_config import get_logs_dir
from gui.components.mapping_table import create_mapping_tab
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
from gui.components.screenshot_action import do_screenshot as _do_screenshot_impl
from gui.components.actions_log_view import (
configure_actions_log_colors as _configure_actions_log_colors_impl,
refresh_actions_log as _refresh_actions_log_impl,
)
from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog as _open_scan_pick_dialog_impl
from gui.components.wifi_adb_reconnect import try_reconnect_last_wifi as _try_reconnect_last_wifi_impl
from gui.components.ocr_results_view import update_ocr_results as _update_ocr_results_impl
from gui.components.log_pump import pump_logs as _pump_logs_impl
from gui.components.win_record_view import (
WinRecordView as _WinRecordView,
refresh_win_record as _refresh_win_record_impl,
on_win_list_select as _on_win_list_select_impl,
open_win_folder as _open_win_folder_impl,
load_false_positives as _load_false_positives_impl,
save_false_positives as _save_false_positives_impl,
)
from gui.components.preview_view import (
PreviewView as _PreviewView,
scan_image_files as _scan_image_files_impl,
update_image_list as _update_image_list_impl,
refresh_preview as _refresh_preview_impl,
_load_and_fit_image as _load_and_fit_image_impl,
open_pic_folder as _open_pic_folder_impl,
async_refresh_preview as _async_refresh_preview_impl,
)
from gui.components.wifi_adb_one_click_scan import (
on_scan_one_click as _on_scan_one_click_impl,
_handle_scan_result as _handle_scan_result_impl,
)
from gui.components.run_log_view import refresh_run_log as _refresh_run_log_impl
from gui.components.text_search import generic_search_widget as _generic_search_widget_impl
from gui.components.logging_config_io import save_logging_config as _save_logging_config_impl
from gui.components.run_params_builder import get_params as _get_params_impl
from gui.components.config_io import (
load_config_to_ui as _load_config_to_ui_impl,
save_ui_to_config as _save_ui_to_config_impl,
)
from gui.components.debug_tab import setup_debug_tab
from gui.components.logging_tab import setup_logging_tab
from gui.components.yanghao_tab import setup_yanghao_tab
from gui.components.reservation_tab import setup_reservation_tab
from gui.components.run_tab import setup_run_tab
# 导入日志颜色配置模块
try:
from gui.components.log_color_config import (
get_color_config,
apply_operation_color,
get_operation_type,
)
except ImportError:
# 如果模块不存在,使用空函数作为回退
def get_color_config(theme: str = "litera"):
return {}
def apply_operation_color(*args, **kwargs):
pass
def get_operation_type(line: str) -> str | None:
return None
# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
# 模块级 logger:内部"日志写入失败 / pump_logs 异常"等错误统一走 logging
_LOGGER = logging.getLogger("gui.gui_app")
def format_gui_log_line(line: str) -> str:
"""将完整日志行转换为 GUI 显示用的精简版本。
实际实现位于 gui.components.log_viewer,此处仅作 re-export,
失败时回退到原始字符串。
"""
try:
from gui.components.log_viewer import format_gui_log_line as _impl
return _impl(line)
except Exception:
return (line or "").rstrip("\n")
def main():
# 主题优先级:使用 config 中的 gui.theme(若有),否则使用默认明亮主题 'litera'
cfg_theme = "darkly"
try:
cfg_theme = read_config().get("gui", {}).get("theme", "litera") or "litera"
except Exception:
cfg_theme = "litera"
# 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
# 使用 config 中指定的主题名
root = tb.Window(themename=cfg_theme)
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()
# 常量兜底:部分主题常量未提供时使用字符串
BOTTOM = "bottom"
# W 常量在部分导入路径中可能不存在,兜底为 'w'(grid sticky 使用)
W = "w"
root.title("抖音福袋挂机 - 可视化控制台")
root.geometry("1400x900") # 增大窗口尺寸,提供更多空间
q: queue.Queue[str] = queue.Queue()
# 线程安全的日志文件写入器(已抽到 gui/components/log_writer)
from gui.components.log_writer import ThreadSafeLogWriter
log_writer = ThreadSafeLogWriter()
# 日志格式化已移至模块级别函数 format_gui_log_line()
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 状态设备(可能未授权/未连接)")
def save_logging_config():
_save_logging_config_impl(
vars_={
"logging_format_mode_var": logging_format_mode_var,
"logging_beautify_var": logging_beautify_var,
"logging_color_var": logging_color_var,
"logging_show_timestamps_var": logging_show_timestamps_var,
"logging_use_dated_logs_var": logging_use_dated_logs_var,
"logging_debug_level_var": logging_debug_level_var,
"logging_error_level_var": logging_error_level_var,
"logging_action_format_var": logging_action_format_var,
"logging_enable_monitor_var": logging_enable_monitor_var,
"logging_keep_days_var": logging_keep_days_var,
"logging_compress_logs_var": logging_compress_logs_var,
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
"logging_compress_after_days_var": logging_compress_after_days_var,
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
"logging_performance_enabled_var": logging_performance_enabled_var,
"logging_track_functions_var": logging_track_functions_var,
"log_unified_enabled_var": log_unified_enabled_var,
"log_unified_path_var": log_unified_path_var,
"gui_theme_var": gui_theme_var,
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
},
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
refresh_devices_btn = ttk.Button(top, text="刷新设备", command=refresh_devices)
refresh_devices_btn.pack(side=LEFT, padx=(0, 8))
# 一键扫描局域网 ADB 设备并自动连接(同 WiFi 下设备已开 5555 / 已授权时无需 USB)
scan_connect_btn = ttk.Button(top, text="扫描 WiFi")
scan_connect_btn.pack(side=LEFT, padx=(0, 20))
_scan_busy = {"flag": False}
def _try_reconnect_last_wifi():
_try_reconnect_last_wifi_impl(
root,
adb_exe=adb_exe,
device_var=device_var,
on_line=on_line,
refresh_devices=refresh_devices,
)
# 启动时延迟一点,等界面创建完成再尝试重连
root.after(300, _try_reconnect_last_wifi)
def _on_scan_one_click():
_on_scan_one_click_impl(
adb_exe=adb_exe,
scan_btn=scan_connect_btn,
scan_busy=_scan_busy,
root=root,
on_line=on_line,
device_var=device_var,
refresh_devices=refresh_devices,
open_pick_dialog=_open_scan_pick_dialog,
)
def _handle_scan_result(devs):
_handle_scan_result_impl(
devs,
on_line=on_line,
device_var=device_var,
refresh_devices=refresh_devices,
open_pick_dialog=_open_scan_pick_dialog,
)
def _open_scan_pick_dialog(devs):
_open_scan_pick_dialog_impl(
root,
devs,
device_var=device_var,
on_line=on_line,
refresh_devices=refresh_devices,
)
scan_connect_btn.config(command=_on_scan_one_click)
# WiFi ADB 功能
wifi_adb_btn = ttk.Button(
top,
text="WiFi ADB",
command=lambda: _open_wifi_adb_dialog(
root,
adb_exe=adb_exe,
on_line=on_line,
refresh_devices=refresh_devices,
),
)
wifi_adb_btn.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)
)
# 连续无福袋退出阈值变量(提前声明,实际声明在下方唯一位置以便与配置同步)
# (变量将在后面统一声明,避免重复创建 IntVar 导致绑定不一致)
# 启用返回键回退开关变量(提前声明)
enable_back_on_misses_var = tk.BooleanVar(
value=bool(cfg.get("enable_back_on_misses", True))
)
swipe_down_back_enabled_var = tk.BooleanVar(
value=bool(cfg.get("swipe_down_back_enabled", False))
)
swipe_down_back_count_var = tk.IntVar(
value=int(cfg.get("swipe_down_back_count", 3) or 3)
)
# 中部:左侧配置(使用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) # 右侧日志/预览区域
# 右侧为日志/预览区域(保持原样)
# right_notebook previously added here; mapping tab will attach to the left notebook
# 左侧使用Notebook标签页组织配置
left_notebook = ttk.Notebook(left_wrap)
left_notebook.pack(fill=BOTH, expand=True)
# 左侧 Notebook 中不再添加映射表页(已移至右侧)
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)
)
reset_after_swipes_action_var = tk.StringVar(
value=str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
)
enable_back_on_misses_var = tk.BooleanVar(
value=bool(cfg.get("enable_back_on_misses", True))
)
# 流式后台截图开关(默认启用)
streaming_enabled_var = tk.BooleanVar(
value=bool(cfg.get("enable_streaming_screenshot", True))
)
# 按需求:删除"自动养号/随机等待/轻微扰动/定时休息"等设置,仅保留"推荐页养号(爱心/收藏/评论)"配置。
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()
)
fansclub_click_delay_var = tk.DoubleVar(
value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6)
)
fansclub_auto_wait_var = tk.DoubleVar(
value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
)
fansclub_manual_wait_var = tk.DoubleVar(
value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
)
# 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", 300) or 300)
)
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_fudai_poll_before_seconds_var = tk.DoubleVar(
value=float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
)
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))
)
high_value_room_revisit_min_interval_seconds_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
)
high_value_room_revisit_max_per_run_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_per_run", 5))
)
high_value_room_revisit_min_prize_value_var = tk.DoubleVar(
value=float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
)
high_value_room_revisit_max_age_days_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_age_days", 30))
)
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_back_verify_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.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_disable_content_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_content_recognition", False))
)
fudai_disable_task_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_task_recognition", False))
)
fudai_exit_after_misses_var = tk.IntVar(
value=int(cfg.get("fudai_exit_after_misses", 30) or 30)
)
fudai_click_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.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)
)
# 滑动速度(毫秒)
swipe_duration_ms_var = tk.IntVar(
value=int(cfg.get("swipe_duration_ms", 600) or 600)
)
# 滑动坐标配置
swipe_up_start_y_var = tk.IntVar(
value=int(cfg.get("swipe_up_start_y", 1200) or 1200)
)
swipe_up_end_y_var = tk.IntVar(value=int(cfg.get("swipe_up_end_y", 600) or 600))
# 推荐页养号:爱心/收藏/评论(基于图标模板匹配 + 坐标点击)
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_only_var = tk.BooleanVar(value=bool(cfg.get("yanghao_only", False)))
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_dwell_on_action_min_var = tk.DoubleVar(
value=float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
)
yg_dwell_on_action_max_var = tk.DoubleVar(
value=float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
)
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_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_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)
)
stage_diag_verbose_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
)
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)
)
# 购物红包背景红色占比阈值(0.0~1.0,默认0.15)
shopping_redpacket_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
)
# 调试图像开关 & 清理相关变量
debug_captures_enabled_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("enabled", False)
if isinstance(cfg.get("debug_captures"), dict)
else False
)
)
# 调试图像清理相关变量
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
)
)
debug_captures_async_save_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("async_save", True)
if isinstance(cfg.get("debug_captures"), dict)
else True
)
)
debug_captures_log_on_complete_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("log_on_complete", False)
if isinstance(cfg.get("debug_captures"), dict)
else False
)
)
# 异步保存计数显示变量
debug_async_success_var = tk.IntVar(value=0)
debug_async_failure_var = tk.IntVar(value=0)
# 日志配置变量
logging_beautify_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("beautify_output", True))
)
logging_color_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("color_output", True))
)
logging_show_timestamps_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("show_timestamps", True))
)
logging_use_dated_logs_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("use_dated_logs", True))
)
logging_enable_monitor_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("enable_monitor", True))
)
log_unified_enabled_var = tk.BooleanVar(
value=bool(cfg.get("log_unified_enabled", True))
)
log_unified_path_var = tk.StringVar(
value=str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
)
logging_keep_days_var = tk.IntVar(
value=int(cfg.get("logging", {}).get("keep_days", 30) or 30)
)
logging_compress_logs_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("compress_logs", True))
)
logging_max_total_size_gb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("max_total_size_gb", 10.0) or 10.0)
)
logging_compress_after_days_var = tk.IntVar(
value=int(cfg.get("logging", {}).get("compress_after_days", 7) or 7)
)
logging_performance_enabled_var = tk.BooleanVar(
value=bool(
cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True)
)
)
logging_track_functions_var = tk.BooleanVar(
value=bool(
cfg.get("logging", {})
.get("performance_tracking", {})
.get("track_function_calls", True)
)
)
logging_debug_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("debug_detail_level", "normal"))
)
logging_error_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("error_detail_level", "full"))
)
logging_action_format_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
)
logging_format_mode_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("log_format_mode", "simple"))
)
logging_monitor_warning_mb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("monitor_warning_mb", 500.0) or 500.0)
)
logging_monitor_critical_mb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("monitor_critical_mb", 2000.0) or 2000.0)
)
# GUI 主题变量
gui_theme_var = tk.StringVar(
value=str(cfg.get("gui", {}).get("theme", "litera") or "litera")
)
gui_realtime_refresh_interval_ms_var = tk.IntVar(
value=int(
cfg.get("gui", {})
.get("realtime_status", {})
.get("refresh_interval_ms", 1000)
or 1000
)
)
gui_realtime_tail_items_var = tk.IntVar(
value=int(
cfg.get("gui", {}).get("realtime_status", {}).get("tail_items", 50) or 50
)
)
# 倒计时小于阈值参数
skip_lt_seconds_var = tk.IntVar(
value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)
)
# 创建左侧配置标签页
# 标签页1:运行设置
setup_run_tab(
left_notebook,
vars_={
"enable_back_on_misses_var": enable_back_on_misses_var,
"fudai_exit_after_misses_var": fudai_exit_after_misses_var,
"infinite_loop_var": infinite_loop_var,
"needswitch_var": needswitch_var,
"reset_after_swipes_action_var": reset_after_swipes_action_var,
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
"reset_after_swipes_var": reset_after_swipes_var,
"skip_gt_seconds_var": skip_gt_seconds_var,
"swipe_down_back_count_var": swipe_down_back_count_var,
"swipe_down_back_enabled_var": swipe_down_back_enabled_var,
"wait_minutes_var": wait_minutes_var,
},
)
# 标签页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=0.01,
format="%.2f",
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)
)
# 粉丝团等待/点击延迟设置
row4b = ttk.Frame(cfg_box)
row4b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4b, text="粉丝团点击延迟(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.1,
to=5.0,
increment=0.1,
textvariable=fansclub_click_delay_var,
width=6,
).pack(side=LEFT, padx=(6, 12))
ttk.Label(row4b, text="自动加入等待(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.5,
to=10.0,
increment=0.5,
textvariable=fansclub_auto_wait_var,
width=6,
).pack(side=LEFT, padx=(6, 12))
ttk.Label(row4b, text="手动加入等待(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.5,
to=10.0,
increment=0.5,
textvariable=fansclub_manual_wait_var,
width=6,
).pack(side=LEFT, padx=(6, 0))
# 标签页3:高价值预约
setup_reservation_tab(
left_notebook,
vars_={
"high_value_fudai_after_action_var": high_value_fudai_after_action_var,
"high_value_fudai_enabled_var": high_value_fudai_enabled_var,
"high_value_fudai_join_ahead_seconds_var": high_value_fudai_join_ahead_seconds_var,
"high_value_fudai_max_reservations_var": high_value_fudai_max_reservations_var,
"high_value_fudai_max_swipe_back_var": high_value_fudai_max_swipe_back_var,
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
"high_value_fudai_threshold_yuan_var": high_value_fudai_threshold_yuan_var,
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
"reservation_back_verify_wait_seconds_var": reservation_back_verify_wait_seconds_var,
},
)
# 养号设置标签(后续代码)
_, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text = setup_yanghao_tab(
left_notebook,
vars_={
"fudai_quiet_end_hour_var": fudai_quiet_end_hour_var,
"fudai_quiet_hours_enabled_var": fudai_quiet_hours_enabled_var,
"fudai_quiet_start_hour_var": fudai_quiet_start_hour_var,
"yg_actions_enabled_var": yg_actions_enabled_var,
"yg_comment_prob_var": yg_comment_prob_var,
"yg_dwell_on_action_max_var": yg_dwell_on_action_max_var,
"yg_dwell_on_action_min_var": yg_dwell_on_action_min_var,
"yg_enabled_var": yg_enabled_var,
"yg_fav_prob_var": yg_fav_prob_var,
"yg_icon_match_threshold_var": yg_icon_match_threshold_var,
"yg_icon_roi_size_var": yg_icon_roi_size_var,
"yg_like_prob_var": yg_like_prob_var,
"yg_only_var": yg_only_var,
"yg_recommend_duration_var": yg_recommend_duration_var,
"yg_recommend_interval_var": yg_recommend_interval_var,
"yg_step_screenshot_var": yg_step_screenshot_var,
},
)
setup_debug_tab(left_notebook, vars_={
"attend_button_red_ratio_threshold_var": attend_button_red_ratio_threshold_var,
"coupon_template_match_threshold_var": coupon_template_match_threshold_var,
"debug_async_failure_var": debug_async_failure_var,
"debug_async_success_var": debug_async_success_var,
"debug_captures_async_save_var": debug_captures_async_save_var,
"debug_captures_auto_cleanup_var": debug_captures_auto_cleanup_var,
"debug_captures_enabled_var": debug_captures_enabled_var,
"debug_captures_keep_days_var": debug_captures_keep_days_var,
"debug_captures_log_on_complete_var": debug_captures_log_on_complete_var,
"debug_captures_max_files_var": debug_captures_max_files_var,
"fansclub_join_red_ratio_threshold_var": fansclub_join_red_ratio_threshold_var,
"fudai_click_wait_seconds_var": fudai_click_wait_seconds_var,
"fudai_detail_template_threshold_var": fudai_detail_template_threshold_var,
"fudai_disable_content_recognition_var": fudai_disable_content_recognition_var,
"fudai_disable_task_recognition_var": fudai_disable_task_recognition_var,
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
"fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var,
"fudai_icon_retry_delay_seconds_var": fudai_icon_retry_delay_seconds_var,
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
"live_room_match_threshold_var": live_room_match_threshold_var,
"lucky_draw_red_ratio_threshold_var": lucky_draw_red_ratio_threshold_var,
"shopping_redpacket_red_ratio_threshold_var": shopping_redpacket_red_ratio_threshold_var,
"stage_diag_max_step_time_var": stage_diag_max_step_time_var,
"stage_diag_max_time_var": stage_diag_max_time_var,
"stage_diag_verbose_var": stage_diag_verbose_var,
"swipe_duration_ms_var": swipe_duration_ms_var,
"swipe_up_end_y_var": swipe_up_end_y_var,
"swipe_up_start_y_var": swipe_up_start_y_var,
"switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var,
"enable_ocr_mode1_var": enable_ocr_mode1_var,
})
# 标签页5:日志配置
setup_logging_tab(
left_notebook,
vars_={
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
"gui_theme_var": gui_theme_var,
"log_unified_enabled_var": log_unified_enabled_var,
"log_unified_path_var": log_unified_path_var,
"logging_action_format_var": logging_action_format_var,
"logging_beautify_var": logging_beautify_var,
"logging_color_var": logging_color_var,
"logging_compress_after_days_var": logging_compress_after_days_var,
"logging_compress_logs_var": logging_compress_logs_var,
"logging_debug_level_var": logging_debug_level_var,
"logging_enable_monitor_var": logging_enable_monitor_var,
"logging_error_level_var": logging_error_level_var,
"logging_format_mode_var": logging_format_mode_var,
"logging_keep_days_var": logging_keep_days_var,
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
"logging_performance_enabled_var": logging_performance_enabled_var,
"logging_show_timestamps_var": logging_show_timestamps_var,
"logging_track_functions_var": logging_track_functions_var,
"logging_use_dated_logs_var": logging_use_dated_logs_var,
"streaming_enabled_var": streaming_enabled_var,
},
on_save_logging=save_logging_config,
)
# 标签页7:关键词
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_want(白名单,空=不限制)").pack(
anchor="w", padx=10, pady=(10, 4)
)
want_text = ScrolledText(kw_box, height=6)
want_text.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(
anchor="w", padx=10, pady=(0, 4)
)
not_want_text = ScrolledText(kw_box, height=8)
not_want_text.pack(fill=X, padx=10, pady=(0, 10))
_config_io_vars = {
"attend_button_red_ratio_threshold_var": attend_button_red_ratio_threshold_var,
"auto_join_var": auto_join_var,
"coupon_template_match_threshold_var": coupon_template_match_threshold_var,
"debug_captures_async_save_var": debug_captures_async_save_var,
"debug_captures_auto_cleanup_var": debug_captures_auto_cleanup_var,
"debug_captures_enabled_var": debug_captures_enabled_var,
"debug_captures_keep_days_var": debug_captures_keep_days_var,
"debug_captures_log_on_complete_var": debug_captures_log_on_complete_var,
"debug_captures_max_files_var": debug_captures_max_files_var,
"enable_back_on_misses_var": enable_back_on_misses_var,
"enable_ocr_mode1_var": enable_ocr_mode1_var,
"fansclub_action_var": fansclub_action_var,
"fansclub_auto_wait_var": fansclub_auto_wait_var,
"fansclub_click_delay_var": fansclub_click_delay_var,
"fansclub_join_red_ratio_threshold_var": fansclub_join_red_ratio_threshold_var,
"fansclub_manual_wait_var": fansclub_manual_wait_var,
"fudai_click_wait_seconds_var": fudai_click_wait_seconds_var,
"fudai_detail_template_threshold_var": fudai_detail_template_threshold_var,
"fudai_disable_content_recognition_var": fudai_disable_content_recognition_var,
"fudai_disable_task_recognition_var": fudai_disable_task_recognition_var,
"fudai_exit_after_misses_var": fudai_exit_after_misses_var,
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
"fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var,
"fudai_icon_retry_delay_seconds_var": fudai_icon_retry_delay_seconds_var,
"fudai_quiet_end_hour_var": fudai_quiet_end_hour_var,
"fudai_quiet_hours_enabled_var": fudai_quiet_hours_enabled_var,
"fudai_quiet_start_hour_var": fudai_quiet_start_hour_var,
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
"gui_theme_var": gui_theme_var,
"high_value_fudai_after_action_var": high_value_fudai_after_action_var,
"high_value_fudai_enabled_var": high_value_fudai_enabled_var,
"high_value_fudai_join_ahead_seconds_var": high_value_fudai_join_ahead_seconds_var,
"high_value_fudai_max_reservations_var": high_value_fudai_max_reservations_var,
"high_value_fudai_max_swipe_back_var": high_value_fudai_max_swipe_back_var,
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
"high_value_fudai_threshold_yuan_var": high_value_fudai_threshold_yuan_var,
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
"infinite_loop_var": infinite_loop_var,
"live_room_match_threshold_var": live_room_match_threshold_var,
"log_unified_enabled_var": log_unified_enabled_var,
"log_unified_path_var": log_unified_path_var,
"logging_action_format_var": logging_action_format_var,
"logging_beautify_var": logging_beautify_var,
"logging_color_var": logging_color_var,
"logging_compress_after_days_var": logging_compress_after_days_var,
"logging_compress_logs_var": logging_compress_logs_var,
"logging_debug_level_var": logging_debug_level_var,
"logging_enable_monitor_var": logging_enable_monitor_var,
"logging_error_level_var": logging_error_level_var,
"logging_format_mode_var": logging_format_mode_var,
"logging_keep_days_var": logging_keep_days_var,
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
"logging_performance_enabled_var": logging_performance_enabled_var,
"logging_show_timestamps_var": logging_show_timestamps_var,
"logging_track_functions_var": logging_track_functions_var,
"logging_use_dated_logs_var": logging_use_dated_logs_var,
"lucky_draw_red_ratio_threshold_var": lucky_draw_red_ratio_threshold_var,
"max_participants_var": max_participants_var,
"min_participants_var": min_participants_var,
"min_value_var": min_value_var,
"needswitch_var": needswitch_var,
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
"reservation_back_verify_wait_seconds_var": reservation_back_verify_wait_seconds_var,
"reset_after_swipes_action_var": reset_after_swipes_action_var,
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
"reset_after_swipes_var": reset_after_swipes_var,
"shopping_redpacket_red_ratio_threshold_var": shopping_redpacket_red_ratio_threshold_var,
"skip_gt_seconds_var": skip_gt_seconds_var,
"skip_lt_seconds_var": skip_lt_seconds_var,
"stage_diag_max_step_time_var": stage_diag_max_step_time_var,
"stage_diag_max_time_var": stage_diag_max_time_var,
"stage_diag_verbose_var": stage_diag_verbose_var,
"streaming_enabled_var": streaming_enabled_var,
"swipe_down_back_count_var": swipe_down_back_count_var,
"swipe_down_back_enabled_var": swipe_down_back_enabled_var,
"swipe_duration_ms_var": swipe_duration_ms_var,
"swipe_up_end_y_var": swipe_up_end_y_var,
"swipe_up_start_y_var": swipe_up_start_y_var,
"switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var,
"wait_minutes_var": wait_minutes_var,
"y_var": y_var,
"yg_actions_enabled_var": yg_actions_enabled_var,
"yg_after_dwell_direction_var": yg_after_dwell_direction_var,
"yg_after_dwell_distance_var": yg_after_dwell_distance_var,
"yg_comment_btn_x_var": yg_comment_btn_x_var,
"yg_comment_btn_y_var": yg_comment_btn_y_var,
"yg_comment_close_x_var": yg_comment_close_x_var,
"yg_comment_close_y_var": yg_comment_close_y_var,
"yg_comment_input_x_var": yg_comment_input_x_var,
"yg_comment_input_y_var": yg_comment_input_y_var,
"yg_comment_prob_var": yg_comment_prob_var,
"yg_comment_send_x_var": yg_comment_send_x_var,
"yg_comment_send_y_var": yg_comment_send_y_var,
"yg_dwell_on_action_max_var": yg_dwell_on_action_max_var,
"yg_dwell_on_action_min_var": yg_dwell_on_action_min_var,
"yg_enabled_var": yg_enabled_var,
"yg_fav_icon_x_var": yg_fav_icon_x_var,
"yg_fav_icon_y_var": yg_fav_icon_y_var,
"yg_fav_prob_var": yg_fav_prob_var,
"yg_fav_roi_offset_x_var": yg_fav_roi_offset_x_var,
"yg_fav_roi_offset_y_var": yg_fav_roi_offset_y_var,
"yg_fav_template_path_var": yg_fav_template_path_var,
"yg_icon_match_threshold_var": yg_icon_match_threshold_var,
"yg_icon_roi_size_var": yg_icon_roi_size_var,
"yg_like_icon_x_var": yg_like_icon_x_var,
"yg_like_icon_y_var": yg_like_icon_y_var,
"yg_like_prob_var": yg_like_prob_var,
"yg_like_roi_offset_x_var": yg_like_roi_offset_x_var,
"yg_like_roi_offset_y_var": yg_like_roi_offset_y_var,
"yg_like_template_path_var": yg_like_template_path_var,
"yg_only_var": yg_only_var,
"yg_recommend_duration_var": yg_recommend_duration_var,
"yg_recommend_interval_var": yg_recommend_interval_var,
"yg_step_screenshot_var": yg_step_screenshot_var,
}
_config_io_texts = {
"not_want_text": not_want_text,
"want_text": want_text,
"yg_comment_texts": yg_comment_texts,
"yg_fav_keywords_text": yg_fav_keywords_text,
"yg_like_keywords_text": yg_like_keywords_text,
}
def load_config_to_ui():
nonlocal cfg
cfg = _load_config_to_ui_impl(
vars_=_config_io_vars,
texts_=_config_io_texts,
read_config=read_config,
)
def save_ui_to_config():
_save_ui_to_config_impl(
vars_=_config_io_vars,
texts_=_config_io_texts,
cfg=cfg,
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
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_btn = ttk.Button(
top_btns,
text="截图+OCR",
command=lambda: _do_screenshot_impl(
device_id=device_var.get().strip(),
y_offset=int(y_var.get() or 0),
image_var=image_var,
on_line=on_line,
root=root,
on_ocr_results=update_ocr_results,
on_refresh_preview=refresh_preview,
),
)
screenshot_btn.pack(side=LEFT, padx=(0, 8))
# 右侧:操作按钮区域(先创建,放在底部)
actions = ttk.Frame(right)
# 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
notebook = ttk.Notebook(right)
# 实时状态工具栏(固定在 Notebook 上方,始终可见)
show_actions_var = tk.BooleanVar(value=True)
show_screenshot_var = tk.BooleanVar(value=False)
auto_scroll_var = tk.BooleanVar(value=True)
realtime_tools = ttk.Frame(right)
realtime_tools.pack(fill=X, padx=8, pady=(4, 0))
ttk.Checkbutton(realtime_tools, text="显示动作流", variable=show_actions_var).pack(
side=LEFT, padx=(0, 8)
)
ttk.Checkbutton(realtime_tools, text="显示截图", variable=show_screenshot_var).pack(
side=LEFT, padx=(0, 8)
)
ttk.Checkbutton(realtime_tools, text="自动滚动", variable=auto_scroll_var).pack(
side=LEFT, padx=(0, 8)
)
# forward-declare handler to satisfy linters; real function defined later
_open_realtime_viewer_impl = None
realtime_view_btn = ttk.Button(
realtime_tools,
text="实时查看",
width=10,
command=lambda: (
_open_realtime_viewer_impl()
if callable(_open_realtime_viewer_impl)
else None
),
)
realtime_view_btn.pack(side=LEFT, padx=(8, 0))
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)
realtime_tab = ttk.Frame(notebook)
ocr_results_tab = ttk.Frame(notebook)
win_record_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(realtime_tab, text="实时状态")
notebook.add(ocr_results_tab, text="OCR结果")
notebook.add(win_record_tab, text="中奖记录")
# 使用模块化组件创建映射表并加入 Notebook
mapping_tab = create_mapping_tab(root, notebook, cfg)
notebook.add(mapping_tab, text="映射表")
# 日志区
log_box = ttk.Frame(log_tab)
log_box.pack(fill=BOTH, expand=True)
# ========== 实时状态 Tab(显示最近动作 + 耗时) ==========
try:
realtime_frame = ttk.Frame(realtime_tab)
realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8)
# 截图预览区域(根据选项显示/隐藏)
image_label = ttk.Label(realtime_frame)
image_label.pack(fill=X)
realtime_text = ScrolledText(realtime_frame, height=14)
realtime_text.pack(fill=BOTH, expand=True)
realtime_text.configure(state="disabled")
# re 已在模块顶部导入,避免重复导入
realtime_after_id = None
def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]:
"""从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。"""
try:
if not os.path.exists(path):
return []
with open(path, "rb") as f:
f.seek(0, os.SEEK_END)
file_size = f.tell()
seek_from = max(0, file_size - max_bytes)
f.seek(seek_from)
data = f.read()
text = data.decode(errors="ignore")
# splitlines 保留不含尾部换行的处理
return text.splitlines()
except Exception:
return []
def parse_action_duration(line: str) -> tuple[str, str] | None:
"""从一行日志提取 (action, duration),未找到返回 None。
支持 ms / s 两种单位(实际 actions.log 写 `耗时=10.00ms`)。
"""
if "耗时" not in line:
return None
idx = line.find("耗时")
tail = line[idx:] # 在"耗时"之后搜,避免把前缀里的数字当成耗时
num = r"([0-9]+(?:\.[0-9]+)?)"
# 优先 ms(必须先于 s 匹配,否则 \s*s 会先吃掉 "10ms" 的 m)
m_ms = re.search(r"耗时[:=]?\s*" + num + r"\s*ms", tail)
m_s = re.search(r"耗时[:=]?\s*" + num + r"\s*s(?![a-zA-Z])", tail)
if m_ms:
dur = m_ms.group(1) + "ms"
elif m_s:
dur = m_s.group(1) + "s"
else:
m2 = re.search(num + r"\s*ms", tail)
if m2:
dur = m2.group(1) + "ms"
else:
m3 = re.search(num + r"\s*s(?![a-zA-Z])", tail)
if m3:
dur = m3.group(1) + "s"
else:
return None
# 动作名取耗时之前的文本片段,最多保留 60 字符
action = line[:idx].strip()
if not action:
# 兜底:取整行前 60 字符
action = line.strip()[:60]
if len(action) > 60:
action = action[:57] + "..."
return (action, dur)
def refresh_realtime_tab():
nonlocal realtime_after_id
cfg = read_config()
gui_cfg = cfg.get("gui", {}).get("realtime_status", {})
refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000))
tail_items = int(gui_cfg.get("tail_items", 50))
path = os.path.join(get_logs_dir(), "actions.log")
lines = tail_read_file(path)
parsed: list[tuple[str, str]] = []
# 从文件末尾向前解析,保持原始顺序输出最近项
for line in reversed(lines):
try:
out = parse_action_duration(line)
if out:
parsed.append(out)
if len(parsed) >= tail_items:
break
except Exception:
continue
parsed = list(reversed(parsed))
# 更新截图(若选中)
if show_screenshot_var.get():
try:
try:
from douyin.core.path_config import get_screenshot_path
screenshot_path = get_screenshot_path()
except Exception:
from douyin.core import path_config
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
# 缩放以适应宽度(保持纵横比),最大宽度 420
max_w = 420
w, h = img.size
if w > max_w:
nw = max_w
nh = int(h * (nw / w))
img = img.resize((nw, nh), Image.LANCZOS)
tk_img = ImageTk.PhotoImage(img)
image_label.configure(image=tk_img)
image_label.image = tk_img
image_label.pack(fill=X)
else:
image_label.configure(image="")
image_label.image = None
image_label.pack_forget()
except Exception:
image_label.configure(image="")
image_label.image = None
image_label.pack_forget()
else:
image_label.configure(image="")
image_label.image = None
image_label.pack_forget()
# 更新动作流文本(若选中)
if show_actions_var.get():
realtime_text.configure(state="normal")
realtime_text.delete("1.0", "end")
if not parsed:
realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)")
else:
for action, dur in parsed:
realtime_text.insert("end", f"{action} {dur}\n")
# 自动滚动
if auto_scroll_var.get():
try:
realtime_text.see("end")
except Exception:
try:
realtime_text.yview_moveto(1.0)
except Exception:
pass
realtime_text.configure(state="disabled")
else:
# 隐藏文本内容但保留控件
realtime_text.configure(state="normal")
realtime_text.delete("1.0", "end")
realtime_text.configure(state="disabled")
# 安排下一次刷新
try:
realtime_after_id = root.after(refresh_ms, refresh_realtime_tab)
except Exception:
realtime_after_id = None
# 启动刷新(仅在 Tab 被创建时启动)
try:
refresh_realtime_tab()
except Exception:
pass
except Exception:
pass
# --------- 实时查看弹窗(紧凑视图) ---------
def _open_realtime_viewer_impl():
"""委托到 gui/components/realtime_viewer.open_realtime_viewer。"""
from gui.components.realtime_viewer import open_realtime_viewer
open_realtime_viewer(root)
# 搜索工具栏
log_search_frame = ttk.Frame(log_box)
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
# 关键字筛选(与行为日志一致)
log_filter_var = tk.StringVar(value="")
ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT)
ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack(
side=LEFT, padx=(0, 8)
)
log_search_var = tk.StringVar(value="")
log_search_entry = ttk.Entry(
log_search_frame, textvariable=log_search_var, width=20
)
def refresh_run_log():
_refresh_run_log_impl(
runner,
text_widget=log_text,
filter_getter=lambda: log_filter_var.get().strip(),
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
)
log_search_matches = [] # 存储所有匹配的位置
log_current_match_index = -1 # 当前匹配的索引
def search_in_log_text(direction=1):
"""在运行日志中搜索文本(调用通用搜索实现)"""
nonlocal log_search_matches, log_current_match_index
log_current_match_index = _generic_search_widget_impl(
log_text,
log_search_var,
log_search_matches,
log_current_match_index,
direction,
)
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=refresh_run_log).pack(
side=LEFT, padx=(0, 8)
)
ttk.Separator(log_search_frame, orient="vertical").pack(
side=LEFT, fill=Y, padx=5, pady=3
)
ttk.Label(log_search_frame, text="搜索:").pack(side=LEFT)
# 把搜索输入框放在分隔符后
log_search_entry.pack(side=LEFT, padx=(0, 5))
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))
# 配置日志颜色标签(如果支持颜色)
try:
# 根据主题调整日志颜色(明亮主题使用深色文字/蓝色系)
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
try:
current_theme = str(gui_theme_var.get() or "litera")
except Exception:
current_theme = "litera"
if current_theme in light_themes:
# 明亮主题 - 使用更适合人眼观看的颜色组合
log_text.configure(
background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C"
)
log_text.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色
log_text.tag_configure(
"log_info", foreground="#1E88E5"
) # 明亮的蓝色,易于阅读
log_text.tag_configure(
"log_warning", foreground="#F57C00"
) # 橙色,警告色但不过于刺眼
log_text.tag_configure(
"log_error", foreground="#D32F2F"
) # 深红色,醒目但不刺眼
log_text.tag_configure(
"log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")
) # 加粗深红色
log_text.tag_configure(
"log_performance", foreground="#388E3C"
) # 深绿色,性能指标
log_text.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识
else:
# 暗色主题 - 优化对比度和可读性
log_text.configure(
background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF"
)
log_text.tag_configure(
"log_timestamp", foreground="#A0A0A0"
) # 浅灰色时间戳
log_text.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级
log_text.tag_configure(
"log_warning", foreground="#FFB74D"
) # 金色警告,暗色背景下醒目
log_text.tag_configure(
"log_error", foreground="#EF5350"
) # 亮红色,错误突出
log_text.tag_configure(
"log_critical", foreground="#F44336", font=("Consolas", 10, "bold")
) # 加粗亮红色
log_text.tag_configure(
"log_performance", foreground="#81C784"
) # 亮绿色,性能数据
log_text.tag_configure(
"log_module", foreground="#BA68C8"
) # 亮紫色,模块标识
# 配置操作类型颜色标签(使用模块化配置)
try:
color_config = get_color_config(current_theme)
for op_type, colors in color_config.items():
tag_name = f"op_{op_type}"
log_text.tag_configure(
tag_name,
foreground=colors["foreground"],
background=colors["background"],
)
except Exception:
pass # 忽略操作类型颜色配置失败
except Exception:
pass # 忽略标签配置失败
# 截图预览
preview_top = ttk.Frame(preview_tab)
preview_top.pack(fill=X, padx=10, pady=10)
try:
from douyin.core.path_config import get_pic_dir
images_dir = get_pic_dir()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
images_dir = path_config.get_pic_dir()
def scan_image_files():
return _scan_image_files_impl(_preview_view)
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):
_update_image_list_impl(_preview_view, refresh_after=refresh_after)
# 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)
def refresh_preview():
_refresh_preview_impl(_preview_view)
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 被回收
_preview_view = _PreviewView(
images_dir=str(images_dir),
image_var=image_var,
image_combo=image_combo,
preview_body=preview_body,
image_label=image_label,
preview_status=preview_status,
on_line=on_line,
root=root,
img_ref=_img_ref,
)
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
def _load_and_fit_image(img_path: str) -> None:
_load_and_fit_image_impl(_preview_view, img_path)
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():
_open_pic_folder_impl(_preview_view)
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:
return _get_params_impl({
"infinite_loop_var": infinite_loop_var,
"wait_minutes_var": wait_minutes_var,
"device_var": device_var,
"y_var": y_var,
"needswitch_var": needswitch_var,
"skip_gt_seconds_var": skip_gt_seconds_var,
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
"reset_after_swipes_var": reset_after_swipes_var,
"min_value_var": min_value_var,
"min_participants_var": min_participants_var,
"max_participants_var": max_participants_var,
"auto_join_var": auto_join_var,
"fansclub_action_var": fansclub_action_var,
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
"enable_ocr_mode1_var": enable_ocr_mode1_var,
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
"yg_only_var": yg_only_var,
"yg_recommend_duration_var": yg_recommend_duration_var,
"enable_back_on_misses_var": enable_back_on_misses_var,
})
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)
)
# (已移除:测试养号/测试评论 按钮与相关UI)
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():
_pump_logs_impl(
q,
text_widget=log_text,
filter_getter=lambda: log_filter_var.get().strip(),
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
root=root,
is_running_getter=runner.is_running,
status_getter=status_var.get,
status_setter=status_var.set,
)
# 统计信息显示
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():
"""委托给 gui/components/stats_formatter.format_stats(纯字符串构建)。"""
try:
from gui.components.stats_formatter import format_stats
stats = runner.get_stats()
stats_text.delete("1.0", "end")
stats_text.insert("1.0", "\n".join(format_stats(stats)))
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():
_refresh_reservations_impl(reservation_text)
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():
_refresh_high_value_rooms_impl(high_value_text)
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
# 配置行为日志颜色标签(使用统一的颜色配置模块)
def configure_actions_log_colors():
_configure_actions_log_colors_impl(
actions_log_text,
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
)
# 初始配置
configure_actions_log_colors()
actions_filter_var = tk.StringVar(value="")
def refresh_actions_log():
_refresh_actions_log_impl(
actions_log_text,
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
filter_getter=lambda: actions_filter_var.get().strip(),
)
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
actions_current_match_index = _generic_search_widget_impl(
actions_log_text,
actions_search_var,
actions_search_matches,
actions_current_match_index,
direction,
)
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):
_update_ocr_results_impl(ocr_results_text, results)
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)
)
# 中奖记录显示
win_record_top = ttk.Frame(win_record_tab)
win_record_top.pack(fill=X, padx=10, pady=(10, 0))
win_record_left = ttk.Frame(win_record_tab)
win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10)
win_record_right = ttk.Frame(win_record_tab)
win_record_right.pack(
side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10
)
# 左侧:中奖截图列表
win_list_label = ttk.Label(win_record_left, text="中奖截图列表:")
win_list_label.pack(anchor="w", padx=(0, 10), pady=(0, 5))
win_list_frame = ttk.Frame(win_record_left)
win_list_frame.pack(fill=BOTH, expand=True)
win_list_scrollbar = ttk.Scrollbar(win_list_frame)
win_list_scrollbar.pack(side=RIGHT, fill=Y)
win_listbox = tk.Listbox(
win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9)
)
win_listbox.pack(side=LEFT, fill=BOTH, expand=True)
win_list_scrollbar.config(command=win_listbox.yview)
# 存储文件路径映射(索引 -> 文件路径)
_win_file_paths: dict[int, str] = {}
# 右侧:截图预览
win_preview_label = ttk.Label(win_record_right, text="截图预览:")
win_preview_label.pack(anchor="w", pady=(0, 5))
win_preview_frame = ttk.Frame(win_record_right)
win_preview_frame.pack(fill=BOTH, expand=True)
win_image_label = ttk.Label(win_preview_frame)
win_image_label.pack(fill=BOTH, expand=True)
_win_img_ref: dict[str, Any] = {"photo": None}
def refresh_win_record():
_refresh_win_record_impl(_win_record_view)
def on_win_list_select(event):
_on_win_list_select_impl(_win_record_view, event)
win_listbox.bind("<<ListboxSelect>>", on_win_list_select)
ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(
side=LEFT, padx=(0, 10)
)
def open_win_folder():
_open_win_folder_impl(_win_record_view)
ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT)
ttk.Button(
win_record_top,
text="实时查看",
command=(
lambda: (
_open_realtime_viewer_impl()
if callable(_open_realtime_viewer_impl)
else None
)
),
).pack(side=LEFT, padx=(8, 0))
# 误识别记录管理
false_positive_frame = ttk.LabelFrame(win_record_right, text="误识别记录管理")
false_positive_frame.pack(fill=X, pady=(10, 0))
false_positive_text = ScrolledText(false_positive_frame, height=6)
false_positive_text.pack(fill=X, padx=10, pady=10)
_win_record_view = _WinRecordView(
listbox=win_listbox,
image_label=win_image_label,
preview_frame=win_preview_frame,
false_positive_text=false_positive_text,
on_line=on_line,
file_paths=_win_file_paths,
img_ref=_win_img_ref,
)
def load_false_positives():
_load_false_positives_impl(_win_record_view)
def save_false_positives():
_save_false_positives_impl(_win_record_view)
false_positive_btn_frame = ttk.Frame(false_positive_frame)
false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10))
ttk.Button(
false_positive_btn_frame, text="刷新", command=load_false_positives
).pack(side=LEFT, padx=(0, 5))
ttk.Button(
false_positive_btn_frame, text="保存", command=save_false_positives
).pack(side=LEFT)
load_false_positives()
pump_logs()
def delayed_refresh_preview() -> None:
if image_var.get():
_async_refresh_preview()
def _async_refresh_preview() -> None:
_async_refresh_preview_impl(_preview_view)
root.after(3000, 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]
root.after(500, refresh_win_record) # 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]
# 定期刷新预约队列(每5秒)
def auto_refresh_reservations() -> None:
refresh_reservations()
root.after(5000, auto_refresh_reservations) # type: ignore[arg-type]
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
root.after(5000, auto_refresh_reservations) # 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 douyin.core.version import print_version_banner
print_version_banner("gui_app")
except Exception:
pass
main()