Skip to content

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

fix(subtitle): continue lines after character-split long words

Rudy Celeklic7fe964c0da3
diff --git a/app/services/video.py b/app/services/video.py
index ff0ee325..c9a03349 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -1377,8 +1377,11 @@ def wrap_text(text, max_width, font="Arial", fontsize=60):
if word_width <= max_width:
current = word
else:
- lines.extend(split_long_token(word))
- current = ""
+ # 最后一段仍未占满整行,后续单词应继续尝试接在它后面,
+ # 否则每个超长词之后都会多出一行。
+ pieces = split_long_token(word)
+ lines.extend(pieces[:-1])
+ current = pieces[-1] if pieces else ""
if current:
lines.append(current)
diff --git a/test/services/test_subtitle_wrap_long_token_tail.py b/test/services/test_subtitle_wrap_long_token_tail.py
new file mode 100644
index 00000000..68519003
--- /dev/null
+++ b/test/services/test_subtitle_wrap_long_token_tail.py
@@ -0,0 +1,42 @@
+from pathlib import Path
+
+from PIL import ImageFont
+
+from app.services.video import wrap_text
+
+FONT_PATH = str(
+ Path(__file__).resolve().parents[2] / "resource/fonts/BeVietnamPro-Medium.ttf"
+)
+
+
+def _width(font, text):
+ left, _, right, _ = font.getbbox(text)
+ return right - left
+
+
+def test_word_after_split_long_token_joins_its_last_fragment():
+ # A token wider than the line is split by character. Its last fragment
+ # does not fill the line, so the following short word must be placed
+ # beside it instead of always starting another subtitle line.
+ font = ImageFont.truetype(FONT_PATH, 60)
+ text = "Supercalifragilisticexpialidocious is"
+
+ wrapped, height = wrap_text(text, 400, font=FONT_PATH, fontsize=60)
+
+ lines = wrapped.splitlines()
+ assert lines[-1].endswith(" is")
+ assert "".join(lines).replace(" ", "") == text.replace(" ", "")
+ assert all(_width(font, line) <= 400 for line in lines)
+ ascent, descent = font.getmetrics()
+ assert height == len(lines) * (ascent + descent)
+
+
+def test_word_after_split_long_token_still_wraps_when_it_does_not_fit():
+ font = ImageFont.truetype(FONT_PATH, 60)
+ text = "Supercalifragilisticexpialidocious extraordinarily"
+
+ wrapped, _ = wrap_text(text, 400, font=FONT_PATH, fontsize=60)
+
+ lines = wrapped.splitlines()
+ assert all(_width(font, line) <= 400 for line in lines)
+ assert "".join(lines).replace(" ", "") == text.replace(" ", "")