File size: 15,361 Bytes
da47978 |
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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
import tempfile
import time
from collections.abc import Sequence
from typing import Any, cast
import gradio as gr
import numpy as np
import pillow_heif
import spaces
import torch
from gradio_image_annotation import image_annotator
from gradio_imageslider import ImageSlider
from PIL import Image
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
from refiners.fluxion.utils import no_grad
from refiners.solutions import BoxSegmenter
from transformers import GroundingDinoForObjectDetection, GroundingDinoProcessor
import spaces
import argparse
import os
from os import path
import shutil
from datetime import datetime
from safetensors.torch import load_file
from huggingface_hub import hf_hub_download
import gradio as gr
from diffusers import FluxPipeline
from PIL import Image
from huggingface_hub import login
# HF ํ ํฐ ์ธ์ฆ ์ฒ๋ฆฌ
HF_TOKEN = os.getenv("HF_TOKEN")
if HF_TOKEN is None:
raise ValueError("Please set the HF_TOKEN environment variable")
try:
login(token=HF_TOKEN)
except Exception as e:
raise ValueError(f"Failed to login to Hugging Face: {str(e)}")
# FLUX ํ์ดํ๋ผ์ธ ์ด๊ธฐํ ์์
def initialize_pipeline():
try:
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
torch_dtype=torch.bfloat16,
use_auth_token=HF_TOKEN
)
pipe.load_lora_weights(
hf_hub_download(
"ByteDance/Hyper-SD",
"Hyper-FLUX.1-dev-8steps-lora.safetensors",
use_auth_token=HF_TOKEN
)
)
pipe.fuse_lora(lora_scale=0.125)
pipe.to(device="cuda", dtype=torch.bfloat16)
return pipe
except Exception as e:
raise ValueError(f"Failed to initialize pipeline: {str(e)}")
# ํ์ดํ๋ผ์ธ ์ด๊ธฐํ
try:
pipe = initialize_pipeline()
except Exception as e:
raise RuntimeError(f"Failed to setup the model: {str(e)}")
BoundingBox = tuple[int, int, int, int]
pillow_heif.register_heif_opener()
pillow_heif.register_avif_opener()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# weird dance because ZeroGPU
segmenter = BoxSegmenter(device="cpu")
segmenter.device = device
segmenter.model = segmenter.model.to(device=segmenter.device)
gd_model_path = "IDEA-Research/grounding-dino-base"
gd_processor = GroundingDinoProcessor.from_pretrained(gd_model_path)
gd_model = GroundingDinoForObjectDetection.from_pretrained(gd_model_path, torch_dtype=torch.float32)
gd_model = gd_model.to(device=device) # type: ignore
assert isinstance(gd_model, GroundingDinoForObjectDetection)
# FLUX ํ์ดํ๋ผ์ธ ์ด๊ธฐํ ์ฝ๋ ์ถ๊ฐ
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
pipe.fuse_lora(lora_scale=0.125)
pipe.to(device="cuda", dtype=torch.bfloat16)
def generate_background(prompt: str, width: int, height: int) -> Image.Image:
"""๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง ์์ฑ ํจ์"""
try:
with timer("Background generation"):
image = pipe(
prompt=prompt,
width=width,
height=height,
num_inference_steps=8,
guidance_scale=4.0,
).images[0]
return image
except Exception as e:
raise gr.Error(f"Background generation failed: {str(e)}") # ๊ดํธ ๋ซ๊ธฐ ์์
def combine_with_background(foreground: Image.Image, background: Image.Image) -> Image.Image:
"""์ ๊ฒฝ๊ณผ ๋ฐฐ๊ฒฝ ํฉ์ฑ ํจ์"""
background = background.resize(foreground.size)
return Image.alpha_composite(background.convert('RGBA'), foreground)
def _process(
img: Image.Image,
prompt: str | BoundingBox | None,
bg_prompt: str | None,
) -> tuple[tuple[Image.Image, Image.Image, Image.Image], gr.DownloadButton]:
try:
# ๊ธฐ์กด ๊ฐ์ฒด ์ถ์ถ ๋ก์ง
mask, bbox, time_log = _gpu_process(img, prompt)
masked_alpha = apply_mask(img, mask, defringe=True)
# ๋ฐฐ๊ฒฝ ์์ฑ ๋ฐ ํฉ์ฑ
if bg_prompt:
background = generate_background(bg_prompt, img.width, img.height)
combined = combine_with_background(masked_alpha, background)
else:
combined = Image.alpha_composite(Image.new("RGBA", masked_alpha.size, "white"), masked_alpha)
# ์ ์ฅ ๋ก์ง
thresholded = mask.point(lambda p: 255 if p > 10 else 0)
bbox = thresholded.getbbox()
to_dl = masked_alpha.crop(bbox)
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
to_dl.save(temp, format="PNG")
temp.close()
return (img, combined, masked_alpha), gr.DownloadButton(value=temp.name, interactive=True)
except Exception as e:
raise gr.Error(f"Processing failed: {str(e)}")
def bbox_union(bboxes: Sequence[list[int]]) -> BoundingBox | None:
if not bboxes:
return None
for bbox in bboxes:
assert len(bbox) == 4
assert all(isinstance(x, int) for x in bbox)
return (
min(bbox[0] for bbox in bboxes),
min(bbox[1] for bbox in bboxes),
max(bbox[2] for bbox in bboxes),
max(bbox[3] for bbox in bboxes),
)
def corners_to_pixels_format(bboxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
x1, y1, x2, y2 = bboxes.round().to(torch.int32).unbind(-1)
return torch.stack((x1.clamp_(0, width), y1.clamp_(0, height), x2.clamp_(0, width), y2.clamp_(0, height)), dim=-1)
def gd_detect(img: Image.Image, prompt: str) -> BoundingBox | None:
assert isinstance(gd_processor, GroundingDinoProcessor)
# Grounding Dino expects a dot after each category.
inputs = gd_processor(images=img, text=f"{prompt}.", return_tensors="pt").to(device=device)
with no_grad():
outputs = gd_model(**inputs)
width, height = img.size
results: dict[str, Any] = gd_processor.post_process_grounded_object_detection(
outputs,
inputs["input_ids"],
target_sizes=[(height, width)],
)[0]
assert "boxes" in results and isinstance(results["boxes"], torch.Tensor)
bboxes = corners_to_pixels_format(results["boxes"].cpu(), width, height)
return bbox_union(bboxes.numpy().tolist())
def apply_mask(
img: Image.Image,
mask_img: Image.Image,
defringe: bool = True,
) -> Image.Image:
assert img.size == mask_img.size
img = img.convert("RGB")
mask_img = mask_img.convert("L")
if defringe:
# Mitigate edge halo effects via color decontamination
rgb, alpha = np.asarray(img) / 255.0, np.asarray(mask_img) / 255.0
foreground = cast(np.ndarray[Any, np.dtype[np.uint8]], estimate_foreground_ml(rgb, alpha))
img = Image.fromarray((foreground * 255).astype("uint8"))
result = Image.new("RGBA", img.size)
result.paste(img, (0, 0), mask_img)
return result
@spaces.GPU
def _gpu_process(
img: Image.Image,
prompt: str | BoundingBox | None,
) -> tuple[Image.Image, BoundingBox | None, list[str]]:
# Because of ZeroGPU shenanigans, we need a *single* function with the
# `spaces.GPU` decorator that *does not* contain postprocessing.
time_log: list[str] = []
if isinstance(prompt, str):
t0 = time.time()
bbox = gd_detect(img, prompt)
time_log.append(f"detect: {time.time() - t0}")
if not bbox:
print(time_log[0])
raise gr.Error("No object detected")
else:
bbox = prompt
t0 = time.time()
mask = segmenter(img, bbox)
time_log.append(f"segment: {time.time() - t0}")
return mask, bbox, time_log
def process_bbox(prompts: dict[str, Any]) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
assert isinstance(img := prompts["image"], Image.Image)
assert isinstance(boxes := prompts["boxes"], list)
if len(boxes) == 1:
assert isinstance(box := boxes[0], dict)
bbox = tuple(box[k] for k in ["xmin", "ymin", "xmax", "ymax"])
else:
assert len(boxes) == 0
bbox = None
return _process(img, bbox)
def on_change_bbox(prompts: dict[str, Any] | None):
return gr.update(interactive=prompts is not None)
def process_prompt(img: Image.Image, prompt: str) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
return _process(img, prompt)
def on_change_prompt(img: Image.Image | None, prompt: str | None):
return gr.update(interactive=bool(img and prompt))
css = """
footer {
visibility: hidden;
}
"""
# ์คํ์ผ ์ ์ ์ถ๊ฐ
css = """
footer {visibility: hidden}
.container {max-width: 1200px; margin: auto; padding: 20px;}
.main-title {text-align: center; color: #2a2a2a; margin-bottom: 2em;}
.tabs {background: #f7f7f7; border-radius: 15px; padding: 20px;}
.input-column {background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);}
.output-column {background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);}
.custom-button {background: #2196F3; color: white; border: none; border-radius: 5px; padding: 10px 20px;}
.custom-button:hover {background: #1976D2;}
.example-region {margin-top: 2em; padding: 20px; background: #f0f0f0; border-radius: 10px;}
"""
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
gr.HTML("""
<div class="main-title">
<h1>๐จ Advanced Image Object Extractor</h1>
<p>Extract objects from images using text prompts or bounding boxes</p>
</div>
""")
with gr.Tabs() as tabs:
with gr.Tab("โจ Extract by Text", id="tab_prompt"):
with gr.Row(equal_height=True):
with gr.Column(scale=1, min_width=400):
gr.HTML("<h3>๐ฅ Input Section</h3>")
iimg = gr.Image(
type="pil",
label="Upload Image"
)
with gr.Group():
prompt = gr.Textbox(
label="๐ฏ Object to Extract",
placeholder="Enter what you want to extract..."
)
bg_prompt = gr.Textbox(
label="๐ผ๏ธ Background Generation Prompt (optional)",
placeholder="Describe the background you want..."
)
btn = gr.Button(
"๐ Process Image",
variant="primary",
interactive=False
)
with gr.Column(scale=1, min_width=400):
gr.HTML("<h3>๐ค Output Section</h3>")
oimg = ImageSlider(
label="Results Preview",
show_download_button=False
)
dlbt = gr.DownloadButton(
"๐พ Download Result",
interactive=False
)
with gr.Accordion("๐ Examples", open=False):
examples = [
["examples/text.jpg", "text"],
["examples/potted-plant.jpg", "potted plant"],
["examples/chair.jpg", "chair"],
["examples/black-lamp.jpg", "black lamp"],
]
ex = gr.Examples(
examples=examples,
inputs=[iimg, prompt],
outputs=[oimg, dlbt],
fn=process_prompt,
cache_examples=True
)
with gr.Tab("๐ Extract by Box", id="tab_bb"):
with gr.Row(equal_height=True):
with gr.Column(scale=1, min_width=400):
gr.HTML("<h3>๐ฅ Input Section</h3>")
annotator = image_annotator(
image_type="pil",
disable_edit_boxes=True,
show_download_button=False,
show_share_button=False,
single_box=True,
label="Draw Box Around Object"
)
btn_bb = gr.Button(
"โ๏ธ Extract Selection",
variant="primary",
interactive=False
)
with gr.Column(scale=1, min_width=400):
gr.HTML("<h3>๐ค Output Section</h3>")
oimg_bb = ImageSlider(
label="Results Preview",
show_download_button=False
)
dlbt_bb = gr.DownloadButton(
"๐พ Download Result",
interactive=False
)
with gr.Accordion("๐ Examples", open=False):
examples_bb = [
{
"image": "examples/text.jpg",
"boxes": [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}],
},
{
"image": "examples/potted-plant.jpg",
"boxes": [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}],
},
{
"image": "examples/chair.jpg",
"boxes": [{"xmin": 98, "ymin": 330, "xmax": 973, "ymax": 1468}],
},
{
"image": "examples/black-lamp.jpg",
"boxes": [{"xmin": 88, "ymin": 148, "xmax": 700, "ymax": 1414}],
},
]
ex_bb = gr.Examples(
examples=examples_bb,
inputs=[annotator],
outputs=[oimg_bb, dlbt_bb],
fn=process_bbox,
cache_examples=True
)
# Event handlers
btn.add(oimg)
for inp in [iimg, prompt]:
inp.change(
fn=on_change_prompt,
inputs=[iimg, prompt],
outputs=[btn],
)
btn.click(
fn=process_prompt,
inputs=[iimg, prompt, bg_prompt], # bg_prompt ์ถ๊ฐ
outputs=[oimg, dlbt],
api_name=False,
)
btn_bb.add(oimg_bb)
annotator.change(
fn=on_change_bbox,
inputs=[annotator],
outputs=[btn_bb],
)
btn_bb.click(
fn=process_bbox,
inputs=[annotator],
outputs=[oimg_bb, dlbt_bb],
api_name=False,
)
# CSS ์คํ์ผ ์ ์
css = """
footer {display: none}
.main-title {
text-align: center;
margin: 2em 0;
}
.main-title h1 {
color: #2196F3;
font-size: 2.5em;
}
.container {
max-width: 1200px;
margin: auto;
padding: 20px;
}
"""
# Launch settings
demo.queue(max_size=30, api_open=False)
demo.launch(
show_api=False,
share=False,
server_name="0.0.0.0",
server_port=7860,
show_error=True
)
# Launch settings
demo.queue(max_size=30, api_open=False)
demo.launch(
show_api=False,
share=False,
server_name="0.0.0.0",
server_port=7860,
show_error=True
)
|