|
| 1 | +# Adding this at the very top of app.py to make 'generative-models' directory discoverable |
| 2 | +import sys |
| 3 | +import os |
| 4 | +sys.path.append(os.path.join(os.path.dirname(__file__), 'generative-models')) |
| 5 | + |
| 6 | +import math |
| 7 | +from glob import glob |
| 8 | +from pathlib import Path |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +import cv2 |
| 12 | +import numpy as np |
| 13 | +import torch |
| 14 | +from einops import rearrange, repeat |
| 15 | +from fire import Fire |
| 16 | +from omegaconf import OmegaConf |
| 17 | +from PIL import Image |
| 18 | +from torchvision.transforms import ToTensor |
| 19 | + |
| 20 | +from scripts.util.detection.nsfw_and_watermark_dectection import \ |
| 21 | + DeepFloydDataFiltering |
| 22 | +from sgm.inference.helpers import embed_watermark |
| 23 | +from sgm.util import default, instantiate_from_config |
| 24 | +from scripts.sampling.simple_video_sample import load_model, get_unique_embedder_keys_from_conditioner, get_batch |
| 25 | + |
| 26 | +import gradio as gr |
| 27 | +import uuid |
| 28 | +import random |
| 29 | +from huggingface_hub import hf_hub_download |
| 30 | + |
| 31 | +# To download all svd models |
| 32 | +#hf_hub_download(repo_id="stabilityai/stable-video-diffusion-img2vid-xt", filename="svd_xt.safetensors", local_dir="checkpoints") |
| 33 | +#hf_hub_download(repo_id="stabilityai/stable-video-diffusion-img2vid", filename="svd.safetensors", local_dir="checkpoints") |
| 34 | +#hf_hub_download(repo_id="stabilityai/stable-video-diffusion-img2vid-xt-1-1", filename="svd_xt_1_1.safetensors", local_dir="checkpoints") |
| 35 | + |
| 36 | + |
| 37 | +# Define the repo, local directory and filename |
| 38 | +repo_id="stabilityai/stable-video-diffusion-img2vid-xt-1-1" # replace with "stabilityai/stable-video-diffusion-img2vid-xt" or "stabilityai/stable-video-diffusion-img2vid" for other models |
| 39 | +filename = "svd_xt_1_1.safetensors" # replace with "svd_xt.safetensors" or "svd.safetensors" for other models |
| 40 | +local_dir = "checkpoints" |
| 41 | +local_file_path = os.path.join(local_dir, filename) |
| 42 | + |
| 43 | +# Check if the file already exists |
| 44 | +if not os.path.exists(local_file_path): |
| 45 | + # If the file doesn't exist, download it |
| 46 | + hf_hub_download( |
| 47 | + repo_id=repo_id, |
| 48 | + filename=filename, |
| 49 | + local_dir=local_dir |
| 50 | + ) |
| 51 | + print("File downloaded.") |
| 52 | +else: |
| 53 | + print("File already exists. No need to download.") |
| 54 | + |
| 55 | + |
| 56 | +version = "svd_xt_1_1" # replace with 'svd_xt' or 'svd' for other models |
| 57 | +device = "cuda" |
| 58 | +max_64_bit_int = 2**63 - 1 |
| 59 | + |
| 60 | +if version == "svd_xt_1_1": |
| 61 | + num_frames = 25 |
| 62 | + num_steps = 30 |
| 63 | + model_config = "scripts/sampling/configs/svd_xt_1_1.yaml" |
| 64 | +else: |
| 65 | + raise ValueError(f"Version {version} does not exist.") |
| 66 | + |
| 67 | +model, filter = load_model( |
| 68 | + model_config, |
| 69 | + device, |
| 70 | + num_frames, |
| 71 | + num_steps, |
| 72 | +) |
| 73 | + |
| 74 | +def sample( |
| 75 | + input_path: str = "assets/test_image.png", # Can either be image file or folder with image files |
| 76 | + seed: Optional[int] = None, |
| 77 | + randomize_seed: bool = True, |
| 78 | + motion_bucket_id: int = 127, |
| 79 | + fps_id: int = 6, |
| 80 | + version: str = "svd_xt_1_1", |
| 81 | + cond_aug: float = 0.02, |
| 82 | + decoding_t: int = 7, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary. |
| 83 | + device: str = "cuda", |
| 84 | + output_folder: str = "outputs", |
| 85 | + progress=gr.Progress(track_tqdm=True) |
| 86 | +): |
| 87 | + """ |
| 88 | + Simple script to generate a single sample conditioned on an image `input_path` or multiple images, one for each |
| 89 | + image file in folder `input_path`. If you run out of VRAM, try decreasing `decoding_t`. |
| 90 | + """ |
| 91 | + fps_id = int(fps_id ) #casting float slider values to int) |
| 92 | + if(randomize_seed): |
| 93 | + seed = random.randint(0, max_64_bit_int) |
| 94 | + |
| 95 | + torch.manual_seed(seed) |
| 96 | + |
| 97 | + path = Path(input_path) |
| 98 | + all_img_paths = [] |
| 99 | + if path.is_file(): |
| 100 | + if any([input_path.endswith(x) for x in ["jpg", "jpeg", "png"]]): |
| 101 | + all_img_paths = [input_path] |
| 102 | + else: |
| 103 | + raise ValueError("Path is not valid image file.") |
| 104 | + elif path.is_dir(): |
| 105 | + all_img_paths = sorted( |
| 106 | + [ |
| 107 | + f |
| 108 | + for f in path.iterdir() |
| 109 | + if f.is_file() and f.suffix.lower() in [".jpg", ".jpeg", ".png"] |
| 110 | + ] |
| 111 | + ) |
| 112 | + if len(all_img_paths) == 0: |
| 113 | + raise ValueError("Folder does not contain any images.") |
| 114 | + else: |
| 115 | + raise ValueError |
| 116 | + |
| 117 | + for input_img_path in all_img_paths: |
| 118 | + with Image.open(input_img_path) as image: |
| 119 | + if image.mode == "RGBA": |
| 120 | + image = image.convert("RGB") |
| 121 | + w, h = image.size |
| 122 | + |
| 123 | + if h % 64 != 0 or w % 64 != 0: |
| 124 | + width, height = map(lambda x: x - x % 64, (w, h)) |
| 125 | + image = image.resize((width, height)) |
| 126 | + print( |
| 127 | + f"WARNING: Your image is of size {h}x{w} which is not divisible by 64. We are resizing to {height}x{width}!" |
| 128 | + ) |
| 129 | + |
| 130 | + image = ToTensor()(image) |
| 131 | + image = image * 2.0 - 1.0 |
| 132 | + |
| 133 | + image = image.unsqueeze(0).to(device) |
| 134 | + H, W = image.shape[2:] |
| 135 | + assert image.shape[1] == 3 |
| 136 | + F = 8 |
| 137 | + C = 4 |
| 138 | + shape = (num_frames, C, H // F, W // F) |
| 139 | + if (H, W) != (576, 1024): |
| 140 | + print( |
| 141 | + "WARNING: The conditioning frame you provided is not 576x1024. This leads to suboptimal performance as model was only trained on 576x1024. Consider increasing `cond_aug`." |
| 142 | + ) |
| 143 | + if motion_bucket_id > 255: |
| 144 | + print( |
| 145 | + "WARNING: High motion bucket! This may lead to suboptimal performance." |
| 146 | + ) |
| 147 | + |
| 148 | + if fps_id < 5: |
| 149 | + print("WARNING: Small fps value! This may lead to suboptimal performance.") |
| 150 | + |
| 151 | + if fps_id > 30: |
| 152 | + print("WARNING: Large fps value! This may lead to suboptimal performance.") |
| 153 | + |
| 154 | + value_dict = {} |
| 155 | + value_dict["motion_bucket_id"] = motion_bucket_id |
| 156 | + value_dict["fps_id"] = fps_id |
| 157 | + value_dict["cond_aug"] = cond_aug |
| 158 | + value_dict["cond_frames_without_noise"] = image |
| 159 | + value_dict["cond_frames"] = image + cond_aug * torch.randn_like(image) |
| 160 | + value_dict["cond_aug"] = cond_aug |
| 161 | + |
| 162 | + with torch.no_grad(): |
| 163 | + with torch.autocast(device): |
| 164 | + batch, batch_uc = get_batch( |
| 165 | + get_unique_embedder_keys_from_conditioner(model.conditioner), |
| 166 | + value_dict, |
| 167 | + [1, num_frames], |
| 168 | + T=num_frames, |
| 169 | + device=device, |
| 170 | + ) |
| 171 | + c, uc = model.conditioner.get_unconditional_conditioning( |
| 172 | + batch, |
| 173 | + batch_uc=batch_uc, |
| 174 | + force_uc_zero_embeddings=[ |
| 175 | + "cond_frames", |
| 176 | + "cond_frames_without_noise", |
| 177 | + ], |
| 178 | + ) |
| 179 | + |
| 180 | + for k in ["crossattn", "concat"]: |
| 181 | + uc[k] = repeat(uc[k], "b ... -> b t ...", t=num_frames) |
| 182 | + uc[k] = rearrange(uc[k], "b t ... -> (b t) ...", t=num_frames) |
| 183 | + c[k] = repeat(c[k], "b ... -> b t ...", t=num_frames) |
| 184 | + c[k] = rearrange(c[k], "b t ... -> (b t) ...", t=num_frames) |
| 185 | + |
| 186 | + randn = torch.randn(shape, device=device) |
| 187 | + |
| 188 | + additional_model_inputs = {} |
| 189 | + additional_model_inputs["image_only_indicator"] = torch.zeros( |
| 190 | + 2, num_frames |
| 191 | + ).to(device) |
| 192 | + additional_model_inputs["num_video_frames"] = batch["num_video_frames"] |
| 193 | + |
| 194 | + def denoiser(input, sigma, c): |
| 195 | + return model.denoiser( |
| 196 | + model.model, input, sigma, c, **additional_model_inputs |
| 197 | + ) |
| 198 | + |
| 199 | + samples_z = model.sampler(denoiser, randn, cond=c, uc=uc) |
| 200 | + model.en_and_decode_n_samples_a_time = decoding_t |
| 201 | + samples_x = model.decode_first_stage(samples_z) |
| 202 | + samples = torch.clamp((samples_x + 1.0) / 2.0, min=0.0, max=1.0) |
| 203 | + |
| 204 | + os.makedirs(output_folder, exist_ok=True) |
| 205 | + base_count = len(glob(os.path.join(output_folder, "*.mp4"))) |
| 206 | + video_path = os.path.join(output_folder, f"{base_count:06d}.mp4") |
| 207 | + writer = cv2.VideoWriter( |
| 208 | + video_path, |
| 209 | + cv2.VideoWriter_fourcc(*"mp4v"), |
| 210 | + fps_id + 1, |
| 211 | + (samples.shape[-1], samples.shape[-2]), |
| 212 | + ) |
| 213 | + |
| 214 | + samples = embed_watermark(samples) |
| 215 | + samples = filter(samples) |
| 216 | + vid = ( |
| 217 | + (rearrange(samples, "t c h w -> t h w c") * 255) |
| 218 | + .cpu() |
| 219 | + .numpy() |
| 220 | + .astype(np.uint8) |
| 221 | + ) |
| 222 | + for frame in vid: |
| 223 | + frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) |
| 224 | + writer.write(frame) |
| 225 | + writer.release() |
| 226 | + |
| 227 | + return video_path, seed |
| 228 | + |
| 229 | + |
| 230 | +def resize_image(image_path, output_size=(1024, 576)): |
| 231 | + image = Image.open(image_path) |
| 232 | + # Calculate aspect ratios |
| 233 | + target_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired size |
| 234 | + image_aspect = image.width / image.height # Aspect ratio of the original image |
| 235 | + |
| 236 | + # Resize then crop if the original image is larger |
| 237 | + if image_aspect > target_aspect: |
| 238 | + # Resize the image to match the target height, maintaining aspect ratio |
| 239 | + new_height = output_size[1] |
| 240 | + new_width = int(new_height * image_aspect) |
| 241 | + resized_image = image.resize((new_width, new_height), Image.LANCZOS) |
| 242 | + # Calculate coordinates for cropping |
| 243 | + left = (new_width - output_size[0]) / 2 |
| 244 | + top = 0 |
| 245 | + right = (new_width + output_size[0]) / 2 |
| 246 | + bottom = output_size[1] |
| 247 | + else: |
| 248 | + # Resize the image to match the target width, maintaining aspect ratio |
| 249 | + new_width = output_size[0] |
| 250 | + new_height = int(new_width / image_aspect) |
| 251 | + resized_image = image.resize((new_width, new_height), Image.LANCZOS) |
| 252 | + # Calculate coordinates for cropping |
| 253 | + left = 0 |
| 254 | + top = (new_height - output_size[1]) / 2 |
| 255 | + right = output_size[0] |
| 256 | + bottom = (new_height + output_size[1]) / 2 |
| 257 | + |
| 258 | + # Crop the image |
| 259 | + cropped_image = resized_image.crop((left, top, right, bottom)) |
| 260 | + |
| 261 | + return cropped_image |
| 262 | + |
| 263 | +with gr.Blocks() as demo: |
| 264 | + 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)) |
| 265 | +#### 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`). Generation takes ~60s in an A100. [Join the waitlist for Stability's upcoming web experience](https://stability.ai/contact). |
| 266 | + ''') |
| 267 | + with gr.Row(): |
| 268 | + with gr.Column(): |
| 269 | + image = gr.Image(label="Upload your image", type="filepath") |
| 270 | + generate_btn = gr.Button("Generate") |
| 271 | + video = gr.Video() |
| 272 | + with gr.Accordion("Advanced options", open=False): |
| 273 | + seed = gr.Slider(label="Seed", value=42, randomize=True, minimum=0, maximum=max_64_bit_int, step=1) |
| 274 | + randomize_seed = gr.Checkbox(label="Randomize seed", value=True) |
| 275 | + 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) |
| 276 | + 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) |
| 277 | + |
| 278 | + image.upload(fn=resize_image, inputs=image, outputs=image, queue=False) |
| 279 | + generate_btn.click(fn=sample, inputs=[image, seed, randomize_seed, motion_bucket_id, fps_id], outputs=[video, seed], api_name="video") |
| 280 | + |
| 281 | +if __name__ == "__main__": |
| 282 | + demo.queue(max_size=20) |
| 283 | + demo.launch(share=True) |
0 commit comments