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>
370 lines
15 KiB
Python
370 lines
15 KiB
Python
# -*- 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
|
||
|
||
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_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)
|
||
return {
|
||
"yt_long": yt_upload,
|
||
"yt_long_upload": yt_upload,
|
||
"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]:
|
||
"""Always keep yt_long_source_daily_max ≥ max(platform quotas); never raise upload cap."""
|
||
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"])
|
||
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)))
|
||
except Exception:
|
||
hard_cap = 200
|
||
new_max = min(hard_cap, max(upload_cap, 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}
|
||
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}
|