利用 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
feat(subtitle): add word-by-word display with pop-up spring animation
Farhan50e91230b264
diff --git a/app/models/schema.py b/app/models/schema.pyindex c4d12e10..293b7ad8 100644--- a/app/models/schema.py+++ b/app/models/schema.py@@ -121,7 +121,13 @@ class VideoParams(BaseModel):subtitle_enabled: Optional[bool] = Truesubtitle_position: Optional[str] = config.ui.get("subtitle_position", "bottom"- ) # top, bottom, center, custom+ ) # top, bottom, center, custom, two_thirds_bottom+ subtitle_display_mode: Optional[str] = config.ui.get(+ "subtitle_display_mode", "sentence"+ ) # sentence, word_by_word+ subtitle_animation: Optional[str] = config.ui.get(+ "subtitle_animation", "none"+ ) # none, pop_springcustom_position: float = config.ui.get("custom_position", 70.0)font_name: Optional[str] = "STHeitiMedium.ttc"text_fore_color: Optional[str] = "#FFFFFF"@@ -147,6 +153,10 @@ class SubtitleRequest(BaseModel):bgm_file: Optional[str] = ""bgm_volume: Optional[float] = 0.2subtitle_position: Optional[str] = config.ui.get("subtitle_position", "bottom")+ subtitle_display_mode: Optional[str] = config.ui.get(+ "subtitle_display_mode", "sentence"+ )+ subtitle_animation: Optional[str] = config.ui.get("subtitle_animation", "none")font_name: Optional[str] = "STHeitiMedium.ttc"text_fore_color: Optional[str] = "#FFFFFF"text_background_color: Union[bool, str] = Falsediff --git a/app/services/subtitle.py b/app/services/subtitle.pyindex 0af875ba..3d9d3d74 100644--- a/app/services/subtitle.py+++ b/app/services/subtitle.py@@ -19,7 +19,7 @@ initial_prompt = config.whisper.get("initial_prompt", "") or Nonemodel = None-def create(audio_file, subtitle_file: str = ""):+def create(audio_file, subtitle_file: str = "", word_level: bool = False):global modelif WhisperModel is None:logger.warning("faster_whisper not available, skipping whisper subtitle generation")@@ -81,6 +81,13 @@ def create(audio_file, subtitle_file: str = ""):)for segment in segments:+ if word_level and segment.words:+ for word in segment.words:+ cleaned_word = word.word.strip()+ if cleaned_word:+ recognized(cleaned_word, word.start, word.end)+ continue+words_idx = 0words_len = len(segment.words)diff --git a/app/services/task.py b/app/services/task.pyindex 6a96aae8..9e4bd98c 100644--- a/app/services/task.py+++ b/app/services/task.py@@ -596,9 +596,14 @@ def generate_subtitle(task_id, params, video_script, sub_maker, audio_file):)return ""+ is_word_level = getattr(params, "subtitle_display_mode", "sentence") == "word_by_word"+if subtitle_provider == "edge":voice.create_subtitle(- text=video_script, sub_maker=sub_maker, subtitle_file=subtitle_path+ text=video_script,+ sub_maker=sub_maker,+ subtitle_file=subtitle_path,+ word_level=is_word_level,)if not os.path.exists(subtitle_path):# Edge 字幕偶尔会因为时间轴与文案无法匹配而没有产出文件。这里不能@@ -612,9 +617,14 @@ def generate_subtitle(task_id, params, video_script, sub_maker, audio_file):return ""if subtitle_provider == "whisper":- subtitle.create(audio_file=audio_file, subtitle_file=subtitle_path)- logger.info("\n\n## correcting subtitle")- subtitle.correct(subtitle_file=subtitle_path, video_script=video_script)+ subtitle.create(+ audio_file=audio_file,+ subtitle_file=subtitle_path,+ word_level=is_word_level,+ )+ if not is_word_level:+ logger.info("\n\n## correcting subtitle")+ subtitle.correct(subtitle_file=subtitle_path, video_script=video_script)subtitle_lines = subtitle.file_to_subtitles(subtitle_path)if not subtitle_lines:diff --git a/app/services/video.py b/app/services/video.pyindex 0a33dae8..93ea468e 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -1239,10 +1239,48 @@ def generate_video(_clip = _clip.with_start(subtitle_item[0][0])_clip = _clip.with_end(subtitle_item[0][1])_clip = _clip.with_duration(duration)++ # Pop-up spring animation effect (scales from 0 -> 1.15 -> 1.0 like a spring)+ anim_type = getattr(params, "subtitle_animation", "none")+ if anim_type in ("pop_spring", "spring", "pop"):+ anim_dur = min(0.18, duration) if duration > 0 else 0.18++ def _spring_scale(t_rel):+ # t_rel is relative time from clip start (0 to anim_dur)+ p = t_rel / anim_dur+ # Damped spring formula: 1 - exp(-6*p) * cos(6*pi*p)+ return 1.0 - math.exp(-6.0 * p) * math.cos(2.5 * math.pi * p)++ def _apply_spring_transform(get_frame, t):+ orig_frame = get_frame(t)+ if anim_dur <= 0:+ return orig_frame+ t_rel = max(0.0, min(t, anim_dur))+ if t_rel >= anim_dur:+ return orig_frame+ scale = _spring_scale(t_rel)+ scale = max(0.05, min(scale, 1.35))+ h, w = orig_frame.shape[:2]+ new_w = max(1, int(round(w * scale)))+ new_h = max(1, int(round(h * scale)))+ im = Image.fromarray(orig_frame)+ resized_im = im.resize((new_w, new_h), Image.Resampling.BILINEAR)+ canvas = Image.new("RGBA", (w, h), (0, 0, 0, 0))+ offset_x = (w - new_w) // 2+ offset_y = (h - new_h) // 2+ canvas.paste(resized_im, (offset_x, offset_y))+ return np.asarray(canvas)++ _clip = _clip.transform(_apply_spring_transform)+if params.subtitle_position == "bottom":_clip = _clip.with_position(("center", video_height * 0.95 - _clip.h))elif params.subtitle_position == "top":_clip = _clip.with_position(("center", video_height * 0.05))+ elif params.subtitle_position in ("two_thirds_bottom", "two_thirds", "2/3_bottom"):+ # 2/3 from the bottom = 1/3 from the top: y = (video_height - _clip.h) * (1/3)+ y_two_thirds = (video_height - _clip.h) / 3.0+ _clip = _clip.with_position(("center", y_two_thirds))elif params.subtitle_position == "custom":# Ensure the subtitle is fully within the screen boundsmargin = 10 # Additional margin, in pixelsdiff --git a/app/services/voice.py b/app/services/voice.pyindex c97d42ea..053191c7 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -2110,16 +2110,82 @@ def _build_subtitle_items_from_legacy_submaker(return sub_items-def create_subtitle(sub_maker: SubMaker, text: str, subtitle_file: str):+def _build_subtitle_items_from_edge_cues_words(sub_maker: SubMaker) -> list[str]:+ """+ Directly format edge_tts cues into single-word / cue-level SRT items.+ """+ formatter = _build_subtitle_formatter()+ sub_items = []+ sub_index = 0+ for cue in sub_maker.cues:+ cue_text = unescape(cue.content).strip()+ if not cue_text:+ continue+ sub_index += 1+ start_time = int(cue.start.total_seconds() * 10000000)+ end_time = int(cue.end.total_seconds() * 10000000)+ sub_items.append(+ formatter(+ idx=sub_index,+ start_time=start_time,+ end_time=end_time,+ sub_text=cue_text,+ )+ )+ return sub_items+++def _build_subtitle_items_from_legacy_submaker_words(sub_maker: SubMaker) -> list[str]:+ """+ Directly format legacy submaker into single-word SRT items.+ """+ formatter = _build_subtitle_formatter()+ sub_items = []+ sub_index = 0+ legacy_offsets = getattr(sub_maker, "offset", [])+ legacy_subs = getattr(sub_maker, "subs", [])+ for offset, sub in zip(legacy_offsets, legacy_subs):+ cue_text = unescape(sub).strip()+ if not cue_text:+ continue+ sub_index += 1+ start_time, end_time = offset+ sub_items.append(+ formatter(+ idx=sub_index,+ start_time=start_time,+ end_time=end_time,+ sub_text=cue_text,+ )+ )+ return sub_items+++def create_subtitle(+ sub_maker: SubMaker,+ text: str,+ subtitle_file: str,+ word_level: bool = False,+):"""优化字幕文件1. 将字幕文件按照标点符号分割成多行2. 逐行匹配字幕文件中的文本3. 生成新的字幕文件+ 如果 word_level 为 True,直接输出逐词单条字幕。"""text = _format_text(text)- script_lines = utils.split_string_by_punctuations(text)try:+ if word_level:+ if hasattr(sub_maker, "cues") and sub_maker.cues:+ sub_items = _build_subtitle_items_from_edge_cues_words(sub_maker)+ else:+ sub_items = _build_subtitle_items_from_legacy_submaker_words(sub_maker)+ if sub_items:+ _write_subtitle_items(sub_items, subtitle_file)+ return++ script_lines = utils.split_string_by_punctuations(text)if hasattr(sub_maker, "cues") and sub_maker.cues:sub_items = _build_subtitle_items_from_edge_cues(sub_maker, script_lines)else:diff --git a/webui/Main.py b/webui/Main.pyindex 4faf3fd1..22efd3de 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -132,6 +132,8 @@ DEFAULT_SUBTITLE_SETTINGS = {"subtitle_enabled": True,"font_name": "MicrosoftYaHeiBold.ttc","subtitle_position": "bottom",+ "subtitle_display_mode": "sentence",+ "subtitle_animation": "none","custom_position": 70.0,"text_fore_color": "#FFFFFF","font_size": 60,@@ -1383,6 +1385,12 @@ def _apply_restored_params(params):_set_stable_widget_value("subtitle_position_select", params.get("subtitle_position") or "bottom")+ _set_stable_widget_value(+ "subtitle_display_mode_select", params.get("subtitle_display_mode") or "sentence"+ )+ _set_stable_widget_value(+ "subtitle_animation_select", params.get("subtitle_animation") or "none"+ )custom_position = min(100.0, max(0.0, float(params.get("custom_position", 70.0))))st.session_state["custom_position_input"] = str(custom_position)st.session_state["font_color_picker"] = params.get("text_fore_color") or "#FFFFFF"@@ -2283,6 +2291,8 @@ def reset_subtitle_settings():st.session_state["subtitle_enabled_checkbox"] = defaults["subtitle_enabled"]_set_stable_widget_value("font_name_select", defaults["font_name"])_set_stable_widget_value("subtitle_position_select", defaults["subtitle_position"])+ _set_stable_widget_value("subtitle_display_mode_select", defaults.get("subtitle_display_mode", "sentence"))+ _set_stable_widget_value("subtitle_animation_select", defaults.get("subtitle_animation", "none"))st.session_state["custom_position_input"] = str(defaults["custom_position"])st.session_state["font_color_picker"] = defaults["text_fore_color"]st.session_state["font_size_slider"] = defaults["font_size"]@@ -2303,6 +2313,8 @@ def reset_subtitle_settings():"subtitle_enabled","font_name","subtitle_position",+ "subtitle_display_mode",+ "subtitle_animation","custom_position","text_fore_color","font_size",@@ -2312,7 +2324,8 @@ def reset_subtitle_settings():"subtitle_background_color","rounded_subtitle_background",):- _set_runtime_config("ui", key, defaults[key])+ if key in defaults:+ _set_runtime_config("ui", key, defaults[key])@st.dialog(tr("Final Prompt Preview"), width="large")@@ -6213,6 +6226,7 @@ def _render_subtitle_settings(panel, params):(tr("Top"), "top"),(tr("Center"), "center"),(tr("Bottom"), "bottom"),+ (tr("2/3 from Bottom"), "two_thirds_bottom"),(tr("Custom"), "custom"),]saved_subtitle_position = config.ui.get(@@ -6230,12 +6244,64 @@ def _render_subtitle_settings(panel, params):key="subtitle_position_select",format_func=lambda value: dict((v, label) for label, v in subtitle_positions- )[value],+ ).get(value, value),disabled=subtitle_settings_disabled,)params.subtitle_position = selected_subtitle_position_set_runtime_config("ui", "subtitle_position", params.subtitle_position)+ # Subtitle Display Mode (Sentence vs Single Word)+ subtitle_display_modes = [+ (tr("Sentence by Sentence"), "sentence"),+ (tr("Single Word (Word by Word)"), "word_by_word"),+ ]+ saved_display_mode = config.ui.get(+ "subtitle_display_mode", DEFAULT_SUBTITLE_SETTINGS.get("subtitle_display_mode", "sentence")+ )+ saved_mode_idx = 0+ for i, (_, mode_val) in enumerate(subtitle_display_modes):+ if mode_val == saved_display_mode:+ saved_mode_idx = i+ break+ selected_display_mode = stable_selectbox(+ tr("Display Mode"),+ options=[val for _, val in subtitle_display_modes],+ default_value=subtitle_display_modes[saved_mode_idx][1],+ key="subtitle_display_mode_select",+ format_func=lambda value: dict(+ (v, label) for label, v in subtitle_display_modes+ ).get(value, value),+ disabled=subtitle_settings_disabled,+ )+ params.subtitle_display_mode = selected_display_mode+ _set_runtime_config("ui", "subtitle_display_mode", params.subtitle_display_mode)++ # Subtitle Animation (None vs Pop Spring)+ subtitle_animations = [+ (tr("None"), "none"),+ (tr("Pop Up (Spring)"), "pop_spring"),+ ]+ saved_anim = config.ui.get(+ "subtitle_animation", DEFAULT_SUBTITLE_SETTINGS.get("subtitle_animation", "none")+ )+ saved_anim_idx = 0+ for i, (_, anim_val) in enumerate(subtitle_animations):+ if anim_val == saved_anim:+ saved_anim_idx = i+ break+ selected_anim = stable_selectbox(+ tr("Subtitle Animation"),+ options=[val for _, val in subtitle_animations],+ default_value=subtitle_animations[saved_anim_idx][1],+ key="subtitle_animation_select",+ format_func=lambda value: dict(+ (v, label) for label, v in subtitle_animations+ ).get(value, value),+ disabled=subtitle_settings_disabled,+ )+ params.subtitle_animation = selected_anim+ _set_runtime_config("ui", "subtitle_animation", params.subtitle_animation)+if params.subtitle_position == "custom":saved_custom_position = config.ui.get("custom_position", DEFAULT_SUBTITLE_SETTINGS["custom_position"]diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex a545e4f5..e0979909 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -177,6 +177,13 @@"Top": "Top","Center": "Center","Bottom": "Bottom (Recommended)",+ "2/3 from Bottom": "2/3 from Bottom",+ "Display Mode": "Display Mode",+ "Sentence by Sentence": "Sentence by Sentence",+ "Single Word (Word by Word)": "Single Word (Word by Word)",+ "Subtitle Animation": "Subtitle Animation",+ "None": "None",+ "Pop Up (Spring)": "Pop Up (Spring)","Custom": "Custom","Custom Position (% from top)": "Custom Position (% from top)","Please enter a value between 0 and 100": "Please enter a value between 0 and 100",@@ -478,4 +485,4 @@"OFox Vendor Volcengine": "Volcano Engine (Mainland China)","OFox Vendor Auto": "Auto (gateway load balancing)"}-}+}\ No newline at end of filediff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex da5d690d..508ddad3 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -177,6 +177,13 @@"Top": "顶部","Center": "中间","Bottom": "底部(推荐)",+ "2/3 from Bottom": "距底部 2/3 (上部 1/3)",+ "Display Mode": "显示模式",+ "Sentence by Sentence": "按句显示",+ "Single Word (Word by Word)": "逐词单字跳显 (Word by Word)",+ "Subtitle Animation": "字幕动画",+ "None": "无动画",+ "Pop Up (Spring)": "弹性弹出 (Pop Up Spring)","Custom": "自定义位置(70,表示离顶部70%的位置)","Custom Position (% from top)": "自定义位置(距顶部百分比)","Please enter a value between 0 and 100": "请输入 0 到 100 之间的数值",@@ -478,4 +485,4 @@"OFox Vendor Volcengine": "火山引擎(中国大陆)","OFox Vendor Auto": "自动分发(网关调度)"}-}+}\ No newline at end of file