feat(mcp): caption presets and the new caption options in add_subtitles
/api/subtitle takes a named preset (subtitles.CAPTION_PRESETS, the same looks the dashboard offers); fields sent alongside it override that part. The MCP add_subtitles tool exposes preset, effect, reveal, one_word, shadow and border_width, and gives a resized line the budget that keeps it on one line, as the dashboard does. A test keeps the server and dashboard preset ids in sync.
This commit is contained in:
parent
9cc0a0feb0
commit
06a119c280
5 changed files with 175 additions and 9 deletions
13
app.py
13
app.py
|
|
@ -3708,7 +3708,7 @@ async def _ensure_job_files(job_id: str, request: Request) -> bool:
|
||||||
|
|
||||||
|
|
||||||
from editor import VideoEditor
|
from editor import VideoEditor
|
||||||
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video
|
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video, CAPTION_PRESETS
|
||||||
from hooks import add_hook_to_video
|
from hooks import add_hook_to_video
|
||||||
from translate import translate_video, get_supported_languages
|
from translate import translate_video, get_supported_languages
|
||||||
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
||||||
|
|
@ -3922,6 +3922,9 @@ class SubtitleRequest(BaseModel):
|
||||||
# keeps the generator's defaults, which is what old clients send.
|
# keeps the generator's defaults, which is what old clients send.
|
||||||
max_chars: Optional[int] = None
|
max_chars: Optional[int] = None
|
||||||
max_duration: Optional[float] = None
|
max_duration: Optional[float] = None
|
||||||
|
# Named look (subtitles.CAPTION_PRESETS); any field sent explicitly
|
||||||
|
# alongside it overrides that field of the preset.
|
||||||
|
preset: Optional[str] = None
|
||||||
input_filename: Optional[str] = None
|
input_filename: Optional[str] = None
|
||||||
# User-edited caption words. When present, the burn uses them VERBATIM
|
# User-edited caption words. When present, the burn uses them VERBATIM
|
||||||
# instead of regenerating from the stored transcript — without this, text
|
# instead of regenerating from the stored transcript — without this, text
|
||||||
|
|
@ -4827,6 +4830,14 @@ async def generate_effects_config(
|
||||||
|
|
||||||
@app.post("/api/subtitle")
|
@app.post("/api/subtitle")
|
||||||
async def add_subtitles(req: SubtitleRequest, request: Request):
|
async def add_subtitles(req: SubtitleRequest, request: Request):
|
||||||
|
if req.preset:
|
||||||
|
preset = CAPTION_PRESETS.get(req.preset.strip().lower())
|
||||||
|
if preset is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Unknown preset. Use one of: {', '.join(CAPTION_PRESETS)}.")
|
||||||
|
req = req.model_copy(update={k: v for k, v in preset.items()
|
||||||
|
if k not in req.model_fields_set})
|
||||||
await require_managed_entitlement(request)
|
await require_managed_entitlement(request)
|
||||||
await _ensure_job_files(req.job_id, request)
|
await _ensure_job_files(req.job_id, request)
|
||||||
if req.job_id not in jobs:
|
if req.job_id not in jobs:
|
||||||
|
|
|
||||||
|
|
@ -1125,7 +1125,7 @@ snippets for Claude Desktop, Cursor, n8n and curl.</p>
|
||||||
<tr><td><code>get_job_status</code></td><td>Progress, recent log lines, and the clips once the job completes.</td></tr>
|
<tr><td><code>get_job_status</code></td><td>Progress, recent log lines, and the clips once the job completes.</td></tr>
|
||||||
<tr><td><code>list_clips</code></td><td>Titles, durations, platform-ready descriptions and download URLs for a finished job.</td></tr>
|
<tr><td><code>list_clips</code></td><td>Titles, durations, platform-ready descriptions and download URLs for a finished job.</td></tr>
|
||||||
<tr><td><code>get_quota</code></td><td>Plan and remaining minutes, so an agent can check before starting a large job.</td></tr>
|
<tr><td><code>get_quota</code></td><td>Plan and remaining minutes, so an agent can check before starting a large job.</td></tr>
|
||||||
<tr><td><code>add_subtitles</code></td><td>Restyles the burned-in captions of one clip, classic or karaoke word highlighting.</td></tr>
|
<tr><td><code>add_subtitles</code></td><td>Restyles the burned-in captions of one clip: presets (default, hormozi, pill, lime, oneword, clean), size, word-by-word reveal, a box behind the active word or one word at a time.</td></tr>
|
||||||
<tr><td><code>publish_clip</code></td><td>Posts or schedules one clip to TikTok, Instagram or YouTube through the connected account.</td></tr>
|
<tr><td><code>publish_clip</code></td><td>Posts or schedules one clip to TikTok, Instagram or YouTube through the connected account.</td></tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ from fastapi import APIRouter, Request
|
||||||
from fastapi.responses import JSONResponse, Response
|
from fastapi.responses import JSONResponse, Response
|
||||||
|
|
||||||
import mcp_ui
|
import mcp_ui
|
||||||
|
from subtitles import CAPTION_PRESETS, line_budget
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -221,20 +222,38 @@ TOOLS = [
|
||||||
"name": "add_subtitles",
|
"name": "add_subtitles",
|
||||||
"title": "Burn styled captions onto a clip",
|
"title": "Burn styled captions onto a clip",
|
||||||
"description": (
|
"description": (
|
||||||
"Re-style the captions of one clip (clips already ship with default "
|
"Re-style the captions of one clip (clips already ship with the "
|
||||||
"captions). style 'karaoke' highlights the active word."
|
"'default' preset). Easiest: pass a preset; any other field you send "
|
||||||
|
"overrides that part of it. Without a preset, style 'karaoke' "
|
||||||
|
"highlights the active word."
|
||||||
),
|
),
|
||||||
"inputSchema": {
|
"inputSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"job_id": {"type": "string"},
|
"job_id": {"type": "string"},
|
||||||
"clip_index": {"type": "integer", "description": "0-based index from list_clips."},
|
"clip_index": {"type": "integer", "description": "0-based index from list_clips."},
|
||||||
|
"preset": {"type": "string", "enum": list(CAPTION_PRESETS),
|
||||||
|
"description": (
|
||||||
|
"default: Anton caps, yellow active word. "
|
||||||
|
"hormozi: words appear as spoken, yellow active word. "
|
||||||
|
"pill: purple box behind the active word. "
|
||||||
|
"lime: lime box behind the active word. "
|
||||||
|
"oneword: one big word at a time. "
|
||||||
|
"clean: no outline, soft shadow, sentence case.")},
|
||||||
"style": {"type": "string", "enum": ["classic", "karaoke"]},
|
"style": {"type": "string", "enum": ["classic", "karaoke"]},
|
||||||
"position": {"type": "string", "enum": ["top", "middle", "bottom"]},
|
"position": {"type": "string", "enum": ["top", "middle", "bottom"]},
|
||||||
"font_size": {"type": "integer"},
|
"font_size": {"type": "integer",
|
||||||
"font_name": {"type": "string"},
|
"description": "44 is the default (M); 34 = S, 56 = L, 70 = XL."},
|
||||||
|
"font_name": {"type": "string",
|
||||||
|
"description": "Anton, Montserrat ExtraBold, Verdana, Arial, Impact, Georgia..."},
|
||||||
"font_color": {"type": "string", "description": "Hex color, e.g. #FFFFFF."},
|
"font_color": {"type": "string", "description": "Hex color, e.g. #FFFFFF."},
|
||||||
"highlight_color": {"type": "string", "description": "Karaoke active-word color."},
|
"highlight_color": {"type": "string", "description": "Karaoke active-word color (or box color with effect 'highlight')."},
|
||||||
|
"effect": {"type": "string", "enum": ["none", "pop", "glow", "box", "highlight"],
|
||||||
|
"description": "Karaoke active-word effect; 'highlight' = solid box behind it."},
|
||||||
|
"reveal": {"type": "boolean", "description": "Karaoke: words appear as they are spoken."},
|
||||||
|
"one_word": {"type": "boolean", "description": "Show one word at a time."},
|
||||||
|
"shadow": {"type": "integer", "description": "Drop shadow depth 0-6."},
|
||||||
|
"border_width": {"type": "integer", "description": "Outline 0-10 (0 needs a shadow to stay readable)."},
|
||||||
"uppercase": {"type": "boolean"},
|
"uppercase": {"type": "boolean"},
|
||||||
},
|
},
|
||||||
"required": ["job_id", "clip_index"],
|
"required": ["job_id", "clip_index"],
|
||||||
|
|
@ -446,10 +465,21 @@ async def _tool_get_quota(client, args):
|
||||||
|
|
||||||
async def _tool_add_subtitles(client, args):
|
async def _tool_add_subtitles(client, args):
|
||||||
body = {"job_id": args["job_id"], "clip_index": args["clip_index"]}
|
body = {"job_id": args["job_id"], "clip_index": args["clip_index"]}
|
||||||
for k in ("style", "position", "font_size", "font_name", "font_color",
|
for k in ("preset", "style", "position", "font_size", "font_name", "font_color",
|
||||||
"highlight_color", "uppercase"):
|
"highlight_color", "effect", "reveal", "shadow", "border_width",
|
||||||
|
"uppercase"):
|
||||||
if args.get(k) is not None:
|
if args.get(k) is not None:
|
||||||
body[k] = args[k]
|
body[k] = args[k]
|
||||||
|
if args.get("one_word"):
|
||||||
|
body["max_chars"] = 1
|
||||||
|
elif ("font_size" in body or "font_name" in body) and \
|
||||||
|
CAPTION_PRESETS.get(str(body.get("preset") or "").lower(), {}).get("max_chars") != 1:
|
||||||
|
# A resized or refonted line gets the budget that keeps it on one
|
||||||
|
# line, as the dashboard does; the preset's font fills the gap.
|
||||||
|
base = CAPTION_PRESETS.get(str(body.get("preset") or "default").lower(),
|
||||||
|
CAPTION_PRESETS["default"])
|
||||||
|
body["max_chars"] = line_budget(body.get("font_name", base["font_name"]),
|
||||||
|
body.get("font_size", base["font_size"]))
|
||||||
resp = await client.post("/api/subtitle", json=body)
|
resp = await client.post("/api/subtitle", json=body)
|
||||||
if resp.status_code >= 400:
|
if resp.status_code >= 400:
|
||||||
return _api_error(resp), True
|
return _api_error(resp), True
|
||||||
|
|
|
||||||
44
subtitles.py
44
subtitles.py
|
|
@ -253,6 +253,50 @@ AUTO_CAPTION_STYLE = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Named looks for /api/subtitle `preset` (and the MCP add_subtitles tool), in
|
||||||
|
# request-field names. Mirrors the dashboard's CAPTION_PRESETS in
|
||||||
|
# SubtitleModal.jsx (a test checks the ids): "default" is what every clip
|
||||||
|
# ships with, the rest are the short-form looks trending in 2026.
|
||||||
|
_PRESET_BASE = {"style": "karaoke", "font_color": "#FFFFFF", "bg_opacity": 0.0,
|
||||||
|
"base_opacity": 1.0, "reveal": False, "shadow": 0,
|
||||||
|
"max_duration": 1.4}
|
||||||
|
CAPTION_PRESETS = {
|
||||||
|
"default": {**_PRESET_BASE, "font_name": "Anton", "font_size": 44,
|
||||||
|
"highlight_color": "#FFE500", "border_width": 4, "effect": "pop",
|
||||||
|
"uppercase": True, "max_chars": 16},
|
||||||
|
# Words appear as they are spoken, yellow active word, shadow.
|
||||||
|
"hormozi": {**_PRESET_BASE, "font_name": "Montserrat ExtraBold", "font_size": 44,
|
||||||
|
"highlight_color": "#FFE500", "border_width": 4, "shadow": 2,
|
||||||
|
"effect": "pop", "uppercase": True, "reveal": True, "max_chars": 9},
|
||||||
|
# Solid box behind the active word (CapCut / Submagic).
|
||||||
|
"pill": {**_PRESET_BASE, "font_name": "Montserrat ExtraBold", "font_size": 44,
|
||||||
|
"highlight_color": "#7C3AED", "border_width": 3, "effect": "highlight",
|
||||||
|
"uppercase": True, "max_chars": 9},
|
||||||
|
"lime": {**_PRESET_BASE, "font_name": "Montserrat ExtraBold", "font_size": 44,
|
||||||
|
"highlight_color": "#A3FF12", "border_width": 3, "effect": "highlight",
|
||||||
|
"uppercase": True, "max_chars": 9},
|
||||||
|
# One big word at a time.
|
||||||
|
"oneword": {**_PRESET_BASE, "font_name": "Anton", "font_size": 70,
|
||||||
|
"highlight_color": "#FFFFFF", "border_width": 5, "effect": "pop",
|
||||||
|
"uppercase": True, "max_chars": 1},
|
||||||
|
# No outline, soft shadow, sentence case.
|
||||||
|
"clean": {**_PRESET_BASE, "font_name": "Montserrat ExtraBold", "font_size": 34,
|
||||||
|
"highlight_color": "#FFFFFF", "border_width": 0, "shadow": 2,
|
||||||
|
"effect": "none", "uppercase": False, "base_opacity": 0.7,
|
||||||
|
"max_chars": 12},
|
||||||
|
}
|
||||||
|
|
||||||
|
# Characters per line at font size 44, per font (Anton is condensed,
|
||||||
|
# Montserrat wide). Mirrors lineBudget in SubtitleModal.jsx.
|
||||||
|
_LINE_CHARS = {"Anton": 16, "Montserrat ExtraBold": 9, "Impact": 16}
|
||||||
|
|
||||||
|
|
||||||
|
def line_budget(font_name, font_size):
|
||||||
|
"""max_chars that keeps one line inside the 9:16 frame at this size."""
|
||||||
|
size = _clamp_number(font_size, 10, 200, 44)
|
||||||
|
return max(6, round(_LINE_CHARS.get(font_name, 14) * 44 / size))
|
||||||
|
|
||||||
|
|
||||||
def _ass_time(seconds):
|
def _ass_time(seconds):
|
||||||
"""Format seconds as ASS timestamp H:MM:SS.cc (centiseconds)."""
|
"""Format seconds as ASS timestamp H:MM:SS.cc (centiseconds)."""
|
||||||
seconds = max(0, seconds)
|
seconds = max(0, seconds)
|
||||||
|
|
|
||||||
81
tests/test_caption_presets.py
Normal file
81
tests/test_caption_presets.py
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
"""Caption presets: the API, the MCP tool and the dashboard agree on them."""
|
||||||
|
import asyncio
|
||||||
|
import re
|
||||||
|
|
||||||
|
from subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_offers_every_server_preset():
|
||||||
|
src = open("dashboard/src/components/SubtitleModal.jsx").read()
|
||||||
|
ids = set(re.findall(r"\{ id: '([a-z]+)'", src))
|
||||||
|
missing = set(CAPTION_PRESETS) - ids
|
||||||
|
assert not missing, f"presets the dashboard does not offer: {missing}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_preset_is_what_clips_ship_with():
|
||||||
|
d = CAPTION_PRESETS["default"]
|
||||||
|
for k in ("font_name", "font_size", "highlight_color", "border_width",
|
||||||
|
"effect", "uppercase", "max_chars", "max_duration"):
|
||||||
|
assert d[k] == AUTO_CAPTION_STYLE[k], k
|
||||||
|
|
||||||
|
|
||||||
|
def test_line_budget_shrinks_with_size_and_wide_fonts():
|
||||||
|
assert line_budget("Anton", 44) == 16
|
||||||
|
assert line_budget("Anton", 70) < line_budget("Anton", 44) < line_budget("Anton", 34)
|
||||||
|
assert line_budget("Montserrat ExtraBold", 44) < line_budget("Anton", 44)
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeResp:
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self):
|
||||||
|
self.body = None
|
||||||
|
|
||||||
|
async def post(self, path, json):
|
||||||
|
assert path == "/api/subtitle"
|
||||||
|
self.body = json
|
||||||
|
return _FakeResp()
|
||||||
|
|
||||||
|
|
||||||
|
def _call(**args):
|
||||||
|
from mcp_server import _tool_add_subtitles
|
||||||
|
client = _FakeClient()
|
||||||
|
asyncio.run(_tool_add_subtitles(client, {"job_id": "j", "clip_index": 0, **args}))
|
||||||
|
return client.body
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_forwards_preset_and_new_options():
|
||||||
|
body = _call(preset="pill", reveal=True, shadow=2, effect="highlight")
|
||||||
|
assert body["preset"] == "pill"
|
||||||
|
assert (body["reveal"], body["shadow"], body["effect"]) == (True, 2, "highlight")
|
||||||
|
assert "max_chars" not in body # the preset's own budget applies
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_one_word_and_resize_set_the_line_budget():
|
||||||
|
assert _call(one_word=True)["max_chars"] == 1
|
||||||
|
assert _call(font_size=70)["max_chars"] == line_budget("Anton", 70)
|
||||||
|
# Resizing the one-word preset keeps it one word.
|
||||||
|
assert "max_chars" not in _call(preset="oneword", font_size=56)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_preset_is_a_400():
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from app import SubtitleRequest, add_subtitles
|
||||||
|
with pytest.raises(HTTPException) as exc:
|
||||||
|
asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None))
|
||||||
|
assert exc.value.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_preset_fills_only_fields_not_sent():
|
||||||
|
from app import SubtitleRequest
|
||||||
|
req = SubtitleRequest(job_id="j", clip_index=0, preset="hormozi", highlight_color="#00FF00")
|
||||||
|
merged = req.model_copy(update={k: v for k, v in CAPTION_PRESETS["hormozi"].items()
|
||||||
|
if k not in req.model_fields_set})
|
||||||
|
assert merged.highlight_color == "#00FF00"
|
||||||
|
assert merged.reveal is True and merged.font_name == "Montserrat ExtraBold"
|
||||||
Loading…
Reference in a new issue