diff --git a/backend/app/caption_pool.py b/backend/app/caption_pool.py new file mode 100644 index 0000000..007162b --- /dev/null +++ b/backend/app/caption_pool.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +"""Street-food English caption pool (DB-backed) for Shorts / TikTok / X. + +User custom template (+1) + 100 seeded captions → random pick at upload time. +Platform variants respect typical length / hashtag habits. +""" +from __future__ import annotations + +import random +import re +import sqlite3 +import time +import uuid +from typing import Any + +# Hard caps used at pick time (algo-friendly headroom inside platform maxima). +LIMITS = { + "shorts": 100, # YouTube title display sweet spot + "tiktok": 150, # first-line hook; API allows more + "x": 270, # X ~280 with media headroom +} + +# 100 English street-food hooks (base lines, no platform tags yet). +_BASE_STREET_FOOD: tuple[str, ...] = ( + "Street food hits different after midnight", + "This street bite is dangerously good", + "Crispy, spicy, gone in 10 seconds", + "The smell alone stopped me on the street", + "Hot off the grill street food moment", + "One skewer and I forgot my diet", + "Street chef energy you can taste", + "Sauce dripping street food ASMR vibes", + "This stall is a local legend", + "Fresh off the wok, still sizzling", + "Sweet, salty, smoky — street perfection", + "I came for one bite and stayed for five", + "Night market fuel, no regrets", + "That crunch is illegal", + "Steam rising, appetite rising", + "Street food therapy after a long day", + "Hand-rolled, fire-kissed, unforgettable", + "Spicy enough to wake the whole block", + "Golden crust, soft center, pure joy", + "This vendor does not miss", + "Follow the smoke for the best bites", + "Street snack that tastes like home", + "One wrap, zero leftovers", + "Char from the grill hits hard", + "Sweet chili drizzle on point", + "Queue was long, worth every minute", + "Street food flex for dinner", + "Crispy edges, melty middle", + "The first bite said everything", + "Hot oil pop, flavor explosion", + "Late-night street food run", + "Local cart, global cravings", + "This sauce recipe must be secret", + "Sizzling skillet street style", + "Fresh herbs on a fiery bite", + "Comfort food from the sidewalk", + "Smoky aroma you can hear", + "Bite-sized happiness on a stick", + "Street food > fancy dinner tonight", + "Crunch check: absolute 10/10", + "Spicy street noodles calling my name", + "That grill sound is music", + "Messy fingers, happy soul", + "Market aisle treasure found", + "Flame-kissed street classic", + "This cart feeds the whole street", + "Savory hit with a sweet finish", + "I would cross town for this", + "Street food plot twist: surprisingly light", + "Hot, loud, and addictive", + "The vendor smiled, the food slapped", + "Steam cloud = flavor cloud", + "Skewer season never ends", + "Crispy shell, juicy center", + "One scoop of street heaven", + "Pepper heat with zero mercy", + "Night lights, night bites", + "This is why I chase food carts", + "Gravy dripping street style", + "Toasted, tossed, and perfect", + "A tiny stall with huge flavor", + "Street food speedrun: eat then dream", + "Garlic butter on the walk home", + "That first crunch echo", + "Spiced just right, not just hot", + "Fresh dough meets open flame", + "Sidewalk gourmet unlocked", + "I saved you a virtual bite", + "Sweet glaze, street glaze", + "The grill never sleeps", + "Local favorite for a reason", + "Crispy wings from a street fryer", + "Soup steam in cold air hits different", + "Wrapped tight, flavor tighter", + "This cart has main-character energy", + "Salt, fire, and a perfect crust", + "Street dessert after spicy? Yes.", + "I followed my nose and won", + "Bite, pause, smile, repeat", + "Market snack that punches above", + "Hot plate, cold drink, perfect pair", + "The oil crackle is the trailer", + "Street food mood: hungry and happy", + "Char marks = chef's signature", + "This sauce belongs in a museum", + "Quick bite, long memory", + "Spicy street bowl for the brave", + "Fresh-cut toppings only", + "The line told the truth", + "Grill smoke in my hoodie forever", + "Soft bun, loud flavor", + "Street classic done right", + "One more skewer? Always.", + "Crunchy coat, tender heart", + "This cart changed my route home", + "Sweet heat on a paper plate", + "Night market MVP right here", + "Flavor first, manners later", + "That sizzle sold me instantly", + "Hungry eyes, happy stomach", +) + +assert len(_BASE_STREET_FOOD) == 100 + + +def _tags(platform: str) -> str: + p = platform.lower() + if p == "shorts": + return "#Shorts #StreetFood #Food" + if p == "tiktok": + return "#streetfood #fyp #foodtok #viral" + return "#StreetFood #Food" + + +def _format_body(base: str, platform: str) -> str: + """Attach platform-native tags and trim to limit.""" + p = platform.lower() + lim = LIMITS.get(p, 200) + tags = _tags(p) + # Leave room for tags + space + room = max(20, lim - len(tags) - 1) + core = re.sub(r"\s+", " ", str(base or "").strip()) + if len(core) > room: + core = core[: room - 1].rstrip() + "…" + text = f"{core} {tags}".strip() + return text[:lim] + + +def ensure_caption_pool_table(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS caption_pool ( + id TEXT PRIMARY KEY, + platform TEXT NOT NULL, + body TEXT NOT NULL, + enabled INTEGER NOT NULL DEFAULT 1, + sort_order INTEGER NOT NULL DEFAULT 0, + created_at REAL NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_caption_pool_plat ON caption_pool(platform, enabled)" + ) + + +def seed_caption_pool(conn: sqlite3.Connection, *, force: bool = False) -> dict[str, int]: + """Insert 100 English captions per platform if missing (or force reseed).""" + ensure_caption_pool_table(conn) + now = time.time() + counts: dict[str, int] = {} + for platform in ("shorts", "tiktok", "x"): + row = conn.execute( + "SELECT COUNT(*) AS n FROM caption_pool WHERE platform = ?", + (platform,), + ).fetchone() + n = int(row["n"] if row else 0) + if n >= 100 and not force: + counts[platform] = n + continue + if force: + conn.execute("DELETE FROM caption_pool WHERE platform = ?", (platform,)) + for i, base in enumerate(_BASE_STREET_FOOD): + body = _format_body(base, platform) + conn.execute( + "INSERT INTO caption_pool(id, platform, body, enabled, sort_order, created_at) " + "VALUES (?, ?, ?, 1, ?, ?)", + (str(uuid.uuid4()), platform, body, i, now), + ) + counts[platform] = 100 + return counts + + +def list_captions(platform: str, *, enabled_only: bool = True, limit: int = 200) -> list[dict[str, Any]]: + from . import db as _db + + plat = str(platform or "").strip().lower() + if plat not in LIMITS: + return [] + with _db._lock: # noqa: SLF001 + conn = _db._connect() # noqa: SLF001 + try: + ensure_caption_pool_table(conn) + sql = "SELECT * FROM caption_pool WHERE platform = ?" + args: list[Any] = [plat] + if enabled_only: + sql += " AND enabled = 1" + sql += " ORDER BY sort_order ASC, created_at ASC LIMIT ?" + args.append(max(1, min(int(limit), 500))) + rows = conn.execute(sql, args).fetchall() + return [dict(r) for r in rows] + finally: + conn.close() + + +def pool_stats() -> dict[str, Any]: + from . import db as _db + + with _db._lock: # noqa: SLF001 + conn = _db._connect() # noqa: SLF001 + try: + ensure_caption_pool_table(conn) + seed_caption_pool(conn) + conn.commit() + out: dict[str, Any] = {"platforms": {}, "limits": dict(LIMITS)} + for plat in LIMITS: + row = conn.execute( + "SELECT COUNT(*) AS n FROM caption_pool WHERE platform = ? AND enabled = 1", + (plat,), + ).fetchone() + out["platforms"][plat] = int(row["n"] if row else 0) + return out + finally: + conn.close() + + +def _render_custom(template: str, *, anchor: str = "", room: str = "", url: str = "") -> str: + text = str(template or "") + reps = { + "{anchor}": anchor or "", + "{room}": room or "", + "{url}": url or "", + "{title}": anchor or "", + "{name}": anchor or "", + } + for k, v in reps.items(): + text = text.replace(k, v) + return re.sub(r"[ \t]+", " ", text).strip() + + +def pick_caption( + platform: str, + *, + custom: str = "", + anchor: str = "", + room: str = "", + url: str = "", +) -> dict[str, Any]: + """Randomly pick from DB pool (100) + user custom (+1). + + Returns {text, source: 'pool'|'custom', pool_size}. + """ + from . import db as _db + + plat = str(platform or "").strip().lower() + if plat == "x_clips": + plat = "x" + lim = LIMITS.get(plat, 200) + custom_text = _render_custom(custom, anchor=anchor, room=room, url=url) + if custom_text: + custom_text = custom_text[:lim] + + with _db._lock: # noqa: SLF001 + conn = _db._connect() # noqa: SLF001 + try: + ensure_caption_pool_table(conn) + seed_caption_pool(conn) + conn.commit() + rows = conn.execute( + "SELECT body FROM caption_pool WHERE platform = ? AND enabled = 1 " + "ORDER BY sort_order ASC", + (plat,), + ).fetchall() + bodies = [str(r["body"] or "").strip() for r in rows if str(r["body"] or "").strip()] + finally: + conn.close() + + options: list[tuple[str, str]] = [("pool", b[:lim]) for b in bodies] + if custom_text: + options.append(("custom", custom_text)) + if not options: + fallback = custom_text or "street food" + return {"text": fallback[:lim], "source": "fallback", "pool_size": 0} + + source, text = random.choice(options) + return {"text": text, "source": source, "pool_size": len(bodies)} diff --git a/backend/app/db.py b/backend/app/db.py index da9d00a..9c4dbf5 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -318,11 +318,14 @@ def init_db() -> None: ): if col not in tt_cols: conn.execute(f"ALTER TABLE tiktok_channels ADD COLUMN {col} {decl}") + from . import caption_pool as _caption_pool from . import x2_db as _x2_db from . import x_clips_db as _x_clips_db _x2_db.ensure_x2_tables(conn) _x_clips_db.ensure_x_clips_tables(conn) + _caption_pool.ensure_caption_pool_table(conn) + _caption_pool.seed_caption_pool(conn) sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()} for col, ddl in [ ("oauth_ok", "INTEGER NOT NULL DEFAULT -1"), diff --git a/backend/app/main.py b/backend/app/main.py index 9297587..63e26b5 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1004,7 +1004,8 @@ async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[st except Exception: raise HTTPException(400, "daily_max 无效") from None if "x_clips_caption_template" in raw: - patch["x_clips_caption_template"] = str(raw.get("x_clips_caption_template") or "").strip()[:200] or "{anchor}" + # User custom (+1); empty means pool-only (100 English captions in DB) + patch["x_clips_caption_template"] = str(raw.get("x_clips_caption_template") or "").strip()[:200] if "x_clips_account_username" in raw: patch["x_clips_account_username"] = str(raw.get("x_clips_account_username") or "").strip().lstrip("@")[:80] if "x_clips_trigger" in raw: @@ -2510,6 +2511,40 @@ async def downloads_catalog() -> dict[str, Any]: return await _db(downloads_mod.catalog) +@app.get("/api/caption-pool") +async def caption_pool_status(platform: str = "") -> dict[str, Any]: + """DB-backed English street-food caption pools (100 per platform + user custom at upload).""" + from . import caption_pool + + stats = await _db(caption_pool.pool_stats) + plat = str(platform or "").strip().lower() + if plat in {"shorts", "tiktok", "x", "x_clips"}: + key = "x" if plat == "x_clips" else plat + samples = await _db(lambda: caption_pool.list_captions(key, limit=5)) + return {**stats, "platform": key, "samples": [s.get("body") for s in samples]} + return stats + + +@app.post("/api/caption-pool/reseed") +async def caption_pool_reseed() -> dict[str, Any]: + """Force re-insert 100 English captions per platform (admin).""" + from . import caption_pool + from . import db as _dbmod + + def _run() -> dict[str, int]: + with _dbmod._lock: # noqa: SLF001 + conn = _dbmod._connect() # noqa: SLF001 + try: + counts = caption_pool.seed_caption_pool(conn, force=True) + conn.commit() + return counts + finally: + conn.close() + + counts = await _db(_run) + return {"ok": True, "counts": counts} + + @app.get("/api/clash") async def clash_catalog() -> dict[str, Any]: from . import clash_dl diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index bb8b68e..9f720b4 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -1231,10 +1231,19 @@ class ShortsPipeline: desc_tpl = str(channel.get("description_template") or "") anchor = str(fresh.get("anchor_name") or job.get("anchor_name") or job.get("room_id") or "live") url = str(fresh.get("source_url") or job.get("source_url") or "") - title = title_tpl.replace("{anchor}", anchor).replace("{url}", url) + from . import caption_pool + + picked = caption_pool.pick_caption( + "shorts", + custom=title_tpl, + anchor=anchor, + url=url, + room=str(fresh.get("room_id") or job.get("room_id") or ""), + ) + title = str(picked.get("text") or "").strip() or title_tpl.replace("{anchor}", anchor).replace("{url}", url) desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url) if "#Shorts" not in title and "#shorts" not in title.lower(): - title = f"{title} #Shorts" + title = f"{title} #Shorts"[:100] pid = profile_id_for_channel(channel) reserve_yt_upload_slot(cfg, profile_id=pid) diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index 72fadb0..447d806 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -651,8 +651,16 @@ class TikTokPipeline: if not tiktok_session.channel_has_session(channel): tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie") return - # 文案只用账号「标题模板」原文,绝不自动拼直播间名/链接 - title = str(channel.get("title_template") or "").strip() + # 文案 = 账号自定义模板(+1) + DB 中 100 条英文 street food 随机其一 + from . import caption_pool + + picked = caption_pool.pick_caption( + "tiktok", + custom=str(channel.get("title_template") or "").strip(), + anchor=str(fresh.get("anchor_name") or job.get("anchor_name") or "").strip(), + room=str(fresh.get("room_id") or job.get("room_id") or "").strip(), + ) + title = str(picked.get("text") or "").strip() if not tiktok_db.touch_tiktok_upload_lease(jid): return proxy = resolve_channel_socks_proxy(channel, cfg) or None diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py index f266872..183a5da 100644 --- a/backend/app/x_clips_pipeline.py +++ b/backend/app/x_clips_pipeline.py @@ -57,20 +57,18 @@ def _clip_sec(cfg: dict[str, Any], room: dict[str, Any] | None = None) -> int: 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.""" + """Random pick: user template (+1) + 100 English street-food captions in DB.""" + from . import caption_pool + 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] + picked = caption_pool.pick_caption( + "x", + custom=tpl, + anchor=str(job.get("anchor_name") or "").strip(), + room=str(job.get("room_id") or "").strip(), + ) + return str(picked.get("text") or tpl or "street food")[:270] def _enqueue_job( @@ -510,10 +508,12 @@ class XClipsPipeline: 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) + # Keep caption chosen at schedule time (100+1 random); only pick if missing. + caption = str(job.get("caption") or "").strip() if not caption: - raise ValueError("文案模板结果为空") + 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("@") diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 8c41010..5f5799f 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -1321,12 +1321,16 @@ export default function ShortsPage() { 按频道可改(1–50),默认 9
- 发到 TikTok 的文案就是这里写的原文,不会自动加直播间名字或链接。 + 上传时随机:你的自定义文案 + 数据库 100 条英文(#streetfood #fyp),约 ≤150 字;不会自动拼直播间名。