feat(test1): 功能优化首批 — 配额可配、失败归因、成片质检、TikTok补量与跨平台标签

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 04:50:28 -05:00
parent 9fbf5ec04a
commit e08db6aa74
14 changed files with 696 additions and 57 deletions

140
backend/app/clip_quality.py Normal file
View File

@ -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

View File

@ -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:

114
backend/app/job_errors.py Normal file
View File

@ -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

View File

@ -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)

View File

@ -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 = {

View File

@ -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,

View File

@ -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

View File

@ -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 "")

View File

@ -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,
}
)

View File

@ -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()

View File

@ -812,7 +812,7 @@ export default function ShortsPage() {
<>
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
["北京日配额", `${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() {
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-slate-400">
<span>
{ch.used}/{ch.daily_max || 9}
<span className="text-slate-600">(强制 9)</span>
</span>
{gap > 0 ? <span className="text-amber-300">缺 {gap}</span> : <span className="text-teal-300">已满</span>}
<span>上传 {ch.uploaded}</span>
@ -1271,14 +1270,31 @@ export default function ShortsPage() {
/>
</label>
<label className="block text-xs text-slate-400">
每日配额
每日最少
<input
type="number"
value={9}
disabled
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900/60 px-3 py-2 text-sm text-slate-400"
min={1}
max={50}
value={Number(form.daily_min ?? 9)}
onChange={(e) =>
setForm((p) => ({ ...p, daily_min: Math.max(1, Number(e.target.value) || 9) }))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<span className="mt-1 block text-[10px] text-amber-300/80">强制每频道每天 9 条(不可改)</span>
</label>
<label className="block text-xs text-slate-400">
每日上限
<input
type="number"
min={1}
max={50}
value={Number(form.daily_max ?? 9)}
onChange={(e) =>
setForm((p) => ({ ...p, daily_max: Math.max(1, Number(e.target.value) || 9) }))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<span className="mt-1 block text-[10px] text-slate-500">按频道可改(1–50),默认 9</span>
</label>
<label className="block text-xs text-slate-400 sm:col-span-2">
标题模板

View File

@ -439,6 +439,17 @@ export default function TikTokPage() {
void load();
};
const fillQuota = async () => {
try {
const r = await fetchJson("/api/tiktok/fill-quota", { method: "POST" });
const n = Number(r.just_quota_filled || 0);
toast.push(n > 0 ? `已补入 ${n} 条待录任务` : "今日配额已满或暂无在播可补", n > 0 ? "ok" : "warn");
void load();
} catch (e: any) {
toast.push(e?.message || "补齐失败", "err");
}
};
const toUploadTarget = (u: {
id: string;
anchor_name?: string;
@ -615,6 +626,13 @@ export default function TikTokPage() {
>
立即取样
</button>
<button
type="button"
onClick={() => void fillQuota()}
className="rounded-xl border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-200 hover:bg-teal-500/20"
>
补齐配额
</button>
<button
type="button"
onClick={() => void togglePipeline()}
@ -1078,7 +1096,7 @@ export default function TikTokPage() {
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-medium text-slate-100">账号配额({channels.length})</h3>
<span className="text-[11px] text-slate-500">
北京日 {beijingWindow || "—"} · 软目标 15 条/日(官方约数);仅撞官方限流时提示
北京日 {beijingWindow || "—"} · 按账号日上限合计(默认可改)
</span>
</div>
<div className="grid gap-3 sm:grid-cols-2">
@ -1312,8 +1330,14 @@ export default function TikTokPage() {
{statusLabel[j.status as keyof typeof statusLabel] || j.status}
</span>
{j.error && (
<div className="max-w-xs truncate text-[10px] text-rose-400/80" title={j.error}>
{j.error}
<div className="max-w-xs text-[10px] text-rose-400/80" title={j.error}>
<div className="font-medium text-rose-300">
{(j as any).error_class?.label || "失败"}
{(j as any).error_class?.action_label
? ` · ${(j as any).error_class.action_label}`
: ""}
</div>
<div className="truncate">{j.error}</div>
</div>
)}
</td>

View File

@ -0,0 +1,25 @@
# test1 分支部署数据安全红线
## 原则
服务器上的业务数据是唯一真实来源。`test1` 只允许更新**代码**,禁止用本机或 git 覆盖数据。
## 禁止覆盖
- `backend/data/monitor.db`(及 `-shm` / `-wal`)
- `backend/data/covers/`
- `backend/data/clips/`
- `backend/data/tiktok_cookies/`
- `pb_data/`
## 正确部署
```bash
python scripts/_deploy_test1_safe.py
```
该脚本只会:备份 DB 到 `/tmp` → `git pull test1` → 重启 API → 前端 build → 重启 Web。
## Schema 变更
允许 `ALTER TABLE ADD COLUMN` 等向前兼容迁移;禁止 DROP 表/列、禁止用本机 DB 替换线上。

View File

@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""
安全部署 test1 分支 —— 只更新代码,绝不污染业务数据。
允许:
- git fetch / checkout test1 / pull(仅代码)
- systemctl restart api/web
- frontend npm run build
- 部署前备份 monitor.db 到 /tmp(只读拷贝,从不回写)
严禁(本脚本不会、也禁止手工做):
- 上传/覆盖 monitor.db、*.db-shm、*.db-wal
- 覆盖 pb_data、covers/、clips/、tiktok_cookies/
- scp/sftp 覆盖服务器业务文件
- git reset --hard / git clean -fd(会误删未跟踪数据若配置不当)
- 从本机推送任何 runtime 数据
用法:
python scripts/_deploy_test1_safe.py
"""
from __future__ import annotations
import time
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REPO = "/opt/douyinWEB"
BRANCH = "test1"
# 绝对禁止被本机覆盖的路径(文档 + 运行时断言)
PROTECTED = (
f"{REPO}/backend/data/monitor.db",
f"{REPO}/backend/data/monitor.db-shm",
f"{REPO}/backend/data/monitor.db-wal",
f"{REPO}/backend/data/covers",
f"{REPO}/backend/data/clips",
f"{REPO}/backend/data/tiktok_cookies",
f"{REPO}/pb_data",
)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
def run(cmd: str, timeout: int = 300) -> str:
_, out, err = c.exec_command(cmd, timeout=timeout)
o = out.read().decode("utf-8", "replace").strip()
e = err.read().decode("utf-8", "replace").strip()
return (o + ("\n" + e if e else "")).strip()
print("=== SAFE DEPLOY test1 (code only, never touch business data) ===")
print("protected:", ", ".join(PROTECTED))
# 1) 备份数据库(只读拷贝到 /tmp,绝不从本机写入)
ts = int(time.time())
print("[backup] monitor.db -> /tmp")
print(
run(
f"test -f {REPO}/backend/data/monitor.db && "
f"cp -a {REPO}/backend/data/monitor.db /tmp/monitor.db.bak_test1_{ts} && "
f"ls -lh /tmp/monitor.db.bak_test1_{ts} || echo 'NO_DB_SKIP'"
)
)
# 2) 记录数据指纹(部署前后对比,确认未被覆盖)
print("[fingerprint] before")
before = run(
f"stat -c '%n %s %Y' {REPO}/backend/data/monitor.db 2>/dev/null; "
f"du -sb {REPO}/backend/data/tiktok_cookies {REPO}/backend/data/clips "
f"{REPO}/backend/data/covers 2>/dev/null | head -20"
)
print(before)
# 3) 仅拉代码:fetch + checkout test1 + pull(不用 reset --hard / clean)
print("[git] fetch + checkout test1 + pull")
print(
run(
f"cd {REPO} && "
f"git fetch origin {BRANCH} 2>&1 && "
f"git checkout {BRANCH} 2>&1 && "
f"git pull --ff-only origin {BRANCH} 2>&1 && "
f"git log --oneline -3 && git status -sb"
)
)
# 4) 重启 API / 构建前端 / 重启 Web(不碰 data)
print("[restart api]")
c.exec_command("systemctl restart douyinweb-api >/dev/null 2>&1", timeout=5)
time.sleep(8)
print("api:", run("systemctl is-active douyinweb-api"))
print("[npm build]")
print(run(f"cd {REPO}/frontend && npm run build 2>&1 | tail -10", timeout=360))
print("[restart web]")
c.exec_command("systemctl restart douyinweb-web >/dev/null 2>&1", timeout=5)
time.sleep(5)
print("web:", run("systemctl is-active douyinweb-web"))
# 5) 再次指纹,必须一致(inode/size/mtime 允许服务写入导致 mtime 变,但 size 不应被本机替换)
print("[fingerprint] after")
after = run(
f"stat -c '%n %s %Y' {REPO}/backend/data/monitor.db 2>/dev/null; "
f"du -sb {REPO}/backend/data/tiktok_cookies {REPO}/backend/data/clips "
f"{REPO}/backend/data/covers 2>/dev/null | head -20"
)
print(after)
# size 对比:monitor.db 字节数若骤降到接近本机空库,视为污染
print("[safety] compare db size line")
print("BEFORE_LINE:", before.splitlines()[0] if before else "")
print("AFTER_LINE:", after.splitlines()[0] if after else "")
c.close()
print("DONE — code updated on test1; business data paths were never uploaded from local.")