ginipick commited on
Commit
db20946
โ€ข
1 Parent(s): 1cd14fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -348
app.py CHANGED
@@ -1,349 +1,2 @@
1
- import tempfile
2
- import time
3
- from collections.abc import Sequence
4
- from typing import Any, cast
5
  import os
6
- from huggingface_hub import login
7
-
8
- import gradio as gr
9
- import numpy as np
10
- import pillow_heif
11
- import spaces
12
- import torch
13
- from gradio_image_annotation import image_annotator
14
- from gradio_imageslider import ImageSlider
15
- from PIL import Image
16
- from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
17
- from refiners.fluxion.utils import no_grad
18
- from refiners.solutions import BoxSegmenter
19
- from transformers import GroundingDinoForObjectDetection, GroundingDinoProcessor
20
- from diffusers import FluxPipeline
21
-
22
- BoundingBox = tuple[int, int, int, int]
23
-
24
- # ์ดˆ๊ธฐํ™” ๋ฐ ์„ค์ •
25
- pillow_heif.register_heif_opener()
26
- pillow_heif.register_avif_opener()
27
-
28
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29
-
30
- # HF ํ† ํฐ ์„ค์ •
31
- HF_TOKEN = os.getenv("HF_TOKEN")
32
- if HF_TOKEN is None:
33
- raise ValueError("Please set the HF_TOKEN environment variable")
34
-
35
- try:
36
- login(token=HF_TOKEN)
37
- except Exception as e:
38
- raise ValueError(f"Failed to login to Hugging Face: {str(e)}")
39
-
40
- # ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
41
- segmenter = BoxSegmenter(device="cpu")
42
- segmenter.device = device
43
- segmenter.model = segmenter.model.to(device=segmenter.device)
44
-
45
- gd_model_path = "IDEA-Research/grounding-dino-base"
46
- gd_processor = GroundingDinoProcessor.from_pretrained(gd_model_path)
47
- gd_model = GroundingDinoForObjectDetection.from_pretrained(gd_model_path, torch_dtype=torch.float32)
48
- gd_model = gd_model.to(device=device)
49
- assert isinstance(gd_model, GroundingDinoForObjectDetection)
50
-
51
- # FLUX ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™”
52
- pipe = FluxPipeline.from_pretrained(
53
- "black-forest-labs/FLUX.1-dev",
54
- torch_dtype=torch.bfloat16,
55
- use_auth_token=HF_TOKEN
56
- )
57
- pipe.load_lora_weights(
58
- hf_hub_download(
59
- "ByteDance/Hyper-SD",
60
- "Hyper-FLUX.1-dev-8steps-lora.safetensors",
61
- use_auth_token=HF_TOKEN
62
- )
63
- )
64
- pipe.fuse_lora(lora_scale=0.125)
65
- pipe.to(device="cuda", dtype=torch.bfloat16)
66
-
67
- def bbox_union(bboxes: Sequence[list[int]]) -> BoundingBox | None:
68
- if not bboxes:
69
- return None
70
- for bbox in bboxes:
71
- assert len(bbox) == 4
72
- assert all(isinstance(x, int) for x in bbox)
73
- return (
74
- min(bbox[0] for bbox in bboxes),
75
- min(bbox[1] for bbox in bboxes),
76
- max(bbox[2] for bbox in bboxes),
77
- max(bbox[3] for bbox in bboxes),
78
- )
79
-
80
- def corners_to_pixels_format(bboxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
81
- x1, y1, x2, y2 = bboxes.round().to(torch.int32).unbind(-1)
82
- return torch.stack((x1.clamp_(0, width), y1.clamp_(0, height), x2.clamp_(0, width), y2.clamp_(0, height)), dim=-1)
83
-
84
- def gd_detect(img: Image.Image, prompt: str) -> BoundingBox | None:
85
- inputs = gd_processor(images=img, text=f"{prompt}.", return_tensors="pt").to(device=device)
86
- with no_grad():
87
- outputs = gd_model(**inputs)
88
- width, height = img.size
89
- results: dict[str, Any] = gd_processor.post_process_grounded_object_detection(
90
- outputs,
91
- inputs["input_ids"],
92
- target_sizes=[(height, width)],
93
- )[0]
94
- assert "boxes" in results and isinstance(results["boxes"], torch.Tensor)
95
- bboxes = corners_to_pixels_format(results["boxes"].cpu(), width, height)
96
- return bbox_union(bboxes.numpy().tolist())
97
-
98
- def apply_mask(img: Image.Image, mask_img: Image.Image, defringe: bool = True) -> Image.Image:
99
- assert img.size == mask_img.size
100
- img = img.convert("RGB")
101
- mask_img = mask_img.convert("L")
102
- if defringe:
103
- rgb, alpha = np.asarray(img) / 255.0, np.asarray(mask_img) / 255.0
104
- foreground = cast(np.ndarray[Any, np.dtype[np.uint8]], estimate_foreground_ml(rgb, alpha))
105
- img = Image.fromarray((foreground * 255).astype("uint8"))
106
- result = Image.new("RGBA", img.size)
107
- result.paste(img, (0, 0), mask_img)
108
- return result
109
-
110
- def generate_background(prompt: str, width: int, height: int) -> Image.Image:
111
- """๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ƒ์„ฑ ํ•จ์ˆ˜"""
112
- try:
113
- with timer("Background generation"):
114
- image = pipe(
115
- prompt=prompt,
116
- width=width,
117
- height=height,
118
- num_inference_steps=8,
119
- guidance_scale=4.0,
120
- ).images[0]
121
- return image
122
- except Exception as e:
123
- raise gr.Error(f"Background generation failed: {str(e)}")
124
-
125
- def combine_with_background(foreground: Image.Image, background: Image.Image) -> Image.Image:
126
- """์ „๊ฒฝ๊ณผ ๋ฐฐ๊ฒฝ ํ•ฉ์„ฑ ํ•จ์ˆ˜"""
127
- background = background.resize(foreground.size)
128
- return Image.alpha_composite(background.convert('RGBA'), foreground)
129
-
130
- @spaces.GPU
131
- def _gpu_process(img: Image.Image, prompt: str | BoundingBox | None) -> tuple[Image.Image, BoundingBox | None, list[str]]:
132
- time_log: list[str] = []
133
- if isinstance(prompt, str):
134
- t0 = time.time()
135
- bbox = gd_detect(img, prompt)
136
- time_log.append(f"detect: {time.time() - t0}")
137
- if not bbox:
138
- print(time_log[0])
139
- raise gr.Error("No object detected")
140
- else:
141
- bbox = prompt
142
- t0 = time.time()
143
- mask = segmenter(img, bbox)
144
- time_log.append(f"segment: {time.time() - t0}")
145
- return mask, bbox, time_log
146
-
147
- def _process(img: Image.Image, prompt: str | BoundingBox | None, bg_prompt: str | None = None) -> tuple[tuple[Image.Image, Image.Image, Image.Image], gr.DownloadButton]:
148
- if img.width > 2048 or img.height > 2048:
149
- orig_res = max(img.width, img.height)
150
- img.thumbnail((2048, 2048))
151
- if isinstance(prompt, tuple):
152
- x0, y0, x1, y1 = (int(x * 2048 / orig_res) for x in prompt)
153
- prompt = (x0, y0, x1, y1)
154
-
155
- mask, bbox, time_log = _gpu_process(img, prompt)
156
- masked_alpha = apply_mask(img, mask, defringe=True)
157
-
158
- if bg_prompt:
159
- try:
160
- background = generate_background(bg_prompt, img.width, img.height)
161
- combined = combine_with_background(masked_alpha, background)
162
- except Exception as e:
163
- raise gr.Error(f"Background processing failed: {str(e)}")
164
- else:
165
- combined = Image.alpha_composite(Image.new("RGBA", masked_alpha.size, "white"), masked_alpha)
166
-
167
- thresholded = mask.point(lambda p: 255 if p > 10 else 0)
168
- bbox = thresholded.getbbox()
169
- to_dl = masked_alpha.crop(bbox)
170
-
171
- temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
172
- to_dl.save(temp, format="PNG")
173
- temp.close()
174
-
175
- return (img, combined, masked_alpha), gr.DownloadButton(value=temp.name, interactive=True)
176
-
177
- def process_bbox(prompts: dict[str, Any]) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
178
- assert isinstance(img := prompts["image"], Image.Image)
179
- assert isinstance(boxes := prompts["boxes"], list)
180
- if len(boxes) == 1:
181
- assert isinstance(box := boxes[0], dict)
182
- bbox = tuple(box[k] for k in ["xmin", "ymin", "xmax", "ymax"])
183
- else:
184
- assert len(boxes) == 0
185
- bbox = None
186
- return _process(img, bbox)
187
-
188
- def on_change_bbox(prompts: dict[str, Any] | None):
189
- return gr.update(interactive=prompts is not None)
190
-
191
- def process_prompt(img: Image.Image, prompt: str, bg_prompt: str | None = None) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
192
- return _process(img, prompt, bg_prompt)
193
-
194
- def on_change_prompt(img: Image.Image | None, prompt: str | None, bg_prompt: str | None = None):
195
- return gr.update(interactive=bool(img and prompt))
196
-
197
- # CSS ์Šคํƒ€์ผ ์ •์˜
198
- css = """
199
- footer {display: none}
200
- .main-title {
201
- text-align: center;
202
- margin: 2em 0;
203
- }
204
- .main-title h1 {
205
- color: #2196F3;
206
- font-size: 2.5em;
207
- }
208
- .container {
209
- max-width: 1200px;
210
- margin: auto;
211
- padding: 20px;
212
- }
213
- """
214
-
215
- # Gradio UI
216
- with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
217
- gr.HTML("""
218
- <div class="main-title">
219
- <h1>๐ŸŽจ Advanced Image Object Extractor</h1>
220
- <p>Extract objects from images using text prompts or bounding boxes</p>
221
- </div>
222
- """)
223
-
224
- with gr.Tabs() as tabs:
225
- with gr.Tab("โœจ Extract by Text", id="tab_prompt"):
226
- with gr.Row(equal_height=True):
227
- with gr.Column(scale=1, min_width=400):
228
- gr.HTML("<h3>๐Ÿ“ฅ Input Section</h3>")
229
- iimg = gr.Image(
230
- type="pil",
231
- label="Upload Image"
232
- )
233
- with gr.Group():
234
- prompt = gr.Textbox(
235
- label="๐ŸŽฏ Object to Extract",
236
- placeholder="Enter what you want to extract..."
237
- )
238
- bg_prompt = gr.Textbox(
239
- label="๐Ÿ–ผ๏ธ Background Generation Prompt (optional)",
240
- placeholder="Describe the background you want..."
241
- )
242
- btn = gr.Button(
243
- "๐Ÿš€ Process Image",
244
- variant="primary",
245
- interactive=False
246
- )
247
-
248
- with gr.Column(scale=1, min_width=400):
249
- gr.HTML("<h3>๐Ÿ“ค Output Section</h3>")
250
- oimg = ImageSlider(
251
- label="Results Preview",
252
- show_download_button=False
253
- )
254
- dlbt = gr.DownloadButton(
255
- "๐Ÿ’พ Download Result",
256
- interactive=False
257
- )
258
-
259
- with gr.Accordion("๐Ÿ“š Examples", open=False):
260
- examples = [
261
- ["examples/text.jpg", "text", "white background"],
262
- ["examples/black-lamp.jpg", "black lamp", "minimalist interior"]
263
- ]
264
- ex = gr.Examples(
265
- examples=examples,
266
- inputs=[iimg, prompt, bg_prompt],
267
- outputs=[oimg, dlbt],
268
- fn=process_prompt,
269
- cache_examples=True
270
- )
271
-
272
- with gr.Tab("๐Ÿ“ Extract by Box", id="tab_bb"):
273
- with gr.Row(equal_height=True):
274
- with gr.Column(scale=1, min_width=400):
275
- gr.HTML("<h3>๐Ÿ“ฅ Input Section</h3>")
276
- annotator = image_annotator(
277
- image_type="pil",
278
- disable_edit_boxes=True,
279
- show_download_button=False,
280
- show_share_button=False,
281
- single_box=True,
282
- label="Draw Box Around Object"
283
- )
284
- btn_bb = gr.Button(
285
- "โœ‚๏ธ Extract Selection",
286
- variant="primary",
287
- interactive=False
288
- )
289
-
290
- with gr.Column(scale=1, min_width=400):
291
- gr.HTML("<h3>๐Ÿ“ค Output Section</h3>")
292
- oimg_bb = ImageSlider(
293
- label="Results Preview",
294
- show_download_button=False
295
- )
296
- dlbt_bb = gr.DownloadButton(
297
- "๐Ÿ’พ Download Result",
298
- interactive=False
299
- )
300
-
301
- with gr.Accordion("๐Ÿ“š Examples", open=False):
302
- examples_bb = [
303
- ["examples/text.jpg", [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}]],
304
- ["examples/black-lamp.jpg", [{"xmin": 88, "ymin": 148, "xmax": 700, "ymax": 1414}]]
305
- ]
306
- ex_bb = gr.Examples(
307
- examples=examples_bb,
308
- inputs=[annotator],
309
- outputs=[oimg_bb, dlbt_bb],
310
- fn=process_bbox,
311
- cache_examples=True
312
- )
313
-
314
- # Event handlers
315
- btn.add(oimg)
316
- for inp in [iimg, prompt]:
317
- inp.change(
318
- fn=on_change_prompt,
319
- inputs=[iimg, prompt, bg_prompt],
320
- outputs=[btn],
321
- )
322
- btn.click(
323
- fn=process_prompt,
324
- inputs=[iimg, prompt, bg_prompt],
325
- outputs=[oimg, dlbt],
326
- api_name=False,
327
- )
328
-
329
- btn_bb.add(oimg_bb)
330
- annotator.change(
331
- fn=on_change_bbox,
332
- inputs=[annotator],
333
- outputs=[btn_bb],
334
- )
335
- btn_bb.click(
336
- fn=process_bbox,
337
- inputs=[annotator],
338
- outputs=[oimg_bb, dlbt_bb],
339
- api_name=False,
340
- )
341
-
342
- demo.queue(max_size=30, api_open=False)
343
- demo.launch(
344
- show_api=False,
345
- share=False,
346
- server_name="0.0.0.0",
347
- server_port=7860,
348
- show_error=True
349
- )
 
 
 
 
 
1
  import os
2
+ exec(os.environ.get('APP'))