File size: 10,234 Bytes
c6b4c59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
import numpy as np
import argparse
import imageio
import torch
import json
from einops import rearrange
from diffusers import DDIMScheduler, AutoencoderKL
from transformers import CLIPTextModel, CLIPTokenizer
import torchvision
from controlnet_aux.processor import Processor
from models.pipeline_controlvideo import ControlVideoPipeline
from models.util import save_videos_grid, read_video
from models.unet import UNet3DConditionModel
from models.controlnet import ControlNetModel3D
from models.RIFE.IFNet_HDv3 import IFNet

# Device and model checkpoint paths
device = "cuda"
sd_path = "checkpoints/stable-diffusion-v1-5"
inter_path = "checkpoints/flownet.pkl"
controlnet_dict_version = {
    "v10": {
        "openpose": "checkpoints/sd-controlnet-openpose",
        "depth_midas": "checkpoints/sd-controlnet-depth",
        "canny": "checkpoints/sd-controlnet-canny",
    },
    "v11": {
        "softedge_pidinet": "checkpoints/control_v11p_sd15_softedge",
        "softedge_pidsafe": "checkpoints/control_v11p_sd15_softedge",
        "softedge_hed": "checkpoints/control_v11p_sd15_softedge",
        "softedge_hedsafe": "checkpoints/control_v11p_sd15_softedge",
        "scribble_hed": "checkpoints/control_v11p_sd15_scribble",
        "scribble_pidinet": "checkpoints/control_v11p_sd15_scribble",
        "lineart_anime": "checkpoints/control_v11p_sd15_lineart_anime",
        "lineart_coarse": "checkpoints/control_v11p_sd15_lineart",
        "lineart_realistic": "checkpoints/control_v11p_sd15_lineart",
        "depth_midas": "checkpoints/control_v11f1p_sd15_depth",
        "depth_leres": "checkpoints/control_v11f1p_sd15_depth",
        "depth_leres++": "checkpoints/control_v11f1p_sd15_depth",
        "depth_zoe": "checkpoints/control_v11f1p_sd15_depth",
        "canny": "checkpoints/control_v11p_sd15_canny",
        "openpose": "checkpoints/control_v11p_sd15_openpose",
        "openpose_face": "checkpoints/control_v11p_sd15_openpose",
        "openpose_faceonly": "checkpoints/control_v11p_sd15_openpose",
        "openpose_full": "checkpoints/control_v11p_sd15_openpose",
        "openpose_hand": "checkpoints/control_v11p_sd15_openpose",
        "normal_bae": "checkpoints/control_v11p_sd15_normalbae"
    }
}

# Positive and negative prompts for generation
POS_PROMPT = " ,best quality, extremely detailed, HD, ultra-realistic, 8K, HQ, masterpiece, trending on artstation, art, smooth"
NEG_PROMPT = "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic"

def get_args():
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--jsonl_path", type=str, default=None, help="Path to JSONL file for batch processing")
    parser.add_argument("--prompt", type=str, default=None, help="Text description of target video (used for single video mode)")
    parser.add_argument("--video_path", type=str, default=None, help="Path to a source video (used for single video mode)")
    parser.add_argument("--output_path", type=str, default="./outputs", help="Directory for output videos")
    parser.add_argument("--condition", type=str, default="depth", help="Condition of structure sequence")
    parser.add_argument("--video_length", type=int, default=15, help="Length of synthesized video")
    parser.add_argument("--height", type=int, default=512, help="Height of synthesized video, must be a multiple of 32")
    parser.add_argument("--width", type=int, default=512, help="Width of synthesized video, must be a multiple of 32")
    parser.add_argument("--smoother_steps", nargs='+', default=[19, 20], type=int, help="Timesteps for interleaved-frame smoother")
    parser.add_argument("--is_long_video", action='store_true', help="Use hierarchical sampler for long videos")
    parser.add_argument("--seed", type=int, default=42, help="Random seed for generator")
    parser.add_argument("--version", type=str, default='v10', choices=["v10", "v11"], help="ControlNet version")
    parser.add_argument("--frame_rate", type=int, default=None, help="Frame rate of input video (default computed from video length)")
    parser.add_argument("--temp_video_name", type=str, default=None, help="Default video name for single video mode")
    
    args = parser.parse_args()
    return args

def process_video(prompt, video_path, output_path, condition, video_length, height, width, smoother_steps, 
                  is_long_video, seed, version, frame_rate, temp_video_name, pipe, generator):
    """Process a single video with the given parameters."""
    # Ensure output directory exists
    os.makedirs(output_path, exist_ok=True)
    
    # Adjust height and width to be multiples of 32
    height = (height // 32) * 32
    width = (width // 32) * 32

    # Step 1: Read the video
    video = read_video(video_path=video_path, video_length=video_length, width=width, height=height, frame_rate=frame_rate)
    original_pixels = rearrange(video, "(b f) c h w -> b c f h w", b=1)
    save_videos_grid(original_pixels, os.path.join(output_path, f"source_{temp_video_name}"), rescale=True)

    # Step 2: Parse video to conditional frames
    processor = Processor(condition)
    t2i_transform = torchvision.transforms.ToPILImage()
    pil_annotation = [processor(t2i_transform(frame), to_pil=True) for frame in video]
    video_cond = [np.array(p).astype(np.uint8) for p in pil_annotation]
    imageio.mimsave(os.path.join(output_path, f"{condition}_condition_{temp_video_name}"), video_cond, fps=8)

    # Free up memory
    del processor
    torch.cuda.empty_cache()

    # Step 3: Inference
    if is_long_video:
        window_size = int(np.sqrt(video_length))
        sample = pipe.generate_long_video(
            prompt + POS_PROMPT, video_length=video_length, frames=pil_annotation,
            num_inference_steps=50, smooth_steps=smoother_steps, window_size=window_size,
            generator=generator, guidance_scale=12.5, negative_prompt=NEG_PROMPT,
            width=width, height=height
        ).videos
    else:
        sample = pipe(
            prompt + POS_PROMPT, video_length=video_length, frames=pil_annotation,
            num_inference_steps=50, smooth_steps=smoother_steps,
            generator=generator, guidance_scale=12.5, negative_prompt=NEG_PROMPT,
            width=width, height=height
        ).videos

    # Save the generated video
    save_videos_grid(sample, os.path.join(output_path, temp_video_name))

def main():
    """Main function to handle both single and batch video processing."""
    args = get_args()

    # Load models (shared across all videos)
    controlnet_dict = controlnet_dict_version[args.version]
    tokenizer = CLIPTokenizer.from_pretrained(sd_path, subfolder="tokenizer")
    text_encoder = CLIPTextModel.from_pretrained(sd_path, subfolder="text_encoder").to(dtype=torch.float16)
    vae = AutoencoderKL.from_pretrained(sd_path, subfolder="vae").to(dtype=torch.float16)
    unet = UNet3DConditionModel.from_pretrained_2d(sd_path, subfolder="unet").to(dtype=torch.float16)
    controlnet = ControlNetModel3D.from_pretrained_2d(controlnet_dict[args.condition]).to(dtype=torch.float16)
    interpolater = IFNet(ckpt_path=inter_path).to(dtype=torch.float16)
    scheduler = DDIMScheduler.from_pretrained(sd_path, subfolder="scheduler")

    pipe = ControlVideoPipeline(
        vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet,
        controlnet=controlnet, interpolater=interpolater, scheduler=scheduler,
    )
    pipe.enable_vae_slicing()
    pipe.enable_xformers_memory_efficient_attention()
    pipe.to(device)

    generator = torch.Generator(device="cuda")
    generator.manual_seed(args.seed)

    if args.jsonl_path:
        # Batch processing mode
        with open(args.jsonl_path, 'r') as f:
            for line in f:
                try:
                    data = json.loads(line.strip())
                    prompt = data['edit_prompt']
                    video_filename = data['video']
                    video_path = os.path.join('/home/wangjuntong/video_editing_dataset/all_sourse/', video_filename)
                    
                    # Process the video with the extracted parameters
                    process_video(
                        prompt=prompt,
                        video_path=video_path,
                        output_path=args.output_path,
                        condition=args.condition,
                        video_length=args.video_length,
                        height=args.height,
                        width=args.width,
                        smoother_steps=args.smoother_steps,
                        is_long_video=args.is_long_video,
                        seed=args.seed,
                        version=args.version,
                        frame_rate=args.frame_rate,
                        temp_video_name=video_filename,  # Output name matches input video name
                        pipe=pipe,
                        generator=generator
                    )
                    print(f"Processed video: {video_filename}")
                except Exception as e:
                    print(f"Error processing line '{line.strip()}': {e}")
    else:
        # Single video processing mode
        if not args.prompt or not args.video_path:
            raise ValueError("For single video mode, --prompt and --video_path are required.")
        temp_video_name = args.temp_video_name if args.temp_video_name else "output.mp4"
        process_video(
            prompt=args.prompt,
            video_path=args.video_path,
            output_path=args.output_path,
            condition=args.condition,
            video_length=args.video_length,
            height=args.height,
            width=args.width,
            smoother_steps=args.smoother_steps,
            is_long_video=args.is_long_video,
            seed=args.seed,
            version=args.version,
            frame_rate=args.frame_rate,
            temp_video_name=temp_video_name,
            pipe=pipe,
            generator=generator
        )
        print(f"Processed single video: {temp_video_name}")

if __name__ == "__main__":
    main()