Manjushri commited on
Commit
b14bfaf
·
verified ·
1 Parent(s): 7eee9de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -13
app.py CHANGED
@@ -3,27 +3,118 @@ import torch
3
  import numpy as np
4
  import modin.pandas as pd
5
  from PIL import Image
6
- from diffusers import DiffusionPipeline
7
  from huggingface_hub import login
8
  import os
9
-
 
 
 
 
10
 
11
  token = os.environ['HF_TOKEN']
12
  login(token=token)
13
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
14
- torch.cuda.max_memory_allocated(device=device)
15
- torch.cuda.empty_cache()
16
- pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid")
17
- #pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
18
- pipe.enable_xformers_memory_efficient_attention()
19
  pipe = pipe.to(device)
20
- torch.cuda.empty_cache()
21
 
 
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- def genie(src_image):
25
- frames = pipe(image=src_image).images[0]
26
- torch.cuda.empty_cache()
27
- return frames
28
 
29
- gr.Interface(fn=genie, inputs=gr.Image(type="pil"), outputs=gr.Video()).launch(debug=True, max_threads=80)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import numpy as np
4
  import modin.pandas as pd
5
  from PIL import Image
6
+ from diffusers import StableVideoDiffusionPipeline
7
  from huggingface_hub import login
8
  import os
9
+ from glob import glob
10
+ from pathlib import Path
11
+ from typing import Optional
12
+ import uuid
13
+ import random
14
 
15
  token = os.environ['HF_TOKEN']
16
  login(token=token)
17
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
18
+ pipe = StableVideoDiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt-1-1", variant="fp16")
 
 
 
 
19
  pipe = pipe.to(device)
 
20
 
21
+ max_64_bit_int = 2**63 - 1
22
 
23
+ def sample(
24
+ image: Image,
25
+ seed: Optional[int] = 42,
26
+ randomize_seed: bool = True,
27
+ motion_bucket_id: int = 127,
28
+ fps_id: int = 6,
29
+ version: str = "svd_xt",
30
+ cond_aug: float = 0.02,
31
+ decoding_t: int = 3, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.
32
+ device: str = "cpu",
33
+ output_folder: str = "outputs",
34
+ ):
35
+ if image.mode == "RGBA":
36
+ image = image.convert("RGB")
37
+
38
+ if(randomize_seed):
39
+ seed = random.randint(0, max_64_bit_int)
40
+ generator = torch.manual_seed(seed)
41
+
42
+ os.makedirs(output_folder, exist_ok=True)
43
+ base_count = len(glob(os.path.join(output_folder, "*.mp4")))
44
+ video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")
45
 
46
+ 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]
47
+ export_to_video(frames, video_path, fps=fps_id)
48
+ torch.manual_seed(seed)
 
49
 
50
+ return video_path, seed
51
+
52
+ def resize_image(image, output_size=(512, 256)):
53
+ # Calculate aspect ratios
54
+ target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size
55
+ image_aspect = image.width / image.height # Aspect ratio of the original image
56
+
57
+ # Resize then crop if the original image is larger
58
+ if image_aspect > target_aspect:
59
+ # Resize the image to match the target height, maintaining aspect ratio
60
+ new_height = output_size[1]
61
+ new_width = int(new_height * image_aspect)
62
+ resized_image = image.resize((new_width, new_height), Image.LANCZOS)
63
+ # Calculate coordinates for cropping
64
+ left = (new_width - output_size[0]) / 2
65
+ top = 0
66
+ right = (new_width + output_size[0]) / 2
67
+ bottom = output_size[1]
68
+ else:
69
+ # Resize the image to match the target width, maintaining aspect ratio
70
+ new_width = output_size[0]
71
+ new_height = int(new_width / image_aspect)
72
+ resized_image = image.resize((new_width, new_height), Image.LANCZOS)
73
+ # Calculate coordinates for cropping
74
+ left = 0
75
+ top = (new_height - output_size[1]) / 2
76
+ right = output_size[0]
77
+ bottom = (new_height + output_size[1]) / 2
78
+
79
+ # Crop the image
80
+ cropped_image = resized_image.crop((left, top, right, bottom))
81
+ return cropped_image
82
+
83
+ with gr.Blocks() as demo:
84
+ 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))
85
+ #### 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).
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(show_api=False)