266 lines
9.5 KiB
Python
266 lines
9.5 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import tkinter as tk
|
|
import time
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from threading import RLock
|
|
from typing import Any
|
|
|
|
from douyin.core import path_config
|
|
|
|
from . import theme
|
|
from .data import DashboardData, fmt_ts, load_dashboard_data
|
|
from .page_data import HOME_RESERVATION_COLUMNS, _reservation_rows_for_display, reservation_auto_refresh_control
|
|
from .page_context import PageContext
|
|
from .stats_view import StatsDashboardView
|
|
from .widgets import flow_grid, 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+)?)")
|
|
|
|
|
|
def _parse_run_ts(line: str) -> float | None:
|
|
match = _RUN_TS_RE.search(line)
|
|
if not match:
|
|
return None
|
|
text = match.group(1).replace(",", ".")
|
|
try:
|
|
return datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f").timestamp()
|
|
except ValueError:
|
|
try:
|
|
return datetime.strptime(text, "%Y-%m-%d %H:%M:%S").timestamp()
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def _fmt_duration(seconds: float) -> str:
|
|
seconds = max(0, int(seconds))
|
|
hours, rem = divmod(seconds, 3600)
|
|
minutes, secs = divmod(rem, 60)
|
|
if hours:
|
|
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
|
|
return f"{minutes:02d}:{secs:02d}"
|
|
|
|
|
|
def _run_durations(data: DashboardData) -> tuple[str, str]:
|
|
starts: list[float] = []
|
|
total = 0.0
|
|
last_duration = 0.0
|
|
running_start: float | None = None
|
|
|
|
for raw_line in [*data.run_log, *data.action_log]:
|
|
line = str(raw_line)
|
|
if "程序开始运行" in line:
|
|
ts = _parse_run_ts(line)
|
|
if ts is not None:
|
|
starts.append(ts)
|
|
running_start = ts
|
|
elif "程序运行结束" in line:
|
|
ts = _parse_run_ts(line)
|
|
if ts is not None and starts:
|
|
start = starts.pop()
|
|
duration = max(0.0, ts - start)
|
|
total += duration
|
|
last_duration = duration
|
|
running_start = starts[-1] if starts else None
|
|
|
|
if running_start is not None:
|
|
current = max(0.0, time.time() - running_start)
|
|
total += current
|
|
else:
|
|
current = last_duration
|
|
return _fmt_duration(current), _fmt_duration(total)
|
|
|
|
|
|
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 _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"):
|
|
current_run, total_run = _run_durations(data)
|
|
stats.setdefault("dashboard_current_run", current_run)
|
|
stats.setdefault("dashboard_total_run", total_run)
|
|
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 int(counters.get(key, 0) or 0)
|
|
except Exception:
|
|
return 0
|
|
|
|
|
|
def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "数据看板", "运行时间 / 队列 / 截图")
|
|
metrics = flow_grid(parent, 3)
|
|
current_run, total_run = _run_durations(data)
|
|
values = [
|
|
("中奖截图", len(data.win_images), "pic/lottery", theme.RED, theme.RED_SOFT),
|
|
("本次运行时间", current_run, "当前轮次", theme.TEAL, theme.TEAL_SOFT),
|
|
("总运行时间", total_run, "日志累计", theme.BLUE, theme.BLUE_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 // 3, column=idx % 3, sticky="ew", padx=6, pady=5)
|
|
|
|
body = tk.Frame(parent, bg=theme.BG)
|
|
body.pack(fill="both", expand=True, pady=(4, 0))
|
|
body.grid_columnconfigure(0, weight=4, minsize=620)
|
|
body.grid_columnconfigure(1, weight=2, minsize=360)
|
|
body.grid_rowconfigure(0, weight=1)
|
|
|
|
left = tk.Frame(body, bg=theme.BG)
|
|
right = tk.Frame(body, bg=theme.BG)
|
|
left.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
|
right.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
|
|
|
rows = _reservation_rows_for_display(data, include_created=False)
|
|
reservation_table = table_panel(left, "预约队列", HOME_RESERVATION_COLUMNS, rows, height=18)
|
|
reservation_table.pack(fill="both", expand=True)
|
|
control_row = tk.Frame(left, bg=theme.BG)
|
|
control_row.pack(fill="x", pady=(6, 0))
|
|
reservation_auto_refresh_control(
|
|
control_row,
|
|
ctx,
|
|
reservation_table,
|
|
HOME_RESERVATION_COLUMNS,
|
|
include_created=False,
|
|
).pack(side="left")
|
|
|
|
preview_panel(
|
|
right,
|
|
data.current_screenshot_path,
|
|
"实时截图",
|
|
max_size=(430, 620),
|
|
auto_refresh_ms=1000,
|
|
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
|
).pack(fill="both", expand=True)
|
|
|
|
|
|
def _statistics_values(data: DashboardData, ctx: PageContext) -> tuple[dict[str, Any], str, str]:
|
|
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))
|
|
return stats, current_run, total_run
|
|
|
|
|
|
def _schedule_statistics_refresh(view: StatsDashboardView, ctx: PageContext, interval_ms: int = 2000) -> None:
|
|
def tick() -> None:
|
|
try:
|
|
if not view.root.winfo_exists():
|
|
return
|
|
except Exception:
|
|
return
|
|
try:
|
|
stats, current_run, total_run = _statistics_values(load_dashboard_data(), ctx)
|
|
view.update(stats, current_run, total_run)
|
|
finally:
|
|
_schedule_statistics_refresh(view, ctx, interval_ms)
|
|
|
|
try:
|
|
view.root.after(interval_ms, tick)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def build_statistics(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "统计信息", "实时运行指标 / 旧GUI同源统计")
|
|
view = StatsDashboardView(parent)
|
|
stats, current_run, total_run = _statistics_values(data, ctx)
|
|
view.update(stats, current_run, total_run)
|
|
_schedule_statistics_refresh(view, ctx)
|