gui_app.py 的 refresh_stats 闭包是 705 行纯字符串构建:把 runner.get_stats() 的字典格式化成多个分段(基本信息/快速汇总/核心统计/跳过/OCR/详情/福袋查找/ 性能/粉丝团/切换/预约/错误/价值/最近福袋/中奖记录)。 抽到 gui/components/stats_formatter.py: - format_stats(stats: Dict) -> List[str] 主入口 - 14 个 _append_* 子段构建器(每段一个,按需追加) - _section_lines(title, body) 标题包装 闭包改为 16 行委托:调 format_stats + 写入 ScrolledText。 新增 32 个单元测试覆盖: - 空 dict / 缺字段时的兜底 - 基本运行状态(uptime / pid / exit_code 各种格式) - 各分段的"有数据 / 无数据"条件 - 关键率计算(打开成功率/点击率/参与成功率/中奖率/跳过率/错误频率) - 边界情况(attend_ok > clicks 检测到已参与,结果未开奖警告,wins 截断到 10 条) 1393 passed (+32)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
571 lines
24 KiB
Python
571 lines
24 KiB
Python
"""gui/components/stats_formatter - 把 runner.get_stats() 字典格式化成可显示的字符串列表
|
||
|
||
从 gui_app.py 的 refresh_stats 闭包抽出来的纯字符串构建逻辑。原本 695 行嵌在
|
||
main() 里,依赖 stats dict + datetime;这里改成纯函数 format_stats(stats) -> list[str],
|
||
caller 自己负责往 ScrolledText 写。
|
||
|
||
入口:format_stats(stats: dict) -> list[str]
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any, Dict, List
|
||
|
||
|
||
def format_stats(stats: Dict[str, Any]) -> List[str]:
|
||
"""把 runner.get_stats() 的字典格式化成可显示的多行字符串。"""
|
||
lines: List[str] = []
|
||
|
||
# ===== 基本信息 =====
|
||
_append_basic_info(lines, stats)
|
||
counters = stats.get("counters", {}) or {}
|
||
uptime_seconds = stats.get("uptime_seconds", 0) or 0
|
||
|
||
# ===== 快速汇总 =====
|
||
fudai_seen_unique = counters.get("fudai_seen_unique", 0)
|
||
fudai_attend_ok_unique = counters.get("fudai_attend_ok_unique", 0)
|
||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||
if fudai_seen_unique > 0 or fudai_attend_ok_unique > 0 or fudai_result_win > 0:
|
||
_append_quick_summary(
|
||
lines,
|
||
fudai_seen_unique,
|
||
fudai_attend_ok_unique,
|
||
fudai_result_win,
|
||
fudai_order_success,
|
||
uptime_seconds,
|
||
)
|
||
|
||
# ===== 核心统计 =====
|
||
_append_core_stats(lines, counters, uptime_seconds, fudai_seen_unique, fudai_attend_ok_unique)
|
||
|
||
# ===== 跳过原因 =====
|
||
_append_skip_stats(lines, counters, fudai_seen_unique)
|
||
|
||
# ===== 高价值预约 / 等待开奖 =====
|
||
if counters.get("fudai_reserved_high_value", 0) > 0:
|
||
lines.extend(_section_lines("高价值预约统计", [
|
||
f"倒计时大于阈值但价值达到高价值阈值,记录预约: {counters['fudai_reserved_high_value']}",
|
||
]))
|
||
if counters.get("fudai_waiting_lottery", 0) > 0:
|
||
lines.extend(_section_lines("等待开奖统计", [
|
||
f"等待开奖次数: {counters['fudai_waiting_lottery']}",
|
||
]))
|
||
|
||
# ===== 阶段诊断 =====
|
||
_append_stage_diag_stats(lines, counters)
|
||
|
||
# ===== OCR / 详情识别 / 福袋查找 =====
|
||
_append_ocr_stats(lines, counters)
|
||
_append_detail_read_stats(lines, counters)
|
||
_append_fudai_find_stats(lines, counters)
|
||
_append_perf_stats(lines, counters)
|
||
|
||
# ===== 粉丝团 / 直播间切换 =====
|
||
_append_fansclub_stats(lines, counters)
|
||
_append_switch_stats(lines, counters, uptime_seconds)
|
||
|
||
# ===== 预约相关(详细版)=====
|
||
_append_reservation_stats(lines, counters)
|
||
|
||
# ===== 错误统计(详细版)=====
|
||
_append_error_stats(lines, counters, uptime_seconds)
|
||
|
||
# ===== 价值统计 =====
|
||
_append_value_stats(lines, stats.get("events", []) or [], fudai_seen_unique)
|
||
|
||
# ===== 最近一次福袋信息 =====
|
||
_append_fudai_last(lines, stats.get("fudai_last", {}) or {})
|
||
|
||
# ===== 中奖记录 =====
|
||
_append_wins(lines, stats.get("wins", []) or [])
|
||
|
||
# 兜底:从来没数据时给个占位
|
||
if not lines:
|
||
lines.extend(["=" * 60, "统计信息", "=" * 60, "暂无统计数据", "", "提示:请先运行程序以收集统计数据"])
|
||
|
||
return lines
|
||
|
||
|
||
# ============================================================
|
||
# 子段构建器
|
||
# ============================================================
|
||
|
||
def _section_lines(title: str, body: List[str]) -> List[str]:
|
||
out = ["=" * 60, title, "=" * 60]
|
||
out.extend(body)
|
||
out.append("")
|
||
return out
|
||
|
||
|
||
def _append_basic_info(lines: List[str], stats: Dict[str, Any]) -> None:
|
||
lines.extend(["=" * 60, "运行状态信息", "=" * 60])
|
||
lines.append(f"运行状态: {'运行中' if stats.get('running') else '未运行'}")
|
||
lines.append(f"PID: {stats.get('pid') or '-'}")
|
||
|
||
uptime_seconds = stats.get("uptime_seconds", 0) or 0
|
||
if uptime_seconds > 0:
|
||
h = uptime_seconds // 3600
|
||
m = (uptime_seconds % 3600) // 60
|
||
s = uptime_seconds % 60
|
||
lines.append(f"运行时长: {h:02d}:{m:02d}:{s:02d}")
|
||
else:
|
||
lines.append("运行时长: -")
|
||
|
||
last_log_ts = stats.get("last_log_ts")
|
||
if last_log_ts:
|
||
lines.append("最近日志时间: " + datetime.fromtimestamp(last_log_ts).strftime("%Y-%m-%d %H:%M:%S"))
|
||
else:
|
||
lines.append("最近日志时间: -")
|
||
|
||
exit_code = stats.get("exit_code")
|
||
lines.append(f"退出码: {exit_code if exit_code is not None else '-'}")
|
||
lines.append("")
|
||
|
||
|
||
def _append_quick_summary(
|
||
lines: List[str],
|
||
fudai_seen_unique: int,
|
||
fudai_attend_ok_unique: int,
|
||
fudai_result_win: int,
|
||
fudai_order_success: int,
|
||
uptime_seconds: int,
|
||
) -> None:
|
||
lines.extend(["=" * 60, "快速汇总", "=" * 60])
|
||
lines.append(f"识别福袋: {fudai_seen_unique} 个")
|
||
lines.append(f"参与成功: {fudai_attend_ok_unique} 次")
|
||
lines.append(f"中奖次数: {fudai_result_win} 次")
|
||
lines.append(f"下单成功: {fudai_order_success} 次")
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
lines.append(f"运行效率: {fudai_attend_ok_unique / hours:.1f} 次参与/小时")
|
||
lines.append("")
|
||
|
||
|
||
def _append_core_stats(
|
||
lines: List[str],
|
||
counters: Dict[str, Any],
|
||
uptime_seconds: int,
|
||
fudai_seen_unique: int,
|
||
fudai_attend_ok_unique: int,
|
||
) -> None:
|
||
lines.extend(["=" * 60, "核心统计", "=" * 60])
|
||
|
||
fudai_open_detail_unique = counters.get("fudai_open_detail_unique", 0)
|
||
fudai_click_attend_unique = counters.get("fudai_click_attend_unique", 0)
|
||
fudai_attend_fail = counters.get("fudai_attend_fail", 0)
|
||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||
fudai_result_no_win = counters.get("fudai_result_no_win", 0)
|
||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||
|
||
lines.append(f"福袋识别次数: {fudai_seen_unique}")
|
||
lines.append(f"打开详情: {fudai_open_detail_unique}")
|
||
if fudai_seen_unique > 0:
|
||
open_rate = (fudai_open_detail_unique / fudai_seen_unique) * 100
|
||
lines.append(f" 打开成功率: {open_rate:.1f}%")
|
||
|
||
lines.append(f"点击参与: {fudai_click_attend_unique}")
|
||
if fudai_open_detail_unique > 0:
|
||
click_rate = (fudai_click_attend_unique / fudai_open_detail_unique) * 100
|
||
lines.append(f" 点击率: {click_rate:.1f}%")
|
||
|
||
lines.append(f"参与成功: {fudai_attend_ok_unique}")
|
||
lines.append(f"参与失败: {fudai_attend_fail}")
|
||
if fudai_click_attend_unique > 0:
|
||
click_attend_success = min(fudai_attend_ok_unique, fudai_click_attend_unique)
|
||
success_rate = (click_attend_success / fudai_click_attend_unique) * 100
|
||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||
if fudai_attend_ok_unique > fudai_click_attend_unique:
|
||
detected_already = fudai_attend_ok_unique - fudai_click_attend_unique
|
||
lines.append(f" (其中 {detected_already} 次为检测到已参与状态)")
|
||
elif fudai_attend_ok_unique > 0 or fudai_attend_fail > 0:
|
||
total_attend = fudai_attend_ok_unique + fudai_attend_fail
|
||
if total_attend > 0:
|
||
success_rate = (fudai_attend_ok_unique / total_attend) * 100
|
||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||
|
||
lines.append(f"中奖次数: {fudai_result_win}")
|
||
lines.append(f"未中奖次数: {fudai_result_no_win}")
|
||
total_results = fudai_result_win + fudai_result_no_win
|
||
if fudai_attend_ok_unique > 0 and total_results < fudai_attend_ok_unique:
|
||
pending = fudai_attend_ok_unique - total_results
|
||
lines.append(f" 注意: 有 {pending} 次参与成功尚未开奖(或开奖结果未识别)")
|
||
if total_results > 0:
|
||
win_rate = (fudai_result_win / total_results) * 100
|
||
lines.append(f" 中奖率: {win_rate:.1f}%")
|
||
lines.append(f"下单成功: {fudai_order_success}")
|
||
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
lines.append("")
|
||
lines.append("效率统计(每小时):")
|
||
if fudai_seen_unique > 0:
|
||
lines.append(f" 识别福袋: {fudai_seen_unique / hours:.1f} 个/小时")
|
||
if fudai_attend_ok_unique > 0:
|
||
lines.append(f" 参与成功: {fudai_attend_ok_unique / hours:.1f} 次/小时")
|
||
if total_results > 0:
|
||
lines.append(f" 开奖次数: {total_results / hours:.1f} 次/小时")
|
||
if fudai_result_win > 0:
|
||
lines.append(f" 中奖次数: {fudai_result_win / hours:.2f} 次/小时")
|
||
lines.append("")
|
||
|
||
|
||
def _append_skip_stats(lines: List[str], counters: Dict[str, Any], fudai_seen_unique: int) -> None:
|
||
skip_stats = [
|
||
("fudai_skip_value_low", "跳过-价值过低"),
|
||
("fudai_skip_participants_low", "跳过-人数过少"),
|
||
("fudai_skip_participants_high", "跳过-人数过多"),
|
||
("fudai_skip_content", "跳过-内容不理想"),
|
||
("fudai_skip_countdown_short", "跳过-倒计时太短"),
|
||
("fudai_skip_countdown_long", "跳过-倒计时太长"),
|
||
("fudai_skip_watch_required", "跳过-需要看播"),
|
||
]
|
||
skip_total = sum(counters.get(k, 0) for k, _ in skip_stats)
|
||
if skip_total <= 0:
|
||
return
|
||
body: List[str] = [f"总跳过次数: {skip_total}"]
|
||
if fudai_seen_unique > 0:
|
||
body.append(f"跳过率: {(skip_total / fudai_seen_unique) * 100:.1f}%")
|
||
body.append("")
|
||
for key, label in skip_stats:
|
||
v = counters.get(key, 0)
|
||
if v > 0:
|
||
pct = (v / skip_total) * 100 if skip_total > 0 else 0
|
||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||
lines.extend(_section_lines("跳过原因统计", body))
|
||
|
||
|
||
def _append_stage_diag_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
complete = counters.get("stage_diagnosis_complete", 0)
|
||
failed = counters.get("stage_diagnosis_failed", 0)
|
||
if complete <= 0 and failed <= 0:
|
||
return
|
||
body = [f"诊断完成: {complete}", f"诊断失败: {failed}"]
|
||
if complete > 0:
|
||
success_rate = (complete / (complete + failed)) * 100
|
||
body.append(f"成功率: {success_rate:.1f}%")
|
||
lines.extend(_section_lines("阶段诊断统计", body))
|
||
|
||
|
||
def _append_ocr_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
attempt = counters.get("ocr_attempt", 0)
|
||
success = counters.get("ocr_success", 0)
|
||
failed = counters.get("ocr_failed", 0)
|
||
if attempt <= 0:
|
||
return
|
||
body = [f"OCR尝试次数: {attempt}", f"OCR成功次数: {success}", f"OCR失败次数: {failed}"]
|
||
total_results = success + failed
|
||
if total_results < attempt:
|
||
body.append(f" 注意: 有 {attempt - total_results} 次尝试未记录结果(可能日志格式不匹配)")
|
||
body.append(f"OCR成功率: {(success / attempt) * 100:.1f}%")
|
||
lines.extend(_section_lines("OCR识别统计", body))
|
||
|
||
|
||
def _append_detail_read_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
attempt = counters.get("fudai_detail_read_attempt", 0)
|
||
if attempt <= 0:
|
||
return
|
||
success = counters.get("fudai_detail_read_success", 0)
|
||
failed = counters.get("fudai_detail_read_failed", 0)
|
||
body = [f"详情识别尝试: {attempt}", f"详情识别成功: {success}", f"详情识别失败: {failed}"]
|
||
total = success + failed
|
||
if total < attempt:
|
||
body.append(f" 注意: 有 {attempt - total} 次尝试未记录结果(可能日志格式不匹配)")
|
||
body.append(f"详情识别成功率: {(success / attempt) * 100:.1f}%")
|
||
lines.extend(_section_lines("详情识别统计", body))
|
||
|
||
|
||
def _append_fudai_find_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
success = counters.get("fudai_find_success", 0)
|
||
not_found = counters.get("fudai_find_not_found", 0)
|
||
timeout = counters.get("fudai_find_timeout", 0)
|
||
if success <= 0 and not_found <= 0 and timeout <= 0:
|
||
return
|
||
body = [f"查找成功: {success}", f"未找到: {not_found}", f"等待超时: {timeout}"]
|
||
lines.extend(_section_lines("福袋查找统计", body))
|
||
|
||
|
||
def _append_perf_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
slow = counters.get("slow_operation", 0)
|
||
if slow > 0:
|
||
lines.extend(_section_lines("性能统计", [f"慢操作(>5秒)次数: {slow}"]))
|
||
|
||
|
||
def _append_fansclub_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
items = [
|
||
("fansclub_required", "需要粉丝团"),
|
||
("fansclub_manual_needed", "需手动加入"),
|
||
("fansclub_unresolved", "未解决"),
|
||
]
|
||
total = sum(counters.get(k, 0) for k, _ in items)
|
||
if total <= 0:
|
||
return
|
||
body: List[str] = []
|
||
for key, label in items:
|
||
v = counters.get(key, 0)
|
||
if v > 0:
|
||
pct = (v / total) * 100 if total > 0 else 0
|
||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||
lines.extend(_section_lines("粉丝团相关统计", body))
|
||
|
||
|
||
def _append_switch_stats(lines: List[str], counters: Dict[str, Any], uptime_seconds: int) -> None:
|
||
total = counters.get("switch_room", 0)
|
||
if total <= 0:
|
||
return
|
||
body = [f"总切换次数: {total}"]
|
||
if uptime_seconds > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
body.append(f"切换频率: {total / hours:.1f} 次/小时")
|
||
body.append("")
|
||
reasons = [
|
||
("switch_room_no_fudai", "无福袋"),
|
||
("switch_room_participants", "人数不符合"),
|
||
("switch_room_value", "价值不符合"),
|
||
("switch_room_content", "内容不符合"),
|
||
("switch_room_countdown", "倒计时不符合"),
|
||
("switch_room_attend_fail", "参与失败"),
|
||
]
|
||
for key, label in reasons:
|
||
v = counters.get(key, 0)
|
||
if v > 0:
|
||
pct = (v / total) * 100 if total > 0 else 0
|
||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||
lines.extend(_section_lines("直播间切换统计", body))
|
||
|
||
|
||
def _append_reservation_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||
keys = [
|
||
"reservation_recorded",
|
||
"reservation_window_entered",
|
||
"reservation_back_success",
|
||
"reservation_back_verify_ok",
|
||
"reservation_back_verify_fail",
|
||
"reservation_window_not_reached",
|
||
"reservation_expired",
|
||
"reservation_queue_empty",
|
||
"reservation_locked",
|
||
"reservation_back_to_first",
|
||
"reservation_queue_full_wait",
|
||
"reservation_drop_low_value",
|
||
"reservation_clear",
|
||
"reservation_back_direct_attend",
|
||
"reservation_queue_full_back_attend",
|
||
"reservation_duplicate_detected",
|
||
"reservation_back_operation",
|
||
]
|
||
values = {k: counters.get(k, 0) for k in keys}
|
||
total = sum(values.values())
|
||
if total <= 0 and values["reservation_recorded"] <= 0:
|
||
return
|
||
|
||
body: List[str] = []
|
||
if values["reservation_recorded"] > 0:
|
||
body.append(f"记录预约总数: {values['reservation_recorded']}")
|
||
if values["reservation_back_success"] > 0:
|
||
body.append(f"成功回退到预约直播间: {values['reservation_back_success']}")
|
||
|
||
verify_total = values["reservation_back_verify_ok"] + values["reservation_back_verify_fail"]
|
||
if verify_total > 0:
|
||
verify_rate = (values["reservation_back_verify_ok"] / verify_total) * 100
|
||
body.append(
|
||
f"回退校验: {values['reservation_back_verify_ok']} 成功 / "
|
||
f"{values['reservation_back_verify_fail']} 失败 (成功率: {verify_rate:.1f}%)"
|
||
)
|
||
|
||
if values["reservation_window_entered"] > 0:
|
||
body.append(f"进入预约参与窗口: {values['reservation_window_entered']}")
|
||
if values["reservation_window_not_reached"] > 0:
|
||
body.append(f"时间窗口未到(跳过): {values['reservation_window_not_reached']}")
|
||
if values["reservation_expired"] > 0:
|
||
body.append(f"过期预约(已清理): {values['reservation_expired']}")
|
||
if values["reservation_locked"] > 0:
|
||
body.append(f"锁定期未结束(跳过): {values['reservation_locked']}")
|
||
if values["reservation_queue_empty"] > 0:
|
||
body.append(f"预约队列为空(检查次数): {values['reservation_queue_empty']}")
|
||
if values["reservation_queue_full_wait"] > 0:
|
||
body.append(f"队列已满等待: {values['reservation_queue_full_wait']}")
|
||
if values["reservation_back_to_first"] > 0:
|
||
body.append(f"回退到第一个直播间: {values['reservation_back_to_first']}")
|
||
if values["reservation_drop_low_value"] > 0:
|
||
body.append(f"丢弃低价值预约: {values['reservation_drop_low_value']}")
|
||
if values["reservation_clear"] > 0:
|
||
body.append(f"清空预约队列: {values['reservation_clear']}")
|
||
if values["reservation_duplicate_detected"] > 0:
|
||
body.append(f"检测到重复预约: {values['reservation_duplicate_detected']}")
|
||
if values["reservation_back_direct_attend"] > 0:
|
||
body.append(f"回退后直接参与: {values['reservation_back_direct_attend']}")
|
||
if values["reservation_queue_full_back_attend"] > 0:
|
||
body.append(f"队列满回退后参与: {values['reservation_queue_full_back_attend']}")
|
||
if values["reservation_back_operation"] > 0:
|
||
body.append(f"回退操作次数: {values['reservation_back_operation']}")
|
||
|
||
if values["reservation_recorded"] > 0 and values["reservation_back_success"] > 0:
|
||
back_rate = (values["reservation_back_success"] / values["reservation_recorded"]) * 100
|
||
body.append(
|
||
f"预约回退成功率: {back_rate:.1f}% "
|
||
f"({values['reservation_back_success']}/{values['reservation_recorded']})"
|
||
)
|
||
|
||
lines.extend(_section_lines("预约相关统计(详细)", body))
|
||
|
||
|
||
def _append_error_stats(lines: List[str], counters: Dict[str, Any], uptime_seconds: int) -> None:
|
||
keys = [
|
||
"error_total", "error_unbound_local", "error_attribute", "error_key",
|
||
"error_value", "error_type", "error_timeout", "error_connection",
|
||
"error_ocr", "error_screenshot", "error_detection", "error_stage_diagnosis",
|
||
"error_read_detail", "error_config_load", "error_state_file",
|
||
"error_live_room_detect", "error_fudai_find", "fudai_open_error",
|
||
"fudai_open_error_too_many",
|
||
]
|
||
v = {k: counters.get(k, 0) for k in keys}
|
||
total_all = sum(v.values())
|
||
if total_all <= 0:
|
||
return
|
||
|
||
body: List[str] = []
|
||
if v["error_total"] > 0:
|
||
body.append(f"总错误数: {v['error_total']}")
|
||
|
||
fudai_errors = v["fudai_open_error"] + v["fudai_open_error_too_many"]
|
||
if fudai_errors > 0:
|
||
body.extend(["", "福袋相关错误:"])
|
||
if v["fudai_open_error"] > 0:
|
||
body.append(f" 打开福袋异常: {v['fudai_open_error']}")
|
||
if v["fudai_open_error_too_many"] > 0:
|
||
body.append(f" 打开失败次数过多: {v['fudai_open_error_too_many']}")
|
||
|
||
python_errors = v["error_unbound_local"] + v["error_attribute"] + v["error_key"] + v["error_value"] + v["error_type"]
|
||
if python_errors > 0:
|
||
body.extend(["", "Python异常类型:"])
|
||
if v["error_unbound_local"] > 0:
|
||
body.append(f" UnboundLocalError: {v['error_unbound_local']}")
|
||
if v["error_attribute"] > 0:
|
||
body.append(f" AttributeError: {v['error_attribute']}")
|
||
if v["error_key"] > 0:
|
||
body.append(f" KeyError: {v['error_key']}")
|
||
if v["error_value"] > 0:
|
||
body.append(f" ValueError: {v['error_value']}")
|
||
if v["error_type"] > 0:
|
||
body.append(f" TypeError: {v['error_type']}")
|
||
|
||
module_errors = (
|
||
v["error_ocr"] + v["error_screenshot"] + v["error_detection"]
|
||
+ v["error_stage_diagnosis"] + v["error_read_detail"] + v["error_config_load"]
|
||
+ v["error_state_file"] + v["error_live_room_detect"] + v["error_fudai_find"]
|
||
)
|
||
if module_errors > 0:
|
||
body.extend(["", "功能模块错误:"])
|
||
for key, label in [
|
||
("error_ocr", "OCR识别错误"),
|
||
("error_screenshot", "截图错误"),
|
||
("error_detection", "识别错误"),
|
||
("error_stage_diagnosis", "阶段诊断错误"),
|
||
("error_read_detail", "读取详情错误"),
|
||
("error_config_load", "配置加载错误"),
|
||
("error_state_file", "状态文件错误"),
|
||
("error_live_room_detect", "直播间检测错误"),
|
||
("error_fudai_find", "福袋查找错误"),
|
||
]:
|
||
if v[key] > 0:
|
||
body.append(f" {label}: {v[key]}")
|
||
|
||
network_errors = v["error_timeout"] + v["error_connection"]
|
||
if network_errors > 0:
|
||
body.extend(["", "网络和超时错误:"])
|
||
if v["error_timeout"] > 0:
|
||
body.append(f" 超时错误: {v['error_timeout']}")
|
||
if v["error_connection"] > 0:
|
||
body.append(f" 连接错误: {v['error_connection']}")
|
||
|
||
if uptime_seconds > 0 and total_all > 0:
|
||
hours = uptime_seconds / 3600.0
|
||
if hours > 0:
|
||
body.extend(["", f"错误频率: {total_all / hours:.2f} 次/小时"])
|
||
|
||
lines.extend(_section_lines("错误统计(详细)", body))
|
||
|
||
|
||
def _append_value_stats(lines: List[str], events: List[Dict[str, Any]], fudai_seen_unique: int) -> None:
|
||
prize_values: List[float] = []
|
||
for event in events:
|
||
meta = event.get("meta", {}) or {}
|
||
if "prize_value_yuan" in meta and meta["prize_value_yuan"] is not None:
|
||
try:
|
||
prize_values.append(float(meta["prize_value_yuan"]))
|
||
except (ValueError, TypeError):
|
||
pass
|
||
if not prize_values:
|
||
return
|
||
|
||
total_value = sum(prize_values)
|
||
avg_value = total_value / len(prize_values)
|
||
body = [f"识别到的福袋总数: {len(prize_values)}"]
|
||
if fudai_seen_unique > len(prize_values):
|
||
body.append(
|
||
f" (总识别次数: {fudai_seen_unique},其中 {len(prize_values)} 个成功识别到价值)"
|
||
)
|
||
body.extend([
|
||
f"总价值: {total_value:.2f} 元",
|
||
f"平均价值: {avg_value:.2f} 元",
|
||
f"最高价值: {max(prize_values):.2f} 元",
|
||
f"最低价值: {min(prize_values):.2f} 元",
|
||
"",
|
||
"价值分布:",
|
||
])
|
||
high = sum(1 for x in prize_values if x >= 500)
|
||
mid = sum(1 for x in prize_values if 100 <= x < 500)
|
||
low = sum(1 for x in prize_values if x < 100)
|
||
body.append(f" 高价值(≥500元): {high} ({high/len(prize_values)*100:.1f}%)")
|
||
body.append(f" 中价值(100-500元): {mid} ({mid/len(prize_values)*100:.1f}%)")
|
||
body.append(f" 低价值(<100元): {low} ({low/len(prize_values)*100:.1f}%)")
|
||
lines.extend(_section_lines("价值统计", body))
|
||
|
||
|
||
def _append_fudai_last(lines: List[str], fudai_last: Dict[str, Any]) -> None:
|
||
if not (fudai_last.get("content") or fudai_last.get("countdown")):
|
||
return
|
||
body = [
|
||
f"内容: {fudai_last.get('content') or '-'}",
|
||
f"倒计时: {fudai_last.get('countdown') or '-'}",
|
||
]
|
||
participants = fudai_last.get("participants")
|
||
copies = fudai_last.get("copies")
|
||
if participants is not None and copies is not None:
|
||
body.append(f"参与人数/份数: {participants} / {copies}")
|
||
if participants > 0 and copies > 0:
|
||
ratio = participants / copies
|
||
body.append(f" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})")
|
||
prize_value = fudai_last.get("prize_value_yuan")
|
||
if prize_value is not None:
|
||
body.append(f"奖品价值: {prize_value} 元")
|
||
updated_ts = fudai_last.get("updated_ts")
|
||
if updated_ts:
|
||
body.append("更新时间: " + datetime.fromtimestamp(updated_ts).strftime("%Y-%m-%d %H:%M:%S"))
|
||
lines.extend(_section_lines("最近一次福袋信息", body))
|
||
|
||
|
||
def _append_wins(lines: List[str], wins: List[Dict[str, Any]]) -> None:
|
||
if not wins:
|
||
return
|
||
body: List[str] = []
|
||
for i, win in enumerate(wins[-10:], 1):
|
||
ts = win.get("ts", 0) or 0
|
||
dt_str = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-"
|
||
body.append(f"\n[{i}] 时间: {dt_str}")
|
||
if win.get("content"):
|
||
body.append(f" 内容: {win.get('content')}")
|
||
if win.get("prize_value_yuan"):
|
||
body.append(f" 价值: {win.get('prize_value_yuan')} 元")
|
||
if win.get("participants") and win.get("copies"):
|
||
body.append(f" 人数/份数: {win.get('participants')} / {win.get('copies')}")
|
||
lines.extend([
|
||
"=" * 60,
|
||
f"最近中奖记录(显示最近 {len(wins)} 条)",
|
||
"=" * 60,
|
||
] + body)
|