douyinWEB/backend/app/stats.py
eric 76afafa6c9 Initial commit: Douyin live monitor with sh2-aligned probe.
Next.js + FastAPI + PocketBase stack for room/session monitoring, cookie sync from sh2, and anti-risk polling defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 09:03:00 -05:00

214 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import statistics
import time
from collections import defaultdict
from datetime import datetime
from typing import Any
from . import db
WEEKDAY_ZH = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
WEEKDAY_EN = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
def _effective_duration(session: dict[str, Any], now: float) -> float:
started = float(session.get("started_at") or 0)
ended = session.get("ended_at")
stored = float(session.get("duration_seconds") or 0)
if ended:
return max(0.0, float(ended) - started) if started else max(0.0, stored)
if started > 0:
return max(0.0, now - started)
return max(0.0, stored)
def summarize_sessions(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
top_anchors: int = 20,
) -> dict[str, Any]:
sessions = db.all_sessions_for_stats(q=q, date_from=date_from, date_to=date_to, status=status)
now = time.time()
by_hour_starts = [0] * 24
by_hour_minutes = [0.0] * 24
by_weekday_starts = [0] * 7
by_weekday_minutes = [0.0] * 7
heatmap_starts = [[0 for _ in range(24)] for _ in range(7)]
heatmap_minutes = [[0.0 for _ in range(24)] for _ in range(7)]
by_date: dict[str, dict[str, Any]] = {}
by_anchor: dict[str, dict[str, Any]] = {}
duration_values: list[float] = []
duration_buckets = {"<15m": 0, "15-60m": 0, "1-3h": 0, "3-6h": 0, "6-12h": 0, ">12h": 0}
active_sessions = 0
for s in sessions:
started = float(s.get("started_at") or 0)
if not started:
continue
duration = _effective_duration(s, now)
duration_values.append(duration)
if not s.get("ended_at"):
active_sessions += 1
dt = datetime.fromtimestamp(started)
hour = dt.hour
weekday = dt.weekday()
by_hour_starts[hour] += 1
by_weekday_starts[weekday] += 1
heatmap_starts[weekday][hour] += 1
# occupancy minutes across hours
end_ts = float(s["ended_at"]) if s.get("ended_at") else now
cursor = started
while cursor < end_ts and (end_ts - started) < 48 * 3600:
slot = datetime.fromtimestamp(cursor)
slot_end = min(end_ts, datetime(slot.year, slot.month, slot.day, slot.hour).timestamp() + 3600)
minutes = max(0.0, (slot_end - cursor) / 60.0)
by_hour_minutes[slot.hour] += minutes
by_weekday_minutes[slot.weekday()] += minutes
heatmap_minutes[slot.weekday()][slot.hour] += minutes
cursor = slot_end
if minutes <= 0:
break
date_key = s.get("push_date") or dt.strftime("%Y-%m-%d")
bucket = by_date.setdefault(date_key, {"date": date_key, "sessions": 0, "hours": 0.0, "anchors": set()})
bucket["sessions"] += 1
bucket["hours"] += duration / 3600.0
bucket["anchors"].add(s.get("anchor_name") or s.get("room_id") or "?")
anchor = (s.get("anchor_name") or "").strip() or s.get("room_id") or "未知"
a = by_anchor.setdefault(
anchor,
{
"anchor_name": anchor,
"source_room_id": s.get("room_id") or "",
"sessions": 0,
"hours_total": 0.0,
"durations": [],
"hours": [],
"weekdays": [],
"starts": [],
"dates": set(),
},
)
a["sessions"] += 1
a["hours_total"] += duration / 3600.0
a["durations"].append(duration)
a["hours"].append(hour)
a["weekdays"].append(weekday)
a["starts"].append(started)
a["dates"].add(date_key)
mins = duration / 60.0
if mins < 15:
duration_buckets["<15m"] += 1
elif mins < 60:
duration_buckets["15-60m"] += 1
elif mins < 180:
duration_buckets["1-3h"] += 1
elif mins < 360:
duration_buckets["3-6h"] += 1
elif mins < 720:
duration_buckets["6-12h"] += 1
else:
duration_buckets[">12h"] += 1
top = []
for a in by_anchor.values():
peak_hour = max(range(24), key=lambda h: a["hours"].count(h)) if a["hours"] else 0
peak_wd = max(range(7), key=lambda d: a["weekdays"].count(d)) if a["weekdays"] else 0
starts_sorted = sorted(a["starts"])
gaps = [
(starts_sorted[i] - starts_sorted[i - 1]) / 3600.0
for i in range(1, len(starts_sorted))
if starts_sorted[i] - starts_sorted[i - 1] > 0
]
dates_active = len(a["dates"]) or 1
top.append(
{
"anchor_name": a["anchor_name"],
"source_room_id": a["source_room_id"],
"sessions": a["sessions"],
"hours_total": round(a["hours_total"], 2),
"avg_duration_seconds": int(statistics.mean(a["durations"])) if a["durations"] else 0,
"peak_hour": peak_hour,
"peak_weekday_label": WEEKDAY_ZH[peak_wd],
"dates_active": dates_active,
"sessions_per_active_day": round(a["sessions"] / dates_active, 2),
"avg_gap_hours": round(statistics.mean(gaps), 2) if gaps else None,
}
)
top.sort(key=lambda x: (x["sessions"], x["hours_total"]), reverse=True)
top = top[: max(1, min(top_anchors, 50))]
by_date_list = []
for key in sorted(by_date.keys()):
item = by_date[key]
by_date_list.append(
{
"date": item["date"],
"sessions": item["sessions"],
"hours": round(item["hours"], 2),
"unique_anchors": len(item["anchors"]),
}
)
total_hours = sum(duration_values) / 3600.0 if duration_values else 0.0
insights = []
if duration_values:
busiest_hour = max(range(24), key=lambda h: by_hour_starts[h])
busiest_day = max(range(7), key=lambda d: by_weekday_starts[d])
insights.append(
{
"zh": f"最常开播时段:{busiest_hour:02d}:00–{busiest_hour:02d}:59;最常开播星期:{WEEKDAY_ZH[busiest_day]}。",
"en": f"Busiest hour: {busiest_hour:02d}:00; busiest weekday: {WEEKDAY_EN[busiest_day]}.",
}
)
if top:
insights.append(
{
"zh": f"开播最多主播:{top[0]['anchor_name']}({top[0]['sessions']} 场 / {top[0]['hours_total']} 小时)。",
"en": f"Top anchor: {top[0]['anchor_name']} ({top[0]['sessions']} sessions / {top[0]['hours_total']}h).",
}
)
return {
"overview": {
"sessions": len(sessions),
"unique_anchors": len(by_anchor),
"active_sessions": active_sessions,
"total_hours": round(total_hours, 2),
"avg_duration_seconds": int(statistics.mean(duration_values)) if duration_values else 0,
"median_duration_seconds": int(statistics.median(duration_values)) if duration_values else 0,
"days_span": len(by_date),
"date_from": by_date_list[0]["date"] if by_date_list else "",
"date_to": by_date_list[-1]["date"] if by_date_list else "",
},
"top_anchors": top,
"by_hour": {
"starts": by_hour_starts,
"minutes": [round(x, 1) for x in by_hour_minutes],
"labels": [f"{h:02d}:00" for h in range(24)],
},
"by_weekday": {
"starts": by_weekday_starts,
"minutes": [round(x, 1) for x in by_weekday_minutes],
"labels": WEEKDAY_EN,
"labels_zh": WEEKDAY_ZH,
},
"heatmap": {
"starts": heatmap_starts,
"minutes": [[round(x, 1) for x in row] for row in heatmap_minutes],
"weekday_labels": WEEKDAY_EN,
"weekday_labels_zh": WEEKDAY_ZH,
"hour_labels": [str(h) for h in range(24)],
},
"by_date": by_date_list,
"duration_buckets": duration_buckets,
"insights": insights,
}