Download runs/scripts/inference_episode.py from BlueSourceJY/ERCBench-MultiShotMaster-400: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/resolve/main/runs/scripts/inference_episode.py
- Command line
-
hf download hf://datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/runs/scripts/inference_episode.py
-
curl -L -o inference_episode.py https://huggingface.co/datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/resolve/main/runs/scripts/inference_episode.py
5.93 kB
| import torch | |
| from diffsynth.utils.data import save_video | |
| from diffsynth.pipelines.wan_video import WanVideoPipeline, ModelConfig | |
| import pandas as pd | |
| import ast | |
| import json | |
| import os | |
| import argparse | |
| from util import rgb_to_latent_shot_groups_list, pad_shot_groups_to_4n_plus_1, get_user_wanted_frames, save_video_with_caption | |
| import random, sys | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--test_csv_path", type=str, default=None) | |
| parser.add_argument("--model_path_json", type=str, default=None) | |
| parser.add_argument("--output_name", type=str, default="1.3b") | |
| parser.add_argument("--target_width", type=int, default=832) | |
| parser.add_argument("--target_height", type=int, default=480) | |
| parser.add_argument("--use_usp", type=bool, default=False) | |
| # [episode run] output named by episode_id, skip finished outputs, claim-based priority-order loop over several GPUs | |
| parser.add_argument("--output_folder", type=str, default=None) | |
| parser.add_argument("--claim_dir", type=str, default=None) | |
| parser.add_argument("--extra_csv_first", type=str, default=None) | |
| args = parser.parse_args() | |
| negative_prompt="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" | |
| # init | |
| load_path_json = args.model_path_json | |
| with open(load_path_json) as user_file: | |
| model_paths = json.load(user_file) | |
| pipe = WanVideoPipeline.from_pretrained( | |
| torch_dtype=torch.bfloat16, | |
| device="cuda", | |
| use_usp=args.use_usp, # if use usp for inference | |
| model_configs=[ | |
| ModelConfig(path=model_paths["dit"]), | |
| ModelConfig(path=model_paths["t5"]), | |
| ModelConfig(path=model_paths["vae"]), | |
| ], | |
| tokenizer_config=ModelConfig(path=model_paths["tokenizer"]), | |
| ) | |
| # read test cases | |
| df = pd.read_csv(args.test_csv_path) | |
| if args.extra_csv_first: # [episode run] process these rows first (smoke episode), then the main priority-ordered CSV | |
| df = pd.concat([pd.read_csv(args.extra_csv_first), df], ignore_index=True) | |
| output_dir = args.output_folder if args.output_folder else f"output/{args.output_name}" | |
| print(f"output_dir: {output_dir}") | |
| os.makedirs(output_dir, exist_ok=True) | |
| import datetime, subprocess | |
| def _ts(): | |
| return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") | |
| def _nframes(path): | |
| r = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", | |
| "stream=nb_read_frames", "-of", "csv=p=0", path], capture_output=True, text=True) | |
| try: | |
| return int(r.stdout.strip()) | |
| except ValueError: | |
| return -1 | |
| os.makedirs(args.claim_dir, exist_ok=True) | |
| for index, row in df.iterrows(): | |
| episode_id = row["episode_id"] | |
| out_path = f"{output_dir}/{episode_id}.mp4" | |
| want_frames = ast.literal_eval(row["shot_groups"])[-1][-1] | |
| if os.path.exists(out_path) and _nframes(out_path) == want_frames: | |
| print(f"{_ts()} [EPISODE] skip {episode_id} (exists, {want_frames} frames)", flush=True) | |
| continue | |
| try: | |
| os.mkdir(os.path.join(args.claim_dir, episode_id)) # atomic claim: another GPU already took it -> next | |
| except FileExistsError: | |
| continue | |
| print(f"{_ts()} [EPISODE] start {episode_id} priority={row['priority']} seed=42", flush=True) | |
| torch.cuda.reset_peak_memory_stats() | |
| # do not use random seed when use_usp=True | |
| seed = 42 # random.randint(0, sys.maxsize) | |
| # read shot groups and transform to latent shot groups | |
| shot_groups = ast.literal_eval(row["shot_groups"]) | |
| padded_shot_groups, save_shot_num_list = pad_shot_groups_to_4n_plus_1(shot_groups) | |
| latent_shot_groups = rgb_to_latent_shot_groups_list(padded_shot_groups) | |
| # read multi-shot captions | |
| with open(row["gemini_caption"]) as user_file: | |
| caption_dict = json.load(user_file) | |
| num_shots = len(latent_shot_groups) | |
| # global caption | |
| global_caption = f"Story: {caption_dict['global_caption']} " | |
| # per-shot captions | |
| now_multishot_video_caption_list = [] | |
| for count in range(num_shots): | |
| now_shot_caption = global_caption + f"Now: {caption_dict[f'shot{count}']}" | |
| now_multishot_video_caption_list.append(now_shot_caption) | |
| multishot_negative_prompt = [negative_prompt] * num_shots | |
| # Text-to-video | |
| video = pipe( | |
| width=args.target_width, | |
| height=args.target_height, | |
| prompt=now_multishot_video_caption_list, | |
| negative_prompt=multishot_negative_prompt, | |
| seed=seed, tiled=True, | |
| num_frames=latent_shot_groups[-1][-1], | |
| shot_groups=shot_groups, | |
| latent_shot_groups=latent_shot_groups, | |
| ) | |
| user_wanted_frames = get_user_wanted_frames(video, padded_shot_groups, save_shot_num_list) | |
| # save video without caption | |
| save_video(user_wanted_frames, out_path, fps=15, quality=5) | |
| # save video with caption | |
| save_video_with_caption(num_shots, shot_groups, now_multishot_video_caption_list, user_wanted_frames, f"{output_dir}/{episode_id}_with_caption.mp4", args.target_width) | |
| print(f"{_ts()} [EPISODE] saved {episode_id} -> {out_path} peak_mem_gb={torch.cuda.max_memory_allocated()/2**30:.1f}", flush=True) | |
| print("Enjoy the story") | |
| torch.cuda.empty_cache() | |