Skip to content

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

fix(video): deduplicate temporary file cleanup

harry07031b181c5e3cf6
diff --git a/app/services/video.py b/app/services/video.py
index 548ffc53..dcca6322 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -491,11 +491,21 @@ def delete_files(files: List[str] | str):
if isinstance(files, str):
files = [files]
- for file in files:
+ # 循环补足视频时,同一个临时片段路径会在 FFmpeg 拼接列表中出现多次。
+ # 拼接必须保留重复项,但清理只能删除一次;这里按原顺序统一去重,让所有
+ # 调用方都获得幂等行为,也避免首次删除成功后连续输出 FileNotFoundError。
+ unique_files = dict.fromkeys(file for file in files if file)
+ for file in unique_files:
try:
os.remove(file)
- except Exception as e:
- logger.debug(f"failed to delete file {file}: {str(e)}")
+ except FileNotFoundError:
+ # 清理动作允许文件已经不存在,例如 FFmpeg 失败路径或并发清理已经
+ # 回收文件;这不是需要用户处理的问题,不应污染生成日志。
+ continue
+ except OSError as e:
+ # 权限、只读文件系统或磁盘异常会留下真实临时文件,保留 warning
+ # 便于根据具体路径和系统错误定位环境问题。
+ logger.warning(f"failed to delete temporary file {file}: {str(e)}")
def get_bgm_file(bgm_type: str = "random", bgm_file: str = ""):
diff --git a/test/services/test_video.py b/test/services/test_video.py
index 8cd97f73..b447e446 100644
--- a/test/services/test_video.py
+++ b/test/services/test_video.py
@@ -63,6 +63,54 @@ class TestVideoService(unittest.TestCase):
vd._runtime_disabled_video_codecs.clear()
vd._ffmpeg_encoder_exists.cache_clear()
+ def test_delete_files_deduplicates_paths_and_ignores_missing_files(self):
+ """
+ 循环片段会让同一路径在拼接列表中重复出现,清理时每个路径只能删除一次。
+
+ 已不存在的文件属于幂等清理的正常状态,不应再产生误导用户的失败日志。
+ """
+ with tempfile.TemporaryDirectory() as temp_dir:
+ existing_file = os.path.join(temp_dir, "temp-clip-1.mp4")
+ missing_file = os.path.join(temp_dir, "already-removed.mp4")
+ Path(existing_file).write_bytes(b"temporary clip")
+
+ original_remove = os.remove
+ with (
+ patch.object(vd.os, "remove", wraps=original_remove) as remove,
+ patch.object(vd.logger, "warning") as warning,
+ ):
+ vd.delete_files(
+ [
+ existing_file,
+ existing_file,
+ missing_file,
+ missing_file,
+ ]
+ )
+
+ self.assertEqual(
+ [item.args[0] for item in remove.call_args_list],
+ [existing_file, missing_file],
+ )
+ warning.assert_not_called()
+
+ def test_delete_files_logs_actionable_os_errors(self):
+ """权限等真实清理失败必须保留路径和系统错误,方便定位残留文件。"""
+ with (
+ patch.object(
+ vd.os,
+ "remove",
+ side_effect=PermissionError("permission denied"),
+ ),
+ patch.object(vd.logger, "warning") as warning,
+ ):
+ vd.delete_files(["protected-temp-clip.mp4"])
+
+ warning.assert_called_once()
+ message = warning.call_args.args[0]
+ self.assertIn("protected-temp-clip.mp4", message)
+ self.assertIn("permission denied", message)
+
def test_generate_video_reports_successful_bgm_mix_and_closes_sources(self):
"""BGM 混合成功后应返回 True,并释放所有原始文件 reader。"""
params = vd.VideoParams(