Files
douyi_guaji_main/gui/components/realtime_viewer.py
T
CodexandClaude Opus 4.7 fe97e82104 fix(gui): 实时查看器/状态 Tab 的耗时解析支持 ms 单位
问题:实际 actions.log 写的是 `耗时=10.00ms`(毫秒),但 _parse_minimal
和 parse_action_duration 的正则只匹配 `s`,导致:
- 实时查看弹窗永远显示"暂无动作"
- 实时状态 Tab 同样空白

同时存在的副 bug:兜底正则在整行匹配,前缀里的 `192.168.5.2:5555` /
日志时间戳 `2026-05-21` 都可能被误识别成耗时。

修复:
- 解析窗口限定到 line.find("耗时") 之后的子串 (tail)
- 优先匹配 ms(顺序很重要:\s*s 会先吃掉 "10ms" 的 m)
- s 单位加 (?![a-zA-Z]) 负向后顾,避免匹配 "ms" / "second" 之类
- 同步修复 gui_app.py:3685 的 parse_action_duration(实时状态 Tab)

测试:
- _parse_minimal 加 4 个新测试覆盖 ms / 整数 ms / 优先级 / 前缀干扰
- 全量 1426 passed (+5)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 09:08:58 +08:00

192 lines
6.3 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.
"""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。
支持 ms / s 两种单位(实际 actions.log 写 `耗时=10.00ms`,旧测试桩用 `2.5s`)。
"""
if "耗时" not in line:
return None
idx = line.find("耗时")
tail = line[idx:] # 在"耗时"之后搜,避免把前缀里的数字当成耗时
# 优先 ms(必须先于 s 匹配,否则 \s*s 会先吃掉 "10ms" 的 m)
m_ms = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*ms", tail)
m_s = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\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:
# 兜底:在"耗时"后任意位置找 数字+ms 或 数字+s
m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*ms", tail)
if m2:
dur = m2.group(1) + "ms"
else:
m3 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s(?![a-zA-Z])", tail)
if m3:
dur = m3.group(1) + "s"
else:
return None
action = line[:idx].strip()
if not action:
action = line.strip()[:80]
if len(action) > 80:
action = action[:77] + "..."
return (action, dur)