Files
douyi_guaji_main/gui/dashboard_app/data.py
T

270 lines
9.8 KiB
Python

from __future__ import annotations
import json
import os
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from douyin.core import path_config
from douyin.reservation.reservation_logic import _normalize_room_title_for_matching
@dataclass
class DashboardData:
cfg: dict[str, Any]
run_log: list[str]
action_log: list[str]
reservations_state: dict[str, Any]
reservations: list[dict[str, Any]]
high_value_rooms: list[dict[str, Any]]
mapping_rows: list[dict[str, Any]]
win_images: list[Path]
current_screenshot_path: Path | None
screenshot_path: Path | None
ocr_files: list[Path]
def _read_json(path: str | Path, default: Any) -> Any:
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return default
def _tail(path: str | Path, limit: int = 220) -> list[str]:
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()[-limit:]
return [line.rstrip("\n") for line in lines if line.strip()]
except Exception:
return []
def _list_images(path: str | Path, limit: int = 40) -> list[Path]:
root = Path(path)
if not root.exists():
return []
items = [
p for p in root.iterdir()
if p.is_file() and p.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}
]
items.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)
return items[:limit]
def _normalize_rows(raw: Any, keys: tuple[str, ...]) -> list[dict[str, Any]]:
if isinstance(raw, dict):
for key in keys:
value = raw.get(key)
if isinstance(value, list):
return [x for x in value if isinstance(x, dict)]
return [raw] if raw else []
if isinstance(raw, list):
return [x for x in raw if isinstance(x, dict)]
return []
def _text(value: Any, default: str = "-") -> str:
if value is None:
return default
text = str(value).strip()
return text if text else default
def _first_text(source: dict[str, Any], *keys: str, default: str = "-") -> str:
for key in keys:
value = source.get(key)
if value not in (None, ""):
return _text(value, default)
return default
def _format_countdown(detail: dict[str, Any]) -> str:
time_text = _first_text(detail, "time_text", "countdown", "countdown_text")
if time_text != "-":
return time_text
mm = _text(detail.get("countdown_mm"), "")
ss = _text(detail.get("countdown_ss"), "")
if mm and ss:
return f"{mm.zfill(2)}:{ss.zfill(2)}"
return mm or ss or "-"
def _common_prefix_len(left: str, right: str) -> int:
count = 0
for lch, rch in zip(left, right):
if lch != rch:
break
count += 1
return count
def _room_title_norms_match(left_norm: str, right_norm: str) -> bool:
if not left_norm or not right_norm:
return False
if left_norm == right_norm or left_norm in right_norm or right_norm in left_norm:
return True
if min(len(left_norm), len(right_norm)) < 8:
return False
return _common_prefix_len(left_norm, right_norm) >= 8
def _merge_mapping_row(base: dict[str, Any], extra: dict[str, Any]) -> dict[str, Any]:
if not base:
return dict(extra)
merged = dict(base)
if merged.get("has_fudai") != "是" and extra.get("has_fudai") == "是":
for key in ("has_fudai", "value", "countdown", "participants", "copies", "button", "task", "content"):
merged[key] = extra.get(key, merged.get(key, "-"))
if merged.get("reserved") != "是" and extra.get("reserved") == "是":
merged["reserved"] = "是"
merged_positions = set(str(v) for v in merged.get("_merged_positions", []) or [])
merged_positions.add(str(merged.get("pos", "")))
merged_positions.add(str(extra.get("pos", "")))
merged["_merged_positions"] = sorted(
[v for v in merged_positions if v],
key=lambda v: int(v) if str(v).isdigit() else 999999,
)
return merged
def _merge_similar_mapping_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
merged: list[dict[str, Any]] = []
norm_by_index: list[str] = []
for row in rows:
title_norm = _normalize_room_title_for_matching(
str(row.get("title") or row.get("raw_title") or "")
)
target_idx = None
for idx, old_norm in enumerate(norm_by_index):
if _room_title_norms_match(old_norm, title_norm):
target_idx = idx
break
if target_idx is None:
merged.append(dict(row))
norm_by_index.append(title_norm)
else:
merged[target_idx] = _merge_mapping_row(merged[target_idx], row)
for row in merged:
row.pop("_merged_positions", None)
return merged
def _mapping_rows() -> list[dict[str, Any]]:
raw = _read_json(Path(path_config.get_project_root()) / "douyin" / "core" / "state" / "room_pos_map.json", {})
reservations = _read_json(path_config.get_reservations_path(), {})
reserved_positions = set()
for item in _normalize_rows(reservations, ("queue", "reservations", "items")):
pos = item.get("pos_seen") or item.get("pos") or item.get("room_pos")
if pos not in (None, ""):
reserved_positions.add(str(pos))
rows: list[dict[str, Any]] = []
if isinstance(raw, dict) and "_meta" in raw:
raw = {key: value for key, value in raw.items() if key != "_meta"}
if isinstance(raw, dict):
source = raw.get("items") or raw.get("records") or raw.get("rooms") or raw
iterable = source.items() if isinstance(source, dict) else enumerate(source if isinstance(source, list) else [])
elif isinstance(raw, list):
iterable = enumerate(raw)
else:
iterable = []
for key, value in iterable:
if str(key).startswith("_"):
continue
if not isinstance(value, dict):
rows.append({
"pos": key,
"title": _text(value),
"raw_title": "-",
"reserved": "是" if str(key) in reserved_positions else "-",
"has_fudai": "-",
"value": "-",
"countdown": "-",
"participants": "-",
"copies": "-",
"button": "-",
"task": "-",
"content": "-",
"updated": "-",
})
continue
detail = value.get("fudai_detail") if isinstance(value.get("fudai_detail"), dict) else {}
pos = _first_text(value, "pos", "room_pos", "pos_seen", default=str(key))
updated = (
value.get("timestamp")
or value.get("updated_at")
or value.get("ts")
or detail.get("timestamp")
or value.get("time")
)
rows.append({
"pos": pos,
"title": _first_text(value, "title", "room_title", "live_room_title", "title_raw"),
"raw_title": _first_text(value, "title_raw", "raw_title", "live_room_title_raw"),
"reserved": "是" if pos in reserved_positions or str(key) in reserved_positions else "-",
"has_fudai": "是" if value.get("has_fudai") else "-",
"value": _first_text(detail, "prize_value_yuan", "value", "value_raw"),
"countdown": _format_countdown(detail),
"participants": _first_text(detail, "participants"),
"copies": _first_text(detail, "copies"),
"button": _first_text(detail, "button_text", "button_text_raw"),
"task": _first_text(detail, "task_list"),
"content": _first_text(value, "fudai_content", "content", default=_first_text(detail, "content")),
"updated": fmt_ts(updated) if updated else "-",
})
def sort_key(row: dict[str, Any]) -> tuple[int, str]:
pos = str(row.get("pos", ""))
return (int(pos), "") if pos.isdigit() else (999999, pos)
return sorted(_merge_similar_mapping_rows(rows), key=sort_key)
def load_dashboard_data() -> DashboardData:
cfg_path = path_config.get_config_path()
cfg = _read_json(cfg_path, {})
reservations_raw = _read_json(path_config.get_reservations_path(), {})
high_raw = _read_json(path_config.get_high_value_rooms_path(), {})
pic_dir = Path(path_config.get_pic_dir())
current_screenshot = Path(path_config.get_screenshot_path())
return DashboardData(
cfg=cfg if isinstance(cfg, dict) else {},
run_log=_tail(path_config.get_log_file_path(), 240) or _tail(path_config.get_simple_log_path(), 240),
action_log=_tail(path_config.get_actions_log_path(), 240),
reservations_state=reservations_raw if isinstance(reservations_raw, dict) else {},
reservations=_normalize_rows(reservations_raw, ("reservations", "items", "queue")),
high_value_rooms=_normalize_rows(high_raw, ("rooms", "items", "records")),
mapping_rows=_mapping_rows(),
win_images=_list_images(pic_dir / "lottery_prize_captures", 60),
current_screenshot_path=current_screenshot if current_screenshot.exists() else None,
screenshot_path=current_screenshot if current_screenshot.exists() else None,
ocr_files=sorted((pic_dir / "ocr").glob("*"), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)[:20]
if (pic_dir / "ocr").exists() else [],
)
def cfg_get(cfg: dict[str, Any], *keys: str, default: Any = "-") -> Any:
cur: Any = cfg
for key in keys:
if not isinstance(cur, dict) or key not in cur:
return default
cur = cur[key]
return cur
def fmt_ts(value: Any) -> str:
try:
ts = float(value)
if ts <= 0:
return "-"
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
except Exception:
return str(value or "-")