# -*- coding: utf-8 -*- """Room sampling recommendations from historical Shorts/TikTok job success.""" from __future__ import annotations import time from typing import Any from .db import _connect, _lock, _row_to_dict def recommend_rooms(*, limit: int = 20, lookback_days: int = 14) -> dict[str, Any]: """Rank Douyin rooms by historical clip→upload success rate.""" since = time.time() - max(1, int(lookback_days)) * 86400 with _lock: conn = _connect() try: # Shorts stats shorts = conn.execute( """ SELECT room_id, COUNT(*) AS total, SUM(CASE WHEN status IN ('uploaded','done') THEN 1 ELSE 0 END) AS ok, SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS fail FROM shorts_jobs WHERE room_id != '' AND created_at >= ? GROUP BY room_id """, (since,), ).fetchall() tiktok = conn.execute( """ SELECT room_id, COUNT(*) AS total, SUM(CASE WHEN status IN ('uploaded','done') THEN 1 ELSE 0 END) AS ok, SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS fail FROM tiktok_jobs WHERE room_id != '' AND created_at >= ? GROUP BY room_id """, (since,), ).fetchall() rooms = { str(r["room_id"]): _row_to_dict(r) for r in conn.execute( "SELECT id, room_id, url, note, tags, last_anchor, last_status, enabled " "FROM rooms WHERE room_id != '' AND room_id NOT LIKE 'yt:%'" ).fetchall() } finally: conn.close() merged: dict[str, dict[str, Any]] = {} for row in shorts: rid = str(row["room_id"] or "") if not rid: continue merged.setdefault(rid, {"room_id": rid, "shorts_total": 0, "shorts_ok": 0, "tiktok_total": 0, "tiktok_ok": 0}) merged[rid]["shorts_total"] = int(row["total"] or 0) merged[rid]["shorts_ok"] = int(row["ok"] or 0) for row in tiktok: rid = str(row["room_id"] or "") if not rid: continue merged.setdefault(rid, {"room_id": rid, "shorts_total": 0, "shorts_ok": 0, "tiktok_total": 0, "tiktok_ok": 0}) merged[rid]["tiktok_total"] = int(row["total"] or 0) merged[rid]["tiktok_ok"] = int(row["ok"] or 0) out: list[dict[str, Any]] = [] for rid, st in merged.items(): total = int(st["shorts_total"]) + int(st["tiktok_total"]) ok = int(st["shorts_ok"]) + int(st["tiktok_ok"]) if total < 2: continue rate = ok / total if total else 0.0 room = rooms.get(rid) or {} tags = room.get("tags") or [] if isinstance(tags, str): tags = [t for t in tags.split(",") if t.strip()] suggest = [] if rate >= 0.45 and "shorts" not in tags and "shorts_only" not in tags: suggest.append("shorts") if rate >= 0.45 and "tiktok" not in tags and "tiktok_only" not in tags: suggest.append("tiktok") out.append( { "room_id": rid, "room_pk": room.get("id") or "", "anchor": room.get("last_anchor") or "", "url": room.get("url") or "", "tags": tags, "enabled": bool(room.get("enabled")), "total": total, "ok": ok, "fail": total - ok, "success_rate": round(rate, 3), "suggest_tags": suggest, "reason": f"近{lookback_days}天成功率 {round(rate*100)}%({ok}/{total})", } ) out.sort(key=lambda x: (-float(x["success_rate"]), -int(x["total"]))) return {"lookback_days": lookback_days, "rooms": out[: max(1, min(int(limit), 100))]}