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