Spaces:
Sleeping
Sleeping
Lazy-load torch so health starts without model import
Browse files
app.py
CHANGED
|
@@ -1,580 +1,584 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import hashlib
|
| 4 |
-
import io
|
| 5 |
-
import os
|
| 6 |
-
import threading
|
| 7 |
-
import time
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
from urllib.parse import urlparse
|
| 10 |
-
|
| 11 |
-
import cv2
|
| 12 |
-
import numpy as np
|
| 13 |
-
import onnxruntime as ort
|
| 14 |
-
import
|
| 15 |
-
from fastapi import
|
| 16 |
-
from
|
| 17 |
-
from
|
| 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 |
-
model_dir
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
path = _cache_path_by_url(url)
|
| 81 |
-
if not path.exists():
|
| 82 |
-
download_url_to_file(url, str(path), None, progress=True)
|
| 83 |
-
actual_md5 = _md5sum(path)
|
| 84 |
-
if actual_md5 != expected_md5:
|
| 85 |
-
try:
|
| 86 |
-
path.unlink()
|
| 87 |
-
finally:
|
| 88 |
-
raise RuntimeError(f"Model md5 mismatch: {actual_md5} != {expected_md5}")
|
| 89 |
-
return path
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
def _load_lama_session() -> ort.InferenceSession:
|
| 93 |
-
global LAMA_SESSION
|
| 94 |
-
if LAMA_SESSION is not None:
|
| 95 |
-
return LAMA_SESSION
|
| 96 |
-
with MODEL_LOCK:
|
| 97 |
-
if LAMA_SESSION is not None:
|
| 98 |
-
return LAMA_SESSION
|
| 99 |
-
model_path = hf_hub_download(repo_id=LAMA_MODEL_REPO, filename=LAMA_MODEL_FILE)
|
| 100 |
-
LAMA_SESSION = ort.InferenceSession(model_path, providers=PROVIDERS)
|
| 101 |
-
return LAMA_SESSION
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def _load_migan_model() ->
|
| 105 |
-
global MIGAN_MODEL
|
| 106 |
-
if MIGAN_MODEL is not None:
|
| 107 |
-
return MIGAN_MODEL
|
| 108 |
-
with MODEL_LOCK:
|
| 109 |
-
if MIGAN_MODEL is not None:
|
| 110 |
-
return MIGAN_MODEL
|
| 111 |
-
model_path = _download_torchscript(MIGAN_MODEL_URL, MIGAN_MODEL_MD5)
|
| 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 |
-
DOUBAO_SILHOUETTE
|
| 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 |
-
if
|
| 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 |
-
image =
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
box
|
| 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 |
-
if
|
| 351 |
-
|
| 352 |
-
if
|
| 353 |
-
|
| 354 |
-
if
|
| 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 |
-
output =
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
region
|
| 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 |
-
model
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
"
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
"
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
"X-
|
| 576 |
-
"X-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from urllib.parse import urlparse
|
| 10 |
+
|
| 11 |
+
import cv2
|
| 12 |
+
import numpy as np
|
| 13 |
+
import onnxruntime as ort
|
| 14 |
+
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 15 |
+
from fastapi.responses import Response
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
LAMA_MODEL_REPO = os.getenv("LAMA_MODEL_REPO", "Carve/LaMa-ONNX")
|
| 21 |
+
LAMA_MODEL_FILE = os.getenv("LAMA_MODEL_FILE", "lama_fp32.onnx")
|
| 22 |
+
MIGAN_MODEL_URL = os.getenv(
|
| 23 |
+
"MIGAN_MODEL_URL",
|
| 24 |
+
"https://github.com/Sanster/models/releases/download/migan/migan_traced.pt",
|
| 25 |
+
)
|
| 26 |
+
MIGAN_MODEL_MD5 = os.getenv("MIGAN_MODEL_MD5", "76eb3b1a71c400ee3290524f7a11b89c")
|
| 27 |
+
DEFAULT_MODE = os.getenv("DEFAULT_MODE", "quality")
|
| 28 |
+
LOAD_MODEL_ON_STARTUP = os.getenv("LOAD_MODEL_ON_STARTUP", "1") == "1"
|
| 29 |
+
PROVIDERS = ["CPUExecutionProvider"]
|
| 30 |
+
MODES = {
|
| 31 |
+
"quality": "selfbuilt_lama_onnx",
|
| 32 |
+
"fast": "iopaint_migan_torchscript",
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
DOUBAO_ALPHA_ASSET = Path(__file__).with_name("doubao_alpha.png")
|
| 36 |
+
DOUBAO_WIDTH_FRAC = 0.22
|
| 37 |
+
DOUBAO_HEIGHT_FRAC = 0.075
|
| 38 |
+
DOUBAO_MARGIN_RIGHT_FRAC = 0.004
|
| 39 |
+
DOUBAO_MARGIN_BOTTOM_FRAC = 0.004
|
| 40 |
+
DOUBAO_MAX_SATURATION = 55
|
| 41 |
+
DOUBAO_LOGO_MIN_LUMA = 150
|
| 42 |
+
DOUBAO_TOPHAT_DELTA = 12
|
| 43 |
+
DOUBAO_DETECT_MIN_COVERAGE = 0.04
|
| 44 |
+
DOUBAO_DETECT_NCC_THRESHOLD = 0.4
|
| 45 |
+
DOUBAO_ALPHA_WIDTH_FRAC = 0.1636
|
| 46 |
+
DOUBAO_ALPHA_HEIGHT_FRAC = 0.0405
|
| 47 |
+
DOUBAO_ALPHA_MARGIN_RIGHT_FRAC = 0.0132
|
| 48 |
+
DOUBAO_ALPHA_MARGIN_BOTTOM_FRAC = 0.0166
|
| 49 |
+
DOUBAO_ALPHA_ALIGN_SEARCH = (0.88, 1.12, 25)
|
| 50 |
+
DOUBAO_RESIDUAL_ALPHA_FLOOR = 0.05
|
| 51 |
+
DOUBAO_TEMPLATE_DILATE = 4
|
| 52 |
+
|
| 53 |
+
LAMA_SESSION: ort.InferenceSession | None = None
|
| 54 |
+
MIGAN_MODEL: object | None = None
|
| 55 |
+
DOUBAO_ALPHA: np.ndarray | None = None
|
| 56 |
+
DOUBAO_SILHOUETTE: np.ndarray | None = None
|
| 57 |
+
MODEL_LOCK = threading.RLock()
|
| 58 |
+
|
| 59 |
+
app = FastAPI(title="Image Services Inpaint")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _md5sum(path: Path) -> str:
|
| 63 |
+
digest = hashlib.md5()
|
| 64 |
+
with path.open("rb") as handle:
|
| 65 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 66 |
+
digest.update(chunk)
|
| 67 |
+
return digest.hexdigest()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _cache_path_by_url(url: str) -> Path:
|
| 71 |
+
parts = urlparse(url)
|
| 72 |
+
model_dir = Path(os.getenv("TORCH_HOME", "/tmp/torch")) / "checkpoints"
|
| 73 |
+
model_dir.mkdir(parents=True, exist_ok=True)
|
| 74 |
+
return model_dir / Path(parts.path).name
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _download_torchscript(url: str, expected_md5: str) -> Path:
|
| 78 |
+
from torch.hub import download_url_to_file
|
| 79 |
+
|
| 80 |
+
path = _cache_path_by_url(url)
|
| 81 |
+
if not path.exists():
|
| 82 |
+
download_url_to_file(url, str(path), None, progress=True)
|
| 83 |
+
actual_md5 = _md5sum(path)
|
| 84 |
+
if actual_md5 != expected_md5:
|
| 85 |
+
try:
|
| 86 |
+
path.unlink()
|
| 87 |
+
finally:
|
| 88 |
+
raise RuntimeError(f"Model md5 mismatch: {actual_md5} != {expected_md5}")
|
| 89 |
+
return path
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _load_lama_session() -> ort.InferenceSession:
|
| 93 |
+
global LAMA_SESSION
|
| 94 |
+
if LAMA_SESSION is not None:
|
| 95 |
+
return LAMA_SESSION
|
| 96 |
+
with MODEL_LOCK:
|
| 97 |
+
if LAMA_SESSION is not None:
|
| 98 |
+
return LAMA_SESSION
|
| 99 |
+
model_path = hf_hub_download(repo_id=LAMA_MODEL_REPO, filename=LAMA_MODEL_FILE)
|
| 100 |
+
LAMA_SESSION = ort.InferenceSession(model_path, providers=PROVIDERS)
|
| 101 |
+
return LAMA_SESSION
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _load_migan_model() -> object:
|
| 105 |
+
global MIGAN_MODEL
|
| 106 |
+
if MIGAN_MODEL is not None:
|
| 107 |
+
return MIGAN_MODEL
|
| 108 |
+
with MODEL_LOCK:
|
| 109 |
+
if MIGAN_MODEL is not None:
|
| 110 |
+
return MIGAN_MODEL
|
| 111 |
+
model_path = _download_torchscript(MIGAN_MODEL_URL, MIGAN_MODEL_MD5)
|
| 112 |
+
import torch
|
| 113 |
+
|
| 114 |
+
MIGAN_MODEL = torch.jit.load(str(model_path), map_location="cpu").eval()
|
| 115 |
+
return MIGAN_MODEL
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _prepare_mask(mask: Image.Image, size: tuple[int, int]) -> np.ndarray:
|
| 119 |
+
arr = np.array(mask.convert("L").resize(size, Image.Resampling.NEAREST), copy=True)
|
| 120 |
+
return np.where(arr > 127, 255, 0).astype(np.uint8)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _load_doubao_alpha() -> np.ndarray:
|
| 124 |
+
global DOUBAO_ALPHA
|
| 125 |
+
if DOUBAO_ALPHA is not None:
|
| 126 |
+
return DOUBAO_ALPHA
|
| 127 |
+
alpha = cv2.imread(str(DOUBAO_ALPHA_ASSET), cv2.IMREAD_GRAYSCALE)
|
| 128 |
+
if alpha is None:
|
| 129 |
+
raise RuntimeError(f"Missing Doubao alpha asset: {DOUBAO_ALPHA_ASSET}")
|
| 130 |
+
DOUBAO_ALPHA = alpha.astype(np.float32) / 255.0
|
| 131 |
+
return DOUBAO_ALPHA
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _load_doubao_silhouette() -> np.ndarray:
|
| 135 |
+
global DOUBAO_SILHOUETTE
|
| 136 |
+
if DOUBAO_SILHOUETTE is not None:
|
| 137 |
+
return DOUBAO_SILHOUETTE
|
| 138 |
+
DOUBAO_SILHOUETTE = (_load_doubao_alpha() > 0.15).astype(np.uint8) * 255
|
| 139 |
+
return DOUBAO_SILHOUETTE
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _doubao_locate(image_bgr: np.ndarray) -> tuple[int, int, int, int]:
|
| 143 |
+
height, width = image_bgr.shape[:2]
|
| 144 |
+
mark_w = max(40, int(width * DOUBAO_WIDTH_FRAC))
|
| 145 |
+
mark_h = max(16, int(width * DOUBAO_HEIGHT_FRAC))
|
| 146 |
+
margin_right = max(4, int(width * DOUBAO_MARGIN_RIGHT_FRAC))
|
| 147 |
+
margin_bottom = max(4, int(width * DOUBAO_MARGIN_BOTTOM_FRAC))
|
| 148 |
+
x = max(0, width - margin_right - mark_w)
|
| 149 |
+
y = max(0, height - margin_bottom - mark_h)
|
| 150 |
+
return x, y, min(mark_w, width - x), min(mark_h, height - y)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _doubao_extract_candidate_mask(image_bgr: np.ndarray, loc: tuple[int, int, int, int]) -> np.ndarray:
|
| 154 |
+
x, y, width, height = loc
|
| 155 |
+
if width < 16 or height < 16:
|
| 156 |
+
return np.zeros((height, width), np.uint8)
|
| 157 |
+
roi = image_bgr[y : y + height, x : x + width].astype(np.float32)
|
| 158 |
+
luma = roi.mean(axis=2)
|
| 159 |
+
saturation = roi.max(axis=2) - roi.min(axis=2)
|
| 160 |
+
grayish = saturation < DOUBAO_MAX_SATURATION
|
| 161 |
+
sigma = max(4.0, height * 0.4)
|
| 162 |
+
local_bg = cv2.GaussianBlur(luma, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 163 |
+
tophat = luma - local_bg
|
| 164 |
+
glyph = (
|
| 165 |
+
grayish
|
| 166 |
+
& (tophat > DOUBAO_TOPHAT_DELTA)
|
| 167 |
+
& (luma > DOUBAO_LOGO_MIN_LUMA)
|
| 168 |
+
).astype(np.uint8) * 255
|
| 169 |
+
glyph = cv2.morphologyEx(glyph, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
|
| 170 |
+
return cv2.morphologyEx(glyph, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _doubao_template_match_score(box_mask: np.ndarray, image_width: int) -> float:
|
| 174 |
+
silhouette = _load_doubao_silhouette()
|
| 175 |
+
if box_mask.size == 0:
|
| 176 |
+
return 0.0
|
| 177 |
+
gw = min(box_mask.shape[1] - 1, max(8, int(DOUBAO_ALPHA_WIDTH_FRAC * image_width)))
|
| 178 |
+
gh = min(box_mask.shape[0] - 1, max(4, int(DOUBAO_ALPHA_HEIGHT_FRAC * image_width)))
|
| 179 |
+
if gw < 8 or gh < 4:
|
| 180 |
+
return 0.0
|
| 181 |
+
template = cv2.resize(silhouette, (gw, gh), interpolation=cv2.INTER_NEAREST)
|
| 182 |
+
return float(cv2.matchTemplate(box_mask, template, cv2.TM_CCOEFF_NORMED).max())
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _doubao_aligned_alpha(image_bgr: np.ndarray) -> tuple[np.ndarray, tuple[int, int, int, int]] | None:
|
| 186 |
+
alpha = _load_doubao_alpha()
|
| 187 |
+
silhouette = _load_doubao_silhouette()
|
| 188 |
+
image_width = image_bgr.shape[1]
|
| 189 |
+
bx, by, bw, bh = _doubao_locate(image_bgr)
|
| 190 |
+
box_mask = _doubao_extract_candidate_mask(image_bgr, (bx, by, bw, bh))
|
| 191 |
+
expected = DOUBAO_ALPHA_WIDTH_FRAC * image_width
|
| 192 |
+
best: tuple[float, int, int, int, int] | None = None
|
| 193 |
+
for scale in np.linspace(*DOUBAO_ALPHA_ALIGN_SEARCH):
|
| 194 |
+
gw = int(expected * scale)
|
| 195 |
+
gh = int(DOUBAO_ALPHA_HEIGHT_FRAC * image_width * scale)
|
| 196 |
+
if gw < 8 or gh < 4 or gw >= bw or gh >= bh:
|
| 197 |
+
continue
|
| 198 |
+
template = cv2.resize(silhouette, (gw, gh), interpolation=cv2.INTER_NEAREST)
|
| 199 |
+
_, score, _, top_left = cv2.minMaxLoc(cv2.matchTemplate(box_mask, template, cv2.TM_CCOEFF_NORMED))
|
| 200 |
+
if best is None or score > best[0]:
|
| 201 |
+
best = (score, gw, gh, top_left[0], top_left[1])
|
| 202 |
+
if best is None:
|
| 203 |
+
return None
|
| 204 |
+
_, gw, gh, ox, oy = best
|
| 205 |
+
return cv2.resize(alpha, (gw, gh), interpolation=cv2.INTER_LINEAR), (bx + ox, by + oy, gw, gh)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _doubao_fixed_alpha(image_bgr: np.ndarray) -> tuple[np.ndarray, tuple[int, int, int, int]]:
|
| 209 |
+
alpha = _load_doubao_alpha()
|
| 210 |
+
image_h, image_w = image_bgr.shape[:2]
|
| 211 |
+
gw = min(image_w, max(1, int(DOUBAO_ALPHA_WIDTH_FRAC * image_w)))
|
| 212 |
+
gh = min(image_h, max(1, int(DOUBAO_ALPHA_HEIGHT_FRAC * image_w)))
|
| 213 |
+
ax = max(0, image_w - int(DOUBAO_ALPHA_MARGIN_RIGHT_FRAC * image_w) - gw)
|
| 214 |
+
ay = max(0, image_h - int(DOUBAO_ALPHA_MARGIN_BOTTOM_FRAC * image_w) - gh)
|
| 215 |
+
return cv2.resize(alpha, (gw, gh), interpolation=cv2.INTER_LINEAR), (ax, ay, gw, gh)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def generate_doubao_template_bbox_mask(image_bgr: np.ndarray) -> tuple[np.ndarray, dict[str, object]]:
|
| 219 |
+
if min(image_bgr.shape[:2]) < 200:
|
| 220 |
+
raise ValueError("Image is too small for Doubao watermark detection.")
|
| 221 |
+
loc = _doubao_locate(image_bgr)
|
| 222 |
+
candidate_mask = _doubao_extract_candidate_mask(image_bgr, loc)
|
| 223 |
+
coverage = float((candidate_mask > 0).sum()) / float(max(1, loc[2] * loc[3]))
|
| 224 |
+
confidence = _doubao_template_match_score(candidate_mask, image_bgr.shape[1]) if coverage >= DOUBAO_DETECT_MIN_COVERAGE else 0.0
|
| 225 |
+
detected = confidence >= DOUBAO_DETECT_NCC_THRESHOLD
|
| 226 |
+
if not detected:
|
| 227 |
+
raise ValueError(f"Doubao watermark not detected. confidence={confidence:.3f} coverage={coverage:.3f}")
|
| 228 |
+
|
| 229 |
+
placed = _doubao_aligned_alpha(image_bgr) or _doubao_fixed_alpha(image_bgr)
|
| 230 |
+
alpha_block, (x, y, width, height) = placed
|
| 231 |
+
silhouette = (alpha_block > DOUBAO_RESIDUAL_ALPHA_FLOOR).astype(np.uint8) * 255
|
| 232 |
+
if int((silhouette > 0).sum()) == 0:
|
| 233 |
+
raise ValueError("Detected Doubao watermark but generated an empty mask.")
|
| 234 |
+
glyph_mask = np.zeros(image_bgr.shape[:2], np.uint8)
|
| 235 |
+
glyph_mask[y : y + height, x : x + width] = silhouette
|
| 236 |
+
if DOUBAO_TEMPLATE_DILATE > 0:
|
| 237 |
+
kernel = cv2.getStructuringElement(
|
| 238 |
+
cv2.MORPH_ELLIPSE,
|
| 239 |
+
(2 * DOUBAO_TEMPLATE_DILATE + 1, 2 * DOUBAO_TEMPLATE_DILATE + 1),
|
| 240 |
+
)
|
| 241 |
+
glyph_mask = cv2.dilate(glyph_mask, kernel)
|
| 242 |
+
|
| 243 |
+
ys, xs = np.where(glyph_mask > 0)
|
| 244 |
+
if len(xs) == 0 or len(ys) == 0:
|
| 245 |
+
raise ValueError("Detected Doubao watermark but bbox mask is empty.")
|
| 246 |
+
bbox_mask = np.zeros_like(glyph_mask)
|
| 247 |
+
x0, x1 = int(xs.min()), int(xs.max()) + 1
|
| 248 |
+
y0, y1 = int(ys.min()), int(ys.max()) + 1
|
| 249 |
+
bbox_mask[y0:y1, x0:x1] = 255
|
| 250 |
+
return bbox_mask, {
|
| 251 |
+
"confidence": round(confidence, 4),
|
| 252 |
+
"coverage": round(coverage, 4),
|
| 253 |
+
"bbox": [x0, y0, x1 - x0, y1 - y0],
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _mask_bbox(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 258 |
+
ys, xs = np.where(mask > 0)
|
| 259 |
+
if len(xs) == 0 or len(ys) == 0:
|
| 260 |
+
raise ValueError("Mask is empty.")
|
| 261 |
+
return ys, xs
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _ceil_modulo(value: int, mod: int) -> int:
|
| 265 |
+
if value % mod == 0:
|
| 266 |
+
return value
|
| 267 |
+
return (value // mod + 1) * mod
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _pad_img_to_modulo(
|
| 271 |
+
image: np.ndarray,
|
| 272 |
+
*,
|
| 273 |
+
mod: int,
|
| 274 |
+
square: bool = False,
|
| 275 |
+
min_size: int | None = None,
|
| 276 |
+
) -> np.ndarray:
|
| 277 |
+
if image.ndim == 2:
|
| 278 |
+
image = image[:, :, None]
|
| 279 |
+
height, width = image.shape[:2]
|
| 280 |
+
out_height = _ceil_modulo(height, mod)
|
| 281 |
+
out_width = _ceil_modulo(width, mod)
|
| 282 |
+
if min_size is not None:
|
| 283 |
+
out_width = max(min_size, out_width)
|
| 284 |
+
out_height = max(min_size, out_height)
|
| 285 |
+
if square:
|
| 286 |
+
side = max(out_height, out_width)
|
| 287 |
+
out_height = side
|
| 288 |
+
out_width = side
|
| 289 |
+
return np.pad(
|
| 290 |
+
image,
|
| 291 |
+
((0, out_height - height), (0, out_width - width), (0, 0)),
|
| 292 |
+
mode="symmetric",
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _resize_max_size(image: np.ndarray, size_limit: int, interpolation: int = cv2.INTER_CUBIC) -> np.ndarray:
|
| 297 |
+
height, width = image.shape[:2]
|
| 298 |
+
if max(height, width) <= size_limit:
|
| 299 |
+
return image
|
| 300 |
+
ratio = size_limit / max(height, width)
|
| 301 |
+
return cv2.resize(image, (int(width * ratio + 0.5), int(height * ratio + 0.5)), interpolation=interpolation)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _norm_img(image: np.ndarray) -> np.ndarray:
|
| 305 |
+
if image.ndim == 2:
|
| 306 |
+
image = image[:, :, None]
|
| 307 |
+
image = np.transpose(image, (2, 0, 1))
|
| 308 |
+
return image.astype("float32") / 255.0
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _boxes_from_mask(mask: np.ndarray) -> list[np.ndarray]:
|
| 312 |
+
_, thresh = cv2.threshold(mask, 127, 255, 0)
|
| 313 |
+
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 314 |
+
boxes: list[np.ndarray] = []
|
| 315 |
+
height, width = mask.shape[:2]
|
| 316 |
+
for contour in contours:
|
| 317 |
+
x, y, box_width, box_height = cv2.boundingRect(contour)
|
| 318 |
+
box = np.array([x, y, x + box_width, y + box_height]).astype(int)
|
| 319 |
+
box[::2] = np.clip(box[::2], 0, width)
|
| 320 |
+
box[1::2] = np.clip(box[1::2], 0, height)
|
| 321 |
+
boxes.append(box)
|
| 322 |
+
return boxes
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _crop_box(
|
| 326 |
+
image: np.ndarray,
|
| 327 |
+
mask: np.ndarray,
|
| 328 |
+
box: np.ndarray,
|
| 329 |
+
*,
|
| 330 |
+
margin: int,
|
| 331 |
+
) -> tuple[np.ndarray, np.ndarray, tuple[int, int, int, int]]:
|
| 332 |
+
box_h = int(box[3] - box[1])
|
| 333 |
+
box_w = int(box[2] - box[0])
|
| 334 |
+
cx = int((box[0] + box[2]) // 2)
|
| 335 |
+
cy = int((box[1] + box[3]) // 2)
|
| 336 |
+
img_h, img_w = image.shape[:2]
|
| 337 |
+
|
| 338 |
+
crop_w = box_w + margin * 2
|
| 339 |
+
crop_h = box_h + margin * 2
|
| 340 |
+
raw_l = cx - crop_w // 2
|
| 341 |
+
raw_r = cx + crop_w // 2
|
| 342 |
+
raw_t = cy - crop_h // 2
|
| 343 |
+
raw_b = cy + crop_h // 2
|
| 344 |
+
|
| 345 |
+
left = max(raw_l, 0)
|
| 346 |
+
right = min(raw_r, img_w)
|
| 347 |
+
top = max(raw_t, 0)
|
| 348 |
+
bottom = min(raw_b, img_h)
|
| 349 |
+
|
| 350 |
+
if raw_l < 0:
|
| 351 |
+
right += abs(raw_l)
|
| 352 |
+
if raw_r > img_w:
|
| 353 |
+
left -= raw_r - img_w
|
| 354 |
+
if raw_t < 0:
|
| 355 |
+
bottom += abs(raw_t)
|
| 356 |
+
if raw_b > img_h:
|
| 357 |
+
top -= raw_b - img_h
|
| 358 |
+
|
| 359 |
+
left = max(left, 0)
|
| 360 |
+
right = min(right, img_w)
|
| 361 |
+
top = max(top, 0)
|
| 362 |
+
bottom = min(bottom, img_h)
|
| 363 |
+
return image[top:bottom, left:right, :], mask[top:bottom, left:right], (left, top, right, bottom)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _erase_lama_onnx(image_bgr: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 367 |
+
session = _load_lama_session()
|
| 368 |
+
inputs = session.get_inputs()
|
| 369 |
+
image_name = inputs[0].name
|
| 370 |
+
mask_name = inputs[1].name
|
| 371 |
+
dims = inputs[0].shape
|
| 372 |
+
size = next((dim for dim in reversed(dims) if isinstance(dim, int) and dim > 1), 512)
|
| 373 |
+
|
| 374 |
+
height, width = image_bgr.shape[:2]
|
| 375 |
+
ys, xs = _mask_bbox(mask)
|
| 376 |
+
|
| 377 |
+
pad = max(16, int(0.4 * max(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1)))
|
| 378 |
+
cx0 = max(0, int(xs.min()) - pad)
|
| 379 |
+
cy0 = max(0, int(ys.min()) - pad)
|
| 380 |
+
cx1 = min(width, int(xs.max()) + 1 + pad)
|
| 381 |
+
cy1 = min(height, int(ys.max()) + 1 + pad)
|
| 382 |
+
|
| 383 |
+
crop = image_bgr[cy0:cy1, cx0:cx1]
|
| 384 |
+
crop_mask = mask[cy0:cy1, cx0:cx1]
|
| 385 |
+
crop_h, crop_w = crop.shape[:2]
|
| 386 |
+
|
| 387 |
+
crop_rs = cv2.resize(crop, (size, size), interpolation=cv2.INTER_AREA)
|
| 388 |
+
mask_rs = cv2.resize(crop_mask, (size, size), interpolation=cv2.INTER_NEAREST)
|
| 389 |
+
|
| 390 |
+
image_input = cv2.cvtColor(crop_rs, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
|
| 391 |
+
image_input = np.transpose(image_input, (2, 0, 1))[None]
|
| 392 |
+
mask_input = (mask_rs > 127).astype(np.float32)[None, None]
|
| 393 |
+
|
| 394 |
+
output = session.run(None, {image_name: image_input, mask_name: mask_input})[0]
|
| 395 |
+
output = np.asarray(output)[0]
|
| 396 |
+
output = np.transpose(output, (1, 2, 0))
|
| 397 |
+
if float(output.max()) <= 1.5:
|
| 398 |
+
output = output * 255.0
|
| 399 |
+
output = np.clip(output, 0, 255).astype(np.uint8)
|
| 400 |
+
output_bgr = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
|
| 401 |
+
output_crop = cv2.resize(output_bgr, (crop_w, crop_h), interpolation=cv2.INTER_LINEAR)
|
| 402 |
+
|
| 403 |
+
result = image_bgr.copy()
|
| 404 |
+
region = result[cy0:cy1, cx0:cx1]
|
| 405 |
+
paste = crop_mask > 127
|
| 406 |
+
region[paste] = output_crop[paste]
|
| 407 |
+
result[cy0:cy1, cx0:cx1] = region
|
| 408 |
+
return result
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _migan_forward(model: object, image_rgb: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 412 |
+
import torch
|
| 413 |
+
|
| 414 |
+
image = _norm_img(image_rgb) * 2 - 1
|
| 415 |
+
mask_binary = (mask > 120).astype(np.uint8) * 255
|
| 416 |
+
mask_input = _norm_img(mask_binary)
|
| 417 |
+
image_tensor = torch.from_numpy(image).unsqueeze(0)
|
| 418 |
+
mask_tensor = torch.from_numpy(mask_input).unsqueeze(0)
|
| 419 |
+
erased = image_tensor * (1 - mask_tensor)
|
| 420 |
+
model_input = torch.cat([0.5 - mask_tensor, erased], dim=1)
|
| 421 |
+
with torch.inference_mode():
|
| 422 |
+
output = model(model_input)
|
| 423 |
+
output = (
|
| 424 |
+
(output.permute(0, 2, 3, 1) * 127.5 + 127.5)
|
| 425 |
+
.round()
|
| 426 |
+
.clamp(0, 255)
|
| 427 |
+
.to(torch.uint8)
|
| 428 |
+
)
|
| 429 |
+
result = output[0].cpu().numpy()
|
| 430 |
+
return cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def _migan_pad_forward(model: object, image_rgb: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 434 |
+
origin_h, origin_w = image_rgb.shape[:2]
|
| 435 |
+
padded_image = _pad_img_to_modulo(image_rgb, mod=512, square=True, min_size=512)
|
| 436 |
+
padded_mask = _pad_img_to_modulo(mask, mod=512, square=True, min_size=512)
|
| 437 |
+
return _migan_forward(model, padded_image, padded_mask)[:origin_h, :origin_w, :]
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _erase_migan_torchscript(image_bgr: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 441 |
+
model = _load_migan_model()
|
| 442 |
+
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 443 |
+
if image_rgb.shape[:2] == (512, 512):
|
| 444 |
+
return _migan_pad_forward(model, image_rgb, mask)
|
| 445 |
+
|
| 446 |
+
result = image_rgb[:, :, ::-1].copy()
|
| 447 |
+
for box in _boxes_from_mask(mask):
|
| 448 |
+
crop_img, crop_mask, (left, top, right, bottom) = _crop_box(image_rgb, mask, box, margin=128)
|
| 449 |
+
origin_size = crop_img.shape[:2]
|
| 450 |
+
resized_img = _resize_max_size(crop_img, 512)
|
| 451 |
+
resized_mask = _resize_max_size(crop_mask, 512)
|
| 452 |
+
inpaint = _migan_pad_forward(model, resized_img, resized_mask)
|
| 453 |
+
inpaint = cv2.resize(inpaint, (origin_size[1], origin_size[0]), interpolation=cv2.INTER_CUBIC)
|
| 454 |
+
keep = crop_mask < 127
|
| 455 |
+
inpaint[keep] = crop_img[:, :, ::-1][keep]
|
| 456 |
+
result[top:bottom, left:right, :] = inpaint
|
| 457 |
+
return result
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _normalize_mode(mode: str | None) -> str:
|
| 461 |
+
requested = (mode or DEFAULT_MODE).strip().lower()
|
| 462 |
+
aliases = {
|
| 463 |
+
"lama": "quality",
|
| 464 |
+
"high": "quality",
|
| 465 |
+
"high-quality": "quality",
|
| 466 |
+
"migan": "fast",
|
| 467 |
+
"quick": "fast",
|
| 468 |
+
}
|
| 469 |
+
normalized = aliases.get(requested, requested)
|
| 470 |
+
if normalized not in MODES:
|
| 471 |
+
raise ValueError(f"Unsupported mode: {mode}. Supported modes: {', '.join(MODES)}")
|
| 472 |
+
return normalized
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def run_inpaint(image: Image.Image, mask: Image.Image, *, mode: str | None = None) -> tuple[Image.Image, str, float]:
|
| 476 |
+
normalized_mode = _normalize_mode(mode)
|
| 477 |
+
rgb_image = np.array(image.convert("RGB"), copy=True)
|
| 478 |
+
image_bgr = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
|
| 479 |
+
prepared_mask = _prepare_mask(mask, image.size)
|
| 480 |
+
|
| 481 |
+
start = time.time()
|
| 482 |
+
with MODEL_LOCK:
|
| 483 |
+
if normalized_mode == "quality":
|
| 484 |
+
result_bgr = _erase_lama_onnx(image_bgr, prepared_mask)
|
| 485 |
+
elif normalized_mode == "fast":
|
| 486 |
+
result_bgr = _erase_migan_torchscript(image_bgr, prepared_mask)
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError(f"Unsupported mode: {normalized_mode}")
|
| 489 |
+
elapsed = time.time() - start
|
| 490 |
+
|
| 491 |
+
result_rgb = cv2.cvtColor(result_bgr.astype(np.uint8), cv2.COLOR_BGR2RGB)
|
| 492 |
+
return Image.fromarray(result_rgb), normalized_mode, elapsed
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def run_remove_doubao(image: Image.Image, *, mode: str | None = None) -> tuple[Image.Image, str, float, dict[str, object]]:
|
| 496 |
+
rgb_image = np.array(image.convert("RGB"), copy=True)
|
| 497 |
+
image_bgr = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
|
| 498 |
+
mask, metadata = generate_doubao_template_bbox_mask(image_bgr)
|
| 499 |
+
mask_image = Image.fromarray(mask, mode="L")
|
| 500 |
+
result, normalized_mode, elapsed = run_inpaint(image, mask_image, mode=mode)
|
| 501 |
+
return result, normalized_mode, elapsed, metadata
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@app.on_event("startup")
|
| 505 |
+
def startup() -> None:
|
| 506 |
+
if not LOAD_MODEL_ON_STARTUP:
|
| 507 |
+
return
|
| 508 |
+
if DEFAULT_MODE == "fast":
|
| 509 |
+
_load_migan_model()
|
| 510 |
+
else:
|
| 511 |
+
_load_lama_session()
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
@app.get("/")
|
| 515 |
+
def root() -> dict[str, object]:
|
| 516 |
+
return health()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@app.get("/health")
|
| 520 |
+
def health() -> dict[str, object]:
|
| 521 |
+
return {
|
| 522 |
+
"status": "ok",
|
| 523 |
+
"mode": "dual-selected-backends",
|
| 524 |
+
"default_mode": DEFAULT_MODE,
|
| 525 |
+
"supported_modes": MODES,
|
| 526 |
+
"loaded": {
|
| 527 |
+
"quality": LAMA_SESSION is not None,
|
| 528 |
+
"fast": MIGAN_MODEL is not None,
|
| 529 |
+
},
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@app.post("/inpaint")
|
| 534 |
+
async def inpaint(
|
| 535 |
+
image: UploadFile = File(...),
|
| 536 |
+
mask: UploadFile = File(...),
|
| 537 |
+
mode: str = Form(DEFAULT_MODE),
|
| 538 |
+
) -> Response:
|
| 539 |
+
try:
|
| 540 |
+
image_bytes = await image.read()
|
| 541 |
+
mask_bytes = await mask.read()
|
| 542 |
+
pil_image = Image.open(io.BytesIO(image_bytes))
|
| 543 |
+
pil_mask = Image.open(io.BytesIO(mask_bytes))
|
| 544 |
+
result, normalized_mode, elapsed = run_inpaint(pil_image, pil_mask, mode=mode)
|
| 545 |
+
output = io.BytesIO()
|
| 546 |
+
result.save(output, format="PNG")
|
| 547 |
+
return Response(
|
| 548 |
+
content=output.getvalue(),
|
| 549 |
+
media_type="image/png",
|
| 550 |
+
headers={
|
| 551 |
+
"X-Inpaint-Mode": normalized_mode,
|
| 552 |
+
"X-Inpaint-Backend": MODES[normalized_mode],
|
| 553 |
+
"X-Inpaint-Elapsed": f"{elapsed:.3f}",
|
| 554 |
+
},
|
| 555 |
+
)
|
| 556 |
+
except Exception as exc:
|
| 557 |
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@app.post("/remove-doubao")
|
| 561 |
+
async def remove_doubao(
|
| 562 |
+
image: UploadFile = File(...),
|
| 563 |
+
mode: str = Form(DEFAULT_MODE),
|
| 564 |
+
) -> Response:
|
| 565 |
+
try:
|
| 566 |
+
image_bytes = await image.read()
|
| 567 |
+
pil_image = Image.open(io.BytesIO(image_bytes))
|
| 568 |
+
result, normalized_mode, elapsed, metadata = run_remove_doubao(pil_image, mode=mode)
|
| 569 |
+
output = io.BytesIO()
|
| 570 |
+
result.save(output, format="PNG")
|
| 571 |
+
return Response(
|
| 572 |
+
content=output.getvalue(),
|
| 573 |
+
media_type="image/png",
|
| 574 |
+
headers={
|
| 575 |
+
"X-Inpaint-Mode": normalized_mode,
|
| 576 |
+
"X-Inpaint-Backend": MODES[normalized_mode],
|
| 577 |
+
"X-Inpaint-Elapsed": f"{elapsed:.3f}",
|
| 578 |
+
"X-Doubao-Confidence": str(metadata["confidence"]),
|
| 579 |
+
"X-Doubao-Coverage": str(metadata["coverage"]),
|
| 580 |
+
"X-Doubao-BBox": ",".join(str(v) for v in metadata["bbox"]),
|
| 581 |
+
},
|
| 582 |
+
)
|
| 583 |
+
except Exception as exc:
|
| 584 |
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|