import gradio as gr from io import BytesIO import requests import PIL from PIL import Image import numpy as np import os import uuid import torch from torch import autocast import cv2 from matplotlib import pyplot as plt from inpainting import StableDiffusionInpaintingPipeline from torchvision import transforms from clipseg.models.clipseg import CLIPDensePredT Image.LOAD_TRUNCATED_IMAGES = True auth_token = os.environ.get("API_TOKEN") or True def download_image(url): response = requests.get(url) return PIL.Image.open(BytesIO(response.content)).convert("RGB") #device = "cpu" #"cuda" if torch.cuda.is_available() else "cpu" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("The model will be running on :: ", device, " ~device") # Convert model parameters and buffers to CPU or Cuda model_id_or_path = "CompVis/stable-diffusion-v1-4" pipe = StableDiffusionInpaintingPipeline.from_pretrained( model_id_or_path, #revision="fp16", torch_dtype=torch.float16, use_auth_token=auth_token ).to(device) #pipe = pipe.to(device) #self.register_buffer('n_', ...) #print ("torch.backends.mps.is_available: ", torch.backends.mps.is_available()) model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True) model = model.to(torch.device(device)) model.eval().float() #model = model.type(torch.HalfTensor) weightsPATH = './clipseg/weights/rd64-uni.pth' #state = {'model': model.state_dict()} #torch.save(state, weightsPATH) model.load_state_dict(torch.load(weightsPATH, map_location=torch.device(device)), strict=False) #False #model.load_state_dict(torch.load(weightsPATH)['model']) print ("Torch load(model) : ", model) print ("Weights : ") # print weights for k, v in model.named_parameters(): print(k, v) imgRes = 256 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), transforms.Resize((imgRes, imgRes)), ]) def predict(radio, dict, word_mask, prompt=""): if(radio == "draw a mask above"): #with autocast(device): #"cuda" with autocast(enable=(False if device=='cpu' else True)): init_image = dict["image"].convert("RGB").resize((imgRes, imgRes)) mask = dict["mask"].convert("RGB").resize((imgRes, imgRes)) elif(radio == "type what to keep"): img = transform(dict["image"]).squeeze(0) #-----New Lines----- if torch.cuda.is_available(): img.cuda() print ("yes, CUDA is available here !! ") #------------------ word_masks = [word_mask] with torch.no_grad(): #torch.cuda.amp.autocast(): # preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0] #model = model.to(torch.device(device)) img = img.to(torch.device(device)) #prompt = prompt.to(torch.device(device)) #--------- init_image = dict['image'].convert('RGB').resize((imgRes, imgRes)) filename = f"{uuid.uuid4()}.png" plt.imsave(filename,torch.sigmoid(preds[0][0])) img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) img = Image.fromarray(img) #img2 = cv2.imread(filename) #if ret == True: gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY) cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB) mask = Image.fromarray(np.uint8(bw_image)).convert('RGB') os.remove(filename) else: img = transform(dict["image"]).unsqueeze(0) #-----New Lines----- if torch.cuda.is_available(): img.cuda() print ("yes, CUDA is available here !! ") #------------------ word_masks = [word_mask] #with torch.cuda.amp.autocast(): # with torch.no_grad(): preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0] #model = model.to(torch.device(device)) img = img.to(torch.device(device)) #prompt = prompt.to(torch.device(device)) init_image = dict['image'].convert('RGB').resize((imgRes, imgRes)) filename = f"{uuid.uuid4()}.png" plt.imsave(filename,torch.sigmoid(preds[0][0])) #img2 = cv2.imread(filename) img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) img = Image.fromarray(img) #if ret == True: gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY) cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB) mask = Image.fromarray(np.uint8(bw_image)).convert('RGB') os.remove(filename) #with autocast(device): #"cuda" with autocast(enable=(False if device=='cpu' else True)): #with autocast(device_type="cpu", dtype=torch.bfloat16): images = pipe(prompt = prompt, init_image=init_image, mask_image=mask, strength=0.8)["sample"] return images[0] # examples = [[dict(image="init_image.png", mask="mask_image.png"), "A panda sitting on a bench"]] css = ''' .container {max-width: 1150px;margin: auto;padding-top: 1.5rem} #image_upload{min-height:400px} #image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px} #mask_radio .gr-form{background:transparent; border: none} #word_mask{margin-top: .75em !important} #word_mask textarea:disabled{opacity: 0.3} .footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5} .footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white} .dark .footer {border-color: #303030} .dark .footer>p {background: #0b0f19} .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%} #image_upload .touch-none{display: flex} ''' def swap_word_mask(radio_option): if(radio_option == "draw a mask above"): return gr.update(interactive=False, placeholder="Disabled") else: return gr.update(interactive=True, placeholder="A cat") image_blocks = gr.Blocks(css=css) with image_blocks as demo: gr.HTML( """
Inpaint Stable Diffusion by either drawing a mask or typing what to replace & what to keep !!!
This repository contains the code used in the paper "Image Segmentation Using Text and Image Prompts".
The systems allows to create segmentation models without training based on:
In the Quickstart.ipynb
notebook we provide the code for using a pre-trained CLIPSeg model. If you run the notebook locally, make sure you downloaded the rd64-uni.pth
weights, either manually or via git lfs extension.
It can also be used interactively using MyBinder
(please note that the VM does not use a GPU, thus inference takes a few seconds).
This code base depends on pytorch, torchvision and clip (pip install git+https://github.com/openai/CLIP.git
).
Additional dependencies are hidden for double blind review.
PhraseCut
and PhraseCutPlus
: Referring expression datasetPFEPascalWrapper
: Wrapper class for PFENet's Pascal-5i implementationPascalZeroShot
: Wrapper class for PascalZeroShotCOCOWrapper
: Wrapper class for COCO.CLIPDensePredT
: CLIPSeg model with transformer-based decoder.ViTDensePredT
: CLIPSeg model with transformer-based decoder.For some of the datasets third party dependencies are required. Run the following commands in the third_party
folder.
git clone https://github.com/cvlab-yonsei/JoEm git clone https://github.com/Jia-Research-Lab/PFENet.git git clone https://github.com/ChenyunWu/PhraseCutDataset.git git clone https://github.com/juhongm999/hsnet.git
The MIT license does not apply to these weights.
To train use the training.py
script with experiment file and experiment id parameters. E.g. python training.py phrasecut.yaml 0
will train the first phrasecut experiment which is defined by the configuration
and first individual_configurations
parameters. Model weights will be written in logs/
.
For evaluation use score.py
. E.g. python score.py phrasecut.yaml 0 0
will train the first phrasecut experiment of test_configuration
and the first configuration in individual_configurations
.
In order to use the dataset and model wrappers for PFENet, the PFENet repository needs to be cloned to the root folder.
git clone https://github.com/Jia-Research-Lab/PFENet.git
The source code files in this repository (excluding model weights) are released under MIT license.
The model is licensed with a CreativeML Open RAIL-M license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please read the license