douyinWEB/backend/app/caption_pool.py
eric 0dcfdb263a feat(yt-long): add 100 English SEO titles and descriptions for street food
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 11:04:21 -05:00

329 lines
11 KiB
Python

# -*- 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
"yt_long": 100, # YouTube long-form title
"yt_long_desc": 4900,
}
# 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
# Long-form SEO pools (titles + descriptions) — isolated from Shorts hooks.
try:
from .yt_long_seo import YT_LONG_DESCS, YT_LONG_TITLES
except Exception:
YT_LONG_TITLES = ()
YT_LONG_DESCS = ()
for platform, items in (("yt_long", YT_LONG_TITLES), ("yt_long_desc", YT_LONG_DESCS)):
row = conn.execute(
"SELECT COUNT(*) AS n FROM caption_pool WHERE platform = ?",
(platform,),
).fetchone()
n = int(row["n"] if row else 0)
need = len(items) if items else 100
if n >= need and not force:
counts[platform] = n
continue
if force:
conn.execute("DELETE FROM caption_pool WHERE platform = ?", (platform,))
for i, body in enumerate(items):
conn.execute(
"INSERT INTO caption_pool(id, platform, body, enabled, sort_order, created_at) "
"VALUES (?, ?, ?, 1, ?, ?)",
(str(uuid.uuid4()), platform, str(body)[:4900], i, now),
)
counts[platform] = len(items)
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)}