feat: 9:16 yt-long masters, cascade cuts to TikTok/Shorts/X, 48h clip retention

Keep vertical long-form by default (16:9 opt-in off), reuse masters via ffmpeg segments for other platforms, and rush-or-delete clips older than 48h.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-20 12:04:42 -05:00
parent 31228a0410
commit 7e4a8b4e70
12 changed files with 676 additions and 43 deletions

373
backend/app/clip_cascade.py Normal file
View File

@ -0,0 +1,373 @@
# -*- coding: utf-8 -*-
"""Cut derived platform clips from a yt-long master (9:16).
Platforms stay isolated (own tables / quotas / workers). This module only:
1) ffmpeg-cuts a segment from an existing master mp4
2) creates a platform job already in scheduled/recorded with clip_path set
Never raises into the yt-long pipeline caller.
"""
from __future__ import annotations
import asyncio
import random
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import settings
def _clamp(v: int, lo: int, hi: int) -> int:
return max(lo, min(hi, int(v)))
def tiktok_cut_sec(cfg: dict[str, Any]) -> int:
"""1–1.5 minutes."""
try:
base = int(cfg.get("tiktok_clip_sec") or 75)
except Exception:
base = 75
base = _clamp(base, 60, 90)
return random.randint(60, max(60, base)) if base > 60 else random.randint(60, 90)
def shorts_cut_sec(cfg: dict[str, Any]) -> int:
"""15–20 seconds."""
try:
base = int(cfg.get("shorts_clip_sec") or 15)
except Exception:
base = 15
base = _clamp(base, 15, 20)
return random.randint(15, 20) if base <= 15 else random.randint(15, base)
def x_cut_sec(cfg: dict[str, Any]) -> int:
"""15–20 seconds."""
try:
base = int(cfg.get("x_clips_clip_sec") or 18)
except Exception:
base = 18
base = _clamp(base, 15, 20)
return random.randint(15, 20) if base <= 15 else random.randint(15, base)
def cut_segment(
*,
src: str,
dst: str,
start_sec: float,
duration_sec: int,
) -> dict[str, Any]:
src_p = Path(src)
if not src_p.is_file():
return {"ok": False, "error": "master missing"}
out = Path(dst)
out.parent.mkdir(parents=True, exist_ok=True)
if out.is_file():
try:
out.unlink()
except OSError:
pass
start = max(0.0, float(start_sec))
dur = max(5, int(duration_sec))
cmd = [
settings.ffmpeg_bin,
"-y",
"-hide_banner",
"-loglevel",
"error",
"-ss",
f"{start:.3f}",
"-i",
str(src_p),
"-t",
str(dur),
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"23",
"-c:a",
"aac",
"-b:a",
"128k",
"-movflags",
"+faststart",
"-avoid_negative_ts",
"make_zero",
str(out),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=dur + 120)
except Exception as exc:
return {"ok": False, "error": str(exc)[:300]}
if proc.returncode != 0:
return {"ok": False, "error": (proc.stderr or proc.stdout or "cut failed")[:400]}
if not out.is_file() or out.stat().st_size < 20_000:
return {"ok": False, "error": "cut too small"}
return {"ok": True, "path": str(out), "seconds": dur}
def _pick_start(master_sec: float, cut_sec: int, window: tuple[float, float]) -> float:
"""Pick start within [lo,hi] fraction of master, leaving room for cut_sec."""
master = max(float(master_sec), float(cut_sec) + 1.0)
lo_f, hi_f = window
lo = master * lo_f
hi = max(lo, master * hi_f)
max_start = max(0.0, master - float(cut_sec) - 0.5)
lo = min(lo, max_start)
hi = min(hi, max_start)
if hi <= lo:
return max(0.0, max_start * 0.2)
return random.uniform(lo, hi)
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)."""
from . import db
from . import tiktok_db
from . import yt_long_db
from . import x_clips_db
settings_map = cfg if cfg is not None else db.get_settings_map()
shorts_n = 0
try:
shorts_n = len(db.list_shorts_channels(enabled=True) or [])
except Exception:
shorts_n = 0
tiktok_n = 0
try:
tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or [])
except Exception:
tiktok_n = 0
yt_long = 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 can feed all platforms once → masters needed = max(...)
source_need = max(yt_long, shorts_need, tiktok_need, x_need, 0)
return {
"yt_long": yt_long,
"shorts": shorts_need,
"tiktok": tiktok_need,
"x": x_need,
"source_masters": source_need,
"shorts_channels": shorts_n,
"tiktok_channels": tiktok_n,
}
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.
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 yt_long_db
settings_map = cfg if cfg is not None else db.get_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"])
if not bool(settings_map.get("clip_cascade_enabled", True)):
return {"ok": True, "adjusted": False, "from": current, "to": current, **need}
if not bool(settings_map.get("yt_long_auto_match_source", False)):
return {"ok": True, "adjusted": False, "from": current, "to": current, **need}
try:
hard_cap = max(42, min(200, int(settings_map.get("yt_long_source_cap") or 200)))
except Exception:
hard_cap = 200
new_max = min(hard_cap, max(current, target))
if new_max > current:
db.update_settings_map({"yt_long_daily_max": new_max})
return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need}
return {"ok": True, "adjusted": False, "from": current, "to": current, **need}
async def cascade_from_yt_long(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""After a yt-long master is recorded, cut TikTok / Shorts / X segments if quotas allow."""
from . import db
from . import tiktok_db
from . import x_clips_db
from .timeutil import push_date_from_ts
settings_map = cfg if cfg is not None else db.get_settings_map()
out: dict[str, Any] = {"tiktok": None, "shorts": None, "x": None}
if not bool(settings_map.get("clip_cascade_enabled", True)):
return {"ok": True, "skipped": "cascade_off", **out}
master = str(job.get("clip_path") or "").strip()
if not master or not Path(master).is_file():
return {"ok": False, "error": "no_master", **out}
try:
master_sec = float(job.get("clip_seconds") or 0) or 300.0
except Exception:
master_sec = 300.0
day = str(job.get("push_date") or "").strip() or push_date_from_ts(time.time())
room_id = str(job.get("room_id") or "")
room_pk = str(job.get("room_pk") or "")
source_url = str(job.get("source_url") or "")
anchor = str(job.get("anchor_name") or "")
stream_url = str(job.get("stream_url") or "")
clips_root = settings.clips_dir
clips_root.mkdir(parents=True, exist_ok=True)
# ── TikTok (1–1.5 min) ─────────────────────────────────────────────
if bool(settings_map.get("tiktok_enabled", False)):
try:
if room_id and tiktok_db.has_tiktok_job_for_room_day(room_id, day):
out["tiktok"] = "dedupe"
else:
ch = tiktok_db.pick_tiktok_channel(day, require_quota=True)
if not ch:
out["tiktok"] = "no_quota"
else:
sec = tiktok_cut_sec(settings_map)
start = _pick_start(master_sec, sec, (0.05, 0.35))
jtmp = tiktok_db.create_tiktok_job(
session_id="",
room_pk=room_pk,
room_id=room_id,
source_url=source_url,
anchor_name=anchor,
stream_url=stream_url,
channel_pk=str(ch.get("id") or ""),
push_date=day,
)
if not jtmp:
out["tiktok"] = "create_failed"
else:
jid = str(jtmp["id"])
dst = str(clips_root / f"tiktok_{jid[:8]}.mp4")
cut = await asyncio.to_thread(
cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec
)
if not cut.get("ok"):
tiktok_db.update_tiktok_job(
jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time()
)
out["tiktok"] = f"cut_fail:{cut.get('error')}"
else:
upload_at = time.time() + random.uniform(60, 600)
tiktok_db.update_tiktok_job(
jid,
status="scheduled",
clip_path=str(cut["path"]),
clip_seconds=float(cut.get("seconds") or sec),
upload_at=upload_at,
error="cascade_from_yt_long",
)
out["tiktok"] = jid
except Exception as exc:
out["tiktok"] = f"err:{exc}"[:120]
# ── Shorts (15–20s) ────────────────────────────────────────────────
if bool(settings_map.get("shorts_enabled", False)):
try:
if room_id and settings_map.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(room_id, day):
out["shorts"] = "dedupe"
else:
ch = db.pick_shorts_channel(day, settings_map, require_upload_quota=True)
if not ch:
out["shorts"] = "no_quota"
else:
sec = shorts_cut_sec(settings_map)
start = _pick_start(master_sec, sec, (0.45, 0.70))
jtmp = db.create_shorts_job(
session_id="",
room_pk=room_pk,
room_id=room_id,
source_url=source_url,
anchor_name=anchor,
stream_url=stream_url,
channel_pk=str(ch.get("id") or ""),
push_date=day,
)
if not jtmp:
out["shorts"] = "create_failed"
else:
jid = str(jtmp["id"])
dst = str(clips_root / f"{jid}.mp4")
cut = await asyncio.to_thread(
cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec
)
if not cut.get("ok"):
db.update_shorts_job(
jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time()
)
out["shorts"] = f"cut_fail:{cut.get('error')}"
else:
from .shorts_schedule import pick_upload_at
upload_at = pick_upload_at(channel_pk=str(ch.get("id") or ""), cfg=settings_map)
db.update_shorts_job(
jid,
status="scheduled",
clip_path=str(cut["path"]),
clip_seconds=float(cut.get("seconds") or sec),
upload_at=upload_at,
error="cascade_from_yt_long",
)
out["shorts"] = jid
except Exception as exc:
out["shorts"] = f"err:{exc}"[:120]
# ── X (15–20s) ─────────────────────────────────────────────────────
if bool(settings_map.get("x_clips_enabled", False)):
try:
if x_clips_db.x_clips_quota_gap(cfg=settings_map) <= 0:
out["x"] = "no_quota"
elif room_id and settings_map.get("x_clips_dedupe_room_day", True) and x_clips_db.has_x_clip_job_for_room_day(
room_id, day
):
out["x"] = "dedupe"
else:
sec = x_cut_sec(settings_map)
start = _pick_start(master_sec, sec, (0.72, 0.92))
acct = str(settings_map.get("x_clips_account_username") or "").strip().lstrip("@")
jtmp = x_clips_db.create_x_clip_job(
session_id="",
room_pk=room_pk,
room_id=room_id,
source_url=source_url,
anchor_name=anchor,
stream_url=stream_url,
push_date=day,
account_username=acct,
)
if not jtmp:
out["x"] = "create_failed"
else:
jid = str(jtmp["id"])
dst = str(clips_root / f"xclip_{jid[:8]}.mp4")
cut = await asyncio.to_thread(
cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec
)
if not cut.get("ok"):
x_clips_db.update_x_clip_job(
jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time()
)
out["x"] = f"cut_fail:{cut.get('error')}"
else:
upload_at = time.time() + random.uniform(45, 480)
x_clips_db.update_x_clip_job(
jid,
status="scheduled",
clip_path=str(cut["path"]),
clip_seconds=float(cut.get("seconds") or sec),
upload_at=upload_at,
error="cascade_from_yt_long",
)
out["x"] = jid
except Exception as exc:
out["x"] = f"err:{exc}"[:120]
return {"ok": True, **out}

View File

@ -0,0 +1,182 @@
# -*- coding: utf-8 -*-
"""Clip retention: materials must not stay on disk longer than 48h.
Policy:
1) Prefer using clips to fill remaining platform quotas (accelerate upload_at)
2) Then delete files older than max_age_hours and clear job clip_path when safe
"""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any
from .config import settings
_DEFAULT_MAX_AGE_H = 48.0
def _max_age_sec(cfg: dict[str, Any]) -> float:
try:
h = float(cfg.get("clips_max_age_hours") or _DEFAULT_MAX_AGE_H)
except Exception:
h = _DEFAULT_MAX_AGE_H
return max(1.0, min(168.0, h)) * 3600.0
def _iter_clip_files() -> list[Path]:
root = Path(settings.clips_dir)
out: list[Path] = []
if not root.is_dir():
return out
for p in root.rglob("*.mp4"):
try:
if p.is_file():
out.append(p)
except OSError:
continue
return out
def _accelerate_jobs_for_path(path: str, now: float) -> int:
from . import db
n = 0
soon = now + 30.0
updates = (
(
"shorts_jobs",
"UPDATE shorts_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' "
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''",
),
(
"tiktok_jobs",
"UPDATE tiktok_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' "
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tiktok_video_id,'') = ''",
),
(
"x_clip_jobs",
"UPDATE x_clip_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' "
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tweet_id,'') = ''",
),
(
"yt_long_jobs",
"UPDATE yt_long_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' "
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''",
),
)
try:
with db._lock:
conn = db._connect()
try:
for _name, sql in updates:
try:
cur = conn.execute(sql, (soon, now, path))
n += int(cur.rowcount or 0)
except Exception:
continue
conn.commit()
finally:
conn.close()
except Exception:
pass
return n
def _clear_path_refs(path: str, now: float) -> None:
from . import db
try:
with db._lock:
conn = db._connect()
try:
for table in ("shorts_jobs", "tiktok_jobs", "x_clip_jobs", "yt_long_jobs"):
try:
conn.execute(
f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?",
(now, path),
)
except Exception:
continue
conn.commit()
finally:
conn.close()
except Exception:
pass
def _job_still_needs_file(path: str) -> bool:
from . import db
checks = (
"SELECT 1 FROM shorts_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
"SELECT 1 FROM tiktok_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
"SELECT 1 FROM x_clip_jobs WHERE clip_path=? AND status IN ('posting','recording') LIMIT 1",
"SELECT 1 FROM yt_long_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
)
try:
with db._lock:
conn = db._connect()
try:
for sql in checks:
try:
if conn.execute(sql, (path,)).fetchone():
return True
except Exception:
continue
finally:
conn.close()
except Exception:
return True
return False
def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Rush pending uploads for old clips, then delete files older than retention window."""
from . import db
settings_map = cfg if cfg is not None else db.get_settings_map()
max_age = _max_age_sec(settings_map)
now = time.time()
rushed = 0
deleted = 0
skipped_inflight = 0
examined = 0
for path in _iter_clip_files():
examined += 1
try:
mtime = path.stat().st_mtime
except OSError:
continue
age = now - mtime
if age < max_age * 0.85:
continue
variants = {str(path)}
try:
variants.add(str(path.resolve()))
except OSError:
pass
if age < max_age:
for sp in variants:
rushed += _accelerate_jobs_for_path(sp, now)
continue
if any(_job_still_needs_file(sp) for sp in variants):
skipped_inflight += 1
continue
for sp in variants:
_accelerate_jobs_for_path(sp, now)
try:
path.unlink(missing_ok=True)
deleted += 1
for sp in variants:
_clear_path_refs(sp, now)
except OSError:
continue
return {
"ok": True,
"examined": examined,
"rushed": rushed,
"deleted": deleted,
"skipped_inflight": skipped_inflight,
"max_age_hours": max_age / 3600.0,
}

View File

@ -427,7 +427,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"shorts_upload_spread": True,
"shorts_upload_min_gap_sec": 720,
"shorts_channel_min_gap_sec": 2400,
"shorts_delete_clip_after_upload": True,
"shorts_delete_clip_after_upload": False,
"shorts_auto_retry_failed": True,
"shorts_auto_retry_max_attempts": 3,
"shorts_auto_retry_interval_sec": 300,
@ -463,7 +463,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
],
# TikTok pipeline (fully isolated from Shorts)
"tiktok_enabled": False,
"tiktok_clip_sec": 60,
"tiktok_clip_sec": 75,
"tiktok_trigger": "tagged",
"tiktok_tag": "shorts",
"tiktok_dedupe_room_day": True,
@ -476,7 +476,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"tiktok_upload_spread": True,
"tiktok_upload_min_gap_sec": 720,
"tiktok_channel_min_gap_sec": 2400,
"tiktok_delete_clip_after_upload": True,
"tiktok_delete_clip_after_upload": False,
# TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default
"tiktok_upload_socks_profiles": [],
# X2 (Twitter/X ops agent) ingest
@ -484,7 +484,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"x2_default_agent_label": "PVE-X2",
# X live-clip auto post (isolated from Shorts / TikTok)
"x_clips_enabled": False,
"x_clips_clip_sec": 12,
"x_clips_clip_sec": 18,
"x_clips_trigger": "tagged",
"x_clips_tag": "x",
"x_clips_dedupe_room_day": True,
@ -497,11 +497,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"x_clips_sample_any_live": True,
"x_clips_upload_spread": True,
"x_clips_upload_min_gap_sec": 600,
"x_clips_delete_clip_after_post": True,
"x_clips_delete_clip_after_post": False,
"x_clips_daily_max": 20,
"x_clips_caption_template": "{anchor}",
"x_clips_account_username": "",
# YouTube long-form 16:9 (isolated; default OFF — does not affect Shorts)
# YouTube long-form 9:16 masters (isolated; default OFF — does not affect Shorts)
"yt_long_enabled": False,
"yt_long_with_shorts": True,
"yt_long_auto_upload": True,
@ -515,9 +515,14 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"yt_long_dedupe_room_day": True,
"yt_long_max_concurrent": 2,
"yt_long_upload_min_gap_sec": 900,
"yt_long_delete_clip_after_upload": True,
"yt_long_delete_clip_after_upload": False,
"yt_long_landscape_16x9": False,
"yt_long_auto_match_source": False,
"yt_long_source_cap": 200,
"yt_long_title_template": "",
"yt_long_description_template": "",
"clip_cascade_enabled": True,
"clips_max_age_hours": 48,
"tiktok_auto_retry_failed": False,
"tiktok_auto_retry_max_attempts": 3,
"tiktok_auto_retry_interval_sec": 300,

View File

@ -1002,7 +1002,7 @@ async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[st
raw = body or {}
if "x_clips_clip_sec" in raw:
try:
patch["x_clips_clip_sec"] = max(10, min(15, int(raw["x_clips_clip_sec"])))
patch["x_clips_clip_sec"] = max(15, min(20, int(raw["x_clips_clip_sec"])))
except Exception:
raise HTTPException(400, "clip_sec 无效") from None
if "x_clips_daily_max" in raw:
@ -1177,7 +1177,7 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
return {"ok": True, "job": updated or job}
# ── YouTube long-form 16:9 (isolated; default disabled) ──────────────────────
# ── YouTube long-form 9:16 (isolated; default disabled) ──────────────────────
@app.get("/api/yt-long/status")
@ -1215,9 +1215,17 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
"yt_long_dedupe_room_day",
"yt_long_delete_clip_after_upload",
"yt_long_live_sample",
"yt_long_landscape_16x9",
"clip_cascade_enabled",
"yt_long_auto_match_source",
):
if k in raw:
patch[k] = bool(raw[k])
if "clips_max_age_hours" in raw:
try:
patch["clips_max_age_hours"] = max(1, min(168, float(raw["clips_max_age_hours"])))
except Exception:
raise HTTPException(400, "clips_max_age_hours 无效") from None
if "yt_long_daily_max" in raw:
try:
patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"])))

View File

@ -565,7 +565,7 @@ class ShortsPipeline:
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400),
"max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)),
"upload_max_concurrent": self._upload_max(cfg),
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)),
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", False)),
"stats": stats,
"board": board,
"history": history,
@ -1058,7 +1058,7 @@ class ShortsPipeline:
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
# Isolated companion: enqueue 16:9 long-form (never raises into Shorts).
# Isolated companion: enqueue 9:16 long-form master (never raises into Shorts).
try:
from .yt_long_pipeline import try_enqueue_from_shorts
@ -1299,7 +1299,7 @@ class ShortsPipeline:
if not won:
# Peer already finalized — do not treat as failure; avoid deleting their state
return
if cfg.get("shorts_delete_clip_after_upload", True):
if cfg.get("shorts_delete_clip_after_upload", False):
self._delete_clip(clip)
self._emit_shorts_event(
kind="shorts_ok",

View File

@ -265,7 +265,7 @@ class TikTokPipeline:
"sampled": self.sampled,
"quota_gap": tiktok_db.tiktok_total_quota_gap(),
"last_error": self.last_error,
"clip_sec": max(60, int(cfg.get("tiktok_clip_sec") or 60)),
"clip_sec": max(60, min(90, int(cfg.get("tiktok_clip_sec") or 75))),
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"board": board,
"oauth_issues": oauth_issues,
@ -504,14 +504,18 @@ class TikTokPipeline:
)
return
# TikTok 素材最少录 1 分钟;多 CDN 线路按 DouyinLiveRecorder 方式试探
sec = max(60, int(cfg.get("tiktok_clip_sec") or 60))
# TikTok 素材 1–1.5 分钟;多 CDN 线路按 DouyinLiveRecorder 方式试探
try:
sec = int(cfg.get("tiktok_clip_sec") or 75)
except Exception:
sec = 75
sec = max(60, min(90, sec))
try:
room_pk = str(job.get("room_pk") or "")
room = db.get_room(room_pk) if room_pk else None
override = db.room_clip_seconds(room, default=0, platform="tiktok") if room else 0
if override > 0:
sec = max(60, override)
sec = max(60, min(90, override))
except Exception:
pass
outcome = await record_clip(
@ -707,7 +711,7 @@ class TikTokPipeline:
oauth_checked_at=time.time(),
oauth_error="",
)
if cfg.get("tiktok_delete_clip_after_upload", True):
if cfg.get("tiktok_delete_clip_after_upload", False):
try:
Path(clip).unlink(missing_ok=True)
except Exception:

View File

@ -60,14 +60,14 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
def _clip_sec(cfg: dict[str, Any], room: dict[str, Any] | None = None) -> int:
try:
base = int(cfg.get("x_clips_clip_sec") or 12)
base = int(cfg.get("x_clips_clip_sec") or 18)
except Exception:
base = 12
base = max(10, min(15, base))
base = 18
base = max(15, min(20, base))
try:
override = db.room_clip_seconds(room, default=0, platform="x") if room else 0
if override > 0:
return max(10, min(15, override))
return max(15, min(20, override))
except Exception:
pass
return base
@ -296,7 +296,7 @@ class XClipsPipeline:
"x_clips_auto_post": bool(cfg.get("x_clips_auto_post", True)),
"x_clips_upload_spread": bool(cfg.get("x_clips_upload_spread", True)),
"x_clips_upload_min_gap_sec": int(cfg.get("x_clips_upload_min_gap_sec") or 600),
"x_clips_delete_clip_after_post": bool(cfg.get("x_clips_delete_clip_after_post", True)),
"x_clips_delete_clip_after_post": bool(cfg.get("x_clips_delete_clip_after_post", False)),
},
}
@ -649,7 +649,7 @@ class XClipsPipeline:
error="",
finished_at=time.time(),
)
if cfg.get("x_clips_delete_clip_after_post", True):
if cfg.get("x_clips_delete_clip_after_post", False):
self._delete_clip(str(job.get("clip_path") or ""))
elif st in {"failed", "cancelled"}:
err = str(row.get("error") or st)[:500]

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""Record landscape 16:9 long clips — isolated from Shorts 9:16 recorder.
"""Record YouTube long-form clips (default 9:16). 16:9 landscape is opt-in and off.
Reuses only side-effect-free stream helpers from shorts_clip.
Writes under clips_dir/yt_long/ so filenames never collide with Shorts.
@ -16,8 +16,16 @@ from .shorts_clip import _headers_arg, probe_stream_url
from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC
def _portrait_vf() -> str:
"""Keep vertical 9:16 (1080x1920 center crop) — same as Shorts/TikTok/X."""
return (
"scale=1080:1920:force_original_aspect_ratio=increase,"
"crop=1080:1920,setsar=1"
)
def _landscape_vf() -> str:
"""Fit source to 1080p height, center on 1920x1080 (pillarbox for 9:16)."""
"""Legacy 16:9 pillarbox — disabled unless yt_long_landscape_16x9=True."""
return (
"scale=-2:1080:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black,setsar=1"
@ -30,14 +38,24 @@ def clips_dir() -> Path:
return d
async def record_landscape_clip(
def _vf_for_settings(cfg: dict[str, Any] | None = None) -> str:
from . import db
settings_map = cfg if cfg is not None else db.get_settings_map()
if bool(settings_map.get("yt_long_landscape_16x9", False)):
return _landscape_vf()
return _portrait_vf()
async def record_long_clip(
*,
job_id: str,
stream_urls: list[str] | None = None,
stream_url: str = "",
seconds: int = 300,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Pull live stream for 3–8 minutes into a 16:9 mp4."""
"""Pull live stream for 3–8 minutes into a 9:16 mp4 (16:9 only if explicitly enabled)."""
urls: list[str] = []
for u in list(stream_urls or []) + [stream_url]:
s = str(u or "").strip()
@ -48,7 +66,7 @@ async def record_landscape_clip(
sec = max(YT_LONG_MIN_SEC, min(int(seconds or 300), YT_LONG_MAX_SEC))
out_path = clips_dir() / f"{job_id}.mp4"
vf = _landscape_vf()
vf = _vf_for_settings(cfg)
last_err = ""
for url in urls:
@ -143,3 +161,8 @@ async def record_landscape_clip(
last_err = str(outcome.get("error") or last_err)
return {"ok": False, "error": last_err or "录制失败"}
# Back-compat alias (name kept so older imports do not break)
async def record_landscape_clip(**kwargs: Any) -> dict[str, Any]:
return await record_long_clip(**kwargs)

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""YouTube long-form (16:9) jobs — fully isolated from shorts_* / tiktok_* / x_clip_*."""
"""YouTube long-form (9:16 default) jobs — fully isolated from shorts_* / tiktok_* / x_clip_*."""
from __future__ import annotations
import sqlite3

View File

@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
"""Isolated YouTube long-form (16:9) pipeline.
"""Isolated YouTube long-form (default 9:16) pipeline.
Companion to Shorts: when Shorts records a room, optionally enqueue a 3–8 min
landscape job. Never writes shorts_* / tiktok_* / x_clip_* tables.
Default: disabled (yt_long_enabled=false) so online Shorts is untouched until
an operator turns this on.
Records 3–8 min masters; optionally cascades cuts to TikTok / Shorts / X
via clip_cascade (each platform keeps its own tables and quotas).
Default: disabled (yt_long_enabled=false) until an operator turns this on.
"""
from __future__ import annotations
@ -18,7 +17,7 @@ from . import db
from . import yt_long_db
from .shorts_clip import resolve_stream_candidates
from .timeutil import push_date_from_ts
from .yt_long_clip import record_landscape_clip
from .yt_long_clip import record_long_clip
from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC
from .yt_long_upload import upload_youtube_long_mp4
@ -335,6 +334,7 @@ class YtLongPipeline:
self.sampled = 0
self.last_error = ""
self._last_sample_at = 0.0
self._last_retention_at = 0.0
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
@ -347,6 +347,13 @@ class YtLongPipeline:
board = yt_long_db.channel_board(day)
except Exception:
board = {"channels": [], "total_gap": 0, "push_date": day}
cascade_need: dict[str, Any] = {}
try:
from .clip_cascade import estimate_platform_daily_need
cascade_need = estimate_platform_daily_need(cfg)
except Exception:
cascade_need = {}
return {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
@ -360,6 +367,7 @@ class YtLongPipeline:
"last_error": self.last_error,
"stats": yt_long_db.yt_long_stats(day),
"board": board,
"cascade_need": cascade_need,
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"settings": {
"yt_long_enabled": bool(cfg.get("yt_long_enabled")),
@ -376,9 +384,12 @@ class YtLongPipeline:
"yt_long_title_template": str(cfg.get("yt_long_title_template") or ""),
"yt_long_description_template": str(cfg.get("yt_long_description_template") or ""),
"yt_long_delete_clip_after_upload": bool(
cfg.get("yt_long_delete_clip_after_upload", True)
cfg.get("yt_long_delete_clip_after_upload", False)
),
"yt_long_upload_min_gap_sec": int(cfg.get("yt_long_upload_min_gap_sec") or 900),
"yt_long_landscape_16x9": bool(cfg.get("yt_long_landscape_16x9", False)),
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
"clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 48),
},
}
@ -446,6 +457,15 @@ class YtLongPipeline:
except Exception:
pass
if (time.time() - self._last_retention_at) >= 600:
self._last_retention_at = time.time()
try:
from .clip_retention import purge_stale_clips
purge_stale_clips(cfg)
except Exception:
pass
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")
# If in-flight + done already fills daily_max, soft-skip leftover pending
@ -525,7 +545,7 @@ class YtLongPipeline:
)
return
sec = _rand_clip_sec(cfg)
outcome = await record_landscape_clip(job_id=jid, stream_urls=candidates, seconds=sec)
outcome = await record_long_clip(job_id=jid, stream_urls=candidates, seconds=sec, cfg=cfg)
if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败")[:500]
yt_long_db.update_yt_long_job(
@ -549,6 +569,13 @@ class YtLongPipeline:
stream_url=str(outcome.get("stream_url") or ""),
error="",
)
fresh = yt_long_db.get_yt_long_job(jid) or {**job, "clip_path": clip_path, "clip_seconds": sec}
try:
from .clip_cascade import cascade_from_yt_long
await cascade_from_yt_long(fresh, cfg)
except Exception:
pass
return
yt_long_db.update_yt_long_job(
jid,
@ -559,6 +586,17 @@ class YtLongPipeline:
upload_at=upload_at,
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:
from .clip_cascade import cascade_from_yt_long
await cascade_from_yt_long(fresh, cfg)
except Exception:
pass
async def _run_upload(self, job: dict[str, Any]) -> None:
try:
@ -648,7 +686,7 @@ class YtLongPipeline:
description=description,
error="",
finished_at=time.time(),
clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip,
clip_path="" if cfg.get("yt_long_delete_clip_after_upload", False) else clip,
)
_emit(
"yt_long_ok",
@ -657,7 +695,7 @@ class YtLongPipeline:
fresh,
{"youtube_url": url, "video_id": vid},
)
if cfg.get("yt_long_delete_clip_after_upload", True):
if cfg.get("yt_long_delete_clip_after_upload", False):
try:
Path(clip).unlink(missing_ok=True)
except Exception:

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""YouTube long-form (16:9) upload — same OAuth transport as Shorts, watch URL not /shorts/."""
"""YouTube long-form upload — same OAuth transport as Shorts, watch URL not /shorts/."""
from __future__ import annotations
from pathlib import Path
@ -41,7 +41,7 @@ async def upload_youtube_long_mp4(
except FileNotFoundError as exc:
raise ValueError("成片文件不存在") from exc
# No #Shorts — this is a normal YouTube video (16:9).
# No #Shorts — this is a normal YouTube watch video (9:16 vertical by default).
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()[:100]
meta = {
"snippet": {

View File

@ -383,7 +383,7 @@ export default function YtLongPage() {
<p className="font-display text-xs uppercase tracking-[0.28em] text-amber-300/80">Long Video Pipeline</p>
<h2 className="font-display text-3xl font-semibold tracking-tight">📺 长视频分发台</h2>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
在播放样 → 16:9 成片 → 上传为普通 YouTube 视频(watch?v=)。频道 OAuth 可从 Shorts 同步,数据与 Shorts 隔离。
在播放样 → 9:16 成片(3–8 分钟)→ 上传为普通 YouTube 视频(watch?v=)。成片可 cascade 切 TikTok / Shorts / X。频道 OAuth 可从 Shorts 同步,业务数据隔离。
</p>
</div>
<div className="flex flex-wrap gap-2">
@ -417,7 +417,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)}分`,
"16:9 横屏 · 非 Shorts",
"9:16 竖屏长视频 · 非 Shorts",
],
].map(([label, value, hint]) => (
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">