vinesmsuic commited on
Commit
cc6a3a0
1 Parent(s): 52105c2
Files changed (1) hide show
  1. gradio_demo.py +397 -0
gradio_demo.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+
4
+ import os
5
+ import sys
6
+ import time
7
+ import subprocess
8
+ import shutil
9
+
10
+ import random
11
+ from omegaconf import OmegaConf
12
+ from moviepy.editor import VideoFileClip
13
+ from PIL import Image
14
+ import torch
15
+ import numpy as np
16
+
17
+
18
+ from black_box_image_edit.instructpix2pix import InstructPix2Pix
19
+ from prepare_video import crop_and_resize_video
20
+ from edit_image import infer_video
21
+
22
+ sys.path.insert(0, "i2vgen-xl")
23
+ from utils import load_ddim_latents_at_t
24
+ from pipelines.pipeline_i2vgen_xl import I2VGenXLPipeline
25
+ from run_group_ddim_inversion import ddim_inversion
26
+ from run_group_pnp_edit import init_pnp
27
+ from diffusers import DDIMInverseScheduler, DDIMScheduler
28
+ from diffusers.utils import load_image
29
+ import imageio
30
+
31
+
32
+ demo_examples = [
33
+ ["./demo/A kitten turning its head on a wooden floor.mp4", "./demo/A kitten turning its head on a wooden floor/edited_first_frame/A dog turning its head on a wooden floor.png", "Dog turning its head"],
34
+ ["./demo/An Old Man Doing Exercises For The Body And Mind.mp4", "./demo/An Old Man Doing Exercises For The Body And Mind/edited_first_frame/jack ma.png", "A Man Doing Exercises For The Body And Mind"],
35
+ ["./demo/Ballet.mp4", "./demo/Ballet/edited_first_frame/van gogh style.png", "Girl dancing ballet"],
36
+ ]
37
+
38
+ TEMP_DIR = "_demo_temp"
39
+
40
+ #================================================================================================
41
+ image_edit_model = InstructPix2Pix()
42
+
43
+ @torch.no_grad()
44
+ @spaces.GPU(duration=30)
45
+ def perform_edit(video_path, prompt, force_512=False, seed=42, negative_prompt=""):
46
+ edited_image_path = infer_video(image_edit_model,
47
+ video_path,
48
+ output_dir=TEMP_DIR,
49
+ prompt=prompt,
50
+ prompt_type="instruct",
51
+ force_512=force_512,
52
+ seed=seed,
53
+ negative_prompt=negative_prompt,
54
+ overwrite=True)
55
+ return edited_image_path
56
+ #================================================================================================
57
+
58
+ config = {
59
+ # DDIM inversion
60
+ "inverse_config": {
61
+ "image_size": [512, 512],
62
+ "n_frames": 16,
63
+ "cfg": 1.0,
64
+ "target_fps": 8,
65
+ "ddim_inv_prompt": "",
66
+ "prompt": "",
67
+ "negative_prompt": "",
68
+ },
69
+ "pnp_config": {
70
+ "random_ratio": 0.0,
71
+ "target_fps": 8,
72
+ },
73
+ }
74
+ config = OmegaConf.create(config)
75
+
76
+ # Initialize the I2VGenXL pipeline
77
+ pipe = I2VGenXLPipeline.from_pretrained(
78
+ "ali-vilab/i2vgen-xl",
79
+ torch_dtype=torch.float16,
80
+ variant="fp16",
81
+ ).to("cuda:0")
82
+
83
+ # Initialize the DDIM inverse scheduler
84
+ inverse_scheduler = DDIMInverseScheduler.from_pretrained(
85
+ "ali-vilab/i2vgen-xl",
86
+ subfolder="scheduler",
87
+ )
88
+ # Initialize the DDIM scheduler
89
+ ddim_scheduler = DDIMScheduler.from_pretrained(
90
+ "ali-vilab/i2vgen-xl",
91
+ subfolder="scheduler",
92
+ )
93
+
94
+ @torch.no_grad()
95
+ @spaces.GPU(duration=150)
96
+ def perform_anyv2v(
97
+ video_path,
98
+ video_prompt,
99
+ video_negative_prompt,
100
+ edited_first_frame_path,
101
+ conv_inj,
102
+ spatial_inj,
103
+ temp_inj,
104
+ num_inference_steps,
105
+ guidance_scale,
106
+ ddim_init_latents_t_idx,
107
+ ddim_inversion_steps,
108
+ seed,
109
+ ):
110
+
111
+ tmp_dir = os.path.join(TEMP_DIR, "AnyV2V")
112
+ if os.path.exists(tmp_dir):
113
+ shutil.rmtree(tmp_dir)
114
+ os.makedirs(tmp_dir)
115
+
116
+ ddim_latents_path = os.path.join(tmp_dir, "ddim_latents")
117
+
118
+ def read_frames(video_path):
119
+ frames = []
120
+ with imageio.get_reader(video_path) as reader:
121
+ for i, frame in enumerate(reader):
122
+ pil_image = Image.fromarray(frame)
123
+ frames.append(pil_image)
124
+ return frames
125
+ frame_list = read_frames(str(video_path))
126
+
127
+ config.inverse_config.image_size = list(frame_list[0].size)
128
+ config.inverse_config.n_steps = ddim_inversion_steps
129
+ config.inverse_config.n_frames = len(frame_list)
130
+ config.inverse_config.output_dir = ddim_latents_path
131
+ ddim_init_latents_t_idx = min(ddim_init_latents_t_idx, num_inference_steps - 1)
132
+
133
+ # Step 1. DDIM Inversion
134
+ first_frame = frame_list[0]
135
+
136
+ generator = torch.Generator(device="cuda:0")
137
+ generator = generator.manual_seed(seed)
138
+ _ddim_latents = ddim_inversion(
139
+ config.inverse_config,
140
+ first_frame,
141
+ frame_list,
142
+ pipe,
143
+ inverse_scheduler,
144
+ generator,
145
+ )
146
+
147
+ # Step 2. DDIM Sampling + PnP feature and attention injection
148
+ # Load the edited first frame
149
+ edited_1st_frame = load_image(edited_first_frame_path).resize(
150
+ config.inverse_config.image_size, resample=Image.Resampling.LANCZOS
151
+ )
152
+ # Load the initial latents at t
153
+ ddim_scheduler.set_timesteps(num_inference_steps)
154
+ print(f"ddim_scheduler.timesteps: {ddim_scheduler.timesteps}")
155
+ ddim_latents_at_t = load_ddim_latents_at_t(
156
+ ddim_scheduler.timesteps[ddim_init_latents_t_idx],
157
+ ddim_latents_path=ddim_latents_path,
158
+ )
159
+ print(
160
+ f"ddim_scheduler.timesteps[t_idx]: {ddim_scheduler.timesteps[ddim_init_latents_t_idx]}"
161
+ )
162
+ print(f"ddim_latents_at_t.shape: {ddim_latents_at_t.shape}")
163
+
164
+ # Blend the latents
165
+ random_latents = torch.randn_like(ddim_latents_at_t)
166
+ print(
167
+ f"Blending random_ratio (1 means random latent): {config.pnp_config.random_ratio}"
168
+ )
169
+ mixed_latents = (
170
+ random_latents * config.pnp_config.random_ratio
171
+ + ddim_latents_at_t * (1 - config.pnp_config.random_ratio)
172
+ )
173
+
174
+ # Init Pnp
175
+ config.pnp_config.n_steps = num_inference_steps
176
+ config.pnp_config.pnp_f_t = conv_inj
177
+ config.pnp_config.pnp_spatial_attn_t = spatial_inj
178
+ config.pnp_config.pnp_temp_attn_t = temp_inj
179
+ config.pnp_config.ddim_init_latents_t_idx = ddim_init_latents_t_idx
180
+ init_pnp(pipe, ddim_scheduler, config.pnp_config)
181
+ # Edit video
182
+ pipe.register_modules(scheduler=ddim_scheduler)
183
+
184
+ edited_video = pipe.sample_with_pnp(
185
+ prompt=video_prompt,
186
+ image=edited_1st_frame,
187
+ height=config.inverse_config.image_size[1],
188
+ width=config.inverse_config.image_size[0],
189
+ num_frames=config.inverse_config.n_frames,
190
+ num_inference_steps=config.pnp_config.n_steps,
191
+ guidance_scale=guidance_scale,
192
+ negative_prompt=video_negative_prompt,
193
+ target_fps=config.pnp_config.target_fps,
194
+ latents=mixed_latents,
195
+ generator=generator,
196
+ return_dict=True,
197
+ ddim_init_latents_t_idx=ddim_init_latents_t_idx,
198
+ ddim_inv_latents_path=ddim_latents_path,
199
+ ddim_inv_prompt=config.inverse_config.ddim_inv_prompt,
200
+ ddim_inv_1st_frame=first_frame,
201
+ ).frames[0]
202
+
203
+ edited_video = [
204
+ frame.resize(config.inverse_config.image_size, resample=Image.LANCZOS)
205
+ for frame in edited_video
206
+ ]
207
+
208
+ def images_to_video(images, output_path, fps=24):
209
+ writer = imageio.get_writer(output_path, fps=fps)
210
+
211
+ for img in images:
212
+ img_np = np.array(img)
213
+ writer.append_data(img_np)
214
+
215
+ writer.close()
216
+ output_path = os.path.join(tmp_dir, "edited_video.mp4")
217
+ images_to_video(
218
+ edited_video, output_path, fps=config.pnp_config.target_fps
219
+ )
220
+ return output_path
221
+ #================================================================================================
222
+
223
+
224
+ def btn_preprocess_video_fn(video_path, width, height, start_time, end_time, center_crop, x_offset, y_offset, longest_to_width):
225
+ def check_video(video_path):
226
+ with VideoFileClip(video_path) as clip:
227
+ if clip.duration == 2 and clip.fps == 8:
228
+ return True
229
+ else:
230
+ return False
231
+
232
+ if check_video(video_path) == False:
233
+ processed_video_path = crop_and_resize_video(input_video_path=video_path,
234
+ output_folder=TEMP_DIR,
235
+ clip_duration=2,
236
+ width=width,
237
+ height=height,
238
+ start_time=start_time,
239
+ end_time=end_time,
240
+ center_crop=center_crop,
241
+ x_offset=x_offset,
242
+ y_offset=y_offset,
243
+ longest_to_width=longest_to_width)
244
+ return processed_video_path
245
+ else:
246
+ return video_path
247
+
248
+ def btn_image_edit_fn(video_path, instruct_prompt, ie_force_512, ie_seed, ie_neg_prompt):
249
+ """
250
+ Generate an image based on the video and text input.
251
+ This function should be replaced with your actual image generation logic.
252
+ """
253
+ # Placeholder logic for image generation
254
+
255
+ if ie_seed < 0:
256
+ ie_seed = int.from_bytes(os.urandom(2), "big")
257
+ print(f"Using seed: {ie_seed}")
258
+
259
+ edited_image_path = perform_edit(video_path=video_path,
260
+ prompt=instruct_prompt,
261
+ force_512=ie_force_512,
262
+ seed=ie_seed,
263
+ negative_prompt=ie_neg_prompt)
264
+ return edited_image_path
265
+
266
+
267
+ def btn_infer_fn(video_path,
268
+ video_prompt,
269
+ video_negative_prompt,
270
+ edited_first_frame_path,
271
+ conv_inj,
272
+ spatial_inj,
273
+ temp_inj,
274
+ num_inference_steps,
275
+ guidance_scale,
276
+ ddim_init_latents_t_idx,
277
+ ddim_inversion_steps,
278
+ seed,
279
+ ):
280
+ if seed < 0:
281
+ seed = int.from_bytes(os.urandom(2), "big")
282
+ print(f"Using seed: {seed}")
283
+
284
+ result_video_path = perform_anyv2v(video_path=video_path,
285
+ video_prompt=video_prompt,
286
+ video_negative_prompt=video_negative_prompt,
287
+ edited_first_frame_path=edited_first_frame_path,
288
+ conv_inj=conv_inj,
289
+ spatial_inj=spatial_inj,
290
+ temp_inj=temp_inj,
291
+ num_inference_steps=num_inference_steps,
292
+ guidance_scale=guidance_scale,
293
+ ddim_init_latents_t_idx=ddim_init_latents_t_idx,
294
+ ddim_inversion_steps=ddim_inversion_steps,
295
+ seed=seed)
296
+
297
+ return result_video_path
298
+
299
+ # Create the UI
300
+ #=====================================
301
+ with gr.Blocks() as demo:
302
+ gr.Markdown("# <img src='https://tiger-ai-lab.github.io/AnyV2V/static/images/icon.png' width='30'/> AnyV2V")
303
+ gr.Markdown("Official 🤗 Gradio demo for [AnyV2V: A Plug-and-Play Framework For Any Video-to-Video Editing Tasks](https://tiger-ai-lab.github.io/AnyV2V/)")
304
+ with gr.Row():
305
+ with gr.Column():
306
+ gr.Markdown("# Preprocessing Video Stage")
307
+ gr.Markdown("AnyV2V only support video with 2 seconds duration and 8 fps. If your video is not in this format, we will preprocess it for you. Click on the Preprocess video button!")
308
+ video_raw = gr.Video(label="Raw Video Input")
309
+ btn_pv = gr.Button("Preprocess Video")
310
+ video_input = gr.Video(label="Preprocessed Video Input")
311
+ advanced_settings_pv = gr.Accordion("Advanced Settings for Video Preprocessing", open=False)
312
+ with advanced_settings_pv:
313
+ with gr.Column():
314
+ pv_width = gr.Number(label="Width", value=512, minimum=1, maximum=4096)
315
+ pv_height = gr.Number(label="Height", value=512, minimum=1, maximum=4096)
316
+ pv_start_time = gr.Number(label="Start Time (End time - Start time must be = 2)", value=0, minimum=0)
317
+ pv_end_time = gr.Number(label="End Time (End time - Start time must be = 2)", value=2, minimum=0)
318
+ pv_center_crop = gr.Checkbox(label="Center Crop", value=True)
319
+ pv_x_offset = gr.Number(label="Horizontal Offset (-1 to 1)", value=0, minimum=-1, maximum=1)
320
+ pv_y_offset = gr.Number(label="Vertical Offset (-1 to 1)", value=0, minimum=-1, maximum=1)
321
+ pv_longest_to_width = gr.Checkbox(label="Resize Longest Dimension to Width")
322
+
323
+ with gr.Column():
324
+ gr.Markdown("# Image Editing Stage")
325
+ gr.Markdown("Edit the first frame of the video to your liking! Click on the Edit the first frame button after inputting the editing instruction prompt.")
326
+ image_input_output = gr.Image(label="Edited Frame", type="filepath")
327
+ image_instruct_prompt = gr.Textbox(label="Editing instruction prompt")
328
+ btn_image_edit = gr.Button("Edit the first frame")
329
+ advanced_settings_image_edit = gr.Accordion("Advanced Settings for Image Editing", open=True)
330
+ with advanced_settings_image_edit:
331
+ with gr.Column():
332
+ ie_neg_prompt = gr.Textbox(label="Negative Prompt", value="low res, blurry, watermark, jpeg artifacts")
333
+ ie_seed = gr.Number(label="Seed (-1 means random)", value=-1, minimum=-1, maximum=sys.maxsize)
334
+ ie_force_512 = gr.Checkbox(label="Force resize to 512x512 before feeding into the image editing model")
335
+
336
+ with gr.Column():
337
+ gr.Markdown("# AnyV2V Stage")
338
+ gr.Markdown("Enjoy the full control of the video editing process using the edited image and the preprocessed video! Click on the Run AnyV2V button after inputting the video description prompt. Try tweak with the setting if the output does not satisfy you!")
339
+ video_output = gr.Video(label="Video Output")
340
+ video_prompt = gr.Textbox(label="Video description prompt")
341
+ btn_infer = gr.Button("Run AnyV2V")
342
+ settings_anyv2v = gr.Accordion("Settings for AnyV2V")
343
+ with settings_anyv2v:
344
+ with gr.Column():
345
+ av_pnp_f_t = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.2, label="Convolutional injection (pnp_f_t)")
346
+ av_pnp_spatial_attn_t = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.2, label="Spatial Attention injection (pnp_spatial_attn_t)")
347
+ av_pnp_temp_attn_t = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.5, label="Temporal Attention injection (pnp_temp_attn_t)")
348
+ advanced_settings_anyv2v = gr.Accordion("Advanced Settings for AnyV2V", open=False)
349
+ with advanced_settings_anyv2v:
350
+ with gr.Column():
351
+ av_ddim_init_latents_t_idx = gr.Number(label="DDIM Initial Latents t Index", value=0, minimum=0)
352
+ av_ddim_inversion_steps = gr.Number(label="DDIM Inversion Steps", value=100, minimum=1)
353
+ av_num_inference_steps = gr.Number(label="Number of Inference Steps", value=50, minimum=1)
354
+ av_guidance_scale = gr.Number(label="Guidance Scale", value=9, minimum=0)
355
+ av_seed = gr.Number(label="Seed (-1 means random)", value=42, minimum=-1, maximum=sys.maxsize)
356
+ av_neg_prompt = gr.Textbox(label="Negative Prompt", value="Distorted, discontinuous, Ugly, blurry, low resolution, motionless, static, disfigured, disconnected limbs, Ugly faces, incomplete arms")
357
+
358
+
359
+ examples = gr.Examples(examples=demo_examples,
360
+ label="Examples (Just click on AnyV2V button after loading them into the UI)",
361
+ inputs=[video_input, image_input_output, video_prompt])
362
+
363
+ btn_pv.click(
364
+ btn_preprocess_video_fn,
365
+ inputs=[video_raw, pv_width, pv_height, pv_start_time, pv_end_time, pv_center_crop, pv_x_offset, pv_y_offset, pv_longest_to_width],
366
+ outputs=video_input
367
+ )
368
+
369
+ btn_image_edit.click(
370
+ btn_image_edit_fn,
371
+ inputs=[video_input, image_instruct_prompt, ie_force_512, ie_seed, ie_neg_prompt],
372
+ outputs=image_input_output
373
+ )
374
+
375
+ btn_infer.click(
376
+ btn_infer_fn,
377
+ inputs=[video_input,
378
+ video_prompt,
379
+ av_neg_prompt,
380
+ image_input_output,
381
+ av_pnp_f_t,
382
+ av_pnp_spatial_attn_t,
383
+ av_pnp_temp_attn_t,
384
+ av_num_inference_steps,
385
+ av_guidance_scale,
386
+ av_ddim_init_latents_t_idx,
387
+ av_ddim_inversion_steps,
388
+ av_seed],
389
+ outputs=video_output
390
+ )
391
+ #=====================================
392
+
393
+ # Minimizing usage of GPU Resources
394
+ torch.set_grad_enabled(False)
395
+
396
+
397
+ demo.launch()