# -*- coding: utf-8 -*- """YouTube Studio live metrics samples — analytics store. Links: Douyin room ↔ assign group / YouTube channel ↔ Neko (local|remote). Samples are appended ~1/min from extension/CDP ingest (and hub mirrors of ops-neko). """ from __future__ import annotations import json import sqlite3 import time from typing import Any, Optional from .db import _connect, _lock, _row_to_dict def ensure_yt_studio_tables(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS yt_studio_samples ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, group_id TEXT NOT NULL DEFAULT '', channel_pk TEXT NOT NULL DEFAULT '', youtube_channel_id TEXT NOT NULL DEFAULT '', source_room_id TEXT NOT NULL DEFAULT '', source_url TEXT NOT NULL DEFAULT '', anchor_name TEXT NOT NULL DEFAULT '', neko_kind TEXT NOT NULL DEFAULT 'local', neko_ref TEXT NOT NULL DEFAULT '', live_page_open INTEGER NOT NULL DEFAULT 0, on_air INTEGER NOT NULL DEFAULT 0, live_status TEXT NOT NULL DEFAULT '', health TEXT NOT NULL DEFAULT '', viewer_count INTEGER, total_views INTEGER, like_count INTEGER, live_duration_sec REAL, live_duration TEXT NOT NULL DEFAULT '', stream_title TEXT NOT NULL DEFAULT '', studio_url TEXT NOT NULL DEFAULT '', detect_source TEXT NOT NULL DEFAULT '', peak_viewers INTEGER, relay_session_uuid TEXT NOT NULL DEFAULT '', meta_json TEXT NOT NULL DEFAULT '{}', created_at REAL NOT NULL ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_studio_ts ON yt_studio_samples(ts DESC)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_studio_group ON yt_studio_samples(group_id, ts DESC)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_studio_channel ON yt_studio_samples(youtube_channel_id, ts DESC)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_studio_room ON yt_studio_samples(source_room_id, ts DESC)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_studio_neko ON yt_studio_samples(neko_ref, ts DESC)" ) def _ensure() -> None: with _lock: conn = _connect() try: ensure_yt_studio_tables(conn) conn.commit() finally: conn.close() def insert_sample( *, ts: float | None = None, group_id: str = "", channel_pk: str = "", youtube_channel_id: str = "", source_room_id: str = "", source_url: str = "", anchor_name: str = "", neko_kind: str = "local", neko_ref: str = "", live_page_open: bool = False, on_air: bool = False, live_status: str = "", health: str = "", viewer_count: Any = None, total_views: Any = None, like_count: Any = None, live_duration_sec: Any = None, live_duration: str = "", stream_title: str = "", studio_url: str = "", detect_source: str = "", peak_viewers: Any = None, relay_session_uuid: str = "", meta: Optional[dict[str, Any]] = None, ) -> dict[str, Any]: """Persist one analytics sample. Returns the stored row dict.""" _ensure() now = time.time() t = float(ts if ts is not None else now) def _int_or_none(v: Any) -> int | None: if v is None or v == "": return None try: return int(v) except (TypeError, ValueError): return None def _float_or_none(v: Any) -> float | None: if v is None or v == "": return None try: return float(v) except (TypeError, ValueError): return None kind = str(neko_kind or "local").strip().lower() if kind not in {"local", "remote"}: kind = "local" row_vals = ( t, str(group_id or "")[:80], str(channel_pk or "")[:80], str(youtube_channel_id or "")[:80], str(source_room_id or "")[:64], str(source_url or "")[:500], str(anchor_name or "")[:120], kind, str(neko_ref or "")[:40], 1 if live_page_open else 0, 1 if on_air else 0, str(live_status or "")[:40], str(health or "")[:40], _int_or_none(viewer_count), _int_or_none(total_views), _int_or_none(like_count), _float_or_none(live_duration_sec), str(live_duration or "")[:16], str(stream_title or "")[:200], str(studio_url or "")[:400], str(detect_source or "")[:40], _int_or_none(peak_viewers), str(relay_session_uuid or "")[:80], json.dumps(meta or {}, ensure_ascii=False)[:2000], now, ) with _lock: conn = _connect() try: ensure_yt_studio_tables(conn) cur = conn.execute( """ INSERT INTO yt_studio_samples( ts, group_id, channel_pk, youtube_channel_id, source_room_id, source_url, anchor_name, neko_kind, neko_ref, live_page_open, on_air, live_status, health, viewer_count, total_views, like_count, live_duration_sec, live_duration, stream_title, studio_url, detect_source, peak_viewers, relay_session_uuid, meta_json, created_at ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) """, row_vals, ) conn.commit() rid = int(cur.lastrowid or 0) row = conn.execute("SELECT * FROM yt_studio_samples WHERE id = ?", (rid,)).fetchone() return _public_sample(_row_to_dict(row) if row else {"id": rid}) finally: conn.close() def _public_sample(row: dict[str, Any]) -> dict[str, Any]: out = dict(row) out["live_page_open"] = bool(out.get("live_page_open")) out["on_air"] = bool(out.get("on_air")) meta = out.pop("meta_json", "{}") try: out["meta"] = json.loads(meta) if meta else {} except json.JSONDecodeError: out["meta"] = {} return out def list_samples( *, group_id: str = "", youtube_channel_id: str = "", source_room_id: str = "", neko_ref: str = "", since_ts: float = 0, limit: int = 200, ) -> list[dict[str, Any]]: _ensure() lim = max(1, min(5000, int(limit))) clauses: list[str] = [] args: list[Any] = [] if group_id: clauses.append("group_id = ?") args.append(str(group_id).strip()) if youtube_channel_id: clauses.append("youtube_channel_id = ?") args.append(str(youtube_channel_id).strip()) if source_room_id: clauses.append("source_room_id = ?") args.append(str(source_room_id).strip()) if neko_ref: clauses.append("neko_ref = ?") args.append(str(neko_ref).strip()) if since_ts > 0: clauses.append("ts >= ?") args.append(float(since_ts)) where = (" WHERE " + " AND ".join(clauses)) if clauses else "" with _lock: conn = _connect() try: ensure_yt_studio_tables(conn) rows = conn.execute( f"SELECT * FROM yt_studio_samples{where} ORDER BY ts DESC LIMIT ?", (*args, lim), ).fetchall() return [_public_sample(_row_to_dict(r)) for r in rows] finally: conn.close() def session_stats_for_group(group_id: str, *, since_ts: float = 0) -> dict[str, Any]: """Aggregate peak/avg/now viewers for a group window (analytics helper).""" rows = list_samples(group_id=group_id, since_ts=since_ts, limit=500) vals = [int(r["viewer_count"]) for r in rows if r.get("viewer_count") is not None] totals = [int(r["total_views"]) for r in rows if r.get("total_views") is not None] peak = max(vals) if vals else None avg = round(sum(vals) / len(vals), 1) if vals else None now_v = vals[0] if vals else None return { "group_id": group_id, "sample_count": len(rows), "peak_viewers": peak, "avg_viewers": avg, "viewer_count": now_v, "total_views": totals[0] if totals else None, "neko_kinds": sorted({str(r.get("neko_kind") or "") for r in rows if r.get("neko_kind")}), } def _sample_viewer(row: dict[str, Any]) -> int | None: v = row.get("viewer_count") if v is None or v == "": return None try: return max(0, int(v)) except (TypeError, ValueError): return None def _sample_total_views(row: dict[str, Any]) -> int | None: v = row.get("total_views") if v is None or v == "": return None try: return max(0, int(v)) except (TypeError, ValueError): return None def cluster_live_sessions( samples: list[dict[str, Any]], *, gap_sec: float = 1500.0, ) -> list[dict[str, Any]]: """Split Studio samples into live sessions (gap / uuid / on_air edges).""" rows = sorted( (r for r in samples if float(r.get("ts") or 0) > 0), key=lambda r: float(r["ts"]), ) if not rows: return [] sessions: list[list[dict[str, Any]]] = [] cur: list[dict[str, Any]] = [] last_ts = 0.0 last_uuid = "" last_on_air = False for r in rows: ts = float(r.get("ts") or 0) uuid = str(r.get("relay_session_uuid") or "").strip() on_air = bool(r.get("on_air")) meaningful = ( on_air or _sample_viewer(r) is not None or _sample_total_views(r) is not None or str(r.get("live_duration") or "").strip() ) if not meaningful and not cur: continue new_sess = False if not cur: new_sess = True elif uuid and last_uuid and uuid != last_uuid: new_sess = True elif last_ts and (ts - last_ts) > gap_sec: new_sess = True elif on_air and not last_on_air and last_ts and (ts - last_ts) > 180: new_sess = True if new_sess and cur: sessions.append(cur) cur = [] if meaningful or cur: cur.append(r) last_ts = ts if uuid: last_uuid = uuid last_on_air = on_air if cur: sessions.append(cur) out: list[dict[str, Any]] = [] for idx, chunk in enumerate(sessions): viewers = [v for v in (_sample_viewer(r) for r in chunk) if v is not None] totals = [v for v in (_sample_total_views(r) for r in chunk) if v is not None] likes = [] for r in chunk: try: if r.get("like_count") is not None: likes.append(int(r["like_count"])) except (TypeError, ValueError): pass started = float(chunk[0]["ts"]) ended = float(chunk[-1]["ts"]) dur_sec = max(0.0, ended - started) # Prefer Studio live_duration_sec if larger (ingest lag) for r in reversed(chunk): try: ld = float(r.get("live_duration_sec") or 0) if ld > dur_sec: dur_sec = ld break except (TypeError, ValueError): pass rooms = [] anchors = [] titles = [] neko_kinds_list = [] uuids = [] healths = [] statuses = [] for r in chunk: rid = str(r.get("source_room_id") or "").strip() if rid and rid not in rooms: rooms.append(rid) an = str(r.get("anchor_name") or "").strip() if an and an not in anchors: anchors.append(an) ti = str(r.get("stream_title") or "").strip() if ti and ti not in titles: titles.append(ti) nk = str(r.get("neko_kind") or "").strip() if nk and nk not in neko_kinds_list: neko_kinds_list.append(nk) uid = str(r.get("relay_session_uuid") or "").strip() if uid and uid not in uuids: uuids.append(uid) h = str(r.get("health") or "").strip() if h and h not in healths: healths.append(h) st = str(r.get("live_status") or "").strip() if st and st not in statuses: statuses.append(st) minute_reports = [] by_min: dict[int, dict[str, Any]] = {} for r in chunk: ts = float(r["ts"]) by_min[int(ts // 60)] = { "ts": ts, "on_air": bool(r.get("on_air")), "live_status": str(r.get("live_status") or ""), "health": str(r.get("health") or ""), "viewer_count": _sample_viewer(r), "total_views": _sample_total_views(r), "live_duration": str(r.get("live_duration") or ""), "live_duration_sec": r.get("live_duration_sec"), "source_room_id": str(r.get("source_room_id") or ""), "anchor_name": str(r.get("anchor_name") or ""), "neko_kind": str(r.get("neko_kind") or ""), } minute_reports = [by_min[k] for k in sorted(by_min)] from .timeutil import push_date_from_ts out.append( { "id": f"studio-{idx}-{int(started)}", "started_at": started, "ended_at": ended, "push_date": push_date_from_ts(started), "duration_sec": round(dur_sec, 1), "sample_count": len(chunk), "minute_count": len(minute_reports), "peak_viewers": max(viewers) if viewers else None, "avg_viewers": round(sum(viewers) / len(viewers), 1) if viewers else None, "end_viewers": viewers[-1] if viewers else None, "start_viewers": viewers[0] if viewers else None, "max_total_views": max(totals) if totals else None, "start_total_views": totals[0] if totals else None, "end_total_views": totals[-1] if totals else None, "max_likes": max(likes) if likes else None, "live_duration": str(chunk[-1].get("live_duration") or ""), "on_air_ratio": round( sum(1 for r in chunk if r.get("on_air")) / max(1, len(chunk)), 3 ), "source_rooms": rooms, "anchors": anchors, "stream_titles": titles[:8], "neko_kinds": neko_kinds_list, "relay_session_uuids": uuids, "healths": healths, "live_statuses": statuses, "source_url": str(chunk[-1].get("source_url") or chunk[0].get("source_url") or ""), "studio_url": str(chunk[-1].get("studio_url") or ""), "detect_sources": sorted( { str(r.get("detect_source") or "") for r in chunk if str(r.get("detect_source") or "").strip() } ), "minute_reports": minute_reports, } ) out.sort(key=lambda s: float(s.get("started_at") or 0), reverse=True) return out def daily_rollup_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: by_day: dict[str, dict[str, Any]] = {} for s in sessions: day = str(s.get("push_date") or "") if not day: continue bucket = by_day.setdefault( day, { "date": day, "session_count": 0, "live_sec": 0.0, "sample_count": 0, "peak_viewers": None, "avg_viewers_sum": 0.0, "avg_viewers_n": 0, "max_total_views": None, "rooms": set(), "anchors": set(), }, ) bucket["session_count"] += 1 bucket["live_sec"] += float(s.get("duration_sec") or 0) bucket["sample_count"] += int(s.get("sample_count") or 0) pk = s.get("peak_viewers") if pk is not None: cur = bucket["peak_viewers"] bucket["peak_viewers"] = int(pk) if cur is None else max(int(cur), int(pk)) av = s.get("avg_viewers") if av is not None: bucket["avg_viewers_sum"] += float(av) bucket["avg_viewers_n"] += 1 tv = s.get("max_total_views") if tv is not None: cur = bucket["max_total_views"] bucket["max_total_views"] = int(tv) if cur is None else max(int(cur), int(tv)) for rid in s.get("source_rooms") or []: bucket["rooms"].add(str(rid)) for an in s.get("anchors") or []: bucket["anchors"].add(str(an)) rows = [] for day in sorted(by_day.keys(), reverse=True): b = by_day[day] n = int(b["avg_viewers_n"] or 0) rows.append( { "date": day, "session_count": b["session_count"], "live_sec": round(float(b["live_sec"]), 1), "live_hours": round(float(b["live_sec"]) / 3600.0, 2), "sample_count": b["sample_count"], "peak_viewers": b["peak_viewers"], "avg_viewers": round(b["avg_viewers_sum"] / n, 1) if n else None, "max_total_views": b["max_total_views"], "room_count": len(b["rooms"]), "rooms": sorted(b["rooms"]), "anchors": sorted(b["anchors"]), } ) return rows def hour_heatmap_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: """Beijing-hour buckets: live minutes + peak concurrent.""" from .timeutil import beijing_from_ts hours = [ {"hour": h, "live_sec": 0.0, "sample_count": 0, "peak_viewers": None, "session_touches": 0} for h in range(24) ] for s in sessions: reports = s.get("minute_reports") or [] touched = set() for r in reports: ts = float(r.get("ts") or 0) if ts <= 0: continue h = int(beijing_from_ts(ts).hour) hours[h]["live_sec"] += 60.0 hours[h]["sample_count"] += 1 touched.add(h) v = r.get("viewer_count") if v is not None: cur = hours[h]["peak_viewers"] hours[h]["peak_viewers"] = int(v) if cur is None else max(int(cur), int(v)) for h in touched: hours[h]["session_touches"] += 1 for h in hours: h["live_sec"] = round(float(h["live_sec"]), 1) h["live_minutes"] = round(float(h["live_sec"]) / 60.0, 1) return hours def room_affinity_from_sessions(sessions: list[dict[str, Any]]) -> list[dict[str, Any]]: by_room: dict[str, dict[str, Any]] = {} for s in sessions: rooms = s.get("source_rooms") or [] if not rooms: rooms = [""] for rid in rooms: key = str(rid or "").strip() or "(unknown)" b = by_room.setdefault( key, { "room_id": key if key != "(unknown)" else "", "session_count": 0, "live_sec": 0.0, "peak_viewers": None, "max_total_views": None, "anchors": set(), "last_started_at": 0.0, }, ) b["session_count"] += 1 b["live_sec"] += float(s.get("duration_sec") or 0) pk = s.get("peak_viewers") if pk is not None: cur = b["peak_viewers"] b["peak_viewers"] = int(pk) if cur is None else max(int(cur), int(pk)) tv = s.get("max_total_views") if tv is not None: cur = b["max_total_views"] b["max_total_views"] = int(tv) if cur is None else max(int(cur), int(tv)) for an in s.get("anchors") or []: b["anchors"].add(str(an)) b["last_started_at"] = max(float(b["last_started_at"] or 0), float(s.get("started_at") or 0)) rows = [] for b in by_room.values(): rows.append( { "room_id": b["room_id"], "session_count": b["session_count"], "live_sec": round(float(b["live_sec"]), 1), "live_hours": round(float(b["live_sec"]) / 3600.0, 2), "peak_viewers": b["peak_viewers"], "max_total_views": b["max_total_views"], "anchors": sorted(b["anchors"]), "last_started_at": b["last_started_at"] or None, "douyin_url": ( f"https://live.douyin.com/{b['room_id']}" if b["room_id"] else "" ), } ) rows.sort(key=lambda r: (float(r.get("live_sec") or 0), int(r.get("session_count") or 0)), reverse=True) return rows def resolve_douyin_room_media(room_id: str) -> dict[str, Any]: """Nickname + cover + URL for a Douyin room (rooms / sessions / pool).""" from .db import _connect, _lock rid = str(room_id or "").strip() out = { "room_id": rid, "anchor_name": "", "cover_url": "", "avatar_url": "", "douyin_url": f"https://live.douyin.com/{rid}" if rid else "", "session_cover_url": "", "note": "", } if not rid: return out with _lock: conn = _connect() try: room = conn.execute( "SELECT last_anchor, note, avatar_url, url FROM rooms WHERE room_id = ? LIMIT 1", (rid,), ).fetchone() if room: out["anchor_name"] = str(room["last_anchor"] or "").strip() out["note"] = str(room["note"] or "").strip() av = str(room["avatar_url"] or "").strip() out["avatar_url"] = av if av.startswith("http") or av.startswith("/"): out["cover_url"] = av ru = str(room["url"] or "").strip() if ru: out["douyin_url"] = ru sess = conn.execute( """ SELECT id, cover_path, anchor_name FROM sessions WHERE room_id = ? ORDER BY started_at DESC LIMIT 1 """, (rid,), ).fetchone() if sess: sid = str(sess["id"] or "") if sid: out["session_cover_url"] = f"/api/sessions/{sid}/cover" if not out["cover_url"]: out["cover_url"] = out["session_cover_url"] if not out["anchor_name"]: out["anchor_name"] = str(sess["anchor_name"] or "").strip() pool = conn.execute( """ SELECT title, cover_url, url, note FROM yt_assign_pool_urls WHERE room_id = ? OR url LIKE ? ORDER BY updated_at DESC LIMIT 1 """, (rid, f"%{rid}%"), ).fetchone() if pool: if not out["anchor_name"]: out["anchor_name"] = str(pool["title"] or pool["note"] or "").strip() cu = str(pool["cover_url"] or "").strip() if cu and (cu.startswith("http") or cu.startswith("/")) and not out["cover_url"]: out["cover_url"] = cu if str(pool["url"] or "").strip(): out["douyin_url"] = str(pool["url"]).strip() except Exception: pass finally: conn.close() if not out["cover_url"] and out["session_cover_url"]: out["cover_url"] = out["session_cover_url"] return out def _perf_score( *, avg_viewers: float | None, peak_viewers: float | None, max_total_views: float | None, live_hours: float, session_count: int, ) -> float: """Rank score for arranging YouTube live from a Douyin source.""" avg = float(avg_viewers or 0) peak = float(peak_viewers or 0) tot = float(max_total_views or 0) hours = float(live_hours or 0) n = max(1, int(session_count or 0)) # Reliability weight: more sessions → trust avg more rel = min(1.5, 0.6 + 0.15 * n) return round(avg * 1.2 * rel + peak * 0.35 + (tot / 500.0) + hours * 4.0, 2) def source_performance_from_sessions( sessions: list[dict[str, Any]], *, group_id: str = "", channel_name: str = "", youtube_channel_id: str = "", ) -> list[dict[str, Any]]: """Per Douyin room performance on one YouTube channel (for planning).""" from .timeutil import beijing_from_ts by_room: dict[str, dict[str, Any]] = {} for s in sessions: rooms = [str(x).strip() for x in (s.get("source_rooms") or []) if str(x).strip()] if not rooms: continue reports = s.get("minute_reports") or [] for rid in rooms: b = by_room.setdefault( rid, { "room_id": rid, "session_count": 0, "live_sec": 0.0, "peaks": [], "avgs": [], "totals": [], "anchors": set(), "titles": set(), "last_started_at": 0.0, "hour_live_sec": [0.0] * 24, "hour_peak": [None] * 24, "hour_samples": [0] * 24, "weekday_live_sec": [0.0] * 7, "weekday_peak": [None] * 7, "session_ids": [], }, ) b["session_count"] += 1 b["live_sec"] += float(s.get("duration_sec") or 0) if s.get("peak_viewers") is not None: b["peaks"].append(float(s["peak_viewers"])) if s.get("avg_viewers") is not None: b["avgs"].append(float(s["avg_viewers"])) if s.get("max_total_views") is not None: b["totals"].append(float(s["max_total_views"])) for an in s.get("anchors") or []: if an: b["anchors"].add(str(an)) for ti in s.get("stream_titles") or []: if ti: b["titles"].add(str(ti)[:80]) b["last_started_at"] = max(float(b["last_started_at"] or 0), float(s.get("started_at") or 0)) b["session_ids"].append(s.get("id")) # hour / weekday from minute reports (prefer), else session start touched_h = set() for r in reports: ts = float(r.get("ts") or 0) if ts <= 0: continue dt = beijing_from_ts(ts) h = int(dt.hour) wd = int(dt.weekday()) b["hour_live_sec"][h] += 60.0 b["hour_samples"][h] += 1 touched_h.add(h) v = r.get("viewer_count") if v is not None: try: iv = int(v) cur = b["hour_peak"][h] b["hour_peak"][h] = iv if cur is None else max(int(cur), iv) curw = b["weekday_peak"][wd] b["weekday_peak"][wd] = iv if curw is None else max(int(curw), iv) except (TypeError, ValueError): pass b["weekday_live_sec"][wd] += 60.0 if not reports and s.get("started_at"): dt = beijing_from_ts(float(s["started_at"])) h = int(dt.hour) wd = int(dt.weekday()) dur = float(s.get("duration_sec") or 0) b["hour_live_sec"][h] += dur b["weekday_live_sec"][wd] += dur if s.get("peak_viewers") is not None: iv = int(s["peak_viewers"]) cur = b["hour_peak"][h] b["hour_peak"][h] = iv if cur is None else max(int(cur), iv) wd_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] rows: list[dict[str, Any]] = [] for rid, b in by_room.items(): media = resolve_douyin_room_media(rid) avg = round(sum(b["avgs"]) / len(b["avgs"]), 1) if b["avgs"] else None peak = int(max(b["peaks"])) if b["peaks"] else None tot = int(max(b["totals"])) if b["totals"] else None live_h = round(float(b["live_sec"]) / 3600.0, 2) score = _perf_score( avg_viewers=avg, peak_viewers=peak, max_total_views=tot, live_hours=live_h, session_count=int(b["session_count"]), ) # best hours: by peak then live minutes hour_rank = sorted( range(24), key=lambda h: ( int(b["hour_peak"][h] or 0), float(b["hour_live_sec"][h]), ), reverse=True, ) best_hours = [] for h in hour_rank: if not b["hour_live_sec"][h] and not b["hour_peak"][h]: continue best_hours.append( { "hour": h, "label": f"{h:02d}:00–{(h + 1) % 24:02d}:00", "peak_viewers": b["hour_peak"][h], "live_minutes": round(float(b["hour_live_sec"][h]) / 60.0, 1), "samples": b["hour_samples"][h], } ) if len(best_hours) >= 5: break wd_rank = sorted( range(7), key=lambda w: (int(b["weekday_peak"][w] or 0), float(b["weekday_live_sec"][w])), reverse=True, ) best_weekdays = [] for w in wd_rank: if not b["weekday_live_sec"][w] and not b["weekday_peak"][w]: continue best_weekdays.append( { "weekday": w, "label": wd_names[w], "peak_viewers": b["weekday_peak"][w], "live_hours": round(float(b["weekday_live_sec"][w]) / 3600.0, 2), } ) if len(best_weekdays) >= 3: break anchor = media.get("anchor_name") or (sorted(b["anchors"])[0] if b["anchors"] else "") tip = "" if best_hours and avg is not None: tip = ( f"建议优先用该源:均值同时约 {avg}," f"北京 {best_hours[0]['label']} 表现最好" + (f"(峰 {best_hours[0]['peak_viewers']})" if best_hours[0].get("peak_viewers") is not None else "") ) elif avg is not None: tip = f"有采样:均值同时 {avg},峰 {peak if peak is not None else '—'}" else: tip = "已关联过本频道,但 Studio 观看样本不足" rows.append( { "room_id": rid, "anchor_name": anchor, "cover_url": media.get("cover_url") or "", "avatar_url": media.get("avatar_url") or "", "douyin_url": media.get("douyin_url") or f"https://live.douyin.com/{rid}", "group_id": group_id, "channel_name": channel_name, "youtube_channel_id": youtube_channel_id, "session_count": int(b["session_count"]), "live_sec": round(float(b["live_sec"]), 1), "live_hours": live_h, "peak_viewers": peak, "avg_viewers": avg, "max_total_views": tot, "score": score, "best_hours": best_hours, "best_weekdays": best_weekdays, "hour_heatmap": [ { "hour": h, "live_minutes": round(float(b["hour_live_sec"][h]) / 60.0, 1), "peak_viewers": b["hour_peak"][h], } for h in range(24) ], "stream_titles": sorted(b["titles"])[:6], "last_started_at": b["last_started_at"] or None, "planning_tip": tip, "in_pool": False, "in_featured": False, "measured": True, } ) rows.sort(key=lambda r: (float(r.get("score") or 0), float(r.get("avg_viewers") or 0)), reverse=True) for i, r in enumerate(rows): r["rank"] = i + 1 return rows def merge_pool_sources_into_rankings( rankings: list[dict[str, Any]], group: dict[str, Any], ) -> list[dict[str, Any]]: """Append assigned pool/featured rooms that have no Studio samples yet.""" by_id = {str(r.get("room_id") or ""): r for r in rankings if r.get("room_id")} feat_ids = set() pool_ids = set() for u in group.get("featured") or []: rid = str(u.get("room_id") or "").strip() if rid: feat_ids.add(rid) for u in group.get("pool") or []: rid = str(u.get("room_id") or "").strip() if rid: pool_ids.add(rid) for r in rankings: rid = str(r.get("room_id") or "") r["in_featured"] = rid in feat_ids r["in_pool"] = rid in pool_ids or rid in feat_ids extras = [] for u in list(group.get("featured") or []) + list(group.get("pool") or []): rid = str(u.get("room_id") or "").strip() if not rid or rid in by_id: if rid in by_id: # enrich cover from pool if missing if not by_id[rid].get("cover_url") and u.get("cover_url"): by_id[rid]["cover_url"] = str(u.get("cover_url") or "") if not by_id[rid].get("anchor_name"): by_id[rid]["anchor_name"] = str(u.get("title") or u.get("anchor_name") or u.get("note") or "") continue media = resolve_douyin_room_media(rid) cover = str(u.get("cover_url") or media.get("cover_url") or "") anchor = str(u.get("title") or u.get("anchor_name") or media.get("anchor_name") or u.get("note") or "") extras.append( { "room_id": rid, "anchor_name": anchor, "cover_url": cover, "avatar_url": media.get("avatar_url") or "", "douyin_url": str(u.get("url") or media.get("douyin_url") or f"https://live.douyin.com/{rid}"), "group_id": str(group.get("id") or ""), "channel_name": str(group.get("name") or ""), "youtube_channel_id": str(group.get("youtube_channel_id") or ""), "session_count": 0, "live_sec": 0.0, "live_hours": 0.0, "peak_viewers": None, "avg_viewers": None, "max_total_views": None, "score": 0.0, "best_hours": [], "best_weekdays": [], "hour_heatmap": [{"hour": h, "live_minutes": 0, "peak_viewers": None} for h in range(24)], "stream_titles": [], "last_started_at": None, "planning_tip": "在本频道池/精选中,但窗口内尚无 Studio 观看样本 — 开播后才会出排名", "in_pool": True, "in_featured": rid in feat_ids, "measured": False, "rank": None, } ) by_id[rid] = extras[-1] return rankings + extras def build_fleet_source_matrix(*, days: int = 30, sample_limit: int = 5000) -> dict[str, Any]: """Cross-channel: which Douyin room performs best on which YouTube channel.""" from . import yt_assign_db from .timeutil import push_date_from_ts days_n = max(1, min(90, int(days or 30))) since = time.time() - days_n * 86400 groups = yt_assign_db.list_groups(include_urls=False) all_pairs: list[dict[str, Any]] = [] per_group_rankings: dict[str, list[dict[str, Any]]] = {} for g in groups: gid = str(g.get("id") or "") if not gid: continue try: an = build_group_analytics(gid, days=days_n, sample_limit=min(2500, int(sample_limit))) except Exception: continue if not an.get("ok"): continue ranks = [r for r in (an.get("source_rankings") or []) if r.get("measured")] per_group_rankings[gid] = ranks[:8] all_pairs.extend(ranks) # Room-centric: for each room, best channel + all channel rows by_room: dict[str, dict[str, Any]] = {} for r in all_pairs: rid = str(r.get("room_id") or "") if not rid: continue bucket = by_room.setdefault( rid, { "room_id": rid, "anchor_name": r.get("anchor_name") or "", "cover_url": r.get("cover_url") or "", "douyin_url": r.get("douyin_url") or "", "channels": [], }, ) if not bucket["anchor_name"] and r.get("anchor_name"): bucket["anchor_name"] = r["anchor_name"] if not bucket["cover_url"] and r.get("cover_url"): bucket["cover_url"] = r["cover_url"] bucket["channels"].append( { "group_id": r.get("group_id"), "channel_name": r.get("channel_name"), "youtube_channel_id": r.get("youtube_channel_id"), "score": r.get("score"), "avg_viewers": r.get("avg_viewers"), "peak_viewers": r.get("peak_viewers"), "max_total_views": r.get("max_total_views"), "live_hours": r.get("live_hours"), "session_count": r.get("session_count"), "best_hours": (r.get("best_hours") or [])[:3], "best_weekdays": (r.get("best_weekdays") or [])[:2], "planning_tip": r.get("planning_tip"), } ) room_rows = [] for rid, b in by_room.items(): chans = sorted(b["channels"], key=lambda x: float(x.get("score") or 0), reverse=True) best = chans[0] if chans else None room_rows.append( { **b, "channels": chans, "best_channel": best, "channel_count": len(chans), "best_score": float(best["score"]) if best else 0, } ) room_rows.sort(key=lambda x: float(x.get("best_score") or 0), reverse=True) # Recommendations: top pairings pairings = sorted(all_pairs, key=lambda x: float(x.get("score") or 0), reverse=True)[:40] return { "ok": True, "window": { "days": days_n, "since_ts": since, "generated_at": time.time(), "today": push_date_from_ts(time.time()), "group_count": len(groups), "pair_count": len(all_pairs), "room_count": len(room_rows), }, "recommendations": [ { "rank": i + 1, "room_id": p.get("room_id"), "anchor_name": p.get("anchor_name"), "cover_url": p.get("cover_url"), "douyin_url": p.get("douyin_url"), "group_id": p.get("group_id"), "channel_name": p.get("channel_name"), "youtube_channel_id": p.get("youtube_channel_id"), "score": p.get("score"), "avg_viewers": p.get("avg_viewers"), "peak_viewers": p.get("peak_viewers"), "max_total_views": p.get("max_total_views"), "live_hours": p.get("live_hours"), "best_hours": (p.get("best_hours") or [])[:3], "planning_tip": p.get("planning_tip"), } for i, p in enumerate(pairings) ], "rooms": room_rows[:80], "groups": [ { "id": str(g.get("id") or ""), "name": g.get("name"), "youtube_channel_id": g.get("youtube_channel_id"), "top_sources": per_group_rankings.get(str(g.get("id") or "")) or [], } for g in groups ], } def build_group_analytics( group_id: str, *, days: int = 30, sample_limit: int = 4000, ) -> dict[str, Any]: """Full channel live analytics payload for assign group detail page.""" from . import yt_assign_db from . import youtube_relay_sessions as relay_sessions from .timeutil import push_date_from_ts gid = str(group_id or "").strip() if not gid: return {"ok": False, "error": "missing group_id"} g = yt_assign_db.get_group(gid) if not g: return {"ok": False, "error": "group_not_found"} days_n = max(1, min(90, int(days or 30))) since = time.time() - days_n * 86400 samples = list_samples(group_id=gid, since_ts=since, limit=max(200, min(5000, int(sample_limit)))) # also try youtube_channel_id if group_id samples sparse ycid = str(g.get("youtube_channel_id") or "").strip() if ycid and len(samples) < 20: extra = list_samples(youtube_channel_id=ycid, since_ts=since, limit=max(200, min(5000, int(sample_limit)))) seen = {int(r.get("id") or 0) for r in samples} for r in extra: rid = int(r.get("id") or 0) if rid and rid not in seen: samples.append(r) seen.add(rid) studio_sessions = cluster_live_sessions(samples) daily = daily_rollup_from_sessions(studio_sessions) hours = hour_heatmap_from_sessions(studio_sessions) rooms = room_affinity_from_sessions(studio_sessions) relay = relay_sessions.list_sessions(group_id=gid, limit=200, offset=0) relay_rows = relay.get("sessions") or [] relay_stats = relay_sessions.summarize_sessions(group_id=gid, top_anchors=30) # Attach nearest relay push rows onto studio sessions + backfill Douyin room ids for s in studio_sessions: st = float(s.get("started_at") or 0) en = float(s.get("ended_at") or 0) matched = [] for rs in relay_rows: rs_st = float(rs.get("started_at") or 0) rs_en = float(rs.get("ended_at") or rs_st) if rs_st <= 0: continue # overlap if rs_st <= en + 600 and rs_en >= st - 600: matched.append( { "id": rs.get("id"), "session_uuid": rs.get("session_uuid"), "started_at": rs.get("started_at"), "ended_at": rs.get("ended_at"), "duration_seconds": rs.get("duration_seconds"), "status": rs.get("status"), "end_reason": rs.get("end_reason"), "source_room_id": rs.get("source_room_id"), "source_url": rs.get("source_url"), "anchor_name": rs.get("anchor_name"), "stream_title": rs.get("stream_title"), } ) s["relay_pushes"] = matched[:8] # Studio samples often omit room_id — borrow from overlapping FFmpeg pushes existing = {str(x).strip() for x in (s.get("source_rooms") or []) if str(x).strip()} anchors = {str(x).strip() for x in (s.get("anchors") or []) if str(x).strip()} for rp in matched: rid = str(rp.get("source_room_id") or "").strip() if rid: existing.add(rid) an = str(rp.get("anchor_name") or "").strip() if an: anchors.add(an) if not s.get("source_url") and rp.get("source_url"): s["source_url"] = rp.get("source_url") # Fallback: same Beijing day relay for this group (when Studio has viewers but no room) if not existing: day = str(s.get("push_date") or "") day_relays = [ rs for rs in relay_rows if str(rs.get("push_date") or "") == day and str(rs.get("source_room_id") or "").strip() ] # Prefer relays whose start falls inside the studio window ±2h near = [] for rs in day_relays: rs_st = float(rs.get("started_at") or 0) if st - 7200 <= rs_st <= en + 7200: near.append(rs) pick = near or day_relays for rs in pick[:3]: rid = str(rs.get("source_room_id") or "").strip() if rid: existing.add(rid) an = str(rs.get("anchor_name") or "").strip() if an: anchors.add(an) matched.append( { "id": rs.get("id"), "started_at": rs.get("started_at"), "ended_at": rs.get("ended_at"), "duration_seconds": rs.get("duration_seconds"), "status": rs.get("status"), "source_room_id": rid, "source_url": rs.get("source_url"), "anchor_name": rs.get("anchor_name"), "stream_title": rs.get("stream_title"), "attrib": "same_day_fallback", } ) s["relay_pushes"] = matched[:8] s["source_rooms"] = sorted(existing) s["anchors"] = sorted(anchors) # also stamp onto minute_reports missing room if existing: rid0 = next(iter(existing)) for mr in s.get("minute_reports") or []: if not str(mr.get("source_room_id") or "").strip(): mr["source_room_id"] = rid0 # distribute studio viewer stats onto attributed rooms via session fields already set # Synthetic sessions from relay-only pushes (no Studio room attribution) covered_relay_ids = set() for s in studio_sessions: for rp in s.get("relay_pushes") or []: if rp.get("id") is not None: covered_relay_ids.add(int(rp["id"])) relay_only_sessions: list[dict[str, Any]] = [] for rs in relay_rows: rid = str(rs.get("source_room_id") or "").strip() if not rid: continue try: rsid = int(rs.get("id") or 0) except (TypeError, ValueError): rsid = 0 if rsid and rsid in covered_relay_ids: continue st = float(rs.get("started_at") or 0) if st <= 0: continue en = float(rs.get("ended_at") or 0) or st dur = float(rs.get("duration_seconds") or max(0.0, en - st)) from .timeutil import push_date_from_ts as _pd relay_only_sessions.append( { "id": f"relay-{rsid or int(st)}", "started_at": st, "ended_at": en, "push_date": str(rs.get("push_date") or _pd(st)), "duration_sec": dur, "sample_count": 0, "minute_count": 0, "peak_viewers": None, "avg_viewers": None, "end_viewers": None, "start_viewers": None, "max_total_views": None, "start_total_views": None, "end_total_views": None, "max_likes": None, "live_duration": "", "on_air_ratio": 0.0, "source_rooms": [rid], "anchors": [str(rs.get("anchor_name") or "").strip()] if rs.get("anchor_name") else [], "stream_titles": [str(rs.get("stream_title") or "").strip()] if rs.get("stream_title") else [], "neko_kinds": [], "relay_session_uuids": [str(rs.get("session_uuid") or "")] if rs.get("session_uuid") else [], "healths": [], "live_statuses": [str(rs.get("status") or "")], "source_url": str(rs.get("source_url") or ""), "studio_url": "", "detect_sources": ["relay"], "minute_reports": [], "relay_pushes": [ { "id": rs.get("id"), "started_at": rs.get("started_at"), "ended_at": rs.get("ended_at"), "duration_seconds": rs.get("duration_seconds"), "status": rs.get("status"), "source_room_id": rid, "anchor_name": rs.get("anchor_name"), } ], } ) ranking_sessions = studio_sessions + relay_only_sessions source_rankings = source_performance_from_sessions( ranking_sessions, group_id=gid, channel_name=str(g.get("name") or ""), youtube_channel_id=ycid, ) source_rankings = merge_pool_sources_into_rankings(source_rankings, g) # Planning slots: top hours across measured sources slot_votes: dict[int, dict[str, Any]] = { h: {"hour": h, "sources": [], "best_peak": None, "best_avg_proxy": 0.0} for h in range(24) } for src in source_rankings: if not src.get("measured"): continue for bh in src.get("best_hours") or []: h = int(bh.get("hour") or 0) slot_votes[h]["sources"].append( { "room_id": src.get("room_id"), "anchor_name": src.get("anchor_name"), "cover_url": src.get("cover_url"), "peak_viewers": bh.get("peak_viewers"), "live_minutes": bh.get("live_minutes"), "score": src.get("score"), } ) pk = bh.get("peak_viewers") if pk is not None: cur = slot_votes[h]["best_peak"] slot_votes[h]["best_peak"] = int(pk) if cur is None else max(int(cur), int(pk)) planning_slots = [] for h in range(24): row = slot_votes[h] row["sources"] = sorted( row["sources"], key=lambda x: (int(x.get("peak_viewers") or 0), float(x.get("score") or 0)), reverse=True, )[:5] if row["sources"]: planning_slots.append(row) planning_slots.sort(key=lambda x: int(x.get("best_peak") or 0), reverse=True) # Overview KPIs all_peaks = [int(s["peak_viewers"]) for s in studio_sessions if s.get("peak_viewers") is not None] all_avgs = [float(s["avg_viewers"]) for s in studio_sessions if s.get("avg_viewers") is not None] all_totals = [int(s["max_total_views"]) for s in studio_sessions if s.get("max_total_views") is not None] live_sec = sum(float(s.get("duration_sec") or 0) for s in studio_sessions) latest = studio_sessions[0] if studio_sessions else None measured = [r for r in source_rankings if r.get("measured")] pool = g.get("pool") or [] featured = g.get("featured") or [] slots = g.get("slots") or [] return { "ok": True, "group": { "id": gid, "name": g.get("name"), "channel_pk": g.get("channel_pk"), "youtube_channel_id": g.get("youtube_channel_id"), "category": g.get("category"), "time_slot_armed": g.get("time_slot_armed"), "neko_instance_id": g.get("neko_instance_id"), "neko_enabled": g.get("neko_enabled"), "neko_open_prefer": g.get("neko_open_prefer"), "ops_neko_bind": g.get("ops_neko_bind"), "has_stream_key": bool(g.get("has_stream_key") or g.get("stream_key")), "pool_count": len(pool) if isinstance(pool, list) else 0, "featured_count": len(featured) if isinstance(featured, list) else 0, "slot_count": len(slots) if isinstance(slots, list) else 0, "pool": pool if isinstance(pool, list) else [], "featured": featured if isinstance(featured, list) else [], }, "window": { "days": days_n, "since_ts": since, "sample_count": len(samples), "generated_at": time.time(), "today": push_date_from_ts(time.time()), }, "overview": { "session_count": len(studio_sessions), "live_sec": round(live_sec, 1), "live_hours": round(live_sec / 3600.0, 2), "peak_viewers": max(all_peaks) if all_peaks else None, "avg_viewers": round(sum(all_avgs) / len(all_avgs), 1) if all_avgs else None, "max_total_views": max(all_totals) if all_totals else None, "relay_push_count": len(relay_rows), "unique_rooms": len(measured), "top_source": measured[0] if measured else None, "latest_session": ( { "started_at": latest.get("started_at"), "ended_at": latest.get("ended_at"), "peak_viewers": latest.get("peak_viewers"), "end_viewers": latest.get("end_viewers"), "max_total_views": latest.get("max_total_views"), "live_duration": latest.get("live_duration"), "anchors": latest.get("anchors"), "source_rooms": latest.get("source_rooms"), } if latest else None ), }, "source_rankings": source_rankings, "planning_slots": planning_slots, "daily": daily, "hours": hours, "rooms": rooms, "studio_sessions": studio_sessions, "relay_sessions": relay_rows, "relay_stats": relay_stats, }