HunyuanVideo: A Systematic Framework For Large Video Generation Model
fix(output): keep generated videos inside the save directory
KimbingNgcc2342e82964
diff --git a/gradio_server.py b/gradio_server.pyindex 3aa5a53..22e22ec 100644--- a/gradio_server.py+++ b/gradio_server.py@@ -1,12 +1,11 @@import os-import time+from datetime import datetimefrom pathlib import Pathfrom loguru import logger-from datetime import datetimeimport gradio as grimport random-from hyvideo.utils.file_utils import save_videos_grid+from hyvideo.utils.file_utils import contained_file, save_videos_gridfrom hyvideo.config import parse_argsfrom hyvideo.inference import HunyuanVideoSamplerfrom hyvideo.constants import NEGATIVE_PROMPT@@ -55,14 +54,13 @@ def generate_video(sample = samples[0].unsqueeze(0)save_path = os.path.join(os.getcwd(), "gradio_outputs")- os.makedirs(save_path, exist_ok=True)-- time_flag = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d-%H:%M:%S")- video_path = f"{save_path}/{time_flag}_seed{outputs['seeds'][0]}_{outputs['prompts'][0][:100].replace('/','')}.mp4"+ time_flag = datetime.now().strftime("%Y-%m-%d-%H%M%S")+ filename = f"{time_flag}_seed{outputs['seeds'][0]}_{outputs['prompts'][0][:100]}.mp4"+ video_path = contained_file(save_path, filename)save_videos_grid(sample, video_path, fps=24)- logger.info(f'Sample saved to: {video_path}')-- return video_path+ logger.info(f"Sample saved to: {video_path}")++ return str(video_path)def create_demo(model_path, save_path):model = initialize_model(model_path)diff --git a/hyvideo/utils/file_utils.py b/hyvideo/utils/file_utils.pyindex 2ba3651..5df47cb 100644--- a/hyvideo/utils/file_utils.py+++ b/hyvideo/utils/file_utils.py@@ -1,5 +1,5 @@-import os-from pathlib import Path+from pathlib import Path, PureWindowsPath+from einops import rearrangeimport torch@@ -14,6 +14,22 @@ CODE_SUFFIXES = {".yml", # Configuration files}+def contained_file(directory, filename: str) -> Path:+ """Join a filename under directory, ignoring any directory part in the name.++ PureWindowsPath.name treats both '/' and '\\' as separators, so a prompt+ such as '..\\\\..\\\\evil' cannot escape on Windows or POSIX. resolve()+ then relative_to() rejects symlink escapes.+ """+ root = Path(directory).expanduser().resolve()+ root.mkdir(parents=True, exist_ok=True)+ leaf = PureWindowsPath(str(filename)).name+ if leaf in {"", ".", ".."}:+ raise ValueError(f"Refusing unsafe filename: {filename}")+ path = (root / leaf).resolve()+ path.relative_to(root)+ return path+def safe_dir(path):"""@@ -50,7 +66,7 @@ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=1, fArgs:videos (torch.Tensor): video tensor predicted by the model- path (str): path to save video+ path (str): path to save video. Parent directory must already exist.rescale (bool, optional): rescale the video tensor from [-1, 1] to . Defaults to False.n_rows (int, optional): Defaults to 1.fps (int, optional): video save fps. Defaults to 8.@@ -66,5 +82,4 @@ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=1, fx = (x * 255).numpy().astype(np.uint8)outputs.append(x)- os.makedirs(os.path.dirname(path), exist_ok=True)imageio.mimsave(path, outputs, fps=fps)diff --git a/sample_video.py b/sample_video.pyindex 14778d4..a91d5aa 100644--- a/sample_video.py+++ b/sample_video.py@@ -1,10 +1,9 @@import os-import time+from datetime import datetimefrom pathlib import Pathfrom loguru import logger-from datetime import datetime-from hyvideo.utils.file_utils import save_videos_grid+from hyvideo.utils.file_utils import contained_file, save_videos_gridfrom hyvideo.config import parse_argsfrom hyvideo.inference import HunyuanVideoSampler@@ -49,10 +48,11 @@ def main():if 'LOCAL_RANK' not in os.environ or int(os.environ['LOCAL_RANK']) == 0:for i, sample in enumerate(samples):sample = samples[i].unsqueeze(0)- time_flag = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d-%H:%M:%S")- cur_save_path = f"{save_path}/{time_flag}_seed{outputs['seeds'][i]}_{outputs['prompts'][i][:100].replace('/','')}.mp4"+ time_flag = datetime.now().strftime("%Y-%m-%d-%H%M%S")+ filename = f"{time_flag}_seed{outputs['seeds'][i]}_{outputs['prompts'][i][:100]}.mp4"+ cur_save_path = contained_file(save_path, filename)save_videos_grid(sample, cur_save_path, fps=24)- logger.info(f'Sample save to: {cur_save_path}')+ logger.info(f"Sample save to: {cur_save_path}")if __name__ == "__main__":main()