from __future__ import annotations import tkinter as tk from datetime import datetime from typing import Any from . import theme from .widgets import flow_grid, rounded_surface 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 _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 _fmt_rate(part: int, total: int) -> str: if total <= 0: return "-" return f"{(part / total) * 100:.1f}%" def _per_hour(value: int, seconds: int | float) -> str: if value <= 0 or seconds <= 0: return "-" return f"{value / (float(seconds) / 3600.0):.1f}/h" def _last_log_time(stats: dict[str, Any]) -> str: ts = stats.get("last_log_ts") if not ts: return "-" try: return datetime.fromtimestamp(float(ts)).strftime("%H:%M:%S") except Exception: return "-" class StatsDashboardView: def __init__(self, parent: tk.Misc) -> None: self.root = tk.Frame(parent, bg=theme.BG) self.root.pack(fill="both", expand=True) self.vars: dict[str, tk.StringVar] = {} self.bars: dict[str, tuple[tk.StringVar, tk.Frame]] = {} self._build() def _var(self, key: str, value: str = "-") -> tk.StringVar: var = tk.StringVar(value=value) self.vars[key] = var return var def _kpi_tile(self, parent: tk.Misc, key: str, title: str, color: str, soft: str) -> tk.Frame: box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) box.configure(height=112) box.pack_propagate(False) inner = tk.Frame(box, bg=theme.SURFACE) inner.pack(fill="both", expand=True, padx=16, pady=12) head = tk.Frame(inner, bg=theme.SURFACE) head.pack(fill="x") tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left") tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right") tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 22, "bold")).pack(anchor="w", pady=(5, 0)) tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3).pack(anchor="w", pady=(7, 0)) return box def _metric_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None: row = tk.Frame(parent, bg=theme.SURFACE_ALT) row.pack(fill="x", pady=5) tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_UI, anchor="w").pack(side="left", fill="x", expand=True, padx=(10, 6), pady=(8, 2)) tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE_ALT, fg=color, font=("Microsoft YaHei UI", 16, "bold")).pack(side="right", padx=10, pady=(8, 2)) tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 5), padx=2) def _bar_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None: row = tk.Frame(parent, bg=theme.SURFACE) row.pack(fill="x", pady=(7, 3)) tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left") value_var = self._var(f"{key}.value") tk.Label(row, textvariable=value_var, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right") track = tk.Frame(parent, bg=theme.BG_ALT, height=10) track.pack(fill="x", pady=(0, 4)) fill = tk.Frame(track, bg=color, height=10) fill.place(relx=0, rely=0, relwidth=0, relheight=1) self.bars[key] = (value_var, fill) def _group(self, parent: tk.Misc, title: str) -> tk.Frame: box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) box.pack(fill="both", expand=True) head = tk.Frame(box, bg=theme.SURFACE) head.pack(fill="x", padx=18, pady=(16, 8)) tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10)) tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left") body = tk.Frame(box, bg=theme.SURFACE) body.pack(fill="both", expand=True, padx=18, pady=(0, 16)) return body def _build(self) -> None: grid = flow_grid(self.root, 4) kpis = [ ("status", "运行状态", theme.TEAL, theme.TEAL_SOFT), ("current_run", "本次运行", theme.BLUE, theme.BLUE_SOFT), ("attend", "参与成功", theme.GREEN, theme.GREEN_SOFT), ("wins", "中奖次数", theme.RED, theme.RED_SOFT), ("seen", "识别福袋", theme.TEAL, theme.TEAL_SOFT), ("open", "打开详情", theme.BLUE, theme.BLUE_SOFT), ("switch", "切换直播间", theme.AMBER, theme.AMBER_SOFT), ("total_run", "总运行", theme.BLUE, theme.BLUE_SOFT), ] for idx, (key, title, color, soft) in enumerate(kpis): self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=6, pady=5) panels = tk.Frame(self.root, bg=theme.BG) panels.pack(fill="both", expand=True) for col in range(2): panels.grid_columnconfigure(col, weight=1, uniform="stats") for row in range(3): panels.grid_rowconfigure(row, weight=1) slots = [] for idx in range(6): slot = tk.Frame(panels, bg=theme.BG) slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 10, 10 if idx % 2 == 0 else 0), pady=7) slots.append(slot) core = self._group(slots[0], "核心流程") for key, label, color in [ ("bar.seen", "识别福袋", theme.TEAL), ("bar.open", "打开详情", theme.BLUE), ("bar.click", "点击参与", theme.AMBER), ("bar.attend", "参与成功", theme.GREEN), ]: self._bar_row(core, key, label, color) self._metric_row(core, "win_rate", "中奖率", theme.RED) efficiency = self._group(slots[1], "效率与动作") self._metric_row(efficiency, "seen_rate", "识别效率", theme.TEAL) self._metric_row(efficiency, "attend_rate", "参与效率", theme.GREEN) self._metric_row(efficiency, "switch_rate", "切换频率", theme.AMBER) self._metric_row(efficiency, "ocr_rate", "OCR成功率", theme.BLUE) skip = self._group(slots[2], "过滤与跳过") for key, label, color in [ ("skip.value_low", "价值过低", theme.AMBER), ("skip.participants_low", "人数过少", theme.BLUE), ("skip.participants_high", "人数过多", theme.BLUE), ("skip.content", "内容过滤", theme.TEAL), ("skip.countdown_short", "倒计时太短", theme.RED), ("skip.countdown_long", "倒计时太长", theme.AMBER), ]: self._bar_row(skip, key, label, color) reservation = self._group(slots[3], "预约与回访") self._metric_row(reservation, "reservation_recorded", "记录预约", theme.TEAL) self._metric_row(reservation, "reservation_back", "回退成功", theme.GREEN) self._metric_row(reservation, "reservation_verify", "回退校验", theme.BLUE) self._metric_row(reservation, "reservation_high", "高价值预约", theme.AMBER) health = self._group(slots[4], "运行健康") self._metric_row(health, "error_total", "总错误数", theme.RED) self._metric_row(health, "vision_errors", "识别/截图异常", theme.RED) self._metric_row(health, "detail_errors", "详情异常", theme.RED) self._metric_row(health, "slow_operations", "慢操作", theme.AMBER) latest = self._group(slots[5], "最近福袋") self._metric_row(latest, "last_content", "内容", theme.TEXT) self._metric_row(latest, "last_countdown", "倒计时", theme.BLUE) self._metric_row(latest, "last_value", "价值", theme.AMBER) self._metric_row(latest, "last_people", "人数/份数", theme.TEAL) def _set(self, key: str, value: object, hint: object | None = None) -> None: if f"{key}.value" in self.vars: self.vars[f"{key}.value"].set(str(value)) if hint is not None and f"{key}.hint" in self.vars: self.vars[f"{key}.hint"].set(str(hint)) def _set_bar(self, key: str, value: int, total: int) -> None: if key not in self.bars: return value_var, fill = self.bars[key] value_var.set(f"{value} {_fmt_rate(value, total)}") pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total)) fill.place_configure(relwidth=pct) def update(self, stats: dict[str, Any], current_run: str, total_run: str) -> None: uptime = int(stats.get("uptime_seconds") or 0) if uptime > 0: current_run = _fmt_duration(uptime) seen = _counter(stats, "fudai_seen_unique") open_detail = _counter(stats, "fudai_open_detail_unique") click = _counter(stats, "fudai_click_attend_unique") attend = _counter(stats, "fudai_attend_ok_unique") win = _counter(stats, "fudai_result_win") no_win = _counter(stats, "fudai_result_no_win") switch = _counter(stats, "switch_room") self._set("status", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}") self._set("current_run", current_run, "当前轮次") self._set("attend", attend, "去重口径") self._set("wins", win, "开奖结果") self._set("seen", seen, "唯一口径") self._set("open", open_detail, "详情页") self._set("switch", switch, "运行动作") self._set("total_run", total_run, "日志累计") self._set_bar("bar.seen", seen, max(seen, 1)) self._set_bar("bar.open", open_detail, max(seen, 1)) self._set_bar("bar.click", click, max(open_detail, 1)) self._set_bar("bar.attend", attend, max(click, attend, 1)) self._set("win_rate", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}") self._set("seen_rate", _per_hour(seen, uptime), "每小时识别福袋") self._set("attend_rate", _per_hour(attend, uptime), "每小时成功参与") self._set("switch_rate", _per_hour(switch, uptime), "每小时切换直播间") ocr_attempt = _counter(stats, "ocr_attempt") self._set("ocr_rate", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}") skips = [ ("skip.value_low", "fudai_skip_value_low"), ("skip.participants_low", "fudai_skip_participants_low"), ("skip.participants_high", "fudai_skip_participants_high"), ("skip.content", "fudai_skip_content"), ("skip.countdown_short", "fudai_skip_countdown_short"), ("skip.countdown_long", "fudai_skip_countdown_long"), ] skip_total = sum(_counter(stats, key) for _, key in skips) for bar_key, counter_key in skips: self._set_bar(bar_key, _counter(stats, counter_key), max(skip_total, 1)) recorded = _counter(stats, "reservation_recorded") back_success = _counter(stats, "reservation_back_success") verify_ok = _counter(stats, "reservation_back_verify_ok") verify_fail = _counter(stats, "reservation_back_verify_fail") self._set("reservation_recorded", recorded, "累计写入预约队列") self._set("reservation_back", back_success, f"成功率 {_fmt_rate(back_success, recorded)}") self._set("reservation_verify", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}") self._set("reservation_high", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高") total_errors = _counter(stats, "error_total") detail_errors = _counter(stats, "error_read_detail") + _counter(stats, "fudai_open_error") vision_errors = _counter(stats, "error_ocr") + _counter(stats, "error_screenshot") + _counter(stats, "error_detection") self._set("error_total", total_errors, "运行日志异常计数") self._set("vision_errors", vision_errors, "OCR、截图、识别") self._set("detail_errors", detail_errors, "读详情或打开失败") self._set("slow_operations", _counter(stats, "slow_operation"), ">5秒操作") last = stats.get("fudai_last", {}) or {} self._set("last_content", last.get("content") or "-", "") self._set("last_countdown", last.get("countdown") or "-", "") self._set("last_value", last.get("prize_value_yuan") or "-", "元") self._set("last_people", f"{last.get('participants') or '-'} / {last.get('copies') or '-'}", "")