feat(yt-long): split source vs upload quota so masters cover all platforms

Auto-size master recording to max(Shorts/TikTok/X/YT upload need) while keeping YouTube long uploads at 14x3; cascade-only masters wait for upload slots.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-20 12:23:52 -05:00
parent 7e4a8b4e70
commit e0776c9142
6 changed files with 271 additions and 106 deletions

View File

@ -130,7 +130,6 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
from . import db from . import db
from . import tiktok_db from . import tiktok_db
from . import yt_long_db from . import yt_long_db
from . import x_clips_db
settings_map = cfg if cfg is not None else db.get_settings_map() settings_map = cfg if cfg is not None else db.get_settings_map()
shorts_n = 0 shorts_n = 0
@ -143,17 +142,18 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or []) tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or [])
except Exception: except Exception:
tiktok_n = 0 tiktok_n = 0
yt_long = int(yt_long_db.yt_long_daily_max(settings_map) or 0) yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE) shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE)
tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE) tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE)
try: try:
x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20)) x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20))
except Exception: except Exception:
x_need = 20 x_need = 20
# One master can feed all platforms once → masters needed = max(...) # One master feeds all platforms once → masters needed = max(...)
source_need = max(yt_long, shorts_need, tiktok_need, x_need, 0) source_need = max(yt_upload, shorts_need, tiktok_need, x_need, 0)
return { return {
"yt_long": yt_long, "yt_long": yt_upload,
"yt_long_upload": yt_upload,
"shorts": shorts_need, "shorts": shorts_need,
"tiktok": tiktok_need, "tiktok": tiktok_need,
"x": x_need, "x": x_need,
@ -164,29 +164,25 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
def ensure_source_covers_platforms(cfg: dict[str, Any] | None = None) -> dict[str, Any]: def ensure_source_covers_platforms(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Report (and optionally raise) yt_long_daily_max so masters ≥ platform quotas. """Always keep yt_long_source_daily_max ≥ max(platform quotas); never raise upload cap."""
Auto-raise only when yt_long_auto_match_source=True (default off) to avoid
suddenly uploading hundreds of long YouTube videos.
"""
from . import db from . import db
from . import yt_long_db from . import yt_long_db
settings_map = cfg if cfg is not None else db.get_settings_map() settings_map = cfg if cfg is not None else db.get_settings_map()
need = estimate_platform_daily_need(settings_map) need = estimate_platform_daily_need(settings_map)
current = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
target = int(need["source_masters"]) target = int(need["source_masters"])
current = int(yt_long_db.yt_long_source_daily_max(settings_map) or 0)
upload_cap = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
if not bool(settings_map.get("clip_cascade_enabled", True)): if not bool(settings_map.get("clip_cascade_enabled", True)):
return {"ok": True, "adjusted": False, "from": current, "to": current, **need} # Without cascade, source only needs to cover YouTube long uploads
if not bool(settings_map.get("yt_long_auto_match_source", False)): target = upload_cap
return {"ok": True, "adjusted": False, "from": current, "to": current, **need}
try: try:
hard_cap = max(42, min(200, int(settings_map.get("yt_long_source_cap") or 200))) hard_cap = max(42, min(300, int(settings_map.get("yt_long_source_cap") or 200)))
except Exception: except Exception:
hard_cap = 200 hard_cap = 200
new_max = min(hard_cap, max(current, target)) new_max = min(hard_cap, max(upload_cap, target))
if new_max > current: if new_max != int(settings_map.get("yt_long_source_daily_max") or 0):
db.update_settings_map({"yt_long_daily_max": new_max}) db.update_settings_map({"yt_long_source_daily_max": new_max})
return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need} return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need}
return {"ok": True, "adjusted": False, "from": current, "to": current, **need} return {"ok": True, "adjusted": False, "from": current, "to": current, **need}

View File

@ -507,17 +507,18 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"yt_long_auto_upload": True, "yt_long_auto_upload": True,
"yt_long_live_sample": True, "yt_long_live_sample": True,
"yt_long_live_sample_interval_sec": 180, "yt_long_live_sample_interval_sec": 180,
"yt_long_live_sample_batch": 2, "yt_long_live_sample_batch": 3,
"yt_long_daily_max": 42, "yt_long_daily_max": 42,
"yt_long_source_daily_max": 42,
"yt_long_channel_daily_max": 3, "yt_long_channel_daily_max": 3,
"yt_long_min_sec": 180, "yt_long_min_sec": 180,
"yt_long_max_sec": 480, "yt_long_max_sec": 480,
"yt_long_dedupe_room_day": True, "yt_long_dedupe_room_day": True,
"yt_long_max_concurrent": 2, "yt_long_max_concurrent": 3,
"yt_long_upload_min_gap_sec": 900, "yt_long_upload_min_gap_sec": 900,
"yt_long_delete_clip_after_upload": False, "yt_long_delete_clip_after_upload": False,
"yt_long_landscape_16x9": False, "yt_long_landscape_16x9": False,
"yt_long_auto_match_source": False, "yt_long_auto_match_source": True,
"yt_long_source_cap": 200, "yt_long_source_cap": 200,
"yt_long_title_template": "", "yt_long_title_template": "",
"yt_long_description_template": "", "yt_long_description_template": "",

View File

@ -1231,6 +1231,16 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"]))) patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"])))
except Exception: except Exception:
raise HTTPException(400, "daily_max 无效") from None raise HTTPException(400, "daily_max 无效") from None
if "yt_long_source_daily_max" in raw:
try:
patch["yt_long_source_daily_max"] = max(0, min(300, int(raw["yt_long_source_daily_max"])))
except Exception:
raise HTTPException(400, "source_daily_max 无效") from None
if "yt_long_source_cap" in raw:
try:
patch["yt_long_source_cap"] = max(42, min(300, int(raw["yt_long_source_cap"])))
except Exception:
raise HTTPException(400, "source_cap 无效") from None
if "yt_long_channel_daily_max" in raw: if "yt_long_channel_daily_max" in raw:
try: try:
patch["yt_long_channel_daily_max"] = max(0, min(50, int(raw["yt_long_channel_daily_max"]))) patch["yt_long_channel_daily_max"] = max(0, min(50, int(raw["yt_long_channel_daily_max"])))

View File

@ -10,8 +10,8 @@ from typing import Any, Optional
from .db import _connect, _lock, _row_to_dict from .db import _connect, _lock, _row_to_dict
from .timeutil import push_date_from_ts from .timeutil import push_date_from_ts
# Quota-consuming statuses for daily long-form caps # Quota-consuming statuses for master *recording* (source material)
_QUOTA_STATUSES = ( _SOURCE_STATUSES = (
"pending", "pending",
"recording", "recording",
"recorded", "recorded",
@ -19,9 +19,18 @@ _QUOTA_STATUSES = (
"uploading", "uploading",
"uploaded", "uploaded",
) )
# Statuses that count toward YouTube *upload* caps (channel + global)
_UPLOAD_STATUSES = (
"scheduled",
"uploading",
"uploaded",
)
# Back-compat alias
_QUOTA_STATUSES = _SOURCE_STATUSES
YT_LONG_DAILY_DEFAULT = 42 # 14 channels × 3 long videos YT_LONG_DAILY_DEFAULT = 42 # YouTube long upload: 14 channels × 3
YT_LONG_CHANNEL_DEFAULT = 3 YT_LONG_CHANNEL_DEFAULT = 3
YT_LONG_SOURCE_DEFAULT = 42 # raised automatically to cover cascade platforms
YT_LONG_MIN_SEC = 180 # 3 min YT_LONG_MIN_SEC = 180 # 3 min
YT_LONG_MAX_SEC = 480 # 8 min YT_LONG_MAX_SEC = 480 # 8 min
@ -103,6 +112,7 @@ def ensure_yt_long_tables(conn: sqlite3.Connection) -> None:
def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int:
"""YouTube long-form *upload* daily cap (not master recording cap)."""
from . import db from . import db
settings = cfg if cfg is not None else db.get_settings_map() settings = cfg if cfg is not None else db.get_settings_map()
@ -113,6 +123,25 @@ def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int:
return max(0, min(200, v)) return max(0, min(200, v))
def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int:
"""Master recording daily cap — must cover cascade platform needs."""
from . import db
settings = cfg if cfg is not None else db.get_settings_map()
upload_cap = yt_long_daily_max(settings)
try:
v = int(settings.get("yt_long_source_daily_max") or 0)
except Exception:
v = 0
if v <= 0:
v = max(upload_cap, YT_LONG_SOURCE_DEFAULT)
try:
hard = max(42, min(300, int(settings.get("yt_long_source_cap") or 200)))
except Exception:
hard = 200
return max(upload_cap, min(hard, v))
def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int: def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
from . import db from . import db
@ -124,9 +153,9 @@ def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
return max(0, min(50, v)) return max(0, min(50, v))
def yt_long_quota_used(push_date: str = "") -> int: def yt_long_source_used(push_date: str = "") -> int:
day = push_date or push_date_from_ts(time.time()) day = push_date or push_date_from_ts(time.time())
placeholders = ",".join("?" for _ in _QUOTA_STATUSES) placeholders = ",".join("?" for _ in _SOURCE_STATUSES)
with _lock: with _lock:
conn = _connect() conn = _connect()
try: try:
@ -136,21 +165,56 @@ def yt_long_quota_used(push_date: str = "") -> int:
SELECT COUNT(*) AS c FROM yt_long_jobs SELECT COUNT(*) AS c FROM yt_long_jobs
WHERE push_date = ? AND status IN ({placeholders}) WHERE push_date = ? AND status IN ({placeholders})
""", """,
(day, *_QUOTA_STATUSES), (day, *_SOURCE_STATUSES),
).fetchone() ).fetchone()
return int(row["c"]) if row else 0 return int(row["c"]) if row else 0
finally: finally:
conn.close() conn.close()
def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: def yt_long_source_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
day = push_date or push_date_from_ts(time.time()) day = push_date or push_date_from_ts(time.time())
return max(0, yt_long_daily_max(cfg) - yt_long_quota_used(day)) return max(0, yt_long_source_daily_max(cfg) - yt_long_source_used(day))
def yt_long_upload_used(push_date: str = "") -> int:
day = push_date or push_date_from_ts(time.time())
placeholders = ",".join("?" for _ in _UPLOAD_STATUSES)
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
row = conn.execute(
f"""
SELECT COUNT(*) AS c FROM yt_long_jobs
WHERE push_date = ? AND status IN ({placeholders})
""",
(day, *_UPLOAD_STATUSES),
).fetchone()
return int(row["c"]) if row else 0
finally:
conn.close()
def yt_long_upload_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
day = push_date or push_date_from_ts(time.time())
return max(0, yt_long_daily_max(cfg) - yt_long_upload_used(day))
def yt_long_quota_used(push_date: str = "") -> int:
"""UI/compat: YouTube upload usage."""
return yt_long_upload_used(push_date)
def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
"""UI/compat: YouTube upload remaining."""
return yt_long_upload_gap(push_date, cfg)
def channel_quota_used(channel_pk: str, push_date: str = "") -> int: def channel_quota_used(channel_pk: str, push_date: str = "") -> int:
"""Per-channel YouTube upload usage (cascade-only masters do not count)."""
day = push_date or push_date_from_ts(time.time()) day = push_date or push_date_from_ts(time.time())
placeholders = ",".join("?" for _ in _QUOTA_STATUSES) placeholders = ",".join("?" for _ in _UPLOAD_STATUSES)
with _lock: with _lock:
conn = _connect() conn = _connect()
try: try:
@ -160,13 +224,38 @@ def channel_quota_used(channel_pk: str, push_date: str = "") -> int:
SELECT COUNT(*) AS c FROM yt_long_jobs SELECT COUNT(*) AS c FROM yt_long_jobs
WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders})
""", """,
(day, channel_pk, *_QUOTA_STATUSES), (day, channel_pk, *_UPLOAD_STATUSES),
).fetchone() ).fetchone()
return int(row["c"]) if row else 0 return int(row["c"]) if row else 0
finally: finally:
conn.close() conn.close()
def list_cascade_only_ready(limit: int = 20, push_date: str = "") -> list[dict[str, Any]]:
"""Recorded masters waiting for a YouTube upload slot."""
day = push_date or push_date_from_ts(time.time())
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
rows = conn.execute(
"""
SELECT * FROM yt_long_jobs
WHERE push_date = ?
AND status = 'recorded'
AND clip_path != ''
AND IFNULL(youtube_video_id, '') = ''
AND (upload_at = 0 OR error = 'cascade_only')
ORDER BY created_at ASC
LIMIT ?
""",
(day, max(1, min(100, int(limit)))),
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()
def has_job_for_room_day(room_id: str, push_date: str) -> bool: def has_job_for_room_day(room_id: str, push_date: str) -> bool:
if not room_id: if not room_id:
return False return False

View File

@ -149,25 +149,25 @@ def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]:
return {"enqueued": False, "reason": "disabled"} return {"enqueued": False, "reason": "disabled"}
if not cfg.get("yt_long_with_shorts", True): if not cfg.get("yt_long_with_shorts", True):
return {"enqueued": False, "reason": "with_shorts_off"} return {"enqueued": False, "reason": "with_shorts_off"}
if yt_long_db.yt_long_quota_gap(cfg=cfg) <= 0: if yt_long_db.yt_long_source_gap(cfg=cfg) <= 0:
return {"enqueued": False, "reason": "quota_full"} return {"enqueued": False, "reason": "source_full"}
room_id = str(job.get("room_id") or "").strip() room_id = str(job.get("room_id") or "").strip()
day = str(job.get("push_date") or push_date_from_ts(time.time())) day = str(job.get("push_date") or push_date_from_ts(time.time()))
if cfg.get("yt_long_dedupe_room_day", True) and room_id and yt_long_db.has_job_for_room_day(room_id, day): if cfg.get("yt_long_dedupe_room_day", True) and room_id and yt_long_db.has_job_for_room_day(room_id, day):
return {"enqueued": False, "reason": "room_dedupe"} return {"enqueued": False, "reason": "room_dedupe"}
channel = pick_yt_long_channel(cfg, day) # Channel only required when we still have YouTube upload slots
if not channel: channel = pick_yt_long_channel(cfg, day) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None
return {"enqueued": False, "reason": "no_channel"}
created = yt_long_db.create_yt_long_job( created = yt_long_db.create_yt_long_job(
room_pk=str(job.get("room_pk") or ""), room_pk=str(job.get("room_pk") or ""),
room_id=room_id, room_id=room_id,
source_url=str(job.get("source_url") or ""), source_url=str(job.get("source_url") or ""),
anchor_name=str(job.get("anchor_name") or ""), anchor_name=str(job.get("anchor_name") or ""),
stream_url=str(job.get("stream_url") or ""), stream_url=str(job.get("stream_url") or ""),
channel_pk=str(channel.get("id") or ""), channel_pk=str((channel or {}).get("id") or ""),
shorts_job_id=str(job.get("id") or ""), shorts_job_id=str(job.get("id") or ""),
push_date=day, push_date=day,
) )
if channel:
try: try:
yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time())
except Exception: except Exception:
@ -178,29 +178,28 @@ def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]:
f"长视频入队:{created.get('anchor_name') or room_id}", f"长视频入队:{created.get('anchor_name') or room_id}",
created, created,
) )
return {"enqueued": True, "job_id": created.get("id"), "channel_pk": channel.get("id")} return {"enqueued": True, "job_id": created.get("id"), "channel_pk": (channel or {}).get("id")}
except Exception as exc: except Exception as exc:
return {"enqueued": False, "reason": "error", "error": str(exc)[:200]} return {"enqueued": False, "reason": "error", "error": str(exc)[:200]}
def _enqueue_from_room(room: dict[str, Any], cfg: dict[str, Any], push_date: str) -> str: def _enqueue_from_room(room: dict[str, Any], cfg: dict[str, Any], push_date: str) -> str:
channel = pick_yt_long_channel(cfg, push_date)
if not channel:
return ""
rid = str(room.get("room_id") or "").strip() rid = str(room.get("room_id") or "").strip()
if not rid: if not rid:
return "" return ""
if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, push_date): if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, push_date):
return "" return ""
channel = pick_yt_long_channel(cfg, push_date) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None
created = yt_long_db.create_yt_long_job( created = yt_long_db.create_yt_long_job(
room_pk=str(room.get("id") or room.get("room_pk") or ""), room_pk=str(room.get("id") or room.get("room_pk") or ""),
room_id=rid, room_id=rid,
source_url=str(room.get("url") or room.get("source_url") or ""), source_url=str(room.get("url") or room.get("source_url") or ""),
anchor_name=str(room.get("last_anchor") or room.get("anchor_name") or ""), anchor_name=str(room.get("last_anchor") or room.get("anchor_name") or ""),
stream_url=str(room.get("stream_url") or ""), stream_url=str(room.get("stream_url") or ""),
channel_pk=str(channel.get("id") or ""), channel_pk=str((channel or {}).get("id") or ""),
push_date=push_date, push_date=push_date,
) )
if channel:
try: try:
yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time())
except Exception: except Exception:
@ -219,11 +218,9 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
return 0 return 0
if not settings.get("yt_long_live_sample", True): if not settings.get("yt_long_live_sample", True):
return 0 return 0
if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: if yt_long_db.yt_long_source_gap(cfg=settings) <= 0:
return 0 return 0
if not pick_yt_long_channel(settings): batch = max(1, min(8, int(settings.get("yt_long_live_sample_batch") or 1)))
return 0
batch = max(1, min(5, int(settings.get("yt_long_live_sample_batch") or 1)))
day = push_date_from_ts(time.time()) day = push_date_from_ts(time.time())
rooms = db.list_live_douyin_rooms_for_shorts(limit=400) rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
candidates: list[dict[str, Any]] = [] candidates: list[dict[str, Any]] = []
@ -241,7 +238,7 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
for room in candidates: for room in candidates:
if enqueued >= batch: if enqueued >= batch:
break break
if yt_long_db.yt_long_quota_gap(cfg=settings) <= 0: if yt_long_db.yt_long_source_gap(cfg=settings) <= 0:
break break
if _enqueue_from_room(room, settings, day): if _enqueue_from_room(room, settings, day):
enqueued += 1 enqueued += 1
@ -258,6 +255,13 @@ def sample_live_now() -> dict[str, Any]:
yt_long_db.sync_channels_from_shorts() yt_long_db.sync_channels_from_shorts()
except Exception: except Exception:
pass pass
try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(settings)
settings = db.get_settings_map()
except Exception:
pass
patched = {**settings, "yt_long_live_sample": True} patched = {**settings, "yt_long_live_sample": True}
rooms = db.list_live_douyin_rooms_for_shorts(limit=400) rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
day = push_date_from_ts(time.time()) day = push_date_from_ts(time.time())
@ -271,10 +275,8 @@ def sample_live_now() -> dict[str, Any]:
reason = "" reason = ""
if n: if n:
reason = "ok" reason = "ok"
elif yt_long_db.yt_long_quota_gap(cfg=patched) <= 0: elif yt_long_db.yt_long_source_gap(cfg=patched) <= 0:
reason = "no_quota" reason = "no_quota"
elif not pick_yt_long_channel(patched):
reason = "no_channel"
elif skipped and skipped >= len(rooms) and len(rooms) > 0: elif skipped and skipped >= len(rooms) and len(rooms) > 0:
reason = "all_deduped" reason = "all_deduped"
elif not rooms: elif not rooms:
@ -284,8 +286,7 @@ def sample_live_now() -> dict[str, Any]:
reason_zh = { reason_zh = {
"ok": "已入队", "ok": "已入队",
"disabled": "模块未启用", "disabled": "模块未启用",
"no_quota": "今日全局配额已满", "no_quota": "今日母片配额已满",
"no_channel": "没有可用已授权频道",
"all_deduped": "今日在播房间均已入队,请等待排队任务录制", "all_deduped": "今日在播房间均已入队,请等待排队任务录制",
"no_live": "当前没有抖音在播源", "no_live": "当前没有抖音在播源",
"enqueue_failed": "入队失败", "enqueue_failed": "入队失败",
@ -298,6 +299,8 @@ def sample_live_now() -> dict[str, Any]:
"job_ids": [str(j.get("id")) for j in pending], "job_ids": [str(j.get("id")) for j in pending],
"reason": reason, "reason": reason,
"reason_zh": reason_zh, "reason_zh": reason_zh,
"source_gap": yt_long_db.yt_long_source_gap(cfg=patched),
"upload_gap": yt_long_db.yt_long_upload_gap(cfg=patched),
} }
@ -309,19 +312,31 @@ def try_fill_daily_quota() -> dict[str, Any]:
yt_long_db.sync_channels_from_shorts() yt_long_db.sync_channels_from_shorts()
except Exception: except Exception:
pass pass
gap = yt_long_db.yt_long_quota_gap(cfg=settings) try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(settings)
settings = db.get_settings_map()
except Exception:
pass
gap = yt_long_db.yt_long_source_gap(cfg=settings)
if gap <= 0: if gap <= 0:
return {"enqueued": 0, "gap": 0, "reason": "quota_full"} return {"enqueued": 0, "gap": 0, "reason": "quota_full"}
patched = {**settings, "yt_long_live_sample_batch": min(gap, 5), "yt_long_live_sample": True} patched = {**settings, "yt_long_live_sample_batch": min(gap, 8), "yt_long_live_sample": True}
total = 0 total = 0
rounds = 0 rounds = 0
while total < gap and rounds < 8: while total < gap and rounds < 12:
rounds += 1 rounds += 1
n = try_sample_live_rooms(patched) n = try_sample_live_rooms(patched)
if n <= 0: if n <= 0:
break break
total += n total += n
return {"enqueued": total, "gap": yt_long_db.yt_long_quota_gap(cfg=settings), "reason": "ok" if total else "no_candidates"} return {
"enqueued": total,
"gap": yt_long_db.yt_long_source_gap(cfg=settings),
"upload_gap": yt_long_db.yt_long_upload_gap(cfg=settings),
"reason": "ok" if total else "no_candidates",
}
class YtLongPipeline: class YtLongPipeline:
@ -349,8 +364,10 @@ class YtLongPipeline:
board = {"channels": [], "total_gap": 0, "push_date": day} board = {"channels": [], "total_gap": 0, "push_date": day}
cascade_need: dict[str, Any] = {} cascade_need: dict[str, Any] = {}
try: try:
from .clip_cascade import estimate_platform_daily_need from .clip_cascade import estimate_platform_daily_need, ensure_source_covers_platforms
ensure_source_covers_platforms(cfg)
cfg = db.get_settings_map()
cascade_need = estimate_platform_daily_need(cfg) cascade_need = estimate_platform_daily_need(cfg)
except Exception: except Exception:
cascade_need = {} cascade_need = {}
@ -360,9 +377,14 @@ class YtLongPipeline:
"enabled": bool(cfg.get("yt_long_enabled")), "enabled": bool(cfg.get("yt_long_enabled")),
"processed": self.processed, "processed": self.processed,
"sampled": self.sampled, "sampled": self.sampled,
"quota_gap": yt_long_db.yt_long_quota_gap(day, cfg), "quota_gap": yt_long_db.yt_long_upload_gap(day, cfg),
"quota_used": yt_long_db.yt_long_quota_used(day), "quota_used": yt_long_db.yt_long_upload_used(day),
"daily_max": yt_long_db.yt_long_daily_max(cfg), "daily_max": yt_long_db.yt_long_daily_max(cfg),
"source_gap": yt_long_db.yt_long_source_gap(day, cfg),
"source_used": yt_long_db.yt_long_source_used(day),
"source_daily_max": yt_long_db.yt_long_source_daily_max(cfg),
"upload_gap": yt_long_db.yt_long_upload_gap(day, cfg),
"upload_used": yt_long_db.yt_long_upload_used(day),
"channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg),
"last_error": self.last_error, "last_error": self.last_error,
"stats": yt_long_db.yt_long_stats(day), "stats": yt_long_db.yt_long_stats(day),
@ -377,6 +399,7 @@ class YtLongPipeline:
"yt_long_live_sample_interval_sec": int(cfg.get("yt_long_live_sample_interval_sec") or 180), "yt_long_live_sample_interval_sec": int(cfg.get("yt_long_live_sample_interval_sec") or 180),
"yt_long_live_sample_batch": int(cfg.get("yt_long_live_sample_batch") or 1), "yt_long_live_sample_batch": int(cfg.get("yt_long_live_sample_batch") or 1),
"yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg), "yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg),
"yt_long_source_daily_max": yt_long_db.yt_long_source_daily_max(cfg),
"yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg),
"yt_long_min_sec": int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC), "yt_long_min_sec": int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC),
"yt_long_max_sec": int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC), "yt_long_max_sec": int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC),
@ -443,6 +466,13 @@ class YtLongPipeline:
interval = max(60.0, float(cfg.get("yt_long_live_sample_interval_sec") or 180)) interval = max(60.0, float(cfg.get("yt_long_live_sample_interval_sec") or 180))
if cfg.get("yt_long_live_sample", True) and (time.time() - self._last_sample_at) >= interval: if cfg.get("yt_long_live_sample", True) and (time.time() - self._last_sample_at) >= interval:
self._last_sample_at = time.time() self._last_sample_at = time.time()
try:
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(cfg)
cfg = db.get_settings_map()
except Exception:
pass
n = try_sample_live_rooms(cfg) n = try_sample_live_rooms(cfg)
if n: if n:
self.sampled += n self.sampled += n
@ -468,25 +498,46 @@ class YtLongPipeline:
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") db_recording = yt_long_db.count_yt_long_jobs_by_status("recording")
# If in-flight + done already fills daily_max, soft-skip leftover pending # Soft-skip leftover pending when master (source) quota is full
try: try:
from .timeutil import push_date_from_ts as _pday from .timeutil import push_date_from_ts as _pday
dmax = yt_long_db.yt_long_daily_max(cfg) smax = yt_long_db.yt_long_source_daily_max(cfg)
day = _pday(time.time()) day = _pday(time.time())
inflight = 0 if smax > 0 and yt_long_db.yt_long_source_used(day) >= smax:
for st_name in ("recording", "recorded", "scheduled", "uploading", "uploaded"):
inflight += yt_long_db.count_yt_long_jobs_by_status(st_name, push_date=day)
if dmax > 0 and inflight >= dmax:
for pj in yt_long_db.list_pending_yt_long_jobs(limit=30): for pj in yt_long_db.list_pending_yt_long_jobs(limit=30):
yt_long_db.update_yt_long_job( yt_long_db.update_yt_long_job(
str(pj.get("id") or ""), str(pj.get("id") or ""),
status="skipped", status="skipped",
error="daily_quota_full", error="source_quota_full",
finished_at=time.time(), finished_at=time.time(),
) )
except Exception: except Exception:
pass pass
# Promote cascade-only masters into YouTube upload slots when available
try:
ugap = yt_long_db.yt_long_upload_gap(cfg=cfg)
if ugap > 0 and cfg.get("yt_long_auto_upload", True):
for cj in yt_long_db.list_cascade_only_ready(limit=min(10, ugap)):
if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0:
break
ch = pick_yt_long_channel(cfg, str(cj.get("push_date") or ""))
if not ch:
break
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
yt_long_db.update_yt_long_job(
str(cj.get("id") or ""),
status="scheduled",
channel_pk=str(ch["id"]),
upload_at=time.time() + random.uniform(20, gap),
error="",
)
try:
yt_long_db.update_yt_long_channel(str(ch["id"]), last_assigned_at=time.time())
except Exception:
pass
except Exception:
pass
while self._active_records < max_rec and db_recording < max_rec: while self._active_records < max_rec and db_recording < max_rec:
pending = yt_long_db.list_pending_yt_long_jobs(limit=1) pending = yt_long_db.list_pending_yt_long_jobs(limit=1)
if not pending: if not pending:
@ -558,9 +609,13 @@ class YtLongPipeline:
_emit("yt_long_fail", "error", f"长视频录制失败:{job.get('anchor_name') or jid} — {err[:80]}", job) _emit("yt_long_fail", "error", f"长视频录制失败:{job.get('anchor_name') or jid} — {err[:80]}", job)
return return
clip_path = str(outcome.get("path") or "") clip_path = str(outcome.get("path") or "")
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) fresh_base = {
upload_at = time.time() + random.uniform(30, gap) **job,
if not cfg.get("yt_long_auto_upload", True): "clip_path": clip_path,
"clip_seconds": float(outcome.get("seconds") or sec),
"stream_url": str(outcome.get("stream_url") or ""),
}
# Always cascade first (TikTok / Shorts / X reuse this master)
yt_long_db.update_yt_long_job( yt_long_db.update_yt_long_job(
jid, jid,
status="recorded", status="recorded",
@ -569,32 +624,38 @@ class YtLongPipeline:
stream_url=str(outcome.get("stream_url") or ""), stream_url=str(outcome.get("stream_url") or ""),
error="", error="",
) )
fresh = yt_long_db.get_yt_long_job(jid) or {**job, "clip_path": clip_path, "clip_seconds": sec} fresh = yt_long_db.get_yt_long_job(jid) or fresh_base
try: try:
from .clip_cascade import cascade_from_yt_long from .clip_cascade import cascade_from_yt_long
await cascade_from_yt_long(fresh, cfg) await cascade_from_yt_long(fresh, cfg)
except Exception: except Exception:
pass pass
if not cfg.get("yt_long_auto_upload", True):
return return
# Only schedule YouTube long upload when upload quota remains
if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0:
yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0)
return
channel = None
if str(fresh.get("channel_pk") or "").strip():
channel = yt_long_db.get_yt_long_channel(str(fresh.get("channel_pk") or ""))
if not channel:
channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or ""))
if not channel:
yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0)
return
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
upload_at = time.time() + random.uniform(30, gap)
yt_long_db.update_yt_long_job( yt_long_db.update_yt_long_job(
jid, jid,
status="scheduled", status="scheduled",
clip_path=clip_path, channel_pk=str(channel["id"]),
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=str(outcome.get("stream_url") or ""),
upload_at=upload_at, upload_at=upload_at,
error="", error="",
) )
fresh = yt_long_db.get_yt_long_job(jid) or {
**job,
"clip_path": clip_path,
"clip_seconds": float(outcome.get("seconds") or sec),
}
try: try:
from .clip_cascade import cascade_from_yt_long yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time())
await cascade_from_yt_long(fresh, cfg)
except Exception: except Exception:
pass pass

View File

@ -406,8 +406,16 @@ export default function YtLongPage() {
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5"> <div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[ {[
["北京日配额", `${status?.quota_used ?? 0} / ${status?.daily_max ?? "—"}`, beijingWindow ? `${beijingWindow}(北京时间 · 全局)` : "全局日上限"], [
["当日缺口", String(quotaGap), `频道合计缺口 ${totals.gap}`], "YouTube 上传",
`${status?.upload_used ?? status?.quota_used ?? 0} / ${status?.daily_max ?? "—"}`,
beijingWindow ? `${beijingWindow} · 长视频上传上限` : "长视频上传日上限(14×3)",
],
[
"母片录制",
`${status?.source_used ?? 0} / ${status?.source_daily_max ?? "—"}`,
`缺口 ${status?.source_gap ?? "—"} · 覆盖 Shorts/TikTok/X`,
],
["已上传", String(totals.uploaded), `排队 ${totals.scheduled}`], ["已上传", String(totals.uploaded), `排队 ${totals.scheduled}`],
[ [
"抖音在播源", "抖音在播源",
@ -417,7 +425,7 @@ export default function YtLongPage() {
[ [
"成片规格", "成片规格",
`${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`, `${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`,
"9:16 竖屏长视频 · 非 Shorts", "9:16 竖屏 · cascade 切短片",
], ],
].map(([label, value, hint]) => ( ].map(([label, value, hint]) => (
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3"> <div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">