利用 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
fix(subtitle): preserve manual line breaks when wrapping captions
Rudy Celekli964c10c02246
diff --git a/app/services/video.py b/app/services/video.pyindex 3df63dd3..a9d267cb 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -1222,6 +1222,18 @@ def wrap_text(text, max_width, font="Arial", fontsize=60):# 字幕换行必须在真正创建 TextClip 前完成,否则 MoviePy 只会按原始文本# 计算渲染区域。这里用 PIL 按当前字体和字号测量宽度,确保每一行都尽量# 控制在视频可用宽度内,避免大字号或中文长句直接溢出画面。+ if "\n" in text:+ # Hard breaks in SRT text are separate layout lines. Measuring a token+ # across a newline makes Pillow count both lines as one wide string,+ # then character wrapping can split an otherwise fitting word.+ wrapped_lines = [+ wrap_text(line, max_width, font=font, fontsize=fontsize)+ for line in text.split("\n")+ ]+ return "\n".join(line for line, _ in wrapped_lines), sum(+ height for _, height in wrapped_lines+ )+font = ImageFont.truetype(font, fontsize)max_width = int(max_width)diff --git a/test/services/test_subtitle_manual_wrap.py b/test/services/test_subtitle_manual_wrap.pynew file mode 100644index 00000000..60ff3a5e--- /dev/null+++ b/test/services/test_subtitle_manual_wrap.py@@ -0,0 +1,34 @@+from pathlib import Path++import pytest+from PIL import ImageFont+from moviepy import TextClip++from app.services import video+from app.utils import utils++[email protected]("text", ["SAFE TEXT\nMORE SAFE", "hello world\nwide text here"])+def test_manual_subtitle_lines_fit_without_rewrapping(text):+ font_path = str(Path(utils.font_dir()) / "MicrosoftYaHeiBold.ttc")+ font = ImageFont.truetype(font_path, 60)+ width = max(font.getbbox(line)[2] - font.getbbox(line)[0] for line in text.split("\n"))+ wrapped, height = video.wrap_text(text, width, font=font_path, fontsize=60)+ assert wrapped == text+ assert height == 2 * sum(font.getmetrics())+ with TextClip(text=wrapped, font=font_path, font_size=60, size=(width, None)) as rendered:+ with TextClip(text=text, font=font_path, font_size=60, size=(width, None)) as expected:+ assert rendered.h == expected.h+++def test_long_manual_line_wraps_without_splitting_the_next_line():+ font_path = str(Path(utils.font_dir()) / "MicrosoftYaHeiBold.ttc")+ font = ImageFont.truetype(font_path, 60)+ text = "hello world and more words\nSAFE TEXT"+ width = font.getbbox("SAFE TEXT")[2]+ wrapped, height = video.wrap_text(text, width, font=font_path, fontsize=60)+ assert wrapped.endswith("\nSAFE TEXT")+ assert " ".join(wrapped.split()) == " ".join(text.split())+ for line in wrapped.split("\n"):+ assert font.getbbox(line)[2] - font.getbbox(line)[0] <= width+ assert height == len(wrapped.split("\n")) * sum(font.getmetrics())