cakemus commited on
Commit
452ceab
·
1 Parent(s): 69dae79
Files changed (1) hide show
  1. app.py +36 -105
app.py CHANGED
@@ -1,116 +1,47 @@
1
- import gradio as gr
2
- import spaces
3
- #import gradio.helpers
4
  import torch
5
- import os
6
- from glob import glob
7
- from pathlib import Path
8
- from typing import Optional
9
-
10
  from diffusers import StableVideoDiffusionPipeline
11
  from diffusers.utils import load_image, export_to_video
12
- from PIL import Image
13
-
14
- import uuid
15
- import random
16
- from huggingface_hub import hf_hub_download
17
 
18
  # Check if GPU is available
19
  device = "cuda" if torch.cuda.is_available() else "cpu"
20
 
21
- # Load the pipeline with authentication token
22
- pipe = StableVideoDiffusionPipeline.from_pretrained(
23
- "stabilityai/stable-video-diffusion-img2vid-xt",
24
- torch_dtype=torch.float16,
25
- variant="fp16"
26
  )
27
- pipe.to("cuda")
28
- #pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
29
- #pipe.vae = torch.compile(pipe.vae, mode="reduce-overhead", fullgraph=True)
30
-
31
- max_64_bit_int = 2**63 - 1
32
 
33
  @spaces.GPU(duration=120)
34
- def sample(
35
- image: Image,
36
- seed: Optional[int] = 42,
37
- randomize_seed: bool = True,
38
- motion_bucket_id: int = 127,
39
- fps_id: int = 6,
40
- version: str = "svd_xt",
41
- cond_aug: float = 0.02,
42
- decoding_t: int = 3, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.
43
- device: str = "cuda",
44
- output_folder: str = "outputs",
45
- progress=gr.Progress(track_tqdm=True)
46
- ):
47
- if image.mode == "RGBA":
48
- image = image.convert("RGB")
49
-
50
- if randomize_seed:
51
- seed = random.randint(0, max_64_bit_int)
52
- generator = torch.manual_seed(seed)
53
-
54
- os.makedirs(output_folder, exist_ok=True)
55
- base_count = len(glob(os.path.join(output_folder, "*.mp4")))
56
- video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")
57
-
58
- 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]
59
- export_to_video(frames, video_path, fps=fps_id)
60
- torch.manual_seed(seed)
61
-
62
- return video_path, seed
63
-
64
- def resize_image(image, output_size=(1024, 576)):
65
- # Calculate aspect ratios
66
- target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size
67
- image_aspect = image.width / image.height # Aspect ratio of the original image
68
-
69
- # Resize then crop if the original image is larger
70
- if image_aspect > target_aspect:
71
- # Resize the image to match the target height, maintaining aspect ratio
72
- new_height = output_size[1]
73
- new_width = int(new_height * image_aspect)
74
- resized_image = image.resize((new_width, new_height), Image.LANCZOS)
75
- # Calculate coordinates for cropping
76
- left = (new_width - output_size[0]) / 2
77
- top = 0
78
- right = (new_width + output_size[0]) / 2
79
- bottom = output_size[1]
80
- else:
81
- # Resize the image to match the target width, maintaining aspect ratio
82
- new_width = output_size[0]
83
- new_height = int(new_width / image_aspect)
84
- resized_image = image.resize((new_width, new_height), Image.LANCZOS)
85
- # Calculate coordinates for cropping
86
- left = 0
87
- top = (new_height - output_size[1]) / 2
88
- right = output_size[0]
89
- bottom = (new_height + output_size[1]) / 2
90
-
91
- # Crop the image
92
- cropped_image = resized_image.crop((left, top, right, bottom))
93
- return cropped_image
94
-
95
- with gr.Blocks() as demo:
96
- gr.Markdown('''# Community demo for Stable Video Diffusion - Img2Vid - XT ([model](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt), [paper](https://stability.ai/research/stable-video-diffusion-scaling-latent-video-diffusion-models-to-large-datasets), [stability's ui waitlist](https://stability.ai/contact))
97
- #### Research release ([_non-commercial_](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt/blob/main/LICENSE)): generate `4s` vid from a single image at (`25 frames` at `6 fps`). this demo uses [🧨 diffusers for low VRAM and fast generation](https://huggingface.co/docs/diffusers/main/en/using-diffusers/svd).
98
- ''')
99
- with gr.Row():
100
- with gr.Column():
101
- image = gr.Image(label="Upload your image", type="pil")
102
- generate_btn = gr.Button("Generate")
103
- video = gr.Video()
104
- with gr.Accordion("Advanced options", open=False):
105
- seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1)
106
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
107
- 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)
108
- 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)
109
-
110
- image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)
111
- generate_btn.click(fn=sample, inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id], outputs=[video, seed], api_name="video")
112
-
113
 
114
- if __name__ == "__main__":
115
- #demo.queue(max_size=20, api_open=False)
116
- demo.launch(share=True, show_api=False)
 
 
 
 
1
  import torch
2
+ import gradio as gr
 
 
 
 
3
  from diffusers import StableVideoDiffusionPipeline
4
  from diffusers.utils import load_image, export_to_video
5
+ import spaces
 
 
 
 
6
 
7
  # Check if GPU is available
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
 
10
+ # Load the pipeline
11
+ pipeline = StableVideoDiffusionPipeline.from_pretrained(
12
+ "stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16"
 
 
13
  )
14
+ pipeline.to(device)
 
 
 
 
15
 
16
  @spaces.GPU(duration=120)
17
+ def generate_video(image_path, seed):
18
+ # Load and preprocess the image
19
+ image = load_image(image_path)
20
+ image = image.resize((1024, 576))
21
+
22
+ # Set the generator seed
23
+ generator = torch.Generator(device=device).manual_seed(seed)
24
+
25
+ # Generate the video frames
26
+ frames = pipeline(image, decode_chunk_size=8, generator=generator).frames[0]
27
+
28
+ # Export the frames to a video file
29
+ output_video_path = "generated.mp4"
30
+ export_to_video(frames, output_video_path, fps=7)
31
+
32
+ return output_video_path
33
+
34
+ # Create the Gradio interface
35
+ iface = gr.Interface(
36
+ fn=generate_video,
37
+ inputs=[
38
+ gr.Image(type="filepath", label="Upload Image"),
39
+ gr.Number(label="Seed", value=42)
40
+ ],
41
+ outputs=gr.Video(label="Generated Video"),
42
+ title="Stable Video Diffusion",
43
+ description="Generate a video from an uploaded image using Stable Video Diffusion.",
44
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # Launch the interface
47
+ iface.launch()