fix(yt-long): 5 long videos/channel BJ-day, drop to 4 when YouTube API limited
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
82bcd5a26b
commit
6a033e6326
@ -512,9 +512,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"yt_long_live_sample": True,
|
||||
"yt_long_live_sample_interval_sec": 180,
|
||||
"yt_long_live_sample_batch": 1,
|
||||
"yt_long_daily_max": 42,
|
||||
"yt_long_source_daily_max": 42,
|
||||
"yt_long_channel_daily_max": 3,
|
||||
"yt_long_daily_max": 70,
|
||||
"yt_long_source_daily_max": 70,
|
||||
"yt_long_channel_daily_max": 5,
|
||||
"yt_long_min_sec": 180,
|
||||
"yt_long_max_sec": 480,
|
||||
"yt_long_dedupe_room_day": True,
|
||||
|
||||
@ -840,6 +840,14 @@ class ShortsPipeline:
|
||||
pid = profile_id_for_job(job)
|
||||
# Keep local counter in sync for UI; do not set blocked_until / defer siblings
|
||||
pause_uploads_until_reset(profile_id=pid, reason="")
|
||||
try:
|
||||
from . import yt_long_db
|
||||
|
||||
# Shorts + yt-long share YouTube Data API → shrink long daily target to 4/ch
|
||||
yt_long_db.mark_yt_long_api_limited(reason=str(raw_error or "")[:160])
|
||||
yt_long_db.reconcile_yt_long_upload_caps()
|
||||
except Exception:
|
||||
pass
|
||||
friendly = quota_error_message(pid)
|
||||
# Prefer raw API body when present so operators see the real interface reply
|
||||
api_snip = (raw_error or "").strip()
|
||||
|
||||
@ -28,9 +28,10 @@ _UPLOAD_STATUSES = (
|
||||
# Back-compat alias
|
||||
_QUOTA_STATUSES = _SOURCE_STATUSES
|
||||
|
||||
YT_LONG_DAILY_DEFAULT = 42 # YouTube long upload: 14 channels × 3
|
||||
YT_LONG_CHANNEL_DEFAULT = 3
|
||||
YT_LONG_SOURCE_DEFAULT = 42 # raised automatically to cover cascade platforms
|
||||
YT_LONG_CHANNEL_DEFAULT = 5 # Beijing-day target per channel (normal)
|
||||
YT_LONG_CHANNEL_LIMITED = 4 # when shared YouTube API quota is limited (3 < n < 5)
|
||||
YT_LONG_DAILY_DEFAULT = 70 # 14 channels × 5
|
||||
YT_LONG_SOURCE_DEFAULT = 70
|
||||
YT_LONG_MIN_SEC = 180 # 3 min
|
||||
YT_LONG_MAX_SEC = 480 # 8 min
|
||||
|
||||
@ -47,7 +48,7 @@ def ensure_yt_long_tables(conn: sqlite3.Connection) -> None:
|
||||
client_secret TEXT NOT NULL DEFAULT '',
|
||||
refresh_token TEXT NOT NULL DEFAULT '',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
daily_max INTEGER NOT NULL DEFAULT 3,
|
||||
daily_max INTEGER NOT NULL DEFAULT 5,
|
||||
title_template TEXT NOT NULL DEFAULT '{anchor} street food live',
|
||||
description_template TEXT NOT NULL DEFAULT '{anchor}\n{url}\n#StreetFood #Live',
|
||||
privacy TEXT NOT NULL DEFAULT 'public',
|
||||
@ -162,6 +163,122 @@ def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
return max(upload_cap, min(hard, v))
|
||||
|
||||
|
||||
def youtube_api_upload_limited(cfg: dict[str, Any] | None = None) -> bool:
|
||||
"""True when Shorts/yt-long share a YouTube Data API upload freeze for this BJ day."""
|
||||
from . import db
|
||||
from .shorts_yt_quota import _load_quota_map
|
||||
|
||||
settings = cfg if cfg is not None else db.get_settings_map()
|
||||
day = push_date_from_ts(time.time())
|
||||
if str(settings.get("yt_long_quota_limited_day") or "") == day:
|
||||
return True
|
||||
now = time.time()
|
||||
try:
|
||||
for entry in _load_quota_map(settings).values():
|
||||
if float((entry or {}).get("blocked_until") or 0) > now:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def mark_yt_long_api_limited(*, reason: str = "") -> None:
|
||||
"""Pin BJ-day reduced long-upload caps after a shared YouTube API quota hit."""
|
||||
from . import db
|
||||
|
||||
day = push_date_from_ts(time.time())
|
||||
patch: dict[str, Any] = {"yt_long_quota_limited_day": day}
|
||||
if reason:
|
||||
patch["yt_long_quota_limited_reason"] = str(reason)[:240]
|
||||
try:
|
||||
db.update_settings_map(patch)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def effective_yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
"""Per-channel Beijing-day upload target: 5 normally, 4 when API-limited."""
|
||||
if youtube_api_upload_limited(cfg):
|
||||
return YT_LONG_CHANNEL_LIMITED
|
||||
return YT_LONG_CHANNEL_DEFAULT
|
||||
|
||||
|
||||
def count_oauth_yt_long_channels(*, enabled_only: bool = True) -> int:
|
||||
rows = list_yt_long_channels(enabled=True if enabled_only else None)
|
||||
n = 0
|
||||
for ch in rows:
|
||||
if enabled_only and not ch.get("enabled"):
|
||||
continue
|
||||
if str(ch.get("refresh_token") or "").strip():
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def reconcile_yt_long_upload_caps(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Keep global + per-channel caps aligned: 5/ch normal, 4/ch when API limited."""
|
||||
from . import db
|
||||
|
||||
settings = cfg if cfg is not None else db.get_settings_map()
|
||||
limited = youtube_api_upload_limited(settings)
|
||||
# Persist the *normal* target at 5 so UI/settings match policy
|
||||
try:
|
||||
stored_ch = int(settings.get("yt_long_channel_daily_max") or 0)
|
||||
except Exception:
|
||||
stored_ch = 0
|
||||
if stored_ch != YT_LONG_CHANNEL_DEFAULT:
|
||||
try:
|
||||
db.update_settings_map({"yt_long_channel_daily_max": YT_LONG_CHANNEL_DEFAULT})
|
||||
settings = db.get_settings_map()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
per = YT_LONG_CHANNEL_LIMITED if limited else YT_LONG_CHANNEL_DEFAULT
|
||||
n = count_oauth_yt_long_channels(enabled_only=True)
|
||||
global_max = max(per, n * per) if n else YT_LONG_DAILY_DEFAULT
|
||||
try:
|
||||
stored_global = int(settings.get("yt_long_daily_max") or 0)
|
||||
except Exception:
|
||||
stored_global = 0
|
||||
if stored_global != global_max:
|
||||
try:
|
||||
db.update_settings_map({"yt_long_daily_max": global_max})
|
||||
settings = db.get_settings_map()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
touched = 0
|
||||
for ch in list_yt_long_channels(enabled=None):
|
||||
if not str(ch.get("refresh_token") or "").strip():
|
||||
continue
|
||||
try:
|
||||
cur = int(ch.get("daily_max") or 0)
|
||||
except Exception:
|
||||
cur = 0
|
||||
if cur != per:
|
||||
try:
|
||||
update_yt_long_channel(str(ch.get("id") or ""), daily_max=per)
|
||||
touched += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
from .clip_cascade import ensure_source_covers_platforms
|
||||
|
||||
ensure_source_covers_platforms(settings)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"limited": limited,
|
||||
"per_channel": per,
|
||||
"channels": n,
|
||||
"daily_max": global_max,
|
||||
"channels_updated": touched,
|
||||
"push_date": push_date_from_ts(time.time()),
|
||||
}
|
||||
|
||||
|
||||
def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
from . import db
|
||||
|
||||
@ -173,6 +290,45 @@ def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
return max(0, min(50, v))
|
||||
|
||||
|
||||
def room_blocks_yt_long_sample(room_id: str, push_date: str, *, need_upload_slots: bool = False) -> bool:
|
||||
"""Room-day dedupe. If upload slots remain, cascade-only dead-ends may be re-recorded."""
|
||||
rid = str(room_id or "").strip()
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
if not rid:
|
||||
return True
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
if not need_upload_slots:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 AS o FROM yt_long_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchone()
|
||||
return bool(row)
|
||||
# Still need YouTube uploads: only block if room already has a real upload pipeline job
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 AS o FROM yt_long_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND (
|
||||
status IN ('pending', 'recording', 'scheduled', 'uploading', 'uploaded')
|
||||
OR (status = 'recorded' AND IFNULL(clip_path, '') != '' AND IFNULL(error, '') != 'cascade_only')
|
||||
)
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchone()
|
||||
return bool(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def yt_long_source_used(push_date: str = "") -> int:
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
placeholders = ",".join("?" for _ in _SOURCE_STATUSES)
|
||||
|
||||
@ -188,9 +188,12 @@ def _enqueue_from_room(room: dict[str, Any], cfg: dict[str, Any], push_date: str
|
||||
rid = str(room.get("room_id") or "").strip()
|
||||
if not rid:
|
||||
return ""
|
||||
if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, push_date):
|
||||
need_upload = yt_long_db.yt_long_upload_gap(cfg=cfg) > 0
|
||||
if cfg.get("yt_long_dedupe_room_day", True) and yt_long_db.room_blocks_yt_long_sample(
|
||||
rid, push_date, need_upload_slots=need_upload
|
||||
):
|
||||
return ""
|
||||
channel = pick_yt_long_channel(cfg, push_date) if yt_long_db.yt_long_upload_gap(cfg=cfg) > 0 else None
|
||||
channel = pick_yt_long_channel(cfg, push_date) if need_upload else None
|
||||
created = yt_long_db.create_yt_long_job(
|
||||
room_pk=str(room.get("id") or room.get("room_pk") or ""),
|
||||
room_id=rid,
|
||||
@ -221,7 +224,11 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
||||
return 0
|
||||
if yt_long_db.yt_long_source_gap(cfg=settings) <= 0:
|
||||
return 0
|
||||
batch = max(1, min(8, int(settings.get("yt_long_live_sample_batch") or 1)))
|
||||
upload_gap = yt_long_db.yt_long_upload_gap(cfg=settings)
|
||||
need_upload = upload_gap > 0
|
||||
# Catch up faster when YouTube long slots remain
|
||||
base_batch = max(1, min(8, int(settings.get("yt_long_live_sample_batch") or 1)))
|
||||
batch = max(base_batch, min(8, upload_gap)) if need_upload else base_batch
|
||||
day = push_date_from_ts(time.time())
|
||||
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
||||
candidates: list[dict[str, Any]] = []
|
||||
@ -229,7 +236,9 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
||||
rid = str(room.get("room_id") or "")
|
||||
if not rid:
|
||||
continue
|
||||
if settings.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day):
|
||||
if settings.get("yt_long_dedupe_room_day", True) and yt_long_db.room_blocks_yt_long_sample(
|
||||
rid, day, need_upload_slots=need_upload
|
||||
):
|
||||
continue
|
||||
candidates.append(room)
|
||||
if not candidates:
|
||||
@ -266,10 +275,13 @@ def sample_live_now() -> dict[str, Any]:
|
||||
patched = {**settings, "yt_long_live_sample": True}
|
||||
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
||||
day = push_date_from_ts(time.time())
|
||||
need_upload = yt_long_db.yt_long_upload_gap(cfg=patched) > 0
|
||||
skipped = 0
|
||||
for room in rooms:
|
||||
rid = str(room.get("room_id") or "")
|
||||
if rid and patched.get("yt_long_dedupe_room_day", True) and yt_long_db.has_job_for_room_day(rid, day):
|
||||
if rid and patched.get("yt_long_dedupe_room_day", True) and yt_long_db.room_blocks_yt_long_sample(
|
||||
rid, day, need_upload_slots=need_upload
|
||||
):
|
||||
skipped += 1
|
||||
n = try_sample_live_rooms(patched)
|
||||
pending = yt_long_db.list_pending_yt_long_jobs(limit=20)
|
||||
@ -359,6 +371,11 @@ class YtLongPipeline:
|
||||
yt_long_db.sync_channels_from_shorts()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
yt_long_db.reconcile_yt_long_upload_caps(cfg)
|
||||
cfg = db.get_settings_map()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
board = yt_long_db.channel_board(day)
|
||||
except Exception:
|
||||
@ -372,6 +389,8 @@ class YtLongPipeline:
|
||||
cascade_need = estimate_platform_daily_need(cfg)
|
||||
except Exception:
|
||||
cascade_need = {}
|
||||
limited = yt_long_db.youtube_api_upload_limited(cfg)
|
||||
effective_ch = yt_long_db.effective_yt_long_channel_daily_max(cfg)
|
||||
return {
|
||||
"running": bool(self._task and not self._task.done()),
|
||||
"busy": self._active_records > 0 or self._active_uploads > 0,
|
||||
@ -386,7 +405,9 @@ class YtLongPipeline:
|
||||
"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": effective_ch,
|
||||
"channel_daily_max_normal": yt_long_db.YT_LONG_CHANNEL_DEFAULT,
|
||||
"api_quota_limited": limited,
|
||||
"last_error": self.last_error,
|
||||
"stats": yt_long_db.yt_long_stats(day),
|
||||
"board": board,
|
||||
@ -402,6 +423,8 @@ class YtLongPipeline:
|
||||
"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_effective": effective_ch,
|
||||
"yt_long_api_quota_limited": limited,
|
||||
"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_dedupe_room_day": bool(cfg.get("yt_long_dedupe_room_day", True)),
|
||||
@ -466,6 +489,11 @@ class YtLongPipeline:
|
||||
if not cfg.get("yt_long_enabled"):
|
||||
await asyncio.sleep(5)
|
||||
continue
|
||||
try:
|
||||
yt_long_db.reconcile_yt_long_upload_caps(cfg)
|
||||
cfg = db.get_settings_map()
|
||||
except Exception:
|
||||
pass
|
||||
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:
|
||||
self._last_sample_at = time.time()
|
||||
@ -708,6 +736,18 @@ class YtLongPipeline:
|
||||
await self._do_upload(job)
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)[:240]
|
||||
msg = str(exc)
|
||||
if "QUOTA_EXCEEDED" in msg or "quotaExceeded" in msg:
|
||||
try:
|
||||
from .shorts_yt_quota import pause_uploads_until_reset, profile_id_for_channel
|
||||
|
||||
ch = yt_long_db.get_yt_long_channel(str(job.get("channel_pk") or ""))
|
||||
pid = profile_id_for_channel(ch) if ch else "A"
|
||||
pause_uploads_until_reset(profile_id=pid, reason=msg[:160])
|
||||
yt_long_db.mark_yt_long_api_limited(reason=msg[:160])
|
||||
yt_long_db.reconcile_yt_long_upload_caps()
|
||||
except Exception:
|
||||
pass
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
|
||||
@ -79,7 +79,7 @@ type Job = {
|
||||
const emptyForm = {
|
||||
name: "",
|
||||
enabled: true,
|
||||
daily_max: 3,
|
||||
daily_max: 5,
|
||||
title_template: "",
|
||||
description_template: "",
|
||||
privacy: "public",
|
||||
@ -215,14 +215,14 @@ export default function YtLongPage() {
|
||||
youtube_channel_id: c.youtube_channel_id,
|
||||
oauth_profile_id: c.oauth_profile_id,
|
||||
enabled: c.enabled,
|
||||
daily_max: Number(c.daily_max ?? 3),
|
||||
daily_max: Number(c.daily_max ?? 5),
|
||||
authorized: Boolean(c.authorized || c.has_refresh_token),
|
||||
used: 0,
|
||||
scheduled: 0,
|
||||
uploaded: 0,
|
||||
pending: 0,
|
||||
failed: 0,
|
||||
gap: Number(c.daily_max ?? 3),
|
||||
gap: Number(c.daily_max ?? 5),
|
||||
}));
|
||||
return base.map((ch) => ({
|
||||
...ch,
|
||||
@ -354,7 +354,7 @@ export default function YtLongPage() {
|
||||
setForm({
|
||||
name: ch.name || "",
|
||||
enabled: ch.enabled !== false,
|
||||
daily_max: Number(ch.daily_max ?? 3),
|
||||
daily_max: Number(ch.daily_max ?? 5),
|
||||
title_template: ch.title_template || "{anchor} street food live",
|
||||
description_template: ch.description_template || "",
|
||||
privacy: ch.privacy || "public",
|
||||
@ -729,7 +729,7 @@ export default function YtLongPage() {
|
||||
type="number"
|
||||
min={0}
|
||||
max={50}
|
||||
value={Number(form.daily_max ?? 3)}
|
||||
value={Number(form.daily_max ?? 5)}
|
||||
onChange={(e) =>
|
||||
setForm((p) => ({ ...p, daily_max: Math.max(0, Number(e.target.value) || 0) }))
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user