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"] SLOT_META = [ {"id": 0, "label": "凌晨", "range": "00:00–04:00", "start_hour": 0}, {"id": 1, "label": "清晨", "range": "04:00–08:00", "start_hour": 4}, {"id": 2, "label": "上午", "range": "08:00–12:00", "start_hour": 8}, {"id": 3, "label": "午后", "range": "12:00–16:00", "start_hour": 12}, {"id": 4, "label": "傍晚", "range": "16:00–20:00", "start_hour": 16}, {"id": 5, "label": "夜间", "range": "20:00–24:00", "start_hour": 20}, ] 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, "by_slot_6": _summarize_slots(sessions, now), } def _slot_index(hour: int) -> int: return min(5, max(0, hour // 4)) def _summarize_slots(sessions: list[dict[str, Any]], now: float) -> dict[str, Any]: slot_opens = [0] * 6 slot_rooms: list[set[str]] = [set() for _ in range(6)] slot_duration = [0.0] * 6 by_date_slot: dict[str, list[int]] = {} for s in sessions: started = float(s.get("started_at") or 0) if not started: continue dt = datetime.fromtimestamp(started) idx = _slot_index(dt.hour) slot_opens[idx] += 1 slot_rooms[idx].add(str(s.get("room_id") or s.get("anchor_name") or s.get("id") or "?")) slot_duration[idx] += _effective_duration(s, now) date_key = s.get("push_date") or dt.strftime("%Y-%m-%d") row = by_date_slot.setdefault(date_key, [0] * 6) row[idx] += 1 total = sum(slot_opens) or 1 slots = [] for meta in SLOT_META: i = meta["id"] slots.append( { **meta, "opens": slot_opens[i], "unique_rooms": len(slot_rooms[i]), "duration_seconds": int(slot_duration[i]), "share": round(slot_opens[i] / total, 4), } ) peak = max(range(6), key=lambda i: slot_opens[i]) if any(slot_opens) else None dates = sorted(by_date_slot.keys()) return { "slots": slots, "peak_slot": peak, "by_date": [{"date": d, "opens": by_date_slot[d]} for d in dates], "totals": {"opens": sum(slot_opens), "days": len(dates)}, } def summarize_anchor_schedule(sessions: list[dict[str, Any]]) -> dict[str, Any]: """Derive open-time habit from an anchor's session list.""" now = time.time() hours: list[int] = [] weekdays: list[int] = [] starts: list[float] = [] slot_counts = [0] * 6 for s in sessions: started = float(s.get("started_at") or 0) if not started: continue dt = datetime.fromtimestamp(started) hours.append(dt.hour) weekdays.append(dt.weekday()) starts.append(started) slot_counts[_slot_index(dt.hour)] += 1 if not starts: return { "peak_hour": None, "peak_weekday_label": None, "peak_slot": None, "slot_counts": slot_counts, "avg_gap_hours": None, "sessions_per_active_day": None, "typical_open_hint": "样本不足", "next_open_hint": None, } peak_hour = max(range(24), key=lambda h: hours.count(h)) peak_wd = max(range(7), key=lambda d: weekdays.count(d)) peak_slot = max(range(6), key=lambda i: slot_counts[i]) starts_sorted = sorted(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({datetime.fromtimestamp(t).strftime("%Y-%m-%d") for t in starts}) or 1 avg_gap = round(statistics.mean(gaps), 2) if gaps else None slot = SLOT_META[peak_slot] typical = f"常在 {slot['label']}({slot['range']})开播,高峰约 {peak_hour:02d}:00,多在{WEEKDAY_ZH[peak_wd]}" next_hint = None last = starts_sorted[-1] if avg_gap and avg_gap > 0: eta = last + avg_gap * 3600.0 if eta < now: # overdue — suggest today's peak hour if still ahead, else tomorrow today = datetime.now().replace(hour=peak_hour, minute=0, second=0, microsecond=0) if today.timestamp() > now: eta = today.timestamp() else: eta = today.timestamp() + 86400 next_hint = { "eta_ts": eta, "label": datetime.fromtimestamp(eta).strftime("%m-%d %H:%M"), "based_on": f"间隔均值 {avg_gap}h · 习惯 {peak_hour:02d}:00", } return { "peak_hour": peak_hour, "peak_weekday_label": WEEKDAY_ZH[peak_wd], "peak_slot": peak_slot, "peak_slot_label": slot["label"], "peak_slot_range": slot["range"], "slot_counts": slot_counts, "avg_gap_hours": avg_gap, "sessions_per_active_day": round(len(starts) / dates_active, 2), "dates_active": dates_active, "typical_open_hint": typical, "next_open_hint": next_hint, }