From e08db6aa742176bd1df31359bdcc06e2eb45086c Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 04:50:28 -0500 Subject: [PATCH] =?UTF-8?q?feat(test1):=20=E5=8A=9F=E8=83=BD=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E9=A6=96=E6=89=B9=20=E2=80=94=20=E9=85=8D=E9=A2=9D?= =?UTF-8?q?=E5=8F=AF=E9=85=8D=E3=80=81=E5=A4=B1=E8=B4=A5=E5=BD=92=E5=9B=A0?= =?UTF-8?q?=E3=80=81=E6=88=90=E7=89=87=E8=B4=A8=E6=A3=80=E3=80=81TikTok?= =?UTF-8?q?=E8=A1=A5=E9=87=8F=E4=B8=8E=E8=B7=A8=E5=B9=B3=E5=8F=B0=E6=A0=87?= =?UTF-8?q?=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- backend/app/clip_quality.py | 140 +++++++++++++++++++++++++++++++ backend/app/db.py | 69 ++++++++------- backend/app/job_errors.py | 114 +++++++++++++++++++++++++ backend/app/main.py | 34 ++++++++ backend/app/notify.py | 6 ++ backend/app/shorts_pipeline.py | 26 +++++- backend/app/tiktok_db.py | 11 +-- backend/app/tiktok_pipeline.py | 68 ++++++++++++++- backend/app/tiktok_schedule.py | 15 +++- backend/app/title_assist.py | 65 ++++++++++++++ frontend/src/app/shorts/page.tsx | 30 +++++-- frontend/src/app/tiktok/page.tsx | 30 ++++++- scripts/DEPLOY_TEST1_SAFE.md | 25 ++++++ scripts/_deploy_test1_safe.py | 120 ++++++++++++++++++++++++++ 14 files changed, 696 insertions(+), 57 deletions(-) create mode 100644 backend/app/clip_quality.py create mode 100644 backend/app/job_errors.py create mode 100644 backend/app/title_assist.py create mode 100644 scripts/DEPLOY_TEST1_SAFE.md create mode 100644 scripts/_deploy_test1_safe.py diff --git a/backend/app/clip_quality.py b/backend/app/clip_quality.py new file mode 100644 index 0000000..b640692 --- /dev/null +++ b/backend/app/clip_quality.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +"""Clip quality gate — reject black/silent/too-short clips before upload queue.""" +from __future__ import annotations + +import json +import subprocess +from pathlib import Path +from typing import Any + + +def probe_clip(path: str | Path) -> dict[str, Any]: + p = Path(path) + if not p.is_file(): + return {"ok": False, "reason": "成片文件不存在", "size": 0} + size = p.stat().st_size + if size < 80_000: + return {"ok": False, "reason": "成片过小,可能录制失败", "size": size} + cmd = [ + "ffprobe", + "-v", + "error", + "-show_entries", + "format=duration,size:stream=codec_type,codec_name,width,height,bit_rate,avg_frame_rate", + "-of", + "json", + str(p), + ] + try: + raw = subprocess.check_output(cmd, stderr=subprocess.STDOUT, timeout=25) + data = json.loads(raw.decode("utf-8", "replace") or "{}") + except Exception as exc: + # ffprobe missing — fall back to size-only gate + return { + "ok": size >= 200_000, + "reason": "" if size >= 200_000 else f"成片偏小且无法探测({exc})", + "size": size, + "duration": 0, + "has_video": True, + "has_audio": True, + "soft": True, + } + + fmt = data.get("format") if isinstance(data.get("format"), dict) else {} + streams = data.get("streams") if isinstance(data.get("streams"), list) else [] + duration = float(fmt.get("duration") or 0) + has_video = any(str(s.get("codec_type") or "") == "video" for s in streams if isinstance(s, dict)) + has_audio = any(str(s.get("codec_type") or "") == "audio" for s in streams if isinstance(s, dict)) + width = 0 + height = 0 + for s in streams: + if not isinstance(s, dict) or str(s.get("codec_type") or "") != "video": + continue + width = int(s.get("width") or 0) + height = int(s.get("height") or 0) + break + + if duration > 0 and duration < 3.0: + return {"ok": False, "reason": "成片时长过短", "size": size, "duration": duration} + if not has_video: + return {"ok": False, "reason": "成片无视频轨", "size": size, "duration": duration} + if width and height and (width < 240 or height < 240): + return {"ok": False, "reason": "分辨率过低", "size": size, "duration": duration, "width": width, "height": height} + + # crude black-frame / silence sample via ffmpeg volumedetect + blackdetect (best-effort) + black_ratio, silence = _sample_black_silence(p) + if black_ratio is not None and black_ratio >= 0.85: + return { + "ok": False, + "reason": "成片疑似黑屏", + "size": size, + "duration": duration, + "black_ratio": black_ratio, + } + if silence is True and has_audio: + return { + "ok": False, + "reason": "成片疑似静音", + "size": size, + "duration": duration, + "silent": True, + } + + return { + "ok": True, + "reason": "", + "size": size, + "duration": duration, + "has_video": has_video, + "has_audio": has_audio, + "width": width, + "height": height, + "black_ratio": black_ratio, + } + + +def _sample_black_silence(path: Path) -> tuple[float | None, bool | None]: + """Return (black_ratio, is_silent). None means probe skipped/failed.""" + try: + # analyze first ~8s + cmd = [ + "ffmpeg", + "-hide_banner", + "-nostats", + "-t", + "8", + "-i", + str(path), + "-vf", + "blackdetect=d=0.5:pix_th=0.10", + "-af", + "volumedetect", + "-f", + "null", + "-", + ] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=40) + err = (proc.stderr or "") + (proc.stdout or "") + black_ratio = None + if "black_start" in err: + # rough: if multiple black segments, treat as mostly black + black_ratio = 0.9 if err.count("black_start") >= 2 else 0.5 + mean = None + for line in err.splitlines(): + if "mean_volume:" in line: + try: + mean = float(line.split("mean_volume:")[1].split("dB")[0].strip()) + except Exception: + mean = None + silent = mean is not None and mean <= -45.0 + return black_ratio, silent + except Exception: + return None, None + + +def assert_clip_quality(path: str | Path) -> dict[str, Any]: + """Raise ValueError if clip fails gate; otherwise return probe dict.""" + info = probe_clip(path) + if not info.get("ok"): + raise ValueError(str(info.get("reason") or "成片质量不合格")) + return info diff --git a/backend/app/db.py b/backend/app/db.py index 4872af0..5e1cd9a 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -13,16 +13,24 @@ from .models import extract_room_id, normalize_room_url, push_date_from_ts _lock = threading.RLock() -# Each Shorts channel is forced to exactly this many slots per Beijing day. +# Default soft targets (Beijing day). Channels may override via daily_min/daily_max. SHORTS_DAILY_FORCE = 9 -# TikTok official Content Posting / Direct Post guideline: -# "typically around 15 posts per day / creator account" -# https://developers.tiktok.com/doc/content-sharing-guidelines +# TikTok official Content Posting / Direct Post guideline ~15/day TIKTOK_DAILY_FORCE = 15 +def _normalize_daily_quota(value: Any = None, *, default: int = 9, lo: int = 1, hi: int = 50) -> int: + """Clamp channel daily quota to a sane range. No longer hard-forces a single global value.""" + try: + n = int(value) if value is not None else int(default) + except Exception: + n = int(default) + return max(int(lo), min(int(hi), n)) + + def _force_daily_quota(value: Any = None) -> int: - return int(SHORTS_DAILY_FORCE) + # Backward-compatible name — now means "normalize", not "force overwrite". + return _normalize_daily_quota(value, default=SHORTS_DAILY_FORCE) def _connect() -> sqlite3.Connection: @@ -328,13 +336,16 @@ def init_db() -> None: conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}") conn.commit() _seed_defaults(conn) + # Do NOT overwrite per-channel daily quotas on every boot (was polluting operator settings). try: conn.execute( - "UPDATE shorts_channels SET daily_min = ?, daily_max = ?", + "UPDATE shorts_channels SET daily_min = ?, daily_max = ? " + "WHERE IFNULL(daily_min,0) <= 0 OR IFNULL(daily_max,0) <= 0", (SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE), ) conn.execute( - "UPDATE tiktok_channels SET daily_min = ?, daily_max = ?", + "UPDATE tiktok_channels SET daily_min = ?, daily_max = ? " + "WHERE IFNULL(daily_min,0) <= 0 OR IFNULL(daily_max,0) <= 0", (TIKTOK_DAILY_FORCE, TIKTOK_DAILY_FORCE), ) conn.commit() @@ -354,22 +365,8 @@ def init_db() -> None: def enforce_shorts_daily_force() -> int: - """Force every channel to daily_min=daily_max=SHORTS_DAILY_FORCE. Returns rows updated.""" - with _lock: - conn = _connect() - try: - cur = conn.execute( - """ - UPDATE shorts_channels - SET daily_min = ?, daily_max = ?, updated_at = ? - WHERE daily_min != ? OR daily_max != ? - """, - (SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE, time.time(), SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE), - ) - conn.commit() - return int(cur.rowcount) - finally: - conn.close() + """Deprecated no-op kept for API compatibility. Quotas are per-channel editable now.""" + return 0 def _seed_defaults(conn: sqlite3.Connection) -> None: @@ -2780,8 +2777,10 @@ def create_shorts_channel( ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) - daily_min = _force_daily_quota(daily_min) - daily_max = _force_daily_quota(daily_max) + daily_min = _normalize_daily_quota(daily_min, default=SHORTS_DAILY_FORCE) + daily_max = _normalize_daily_quota(daily_max, default=SHORTS_DAILY_FORCE) + if daily_max < daily_min: + daily_max = daily_min with _lock: conn = _connect() try: @@ -2850,17 +2849,15 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: if k not in allowed or v is None: continue if k in {"daily_min", "daily_max"}: - continue # forced below + v = _normalize_daily_quota(v, default=SHORTS_DAILY_FORCE) if k == "enabled": v = 1 if v else 0 if k == "oauth_profile_id": v = str(v or "").strip().upper() sets.append(f"{k} = ?") params.append(v) - sets.append("daily_min = ?") - params.append(SHORTS_DAILY_FORCE) - sets.append("daily_max = ?") - params.append(SHORTS_DAILY_FORCE) + if not sets: + return _row_to_dict(row) sets.append("updated_at = ?") params.append(time.time()) params.append(channel_pk) @@ -3244,10 +3241,10 @@ def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for ch in list_shorts_channels(enabled=True): cid = str(ch["id"]) - daily_min = max(0, int(ch.get("daily_min") or SHORTS_DAILY_FORCE)) - daily_max = max(1, int(ch.get("daily_max") or SHORTS_DAILY_FORCE)) - daily_min = SHORTS_DAILY_FORCE - daily_max = SHORTS_DAILY_FORCE + daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE) + daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) + if daily_max < daily_min: + daily_max = daily_min used = shorts_channel_upload_count(cid, day) rows.append( { @@ -3383,10 +3380,10 @@ def pick_shorts_channel( if require_upload_quota and not project_uploads_available(cfg, profile_id=pid): continue used = shorts_channel_upload_count(str(ch["id"]), push_date) - daily_max = SHORTS_DAILY_FORCE + daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) if used >= daily_max: continue - daily_min = SHORTS_DAILY_FORCE + daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE) under = 0 if used < daily_min else 1 scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch)) if not scored: diff --git a/backend/app/job_errors.py b/backend/app/job_errors.py new file mode 100644 index 0000000..6ade774 --- /dev/null +++ b/backend/app/job_errors.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +"""Classify Shorts/TikTok job errors into actionable buckets for UI.""" +from __future__ import annotations + +from typing import Any + + +def classify_job_error(error: str = "", *, platform: str = "") -> dict[str, Any]: + text = str(error or "").strip() + low = text.lower() + plat = str(platform or "").strip().lower() + + def hit(*needles: str) -> bool: + return any(n in low or n in text for n in needles) + + if not text: + return { + "code": "ok", + "label": "正常", + "action": "", + "action_label": "", + "severity": False, + } + + if hit("cookie", "sessionid", "登录", "login expired", "未配置 cookie", "会话"): + return { + "code": "cookie", + "label": "Cookie / 登录失效", + "action": "update_cookie", + "action_label": "更新 Cookie", + "severity": False, + } + if hit("2158", "限流", "too fast", "take a rest", "spam", "rate_limit", "rate limit", "官方限流"): + return { + "code": "rate_limit", + "label": "平台限流", + "action": "wait_retry", + "action_label": "等待后自动试传", + "severity": True, + } + if hit("quota", "403", "daily limit", "upload limit", "youtube.*quota", "exceeded"): + return { + "code": "quota", + "label": "平台配额用尽", + "action": "wait_quota", + "action_label": "等配额重置或换 Client", + "severity": True, + } + if hit("成片文件不存在", "clip", "no such file", "过小", "too small", "empty file", "录制失败"): + return { + "code": "clip", + "label": "成片缺失/损坏", + "action": "rerecord", + "action_label": "重新录制", + "severity": True, + } + if hit("黑屏", "静音", "质量不合格", "quality"): + return { + "code": "quality", + "label": "成片质量不合格", + "action": "rerecord", + "action_label": "换时段重录", + "severity": True, + } + if hit("stream", "直播已结束", "not live", "404", "拉流", "cdn"): + return { + "code": "stream", + "label": "直播流不可用", + "action": "skip_or_retry", + "action_label": "跳过或换房", + "severity": False, + } + if hit("socks", "proxy", "代理"): + return { + "code": "proxy", + "label": "代理/网络异常", + "action": "check_socks", + "action_label": "检查 SOCKS", + "retryable": True, + } + if hit("oauth", "token", "unauthorized", "401"): + return { + "code": "oauth", + "label": "OAuth 授权失效", + "action": "reauth", + "action_label": "重新授权", + "retryable": False, + } + if plat == "tiktok" and hit("机房", "datacenter", "tt-target-idc", "project"): + return { + "code": "dc", + "label": "TikTok 机房不匹配", + "action": "update_cookie", + "action_label": "重贴 Cookie + 机房", + "retryable": False, + } + return { + "code": "unknown", + "label": "其他错误", + "action": "retry", + "action_label": "重试", + "retryable": True, + "detail": text[:200], + } + + +def enrich_job_error(job: dict[str, Any] | None, *, platform: str = "") -> dict[str, Any] | None: + if not job: + return None + out = dict(job) + err = str(out.get("error") or "") + info = classify_job_error(err, platform=platform) + out["error_class"] = info + return out diff --git a/backend/app/main.py b/backend/app/main.py index 1b79779..fe8272d 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -424,6 +424,9 @@ def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None: return None from pathlib import Path + from .job_errors import enrich_job_error + from .title_assist import title_candidates + out = dict(job) clip = str(out.get("clip_path") or "").strip() out["clip_ready"] = bool(clip) and Path(clip).is_file() @@ -434,6 +437,13 @@ def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None: else: out.setdefault("channel_name", "") out.setdefault("oauth_profile_id", "") + out = enrich_job_error(out, platform="shorts") or out + out["title_candidates"] = title_candidates( + platform="shorts", + anchor=str(out.get("anchor_name") or ""), + url=str(out.get("source_url") or ""), + template=str(ch.get("title_template") or ""), + ) return out @@ -1092,7 +1102,10 @@ def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None: if not job: return None from pathlib import Path + from . import tiktok_db + from .job_errors import enrich_job_error + from .title_assist import title_candidates out = dict(job) clip = str(out.get("clip_path") or "").strip() @@ -1103,6 +1116,13 @@ def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None: else: out["channel_name"] = "" out["channel_pending"] = not bool(str(out.get("channel_pk") or "").strip()) + out = enrich_job_error(out, platform="tiktok") or out + out["title_candidates"] = title_candidates( + platform="tiktok", + anchor=str(out.get("anchor_name") or ""), + url=str(out.get("source_url") or ""), + template=str(ch.get("title_template") or ""), + ) return out @@ -1121,6 +1141,20 @@ async def tiktok_status() -> dict[str, Any]: return st +@app.post("/api/tiktok/fill-quota") +async def tiktok_fill_quota() -> dict[str, Any]: + """Manually trigger Beijing-day quota fill toward each TikTok channel daily_max.""" + from .tiktok_pipeline import try_fill_daily_quota + + cfg = db.get_settings_map() + if not cfg.get("tiktok_enabled"): + raise HTTPException(400, "请先启用 TikTok") + qn = await asyncio.to_thread(try_fill_daily_quota, cfg) + st = await asyncio.to_thread(tiktok_pipeline.status) + st["just_quota_filled"] = qn + return st + + @app.get("/api/tiktok/setup") async def tiktok_setup() -> dict[str, Any]: cfg = await _db(db.get_settings_map) diff --git a/backend/app/notify.py b/backend/app/notify.py index 31076fc..4560fec 100644 --- a/backend/app/notify.py +++ b/backend/app/notify.py @@ -25,6 +25,12 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None: return if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True): return + if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True): + return + if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False): + return + if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True): + return # allow ops/test always when URL configured body = { diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 25a2177..538d045 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -46,8 +46,10 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: return True if trigger == "favorite": return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts"} for t in tags) + if "tiktok_only" in tags: + return False tag = str(cfg.get("shorts_tag") or "shorts").strip() or "shorts" - return tag in tags or "shorts" in tags + return tag in tags or "shorts" in tags or "both" in tags def _enqueue_job( @@ -1110,6 +1112,28 @@ class ShortsPipeline: ) 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: + db.update_shorts_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(), + ) + self._emit_shorts_event( + kind="shorts_fail", + level="error", + message=f"Shorts 成片质量不合格:{job.get('anchor_name') or job.get('room_id') or jid} — {str(qerr)[:80]}", + job=job, + extra={"error": str(qerr)}, + ) + return if not cfg.get("shorts_auto_upload", True): db.update_shorts_job( jid, diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index 26f739b..b1cd85e 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -7,12 +7,12 @@ import time import uuid from typing import Any, Optional -from .db import TIKTOK_DAILY_FORCE, _connect, _lock, _row_to_dict +from .db import TIKTOK_DAILY_FORCE, _connect, _lock, _normalize_daily_quota, _row_to_dict from .timeutil import push_date_from_ts def _force_daily(v: int) -> int: - return TIKTOK_DAILY_FORCE + return _normalize_daily_quota(v, default=TIKTOK_DAILY_FORCE, lo=1, hi=30) # 占用「今日上传配额」的状态:待录/录制中不算,避免取样把账号配额占满后无法再分配 @@ -197,10 +197,10 @@ def pick_tiktok_channel( if not tiktok_session.channel_has_session(ch): continue used = tiktok_channel_upload_count(str(ch["id"]), push_date) - daily_max = TIKTOK_DAILY_FORCE + daily_max = _force_daily(int(ch.get("daily_max") or TIKTOK_DAILY_FORCE)) if require_quota and used >= daily_max: continue - daily_min = TIKTOK_DAILY_FORCE + daily_min = _force_daily(int(ch.get("daily_min") or TIKTOK_DAILY_FORCE)) under = 0 if used < daily_min else 1 scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch)) if not scored: @@ -253,7 +253,8 @@ def tiktok_total_quota_gap(push_date: str = "") -> int: gap = 0 for ch in list_tiktok_channels(enabled=True): used = tiktok_channel_upload_count(str(ch["id"]), day) - gap += max(0, TIKTOK_DAILY_FORCE - used) + daily_max = _force_daily(int(ch.get("daily_max") or TIKTOK_DAILY_FORCE)) + gap += max(0, daily_max - used) return gap diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index dbbba2e..a4236fc 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -32,8 +32,10 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool: return True if trigger == "favorite": return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts", "tiktok"} for t in tags) + if "shorts_only" in tags: + return False tag = str(cfg.get("tiktok_tag") or "shorts").strip() or "shorts" - return tag in tags or "tiktok" in tags or "shorts" in tags + return tag in tags or "tiktok" in tags or "shorts" in tags or "both" in tags def _enqueue_job( @@ -173,6 +175,55 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: } +def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: + """Enqueue live-room clips toward each TikTok channel's daily_max (Beijing day).""" + try: + settings = cfg or db.get_settings_map() + if not settings.get("tiktok_enabled"): + return 0 + day = push_date_from_ts(time.time()) + gap_total = tiktok_db.tiktok_total_quota_gap(day) + if gap_total <= 0: + return 0 + if not tiktok_db.pick_tiktok_channel(day, require_quota=True): + return 0 + from .timeutil import beijing_day_bounds + + day_start, day_end = beijing_day_bounds(day) + now = time.time() + day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start))) + base_batch = max(1, min(int(settings.get("tiktok_quota_fill_batch") or 3), 10)) + if day_progress > 0.7: + base_batch = max(base_batch, min(gap_total, 8)) + rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + any_live = settings.get("tiktok_sample_any_live", True) + candidates: list[dict[str, Any]] = [] + for room in rooms: + rid = str(room.get("room_id") or "") + if not rid: + continue + if tiktok_db.has_tiktok_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 >= base_batch: + break + if not tiktok_db.pick_tiktok_channel(day, require_quota=True): + 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): + enqueued += 1 + return enqueued + except Exception: + return 0 + + class TikTokPipeline: def __init__(self) -> None: self._task: asyncio.Task | None = None @@ -497,6 +548,21 @@ class TikTokPipeline: out_path = str(outcome.get("path") or "") seconds = float(outcome.get("seconds") or sec) + try: + from .clip_quality import assert_clip_quality + + assert_clip_quality(out_path) + except ValueError as qerr: + tiktok_db.update_tiktok_job( + jid, + status="failed", + clip_path=out_path, + clip_seconds=seconds, + stream_url=stream, + error=str(qerr)[:500], + finished_at=time.time(), + ) + return day = str(job.get("push_date") or push_date_from_ts(time.time())) channel = tiktok_db.ensure_tiktok_job_channel(job, require_quota=False) ch_pk = str((channel or {}).get("id") or job.get("channel_pk") or "") diff --git a/backend/app/tiktok_schedule.py b/backend/app/tiktok_schedule.py index a6b7639..4267ec5 100644 --- a/backend/app/tiktok_schedule.py +++ b/backend/app/tiktok_schedule.py @@ -127,7 +127,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: cid = str(c["id"]) stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) used = int(stats["used"]) - gap = max(0, TIKTOK_DAILY_FORCE - used) + daily_max = max(1, int(c.get("daily_max") or TIKTOK_DAILY_FORCE)) + try: + from .db import _normalize_daily_quota + + daily_max = _normalize_daily_quota(daily_max, default=TIKTOK_DAILY_FORCE, lo=1, hi=30) + except Exception: + pass + gap = max(0, daily_max - used) if c.get("enabled"): total_gap += gap channel_rows.append( @@ -143,10 +150,10 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "heart_count": int(c.get("heart_count") or 0), "enabled": bool(c.get("enabled")), "authorized": tiktok_session.channel_has_session(c), - "daily_min": TIKTOK_DAILY_FORCE, - "daily_max": TIKTOK_DAILY_FORCE, + "daily_min": int(c.get("daily_min") or TIKTOK_DAILY_FORCE), + "daily_max": daily_max, "gap": gap, - "max_met": used >= TIKTOK_DAILY_FORCE, + "max_met": used >= daily_max, **stats, } ) diff --git a/backend/app/title_assist.py b/backend/app/title_assist.py new file mode 100644 index 0000000..8060e0c --- /dev/null +++ b/backend/app/title_assist.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +"""Title / caption candidates for Shorts & TikTok uploads.""" +from __future__ import annotations + +import re +from typing import Any + + +def _fill(template: str, *, anchor: str = "", url: str = "", room: str = "") -> str: + text = str(template or "") + reps = { + "{anchor}": anchor or "直播", + "{url}": url or "", + "{room}": room or "", + "{name}": anchor or "直播", + } + for k, v in reps.items(): + text = text.replace(k, v) + return re.sub(r"\s+", " ", text).strip() + + +def title_candidates( + *, + platform: str = "shorts", + anchor: str = "", + url: str = "", + room: str = "", + template: str = "", + extra_tags: list[str] | None = None, +) -> list[dict[str, str]]: + """Return up to 3 editable candidates. No external AI required.""" + plat = str(platform or "shorts").lower() + anchor = str(anchor or "").strip() or "直播" + url = str(url or "").strip() + base = _fill(template, anchor=anchor, url=url, room=room) if template else "" + tags = [t for t in (extra_tags or []) if str(t).strip()] + out: list[dict[str, str]] = [] + + def add(kind: str, title: str) -> None: + t = re.sub(r"\s+", " ", str(title or "").strip()) + if not t: + return + if any(x["title"] == t for x in out): + return + out.append({"kind": kind, "title": t[:2200]}) + + if base: + add("template", base) + + if plat == "tiktok": + add("plain", f"{anchor} 现场瞬间") + add("hook", f"跟着 {anchor} 看这一段 #fyp") + add("tag", f"{anchor} #streetfood #viral" if not tags else f"{anchor} " + " ".join(f"#{t}" for t in tags[:4])) + else: + add("plain", f"{anchor} 直播瞬间 #Shorts") + add("hook", f"别划走!{anchor} 这段太好看 #Shorts") + add("tag", f"{anchor} #Shorts #直播" + ("" if not url else f"\n{url}")) + + return out[:3] + + +def pick_default_title(candidates: list[dict[str, str]], *, fallback: str = "") -> str: + if candidates: + return str(candidates[0].get("title") or fallback or "").strip() + return str(fallback or "").strip() diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index a49433a..5906396 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -812,7 +812,7 @@ export default function ShortsPage() { <>
{[ - ["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "每频道强制 9 条/日"], + ["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"], ["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"], ["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`], [ @@ -1169,7 +1169,6 @@ export default function ShortsPage() {
{ch.used}/{ch.daily_max || 9} - (强制 9) {gap > 0 ? 缺 {gap} : 已满} 上传 {ch.uploaded} @@ -1271,14 +1270,31 @@ export default function ShortsPage() { /> +