Spaces:
Runtime error
Runtime error
Commit ·
d56d267
1
Parent(s): 5e1ee6f
Update app.py
Browse files7 unmodified lines89101112132 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515239 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481497 unmodified linesimport numpy as npimport torchfrom einops import rearrange, repeatfrom omegaconf import OmegaConffrom PIL import Imagefrom torchvision.transforms import ToTensor2 unmodified linesDeepFloydDataFilteringfrom sgm.inference.helpers import embed_watermarkfrom sgm.util import default, instantiate_from_configfrom huggingface_hub import hf_hub_downloadimport gradio as grimport uuidfrom simple_video_sample import samplenum_frames = 25num_steps = 30model_config = "scripts/sampling/configs/svd_xt.yaml"device = "cuda"hf_hub_download(repo_id="stabilityai/stable-video-diffusion-img2vid-xt", filename="svd_xt.safetensors", local_dir="checkpoints", token=os.getenv("HF_TOKEN"))def run_sampling(input_path: str,num_frames: Optional[int] = 25,num_steps: Optional[int] = 30,version: str = "svd_xt",fps_id: int = 6,motion_bucket_id: int = 127,cond_aug: float = 0.02,seed: int = 23,decoding_t: int = 7, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.):output_folder = str(uuid.uuid4())print(output_folder)print(version)print(input_path)sample(input_path, version=version, output_folder=output_folder, decoding_t=decoding_t)return f"{output_folder}/000000.mp4"def get_unique_embedder_keys_from_conditioner(conditioner):return list(set([x.input_key for x in conditioner.embedders]))39 unmodified linesbatch_uc[key] = torch.clone(batch[key])return batch, batch_ucdef resize_image(image_path, output_size=(1024, 576)):with Image.open(image_path) as image:# Calculate aspect ratiostarget_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired sizeimage_aspect = image.width / image.height # Aspect ratio of the original image# Resize then crop if the original image is largerif image_aspect > target_aspect:# Resize the image to match the target height, maintaining aspect rationew_height = output_size[1]new_width = int(new_height * image_aspect)resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)# Calculate coordinates for croppingleft = (new_width - output_size[0]) / 2top = 0right = (new_width + output_size[0]) / 2bottom = output_size[1]else:# Resize the image to match the target width, maintaining aspect rationew_width = output_size[0]new_height = int(new_width / image_aspect)resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)# Calculate coordinates for croppingleft = 0top = (new_height - output_size[1]) / 2right = output_size[0]bottom = (new_height + output_size[1]) / 2# Crop the imagecropped_image = resized_image.crop((left, top, right, bottom))return cropped_imagecss = '''.gradio-container{max-width:850px !important}'''with gr.Blocks(css=css) as demo:gr.Markdown('''# Stable Video Diffusion - Image2Video - XTGenerate 25 frames of video from a single image with SDV-XT. [Join the waitlist](https://stability.ai/contact) for the text-to-video web experience''')with gr.Column():image = gr.Image(label="Upload your image (it will be center cropped to 1024x576)", type="filepath")generate_btn = gr.Button("Generate")#with gr.Accordion("Advanced options", open=False):# cond_aug = gr.Slider(label="Conditioning augmentation", value=0.02, minimum=0.0)# seed = gr.Slider(label="Seed", value=42, minimum=0, maximum=int(1e9), step=1)#decoding_t = gr.Slider(label="Decode frames at a time", value=6, minimum=1, maximum=14, interactive=False)# saving_fps = gr.Slider(label="Saving FPS", value=6, minimum=6, maximum=48, step=6)with gr.Column():video = gr.Video()image.upload(fn=resize_image, inputs=image, outputs=image)generate_btn.click(fn=run_sampling, inputs=[image], outputs=video, api_name="video")demo.launch()7 unmodified lines8910111213142 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321439 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043057 unmodified linesimport numpy as npimport torchfrom einops import rearrange, repeatfrom fire import Firefrom omegaconf import OmegaConffrom PIL import Imagefrom torchvision.transforms import ToTensor2 unmodified linesDeepFloydDataFilteringfrom sgm.inference.helpers import embed_watermarkfrom sgm.util import default, instantiate_from_confighf_hub_download(repo_id="stabilityai/stable-video-diffusion-img2vid-xt", filename="svd_xt.safetensors", local_dir="checkpoints")version = "svd_xt"device = "cuda"def load_model(config: str,device: str,num_frames: int,num_steps: int,):config = OmegaConf.load(config)if device == "cuda":config.model.params.conditioner_config.params.emb_models[0].params.open_clip_embedding_config.params.init_device = deviceconfig.model.params.sampler_config.params.num_steps = num_stepsconfig.model.params.sampler_config.params.guider_config.params.num_frames = (num_frames)if device == "cuda":with torch.device(device):model = instantiate_from_config(config.model).to(device).eval()else:model = instantiate_from_config(config.model).to(device).eval()filter = DeepFloydDataFiltering(verbose=False, device=device)return model, filterif version == "svd_xt":num_frames = 25num_steps = 30model_config = "scripts/sampling/configs/svd_xt.yaml"else:raise ValueError(f"Version {version} does not exist.")model, filter = load_model(model_config,device,num_frames,num_steps,)def sample(input_path: str = "assets/test_image.png", # Can either be image file or folder with image filesversion: str = "svd_xt",fps_id: int = 6,motion_bucket_id: int = 127,cond_aug: float = 0.02,seed: int = 23,decoding_t: int = 7, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary.device: str = "cuda",output_folder: str = "outputs",):"""Simple script to generate a single sample conditioned on an image `input_path` or multiple images, one for eachimage file in folder `input_path`. If you run out of VRAM, try decreasing `decoding_t`."""torch.manual_seed(seed)path = Path(input_path)all_img_paths = []if path.is_file():if any([input_path.endswith(x) for x in ["jpg", "jpeg", "png"]]):all_img_paths = [input_path]else:raise ValueError("Path is not valid image file.")elif path.is_dir():all_img_paths = sorted([ffor f in path.iterdir()if f.is_file() and f.suffix.lower() in [".jpg", ".jpeg", ".png"]])if len(all_img_paths) == 0:raise ValueError("Folder does not contain any images.")else:raise ValueErrorfor input_img_path in all_img_paths:with Image.open(input_img_path) as image:if image.mode == "RGBA":image = image.convert("RGB")w, h = image.sizeif h % 64 != 0 or w % 64 != 0:width, height = map(lambda x: x - x % 64, (w, h))image = image.resize((width, height))print(f"WARNING: Your image is of size {h}x{w} which is not divisible by 64. We are resizing to {height}x{width}!")image = ToTensor()(image)image = image * 2.0 - 1.0image = image.unsqueeze(0).to(device)H, W = image.shape[2:]assert image.shape[1] == 3F = 8C = 4shape = (num_frames, C, H // F, W // F)if (H, W) != (576, 1024):print("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`.")if motion_bucket_id > 255:print("WARNING: High motion bucket! This may lead to suboptimal performance.")if fps_id < 5:print("WARNING: Small fps value! This may lead to suboptimal performance.")if fps_id > 30:print("WARNING: Large fps value! This may lead to suboptimal performance.")value_dict = {}value_dict["motion_bucket_id"] = motion_bucket_idvalue_dict["fps_id"] = fps_idvalue_dict["cond_aug"] = cond_augvalue_dict["cond_frames_without_noise"] = imagevalue_dict["cond_frames"] = image + cond_aug * torch.randn_like(image)value_dict["cond_aug"] = cond_augwith torch.no_grad():with torch.autocast(device):batch, batch_uc = get_batch(get_unique_embedder_keys_from_conditioner(model.conditioner),value_dict,[1, num_frames],T=num_frames,device=device,)c, uc = model.conditioner.get_unconditional_conditioning(batch,batch_uc=batch_uc,force_uc_zero_embeddings=["cond_frames","cond_frames_without_noise",],)for k in ["crossattn", "concat"]:uc[k] = repeat(uc[k], "b ... -> b t ...", t=num_frames)uc[k] = rearrange(uc[k], "b t ... -> (b t) ...", t=num_frames)c[k] = repeat(c[k], "b ... -> b t ...", t=num_frames)c[k] = rearrange(c[k], "b t ... -> (b t) ...", t=num_frames)randn = torch.randn(shape, device=device)additional_model_inputs = {}additional_model_inputs["image_only_indicator"] = torch.zeros(2, num_frames).to(device)additional_model_inputs["num_video_frames"] = batch["num_video_frames"]def denoiser(input, sigma, c):return model.denoiser(model.model, input, sigma, c, **additional_model_inputs)samples_z = model.sampler(denoiser, randn, cond=c, uc=uc)model.en_and_decode_n_samples_a_time = decoding_tsamples_x = model.decode_first_stage(samples_z)samples = torch.clamp((samples_x + 1.0) / 2.0, min=0.0, max=1.0)os.makedirs(output_folder, exist_ok=True)base_count = len(glob(os.path.join(output_folder, "*.mp4")))video_path = os.path.join(output_folder, f"{base_count:06d}.mp4")writer = cv2.VideoWriter(video_path,cv2.VideoWriter_fourcc(*"mp4v"),fps_id + 1,(samples.shape[-1], samples.shape[-2]),)samples = embed_watermark(samples)samples = filter(samples)vid = ((rearrange(samples, "t c h w -> t h w c") * 255).cpu().numpy().astype(np.uint8))for frame in vid:frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)writer.write(frame)writer.release()return video_pathdef get_unique_embedder_keys_from_conditioner(conditioner):return list(set([x.input_key for x in conditioner.embedders]))39 unmodified linesbatch_uc[key] = torch.clone(batch[key])return batch, batch_ucimport gradio as grimport uuiddef resize_image(image_path, output_size=(1024, 576)):image = Image.open(image_path)# Calculate aspect ratiostarget_aspect = output_size[0] / output_size[1] # Aspect ratio of the desired sizeimage_aspect = image.width / image.height # Aspect ratio of the original image# Resize then crop if the original image is largerif image_aspect > target_aspect:# Resize the image to match the target height, maintaining aspect rationew_height = output_size[1]new_width = int(new_height * image_aspect)resized_image = image.resize((new_width, new_height), Image.LANCZOS)# Calculate coordinates for croppingleft = (new_width - output_size[0]) / 2top = 0right = (new_width + output_size[0]) / 2bottom = output_size[1]else:# Resize the image to match the target width, maintaining aspect rationew_width = output_size[0]new_height = int(new_width / image_aspect)resized_image = image.resize((new_width, new_height), Image.LANCZOS)# Calculate coordinates for croppingleft = 0top = (new_height - output_size[1]) / 2right = output_size[0]bottom = (new_height + output_size[1]) / 2# Crop the imagecropped_image = resized_image.crop((left, top, right, bottom))return cropped_imagewith gr.Blocks() as demo:gr.Markdown('''# Stable Video Diffusion - Image2Video - XTGenerate 25 frames of video from a single image using SDV-XT.''')with gr.Column():image = gr.Image(label="Upload your image (it will be center cropped to 1024x576)", type="filepath")generate_btn = gr.Button("Generate")with gr.Column():video = gr.Video()image.upload(fn=resize_image, inputs=image, outputs=image, queue=False)generate_btn.click(fn=sample, inputs=image, outputs=video, api_name="video")if __name__ == "__main__":demo.launch(share=True)
app.py+218-62