diff --git a/backend/app/clip_cascade.py b/backend/app/clip_cascade.py index cdfc792..9012184 100644 --- a/backend/app/clip_cascade.py +++ b/backend/app/clip_cascade.py @@ -159,7 +159,12 @@ def _pick_start(master_sec: float, cut_sec: int, window: tuple[float, float]) -> def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, int]: - """How many uploads each platform wants today (enabled channels × per-channel caps).""" + """Platform daily wants (informational) + authoritative yt-long master count. + + Master recordings are owned by **enabled yt_long channels × per-channel cap**. + One master can cascade-cut Shorts/TikTok/X — do **not** inflate masters to + Shorts fleet size (that produced 7×9=63 while only 7 long channels × 2 = 14). + """ from . import db from . import tiktok_db from . import yt_long_db @@ -175,15 +180,17 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or []) except Exception: tiktok_n = 0 - yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0) + # Prefer sum of enabled oauth channel caps (respects per-row daily_max). + yt_upload = int(yt_long_db.yt_long_enabled_upload_cap(settings_map) or 0) + if yt_upload <= 0: + yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0) shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE) tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE) try: x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20)) except Exception: x_need = 20 - # One master feeds all platforms once → masters needed = max(...) - source_need = max(yt_upload, shorts_need, tiktok_need, x_need, 0) + source_need = max(0, yt_upload) return { "yt_long": yt_upload, "yt_long_upload": yt_upload, @@ -197,23 +204,21 @@ 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]: - """Always keep yt_long_source_daily_max ≥ max(platform quotas); never raise upload cap.""" + """Keep yt_long_source_daily_max == enabled long-upload cap (no Shorts inflation).""" from . import db from . import yt_long_db settings_map = cfg if cfg is not None else db.get_settings_map() need = estimate_platform_daily_need(settings_map) - target = int(need["source_masters"]) + upload_cap = int(need.get("yt_long_upload") or yt_long_db.yt_long_daily_max(settings_map) or 0) + target = upload_cap 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)): - # Without cascade, source only needs to cover YouTube long uploads - target = upload_cap try: - hard_cap = max(42, min(300, int(settings_map.get("yt_long_source_cap") or 200))) + hard_cap = max(upload_cap, min(300, int(settings_map.get("yt_long_source_cap") or 200))) except Exception: - hard_cap = 200 - new_max = min(hard_cap, max(upload_cap, target)) + hard_cap = max(upload_cap, 200) + # Never floor at 42 — that forced 母片≥42 when only 7×2=14 was configured. + new_max = min(hard_cap, max(0, target)) if new_max != int(settings_map.get("yt_long_source_daily_max") or 0): db.update_settings_map({"yt_long_source_daily_max": new_max}) return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need} diff --git a/backend/app/main.py b/backend/app/main.py index 270ced4..91f4157 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1686,7 +1686,7 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st 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"]))) + patch["yt_long_source_cap"] = max(0, 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: diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index b8b2123..2fcd5d7 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -144,23 +144,39 @@ def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: return max(0, min(200, v)) +def yt_long_enabled_upload_cap(cfg: dict[str, Any] | None = None) -> int: + """Sum of daily_max for enabled oauth yt_long channels (authoritative upload/master cap).""" + per = effective_yt_long_channel_daily_max(cfg) + total = 0 + n = 0 + for ch in list_yt_long_channels(enabled=True): + if not ch.get("enabled", True): + continue + if not str(ch.get("refresh_token") or "").strip(): + continue + n += 1 + try: + row_max = int(ch.get("daily_max") or 0) + except Exception: + row_max = 0 + if row_max <= 0: + row_max = per + # Soft API limit: never count above effective per-channel cap. + total += min(row_max, per) if per > 0 else row_max + if n <= 0: + return max(0, per) + return max(0, total) + + def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int: - """Master recording daily cap — must cover cascade platform needs.""" + """Master recording daily cap — equals enabled long-upload quota (not Shorts fleet).""" 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)) + upload_cap = yt_long_enabled_upload_cap(settings) + if upload_cap <= 0: + upload_cap = yt_long_daily_max(settings) + return max(0, upload_cap) def youtube_api_upload_limited(cfg: dict[str, Any] | None = None) -> bool: @@ -234,14 +250,27 @@ def reconcile_yt_long_upload_caps(cfg: dict[str, Any] | None = None) -> dict[str limited = youtube_api_upload_limited(settings) per = effective_yt_long_channel_daily_max(settings) n = count_oauth_yt_long_channels(enabled_only=True) - global_max = max(per, n * per) if n else max(per, YT_LONG_DAILY_DEFAULT) + # Enabled channels only — never multiply by disabled Account B rows. + global_max = yt_long_enabled_upload_cap(settings) + if global_max <= 0: + global_max = max(per, n * per) if n else max(per, 0) try: stored_global = int(settings.get("yt_long_daily_max") or 0) except Exception: stored_global = 0 + patch: dict[str, Any] = {} if stored_global != global_max: + patch["yt_long_daily_max"] = global_max + # Keep source in lockstep with enabled upload cap (clear Shorts-inflated 63 etc.). + try: + stored_src = int(settings.get("yt_long_source_daily_max") or 0) + except Exception: + stored_src = 0 + if stored_src != global_max: + patch["yt_long_source_daily_max"] = global_max + if patch: try: - db.update_settings_map({"yt_long_daily_max": global_max}) + db.update_settings_map(patch) settings = db.get_settings_map() except Exception: pass diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index 9989b25..fe11056 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -379,14 +379,16 @@ export default function YtLongPage() { }, [upcoming, channelProfileMap]); const totals = useMemo(() => { - const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0); - const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0); - // Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。 + // Only **enabled** channels count toward YouTube 上传 3/14 (not disabled Account B). + const active = displayChannels.filter((c) => c.enabled !== false); + const uploaded = active.reduce((s, c) => s + (c.uploaded || 0), 0); + const scheduled = active.reduce((s, c) => s + (c.scheduled || 0), 0); const used = uploaded; - const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0); - const gap = displayChannels - .filter((c) => c.enabled !== false) - .reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0); + const cap = active.reduce((s, c) => s + (c.daily_max || 0), 0); + const gap = active.reduce( + (s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), + 0, + ); return { uploaded, scheduled, used, cap, gap }; }, [displayChannels]); diff --git a/scripts/_fix_yt_long_quota_both.py b/scripts/_fix_yt_long_quota_both.py new file mode 100644 index 0000000..bfadb45 --- /dev/null +++ b/scripts/_fix_yt_long_quota_both.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +"""Fix yt-long quota inflation on dy + dylive and restart.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +JUMP = "107.173.30.245" +DY = "108.174.50.68" + +FILES = [ + "backend/app/clip_cascade.py", + "backend/app/yt_long_db.py", + "backend/app/main.py", + "frontend/src/app/yt-long/page.tsx", +] + +SH = r''' +set -e +cp -a /tmp/_ql_clip_cascade.py /opt/douyinWEB/backend/app/clip_cascade.py +cp -a /tmp/_ql_yt_long_db.py /opt/douyinWEB/backend/app/yt_long_db.py +cp -a /tmp/_ql_main.py /opt/douyinWEB/backend/app/main.py +install -D -m 644 /tmp/_ql_page.tsx /opt/douyinWEB/frontend/src/app/yt-long/page.tsx +cd /opt/douyinWEB/backend +.venv/bin/python -m py_compile app/clip_cascade.py app/yt_long_db.py app/main.py +.venv/bin/python - <<'PY' +from app import db, yt_long_db +from app.clip_cascade import estimate_platform_daily_need, ensure_source_covers_platforms +print("reconcile", yt_long_db.reconcile_yt_long_upload_caps()) +print("need", estimate_platform_daily_need()) +print("adj", ensure_source_covers_platforms()) +cfg = db.get_settings_map() +en = [c for c in yt_long_db.list_yt_long_channels(enabled=True) if c.get("enabled") and str(c.get("refresh_token") or "").strip()] +print("enabled_oauth", len(en)) +print("caps", yt_long_db.yt_long_enabled_upload_cap(), cfg.get("yt_long_daily_max"), cfg.get("yt_long_source_daily_max")) +print("source_fn", yt_long_db.yt_long_source_daily_max(), "used", yt_long_db.yt_long_source_used(), "gap", yt_long_db.yt_long_source_gap()) +print("upload_gap", yt_long_db.yt_long_upload_gap()) +PY +systemctl restart douyinweb-api +for i in $(seq 1 20); do + c=$(curl -sS -m 3 -o /dev/null -w "%{http_code}" http://127.0.0.1:8014/api/health || echo x) + echo health:$c + [ "$c" = "200" ] && break + sleep 2 +done +cd /opt/douyinWEB/frontend && npm run build 2>&1 | tail -20 +systemctl restart douyinweb-web +sleep 2 +systemctl is-active douyinweb-api douyinweb-web +echo HOST_DONE +''' + + +def wait_out(c: paramiko.SSHClient, path: str, token: str = "HOST_DONE", rounds: int = 150) -> str: + out = "" + for i in range(rounds): + time.sleep(3) + _, o, _ = c.exec_command(f"tail -c 25000 {path} 2>/dev/null", timeout=20) + out = o.read().decode("utf-8", "replace") + if token in out and "EXIT:" in out: + return out + if i % 5 == 0: + print("poll", i, out[-140:].replace("\n", " | "), flush=True) + return out + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(JUMP, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + mapping = { + "clip_cascade.py": "/tmp/_ql_clip_cascade.py", + "yt_long_db.py": "/tmp/_ql_yt_long_db.py", + "main.py": "/tmp/_ql_main.py", + "page.tsx": "/tmp/_ql_page.tsx", + } + for rel in FILES: + name = Path(rel).name + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n") + with sftp.file(mapping[name], "wb") as f: + f.write(data) + print("staged", name, len(data), flush=True) + with sftp.file("/tmp/_ql_remote.sh", "w") as f: + f.write(SH) + sftp.close() + + print("\n===== dylive =====", flush=True) + c.exec_command( + "bash /tmp/_ql_remote.sh > /tmp/_ql_dylive.out 2>&1; echo EXIT:$? >> /tmp/_ql_dylive.out", + timeout=1, + ) + print(wait_out(c, "/tmp/_ql_dylive.out")[-12000:], flush=True) + + print("\n===== dy.live =====", flush=True) + files = " ".join(mapping.values()) + " /tmp/_ql_remote.sh" + c.exec_command( + f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no {files} root@{DY}:/tmp/ && " + f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} " + f"'bash /tmp/_ql_remote.sh' > /tmp/_ql_dy.out 2>&1; echo EXIT:$? >> /tmp/_ql_dy.out", + timeout=1, + ) + print(wait_out(c, "/tmp/_ql_dy.out")[-12000:], flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())