Files
douyin_guaji-main/gui/gui_app.py
T

471 lines
17 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 logging
import os
import queue
import re
import sys
import warnings
# 确保项目根目录在 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 ImageTk # type: ignore[import]
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
from gui.gui_core import (
RunParams,
Runner,
read_config,
write_config,
)
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 # noqa: F401 re-export
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.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.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.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
from gui.components.filter_tab import setup_filter_tab
from gui.components.realtime_tab import setup_realtime_tab
from gui.components.win_record_tab import setup_win_record_tab
from gui.components.actions_log_toolbar import setup_actions_log_toolbar
from gui.components.simple_tabs import setup_simple_text_tab
from gui.components.preview_tab import setup_preview_tab
from gui.components.keywords_tab import setup_keywords_tab
from gui.components.main_notebook import setup_main_notebook
from gui.components.action_buttons import setup_action_buttons
from gui.components.config_vars import build_config_vars
from gui.components.top_device_bar import setup_top_device_bar
from gui.components.top_buttons import setup_top_buttons
from gui.components.log_tab import setup_log_tab
from gui.components.periodic_refreshers import (
setup_periodic_refreshers,
setup_close_handler,
)
# 导入日志颜色配置模块
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()
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)
_top_bar = setup_top_device_bar(top, root=root, on_line=on_line)
device_var = _top_bar.device_var
refresh_devices = _top_bar.refresh_devices
def save_logging_config():
_save_logging_config_impl(
vars_=_vars_,
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
# 配置区(提前读取配置,供后续使用)
cfg = read_config()
_vars_ = build_config_vars(cfg)
gui_theme_var = _vars_["gui_theme_var"]
y_var = _vars_["y_var"]
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)
# 创建左侧配置标签页
setup_run_tab(left_notebook, vars_=_vars_)
setup_filter_tab(left_notebook, vars_=_vars_)
setup_reservation_tab(left_notebook, vars_=_vars_)
_, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text = setup_yanghao_tab(left_notebook, vars_=_vars_)
setup_debug_tab(left_notebook, vars_=_vars_)
setup_logging_tab(left_notebook, vars_=_vars_, on_save_logging=save_logging_config)
want_text, not_want_text = setup_keywords_tab(left_notebook, ScrolledText_cls=ScrolledText)
_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_=_vars_,
texts_=_config_io_texts,
read_config=read_config,
)
def save_ui_to_config():
_save_ui_to_config_impl(
vars_=_vars_,
texts_=_config_io_texts,
cfg=cfg,
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
load_config_to_ui()
# 右侧:操作按钮区域(先创建,放在底部)
actions = ttk.Frame(right)
# 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
_main_nb = setup_main_notebook(
right,
on_open_realtime_viewer=lambda: (
_open_realtime_viewer_impl()
if callable(_open_realtime_viewer_impl)
else None
),
)
notebook = _main_nb.notebook
log_tab = _main_nb.log_tab
preview_tab = _main_nb.preview_tab
stats_tab = _main_nb.stats_tab
reservation_tab = _main_nb.reservation_tab
high_value_tab = _main_nb.high_value_tab
actions_log_tab = _main_nb.actions_log_tab
realtime_tab = _main_nb.realtime_tab
ocr_results_tab = _main_nb.ocr_results_tab
win_record_tab = _main_nb.win_record_tab
# forward-declare handler to satisfy linters; real function defined later
_open_realtime_viewer_impl = None
# 使用模块化组件创建映射表并加入 Notebook
mapping_tab = create_mapping_tab(root, notebook, cfg)
notebook.add(mapping_tab, text="映射表")
# 日志区
_log_tab_handles = setup_log_tab(
log_tab,
runner=runner,
ScrolledText_cls=ScrolledText,
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
)
log_text = _log_tab_handles.log_text
log_filter_var = _log_tab_handles.log_filter_var
refresh_run_log = _log_tab_handles.refresh_run_log
setup_realtime_tab(
realtime_tab,
vars_={
"show_actions_var": _main_nb.show_actions_var,
"show_screenshot_var": _main_nb.show_screenshot_var,
"auto_scroll_var": _main_nb.auto_scroll_var,
},
root=root,
ScrolledText_cls=ScrolledText,
logs_dir_getter=get_logs_dir,
read_config=read_config,
)
# --------- 实时查看弹窗(紧凑视图) ---------
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)
_preview_handles = setup_preview_tab(
preview_tab,
on_line=on_line,
root=root,
)
_preview_view = _preview_handles.preview_view
image_var = _preview_handles.image_var
refresh_preview = _preview_handles.refresh_preview
status_var = tk.StringVar(value="就绪")
def get_params() -> RunParams:
return _get_params_impl({**_vars_, "device_var": device_var})
# 先打包 actions 到底部(不 expand,固定在底部)
actions.pack(fill=X, pady=(10, 0), padx=12, side="bottom")
# 然后打包 notebook 填充剩余空间(在 actions 之上)
notebook.pack(fill=BOTH, expand=True)
setup_action_buttons(
actions,
runner=runner,
status_var=status_var,
device_var=device_var,
on_line=on_line,
save_ui_to_config=save_ui_to_config,
get_params=get_params,
)
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, stats_text = setup_simple_text_tab(stats_tab, ScrolledText_cls=ScrolledText)
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, reservation_text = setup_simple_text_tab(reservation_tab, ScrolledText_cls=ScrolledText)
def refresh_reservations():
_refresh_reservations_impl(reservation_text)
ttk.Button(reservation_top, text="刷新", command=refresh_reservations).pack(
side=LEFT
)
# 高价值房间显示
high_value_top, high_value_text = setup_simple_text_tab(high_value_tab, ScrolledText_cls=ScrolledText)
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, actions_log_text = setup_simple_text_tab(actions_log_tab, ScrolledText_cls=ScrolledText)
_actions_log_handles = setup_actions_log_toolbar(
actions_log_top,
actions_log_text=actions_log_text,
theme_getter=lambda: str(gui_theme_var.get() or "litera"),
)
refresh_actions_log = _actions_log_handles.refresh_actions_log
# OCR结果显示
ocr_results_top, ocr_results_text = setup_simple_text_tab(ocr_results_tab, ScrolledText_cls=ScrolledText)
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)
)
# 顶部常驻按钮(放在 image_var/update_ocr_results/refresh_preview 都已就绪之后)
setup_top_buttons(
top,
device_var=device_var,
y_var=y_var,
image_var=image_var,
on_line=on_line,
root=root,
on_save_ui_to_config=save_ui_to_config,
on_ocr_results=update_ocr_results,
on_refresh_preview=refresh_preview,
)
_win_record_handles = setup_win_record_tab(
win_record_tab,
on_line=on_line,
ScrolledText_cls=ScrolledText,
open_realtime_viewer=lambda: (
_open_realtime_viewer_impl()
if callable(_open_realtime_viewer_impl)
else None
),
)
refresh_win_record = _win_record_handles.refresh_win_record
pump_logs()
def _async_refresh_preview() -> None:
_async_refresh_preview_impl(_preview_view)
setup_periodic_refreshers(
root,
image_var=image_var,
async_refresh_preview=_async_refresh_preview,
refresh_stats=refresh_stats,
refresh_reservations=refresh_reservations,
refresh_high_value_rooms=refresh_high_value_rooms,
refresh_actions_log=refresh_actions_log,
refresh_win_record=refresh_win_record,
runner=runner,
)
setup_close_handler(root, runner=runner)
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()