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"
model_id_or_path = "CompVis/stable-diffusion-v1-4"
pipe = StableDiffusionInpaintingPipeline.from_pretrained(
model_id_or_path,
revision="fp16",
torch_dtype=torch.half, #float16
use_auth_token=auth_token
)
pipe = pipe.to(device)
model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64)
model.eval()
model.load_state_dict(torch.load('./clipseg/weights/rd64-uni.pth', map_location=torch.device(device)), strict=False)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
transforms.Resize((512, 512)),
])
def predict(radio, dict, word_mask, prompt=""):
if(radio == "draw a mask above"):
with autocast(device): #"cuda"
init_image = dict["image"].convert("RGB").resize((512, 512))
mask = dict["mask"].convert("RGB").resize((512, 512))
elif(radio == "type what to keep"):
img = transform(dict["image"]).squeeze(0)
word_masks = [word_mask]
with torch.no_grad():
preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
init_image = dict['image'].convert('RGB').resize((512, 512))
filename = f"{uuid.uuid4()}.png"
plt.imsave(filename,torch.sigmoid(preds[0][0]))
img2 = cv2.imread(filename)
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)
word_masks = [word_mask]
with torch.no_grad():
preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
init_image = dict['image'].convert('RGB').resize((512, 512))
filename = f"{uuid.uuid4()}.png"
plt.imsave(filename,torch.sigmoid(preds[0][0]))
img2 = cv2.imread(filename)
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}
.markdown-body {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";
font-size: 16px;
line-height: 1.5;
word-wrap: break-word;
}
.container-lg {
max-width: 1012px;
margin-right: auto;
margin-left: auto;
}
[data-color-mode="auto"][data-light-theme*="light"] {
--color-workflow-card-connector: var(--color-scale-gray-3);
--color-workflow-card-connector-bg: var(--color-scale-gray-3);
--color-workflow-card-connector-inactive: var(--color-border-default);
--color-workflow-card-connector-inactive-bg: var(--color-border-default);
--color-workflow-card-connector-highlight: var(--color-scale-blue-4);
--color-workflow-card-connector-highlight-bg: var(--color-scale-blue-4);
--color-workflow-card-bg: var(--color-scale-white);
--color-workflow-card-inactive-bg: var(--color-canvas-inset);
--color-workflow-card-header-shadow: rgba(0, 0, 0, 0);
--color-workflow-card-progress-complete-bg: var(--color-scale-blue-4);
--color-workflow-card-progress-incomplete-bg: var(--color-scale-gray-2);
--color-discussions-state-answered-icon: var(--color-scale-white);
--color-bg-discussions-row-emoji-box: rgba(209, 213, 218, 0.5);
--color-notifications-button-text: var(--color-fg-muted);
--color-notifications-button-hover-text: var(--color-fg-default);
--color-notifications-button-hover-bg: var(--color-scale-gray-2);
--color-notifications-row-read-bg: var(--color-canvas-subtle);
--color-notifications-row-bg: var(--color-scale-white);
--color-icon-directory: var(--color-scale-blue-3);
--color-checks-step-error-icon: var(--color-scale-red-4);
--color-calendar-halloween-graph-day-L1-bg: #ffee4a;
--color-calendar-halloween-graph-day-L2-bg: #ffc501;
--color-calendar-halloween-graph-day-L3-bg: #fe9600;
--color-calendar-halloween-graph-day-L4-bg: #03001c;
--color-calendar-graph-day-bg: #ebedf0;
--color-calendar-graph-day-border: rgba(27, 31, 35, 0.06);
--color-calendar-graph-day-L1-bg: #9be9a8;
--color-calendar-graph-day-L2-bg: #40c463;
--color-calendar-graph-day-L3-bg: #30a14e;
--color-calendar-graph-day-L4-bg: #216e39;
--color-calendar-graph-day-L1-border: rgba(27, 31, 35, 0.06);
--color-calendar-graph-day-L2-border: rgba(27, 31, 35, 0.06);
--color-calendar-graph-day-L3-border: rgba(27, 31, 35, 0.06);
--color-calendar-graph-day-L4-border: rgba(27, 31, 35, 0.06);
--color-user-mention-fg: var(--color-fg-default);
--color-user-mention-bg: var(--color-attention-subtle);
--color-text-white: var(--color-scale-white);
}
:root {
--Layout-pane-width: 220px;
--Layout-content-width: 100%;
--Layout-template-columns: 1fr var(--Layout-pane-width);
--Layout-template-areas: "content pane";
--Layout-column-gap: 16px;
--Layout-row-gap: 16px;
--Layout-outer-spacing-x: 0px;
--Layout-outer-spacing-y: 0px;
--Layout-inner-spacing-min: 0px;
--Layout-inner-spacing-max: 0px;
}
'''
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.inputs.Dropdown("512*512", "256*256")
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" .
The systems allows to create segmentation models without training based on:
An arbitrary text query
Or an image with a mask highlighting stuff or an object.
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
PhraseCut
and PhraseCutPlus
: Referring expression dataset
PFEPascalWrapper
: Wrapper class for PFENet's Pascal-5i implementation
PascalZeroShot
: Wrapper class for PascalZeroShot
COCOWrapper
: Wrapper class for COCO.
Models
CLIPDensePredT
: CLIPSeg model with transformer-based decoder.
ViTDensePredT
: CLIPSeg model with transformer-based decoder.
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.
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()