Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(video): reject invalid subtitle colors before generation

Rudy Celekli8d30664bda92
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.py
index 48301a13..401278f1 100644
--- a/app/controllers/v1/video.py
+++ b/app/controllers/v1/video.py
@@ -238,6 +238,7 @@ def create_task(
and isinstance(body, TaskVideoRequest)
and body.subtitle_enabled
):
+ tm.video.validate_subtitle_colors(body)
# 字体名可由 API 客户端直接提交,不能等到后台渲染时才发现路径越界。
# 这里与渲染层共用目录边界校验,让非法请求在创建付费任务前返回 400。
file_security.resolve_path_within_directory(
diff --git a/app/services/task.py b/app/services/task.py
index 418b5160..9bd5d036 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -1490,6 +1490,12 @@ def _run_pipeline(
failed_stage=None, error=None,
)
+ if stop_at == "video" and params.subtitle_enabled:
+ try:
+ video.validate_subtitle_colors(params)
+ except ValueError as exc:
+ return _mark_task_failed(task_id, "preflight", str(exc))
+
if stop_at in {"materials", "video"} and params.video_source not in _SUPPORTED_VIDEO_SOURCES:
return _mark_task_failed(
task_id, "preflight", f"unsupported video source: {params.video_source!r}"
diff --git a/app/services/video.py b/app/services/video.py
index 7de00bef..be338d62 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -28,7 +28,7 @@ from moviepy import (
afx,
)
from moviepy.video.tools.subtitles import SubtitlesClip
-from PIL import Image, ImageDraw, ImageFont, ImageOps
+from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps
from app.config import config
from app.models import const
@@ -1454,6 +1454,25 @@ def _get_visible_center_position(
return x, y
+def validate_subtitle_colors(params: VideoParams) -> None:
+ """Reject colors Pillow cannot render, before generation services run."""
+ if not params.subtitle_enabled:
+ return
+ colors = [("text_fore_color", params.text_fore_color)]
+ # Rendering truncates the width to an integer; a zero-width stroke is unused.
+ if int(params.stroke_width) > 0:
+ colors.append(("stroke_color", params.stroke_color))
+ if isinstance(params.text_background_color, str):
+ colors.append(("text_background_color", params.text_background_color))
+ for field, value in colors:
+ if value is None:
+ continue
+ try:
+ ImageColor.getcolor(value, "RGBA")
+ except (ValueError, TypeError) as exc:
+ raise ValueError(f"invalid subtitle color: {field}") from exc
+
+
def subtitle_colors_are_indistinguishable(params: VideoParams) -> bool:
"""判断字幕文字和背景是否同色,提醒用户可能无法看清字幕。"""
if not params.subtitle_enabled or not params.text_background_color:
diff --git a/test/services/test_subtitle_color_preflight.py b/test/services/test_subtitle_color_preflight.py
new file mode 100644
index 00000000..5c29504c
--- /dev/null
+++ b/test/services/test_subtitle_color_preflight.py
@@ -0,0 +1,68 @@
+from unittest.mock import patch
+
+import pytest
+from fastapi.testclient import TestClient
+from PIL import Image, ImageDraw
+
+from app import asgi
+from app.config import config
+from app.controllers.v1 import video as controller
+from app.models.schema import VideoParams
+from app.services import state as sm
+from app.services import task
+
+
[email protected]("field", ["text_fore_color", "stroke_color", "text_background_color"])
+def test_http_rejects_invalid_active_color_before_queue(field):
+ with patch.dict(config.app, {"api_key": ""}), patch.object(sm, "state", sm.MemoryState()), patch.object(controller.task_manager, "add_task") as queued:
+ with TestClient(asgi.app) as client:
+ response = client.post("/api/v1/videos", json={"video_subject": "Coffee", field: "#gg0000"})
+ assert response.status_code == 400
+ assert field in response.json()["message"]
+ queued.assert_not_called()
+ assert sm.state.list_task_ids() == []
+
+
[email protected]("field", ["text_fore_color", "stroke_color", "text_background_color"])
+def test_pipeline_rejects_invalid_color_before_generation(field):
+ params = VideoParams(video_subject="Coffee", **{field: "not-a-color"})
+ with patch.object(sm, "state", sm.MemoryState()), patch.object(task.llm, "generate_script", side_effect=RuntimeError("generation boundary reached")) as provider:
+ task.start("bad-color", params)
+ provider.assert_not_called()
+ failure = sm.state.get_task("bad-color")
+ assert failure["failed_stage"] == "preflight"
+ assert field in failure["error"]
+
+
[email protected]("colors", [
+ {"text_fore_color": "RebeccaPurple", "stroke_color": "rgb(1, 2, 3)", "text_background_color": "hsl(0, 100%, 50%)"},
+ {"text_fore_color": "#abcd", "stroke_color": "#12345678", "text_background_color": "rgba(1, 2, 3, 0)"},
+ {"text_fore_color": None, "stroke_color": None, "text_background_color": False},
+ {"text_background_color": True},
+ {"stroke_width": 0, "stroke_color": "not-used"},
+])
+def test_http_preserves_supported_pillow_colors_and_unused_stroke(colors):
+ # Verify accepted color syntax against the actual renderer's Pillow consumer.
+ image = Image.new("RGBA", (32, 32))
+ draw = ImageDraw.Draw(image)
+ draw.text((0, 0), "A", fill=colors.get("text_fore_color", "white"), stroke_width=int(colors.get("stroke_width", 1)), stroke_fill=colors.get("stroke_color", "black"))
+ background = colors.get("text_background_color", False)
+ if isinstance(background, str):
+ Image.new("RGBA", (1, 1), background)
+ with patch.dict(config.app, {"api_key": ""}), patch.object(sm, "state", sm.MemoryState()), patch.object(controller.task_manager, "add_task") as queued:
+ with TestClient(asgi.app) as client:
+ response = client.post("/api/v1/videos", json={"video_subject": "Coffee", **colors})
+ assert response.status_code == 200
+ queued.assert_called_once()
+
+
[email protected]("endpoint,payload", [
+ ("/api/v1/videos", {"video_subject": "Coffee", "subtitle_enabled": False}),
+ ("/api/v1/subtitle", {"video_script": "Coffee"}),
+])
+def test_http_does_not_validate_colors_that_will_not_render(endpoint, payload):
+ with patch.dict(config.app, {"api_key": ""}), patch.object(sm, "state", sm.MemoryState()), patch.object(controller.task_manager, "add_task") as queued:
+ with TestClient(asgi.app) as client:
+ response = client.post(endpoint, json={**payload, "text_fore_color": "unused-color"})
+ assert response.status_code == 200
+ queued.assert_called_once()