douyinWEB/backend/app/x_clips_pipeline.py
eric 0c3fc9f68e fix(test1): X立即取样提示区分「今日已取样」与真无候选
当前在播房同日去重后返回 all_deduped,不再误报 no_candidates。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 08:37:31 -05:00

635 lines
24 KiB
Python

# -*- coding: utf-8 -*-
"""Isolated X live-clip pipeline — sample → record → S3 → extension engage.post.
Never touches Shorts / TikTok uploaders or Douyin monitor control flow.
Shares only side-effect-free tools: record_clip, resolve_stream_candidates, S3 helpers.
"""
from __future__ import annotations
import asyncio
import random
import time
from pathlib import Path
from typing import Any, Optional
from . import db
from . import x2_db
from . import x2_media
from . import x_clips_db
from .shorts_clip import record_clip, resolve_stream_candidates
from .timeutil import push_date_from_ts
from .x_clips_schedule import pick_upload_at, schedule_board
def _room_tags(room: dict[str, Any]) -> list[str]:
tags = room.get("tags") or []
if isinstance(tags, str):
return [t.strip() for t in tags.split(",") if t.strip()]
return [str(t).strip() for t in tags if str(t).strip()]
def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
trigger = str(cfg.get("x_clips_trigger") or "tagged").strip().lower()
tags = _room_tags(room)
if "shorts_only" in tags or "tiktok_only" in tags:
return False
if trigger == "all":
return True
if trigger == "favorite":
return any(t in {"收藏", "重点", "priority", "vip", "高优", "x", "shorts"} for t in tags)
tag = str(cfg.get("x_clips_tag") or "x").strip() or "x"
return tag in tags or "x" in tags or "both" in tags or "x_only" in tags
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)
except Exception:
base = 12
base = max(10, min(15, 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))
except Exception:
pass
return base
def build_caption(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> str:
"""Render caption strictly from settings template — never invent live-room copy."""
settings = cfg or db.get_settings_map()
tpl = str(settings.get("x_clips_caption_template") or "").strip()
if not tpl:
tpl = "{anchor}"
anchor = str(job.get("anchor_name") or "").strip() or "Live"
room = str(job.get("room_id") or "").strip()
text = (
tpl.replace("{anchor}", anchor)
.replace("{room}", room)
.replace("{title}", anchor)
).strip()
# X hard limit ~280; leave headroom for media
return (text or anchor)[:270]
def _enqueue_job(
*,
session: dict[str, Any] | None,
room: dict[str, Any],
stream_url: str = "",
cfg: dict[str, Any] | None = None,
push_date: str = "",
) -> Optional[dict[str, Any]]:
try:
settings = cfg or db.get_settings_map()
if not settings.get("x_clips_enabled"):
return None
if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0:
return None
room_id = str(room.get("room_id") or (session or {}).get("room_id") or "")
if room_id.startswith("yt:"):
return None
day = str(push_date or "").strip() or push_date_from_ts(time.time())
if settings.get("x_clips_dedupe_room_day", True) and room_id:
if x_clips_db.has_x_clip_job_for_room_day(room_id, day):
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
acct = str(settings.get("x_clips_account_username") or "").strip().lstrip("@")
job = x_clips_db.create_x_clip_job(
session_id=sid,
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
room_id=room_id,
source_url=str((session or {}).get("source_url") or room.get("url") or ""),
anchor_name=str(
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
),
stream_url=str(stream_url or ""),
push_date=day,
account_username=acct,
)
if not job:
return None
try:
db.add_event(
kind="ops",
level="info",
message=f"X 切片任务已入队:{job.get('anchor_name') or room_id}",
room_id=room_id,
room_pk=str(room.get("id") or ""),
session_id=sid,
anchor_name=str(job.get("anchor_name") or ""),
meta={"x_clip_job_id": job.get("id")},
)
except Exception:
pass
return job
except Exception:
return None
def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
"""Pick live Douyin rooms and enqueue X clip jobs. Never raises."""
try:
settings = cfg or db.get_settings_map()
if not settings.get("x_clips_enabled"):
return 0
if not settings.get("x_clips_live_sample", True):
return 0
if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0:
return 0
batch = max(1, min(5, int(settings.get("x_clips_live_sample_batch") or 1)))
any_live = bool(settings.get("x_clips_sample_any_live", True))
day = push_date_from_ts(time.time())
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
candidates: list[dict[str, Any]] = []
for room in rooms:
rid = str(room.get("room_id") or "")
if not rid:
continue
if settings.get("x_clips_dedupe_room_day", True) and x_clips_db.has_x_clip_job_for_room_day(rid, day):
continue
if any_live or _room_eligible(room, settings):
candidates.append(room)
if not candidates:
return 0
random.shuffle(candidates)
enqueued = 0
for room in candidates:
if enqueued >= batch:
break
if x_clips_db.x_clips_quota_gap(cfg=settings) <= 0:
break
sid = str(room.get("active_session_id") or "")
session = db.get_session(sid) if sid else None
if _enqueue_job(session=session, room=room, cfg=settings, push_date=day):
enqueued += 1
return enqueued
except Exception:
return 0
def sample_live_now() -> dict[str, Any]:
"""Manual sample entry — returns summary for API."""
settings = db.get_settings_map()
if not settings.get("x_clips_enabled"):
return {"enqueued": 0, "live_count": 0, "skipped_dedupe": 0, "job_ids": [], "reason": "x_clips_disabled"}
# Manual sample must run even if periodic live_sample switch is off
patched = {**settings, "x_clips_live_sample": True}
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
day = push_date_from_ts(time.time())
skipped = 0
eligible = 0
any_live = bool(patched.get("x_clips_sample_any_live", True))
for room in rooms:
rid = str(room.get("room_id") or "")
if not rid:
continue
if patched.get("x_clips_dedupe_room_day", True) and x_clips_db.has_x_clip_job_for_room_day(rid, day):
skipped += 1
continue
if any_live or _room_eligible(room, patched):
eligible += 1
n = try_sample_live_rooms(patched)
jobs = x_clips_db.list_pending_x_clip_jobs(limit=20)
reason = ""
if n:
reason = ""
elif x_clips_db.x_clips_quota_gap(cfg=patched) <= 0:
reason = "no_quota"
elif skipped and skipped >= len(rooms) and len(rooms) > 0:
reason = "all_deduped"
elif eligible <= 0:
reason = "no_candidates"
else:
reason = "enqueue_failed"
return {
"enqueued": n,
"live_count": len(rooms),
"skipped_dedupe": skipped,
"eligible": eligible,
"job_ids": [str(j.get("id")) for j in jobs],
"reason": reason,
}
def try_fill_daily_quota() -> dict[str, Any]:
settings = db.get_settings_map()
if not settings.get("x_clips_enabled"):
return {"enqueued": 0, "gap": 0, "reason": "disabled"}
gap = x_clips_db.x_clips_quota_gap(cfg=settings)
if gap <= 0:
return {"enqueued": 0, "gap": 0, "reason": "quota_full"}
# Temporarily bump batch to fill gap (capped)
patched = {**settings, "x_clips_live_sample_batch": min(gap, 5), "x_clips_live_sample": True}
total = 0
rounds = 0
while total < gap and rounds < 8:
rounds += 1
n = try_sample_live_rooms(patched)
if n <= 0:
break
total += n
patched = {**patched, "x_clips_live_sample_batch": min(gap - total, 5)}
return {"enqueued": total, "gap": gap, "reason": ""}
class XClipsPipeline:
def __init__(self) -> None:
self._task: asyncio.Task | None = None
self._stop = asyncio.Event()
self._active_records = 0
self._active_posts = 0
self.processed = 0
self.sampled = 0
self.last_error = ""
self._last_sample_at = 0.0
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
try:
board = schedule_board(limit=30)
except Exception:
board = {}
day = push_date_from_ts(time.time())
return {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_posts > 0,
"enabled": bool(cfg.get("x_clips_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"quota_gap": x_clips_db.x_clips_quota_gap(day, cfg),
"quota_used": x_clips_db.x_clips_quota_used(day),
"daily_max": x_clips_db.x_clips_daily_max(cfg),
"last_error": self.last_error,
"clip_sec": _clip_sec(cfg),
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"board": board,
"stats": x_clips_db.x_clips_stats(day),
"settings": {
"x_clips_enabled": bool(cfg.get("x_clips_enabled")),
"x_clips_clip_sec": _clip_sec(cfg),
"x_clips_trigger": cfg.get("x_clips_trigger") or "tagged",
"x_clips_tag": cfg.get("x_clips_tag") or "x",
"x_clips_daily_max": x_clips_db.x_clips_daily_max(cfg),
"x_clips_caption_template": cfg.get("x_clips_caption_template") or "{anchor}",
"x_clips_account_username": str(cfg.get("x_clips_account_username") or "").strip().lstrip("@"),
"x_clips_live_sample": bool(cfg.get("x_clips_live_sample", True)),
"x_clips_live_sample_interval_sec": int(cfg.get("x_clips_live_sample_interval_sec") or 180),
"x_clips_live_sample_batch": int(cfg.get("x_clips_live_sample_batch") or 1),
"x_clips_sample_any_live": bool(cfg.get("x_clips_sample_any_live", True)),
"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)),
},
}
async def start(self) -> None:
if self._task and not self._task.done():
return
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="x-clips-pipeline")
async def stop(self) -> None:
self._stop.set()
if self._task:
try:
await asyncio.wait_for(self._task, timeout=5)
except Exception:
self._task.cancel()
self._task = None
async def kick_pending_records(self, job_ids: list[str]) -> int:
ids = [str(j) for j in job_ids if str(j).strip()]
if not ids:
return 0
cfg = db.get_settings_map()
max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1))
async def _drain() -> None:
leftover = list(ids)
while leftover:
while self._active_records >= max_rec:
await asyncio.sleep(0.25)
jid = leftover.pop(0)
job = x_clips_db.claim_x_clip_job_record(jid)
if not job:
continue
self._active_records += 1
asyncio.create_task(self._run_record(job))
asyncio.create_task(_drain())
return min(len(ids), max_rec)
async def post_job_now(self, job_id: str) -> dict[str, Any]:
job = x_clips_db.claim_x_clip_job_manual_post(job_id)
if not job:
raise ValueError("任务不可立即发帖(需要成片且未发布)")
try:
await self._do_post(job, manual=True)
except Exception as exc:
x_clips_db.update_x_clip_job(
job_id,
status="failed",
error=str(exc)[:500],
finished_at=time.time(),
)
raise
fresh = x_clips_db.get_x_clip_job(job_id)
if not fresh:
raise ValueError("任务不存在")
if str(fresh.get("status") or "") not in {"posted", "posting"}:
raise ValueError(str(fresh.get("error") or "发帖未完成"))
return fresh
async def _loop(self) -> None:
while not self._stop.is_set():
try:
cfg = db.get_settings_map()
if not cfg.get("x_clips_enabled"):
await asyncio.sleep(5)
continue
interval = max(60.0, float(cfg.get("x_clips_live_sample_interval_sec") or 180))
if cfg.get("x_clips_live_sample", True) and (time.time() - self._last_sample_at) >= interval:
self._last_sample_at = time.time()
n = try_sample_live_rooms(cfg)
if n:
self.sampled += n
try:
x_clips_db.reclaim_stale_x_clip_recordings(max_age_sec=240)
except Exception:
pass
try:
x_clips_db.reclaim_stale_x_clip_posts(max_age_sec=900)
except Exception:
pass
# Sync extension job outcomes
try:
await asyncio.to_thread(self._sync_posting_jobs)
except Exception as exc:
self.last_error = str(exc)[:240]
max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1))
while self._active_records < max_rec:
pending = x_clips_db.list_pending_x_clip_jobs(limit=1)
if not pending:
break
job = x_clips_db.claim_x_clip_job_record(str(pending[0].get("id") or ""))
if not job:
break
self._active_records += 1
asyncio.create_task(self._run_record(job))
if cfg.get("x_clips_auto_post", True):
max_post = max(1, int(cfg.get("x_clips_max_concurrent") or 1))
while self._active_posts < max_post:
job = x_clips_db.claim_due_x_clip_post()
if not job:
break
self._active_posts += 1
asyncio.create_task(self._run_post(job))
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(2.5)
async def _run_record(self, job: dict[str, Any]) -> None:
try:
await self._do_record(job)
except Exception as exc:
self.last_error = str(exc)[:240]
x_clips_db.update_x_clip_job(
str(job.get("id") or ""),
status="failed",
error=str(exc)[:500],
finished_at=time.time(),
)
finally:
self._active_records = max(0, self._active_records - 1)
async def _do_record(self, job: dict[str, Any]) -> None:
cfg = db.get_settings_map()
jid = str(job.get("id") or "")
cookie = str(cfg.get("dy_cookie") or "")
source = str(job.get("source_url") or "")
candidates = await resolve_stream_candidates(
source_url=source,
stream_url=str(job.get("stream_url") or ""),
cookie=cookie,
prefer_fresh=True,
max_candidates=8,
)
if not candidates:
err = str(job.get("error") or "")
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
x_clips_db.update_x_clip_job(
jid,
status="pending",
error="stream_retry:1",
stream_url="",
started_at=0,
)
return
x_clips_db.update_x_clip_job(
jid,
status="failed",
error="无法获取直播流(可能已停播)",
finished_at=time.time(),
)
return
room_pk = str(job.get("room_pk") or "")
room = db.get_room(room_pk) if room_pk else None
sec = _clip_sec(cfg, room)
outcome = await record_clip(
job_id=f"xclip_{jid[:8]}",
stream_urls=candidates,
seconds=sec,
)
stream = str(outcome.get("stream_url") or (candidates[0] if candidates else ""))
if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败")
x_clips_db.update_x_clip_job(
jid,
status="failed",
error=err[:500],
stream_url=stream,
finished_at=time.time(),
)
return
clip_path = str(outcome.get("path") or "")
try:
from .clip_quality import assert_clip_quality
assert_clip_quality(clip_path)
except ValueError as qerr:
x_clips_db.update_x_clip_job(
jid,
status="failed",
clip_path=clip_path,
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
error=str(qerr)[:500],
finished_at=time.time(),
)
return
except Exception:
pass
caption = build_caption({**job, "id": jid}, cfg)
day = str(job.get("push_date") or "") or push_date_from_ts(time.time())
upload_at = pick_upload_at(push_date=day, cfg=cfg)
x_clips_db.update_x_clip_job(
jid,
status="scheduled",
clip_path=clip_path,
clip_seconds=float(outcome.get("seconds") or sec),
stream_url=stream,
caption=caption,
upload_at=upload_at,
error="",
)
self.processed += 1
async def _run_post(self, job: dict[str, Any]) -> None:
try:
await self._do_post(job, manual=False)
except Exception as exc:
self.last_error = str(exc)[:240]
x_clips_db.update_x_clip_job(
str(job.get("id") or ""),
status="failed",
error=str(exc)[:500],
finished_at=time.time(),
)
finally:
self._active_posts = max(0, self._active_posts - 1)
async def _do_post(self, job: dict[str, Any], *, manual: bool = False) -> None:
jid = str(job.get("id") or "")
cfg = db.get_settings_map()
# Always re-render from current template at post time (ignore stale job.caption)
caption = build_caption(job, cfg)
if not caption:
raise ValueError("文案模板结果为空")
acct = (
str(job.get("account_username") or "").strip().lstrip("@")
or str(cfg.get("x_clips_account_username") or "").strip().lstrip("@")
)
if acct and str(job.get("account_username") or "").strip().lstrip("@") != acct:
x_clips_db.update_x_clip_job(jid, account_username=acct)
media_url = str(job.get("media_url") or "").strip()
media_key = str(job.get("media_key") or "").strip()
clip = str(job.get("clip_path") or "").strip()
# Prefer re-stage from local clip so retries survive prior S3 cleanup / 404.
if clip and Path(clip).is_file():
staged = await asyncio.to_thread(x2_media.upload_media_file, Path(clip), filename=Path(clip).name)
media_url = str(staged.get("url") or "")
media_key = str(staged.get("key") or "")
if not media_url or not media_key:
raise ValueError("S3 暂存失败")
x_clips_db.update_x_clip_job(jid, media_url=media_url, media_key=media_key, caption=caption)
elif not media_url or not media_key:
raise ValueError("成片文件不存在且无可用媒体 URL")
# Already dispatched?
existing_x2 = str(job.get("x2_job_id") or "").strip()
if existing_x2 and not manual:
return
media_item = {
"url": media_url,
"key": media_key,
"mime": "video/mp4",
"name": Path(clip).name if clip else "clip.mp4",
"size": Path(clip).stat().st_size if clip and Path(clip).is_file() else 0,
}
x2_job = await asyncio.to_thread(
x2_db.create_web_job,
"engage.post",
{
"text": caption,
"mediaUrls": [media_item],
"xClipJobId": jid,
**({"username": acct} if acct else {}),
},
)
x2_id = str(x2_job.get("id") or "")
if not x2_id:
raise ValueError("创建插件发帖任务失败")
x_clips_db.update_x_clip_job(
jid,
status="posting",
caption=caption,
media_url=media_url,
media_key=media_key,
x2_job_id=x2_id,
error="",
)
# Best-effort push to connected extension (poll fallback remains)
try:
from .x2_ws import hub
asyncio.create_task(hub.dispatch_queued())
except Exception:
pass
def _sync_posting_jobs(self) -> None:
cfg = db.get_settings_map()
for job in x_clips_db.list_posting_x_clip_jobs(limit=40):
jid = str(job.get("id") or "")
x2_id = str(job.get("x2_job_id") or "").strip()
if not jid or not x2_id:
continue
row = x2_db.get_job(x2_id)
if not row:
continue
st = str(row.get("status") or "")
if st == "completed":
tweet_id = ""
result = row.get("result") if isinstance(row.get("result"), dict) else {}
if not result:
try:
import json
result = json.loads(str(row.get("result_json") or "{}"))
except Exception:
result = {}
if isinstance(result, dict):
tweet_id = str(
result.get("tweetId")
or result.get("tweet_id")
or result.get("id")
or ""
).strip()
x_clips_db.update_x_clip_job(
jid,
status="posted",
tweet_id=tweet_id,
error="",
finished_at=time.time(),
)
if cfg.get("x_clips_delete_clip_after_post", True):
self._delete_clip(str(job.get("clip_path") or ""))
elif st in {"failed", "cancelled"}:
err = str(row.get("error") or st)[:500]
x_clips_db.update_x_clip_job(
jid,
status="failed",
error=err,
finished_at=time.time(),
)
@staticmethod
def _delete_clip(path: str) -> None:
try:
Path(path).unlink(missing_ok=True)
except Exception:
pass
x_clips_pipeline = XClipsPipeline()