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 #from huggingface_hub import hf_hub_download #hf_hub_download(repo_id="ThereforeGames/txt2mask", filename="/repositories/clipseg/") #clone_from (str, optional) — Either a repository url or repo_id. Example: #api = HfApi() #from huggingface_hub import Repository #with Repository(local_dir="clipseg", clone_from="ThereforeGames/txt2mask/repositories/clipseg/") """ import sys import os from zipfile import ZipFile zf = ZipFile('clipseg-master.zip', 'r') zf.extractall('./clipseg') zf.close() from huggingface_hub import HfApi api = HfApi() api.upload_folder( folder_path="/", path_in_repo="ThereforeGames/txt2mask/repositories/clipseg/", repo_id="ThereforeGames/txt2mask", # repo_type="dataset", # ignore_patterns="**/logs/*.txt", ) """ #.commit(commit_message="clipseg uploaded...") # with open("file.txt", "w+") as f: # f.write(json.dumps({"hey": 8})) 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.double, #float16 use_auth_token=auth_token ) #self.register_buffer('n_', ...) print ("torch.backends.mps.is_available: ", torch.backends.mps.is_available()) pipe = pipe.to(device) model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True) model = model.to(torch.device(device)) model.eval() #.half() 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" 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])) img2 = cv2.imread(filename) #if ret == True: gray_image = cv2.cvtColor(img2, 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) #if ret == True: gray_image = cv2.cvtColor(img2, 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" 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( """

Stable Diffusion Multi Inpainting

Inpaint Stable Diffusion by either drawing a mask or typing what to replace & what to keep !!!

""" ) with gr.Row(): with gr.Column(): image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Upload").style(height=400) with gr.Box(elem_id="mask_radio").style(border=False): radio = gr.Radio(["draw a mask above", "type what to mask below", "type what to keep"], value="draw a mask above", show_label=False, interactive=True).style(container=False) word_mask = gr.Textbox(label = "What to find in your image", interactive=False, elem_id="word_mask", placeholder="Disabled").style(container=False) img_res = gr.Dropdown(['512*512', '256*256'], label="Image Resolution") prompt = gr.Textbox(label = 'Your prompt (what you want to add in place of what you are removing)') radio.change(fn=swap_word_mask, inputs=radio, outputs=word_mask,show_progress=False) radio.change(None, inputs=[], outputs=image_blocks, _js = """ () => { css_style = document.styleSheets[document.styleSheets.length - 1] last_item = css_style.cssRules[css_style.cssRules.length - 1] last_item.style.display = ["flex", ""].includes(last_item.style.display) ? "none" : "flex"; }""") btn = gr.Button("Run") with gr.Column(): result = gr.Image(label="Result") btn.click(fn=predict, inputs=[radio, image, word_mask, prompt], outputs=result) gr.HTML( """

Image Segmentation Using Text and Image Prompts

This repository contains the code used in the paper "Image Segmentation Using Text and Image Prompts".

drawing

The systems allows to create segmentation models without training based on:

Quick Start

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).

Dependencies

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.

Datasets

Models

Third Party Dependencies

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

Weights

The MIT license does not apply to these weights.

Training and Evaluation

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.

Usage of PFENet Wrappers

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

LICENSE

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

Biases and content acknowledgment

Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. The model was trained on the LAION-5B dataset, which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes. You can read more in the model card

""" ) demo.launch()