Spaces:
Running
Running
File size: 12,294 Bytes
fd3a517 53a6bc7 fd3a517 53a6bc7 7145dd2 26ebe16 19fc903 53a6bc7 a51380e fd3a517 cd0e33c a51380e cd0e33c a51380e 5fcc3eb fd3a517 cd0e33c a51380e cd0e33c a51380e fd3a517 19fc903 a51380e 19fc903 a51380e fd3a517 19fc903 7145dd2 19fc903 93ddd94 19fc903 9381693 7145dd2 19fc903 a51380e cd0e33c 7145dd2 cd0e33c 19fc903 fd3a517 cd0e33c fd3a517 a51380e fd3a517 cd0e33c fd3a517 a51380e 4b81875 cd0e33c 4b81875 cd0e33c 4b81875 cd0e33c 4b81875 cd0e33c fd3a517 19fc903 a51380e cd0e33c fd3a517 a51380e fd3a517 19fc903 a51380e fd3a517 cd0e33c fd3a517 cd0e33c fd3a517 cd0e33c fd3a517 cd0e33c fd3a517 cd0e33c fd3a517 a51380e fd3a517 7145dd2 a51380e fd3a517 cd0e33c fd3a517 a51380e fd3a517 cd0e33c fd3a517 a51380e fd3a517 a51380e fd3a517 ac4fa5c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
import os
import gradio as gr
from gradio_client import Client, handle_file
from pathlib import Path
from gradio.utils import get_cache_folder
import torch
import torchvision.transforms as transforms
from PIL import Image
import cv2
import numpy as np
class Examples(gr.helpers.Examples):
def __init__(self, *args, cached_folder=None, **kwargs):
super().__init__(*args, **kwargs, _initiated_directly=False)
if cached_folder is not None:
self.cached_folder = cached_folder
# self.cached_file = Path(self.cached_folder) / "log.csv"
self.create()
def postprocess(output, prompt):
result = []
image = Image.open(output)
w, h = image.size
n = len(prompt)
slice_width = w // n
for i in range(n):
left = i * slice_width
right = (i + 1) * slice_width if i < n - 1 else w
cropped_img = image.crop((left, 0, right, h))
# 生成 caption
caption = prompt[i]
# 存入列表
result.append((cropped_img, caption))
return result
# user click the image to get points, and show the points on the image
def get_point(img, sel_pix, evt: gr.SelectData):
print(sel_pix)
if len(sel_pix) < 5:
sel_pix.append((evt.index, 1)) # default foreground_point
img = cv2.imread(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# draw points
for point, label in sel_pix:
cv2.drawMarker(img, point, colors[label], markerType=markers[label], markerSize=20, thickness=5)
# if img[..., 0][0, 0] == img[..., 2][0, 0]: # BGR to RGB
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(sel_pix)
return img, sel_pix
# undo the selected point
def undo_points(orig_img, sel_pix):
if isinstance(orig_img, int): # if orig_img is int, the image if select from examples
temp = cv2.imread(image_examples[orig_img][0])
temp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)
else:
temp = cv2.imread(orig_img)
temp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)
# draw points
if len(sel_pix) != 0:
sel_pix.pop()
for point, label in sel_pix:
cv2.drawMarker(temp, point, colors[label], markerType=markers[label], markerSize=20, thickness=5)
if temp[..., 0][0, 0] == temp[..., 2][0, 0]: # BGR to RGB
temp = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)
return temp, sel_pix
HF_TOKEN = os.environ.get('HF_KEY')
client = Client("Canyu/Diception",
max_workers=3,
hf_token=HF_TOKEN)
colors = [(255, 0, 0), (0, 255, 0)]
markers = [1, 5]
map_prompt = {
'depth': '[[image2depth]]',
'normal': '[[image2normal]]',
'human pose': '[[image2pose]]',
'entity segmentation': '[[image2panoptic coarse]]',
'point segmentation': '[[image2segmentation]]',
'semantic segmentation': '[[image2semantic]]',
}
def download_additional_params(model_name, filename="add_params.bin"):
# 下载文件并返回文件路径
file_path = hf_hub_download(repo_id=model_name, filename=filename, use_auth_token=HF_TOKEN)
return file_path
# 加载 additional_params.bin 文件
def load_additional_params(model_name):
# 下载 additional_params.bin
params_path = download_additional_params(model_name)
# 使用 torch.load() 加载文件内容
additional_params = torch.load(params_path, map_location='cpu')
# 返回加载的参数内容
return additional_params
def process_image_check(path_input, prompt, sel_points, semantic):
if path_input is None:
raise gr.Error(
"Missing image in the left pane: please upload an image first."
)
if len(prompt) == 0:
raise gr.Error(
"At least 1 prediction type is needed."
)
def process_image_4(image_path, prompt):
inputs = []
for p in prompt:
cur_p = map_prompt[p]
coor_point = []
point_labels = []
cur_input = {
# 'original_size': [[w,h]],
# 'target_size': [[768, 768]],
'prompt': [cur_p],
'coor_point': coor_point,
'point_labels': point_labels,
}
inputs.append(cur_input)
return inputs
def inf(image_path, prompt, sel_points, semantic):
print('=========== PROCESS IMAGE CHECK ===========')
print(f"Image Path: {image_path}")
print(f"Prompt: {prompt}")
print(f"Selected Points (before processing): {sel_points}")
print(f"Semantic Input: {semantic}")
print('===========================================')
if 'point segmentation' in prompt and len(sel_points) == 0:
raise gr.Error(
"At least 1 point is needed."
)
return
if 'point segmentation' not in prompt and len(sel_points) != 0:
raise gr.Error(
"You must select 'point segmentation' when performing point segmentation."
)
return
if 'semantic segmentation' in prompt and semantic == '':
raise gr.Error(
"Target category is needed."
)
return
if 'semantic segmentation' not in prompt and semantic != '':
raise gr.Error(
"You must select 'semantic segmentation' when performing semantic segmentation."
)
return
# return None
# inputs = process_image_4(image_path, prompt, sel_points, semantic)
prompt_str = str(sel_points)
result = client.predict(
input_image=handle_file(image_path),
checkbox_group=prompt,
selected_points=prompt_str,
semantic_input=semantic,
api_name="/inf"
)
result = postprocess(result, prompt)
return result
def clear_cache():
return None, None
def run_demo_server():
options = ['depth', 'normal', 'entity segmentation', 'human pose', 'point segmentation', 'semantic segmentation']
gradio_theme = gr.themes.Default()
with gr.Blocks(
theme=gradio_theme,
title="Diception",
css="""
#download {
height: 118px;
}
.slider .inner {
width: 5px;
background: #FFF;
}
.viewport {
aspect-ratio: 4/3;
}
.tabs button.selected {
font-size: 20px !important;
color: crimson !important;
}
h1 {
text-align: center;
display: block;
}
h2 {
text-align: center;
display: block;
}
h3 {
text-align: center;
display: block;
}
.md_feedback li {
margin-bottom: 0px !important;
}
""",
head="""
<script async src="https://www.googletagmanager.com/gtag/js?id=G-1FWSVCGZTG"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-1FWSVCGZTG');
</script>
""",
) as demo:
selected_points = gr.State([]) # store points
original_image = gr.State(value=None) # store original image without points, default None
gr.HTML(
"""
<h1>DICEPTION: A Generalist Diffusion Model for Vision Perception</h1>
<h3>One single model solves multiple perception tasks, producing impressive results!</h3>
<p align="center">
<a title="arXiv" href="https://arxiv.org" target="_blank" rel="noopener noreferrer"
style="display: inline-block;">
<img src="https://www.obukhov.ai/img/badges/badge-pdf.svg">
</a>
<a title="Github" href="https://github.com/aim-uofa/Diception" target="_blank" rel="noopener noreferrer"
style="display: inline-block;">
<img src="https://img.shields.io/github/stars/aim-uofa/Diception?label=GitHub%20%E2%98%85&logo=github&color=C8C"
alt="badge-github-stars">
</a>
</p>
"""
)
with gr.Row():
checkbox_group = gr.CheckboxGroup(choices=options, label="Select options:")
with gr.Row():
semantic_input = gr.Textbox(label="Category Name (for semantic segmentation only, in COCO)", placeholder="e.g. person/cat/dog/elephant......")
with gr.Row():
gr.Markdown('For non-human image inputs, the pose results may have issues. Same when perform semantic segmentation with categories that are not in COCO.')
with gr.Row():
with gr.Column():
input_image = gr.Image(
label="Input Image",
type="filepath",
)
with gr.Column():
with gr.Row():
gr.Markdown('You can click on the image to select points prompt. At most 5 point.')
matting_image_submit_btn = gr.Button(
value="Run", variant="primary"
)
with gr.Row():
undo_button = gr.Button('Undo point')
matting_image_reset_btn = gr.Button(value="Reset")
# with gr.Row():
# img_clear_button = gr.Button("Clear Cache")
with gr.Column():
# matting_image_output = gr.Image(label='Output')
# matting_image_output = gr.Image(label='Results')
matting_image_output = gr.Gallery(label="Results")
# label="Matting Output",
# type="filepath",
# show_download_button=True,
# show_share_button=True,
# interactive=False,
# elem_classes="slider",
# position=0.25,
# )
# img_clear_button.click(clear_cache, outputs=[input_image, matting_image_output])
matting_image_submit_btn.click(
fn=process_image_check,
inputs=[input_image, checkbox_group, selected_points, semantic_input],
outputs=None,
preprocess=False,
queue=False,
).success(
# fn=process_pipe_matting,
fn=inf,
inputs=[input_image, checkbox_group, selected_points, semantic_input],
outputs=[matting_image_output],
concurrency_limit=1,
)
matting_image_reset_btn.click(
fn=lambda: (
None,
None,
[]
),
inputs=[],
outputs=[
input_image,
matting_image_output,
selected_points
],
queue=False,
)
# once user upload an image, the original image is stored in `original_image`
def store_img(img):
return img, [] # when new image is uploaded, `selected_points` should be empty
input_image.upload(
store_img,
[input_image],
[original_image, selected_points]
)
input_image.select(
get_point,
[input_image, selected_points],
[input_image, selected_points],
)
undo_button.click(
undo_points,
[original_image, selected_points],
[input_image, selected_points]
)
# gr.Examples(
# fn=inf,
# examples=[
# ["assets/person.jpg", ['depth', 'normal', 'entity segmentation', 'pose']]
# ],
# inputs=[input_image, checkbox_group],
# outputs=[matting_image_output],
# cache_examples=True,
# # cache_examples=False,
# # cached_folder="cache_dir",
# )
demo.queue(
api_open=False,
).launch()
if __name__ == '__main__':
run_demo_server() |