salomonsky commited on
Commit
f31cbbe
·
verified ·
1 Parent(s): 9d2d672

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -59
app.py CHANGED
@@ -1,107 +1,70 @@
1
  import gradio as gr
2
- #import gradio.helpers
3
  import torch
4
  import os
5
  from glob import glob
6
  from pathlib import Path
7
  from typing import Optional
8
-
9
  from diffusers import StableVideoDiffusionPipeline
10
  from diffusers.utils import load_image, export_to_video
11
  from PIL import Image
12
-
13
  import uuid
14
  import random
15
  from huggingface_hub import hf_hub_download
16
- import spaces
17
-
18
- pipe = StableVideoDiffusionPipeline.from_pretrained(
19
- "vdo/stable-video-diffusion-img2vid-xt-1-1", torch_dtype=torch.float16, variant="fp16"
20
- )
21
- pipe.to("cuda")
22
 
23
  max_64_bit_int = 2**63 - 1
24
-
 
25
  @spaces.GPU(duration=120)
26
- def sample(
27
- image: Image,
28
- seed: Optional[int] = 42,
29
- randomize_seed: bool = True,
30
- motion_bucket_id: int = 127,
31
- fps_id: int = 6,
32
- version: str = "svd_xt",
33
- cond_aug: float = 0.02,
34
- decoding_t: int = 3, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.
35
- device: str = "cuda",
36
- output_folder: str = "outputs",
37
- ):
38
- if image.mode == "RGBA":
39
- image = image.convert("RGB")
40
-
41
- if(randomize_seed):
42
- seed = random.randint(0, max_64_bit_int)
43
  generator = torch.manual_seed(seed)
44
-
45
  os.makedirs(output_folder, exist_ok=True)
46
  base_count = len(glob(os.path.join(output_folder, "*.mp4")))
47
  video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")
48
-
49
  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]
50
  export_to_video(frames, video_path, fps=fps_id)
51
  torch.manual_seed(seed)
52
-
53
  return video_path, frames, seed
54
 
55
  def resize_image(image, output_size=(1024, 576)):
56
- # Calculate aspect ratios
57
- target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size
58
- image_aspect = image.width / image.height # Aspect ratio of the original image
59
-
60
- # Resize then crop if the original image is larger
61
  if image_aspect > target_aspect:
62
- # Resize the image to match the target height, maintaining aspect ratio
63
  new_height = output_size[1]
64
  new_width = int(new_height * image_aspect)
65
  resized_image = image.resize((new_width, new_height), Image.LANCZOS)
66
- # Calculate coordinates for cropping
67
  left = (new_width - output_size[0]) / 2
68
  top = 0
69
  right = (new_width + output_size[0]) / 2
70
  bottom = output_size[1]
71
  else:
72
- # Resize the image to match the target width, maintaining aspect ratio
73
  new_width = output_size[0]
74
  new_height = int(new_width / image_aspect)
75
  resized_image = image.resize((new_width, new_height), Image.LANCZOS)
76
- # Calculate coordinates for cropping
77
  left = 0
78
  top = (new_height - output_size[1]) / 2
79
  right = output_size[0]
80
  bottom = (new_height + output_size[1]) / 2
81
-
82
- # Crop the image
83
  cropped_image = resized_image.crop((left, top, right, bottom))
84
  return cropped_image
85
 
86
  with gr.Blocks() as demo:
87
- 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))
88
- #### 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).
89
- ''')
90
- with gr.Row():
91
- with gr.Column():
92
- image = gr.Image(label="Upload your image", type="pil")
93
- with gr.Accordion("Advanced options", open=False):
94
- seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1)
95
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
96
- 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)
97
- 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)
98
- generate_btn = gr.Button(value="Animate", variant="primary")
99
- with gr.Column():
100
- video = gr.Video(label="Generated video")
101
- gallery = gr.Gallery(label="Generated frames")
102
-
103
- image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)
104
- generate_btn.click(fn=sample, inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id], outputs=[video, gallery, seed], api_name="video")
105
 
106
  if __name__ == "__main__":
107
  demo.launch(share=True, show_api=False)
 
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
  from diffusers import StableVideoDiffusionPipeline
8
  from diffusers.utils import load_image, export_to_video
9
  from PIL import Image
 
10
  import uuid
11
  import random
12
  from huggingface_hub import hf_hub_download
 
 
 
 
 
 
13
 
14
  max_64_bit_int = 2**63 - 1
15
+ pipe = StableVideoDiffusionPipeline.from_pretrained("vdo/stable-video-diffusion-img2vid-xt-1-1", torch_dtype=torch.float16, variant="fp16")
16
+ pipe.to("cuda")
17
  @spaces.GPU(duration=120)
18
+
19
+ def sample(image, seed=42, randomize_seed=True, motion_bucket_id=127, fps_id=6, version="svd_xt", cond_aug=0.02, decoding_t=3, device="cuda", output_folder="outputs"):
20
+ if image.mode == "RGBA": image = image.convert("RGB")
21
+ if randomize_seed: seed = random.randint(0, max_64_bit_int)
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  generator = torch.manual_seed(seed)
 
23
  os.makedirs(output_folder, exist_ok=True)
24
  base_count = len(glob(os.path.join(output_folder, "*.mp4")))
25
  video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")
 
26
  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]
27
  export_to_video(frames, video_path, fps=fps_id)
28
  torch.manual_seed(seed)
 
29
  return video_path, frames, seed
30
 
31
  def resize_image(image, output_size=(1024, 576)):
32
+ target_aspect = output_size[0] / output_size[1]
33
+ image_aspect = image.width / image.height
 
 
 
34
  if image_aspect > target_aspect:
 
35
  new_height = output_size[1]
36
  new_width = int(new_height * image_aspect)
37
  resized_image = image.resize((new_width, new_height), Image.LANCZOS)
 
38
  left = (new_width - output_size[0]) / 2
39
  top = 0
40
  right = (new_width + output_size[0]) / 2
41
  bottom = output_size[1]
42
  else:
 
43
  new_width = output_size[0]
44
  new_height = int(new_width / image_aspect)
45
  resized_image = image.resize((new_width, new_height), Image.LANCZOS)
 
46
  left = 0
47
  top = (new_height - output_size[1]) / 2
48
  right = output_size[0]
49
  bottom = (new_height + output_size[1]) / 2
 
 
50
  cropped_image = resized_image.crop((left, top, right, bottom))
51
  return cropped_image
52
 
53
  with gr.Blocks() as demo:
54
+ with gr.Row():
55
+ with gr.Column():
56
+ image = gr.Image(label="Upload your image", type="pil")
57
+ with gr.Accordion("Advanced options", open=False):
58
+ seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1)
59
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
60
+ motion_bucket_id = gr.Slider(label="Motion bucket id", value=127, minimum=1, maximum=255)
61
+ fps_id = gr.Slider(label="Frames per second", value=6, minimum=5, maximum=30)
62
+ generate_btn = gr.Button(value="Animate", variant="primary")
63
+ with gr.Column():
64
+ video = gr.Video(label="Generated video")
65
+ gallery = gr.Gallery(label="Generated frames")
66
+ image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)
67
+ generate_btn.click(fn=sample, inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id], outputs=[video, gallery, seed], api_name="video")
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
  demo.launch(share=True, show_api=False)