Skip to content

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

fix: avoid repeated material selection across batch videos

giteeProda185e0a1e45
diff --git a/app/services/task.py b/app/services/task.py
index 776229f0..161a0cab 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -1,3 +1,4 @@
+import json
import math
import os
import re
@@ -833,19 +834,52 @@ def _record_loomloom_run_reference(
return None
+def _get_material_source_groups(task_id: str, video_paths: list[str]) -> dict[str, str]:
+ """Recover keyword groups from the downloaded material manifest."""
+ try:
+ with open(path.join(utils.task_dir(task_id), "script.json"), encoding="utf-8") as file:
+ payload = json.load(file)
+ groups = {
+ record["local_file"]: record["search_term"]
+ for record in payload.get("material_sources", [])
+ if isinstance(record, dict)
+ and isinstance(record.get("local_file"), str)
+ and isinstance(record.get("search_term"), str)
+ and record["search_term"]
+ }
+ return {
+ file: groups[path.basename(file)]
+ for file in video_paths
+ if path.basename(file) in groups
+ }
+ except (OSError, ValueError, AttributeError, TypeError) as exc:
+ logger.warning(f"Cannot read material keyword groups: task_id={task_id}, error={exc}")
+ return {}
+
+
def generate_final_videos(
task_id, params, downloaded_videos, audio_file, subtitle_path, audio_duration
):
final_video_paths = []
combined_video_paths = []
warnings = []
+ allocate_batch_materials = params.video_count > 1 and params.video_source in {
+ "pexels", "pixabay", "coverr", "local"
+ }
+ source_usage = {}
+ material_selections = []
+ source_groups = (
+ _get_material_source_groups(task_id, downloaded_videos)
+ if (allocate_batch_materials and params.match_materials_to_script
+ and params.video_source != "local")
+ else {}
+ )
video_music_provider = _VIDEO_MUSIC_PROVIDERS.get(params.bgm_type)
video_music_requested = (
video_music_provider is not None
and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
)
- # 多视频生成默认会打散素材以增加差异;但“按文案顺序匹配素材”追求的是
- # 时间线稳定性和可解释性,所以开启后所有输出都使用顺序拼接。
+ # Matching preserves keyword order; batch allocation varies each keyword's candidates.
if params.match_materials_to_script:
video_concat_mode = VideoConcatMode.sequential
elif params.video_count == 1:
@@ -861,6 +895,15 @@ def generate_final_videos(
utils.task_dir(task_id), f"combined-{index}.mp4"
)
logger.info(f"\n\n## combining video: {index} => {combined_video_path}")
+ used_video_paths = []
+ batch_options = (
+ {
+ "source_usage": source_usage,
+ "source_groups": source_groups,
+ "used_video_paths": used_video_paths,
+ }
+ if allocate_batch_materials else {}
+ )
video.combine_videos(
combined_video_path=combined_video_path,
video_paths=downloaded_videos,
@@ -872,7 +915,29 @@ def generate_final_videos(
max_clip_duration=params.video_clip_duration,
threads=params.n_threads,
clip_speed=params.video_clip_speed,
+ **batch_options,
)
+ if allocate_batch_materials:
+ selected_sources = list(dict.fromkeys(used_video_paths))
+ reused_sources = [file for file in selected_sources if source_usage.get(file, 0)]
+ for file in selected_sources:
+ source_usage[file] = source_usage.get(file, 0) + 1
+ material_selections.append({
+ "video_index": index,
+ "local_files": [path.basename(file) for file in used_video_paths],
+ "reused_files": [path.basename(file) for file in reused_sources],
+ })
+ task_artifacts.patch_script_data(task_id, material_selections=material_selections)
+ logger.info(
+ f"Batch material allocation: video_index={index}, "
+ f"sources={len(selected_sources)}, reused_sources={len(reused_sources)}"
+ )
+ if reused_sources:
+ warnings.append({
+ "code": "batch_materials_reused",
+ "video_index": index,
+ "count": len(reused_sources),
+ })
_progress += 50 / params.video_count / 2
sm.state.update_task(task_id, progress=_progress)
diff --git a/app/services/video.py b/app/services/video.py
index 19d3fa0a..53830384 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -198,6 +198,8 @@ def is_material_resolution_acceptable(width: int, height: int) -> bool:
def _prioritize_unique_source_clips(
subclipped_items: List[SubClippedVideoClip],
concat_mode: VideoConcatMode,
+ source_usage: dict[str, int] | None = None,
+ source_groups: dict[str, str] | None = None,
) -> List[SubClippedVideoClip]:
"""
优先让每个源素材只出现一次,降低成片里同一素材反复出现的概率。
@@ -214,7 +216,26 @@ def _prioritize_unique_source_clips(
concat_mode_value = getattr(concat_mode, "value", concat_mode)
if concat_mode_value != VideoConcatMode.random.value:
- return subclipped_items
+ if source_usage is None:
+ return subclipped_items
+ if not source_groups:
+ return sorted(
+ subclipped_items,
+ key=lambda item: source_usage.get(item.source_file_path, 0),
+ )
+ # Keep keyword rounds in order while rotating candidates within each keyword.
+ groups = {}
+ for item in subclipped_items:
+ key = source_groups.get(item.source_file_path, item.source_file_path)
+ groups.setdefault(key, []).append(item)
+ for items in groups.values():
+ items.sort(key=lambda item: source_usage.get(item.source_file_path, 0))
+ return [
+ item
+ for row in itertools.zip_longest(*groups.values())
+ for item in row
+ if item is not None
+ ]
grouped_items: dict[str, list[SubClippedVideoClip]] = {}
for item in subclipped_items:
@@ -229,6 +250,10 @@ def _prioritize_unique_source_clips(
random.shuffle(primary_items)
random.shuffle(overflow_items)
+ if source_usage is not None:
+ # Stable sorting retains randomness among equally used sources.
+ primary_items.sort(key=lambda item: source_usage.get(item.source_file_path, 0))
+ overflow_items.sort(key=lambda item: source_usage.get(item.source_file_path, 0))
logger.info(
"prioritized unique video materials, "
f"sources: {len(grouped_items)}, "
@@ -689,6 +714,9 @@ def combine_videos(
threads: int = 2,
clip_speed: float = 1.0,
video_fit_mode: VideoFitMode = VideoFitMode.cover,
+ source_usage: dict[str, int] | None = None,
+ source_groups: dict[str, str] | None = None,
+ used_video_paths: List[str] | None = None,
) -> str:
audio_clip = AudioFileClip(audio_file)
try:
@@ -760,6 +788,8 @@ def combine_videos(
subclipped_items = _prioritize_unique_source_clips(
subclipped_items=subclipped_items,
concat_mode=video_concat_mode,
+ **({"source_usage": source_usage, "source_groups": source_groups}
+ if source_usage is not None else {}),
)
logger.debug(f"total subclipped items: {len(subclipped_items)}")
@@ -896,6 +926,14 @@ def combine_videos(
output_dir=output_dir,
max_duration=audio_duration,
)
+ if used_video_paths is not None:
+ # Exclude safety-margin clips that FFmpeg trims entirely from the output.
+ elapsed = 0.0
+ for clip in processed_clips:
+ if elapsed >= audio_duration:
+ break
+ used_video_paths.append(clip.source_file_path)
+ elapsed += clip.duration
# clean temp files
delete_files(clip_files)
diff --git a/test/services/test_batch_material_allocation.py b/test/services/test_batch_material_allocation.py
new file mode 100644
index 00000000..41a8cb01
--- /dev/null
+++ b/test/services/test_batch_material_allocation.py
@@ -0,0 +1,196 @@
+import json
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from app.models.schema import VideoParams
+from app.services import task, video
+
+
+class FakeClip:
+ size = (1080, 1920)
+ w, h = size
+
+ def __init__(self, duration):
+ self.duration = duration
+
+ def close(self):
+ pass
+
+ def subclipped(self, start, end):
+ return FakeClip(end - start)
+
+ def with_speed_scaled(self, factor):
+ return FakeClip(self.duration / factor)
+
+
+def render_batch(tmp_path):
+ def run(*, sources, duration=5.9, match=True, count=3, speed=1,
+ source="pexels", subtitle_enabled=True, voice_name="test-voice",
+ fail_first=False):
+ task_id = "allocation-test"
+ manifest = tmp_path / "script.json"
+ manifest.write_text(json.dumps({"material_sources": [
+ {"local_file": name, "search_term": term}
+ for name, (term, _) in sources.items()
+ ]}), encoding="utf-8")
+ params = VideoParams(
+ video_subject="test", video_source=source, video_count=count,
+ match_materials_to_script=match, video_clip_duration=3,
+ video_clip_speed=speed, bgm_type="", subtitle_enabled=subtitle_enabled,
+ voice_name=voice_name,
+ )
+ writes = 0
+
+ def write_clip(*args, **kwargs):
+ nonlocal writes
+ writes += 1
+ if fail_first and writes == 1:
+ raise OSError("Unreadable source frames")
+
+ with (
+ patch.object(task.utils, "task_dir", return_value=str(tmp_path)),
+ patch.object(video, "AudioFileClip", return_value=FakeClip(duration)),
+ patch.object(video, "_open_video_clip_quietly",
+ side_effect=lambda name: FakeClip(sources[name][1])),
+ patch.object(video, "_write_videofile_with_codec_fallback", side_effect=write_clip),
+ patch.object(video, "concat_video_clips_with_ffmpeg"),
+ patch.object(video, "delete_files"),
+ patch.object(video, "generate_video") as final_render,
+ patch.object(task.sm.state, "update_task"),
+ ):
+ result = task.generate_final_videos(
+ task_id, params, list(sources), "audio.mp3",
+ "subtitle.srt" if subtitle_enabled else "", duration,
+ )
+ return SimpleNamespace(
+ selections=json.loads(manifest.read_text()).get("material_selections", []),
+ warnings=result[2], outputs=result[0], final_render=final_render,
+ )
+ return run
+
+
[email protected]("subtitle_enabled,voice_name", [
+ (True, "zh-CN-XiaoxiaoNeural"), (False, "en-US-JennyNeural"),
+])
+def test_matched_batch_rotates_candidates_in_keyword_order(
+ render_batch, subtitle_enabled, voice_name,
+):
+ sources = {
+ f"{term}-{index}.mp4": (term, 6)
+ for index in range(3) for term in ("room", "window")
+ }
+ result = render_batch(sources=sources, subtitle_enabled=subtitle_enabled,
+ voice_name=voice_name)
+ assert [item["local_files"] for item in result.selections] == [
+ [f"room-{index}.mp4", f"window-{index}.mp4"] for index in range(3)
+ ]
+ assert result.warnings == []
+ assert len(result.outputs) == 3
+ assert result.final_render.call_count == 3
+
+
[email protected]("source", ["pexels", "pixabay", "coverr", "local"])
+def test_random_batch_uses_new_sources_before_reuse(render_batch, source):
+ sources = {f"clip-{i}.mp4": ("room", 12) for i in range(6)}
+ result = render_batch(sources=sources, match=False, source=source)
+ selected = [name for item in result.selections for name in item["local_files"]]
+ assert len(selected) == len(set(selected)) == 6
+ assert result.warnings == []
+
+
+def test_shortage_reuses_only_exhausted_keyword_candidates(render_batch):
+ sources = {
+ "room-0.mp4": ("room", 6), "window.mp4": ("window", 6),
+ "room-1.mp4": ("room", 6), "room-2.mp4": ("room", 6),
+ }
+ result = render_batch(sources=sources)
+ assert [item["local_files"] for item in result.selections] == [
+ [f"room-{i}.mp4", "window.mp4"] for i in range(3)
+ ]
+ assert result.warnings == [
+ {"code": "batch_materials_reused", "video_index": i, "count": 1}
+ for i in (2, 3)
+ ]
+
+
[email protected]("speed,expected_first_count", [(0.5, 2), (2, 4)])
+def test_allocation_tracks_actual_duration_and_speed(render_batch, speed, expected_first_count):
+ sources = {f"clip-{i}.mp4": ("room", 3) for i in range(8)}
+ result = render_batch(sources=sources, duration=5.9, speed=speed, count=2)
+ first, second = [item["local_files"] for item in result.selections]
+ assert len(first) == expected_first_count
+ assert set(first).isdisjoint(second)
+ assert result.warnings == []
+
+
+def test_safety_margin_does_not_consume_trimmed_source(render_batch):
+ sources = {f"clip-{i}.mp4": ("room", 3) for i in range(4)}
+ result = render_batch(sources=sources, duration=6, count=2)
+ assert [item["local_files"] for item in result.selections] == [
+ ["clip-0.mp4", "clip-1.mp4"], ["clip-2.mp4", "clip-3.mp4"],
+ ]
+ assert result.warnings == []
+
+
+def test_short_sources_and_looping_still_fill_narration(render_batch):
+ sources = {"short.mp4": ("room", 1), "long.mp4": ("window", 3)}
+ result = render_batch(sources=sources, count=2)
+ assert result.selections[0]["local_files"] == [
+ "short.mp4", "long.mp4", "short.mp4", "long.mp4",
+ ]
+ assert result.warnings == [
+ {"code": "batch_materials_reused", "video_index": 2, "count": 2},
+ ]
+
+
+def test_failed_clip_does_not_count_as_used(render_batch):
+ sources = {f"clip-{i}.mp4": ("room", 3) for i in range(3)}
+ result = render_batch(sources=sources, count=2, fail_first=True)
+ assert [item["local_files"] for item in result.selections] == [
+ ["clip-1.mp4", "clip-2.mp4"], ["clip-0.mp4", "clip-1.mp4"],
+ ]
+ assert result.warnings == [
+ {"code": "batch_materials_reused", "video_index": 2, "count": 1},
+ ]
+
+
+def test_single_output_preserves_existing_selection(render_batch):
+ result = render_batch(sources={"clip.mp4": ("room", 6)}, count=1)
+ assert result.selections == []
+ assert result.warnings == []
+
+
+def test_generated_video_sources_do_not_receive_batch_allocation(tmp_path):
+ for source in ("wavespeed", "loomloom", "volcengine_seedance"):
+ with (
+ patch.object(task.utils, "task_dir", return_value=str(tmp_path)),
+ patch.object(video, "combine_videos") as combine,
+ patch.object(video, "generate_video"),
+ patch.object(task.sm.state, "update_task"),
+ ):
+ task.generate_final_videos(
+ "test", VideoParams(video_subject="test", video_source=source,
+ video_count=2, bgm_type=""),
+ ["clip.mp4"], "audio.mp3", "", 6,
+ )
+ assert all("source_usage" not in call.kwargs for call in combine.call_args_list)
+
+
+def test_random_allocation_keeps_unique_sources_ahead_of_extra_slices():
+ clips = [video.SubClippedVideoClip(name, start, start + 3, source_file_path=name)
+ for name in ("used.mp4", "new.mp4") for start in (0, 3)]
+ ordered = video._prioritize_unique_source_clips(
+ clips, video.VideoConcatMode.random,
+ source_usage={"used.mp4": 1},
+ )
+ assert [clip.source_file_path for clip in ordered] == [
+ "new.mp4", "used.mp4", "new.mp4", "used.mp4",
+ ]
+
+
+def test_missing_manifest_falls_back_to_ungrouped_allocation(tmp_path):
+ with patch.object(task.utils, "task_dir", return_value=str(tmp_path)):
+ assert task._get_material_source_groups("missing", ["clip.mp4"]) == {}
diff --git a/test/services/test_webui_task.py b/test/services/test_webui_task.py
index 6369db98..37258e17 100644
--- a/test/services/test_webui_task.py
+++ b/test/services/test_webui_task.py
@@ -182,6 +182,7 @@ def test_completed_task_renders_subject_named_video_download(
self.session_state = {}
self.downloads = []
self.videos = []
+ self.warnings = []
def columns(self, count):
return [FakeColumn() for _ in range(count)]
@@ -195,8 +196,8 @@ def test_completed_task_renders_subject_named_video_download(
def success(self, _message):
pass
- def warning(self, _message):
- pass
+ def warning(self, message):
+ self.warnings.append(message)
def error(self, _message):
pass
@@ -215,7 +216,10 @@ def test_completed_task_renders_subject_named_video_download(
"os": os,
"re": re,
"st": fake_st,
- "tr": lambda key: key,
+ "tr": lambda key: (
+ "Video {index} reused {count} source clips."
+ if key == "Batch Material Reuse Warning" else key
+ ),
"_render_generation_logs": lambda _task_id: None,
}
module = ast.fix_missing_locations(ast.Module(body=selected_nodes, type_ignores=[]))
@@ -227,12 +231,15 @@ def test_completed_task_renders_subject_named_video_download(
"state": const.TASK_STATE_COMPLETE,
"progress": 100,
"videos": [str(video_path)],
- "warnings": [],
+ "warnings": [
+ {"code": "batch_materials_reused", "video_index": 2, "count": 3}
+ ],
"video_subject": "A day: in / Shanghai?",
},
)
assert fake_st.videos == [str(video_path)]
+ assert fake_st.warnings == ["Video 2 reused 3 source clips."]
assert fake_st.downloads == [
(
"Download Video",
diff --git a/webui/Main.py b/webui/Main.py
index a827d033..8e7faeb7 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -1930,7 +1930,13 @@ def _render_generation_task_snapshot(task_id, task):
st.success(tr("Video Generation Completed"))
for warning in task.get("warnings") or []:
- if isinstance(warning, Mapping) and warning.get("code") == "sonilo_bgm_failed":
+ if isinstance(warning, Mapping) and warning.get("code") == "batch_materials_reused":
+ st.warning(
+ tr("Batch Material Reuse Warning").format(
+ index=warning.get("video_index", ""), count=warning.get("count", 0)
+ )
+ )
+ elif isinstance(warning, Mapping) and warning.get("code") == "sonilo_bgm_failed":
st.warning(
tr("Sonilo BGM Fallback Warning").format(
index=warning.get("video_index", "")
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index 64d7c48a..1dfaa73c 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -157,6 +157,7 @@
"Sonilo Connection Test Succeeded": "Sonilo connection succeeded.",
"Sonilo Connection Test Failed": "Sonilo connection failed: {error}",
"Sonilo BGM Fallback Warning": "Video {index} was generated without Sonilo background music because the music request failed.",
+ "Batch Material Reuse Warning": "Video {index} reused {count} source clips from earlier videos because the available candidates could not fill this video without reuse under the current ordering and duration settings.",
"ElevenLabs Background Music": "Automatic Video-Matched Music (ElevenLabs AI)",
"ElevenLabs Music API Key": "ElevenLabs API Key ([Get API Key](https://elevenlabs.io/app/settings/api-keys))",
"ElevenLabs API Key Help": "This key is shared with ElevenLabs TTS. It is masked and saved in your local config.toml.",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index d789b357..b90de958 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -157,6 +157,7 @@
"Sonilo Connection Test Succeeded": "Sonilo 连接成功。",
"Sonilo Connection Test Failed": "Sonilo 连接失败:{error}",
"Sonilo BGM Fallback Warning": "第 {index} 条视频的 Sonilo 配乐生成失败,已降级生成无背景音乐的视频。",
+ "Batch Material Reuse Warning": "第 {index} 条视频复用了前面成片中的 {count} 个素材:现有候选素材在当前顺序和时长要求下不足以完全错开。",
"ElevenLabs Background Music": "根据画面自动配乐(ElevenLabs AI)",
"ElevenLabs Music API Key": "ElevenLabs API 密钥([点击获取](https://elevenlabs.io/app/settings/api-keys))",
"ElevenLabs API Key Help": "该 Key 与 ElevenLabs 配音共用,输入内容会以密码形式显示,并保存到本机 config.toml。",