Files changed (1) hide show
  1. app.py +111 -27
app.py CHANGED
@@ -1,36 +1,120 @@
1
  import gradio as gr
2
- from diffusers import DiffusionPipeline
3
  import torch
 
 
 
 
 
 
 
4
  from PIL import Image
5
- import spaces
6
-
7
- # Load the pre-trained pipeline
8
- pipeline = DiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt")
9
-
10
- # Define the Gradio interface
11
- interface = gr.Interface(
12
- fn=lambda img: generate_video(img),
13
- inputs=gr.Image(type="pil"),
14
- outputs=gr.Video(),
15
- title="Stable Video Diffusion",
16
- description="Upload an image to generate a video",
17
- theme="soft"
18
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- @spaces.GPU(duration=250)
21
- def generate_video(image):
22
- """
23
- Generates a video from an input image using the pipeline.
24
 
25
- Args:
26
- image: A PIL Image object representing the input image.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- Returns:
29
- A list of PIL Images representing the video frames.
30
- """
31
- video_frames = pipeline(image=image, num_inference_steps=20).images
32
 
33
- return video_frames
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # Launch the Gradio app
36
- interface.launch()
 
 
1
  import gradio as gr
 
2
  import torch
3
+ import os
4
+ from glob import glob
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from diffusers import StableVideoDiffusionPipeline
9
+ from diffusers.utils import load_image, export_to_video
10
  from PIL import Image
11
+
12
+ import uuid
13
+ import random
14
+ from huggingface_hub import hf_hub_download
15
+
16
+ pipe = StableVideoDiffusionPipeline.from_pretrained(
17
+ "multimodalart/stable-video-diffusion", torch_dtype=torch.float16, variant="fp16"
 
 
 
 
 
 
18
  )
19
+ pipe.to("cuda")
20
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
21
+
22
+ max_64_bit_int = 2**63 - 1
23
+
24
+ def sample(
25
+ image: Image,
26
+ seed: Optional[int] = 42,
27
+ randomize_seed: bool = True,
28
+ motion_bucket_id: int = 127,
29
+ fps_id: int = 6,
30
+ version: str = "svd_xt",
31
+ cond_aug: float = 0.02,
32
+ decoding_t: int = 3, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.
33
+ device: str = "cuda",
34
+ output_folder: str = "outputs",
35
+ ):
36
+ if image.mode == "RGBA":
37
+ image = image.convert("RGB")
38
+
39
+ if(randomize_seed):
40
+ seed = random.randint(0, max_64_bit_int)
41
+ generator = torch.manual_seed(seed)
42
+
43
+ os.makedirs(output_folder, exist_ok=True)
44
+ base_count = len(glob(os.path.join(output_folder, "*.mp4")))
45
+ video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")
46
+
47
+ frames = pipe(image, decode_chunk_size=decoding_t, generator=generator, motion_bucket_id=motion_bucket_id, noise_aug_strength=0.1, num_frames=25).frames[0]
48
+ export_to_video(frames, video_path, fps=fps_id)
49
+ torch.manual_seed(seed)
50
+
51
+ return video_path, seed
52
 
53
+ def resize_image(image, output_size=(1024, 576)):
54
+ # Calculate aspect ratios
55
+ target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size
56
+ image_aspect = image.width / image.height # Aspect ratio of the original image
57
 
58
+ # Resize then crop if the original image is larger
59
+ if image_aspect > target_aspect:
60
+ # Resize the image to match the target height, maintaining aspect ratio
61
+ new_height = output_size[1]
62
+ new_width = int(new_height * image_aspect)
63
+ resized_image = image.resize((new_width, new_height), Image.LANCZOS)
64
+ # Calculate coordinates for cropping
65
+ left = (new_width - output_size[0]) / 2
66
+ top = 0
67
+ right = (new_width + output_size[0]) / 2
68
+ bottom = output_size[1]
69
+ else:
70
+ # Resize the image to match the target width, maintaining aspect ratio
71
+ new_width = output_size[0]
72
+ new_height = int(new_width / image_aspect)
73
+ resized_image = image.resize((new_width, new_height), Image.LANCZOS)
74
+ # Calculate coordinates for cropping
75
+ left = 0
76
+ top = (new_height - output_size[1]) / 2
77
+ right = output_size[0]
78
+ bottom = (new_height + output_size[1]) / 2
79
 
80
+ # Crop the image
81
+ cropped_image = resized_image.crop((left, top, right, bottom))
82
+ return cropped_image
 
83
 
84
+ with gr.Blocks() as demo:
85
+ gr.Markdown('''# Stable Video Diffusion
86
+ ''')
87
+ with gr.Row():
88
+ with gr.Column():
89
+ image = gr.Image(label="Upload your image", type="pil")
90
+ generate_btn = gr.Button("Generate")
91
+ video = gr.Video()
92
+ with gr.Accordion("Advanced options", open=False):
93
+ seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1)
94
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
95
+ motion_bucket_id = gr.Slider(label="Motion bucket id", info="Controls how much motion to add/remove from the image", value=127, minimum=1, maximum=255)
96
+ fps_id = gr.Slider(label="Frames per second", info="The length of your video in seconds will be 25/fps", value=6, minimum=5, maximum=30)
97
+
98
+ image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)
99
+ generate_btn.click(fn=sample, inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id], outputs=[video, seed], api_name="video")
100
+ gr.Examples(
101
+ examples=[
102
+ "images/blink_meme.png",
103
+ "images/confused2_meme.png",
104
+ "images/disaster_meme.png",
105
+ "images/distracted_meme.png",
106
+ "images/hide_meme.png",
107
+ "images/nazare_meme.png",
108
+ "images/success_meme.png",
109
+ "images/willy_meme.png",
110
+ "images/wink_meme.png"
111
+ ],
112
+ inputs=image,
113
+ outputs=[video, seed],
114
+ fn=sample,
115
+ cache_examples=True,
116
+ )
117
 
118
+ if __name__ == "__main__":
119
+ demo.queue(max_size=20, api_open=False)
120
+ demo.launch(share=True, show_api=False)