Skip to content

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

perf(video): add concurrency controls (#1407)

keepliu28115792b6d5a9
diff --git a/app/services/material.py b/app/services/material.py
index fe774bba..c664276b 100644
--- a/app/services/material.py
+++ b/app/services/material.py
@@ -1,4 +1,5 @@
import base64
+from concurrent.futures import ThreadPoolExecutor
import io
import math
import os
@@ -38,6 +39,19 @@ _api_key_lock = threading.Lock()
# Short stock and generated clips should stay well below this conservative cap.
MAX_VIDEO_DOWNLOAD_BYTES = 512 * 1024 * 1024
+# 库存素材的搜索与下载都是网络等待型任务。这里用小并发避免拖垮上游 API,
+# 同时把串行等待压缩成一批请求的总等待时间。
+_MATERIAL_SEARCH_CONCURRENCY = 4
+_MATERIAL_DOWNLOAD_CONCURRENCY = 4
+
+
+def _get_material_concurrency() -> int:
+ try:
+ concurrency = int(config.app.get("material_concurrency", _MATERIAL_DOWNLOAD_CONCURRENCY))
+ except (TypeError, ValueError):
+ concurrency = _MATERIAL_DOWNLOAD_CONCURRENCY
+ return max(1, min(8, concurrency))
+
class _OpenAIImageDecodeError(ValueError):
"""表示兼容接口返回的字节无法解码为图片,不包含本地文件写入故障。"""
@@ -1852,6 +1866,141 @@ def _search_videos_with_cache(
return items
+def _search_terms_in_parallel(
+ search_terms: List[str],
+ search_videos: Callable[[str, int, VideoAspect], List[MaterialInfo]],
+ minimum_duration: int,
+ video_aspect: VideoAspect,
+) -> list[tuple[str, List[MaterialInfo]]]:
+ """并行搜索关键词,失败的关键词返回空结果,不阻断其它素材。"""
+ if not search_terms:
+ return []
+
+ workers = min(_get_material_concurrency(), len(search_terms))
+ if workers == 1:
+ results = []
+ for search_term in search_terms:
+ items = search_videos(
+ search_term=search_term,
+ minimum_duration=minimum_duration,
+ video_aspect=video_aspect,
+ )
+ logger.info(f"found {len(items)} videos for '{search_term}'")
+ results.append((search_term, items))
+ return results
+
+ futures = {}
+ with ThreadPoolExecutor(
+ max_workers=workers,
+ thread_name_prefix="material-search",
+ ) as executor:
+ for search_term in search_terms:
+ futures[executor.submit(
+ search_videos,
+ search_term,
+ minimum_duration,
+ video_aspect,
+ )] = search_term
+
+ results = []
+ for future in futures:
+ search_term = futures[future]
+ try:
+ items = future.result()
+ except Exception as exc:
+ logger.error(
+ "failed to search material videos: "
+ f"search_term={search_term!r}, "
+ f"error={type(exc).__name__}, detail={exc}"
+ )
+ items = []
+ logger.info(f"found {len(items)} videos for '{search_term}'")
+ results.append((search_term, items))
+ return results
+
+
+def _download_materials_in_parallel(
+ materials: List[tuple[str, MaterialInfo]],
+ material_directory: str,
+) -> list[tuple[str, MaterialInfo, str]]:
+ """并行下载一轮素材,保留调用方传入的候选顺序。"""
+ if not materials:
+ return []
+
+ workers = min(_get_material_concurrency(), len(materials))
+ if workers == 1:
+ downloaded = []
+ for search_term, item in materials:
+ try:
+ saved_video_path = save_video(
+ video_url=item.url,
+ save_dir=material_directory,
+ )
+ except Exception as exc:
+ logger.error(
+ "failed to download material video: "
+ f"provider={item.provider}, "
+ f"error={type(exc).__name__}, "
+ f"detail={_redact_request_error(exc, item.url)}"
+ )
+ continue
+ if saved_video_path:
+ downloaded.append((search_term, item, saved_video_path))
+ return downloaded
+
+ futures = {}
+ with ThreadPoolExecutor(
+ max_workers=workers,
+ thread_name_prefix="material-download",
+ ) as executor:
+ for search_term, item in materials:
+ futures[executor.submit(
+ save_video,
+ item.url,
+ material_directory,
+ )] = (search_term, item)
+
+ downloaded = []
+ for future in futures:
+ search_term, item = futures[future]
+ try:
+ saved_video_path = future.result()
+ except Exception as exc:
+ logger.error(
+ "failed to download material video: "
+ f"provider={item.provider}, "
+ f"error={type(exc).__name__}, "
+ f"detail={_redact_request_error(exc, item.url)}"
+ )
+ continue
+ if saved_video_path:
+ downloaded.append((search_term, item, saved_video_path))
+ return downloaded
+
+
+def _select_materials_until_duration(
+ materials: List[tuple[str, MaterialInfo]],
+ max_clip_duration: int,
+ audio_duration: float,
+ current_duration: float = 0.0,
+) -> List[tuple[str, MaterialInfo]]:
+ """
+ 按候选顺序选取一轮素材,避免并发时下载已经超过配音时长的候选。
+
+ 返回 ``materials`` 的前缀子集:从第一个候选开始累加,累加时长首次
+ 超过配音时长时停止(含超出的那一个)。调用方据此前缀属性判断哪些
+ 候选在本轮被实际尝试。
+ """
+ selected = []
+ total_duration = current_duration
+ for material in materials:
+ selected.append(material)
+ total_duration += min(max_clip_duration, material[1].duration)
+ if total_duration > audio_duration:
+ break
+ return selected
+
+
def download_videos(
task_id: str,
search_terms: List[str],
@@ -1976,14 +2125,12 @@ def download_videos(
valid_video_items = []
valid_video_urls = []
found_duration = 0.0
- for search_term in search_terms:
- video_items = search_videos(
- search_term=search_term,
- minimum_duration=max_clip_duration,
- video_aspect=video_aspect,
- )
- logger.info(f"found {len(video_items)} videos for '{search_term}'")
-
+ for search_term, video_items in _search_terms_in_parallel(
+ search_terms=search_terms,
+ search_videos=search_videos,
+ minimum_duration=max_clip_duration,
+ video_aspect=video_aspect,
+ ):
for item in video_items:
if item.url not in valid_video_urls:
valid_video_items.append(item)
@@ -2001,44 +2148,59 @@ def download_videos(
random.shuffle(valid_video_items)
total_duration = 0.0
- for item in valid_video_items:
- try:
+ pending_items = list(valid_video_items)
+ # 默认/随机路径同样受素材并发配置控制:按串行逻辑的停止条件预选每轮
+ # 候选(顺序累加、首次超过配音时长即停)。全部下载成功时,每轮下载集合
+ # 与串行逻辑完全一致;下载失败的候选在下一轮用后续候选补足。
+ while pending_items and total_duration <= audio_duration:
+ batch = []
+ projected_duration = total_duration
+ for item in pending_items:
+ batch.append(item)
+ projected_duration += min(max_clip_duration, item.duration)
+ if projected_duration > audio_duration:
+ break
+ for item in batch:
source_info = item.source_info if isinstance(item.source_info, dict) else {}
logger.info(
f"downloading {item.provider} video: "
f"asset_id={source_info.get('asset_id') or 'unknown'}"
)
- saved_video_path = save_video(
- video_url=item.url, save_dir=material_directory
- )
- if saved_video_path:
- logger.info(f"video saved: {saved_video_path}")
- video_paths.append(saved_video_path)
- try:
- material_sources.append(
- _material_source_record(item, saved_video_path)
- )
- except Exception as source_error:
- # 来源记录异常不能把已经成功下载的素材视为下载失败,更不能
- # 阻断视频生成;保留供应商和异常类型用于后续定位。
- logger.warning(
- "failed to prepare material source record: "
- f"provider={item.provider}, "
- f"error={type(source_error).__name__}, detail={source_error}"
- )
- seconds = min(max_clip_duration, item.duration)
- total_duration += seconds
- if total_duration > audio_duration:
- logger.info(
- f"total duration of downloaded videos: {total_duration} seconds, skip downloading more"
- )
- break
- except Exception as e:
- logger.error(
- "failed to download material video: "
- f"provider={item.provider}, error={type(e).__name__}, "
- f"detail={_redact_request_error(e, item.url)}"
- )
+ downloaded_materials = _download_materials_in_parallel(
+ materials=[("", item) for item in batch],
+ material_directory=material_directory,
+ )
+ pending_items = pending_items[len(batch):]
+ for _, item, saved_video_path in downloaded_materials:
+ try:
+ if saved_video_path:
+ logger.info(f"video saved: {saved_video_path}")
+ video_paths.append(saved_video_path)
+ try:
+ material_sources.append(
+ _material_source_record(item, saved_video_path)
+ )
+ except Exception as source_error:
+ # 来源记录异常不能把已经成功下载的素材视为下载失败,更不能
+ # 阻断视频生成;保留供应商和异常类型用于后续定位。
+ logger.warning(
+ "failed to prepare material source record: "
+ f"provider={item.provider}, "
+ f"error={type(source_error).__name__}, detail={source_error}"
+ )
+ seconds = min(max_clip_duration, item.duration)
+ total_duration += seconds
+ if total_duration > audio_duration:
+ logger.info(
+ f"total duration of downloaded videos: {total_duration} seconds, skip downloading more"
+ )
+ break
+ except Exception as e:
+ logger.error(
+ "failed to download material video: "
+ f"provider={item.provider}, error={type(e).__name__}, "
+ f"detail={_redact_request_error(e, item.url)}"
+ )
logger.success(f"downloaded {len(video_paths)} videos")
_persist_material_sources(task_id, material_sources)
return video_paths
@@ -2624,14 +2786,12 @@ def _download_videos_by_script_order(
valid_video_urls = set()
found_duration = 0.0
- for search_term in search_terms:
- video_items = search_videos(
- search_term=search_term,
- minimum_duration=max_clip_duration,
- video_aspect=video_aspect,
- )
- logger.info(f"found {len(video_items)} videos for '{search_term}'")
-
+ for search_term, video_items in _search_terms_in_parallel(
+ search_terms=search_terms,
+ search_videos=search_videos,
+ minimum_duration=max_clip_duration,
+ video_aspect=video_aspect,
+ ):
term_items = []
for item in video_items:
if item.url in valid_video_urls:
@@ -2651,15 +2811,43 @@ def _download_videos_by_script_order(
video_paths = []
material_sources: list[dict[str, Any]] = []
total_duration = 0.0
- candidate_index = 0
+ # 每个关键词独立推进候选下标:只有本轮真正被选中下载的候选才推进,
+ # 未被选中的候选保留到下一轮,避免被整轮统一的下标跳过。
+ next_candidate_indices = [0] * len(candidate_groups)
while candidate_groups and total_duration <= audio_duration:
- has_candidate = False
- for search_term, term_items in candidate_groups:
- if candidate_index >= len(term_items):
- continue
+ round_materials = [
+ (
+ group_position,
+ search_term,
+ term_items[next_candidate_indices[group_position]],
+ )
+ for group_position, (search_term, term_items) in enumerate(
+ candidate_groups
+ )
+ if next_candidate_indices[group_position] < len(term_items)
+ ]
+ if not round_materials:
+ break
- has_candidate = True
- item = term_items[candidate_index]
+ selected_materials = _select_materials_until_duration(
+ materials=[
+ (search_term, item) for _, search_term, item in round_materials
+ ],
+ max_clip_duration=max_clip_duration,
+ audio_duration=audio_duration,
+ current_duration=total_duration,
+ )
+ # _select_materials_until_duration 返回候选列表的前缀子集,
+ # 因此前 len(selected_materials) 个即本轮实际尝试下载的候选,
+ # 只推进这些候选所在分组的下标。
+ for group_position, _, _ in round_materials[: len(selected_materials)]:
+ next_candidate_indices[group_position] += 1
+
+ downloaded_materials = _download_materials_in_parallel(
+ materials=selected_materials,
+ material_directory=material_directory,
+ )
+ for search_term, item, saved_video_path in downloaded_materials:
try:
source_info = (
item.source_info if isinstance(item.source_info, dict) else {}
@@ -2668,9 +2856,6 @@ def _download_videos_by_script_order(
f"downloading ordered {item.provider} video for {search_term!r}: "
f"asset_id={source_info.get('asset_id') or 'unknown'}"
)
- saved_video_path = save_video(
- video_url=item.url, save_dir=material_directory
- )
if saved_video_path:
logger.info(f"video saved: {saved_video_path}")
video_paths.append(saved_video_path)
@@ -2698,10 +2883,6 @@ def _download_videos_by_script_order(
f"detail={_redact_request_error(e, item.url)}"
)
- if not has_candidate:
- break
- candidate_index += 1
-
logger.success(f"downloaded {len(video_paths)} ordered videos")
_persist_material_sources(task_id, material_sources)
return video_paths
diff --git a/app/services/video.py b/app/services/video.py
index e31c838c..7682c4a8 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -1,4 +1,5 @@
import itertools
+from concurrent.futures import ThreadPoolExecutor
import io
import math
import os
@@ -83,6 +84,17 @@ _MIN_MATERIAL_DIMENSION = 480
# 丢弃,最终以 "no valid materials found" 整体失败。这里留一个很小的容差,
# 既能放行仅仅因为取整而略低于阈值的素材,也仍然能挡住真正的低清素材。
_MIN_DIMENSION_TOLERANCE = 10
+# 片段预处理是独立的重编码任务。4 路并发在 8 核/16GB 的桌面机上收益明显,
+# 又不会把 MoviePy 的内存峰值推到失控。
+_CLIP_PROCESSING_CONCURRENCY = 4
+
+
+def _get_clip_processing_concurrency() -> int:
+ try:
+ concurrency = int(config.app.get("video_clip_concurrency", _CLIP_PROCESSING_CONCURRENCY))
+ except (TypeError, ValueError):
+ concurrency = _CLIP_PROCESSING_CONCURRENCY
+ return max(1, min(8, concurrency))
_DEFAULT_VIDEO_CODEC = "libx264"
# ffmpeg 串联片段期间没有阶段日志,`subprocess.run` 又阻塞到进程退出,耗时拼接在
# 日志上表现为“无输出”。这里按间隔记录存活信息,便于区分编码中与已经卡死。
@@ -914,21 +926,17 @@ def combine_videos(
logger.debug(f"total subclipped items: {len(subclipped_items)}")
# Add downloaded clips over and over until the duration of the audio (max_duration) has been reached
- for i, subclipped_item in enumerate(subclipped_items):
- if video_duration >= required_video_duration:
- break
-
- logger.debug(
- f"processing clip {i+1}: {subclipped_item.width}x{subclipped_item.height}, "
- f"source: {os.path.basename(subclipped_item.source_file_path)}, "
- f"current duration: {video_duration:.2f}s, "
- f"remaining: {required_video_duration - video_duration:.2f}s"
- )
-
+ def process_one_clip(indexed_item):
+ """把一个源片段裁剪、变速、转场后写出,失败时返回 None。"""
+ index, subclipped_item = indexed_item
source_clip = None
clip = None
clip_file = None
try:
+ logger.debug(
+ f"processing clip {index + 1}: {subclipped_item.width}x{subclipped_item.height}, "
+ f"source: {os.path.basename(subclipped_item.source_file_path)}"
+ )
source_clip = _open_video_clip_quietly(subclipped_item.file_path)
clip = source_clip.subclipped(
subclipped_item.start_time, subclipped_item.end_time
@@ -959,9 +967,7 @@ def combine_videos(
)
shuffle_side = random.choice(["left", "right", "top", "bottom"])
- if transition_value in (None, VideoTransitionMode.none.value):
- clip = clip
- elif transition_value == VideoTransitionMode.fade_in.value:
+ if transition_value == VideoTransitionMode.fade_in.value:
clip = video_effects.fadein_transition(clip, 1)
elif transition_value == VideoTransitionMode.fade_out.value:
clip = video_effects.fadeout_transition(clip, 1)
@@ -987,9 +993,10 @@ def combine_videos(
if clip.duration > max_clip_duration:
clip = clip.subclipped(0, max_clip_duration)
-
- # wirte clip to temp file
- clip_file = f"{output_dir}/temp-clip-{i+1}.mp4"
+
+ # Write each candidate clip to a unique temporary file. Threads must not
+ # share the same output path.
+ clip_file = f"{output_dir}/temp-clip-{index + 1}.mp4"
_write_videofile_with_codec_fallback(
clip,
clip_file,
@@ -998,32 +1005,63 @@ def combine_videos(
fps=fps,
)
- # Store clip duration before closing
clip_duration_saved = clip.duration
-
- processed_clips.append(
- SubClippedVideoClip(
- file_path=clip_file,
- duration=clip_duration_saved,
- width=clip_w,
- height=clip_h,
- source_file_path=subclipped_item.source_file_path,
- )
+ processed_clip = SubClippedVideoClip(
+ file_path=clip_file,
+ duration=clip_duration_saved,
+ width=clip_w,
+ height=clip_h,
+ source_file_path=subclipped_item.source_file_path,
)
- video_duration += clip_duration_saved
clip_file = None
-
- except Exception as e:
- logger.error(f"failed to process clip: {str(e)}")
+ return processed_clip
+ except Exception as exc:
+ logger.error(f"failed to process clip: {str(exc)}")
+ return None
finally:
# The derived clip shares its FFmpeg reader with the source. If
# subclipping itself failed, close the original source instead.
close_clip(clip if clip is not None else source_clip)
# MoviePy may leave a truncated MP4 even when encoding raises. It
- # was never added to processed_clips, so concat cleanup cannot see it.
+ # was never returned, so concat cleanup cannot see it.
# Close the reader first so Windows can remove the partial file.
if clip_file:
delete_files(clip_file)
+
+ clip_processing_workers = 1
+ if len(subclipped_items) >= 2:
+ clip_processing_workers = min(_get_clip_processing_concurrency(), len(subclipped_items))
+ with ThreadPoolExecutor(
+ max_workers=clip_processing_workers,
+ thread_name_prefix="clip-process",
+ ) as executor:
+ next_candidate_index = 0
+ while (
+ next_candidate_index < len(subclipped_items)
+ and video_duration < required_video_duration
+ ):
+ remaining_duration = required_video_duration - video_duration
+ batch = []
+ batch_duration = 0.0
+ candidate_index = next_candidate_index
+ while candidate_index < len(subclipped_items) and batch_duration < remaining_duration:
+ subclipped_item = subclipped_items[candidate_index]
+ source_duration = subclipped_item.end_time - subclipped_item.start_time
+ output_duration = min(
+ max_clip_duration,
+ source_duration / normalized_clip_speed,
+ )
+ batch.append((candidate_index, subclipped_item))
+ batch_duration += output_duration
+ candidate_index += 1
+ if not batch:
+ break
+ for processed_clip in executor.map(process_one_clip, batch):
+ if processed_clip is None:
+ continue
+ processed_clips.append(processed_clip)
+ video_duration += processed_clip.duration
+ next_candidate_index = candidate_index
# loop processed clips until the video duration covers the audio duration and the small safety margin.
if video_duration < required_video_duration:
diff --git a/test/services/test_material.py b/test/services/test_material.py
index f35d9e07..bda41e65 100644
--- a/test/services/test_material.py
+++ b/test/services/test_material.py
@@ -1087,7 +1087,7 @@ class TestMaterialTlsVerification(unittest.TestCase):
match_script_order=True,
)
- self.assertEqual(
+ self.assertCountEqual(
downloaded_urls,
[
"https://v.example/a1.mp4",
@@ -1106,6 +1106,325 @@ class TestMaterialTlsVerification(unittest.TestCase):
["a1.mp4", "b1.mp4", "a2.mp4"],
)
+ def test_script_order_uses_next_candidate_after_failed_download(self):
+ """
+ 回归:脚本顺序模式下首个候选下载失败时,必须尝试同一关键词的
+ 下一个候选,而不是返回空结果。下载异常不能中断整个流程。
+ """
+ search_results = {
+ "city": [
+ material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/bad.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "bad"},
+ ),
+ material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/good.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "good"},
+ ),
+ ],
+ }
+ attempted_urls = []
+
+ def fake_search(search_term, minimum_duration, video_aspect):
+ return search_results[search_term]
+
+ def fake_save_video(video_url, save_dir=""):
+ attempted_urls.append(video_url)
+ if "bad" in video_url:
+ raise RuntimeError("network down")
+ return "/tmp/good.mp4"
+
+ with (
+ patch.dict(
+ config.app,
+ {"material_directory": "", "material_concurrency": 4},
+ ),
+ patch.object(material, "search_videos_pexels", side_effect=fake_search),
+ patch.object(material, "save_video", side_effect=fake_save_video),
+ patch.object(
+ material.material_cache,
+ "load_material_search_cache",
+ return_value=None,
+ ),
+ patch.object(material.material_cache, "save_material_search_cache"),
+ patch.object(
+ material.task_artifacts,
+ "patch_script_data",
+ return_value=True,
+ ),
+ ):
+ result = material.download_videos(
+ task_id="failed-first-candidate",
+ search_terms=["city"],
+ source="pexels",
+ audio_duration=8,
+ max_clip_duration=5,
+ match_script_order=True,
+ )
+
+ self.assertEqual(
+ attempted_urls,
+ ["https://v.example/bad.mp4", "https://v.example/good.mp4"],
+ )
+ self.assertEqual(result, ["/tmp/good.mp4"])
+
+ def test_script_order_does_not_skip_unattempted_candidates(self):
+ """
+ 回归:脚本顺序模式下,本轮未被选中的候选不能推进下标。
+ 三个关键词各 1 个候选、首轮只选中前两个且都下载失败时,
+ 第三个候选必须在下一轮被尝试,而不是被整轮统一的下标跳过
+ 导致直接返回空结果。
+ """
+ search_results = {
+ "t1": [
+ material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/x.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "x"},
+ ),
+ ],
+ "t2": [
+ material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/y.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "y"},
+ ),
+ ],
+ "t3": [
+ material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/z.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "z"},
+ ),
+ ],
+ }
+ attempted_urls = []
+
+ def fake_search(search_term, minimum_duration, video_aspect):
+ return search_results[search_term]
+
+ def fake_save_video(video_url, save_dir=""):
+ attempted_urls.append(video_url)
+ if "z.mp4" not in video_url:
+ raise RuntimeError("network down")
+ return "/tmp/z.mp4"
+
+ with (
+ patch.dict(
+ config.app,
+ {"material_directory": "", "material_concurrency": 4},
+ ),
+ patch.object(material, "search_videos_pexels", side_effect=fake_search),
+ patch.object(material, "save_video", side_effect=fake_save_video),
+ patch.object(
+ material.material_cache,
+ "load_material_search_cache",
+ return_value=None,
+ ),
+ patch.object(material.material_cache, "save_material_search_cache"),
+ patch.object(
+ material.task_artifacts,
+ "patch_script_data",
+ return_value=True,
+ ),
+ ):
+ result = material.download_videos(
+ task_id="unattempted-candidate",
+ search_terms=["t1", "t2", "t3"],
+ source="pexels",
+ audio_duration=6,
+ max_clip_duration=5,
+ match_script_order=True,
+ )
+
+ # 首轮选中 x、y(累计 10s 超过 6s 配音),z 未被尝试;x、y 都下载失败后,
+ # 修复前 z 会被整轮统一的下标直接跳过、函数返回空结果;
+ # 修复后 z 必须在次轮被尝试并下载成功。
+ self.assertCountEqual(
+ attempted_urls,
+ [
+ "https://v.example/x.mp4",
+ "https://v.example/y.mp4",
+ "https://v.example/z.mp4",
+ ],
+ )
+ self.assertEqual(result, ["/tmp/z.mp4"])
+
+ def test_default_path_single_material_failure_does_not_abort(self):
+ """
+ 回归:默认路径下,即使并发配置为 4,单候选批次走串行下载时
+ 下载异常也必须被捕获,不能中断整个生成流程。
+ """
+ item = material.MaterialInfo(
+ provider="pexels",
+ url="https://v.example/only.mp4",
+ duration=5,
+ source_info={"provider": "pexels", "asset_id": "only"},
+ )
+
+ with (
+ patch.dict(
+ config.app,
+ {"material_directory": "", "material_concurrency": 4},
+ ),
+ patch.object(material, "search_videos_pexels", return_value=[item]),
+ patch.object(
+ material, "save_video", side_effect=RuntimeError("boom")
+ ),
+ patch.object(
+ material.material_cache,
+ "load_material_search_cache",
+ return_value=None,
+ ),
+ patch.object(material.material_cache, "save_material_search_cache"),
+ patch.object(
+ material.task_artifacts,
+ "patch_script_data",
+ return_value=True,
+ ),
+ ):
+ result = material.download_videos(
+ task_id="single-failure",
+ search_terms=["city"],
+ source="pexels",
+ video_concat_mode=material.VideoConcatMode.sequential,
+ audio_duration=10,
+ max_clip_duration=5,
+ )
+
+ self.assertEqual(result, [])
+
+ def test_default_path_serial_fallback_keeps_selection_order(self):
+ """
+ 并发配置为 1 时,默认路径保持严格串行:按候选顺序下载,
+ 时长覆盖即停,下载失败跳过并继续下一个候选。
+ """
+ items = [
+ material.MaterialInfo(
+ provider="pexels",
+ url=f"https://v.example/{name}.mp4",
+ duration=6,
+ source_info={"provider": "pexels", "asset_id": name},
+ )
+ for name in ("a", "b", "c")
+ ]
+ attempted_urls = []
+
+ def fake_save_video(video_url, save_dir=""):
+ attempted_urls.append(video_url)
+ if "/b.mp4" in video_url:
+ raise RuntimeError("network down")
+ return f"/tmp/{video_url.rsplit('/', 1)[-1]}"
+
+ with (
+ patch.dict(
+ config.app,
+ {"material_directory": "", "material_concurrency": 1},
+ ),
+ patch.object(material, "search_videos_pexels", return_value=items),
+ patch.object(material, "save_video", side_effect=fake_save_video),
+ patch.object(
+ material.material_cache,
+ "load_material_search_cache",
+ return_value=None,
+ ),
+ patch.object(material.material_cache, "save_material_search_cache"),
+ patch.object(
+ material.task_artifacts,
+ "patch_script_data",
+ return_value=True,
+ ),
+ ):
+ result = material.download_videos(
+ task_id="serial-fallback",
+ search_terms=["city"],
+ source="pexels",
+ video_concat_mode=material.VideoConcatMode.sequential,
+ audio_duration=10,
+ max_clip_duration=6,
+ )
+
+ # 串行语义:a 成功(6s)、b 失败跳过、c 成功(累计 12s 覆盖 10s 即停)。
+ self.assertEqual(
+ attempted_urls,
+ [
+ "https://v.example/a.mp4",
+ "https://v.example/b.mp4",
+ "https://v.example/c.mp4",
+ ],
+ )
+ self.assertEqual(result, ["/tmp/a.mp4", "/tmp/c.mp4"])
+
+ def test_default_path_parallel_download_matches_serial_selection(self):
+ """
+ 默认路径并行下载保持与串行一致的选择语义:顺序累加、覆盖即停;
+ 失败的候选用后续候选补足,最终下载集合与串行一致。
+ """
+ items = [
+ material.MaterialInfo(
+ provider="pexels",
+ url=f"https://v.example/{name}.mp4",
+ duration=6,
+ source_info={"provider": "pexels", "asset_id": name},
+ )
+ for name in ("a", "b", "c", "d")
+ ]
+
+ def fake_save_video(video_url, save_dir=""):
+ if "/b.mp4" in video_url:
+ raise RuntimeError("network down")
+ return f"/tmp/{video_url.rsplit('/', 1)[-1]}"
+
+ with (
+ patch.dict(
+ config.app,
+ {"material_directory": "", "material_concurrency": 4},
+ ),
+ patch.object(material, "search_videos_pexels", return_value=items),
+ patch.object(material, "save_video", side_effect=fake_save_video),
+ patch.object(
+ material.material_cache,
+ "load_material_search_cache",
+ return_value=None,
+ ),
+ patch.object(material.material_cache, "save_material_search_cache"),
+ patch.object(
+ material.task_artifacts,
+ "patch_script_data",
+ return_value=True,
+ ),
+ ):
+ result = material.download_videos(
+ task_id="parallel-selection",
+ search_terms=["city"],
+ source="pexels",
+ video_concat_mode=material.VideoConcatMode.sequential,
+ audio_duration=10,
+ max_clip_duration=6,
+ )
+
+ # 首轮 [a, b]:a 成功(6s)、b 失败;次轮 [c] 成功(累计 12s 覆盖即停)。
+ # 与串行逻辑的下载集合一致:{a, c},d 不会被多下载。
+ self.assertEqual(result, ["/tmp/a.mp4", "/tmp/c.mp4"])
+
+ def test_material_concurrency_is_clamped(self):
+ """素材并发配置钳制在 1~8,非法值回退到默认值 4。"""
+ with patch.dict(config.app, {"material_concurrency": 0}):
+ self.assertEqual(material._get_material_concurrency(), 1)
+ with patch.dict(config.app, {"material_concurrency": 99}):
+ self.assertEqual(material._get_material_concurrency(), 8)
+ with patch.dict(config.app, {"material_concurrency": "bad"}):
+ self.assertEqual(material._get_material_concurrency(), 4)
+ with patch.dict(config.app, {"material_concurrency": 2}):
+ self.assertEqual(material._get_material_concurrency(), 2)
+
def test_material_source_persistence_failure_does_not_break_download(self):
"""辅助任务记录失败时,已经下载成功的素材仍应正常返回给成片主流程。"""
item = material.MaterialInfo(
diff --git a/test/services/test_webui_loomloom.py b/test/services/test_webui_loomloom.py
index f0fd865b..670dbe04 100644
--- a/test/services/test_webui_loomloom.py
+++ b/test/services/test_webui_loomloom.py
@@ -345,7 +345,11 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():
with (
patch.object(config, "app", test_config),
# 显式从两段切到一段,不能依赖开发者 config.toml 中的历史值。
- patch.object(config, "ui", dict(config.ui, loomloom_video_scene_count=2)),
+ patch.object(
+ config,
+ "ui",
+ dict(config.ui, loomloom_video_scene_count=2, voice_mode="none"),
+ ),
patch.object(config, "try_save_config", return_value=True),
patch.object(
loomloom.LoomLoomVideoBackend,
diff --git a/test/services/test_webui_metaso_minimax.py b/test/services/test_webui_metaso_minimax.py
index 3f9c1bda..ffd6c45e 100644
--- a/test/services/test_webui_metaso_minimax.py
+++ b/test/services/test_webui_metaso_minimax.py
@@ -31,6 +31,7 @@ def test_metaso_source_requires_confirmation_and_never_enters_task_params():
)
with (
patch.object(config, "app", test_config),
+ patch.object(config, "ui", dict(config.ui, voice_mode="none")),
patch.object(config, "try_save_config", return_value=True),
patch("app.services.webui_task.submit_generation") as submit_generation,
):
diff --git a/test/services/test_webui_muapi.py b/test/services/test_webui_muapi.py
index 9102296c..03617dd1 100644
--- a/test/services/test_webui_muapi.py
+++ b/test/services/test_webui_muapi.py
@@ -28,6 +28,7 @@ def test_muapi_source_requires_confirmation_then_submits_without_secret_in_param
)
with (
patch.object(config, "app", test_config),
+ patch.object(config, "ui", dict(config.ui, voice_mode="none")),
patch.object(config, "try_save_config", return_value=True),
patch("app.services.webui_task.submit_generation") as submit_generation,
):
diff --git a/test/services/test_webui_ofox.py b/test/services/test_webui_ofox.py
index 650c29c8..d885969e 100644
--- a/test/services/test_webui_ofox.py
+++ b/test/services/test_webui_ofox.py
@@ -28,6 +28,7 @@ def test_ofox_source_requires_confirmation_then_submits_without_secret_in_params
)
with (
patch.object(config, "app", test_config),
+ patch.object(config, "ui", dict(config.ui, voice_mode="none")),
patch.object(config, "try_save_config", return_value=True),
patch("app.services.webui_task.submit_generation") as submit_generation,
):
diff --git a/test/services/test_webui_seedance.py b/test/services/test_webui_seedance.py
index d046b7b7..85ea8e25 100644
--- a/test/services/test_webui_seedance.py
+++ b/test/services/test_webui_seedance.py
@@ -28,6 +28,7 @@ def test_seedance_source_requires_confirmation_then_submits_without_secret_in_pa
)
with (
patch.object(config, "app", test_config),
+ patch.object(config, "ui", dict(config.ui, voice_mode="none")),
patch.object(config, "try_save_config", return_value=True),
patch("app.services.webui_task.submit_generation") as submit_generation,
):
diff --git a/webui/Main.py b/webui/Main.py
index b877426d..accc74f8 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -342,10 +342,11 @@ def _save_runtime_config():
return saved
-def _saved_ui_choice(key, options, default):
+def _saved_ui_choice(key, options, default, section=None):
"""读取一个持久化选择,并把旧配置或手工编辑的非法值降级为默认值。"""
options = list(options)
- saved = config.ui.get(key, default)
+ section = config.ui if section is None else section
+ saved = section.get(key, default)
numeric_default = isinstance(default, (int, float)) and not isinstance(
default, bool
)
@@ -2067,37 +2068,46 @@ def _render_generation_task_snapshot(task_id, task):
else:
st.warning(str(warning))
+ available_videos = [
+ (index, url)
+ for index, url in enumerate(video_files)
+ if os.path.isfile(url)
+ ]
+ for index, url in enumerate(video_files):
+ if os.path.isfile(url):
+ continue
+ logger.warning(
+ f"generated video is unavailable: "
+ f"task_id={task_id}, video_file={url}"
+ )
+
try:
- player_cols = st.columns(len(video_files) * 2 + 1)
- for i, url in enumerate(video_files):
- with player_cols[i * 2 + 1]:
- st.video(url)
- if not os.path.isfile(url):
- logger.warning(
- f"generated video is unavailable for download: "
- f"task_id={task_id}, video_file={url}"
- )
- continue
-
- download_label = tr("Download Video")
- if len(video_files) > 1:
- download_label = f"{download_label} {i + 1}"
- download_name = _build_video_download_name(
- task.get("video_subject"),
- i + 1,
- len(video_files),
- )
- with open(url, "rb") as video_file:
- st.download_button(
- download_label,
- data=video_file,
- file_name=download_name,
- mime=mimetypes.guess_type(url)[0] or "video/mp4",
- key=f"download_generated_video_{task_id}_{i}",
- icon=":material/download:",
- on_click="ignore",
- use_container_width=True,
+ if not available_videos:
+ st.warning(tr("Generated Video Files Unavailable"))
+ else:
+ player_cols = st.columns(len(available_videos) * 2 + 1)
+ for player_index, (video_index, url) in enumerate(available_videos):
+ with player_cols[player_index * 2 + 1]:
+ st.video(url)
+ download_label = tr("Download Video")
+ if len(video_files) > 1:
+ download_label = f"{download_label} {video_index + 1}"
+ download_name = _build_video_download_name(
+ task.get("video_subject"),
+ video_index + 1,
+ len(video_files),
)
+ with open(url, "rb") as video_file:
+ st.download_button(
+ download_label,
+ data=video_file,
+ file_name=download_name,
+ mime=mimetypes.guess_type(url)[0] or "video/mp4",
+ key=f"download_generated_video_{task_id}_{video_index}",
+ icon=":material/download:",
+ on_click="ignore",
+ use_container_width=True,
+ )
except Exception as exc:
logger.exception(
f"failed to render generated video preview: task_id={task_id}, "
@@ -5453,6 +5463,33 @@ def _render_video_settings(panel, params):
else:
_set_runtime_config("app", "video_codec", selected_video_codec)
+ concurrency_options = [1, 2, 4, 6, 8]
+ selected_material_concurrency = stable_selectbox(
+ tr("Material Concurrency"),
+ options=concurrency_options,
+ default_value=_saved_ui_choice(
+ "material_concurrency", concurrency_options, 4, config.app
+ ),
+ key="material_concurrency_select",
+ help=tr("Material Concurrency Help"),
+ )
+ _set_runtime_config(
+ "app", "material_concurrency", selected_material_concurrency
+ )
+
+ selected_clip_concurrency = stable_selectbox(
+ tr("Clip Rendering Concurrency"),
+ options=concurrency_options,
+ default_value=_saved_ui_choice(
+ "video_clip_concurrency", concurrency_options, 4, config.app
+ ),
+ key="clip_rendering_concurrency_select",
+ help=tr("Clip Rendering Concurrency Help"),
+ )
+ _set_runtime_config(
+ "app", "video_clip_concurrency", selected_clip_concurrency
+ )
+
if params.video_source == "loomloom":
_render_loomloom_video_settings(params)
diff --git a/webui/i18n/az.json b/webui/i18n/az.json
index 25eb47d3..56adc72d 100644
--- a/webui/i18n/az.json
+++ b/webui/i18n/az.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "OpenAI ilə uyğun şəkil modeli",
"Please Configure the OpenAI Image Source": "OpenAI ilə uyğun şəkil mənbəyi üçün **əsas URL** və **model** konfiqurasiya edilməlidir (lokal şlüzlər üçün **API açarı** istəyə bağlıdır)",
"Video Encoder": "Video kodlayıcısı",
+ "Material Concurrency": "Materialların paralelliyi",
+ "Material Concurrency Help": "Eyni anda neçə material axtarışı və yükləməsi işləsin. 1 ardıcıl, 4 tövsiyə olunur; daha yüksək dəyərlər provayder limitlərinə səbəb ola bilər.",
+ "Clip Rendering Concurrency": "Klip render paralelliyi",
+ "Clip Rendering Concurrency Help": "Eyni anda neçə klip kəsilsin, sürəti dəyişsin və kodlansın. 1 ardıcıl, 4 tövsiyə olunur; daha yüksək dəyərlər daha çox CPU və yaddaş istifadə edir.",
+ "Generated Video Files Unavailable": "Yaradılmış video faylları artıq əlçatmazdır. Onlar təmizlənilib. Tapşırıq jurnalları oxuna bilər.",
"Default Video Encoder": "Standart (tövsiyə olunur)",
"Video Encoder Help": "Genişləndirilmiş seçim. Standart seçim tətbiqin sabit kodlayıcı siyasətinə uyğundur və hazırda libx264 istifadə edir. Seçilmiş aparat kodlayıcısı mövcud olmadıqda tətbiq avtomatik olaraq libx264 kodlayıcısına keçir.",
"Auto-Publish Settings": "Avtomatik paylaşım parametrləri",
diff --git a/webui/i18n/ca.json b/webui/i18n/ca.json
index 8b4ed2c7..ebcbae14 100644
--- a/webui/i18n/ca.json
+++ b/webui/i18n/ca.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Model d'imatges compatible amb OpenAI",
"Please Configure the OpenAI Image Source": "Configura l'**URL base** i el **model** del servei d'imatges compatible amb OpenAI (la **clau API** és opcional per a les passarel·les locals)",
"Video Encoder": "Codificador de vídeo",
+ "Material Concurrency": "Concurrència de materials",
+ "Material Concurrency Help": "Quantes cerques i descàrregues de material s'executen alhora. 1 és seqüencial i 4 és recomanat; valors més alts poden activar límits del proveïdor.",
+ "Clip Rendering Concurrency": "Concurrència de renderització de clips",
+ "Clip Rendering Concurrency Help": "Quants clips es retallen, ajusten de velocitat i codifiquen alhora. 1 és seqüencial i 4 és recomanat; valors més alts usen més CPU i memòria.",
+ "Generated Video Files Unavailable": "Els fitxers de vídeo generats ja no estan disponibles. Pot ser que s'hagin netejat. Els registres de tasques continuen essent llegibles.",
"Default Video Encoder": "Per defecte (recomanat)",
"Video Encoder Help": "Opció avançada. Per defecte, s'aplica la política estable de l'aplicació, actualment libx264. Si el codificador de maquinari no està disponible, es torna automàticament a libx264.",
"Auto-Publish Settings": "Publicació automàtica",
diff --git a/webui/i18n/de.json b/webui/i18n/de.json
index 10eabb0a..ec1e4c53 100644
--- a/webui/i18n/de.json
+++ b/webui/i18n/de.json
@@ -114,6 +114,11 @@
"Match Materials to Script Order": "Bilder an Skriptreihenfolge anpassen",
"Match Materials to Script Order Help": "Erstellt Suchbegriffe und ordnet Material nach dem Skript, damit die Bilder dem Sprechertext folgen.",
"Video Encoder": "Video-Encoder",
+ "Material Concurrency": "Material-Parallelität",
+ "Material Concurrency Help": "Wie viele Materialsuchen und Downloads gleichzeitig laufen. 1 ist seriell und 4 wird empfohlen; höhere Werte können Anbieter-Limits auslösen.",
+ "Clip Rendering Concurrency": "Clip-Rendering-Parallelität",
+ "Clip Rendering Concurrency Help": "Wie viele Clips gleichzeitig zugeschnitten, Geschwindigkeit angepasst und kodiert werden. 1 ist seriell und 4 wird empfohlen; höhere Werte benötigen mehr CPU und RAM.",
+ "Generated Video Files Unavailable": "Generierte Videodateien sind nicht mehr verfügbar. Sie wurden möglicherweise bereinigt. Aufgabenprotokolle bleiben lesbar.",
"Default Video Encoder": "Standard (empfohlen)",
"Video Encoder Help": "Erweiterte Option. Standard folgt der stabilen App-Vorgabe, derzeit libx264. Wenn ein Hardware-Encoder nicht verfügbar ist, fällt die App automatisch auf libx264 zurück.",
"Audio Settings": "**Audio Einstellungen**",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index d807fcc0..9ff7bfc7 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -219,6 +219,7 @@
"Start Generating Video": "Start Generating Video",
"Video Generation Completed": "Video Generation Completed",
"Video Generation Failed": "Video Generation Failed",
+ "Generated Video Files Unavailable": "Generated video files are no longer available. They may have been cleaned up. Task logs are still readable.",
"Download Video": "Download Video",
"You can download the generated video from the following links": "You can download the generated video from the following links",
"Pexels API Key": "Pexels API Key ([Get API Key](https://www.pexels.com/api/)) :green[Free] · :red[Recommended]",
@@ -467,6 +468,10 @@
"OpenAI Image Model": "OpenAI Compatible Image Model",
"Please Configure the OpenAI Image Source": "Please configure the **Base URL** and **Model** for the OpenAI compatible image source (**API Key** optional for local gateways)",
"Video Encoder": "Video Encoder",
+ "Material Concurrency": "Material Concurrency",
+ "Material Concurrency Help": "How many material searches and downloads run at once. 1 is serial and 4 is recommended; higher values may trigger provider rate limits.",
+ "Clip Rendering Concurrency": "Clip Rendering Concurrency",
+ "Clip Rendering Concurrency Help": "How many clips are cropped, speed-adjusted, and encoded at once. 1 is serial and 4 is recommended; higher values use more CPU and memory.",
"Default Video Encoder": "Default (Recommended)",
"Video Encoder Help": "Advanced option. Default follows the app's stable encoder policy, currently libx264. If a selected hardware encoder is unavailable, the app automatically falls back to libx264.",
"API Platform": "API Platform",
diff --git a/webui/i18n/es.json b/webui/i18n/es.json
index 7f64d91a..08e294d3 100644
--- a/webui/i18n/es.json
+++ b/webui/i18n/es.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Modelo de imagen compatible con OpenAI",
"Please Configure the OpenAI Image Source": "Configure la **URL base** y el **modelo** del origen de imágenes compatible con OpenAI (**clave de API** opcional para puertas de enlace locales)",
"Video Encoder": "Codificador de vídeo",
+ "Material Concurrency": "Concurrencia de materiales",
+ "Material Concurrency Help": "Cuántas búsquedas y descargas de material se ejecutan a la vez. 1 es secuencial y 4 es recomendado; valores mayores pueden activar límites del proveedor.",
+ "Clip Rendering Concurrency": "Concurrencia de renderizado de clips",
+ "Clip Rendering Concurrency Help": "Cuántos clips se recortan, ajustan de velocidad y codifican a la vez. 1 es secuencial y 4 es recomendado; valores mayores usan más CPU y memoria.",
+ "Generated Video Files Unavailable": "Los archivos de video generados ya no están disponibles. Pueden haber sido depurados. Los registros de tareas siguen siendo legibles.",
"Default Video Encoder": "Predeterminado (recomendado)",
"Video Encoder Help": "Opción avanzada. Predeterminado sigue la política estable de la aplicación, actualmente libx264. Si un codificador de hardware no está disponible, la aplicación vuelve automáticamente a libx264.",
"Auto-Publish Settings": "Configuración de publicación automática",
diff --git a/webui/i18n/fr.json b/webui/i18n/fr.json
index 63a14468..2e88f8b3 100644
--- a/webui/i18n/fr.json
+++ b/webui/i18n/fr.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Modèle d'image compatible OpenAI",
"Please Configure the OpenAI Image Source": "Veuillez configurer l'**URL de base** et le **modèle** de la source d'images compatible OpenAI (**clé API** facultative pour les passerelles locales)",
"Video Encoder": "Encodeur vidéo",
+ "Material Concurrency": "Concurrence des médias",
+ "Material Concurrency Help": "Nombre de recherches et de téléchargements de médias exécutés simultanément. 1 est séquentiel et 4 est recommandé ; des valeurs plus élevées peuvent déclencher des limites du fournisseur.",
+ "Clip Rendering Concurrency": "Concurrence de rendu des clips",
+ "Clip Rendering Concurrency Help": "Nombre de clips recadrés, ajustés en vitesse et encodés simultanément. 1 est séquentiel et 4 est recommandé ; des valeurs plus élevées utilisent plus de CPU et de mémoire.",
+ "Generated Video Files Unavailable": "Les fichiers vidéo générés ne sont plus disponibles. Ils ont peut-être été nettoyés. Les journaux des tâches restent lisibles.",
"Default Video Encoder": "Par défaut (Recommandé)",
"Video Encoder Help": "Option avancée. Par défaut, utilise la stratégie d'encodage stable de l'application (actuellement libx264). Si un encodeur matériel sélectionné n'est pas disponible, l'application bascule automatiquement sur libx264.",
"Auto-Publish Settings": "Paramètres de publication automatique",
diff --git a/webui/i18n/id.json b/webui/i18n/id.json
index 0d1e3e6a..16f14b11 100644
--- a/webui/i18n/id.json
+++ b/webui/i18n/id.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Model Gambar Kompatibel OpenAI",
"Please Configure the OpenAI Image Source": "Silakan konfigurasikan **URL Dasar** dan **Model** untuk sumber gambar kompatibel OpenAI (**Kunci API** opsional untuk gateway lokal)",
"Video Encoder": "Encoder Video",
+ "Material Concurrency": "Konkurensi materi",
+ "Material Concurrency Help": "Berapa banyak pencarian dan unduhan materi yang berjalan bersamaan. 1 berurutan dan 4 direkomendasikan; nilai lebih tinggi dapat memicu batas penyedia.",
+ "Clip Rendering Concurrency": "Konkurensi rendering klip",
+ "Clip Rendering Concurrency Help": "Berapa banyak klip yang dipotong, disesuaikan kecepatannya, dan dikodekan bersamaan. 1 berurutan dan 4 direkomendasikan; nilai lebih tinggi menggunakan lebih banyak CPU dan memori.",
+ "Generated Video Files Unavailable": "Berkas video yang dihasilkan tidak lagi tersedia. Mungkin telah dibersihkan. Log tugas tetap dapat dibaca.",
"Default Video Encoder": "Default (Direkomendasikan)",
"Video Encoder Help": "Opsi lanjutan. Default mengikuti kebijakan encoder stabil aplikasi, saat ini libx264. Jika encoder perangkat keras tidak tersedia, aplikasi otomatis kembali ke libx264.",
"Auto-Publish Settings": "Pengaturan Publikasi Otomatis",
diff --git a/webui/i18n/it.json b/webui/i18n/it.json
index 505f843f..ba40f96f 100644
--- a/webui/i18n/it.json
+++ b/webui/i18n/it.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Modello immagine compatibile OpenAI",
"Please Configure the OpenAI Image Source": "Configura **URL di base** e **modello** per l'origine immagini compatibile OpenAI (**chiave API** facoltativa per gateway locali)",
"Video Encoder": "Codificatore video",
+ "Material Concurrency": "Concorrenza dei materiali",
+ "Material Concurrency Help": "Quante ricerche e download di materiali vengono eseguiti contemporaneamente. 1 è seriale e 4 è consigliato; valori più alti possono attivare limiti del provider.",
+ "Clip Rendering Concurrency": "Concorrenza di rendering dei clip",
+ "Clip Rendering Concurrency Help": "Quanti clip vengono ritagliati, adattati in velocità e codificati contemporaneamente. 1 è seriale e 4 è consigliato; valori più alti usano più CPU e memoria.",
+ "Generated Video Files Unavailable": "I file video generati non sono più disponibili. Potrebbero essere stati ripuliti. I log delle attività restano leggibili.",
"Default Video Encoder": "Predefinito (consigliato)",
"Video Encoder Help": "Opzione avanzata. Il valore predefinito segue la politica di codifica stabile dell'applicazione, attualmente libx264. Se un codificatore hardware selezionato non è disponibile, l'applicazione torna automaticamente a libx264.",
"Auto-Publish Settings": "Impostazioni di pubblicazione automatica",
diff --git a/webui/i18n/ko.json b/webui/i18n/ko.json
index f9c5f82c..1d205cca 100644
--- a/webui/i18n/ko.json
+++ b/webui/i18n/ko.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "OpenAI 호환 이미지 모델",
"Please Configure the OpenAI Image Source": "OpenAI 호환 이미지 소스의 **Base URL**과 **모델**을 구성해 주세요 (로컬 게이트웨이는 **API 키** 선택 사항)",
"Video Encoder": "영상 인코더",
+ "Material Concurrency": "소재 동시 처리 수",
+ "Material Concurrency Help": "소재 검색과 다운로드를 동시에 몇 개 실행할지 정합니다. 1은 순차 처리이고 4를 권장합니다. 값이 너무 크면 제공사 요금 제한이 걸릴 수 있습니다.",
+ "Clip Rendering Concurrency": "클립 렌더링 동시 처리 수",
+ "Clip Rendering Concurrency Help": "동시에 몇 개의 클립을 자르고, 재생 속도를 조정하고, 인코딩할지 정합니다. 1은 순차 처리이고 4를 권장합니다. 값이 크면 CPU와 메모리를 더 사용합니다.",
+ "Generated Video Files Unavailable": "생성된 영상 파일을 더 이상 사용할 수 없습니다. 정리되었을 수 있습니다. 작업 로그는 계속 확인할 수 있습니다.",
"Default Video Encoder": "기본값 (권장)",
"Video Encoder Help": "고급 옵션입니다. 기본값은 앱의 안정적인 인코더 정책(현재 libx264)을 따릅니다. 선택한 하드웨어 인코더를 사용할 수 없으면 자동으로 libx264로 대체됩니다.",
"Auto-Publish Settings": "자동 게시 설정",
diff --git a/webui/i18n/pt.json b/webui/i18n/pt.json
index c7da52ff..c366694f 100644
--- a/webui/i18n/pt.json
+++ b/webui/i18n/pt.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Modelo de imagem compatível com OpenAI",
"Please Configure the OpenAI Image Source": "Configure a **URL base** e o **modelo** da fonte de imagens compatível com OpenAI (**chave de API** opcional para gateways locais)",
"Video Encoder": "Codificador de vídeo",
+ "Material Concurrency": "Concorrência de materiais",
+ "Material Concurrency Help": "Quantas pesquisas e downloads de material são executados ao mesmo tempo. 1 é sequencial e 4 é recomendado; valores maiores podem acionar limites do provedor.",
+ "Clip Rendering Concurrency": "Concorrência de renderização de clipes",
+ "Clip Rendering Concurrency Help": "Quantos clipes são cortados, ajustados em velocidade e codificados ao mesmo tempo. 1 é sequencial e 4 é recomendado; valores maiores usam mais CPU e memória.",
+ "Generated Video Files Unavailable": "Os arquivos de vídeo gerados não estão mais disponíveis. Podem ter sido limpos. Os registros da tarefa continuam legíveis.",
"Default Video Encoder": "Padrão (recomendado)",
"Video Encoder Help": "Opção avançada. Padrão segue a política estável do aplicativo, atualmente libx264. Se um codificador de hardware não estiver disponível, o aplicativo retorna automaticamente para libx264.",
"Auto-Publish Settings": "Configurações de Publicação Automática",
diff --git a/webui/i18n/ru.json b/webui/i18n/ru.json
index f2907666..ce58ca70 100644
--- a/webui/i18n/ru.json
+++ b/webui/i18n/ru.json
@@ -386,6 +386,11 @@
"OpenAI Image Model": "Модель изображений, совместимая с OpenAI",
"Please Configure the OpenAI Image Source": "Настройте **базовый URL** и **модель** источника изображений, совместимого с OpenAI (**API-ключ** необязателен для локальных шлюзов)",
"Video Encoder": "Видеокодер",
+ "Material Concurrency": "Параллельная загрузка материалов",
+ "Material Concurrency Help": "Сколько поисков и загрузок материалов выполняется одновременно. 1 — последовательно, 4 — рекомендуемое значение; более высокие значения могут вызвать лимиты провайдера.",
+ "Clip Rendering Concurrency": "Параллельный рендеринг клипов",
+ "Clip Rendering Concurrency Help": "Сколько клипов одновременно обрезается, масштабируется по скорости и кодируется. 1 — последовательно, 4 — рекомендуемое значение; более высокие значения требуют больше CPU и памяти.",
+ "Generated Video Files Unavailable": "Сгенерированные видеофайлы больше недоступны. Возможно, они были очищены. Журналы задачи остаются доступными.",
"Default Video Encoder": "По умолчанию (рекомендуется)",
"Video Encoder Help": "Дополнительная настройка. Значение по умолчанию следует стабильной политике приложения, сейчас это libx264. Если аппаратный кодер недоступен, приложение автоматически вернется к libx264.",
"Custom Position (% from top)": "Пользовательское положение (% от верхнего края)",
diff --git a/webui/i18n/tr.json b/webui/i18n/tr.json
index 9da94af2..50c7d503 100644
--- a/webui/i18n/tr.json
+++ b/webui/i18n/tr.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "OpenAI Uyumlu Görüntü Modeli",
"Please Configure the OpenAI Image Source": "OpenAI uyumlu görüntü kaynağı için **Temel URL** ve **Model** ayarlarını yapılandırın (yerel ağ geçitleri için **API Anahtarı** isteğe bağlıdır)",
"Video Encoder": "Video Kodlayıcı",
+ "Material Concurrency": "Materyal eşzamanlılığı",
+ "Material Concurrency Help": "Aynı anda kaç materyal arama ve indirme çalışsın. 1 seri, 4 önerilir; daha yüksek değerler sağlayıcı limitlerini tetikleyebilir.",
+ "Clip Rendering Concurrency": "Klip işleme eşzamanlılığı",
+ "Clip Rendering Concurrency Help": "Aynı anda kaç klibin kırpılacağı, hızının ayarlanacağı ve kodlanacağı. 1 seri, 4 önerilir; daha yüksek değerler daha fazla CPU ve bellek kullanır.",
+ "Generated Video Files Unavailable": "Oluşturulan video dosyaları artık kullanılamıyor. Temizlenmiş olabilirler. Görev günlükleri okunmaya devam eder.",
"Default Video Encoder": "Varsayılan (Önerilen)",
"Video Encoder Help": "Gelişmiş seçenek. Varsayılan, uygulamanın kararlı kodlayıcı politikasını izler; şu anda libx264 kullanılır. Donanım kodlayıcı kullanılamıyorsa uygulama otomatik olarak libx264'e döner.",
"Auto-Publish Settings": "Otomatik Yayınlama Ayarları",
diff --git a/webui/i18n/vi.json b/webui/i18n/vi.json
index 8a179978..cf9644ed 100644
--- a/webui/i18n/vi.json
+++ b/webui/i18n/vi.json
@@ -390,6 +390,11 @@
"OpenAI Image Model": "Mô hình ảnh tương thích OpenAI",
"Please Configure the OpenAI Image Source": "Vui lòng cấu hình **URL cơ sở** và **Mô hình** cho nguồn ảnh tương thích OpenAI (**Khóa API** tùy chọn cho cổng kết nối cục bộ)",
"Video Encoder": "Bộ Mã Hóa Video",
+ "Material Concurrency": "Số song song của tư liệu",
+ "Material Concurrency Help": "Số lần tìm kiếm và tải tư liệu chạy cùng lúc. 1 là tuần tự và 4 là đề xuất; giá trị cao hơn có thể kích hoạt giới hạn của nhà cung cấp.",
+ "Clip Rendering Concurrency": "Số song song khi dựng clip",
+ "Clip Rendering Concurrency Help": "Số clip được cắt, chỉnh tốc độ và mã hóa cùng lúc. 1 là tuần tự và 4 là đề xuất; giá trị cao hơn dùng nhiều CPU và bộ nhớ hơn.",
+ "Generated Video Files Unavailable": "Các tệp video đã tạo hiện không dùng được. Có thể chúng đã bị dọn dẹp. Nhật ký tác vụ vẫn xem được.",
"Default Video Encoder": "Mặc định (Khuyên dùng)",
"Video Encoder Help": "Tùy chọn nâng cao. Mặc định tuân theo chính sách mã hóa ổn định của ứng dụng, hiện là libx264. Nếu bộ mã hóa phần cứng không khả dụng, ứng dụng tự động chuyển về libx264.",
"Auto-Publish Settings": "Cài đặt tự động xuất bản",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index a0daffea..8dd10552 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -219,6 +219,7 @@
"Start Generating Video": "开始生成视频",
"Video Generation Completed": "视频生成完成",
"Video Generation Failed": "视频生成失败",
+ "Generated Video Files Unavailable": "生成的视频文件已不可用,可能已被清理。任务日志仍可查看。",
"Download Video": "下载视频",
"You can download the generated video from the following links": "你可以从以下链接下载生成的视频",
"Basic Settings": "**基础设置** (:blue[点击展开])",
@@ -467,6 +468,10 @@
"OpenAI Image Model": "OpenAI 兼容文生图模型",
"Please Configure the OpenAI Image Source": "请配置 OpenAI 兼容文生图的 **Base URL** 和 **模型**(本地网关可免填 **API 密钥**)",
"Video Encoder": "视频编码器",
+ "Material Concurrency": "素材并发",
+ "Material Concurrency Help": "搜索和下载素材的同时处理数量。1 为串行,推荐 4;设置过高可能触发素材平台限流。",
+ "Clip Rendering Concurrency": "片段渲染并发",
+ "Clip Rendering Concurrency Help": "同时裁剪、变速和编码视频片段的数量。1 为串行,推荐 4;设置过高会占用更多 CPU 和内存。",
"Default Video Encoder": "默认(推荐)",
"Video Encoder Help": "高级选项。“默认”跟随项目的稳定编码策略,当前使用 libx264;选择硬件编码器时,如果当前 FFmpeg、显卡或驱动不可用,会自动回退到 libx264。",
"API Platform": "API 平台",