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 "-" def _group(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=16, pady=(14, 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=16, pady=(0, 14)) return body def _metric_row(parent: tk.Misc, label: str, value: object, hint: str = "", color: str = theme.TEAL) -> None: row = tk.Frame(parent, bg=theme.SURFACE) row.pack(fill="x", pady=4) tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left") tk.Label(row, text=str(value), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right") if hint: tk.Label(parent, text=hint, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4)) def _kpi_tile(parent: tk.Misc, title: str, value: object, hint: str, color: str, soft: str) -> tk.Frame: box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) box.configure(height=104) box.pack_propagate(False) accent = tk.Frame(box, bg=color, width=4) accent.pack(side="left", fill="y") inner = tk.Frame(box, bg=theme.SURFACE) inner.pack(side="left", fill="both", expand=True, padx=14, pady=10) 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, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0)) tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0)) return box def _bar_row(parent: tk.Misc, label: str, value: int, total: int, color: str = theme.TEAL) -> None: row = tk.Frame(parent, bg=theme.SURFACE) row.pack(fill="x", pady=5) tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left") tk.Label(row, text=f"{value} {_fmt_rate(value, total)}", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right") track = tk.Frame(parent, bg=theme.BG_ALT, height=8) track.pack(fill="x", pady=(0, 4)) pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total)) fill = tk.Frame(track, bg=color, height=8) fill.place(relx=0, rely=0, relwidth=pct, relheight=1) 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=104) box.pack_propagate(False) tk.Frame(box, bg=color, width=4).pack(side="left", fill="y") inner = tk.Frame(box, bg=theme.SURFACE) inner.pack(side="left", fill="both", expand=True, padx=14, pady=10) 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", 18, "bold")).pack(anchor="w", pady=(4, 0)) tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 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) row.pack(fill="x", pady=4) tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left") tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right") tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4)) 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=5) 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=8) track.pack(fill="x", pady=(0, 4)) fill = tk.Frame(track, bg=color, height=8) 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=16, pady=(14, 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=16, pady=(0, 14)) 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=4, pady=4) 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 8, 8 if idx % 2 == 0 else 0), pady=6) 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 '-'}", "") def _build_top_cards(parent: tk.Misc, 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) grid = flow_grid(parent, 4) values = [ ("运行状态", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}", theme.TEAL, theme.TEAL_SOFT), ("本次运行", current_run, "当前轮次", 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, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT), ("打开详情", _counter(stats, "fudai_open_detail_unique"), "详情页", theme.BLUE, theme.BLUE_SOFT), ("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT), ("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT), ] for idx, item in enumerate(values): tile = _kpi_tile(grid, *item[:3], color=item[3], soft=item[4]) tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4) def _build_core_flow(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "核心流程") 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") _bar_row(body, "识别福袋", seen, max(seen, 1), theme.TEAL) _bar_row(body, "打开详情", open_detail, max(seen, 1), theme.BLUE) _bar_row(body, "点击参与", click, max(open_detail, 1), theme.AMBER) _bar_row(body, "参与成功", attend, max(click, attend, 1), theme.GREEN) _metric_row(body, "中奖率", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}", theme.RED) def _build_efficiency(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "效率与动作") uptime = int(stats.get("uptime_seconds") or 0) _metric_row(body, "识别效率", _per_hour(_counter(stats, "fudai_seen_unique"), uptime), "每小时识别福袋", theme.TEAL) _metric_row(body, "参与效率", _per_hour(_counter(stats, "fudai_attend_ok_unique"), uptime), "每小时成功参与", theme.GREEN) _metric_row(body, "切换频率", _per_hour(_counter(stats, "switch_room"), uptime), "每小时切换直播间", theme.AMBER) ocr_attempt = _counter(stats, "ocr_attempt") _metric_row(body, "OCR成功率", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}", theme.BLUE) def _build_skip(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "过滤与跳过") items = [ ("价值过低", "fudai_skip_value_low", theme.AMBER), ("人数过少", "fudai_skip_participants_low", theme.BLUE), ("人数过多", "fudai_skip_participants_high", theme.BLUE), ("内容过滤", "fudai_skip_content", theme.TEAL), ("倒计时太短", "fudai_skip_countdown_short", theme.RED), ("倒计时太长", "fudai_skip_countdown_long", theme.AMBER), ("需要看播", "fudai_skip_watch_required", theme.RED), ] total = sum(_counter(stats, key) for _, key, _ in items) if total <= 0: tk.Label(body, text="暂无跳过记录", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8) return for label, key, color in items: value = _counter(stats, key) if value > 0: _bar_row(body, label, value, total, color) def _build_reservation(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "预约与回访") 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") _metric_row(body, "记录预约", recorded, "累计写入预约队列", theme.TEAL) _metric_row(body, "回退成功", back_success, f"成功率 {_fmt_rate(back_success, recorded)}", theme.GREEN) _metric_row(body, "回退校验", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}", theme.BLUE) _metric_row(body, "高价值预约", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高", theme.AMBER) def _build_health(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "运行健康") total = _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") _metric_row(body, "总错误数", total, "运行日志异常计数", theme.RED if total else theme.GREEN) _metric_row(body, "识别/截图异常", vision_errors, "OCR、截图、识别", theme.RED if vision_errors else theme.GREEN) _metric_row(body, "详情异常", detail_errors, "读详情或打开失败", theme.RED if detail_errors else theme.GREEN) _metric_row(body, "慢操作", _counter(stats, "slow_operation"), ">5秒操作", theme.AMBER) def _build_latest(parent: tk.Misc, stats: dict[str, Any]) -> None: body = _group(parent, "最近福袋") last = stats.get("fudai_last", {}) or {} if not (last.get("content") or last.get("countdown")): tk.Label(body, text="暂无最近福袋信息", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8) return _metric_row(body, "内容", last.get("content") or "-", color=theme.TEXT) _metric_row(body, "倒计时", last.get("countdown") or "-", color=theme.BLUE) _metric_row(body, "价值", f"{last.get('prize_value_yuan') or '-'}", "元", theme.AMBER) participants = last.get("participants") copies = last.get("copies") _metric_row(body, "人数/份数", f"{participants or '-'} / {copies or '-'}", color=theme.TEAL) def build_stats_dashboard(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> tk.Frame: _build_top_cards(parent, stats, current_run, total_run) grid = tk.Frame(parent, bg=theme.BG) grid.pack(fill="both", expand=True) for col in range(2): grid.grid_columnconfigure(col, weight=1, uniform="stats") for row in range(3): grid.grid_rowconfigure(row, weight=1) panels = [ _build_core_flow, _build_efficiency, _build_skip, _build_reservation, _build_health, _build_latest, ] for idx, builder in enumerate(panels): slot = tk.Frame(grid, bg=theme.BG) slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6) builder(slot, stats) return grid