ginipick commited on
Commit
6f3a0c2
β€’
1 Parent(s): e952798

Create src/app.py

Browse files
Files changed (1) hide show
  1. src/app.py +453 -0
src/app.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import time
3
+ from collections.abc import Sequence
4
+ from typing import Any, cast
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import pillow_heif
9
+ import spaces
10
+ import torch
11
+ from gradio_image_annotation import image_annotator
12
+ from gradio_imageslider import ImageSlider
13
+ from PIL import Image
14
+ from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
15
+ from refiners.fluxion.utils import no_grad
16
+ from refiners.solutions import BoxSegmenter
17
+ from transformers import GroundingDinoForObjectDetection, GroundingDinoProcessor
18
+
19
+ import spaces
20
+ import argparse
21
+ import os
22
+ from os import path
23
+ import shutil
24
+ from datetime import datetime
25
+ from safetensors.torch import load_file
26
+ from huggingface_hub import hf_hub_download
27
+ import gradio as gr
28
+ from diffusers import FluxPipeline
29
+ from PIL import Image
30
+ from huggingface_hub import login
31
+
32
+ # HF 토큰 인증 처리
33
+ HF_TOKEN = os.getenv("HF_TOKEN")
34
+ if HF_TOKEN is None:
35
+ raise ValueError("Please set the HF_TOKEN environment variable")
36
+
37
+ try:
38
+ login(token=HF_TOKEN)
39
+ except Exception as e:
40
+ raise ValueError(f"Failed to login to Hugging Face: {str(e)}")
41
+
42
+ # FLUX νŒŒμ΄ν”„λΌμΈ μ΄ˆκΈ°ν™” μˆ˜μ •
43
+ def initialize_pipeline():
44
+ try:
45
+ pipe = FluxPipeline.from_pretrained(
46
+ "black-forest-labs/FLUX.1-dev",
47
+ torch_dtype=torch.bfloat16,
48
+ use_auth_token=HF_TOKEN
49
+ )
50
+ pipe.load_lora_weights(
51
+ hf_hub_download(
52
+ "ByteDance/Hyper-SD",
53
+ "Hyper-FLUX.1-dev-8steps-lora.safetensors",
54
+ use_auth_token=HF_TOKEN
55
+ )
56
+ )
57
+ pipe.fuse_lora(lora_scale=0.125)
58
+ pipe.to(device="cuda", dtype=torch.bfloat16)
59
+ return pipe
60
+ except Exception as e:
61
+ raise ValueError(f"Failed to initialize pipeline: {str(e)}")
62
+ # νŒŒμ΄ν”„λΌμΈ μ΄ˆκΈ°ν™”
63
+ try:
64
+ pipe = initialize_pipeline()
65
+ except Exception as e:
66
+ raise RuntimeError(f"Failed to setup the model: {str(e)}")
67
+
68
+ BoundingBox = tuple[int, int, int, int]
69
+
70
+ pillow_heif.register_heif_opener()
71
+ pillow_heif.register_avif_opener()
72
+
73
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
74
+
75
+ # weird dance because ZeroGPU
76
+ segmenter = BoxSegmenter(device="cpu")
77
+ segmenter.device = device
78
+ segmenter.model = segmenter.model.to(device=segmenter.device)
79
+
80
+ gd_model_path = "IDEA-Research/grounding-dino-base"
81
+ gd_processor = GroundingDinoProcessor.from_pretrained(gd_model_path)
82
+ gd_model = GroundingDinoForObjectDetection.from_pretrained(gd_model_path, torch_dtype=torch.float32)
83
+ gd_model = gd_model.to(device=device) # type: ignore
84
+ assert isinstance(gd_model, GroundingDinoForObjectDetection)
85
+
86
+ # FLUX νŒŒμ΄ν”„λΌμΈ μ΄ˆκΈ°ν™” μ½”λ“œ μΆ”κ°€
87
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
88
+ pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
89
+ pipe.fuse_lora(lora_scale=0.125)
90
+ pipe.to(device="cuda", dtype=torch.bfloat16)
91
+
92
+ def generate_background(prompt: str, width: int, height: int) -> Image.Image:
93
+ """λ°°κ²½ 이미지 생성 ν•¨μˆ˜"""
94
+ try:
95
+ with timer("Background generation"):
96
+ image = pipe(
97
+ prompt=prompt,
98
+ width=width,
99
+ height=height,
100
+ num_inference_steps=8,
101
+ guidance_scale=4.0,
102
+ ).images[0]
103
+ return image
104
+ except Exception as e:
105
+ raise gr.Error(f"Background generation failed: {str(e)}") # κ΄„ν˜Έ λ‹«κΈ° μˆ˜μ •
106
+
107
+
108
+ def combine_with_background(foreground: Image.Image, background: Image.Image) -> Image.Image:
109
+ """μ „κ²½κ³Ό λ°°κ²½ ν•©μ„± ν•¨μˆ˜"""
110
+ background = background.resize(foreground.size)
111
+ return Image.alpha_composite(background.convert('RGBA'), foreground)
112
+
113
+ def _process(
114
+ img: Image.Image,
115
+ prompt: str | BoundingBox | None,
116
+ bg_prompt: str | None,
117
+ ) -> tuple[tuple[Image.Image, Image.Image, Image.Image], gr.DownloadButton]:
118
+ try:
119
+ # κΈ°μ‘΄ 객체 μΆ”μΆœ 둜직
120
+ mask, bbox, time_log = _gpu_process(img, prompt)
121
+ masked_alpha = apply_mask(img, mask, defringe=True)
122
+
123
+ # λ°°κ²½ 생성 및 ν•©μ„±
124
+ if bg_prompt:
125
+ background = generate_background(bg_prompt, img.width, img.height)
126
+ combined = combine_with_background(masked_alpha, background)
127
+ else:
128
+ combined = Image.alpha_composite(Image.new("RGBA", masked_alpha.size, "white"), masked_alpha)
129
+
130
+ # μ €μž₯ 둜직
131
+ thresholded = mask.point(lambda p: 255 if p > 10 else 0)
132
+ bbox = thresholded.getbbox()
133
+ to_dl = masked_alpha.crop(bbox)
134
+
135
+ temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
136
+ to_dl.save(temp, format="PNG")
137
+ temp.close()
138
+
139
+ return (img, combined, masked_alpha), gr.DownloadButton(value=temp.name, interactive=True)
140
+ except Exception as e:
141
+ raise gr.Error(f"Processing failed: {str(e)}")
142
+
143
+ def bbox_union(bboxes: Sequence[list[int]]) -> BoundingBox | None:
144
+ if not bboxes:
145
+ return None
146
+ for bbox in bboxes:
147
+ assert len(bbox) == 4
148
+ assert all(isinstance(x, int) for x in bbox)
149
+ return (
150
+ min(bbox[0] for bbox in bboxes),
151
+ min(bbox[1] for bbox in bboxes),
152
+ max(bbox[2] for bbox in bboxes),
153
+ max(bbox[3] for bbox in bboxes),
154
+ )
155
+
156
+
157
+ def corners_to_pixels_format(bboxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
158
+ x1, y1, x2, y2 = bboxes.round().to(torch.int32).unbind(-1)
159
+ return torch.stack((x1.clamp_(0, width), y1.clamp_(0, height), x2.clamp_(0, width), y2.clamp_(0, height)), dim=-1)
160
+
161
+
162
+ def gd_detect(img: Image.Image, prompt: str) -> BoundingBox | None:
163
+ assert isinstance(gd_processor, GroundingDinoProcessor)
164
+
165
+ # Grounding Dino expects a dot after each category.
166
+ inputs = gd_processor(images=img, text=f"{prompt}.", return_tensors="pt").to(device=device)
167
+
168
+ with no_grad():
169
+ outputs = gd_model(**inputs)
170
+ width, height = img.size
171
+ results: dict[str, Any] = gd_processor.post_process_grounded_object_detection(
172
+ outputs,
173
+ inputs["input_ids"],
174
+ target_sizes=[(height, width)],
175
+ )[0]
176
+ assert "boxes" in results and isinstance(results["boxes"], torch.Tensor)
177
+
178
+ bboxes = corners_to_pixels_format(results["boxes"].cpu(), width, height)
179
+ return bbox_union(bboxes.numpy().tolist())
180
+
181
+
182
+ def apply_mask(
183
+ img: Image.Image,
184
+ mask_img: Image.Image,
185
+ defringe: bool = True,
186
+ ) -> Image.Image:
187
+ assert img.size == mask_img.size
188
+ img = img.convert("RGB")
189
+ mask_img = mask_img.convert("L")
190
+
191
+ if defringe:
192
+ # Mitigate edge halo effects via color decontamination
193
+ rgb, alpha = np.asarray(img) / 255.0, np.asarray(mask_img) / 255.0
194
+ foreground = cast(np.ndarray[Any, np.dtype[np.uint8]], estimate_foreground_ml(rgb, alpha))
195
+ img = Image.fromarray((foreground * 255).astype("uint8"))
196
+
197
+ result = Image.new("RGBA", img.size)
198
+ result.paste(img, (0, 0), mask_img)
199
+ return result
200
+
201
+
202
+ @spaces.GPU
203
+ def _gpu_process(
204
+ img: Image.Image,
205
+ prompt: str | BoundingBox | None,
206
+ ) -> tuple[Image.Image, BoundingBox | None, list[str]]:
207
+ # Because of ZeroGPU shenanigans, we need a *single* function with the
208
+ # `spaces.GPU` decorator that *does not* contain postprocessing.
209
+
210
+ time_log: list[str] = []
211
+
212
+ if isinstance(prompt, str):
213
+ t0 = time.time()
214
+ bbox = gd_detect(img, prompt)
215
+ time_log.append(f"detect: {time.time() - t0}")
216
+ if not bbox:
217
+ print(time_log[0])
218
+ raise gr.Error("No object detected")
219
+ else:
220
+ bbox = prompt
221
+
222
+ t0 = time.time()
223
+ mask = segmenter(img, bbox)
224
+ time_log.append(f"segment: {time.time() - t0}")
225
+
226
+ return mask, bbox, time_log
227
+
228
+
229
+
230
+
231
+
232
+ def process_bbox(prompts: dict[str, Any]) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
233
+ assert isinstance(img := prompts["image"], Image.Image)
234
+ assert isinstance(boxes := prompts["boxes"], list)
235
+ if len(boxes) == 1:
236
+ assert isinstance(box := boxes[0], dict)
237
+ bbox = tuple(box[k] for k in ["xmin", "ymin", "xmax", "ymax"])
238
+ else:
239
+ assert len(boxes) == 0
240
+ bbox = None
241
+ return _process(img, bbox)
242
+
243
+
244
+ def on_change_bbox(prompts: dict[str, Any] | None):
245
+ return gr.update(interactive=prompts is not None)
246
+
247
+
248
+ def process_prompt(img: Image.Image, prompt: str) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
249
+ return _process(img, prompt)
250
+
251
+
252
+ def on_change_prompt(img: Image.Image | None, prompt: str | None):
253
+ return gr.update(interactive=bool(img and prompt))
254
+
255
+
256
+ css = """
257
+ footer {
258
+ visibility: hidden;
259
+ }
260
+ """
261
+
262
+ # μŠ€νƒ€μΌ μ •μ˜ μΆ”κ°€
263
+ css = """
264
+ footer {visibility: hidden}
265
+ .container {max-width: 1200px; margin: auto; padding: 20px;}
266
+ .main-title {text-align: center; color: #2a2a2a; margin-bottom: 2em;}
267
+ .tabs {background: #f7f7f7; border-radius: 15px; padding: 20px;}
268
+ .input-column {background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);}
269
+ .output-column {background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);}
270
+ .custom-button {background: #2196F3; color: white; border: none; border-radius: 5px; padding: 10px 20px;}
271
+ .custom-button:hover {background: #1976D2;}
272
+ .example-region {margin-top: 2em; padding: 20px; background: #f0f0f0; border-radius: 10px;}
273
+ """
274
+
275
+ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
276
+ gr.HTML("""
277
+ <div class="main-title">
278
+ <h1>🎨 Advanced Image Object Extractor</h1>
279
+ <p>Extract objects from images using text prompts or bounding boxes</p>
280
+ </div>
281
+ """)
282
+
283
+ with gr.Tabs() as tabs:
284
+ with gr.Tab("✨ Extract by Text", id="tab_prompt"):
285
+ with gr.Row(equal_height=True):
286
+ with gr.Column(scale=1, min_width=400):
287
+ gr.HTML("<h3>πŸ“₯ Input Section</h3>")
288
+ iimg = gr.Image(
289
+ type="pil",
290
+ label="Upload Image"
291
+ )
292
+ with gr.Group():
293
+ prompt = gr.Textbox(
294
+ label="🎯 Object to Extract",
295
+ placeholder="Enter what you want to extract..."
296
+ )
297
+ bg_prompt = gr.Textbox(
298
+ label="πŸ–ΌοΈ Background Generation Prompt (optional)",
299
+ placeholder="Describe the background you want..."
300
+ )
301
+ btn = gr.Button(
302
+ "πŸš€ Process Image",
303
+ variant="primary",
304
+ interactive=False
305
+ )
306
+
307
+ with gr.Column(scale=1, min_width=400):
308
+ gr.HTML("<h3>πŸ“€ Output Section</h3>")
309
+ oimg = ImageSlider(
310
+ label="Results Preview",
311
+ show_download_button=False
312
+ )
313
+ dlbt = gr.DownloadButton(
314
+ "πŸ’Ύ Download Result",
315
+ interactive=False
316
+ )
317
+
318
+ with gr.Accordion("πŸ“š Examples", open=False):
319
+ examples = [
320
+ ["examples/text.jpg", "text"],
321
+ ["examples/potted-plant.jpg", "potted plant"],
322
+ ["examples/chair.jpg", "chair"],
323
+ ["examples/black-lamp.jpg", "black lamp"],
324
+ ]
325
+ ex = gr.Examples(
326
+ examples=examples,
327
+ inputs=[iimg, prompt],
328
+ outputs=[oimg, dlbt],
329
+ fn=process_prompt,
330
+ cache_examples=True
331
+ )
332
+
333
+ with gr.Tab("πŸ“ Extract by Box", id="tab_bb"):
334
+ with gr.Row(equal_height=True):
335
+ with gr.Column(scale=1, min_width=400):
336
+ gr.HTML("<h3>πŸ“₯ Input Section</h3>")
337
+ annotator = image_annotator(
338
+ image_type="pil",
339
+ disable_edit_boxes=True,
340
+ show_download_button=False,
341
+ show_share_button=False,
342
+ single_box=True,
343
+ label="Draw Box Around Object"
344
+ )
345
+ btn_bb = gr.Button(
346
+ "βœ‚οΈ Extract Selection",
347
+ variant="primary",
348
+ interactive=False
349
+ )
350
+
351
+ with gr.Column(scale=1, min_width=400):
352
+ gr.HTML("<h3>πŸ“€ Output Section</h3>")
353
+ oimg_bb = ImageSlider(
354
+ label="Results Preview",
355
+ show_download_button=False
356
+ )
357
+ dlbt_bb = gr.DownloadButton(
358
+ "πŸ’Ύ Download Result",
359
+ interactive=False
360
+ )
361
+
362
+ with gr.Accordion("πŸ“š Examples", open=False):
363
+ examples_bb = [
364
+ {
365
+ "image": "examples/text.jpg",
366
+ "boxes": [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}],
367
+ },
368
+ {
369
+ "image": "examples/potted-plant.jpg",
370
+ "boxes": [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}],
371
+ },
372
+ {
373
+ "image": "examples/chair.jpg",
374
+ "boxes": [{"xmin": 98, "ymin": 330, "xmax": 973, "ymax": 1468}],
375
+ },
376
+ {
377
+ "image": "examples/black-lamp.jpg",
378
+ "boxes": [{"xmin": 88, "ymin": 148, "xmax": 700, "ymax": 1414}],
379
+ },
380
+ ]
381
+ ex_bb = gr.Examples(
382
+ examples=examples_bb,
383
+ inputs=[annotator],
384
+ outputs=[oimg_bb, dlbt_bb],
385
+ fn=process_bbox,
386
+ cache_examples=True
387
+ )
388
+
389
+ # Event handlers
390
+ btn.add(oimg)
391
+ for inp in [iimg, prompt]:
392
+ inp.change(
393
+ fn=on_change_prompt,
394
+ inputs=[iimg, prompt],
395
+ outputs=[btn],
396
+ )
397
+ btn.click(
398
+ fn=process_prompt,
399
+ inputs=[iimg, prompt, bg_prompt], # bg_prompt μΆ”κ°€
400
+ outputs=[oimg, dlbt],
401
+ api_name=False,
402
+ )
403
+
404
+ btn_bb.add(oimg_bb)
405
+ annotator.change(
406
+ fn=on_change_bbox,
407
+ inputs=[annotator],
408
+ outputs=[btn_bb],
409
+ )
410
+ btn_bb.click(
411
+ fn=process_bbox,
412
+ inputs=[annotator],
413
+ outputs=[oimg_bb, dlbt_bb],
414
+ api_name=False,
415
+ )
416
+
417
+ # CSS μŠ€νƒ€μΌ μ •μ˜
418
+ css = """
419
+ footer {display: none}
420
+ .main-title {
421
+ text-align: center;
422
+ margin: 2em 0;
423
+ }
424
+ .main-title h1 {
425
+ color: #2196F3;
426
+ font-size: 2.5em;
427
+ }
428
+ .container {
429
+ max-width: 1200px;
430
+ margin: auto;
431
+ padding: 20px;
432
+ }
433
+ """
434
+
435
+ # Launch settings
436
+ demo.queue(max_size=30, api_open=False)
437
+ demo.launch(
438
+ show_api=False,
439
+ share=False,
440
+ server_name="0.0.0.0",
441
+ server_port=7860,
442
+ show_error=True
443
+ )
444
+
445
+ # Launch settings
446
+ demo.queue(max_size=30, api_open=False)
447
+ demo.launch(
448
+ show_api=False,
449
+ share=False,
450
+ server_name="0.0.0.0",
451
+ server_port=7860,
452
+ show_error=True
453
+ )