Tighten http/youtubei live probes, classify Studio encoder_lost vs waiting, and keep dy/dylive public live counts aligned via edge assign_lives. Co-authored-by: Cursor <cursoragent@cursor.com>
250 lines
8.2 KiB
Python
250 lines
8.2 KiB
Python
# -*- 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(2000, 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")}),
|
|
}
|