gui_app.py 嵌套函数 _open_realtime_viewer_impl 是 170 行的"实时查看"对话框: 弹 Toplevel 显示当前 pic/screenshot.png + 列表展示 actions.log 中含"耗时"的 最近 80 行,每秒刷新。 抽到 gui/components/realtime_viewer.py: - open_realtime_viewer(root) 主入口 - _tail_read(path, max_bytes) 末尾字节读取 - _parse_minimal(line) 提取 (动作名, 耗时) 二元组 - 全局单例 _active_win 替代原嵌套 def 的属性式 _win gui_app.py 中嵌套 def 缩成 4 行委托。 新增 13 个单元测试覆盖 _tail_read 4 种情况 + _parse_minimal 8 种格式。 1421 passed (+13)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
177 lines
5.7 KiB
Python
177 lines
5.7 KiB
Python
"""gui/components/realtime_viewer - "实时查看 - 截图与最简动作流" 对话框
|
|
|
|
从 gui_app.py 的 _open_realtime_viewer_impl 嵌套函数抽出来。功能:
|
|
- 弹一个 Toplevel 显示当前 pic/screenshot.png
|
|
- 列表展示 logs/actions.log 中包含"耗时"的最近 80 行(用于实时观察)
|
|
- 每秒自动刷新
|
|
|
|
入口:open_realtime_viewer(root) -> tk.Toplevel | None
|
|
单例:同一个 root 重复调用只会聚焦已有窗口,不会重开。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
import tkinter as tk
|
|
from tkinter import ttk
|
|
from typing import Optional
|
|
|
|
from PIL import Image, ImageTk # type: ignore[import]
|
|
|
|
from douyin.core.path_config import get_logs_dir, get_screenshot_path
|
|
|
|
|
|
# 全局单例:避免同一进程多次开窗
|
|
_active_win: Optional[tk.Toplevel] = None
|
|
|
|
|
|
def open_realtime_viewer(root: tk.Tk) -> Optional[tk.Toplevel]:
|
|
"""打开(或聚焦已有的)实时查看器对话框。
|
|
|
|
Returns:
|
|
新创建或已存在的 Toplevel,None 表示创建失败。
|
|
"""
|
|
global _active_win
|
|
|
|
try:
|
|
if _active_win is not None:
|
|
try:
|
|
_active_win.lift()
|
|
except Exception:
|
|
pass
|
|
return _active_win
|
|
|
|
win = tk.Toplevel(root)
|
|
win.title("实时查看 - 截图与最简动作流")
|
|
win.geometry("520x520")
|
|
_active_win = win
|
|
|
|
# 图片与列表
|
|
img_lbl = ttk.Label(win)
|
|
img_lbl.pack(fill=tk.X, pady=(6, 4))
|
|
|
|
list_frame = ttk.Frame(win)
|
|
list_frame.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
|
|
listbox = tk.Listbox(list_frame, height=12)
|
|
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
|
scrollbar = ttk.Scrollbar(
|
|
list_frame, orient=tk.VERTICAL, command=listbox.yview
|
|
)
|
|
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
|
listbox.configure(yscrollcommand=scrollbar.set)
|
|
|
|
stop_flag = {"stop": False}
|
|
|
|
def close_win() -> None:
|
|
global _active_win
|
|
stop_flag["stop"] = True
|
|
try:
|
|
win.destroy()
|
|
except Exception:
|
|
pass
|
|
_active_win = None
|
|
|
|
win.protocol("WM_DELETE_WINDOW", close_win)
|
|
|
|
def update_loop() -> None:
|
|
if stop_flag["stop"]:
|
|
return
|
|
|
|
# update image
|
|
try:
|
|
screenshot_path = get_screenshot_path()
|
|
if os.path.exists(screenshot_path):
|
|
img = Image.open(screenshot_path)
|
|
max_w = 480
|
|
w, h = img.size
|
|
if w > max_w:
|
|
nw = max_w
|
|
nh = int(h * (nw / w))
|
|
img = img.resize((nw, nh), Image.LANCZOS)
|
|
tkimg = ImageTk.PhotoImage(img)
|
|
img_lbl.configure(image=tkimg)
|
|
img_lbl.image = tkimg # type: ignore[attr-defined]
|
|
else:
|
|
img_lbl.configure(image="")
|
|
img_lbl.image = None # type: ignore[attr-defined]
|
|
except Exception:
|
|
img_lbl.configure(image="")
|
|
img_lbl.image = None # type: ignore[attr-defined]
|
|
|
|
# update minimal action list
|
|
try:
|
|
path = os.path.join(get_logs_dir(), "actions.log")
|
|
lines = _tail_read(path, max_bytes=64 * 1024)
|
|
items: list[str] = []
|
|
for line in reversed(lines):
|
|
out = _parse_minimal(line)
|
|
if out:
|
|
items.append(f"{out[0]} {out[1]}")
|
|
if len(items) >= 80:
|
|
break
|
|
items = list(reversed(items))
|
|
listbox.delete(0, tk.END)
|
|
if not items:
|
|
listbox.insert(tk.END, "暂无动作(仅显示包含 耗时 的行)")
|
|
else:
|
|
for it in items:
|
|
listbox.insert(tk.END, it)
|
|
try:
|
|
listbox.yview_moveto(1.0)
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
try:
|
|
listbox.delete(0, tk.END)
|
|
listbox.insert(tk.END, "更新失败")
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
win.after(1000, update_loop)
|
|
except Exception:
|
|
return
|
|
|
|
update_loop()
|
|
return win
|
|
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _tail_read(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)
|
|
sz = f.tell()
|
|
f.seek(max(0, sz - max_bytes))
|
|
return f.read().decode(errors="ignore").splitlines()
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def _parse_minimal(line: str) -> Optional[tuple[str, str]]:
|
|
"""从一行日志中提取 (动作名, 耗时) 二元组;不含"耗时"则返回 None。"""
|
|
if "耗时" not in line:
|
|
return None
|
|
m = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*s", line)
|
|
dur = None
|
|
if m:
|
|
dur = m.group(1) + "s"
|
|
else:
|
|
m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s", line)
|
|
if m2:
|
|
dur = m2.group(1) + "s"
|
|
if not dur:
|
|
return None
|
|
idx = line.find("耗时")
|
|
action = line[:idx].strip()
|
|
if not action:
|
|
action = line.strip()[:80]
|
|
if len(action) > 80:
|
|
action = action[:77] + "..."
|
|
return (action, dur)
|