use runtime counters for dashboard statistics

This commit is contained in:
Your Name committed 2026-06-19 20:49:01 +08:00
1 parent 680c02d362
commit 8fac904ba9
1 file changed
+119 -84
+119 -84
View File
@@ -4,12 +4,14 @@ import re
import tkinter as tk
import time
from datetime import datetime
from threading import RLock
from typing import Any
from . import theme
from .data import DashboardData, fmt_ts
from .page_context import PageContext
from .page_helpers import reservation_rows
from .widgets import flow_grid, mini_table, preview_panel, section, stat_tile, table_panel
from .widgets import flow_grid, log_panel, preview_panel, section, stat_tile, table_panel
_RUN_TS_RE = re.compile(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:[.,]\d+)?)")
@@ -68,46 +70,115 @@ def _run_durations(data: DashboardData) -> tuple[str, str]:
return _fmt_duration(current), _fmt_duration(total)
def _count_lines(lines: list[str], keyword: str) -> int:
return sum(1 for line in lines if keyword in str(line))
class _StatsReplayRunner:
def __init__(self) -> None:
self._lock = RLock()
self._last_log_ts: float | None = None
self._counters: dict[str, int] = {}
self._fudai_last: dict[str, Any] = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events: list[dict[str, Any]] = []
self._events_cap = 5000
self._wins: list[dict[str, Any]] = []
self._wins_cap = 200
self._unique_keys_seen: set[str] = set()
self._unique_keys_open: set[str] = set()
self._unique_keys_attend: set[str] = set()
self._current_room_pos: int | None = None
self._fudai_seen_room_pos: set[int] = set()
self._fudai_open_room_pos: set[int] = set()
self._fudai_attend_ok_room_pos: set[int] = set()
self._fudai_attend_fail_room_pos: set[int] = set()
self._recorded_fudai_seen: set[tuple[str, str]] = set()
def _inc(self, key: str, n: int = 1) -> None:
with self._lock:
self._counters[key] = int(self._counters.get(key, 0)) + int(n)
def _record_event(self, typ: str, meta: dict | None = None) -> None:
with self._lock:
self._events.append({"ts": time.time(), "type": str(typ), "meta": meta or {}})
if len(self._events) > self._events_cap:
self._events = self._events[-self._events_cap:]
def _snapshot_fudai(self) -> dict[str, Any]:
with self._lock:
return {
"content": self._fudai_last.get("content") or "",
"countdown": self._fudai_last.get("countdown") or "",
"participants": self._fudai_last.get("participants"),
"copies": self._fudai_last.get("copies"),
"prize_value_yuan": self._fudai_last.get("prize_value_yuan"),
}
def _make_unique_key(self) -> str:
snap = self._snapshot_fudai()
return f"{snap.get('content') or ''}|{snap.get('prize_value_yuan') or ''}|{snap.get('countdown') or ''}"
def _record_win(self) -> None:
with self._lock:
self._wins.append({"ts": time.time(), **self._snapshot_fudai()})
if len(self._wins) > self._wins_cap:
self._wins = self._wins[-self._wins_cap:]
def replay(self, lines: list[str]) -> None:
from gui.gui_core_pkg.stats_log_parser import update_stats_from_line
for line in lines:
update_stats_from_line(self, line)
def get_stats(self) -> dict[str, Any]:
with self._lock:
return {
"running": False,
"pid": None,
"start_ts": None,
"last_log_ts": self._last_log_ts,
"exit_code": None,
"uptime_seconds": 0,
"counters": dict(self._counters),
"fudai_last": dict(self._fudai_last),
"wins": list(self._wins[-20:]),
"events": list(self._events[-1000:]),
}
def _latest_ts_from_paths(paths) -> str:
items = list(paths or [])
if not items:
return "-"
def _runtime_stats(data: DashboardData, ctx: PageContext) -> dict[str, Any]:
runner = ctx.runner
if runner is not None:
try:
stats = runner.get_stats()
if stats.get("counters") or stats.get("running"):
return stats
except Exception:
pass
replay = _StatsReplayRunner()
replay.replay([*data.run_log, *data.action_log])
stats = replay.get_stats()
current_run, total_run = _run_durations(data)
stats["dashboard_current_run"] = current_run
stats["dashboard_total_run"] = total_run
return stats
def _counter(stats: dict[str, Any], key: str) -> int:
counters = stats.get("counters", {}) or {}
try:
return fmt_ts(max(p.stat().st_mtime for p in items if p.exists()))
return int(counters.get(key, 0) or 0)
except Exception:
return "-"
return 0
def _latest_log_time(data: DashboardData) -> str:
for line in reversed([*data.run_log, *data.action_log]):
ts = _parse_run_ts(str(line))
if ts is not None:
return fmt_ts(ts)
return "-"
def _stats_lines(stats: dict[str, Any]) -> list[str]:
from gui.components.stats_formatter import format_stats
def _high_value_rows(data: DashboardData) -> list[tuple[str, str, str]]:
rows: list[tuple[str, str, str]] = []
for item in data.high_value_rooms[:8]:
title = str(item.get("room_title") or item.get("title") or "-")
value = str(item.get("prize_value_yuan") or item.get("value") or "-")
content = str(item.get("content") or item.get("prize_content") or "-")
rows.append((title[:36], value, content[:18]))
return rows
def _mapping_rows(data: DashboardData) -> list[tuple[str, str, str]]:
rows: list[tuple[str, str, str]] = []
for item in data.mapping_rows[:8]:
pos = str(item.get("pos") or "-")
title = str(item.get("title") or "-")
state = "有福袋" if item.get("has_fudai") == "是" else str(item.get("updated") or "-")
rows.append((f"位置 {pos} {title[:28]}", str(item.get("value") or "-"), state[:16]))
return rows
return format_stats(stats)
def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
@@ -145,60 +216,24 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
def build_statistics(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
section(parent, "统计信息", "运行概览 / 数据资产 / 最近记录")
current_run, total_run = _run_durations(data)
section(parent, "统计信息", "旧GUI同源运行统计 / 自动解析运行日志")
stats = _runtime_stats(data, ctx)
current_run = str(stats.get("dashboard_current_run") or "-")
total_run = str(stats.get("dashboard_total_run") or "-")
if stats.get("uptime_seconds"):
current_run = _fmt_duration(float(stats.get("uptime_seconds") or 0))
metrics = flow_grid(parent, 4)
values = [
("本次运行", current_run, "当前轮次", theme.TEAL, theme.TEAL_SOFT),
("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT),
("打开详情", _counter(stats, "fudai_open_detail_unique"), "旧GUI口径", theme.BLUE, theme.BLUE_SOFT),
("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重统计", theme.GREEN, theme.GREEN_SOFT),
("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT),
("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT),
("错误数", _counter(stats, "error_total"), "异常统计", theme.RED, theme.RED_SOFT),
("本次运行", current_run, "Runner", theme.TEAL, theme.TEAL_SOFT),
("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT),
("运行日志", len(data.run_log), "最近读取", theme.GREEN, theme.GREEN_SOFT),
("行为日志", len(data.action_log), "关键动作", theme.AMBER, theme.AMBER_SOFT),
("中奖截图", len(data.win_images), "pic/lottery", theme.RED, theme.RED_SOFT),
("映射条目", len(data.mapping_rows), "room_pos", theme.TEAL, theme.TEAL_SOFT),
("高价值记录", len(data.high_value_rooms), "持久化", theme.BLUE, theme.BLUE_SOFT),
("OCR文件", len(data.ocr_files), "识别结果", theme.GREEN, theme.GREEN_SOFT),
]
for idx, item in enumerate(values):
tile = stat_tile(metrics, *item[:3], color=item[3], soft=item[4], compact=True)
tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
body = tk.Frame(parent, bg=theme.BG)
body.pack(fill="both", expand=True)
body.grid_columnconfigure(0, weight=1)
body.grid_columnconfigure(1, weight=1)
body.grid_rowconfigure(1, weight=1)
run_rows = [
("开始次数", str(_count_lines(data.run_log + data.action_log, "程序开始运行")), "日志"),
("结束次数", str(_count_lines(data.run_log + data.action_log, "程序运行结束")), "日志"),
("最近日志", _latest_log_time(data), "时间"),
("实时截图", "存在" if data.current_screenshot_path else "缺失", "pic"),
("运行日志行", str(len(data.run_log)), "log"),
("行为日志行", str(len(data.action_log)), "log"),
]
asset_rows = [
("最新中奖截图", _latest_ts_from_paths(data.win_images), "时间"),
("最新OCR文件", _latest_ts_from_paths(data.ocr_files), "时间"),
("当前截图", fmt_ts(data.current_screenshot_path.stat().st_mtime) if data.current_screenshot_path else "-", "时间"),
("配置项数量", str(len(data.cfg)), "config"),
("动作关键行", str(_count_lines(data.action_log, "[ACTION]") + _count_lines(data.action_log, "[操作]")), "actions"),
("运行关键行", str(_count_lines(data.run_log, "运行") + _count_lines(data.action_log, "[运行]")), "runtime"),
]
left = tk.Frame(body, bg=theme.BG)
right = tk.Frame(body, bg=theme.BG)
left.grid(row=0, column=0, sticky="nsew", padx=(0, 8), pady=(0, 12))
right.grid(row=0, column=1, sticky="nsew", padx=(8, 0), pady=(0, 12))
mini_table(left, "运行概览", run_rows, color=theme.TEAL).pack(fill="both", expand=True)
mini_table(right, "数据资产", asset_rows, color=theme.BLUE).pack(fill="both", expand=True)
lower = tk.Frame(body, bg=theme.BG)
lower.grid(row=1, column=0, columnspan=2, sticky="nsew")
lower.grid_columnconfigure(0, weight=1)
lower.grid_columnconfigure(1, weight=1)
high = tk.Frame(lower, bg=theme.BG)
mapping = tk.Frame(lower, bg=theme.BG)
high.grid(row=0, column=0, sticky="nsew", padx=(0, 8))
mapping.grid(row=0, column=1, sticky="nsew", padx=(8, 0))
mini_table(high, "最近高价值记录", _high_value_rows(data), color=theme.RED).pack(fill="both", expand=True)
mini_table(mapping, "最近映射记录", _mapping_rows(data), color=theme.GREEN).pack(fill="both", expand=True)
log_panel(parent, "运行数据统计", _stats_lines(stats), height=28)[0].pack(fill="both", expand=True)