利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
Add optional rounded subtitle background
harry0703f85a0ffda06c
diff --git a/app/models/schema.py b/app/models/schema.pyindex ef7958f9..a57c7f92 100644--- a/app/models/schema.py+++ b/app/models/schema.py@@ -100,6 +100,7 @@ class VideoParams(BaseModel):font_name: Optional[str] = "STHeitiMedium.ttc"text_fore_color: Optional[str] = "#FFFFFF"text_background_color: Union[bool, str] = True+ rounded_subtitle_background: bool = Falsefont_size: int = 60stroke_color: Optional[str] = "#000000"@@ -123,6 +124,7 @@ class SubtitleRequest(BaseModel):font_name: Optional[str] = "STHeitiMedium.ttc"text_fore_color: Optional[str] = "#FFFFFF"text_background_color: Union[bool, str] = True+ rounded_subtitle_background: bool = Falsefont_size: int = 60stroke_color: Optional[str] = "#000000"stroke_width: float = 1.5diff --git a/app/services/video.py b/app/services/video.pyindex 4c0515f1..a6bd23e2 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -9,6 +9,7 @@ import subprocessfrom contextlib import redirect_stdoutfrom typing import Listfrom loguru import logger+import numpy as npfrom moviepy import (AudioFileClip,ColorClip,@@ -20,7 +21,7 @@ from moviepy import (afx,)from moviepy.video.tools.subtitles import SubtitlesClip-from PIL import Image, ImageFont+from PIL import Image, ImageDraw, ImageFontfrom app.models import constfrom app.models.schema import (@@ -534,6 +535,39 @@ def wrap_text(text, max_width, font="Arial", fontsize=60):return result, height+def _hex_to_rgb(color: str) -> tuple[int, int, int]:+ # 字幕背景色来自 API/WebUI 参数,可能为空或格式不规范。这里统一只接受+ # #RRGGBB 形式,非法值回退为黑色,避免 PIL 渲染阶段抛出异常中断任务。+ if isinstance(color, str) and color.startswith("#") and len(color) == 7:+ try:+ return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))+ except ValueError:+ pass+ return (0, 0, 0)+++def _rounded_subtitle_background_clip(+ width: int,+ height: int,+ color: str,+ alpha: int = 140,+ radius: int = 16,+) -> ImageClip:+ # 新字幕背景仅在用户显式开启时使用:通过 RGBA 图片绘制圆角半透明底板,+ # 再交给 MoviePy 作为透明 ImageClip 参与合成。这样默认路径完全不变,+ # 同时可以低成本试验更柔和的字幕视觉效果。+ rgb = _hex_to_rgb(color)+ safe_alpha = max(0, min(255, int(alpha)))+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))+ draw = ImageDraw.Draw(img)+ draw.rounded_rectangle(+ [0, 0, max(0, width - 1), max(0, height - 1)],+ radius=max(0, int(radius)),+ fill=(rgb[0], rgb[1], rgb[2], safe_alpha),+ )+ return ImageClip(np.array(img), transparent=True)++def generate_video(video_path: str,audio_path: str,@@ -588,23 +622,70 @@ def generate_video(# 描边或背景色时,容易把最后一行的下半部分裁掉。这里显式传入# 一个更保守的高度,把行间距和额外上下留白一并算进去,保证字幕# 背景框与文字本身都能完整渲染出来。- size = (- int(max_width),- int(txt_height + vertical_padding + (interline * line_count)),+ clip_h = int(txt_height + vertical_padding + (interline * line_count))+ bg_color = resolve_subtitle_background_color()+ rounded_bg_enabled = bool(+ getattr(params, "rounded_subtitle_background", False) and bg_color)- _clip = TextClip(- text=wrapped_txt,- font=font_path,- font_size=params.font_size,- color=params.text_fore_color,- bg_color=resolve_subtitle_background_color(),- stroke_color=params.stroke_color,- stroke_width=params.stroke_width,- interline=interline,- size=size,- text_align="center",- )+ if rounded_bg_enabled:+ # 圆角背景需要贴合文字宽度,而不是沿用 90% 视频宽度。这里先用+ # PIL 测量最长一行文字,再加水平内边距,避免短字幕出现过宽底板。+ try:+ font = ImageFont.truetype(font_path, params.font_size)+ text_w = max(+ int(font.getbbox(line)[2] - font.getbbox(line)[0])+ for line in wrapped_txt.split("\n")+ )+ except Exception as exc:+ logger.warning(+ f"failed to measure subtitle text width, fallback to max width: {str(exc)}"+ )+ text_w = int(max_width)++ pad_x = int(params.font_size * 0.6)+ box_w = max(1, min(int(max_width), text_w + 2 * pad_x))+ radius = max(8, int(params.font_size * 0.4))+ text_clip = TextClip(+ text=wrapped_txt,+ font=font_path,+ font_size=params.font_size,+ color=params.text_fore_color,+ bg_color=None,+ stroke_color=params.stroke_color,+ stroke_width=params.stroke_width,+ interline=interline,+ size=(box_w, clip_h),+ text_align="center",+ )+ bg_clip = _rounded_subtitle_background_clip(+ width=box_w,+ height=clip_h,+ color=bg_color,+ alpha=140,+ radius=radius,+ )+ _clip = CompositeVideoClip(+ [bg_clip, text_clip.with_position("center")],+ size=(box_w, clip_h),+ )+ else:+ size = (+ int(max_width),+ clip_h,+ )+ _clip = TextClip(+ text=wrapped_txt,+ font=font_path,+ font_size=params.font_size,+ color=params.text_fore_color,+ bg_color=bg_color,+ stroke_color=params.stroke_color,+ stroke_width=params.stroke_width,+ interline=interline,+ size=size,+ text_align="center",+ )duration = subtitle_item[0][1] - subtitle_item[0][0]_clip = _clip.with_start(subtitle_item[0][0])_clip = _clip.with_end(subtitle_item[0][1])diff --git a/test/services/test_video.py b/test/services/test_video.pyindex 3da5c2a1..225e39d1 100644--- a/test/services/test_video.py+++ b/test/services/test_video.py@@ -311,5 +311,29 @@ class TestVideoService(unittest.TestCase):except Exception as e:self.fail(f"test wrap_text failed: {str(e)}")+ def test_rounded_subtitle_background_clip_has_transparent_corners(self):+ """+ 圆角字幕背景只在用户显式开启时使用。这里直接验证生成的 RGBA+ 背景具备透明圆角和半透明中心,避免后续改动把圆角效果退化成实心矩形。+ """+ clip = vd._rounded_subtitle_background_clip(+ width=120,+ height=48,+ color="#123456",+ alpha=140,+ radius=16,+ )+ try:+ frame = clip.get_frame(0)+ mask = clip.mask.get_frame(0)++ self.assertEqual(frame.shape[0:2], (48, 120))+ self.assertEqual(tuple(frame[24, 60]), (18, 52, 86))+ self.assertEqual(mask[0, 0], 0)+ self.assertGreater(mask[24, 60], 0.5)+ self.assertLess(mask[24, 60], 0.6)+ finally:+ clip.close()+if __name__ == "__main__":unittest.main()diff --git a/webui/Main.py b/webui/Main.pyindex 82492614..48f7a447 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -1084,6 +1084,15 @@ with right_panel:params.stroke_color = st.color_picker(tr("Stroke Color"), "#000000")with stroke_cols[1]:params.stroke_width = st.slider(tr("Stroke Width"), 0.0, 10.0, 1.5)+ saved_rounded_subtitle_background = config.ui.get(+ "rounded_subtitle_background", False+ )+ params.rounded_subtitle_background = st.checkbox(+ tr("Rounded Subtitle Background"),+ value=saved_rounded_subtitle_background,+ help=tr("Rounded Subtitle Background Help"),+ )+ config.ui["rounded_subtitle_background"] = params.rounded_subtitle_backgroundwith st.expander(tr("Click to show API Key management"), expanded=False):st.subheader(tr("Manage Pexels and Pixabay API Keys"))diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex dda0ca70..4a201e2a 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -71,6 +71,8 @@"Font Color": "Subtitle Font Color","Stroke Color": "Subtitle Outline Color","Stroke Width": "Subtitle Outline Width",+ "Rounded Subtitle Background": "Enable rounded translucent subtitle background",+ "Rounded Subtitle Background Help": "Disabled by default. When enabled, subtitle backgrounds use a rounded translucent style that better fits the text width.","Generate Video": "Generate Video","Video Script and Subject Cannot Both Be Empty": "Video Subject and Video Script cannot both be empty","Generating Video": "Generating video, please wait...",diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex 1f8f66af..15676aab 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -71,6 +71,8 @@"Font Color": "字幕颜色","Stroke Color": "描边颜色","Stroke Width": "描边粗细",+ "Rounded Subtitle Background": "启用圆角半透明字幕背景",+ "Rounded Subtitle Background Help": "默认关闭。开启后字幕背景会显示为更贴合文字宽度的圆角半透明样式。","Generate Video": "生成视频","Video Script and Subject Cannot Both Be Empty": "视频主题 和 视频文案,不能同时为空","Generating Video": "正在生成视频,请稍候...",