Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464762 unmodified lines11011111211311411511611711811912010 unmodified lines1311321331341351361371381391401411421431441451461472 unmodified lines1501511521531541551561571581591601611621631642 unmodified lines167168169170import os# Disable JITos.environ["PYTORCH_JIT"] = "0"from einops import rearrangeimport gradio as grimport spacesimport torchimport torch.nn.functional as Ffrom PIL import Image, ImageOpsfrom transformers import AutoModel, CLIPImageProcessorhf_repo = "nvidia/RADIO-L"image_processor = CLIPImageProcessor.from_pretrained(hf_repo)model = AutoModel.from_pretrained(hf_repo, trust_remote_code=True)model.eval()title = """RADIO: Reduce All Domains Into One"""description = """# RADIOAM-RADIO is a framework to distill Large Vision Foundation models into a single one.RADIO, a new vision foundation model, excels across visual domains, serving as a superior replacement for vision backbones.Integrating CLIP variants, DINOv2, and SAM through distillation, it preserves unique features like text grounding and segmentation correspondence.Outperforming teachers in ImageNet zero-shot (+6.8%), kNN (+2.39%), and linear probing segmentation (+3.8%) and vision-language models (LLaVa 1.5 up to 1.5%), it scales to any resolution, supports non-square images.# InstructionsSimply paste an image or pick one from the gallery of examples and then click the "Submit" button."""inputs = [gr.Image(type="pil")]examples = "./samples/"outputs = [gr.Textbox(label="Feature Shape"),gr.Image(),]def get_robust_pca(features: torch.Tensor, m: float = 2, remove_first_component=False):# features: (N, C)62 unmodified linesreturn pca_colordef pad_image_to_multiple_of_16(image):# Calculate the new dimensions to make them multiples of 16width, height = image.sizenew_width = (width + 15) // 16 * 16new_height = (height + 15) // 16 * 16# Calculate the padding needed on each sidepad_width = new_width - width10 unmodified linesreturn padded_image@spaces.GPUdef infer_radio(image):"""Define the function to generate the output."""model.cuda()image=pad_image_to_multiple_of_16(image)width, height = image.sizepixel_values = image_processor(images=image, return_tensors='pt').pixel_valuespixel_values = pixel_values.to(torch.bfloat16).cuda()_, features = model(pixel_values)num_rows = height // model.patch_sizenum_cols = width // model.patch_size2 unmodified linesfeatures = rearrange(features, 'b (h w) c -> b h w c', h=num_rows, w=num_cols).float()pca_viz = get_pca_map(features, (height, width), interpolation='bilinear')return f"{features.shape}", pca_viz# Create the Gradio interfacedemo = gr.Interface(fn=infer_radio,inputs=inputs,examples=examples,outputs=outputs,title=title,description=description,2 unmodified linesif __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979862 unmodified lines16116216316416516616716816917017110 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified lines318319320import osimport requests# Disable JITos.environ["PYTORCH_JIT"] = "0"from einops import rearrangeimport gradio as grimport numpy as npimport spacesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom PIL import Image, ImageOpsfrom transformers import AutoModel, CLIPImageProcessorfrom segment_anything import SamAutomaticMaskGenerator, sam_model_registryfrom segment_anything.modeling.image_encoder import ImageEncoderViTclass RADIOVenc(nn.Module):def __init__(self, radio: nn.Module, img_enc: ImageEncoderViT, img_size: int = 1024):super().__init__()self.radio = radioself.neck = img_enc.neckself.img_size = img_sizeself.dtype = radio.input_conditioner.dtypedef forward(self, x: torch.Tensor):h, w = x.shape[-2:]if self.dtype is not None:x = x.to(dtype=self.dtype)with torch.autocast('cuda', dtype=torch.bfloat16, enabled=self.dtype is None):output = self.radio(x)features = output["sam"].featuresrows = h // 16cols = w // 16features = rearrange(features, 'b (h w) c -> b c h w', h=rows, w=cols)features = self.neck(features)return featuresdef download_file(url, save_path):# Check if the file already existsif os.path.exists(save_path):print(f"File already exists at {save_path}. Skipping download.")returnprint(f"Downloading from {url}")# Send a GET request to the URLresponse = requests.get(url, stream=True)# Check if the request was successfulif response.status_code == 200:# Open the file in binary write modewith open(save_path, 'wb') as file:# Iterate over the response content in chunksfor chunk in response.iter_content(chunk_size=1024):if chunk: # filter out keep-alive new chunksfile.write(chunk)print(f"File downloaded successfully and saved as {save_path}")else:print(f"Failed to download file. HTTP Status Code: {response.status_code}")hf_repo = "nvidia/RADIO-L"image_processor = CLIPImageProcessor.from_pretrained(hf_repo)model_version = "radio_v2.5-l" # for RADIOv2.5-L model (ViT-L/16)model = torch.hub.load('NVlabs/RADIO','radio_model',version=model_version,progress=True,skip_validation=True,adaptor_names='sam',vitdet_window_size=16)model.eval()local_sam_checkpoint_path = "sam_vit_h_4b8939.pth"download_file("https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", local_sam_checkpoint_path)sam = sam_model_registry["vit_h"](checkpoint=local_sam_checkpoint_path)model._patch_size = 16sam.image_encoder = RADIOVenc(model, sam.image_encoder, img_size=1024)conditioner = model.make_preprocessor_external()sam.pixel_mean = conditioner.norm_mean * 255sam.pixel_std = conditioner.norm_std * 255def get_robust_pca(features: torch.Tensor, m: float = 2, remove_first_component=False):# features: (N, C)62 unmodified linesreturn pca_colordef pad_image_to_multiple_of(image, multiple=16):# Calculate the new dimensions to make them multipleswidth, height = image.sizenew_width = (width + multiple -1) // multiple * multiplenew_height = (height + multiple -1) // multiple * multiple# Calculate the padding needed on each sidepad_width = new_width - width10 unmodified linesreturn padded_imagedef center_crop_resize(image, size=(1024, 1024)):# Get dimensionswidth, height = image.size# Determine the center crop boxif width > height:new_width = heightnew_height = heightleft = (width - new_width) / 2top = 0right = (width + new_width) / 2bottom = heightelse:new_width = widthnew_height = widthleft = 0top = (height - new_height) / 2right = widthbottom = (height + new_height) / 2# Crop the image to a squareimage = image.crop((left, top, right, bottom))# Resize the cropped image to the target sizeimage = image.resize(size, Image.LANCZOS)return imagedef visualize_anns(orig_image: np.ndarray, anns):if len(anns) == 0:return orig_imagesorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)kernel = torch.ones(1, 1, 5, 5, dtype=torch.float32)# RGBAmask = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4), dtype=np.float32)mask[:,:,3] = 0for ann in sorted_anns:m = ann['segmentation']color_mask = np.concatenate([np.random.random(3), [0.35]])tm = torch.as_tensor(m).reshape(1, 1, *m.shape).float()cvtm = F.conv2d(tm, kernel, padding=2)border_mask = (cvtm < 25).flatten(0, 2).numpy()mask[m] = color_maskmask[m & border_mask, 3] *= 1.0 / 0.35color, alpha = mask[..., :3], mask[..., -1:]orig_image = orig_image.astype(np.float32) / 255overlay = alpha * color + (1 - alpha) * orig_imageoverlay = (overlay * 255).astype(np.uint8)return overlay@spaces.GPUdef infer_radio(image):"""Define the function to generate the output."""model.cuda()conditioner.cuda()sam.cuda()sam_generator = SamAutomaticMaskGenerator(sam, output_mode="binary_mask")# PCA feature visalizationpadded_image=pad_image_to_multiple_of(image, multiple=256)width, height = padded_image.sizepixel_values = image_processor(images=padded_image, return_tensors='pt').pixel_valuespixel_values = pixel_values.to(torch.bfloat16).cuda()pixel_values = conditioner(pixel_values)_, features = model(pixel_values)["backbone"]num_rows = height // model.patch_sizenum_cols = width // model.patch_size2 unmodified linesfeatures = rearrange(features, 'b (h w) c -> b h w c', h=num_rows, w=num_cols).float()pca_viz = get_pca_map(features, (height, width), interpolation='bilinear')# SAM feature visualizationresized_image = center_crop_resize(image)image_array = np.array(image)print("image size", image_array.shape)#image_array = np.transpose(image_array, (2, 0, 1))masks = sam_generator.generate(image_array)overlay = visualize_anns(image_array, masks)return f"{features.shape}", pca_viz, overlaytitle = """RADIO: Reduce All Domains Into One"""description = """# RADIOAM-RADIO is a framework to distill Large Vision Foundation models into a single one.RADIO, a new vision foundation model, excels across visual domains, serving as a superior replacement for vision backbones.Integrating CLIP variants, DINOv2, and SAM through distillation, it preserves unique features like text grounding and segmentation correspondence.Outperforming teachers in ImageNet zero-shot (+6.8%), kNN (+2.39%), and linear probing segmentation (+3.8%) and vision-language models (LLaVa 1.5 up to 1.5%), it scales to any resolution, supports non-square images.# InstructionsSimply paste an image or pick one from the gallery of examples and then click the "Submit" button."""inputs = [gr.Image(type="pil")]outputs = [gr.Textbox(label="Feature Shape"),gr.Image(label="PCA Feature Visalization"),gr.Image(label="SAM Masks"),]# Create the Gradio interfacedemo = gr.Interface(fn=infer_radio,inputs=inputs,examples="./samples/",outputs=outputs,title=title,description=description,2 unmodified linesif __name__ == "__main__":demo.launch()
app.py+185-35