Spaces:
Sleeping
Sleeping
Sync from GitHub via hub-sync
Browse files
main.py
CHANGED
|
@@ -2,6 +2,7 @@ import asyncio
|
|
| 2 |
from contextlib import asynccontextmanager
|
| 3 |
|
| 4 |
from fastapi import FastAPI, File, UploadFile, Form
|
|
|
|
| 5 |
from fastapi.staticfiles import StaticFiles
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
import uvicorn
|
|
@@ -12,6 +13,9 @@ from celery.result import AsyncResult
|
|
| 12 |
import config as config
|
| 13 |
from schemas import InpaintRequest, SegmentRequest
|
| 14 |
from services import job_lifecycle
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
job_lifecycle.ensure_upload_dir()
|
| 17 |
|
|
@@ -77,6 +81,13 @@ async def detect_objects(job_id: str, prompt: str = Form(...)):
|
|
| 77 |
return job_id
|
| 78 |
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
@app.post("/process/segment_objects/{job_id}")
|
| 81 |
async def segment_objects(job_id: str, data: SegmentRequest):
|
| 82 |
tasks.celery_app.backend.delete(f"celery-task-meta-{job_id}")
|
|
@@ -84,6 +95,31 @@ async def segment_objects(job_id: str, data: SegmentRequest):
|
|
| 84 |
return job_id
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
@app.post("/process/inpaint/{job_id}")
|
| 88 |
async def inpaint(job_id: str, data: InpaintRequest):
|
| 89 |
tasks.celery_app.backend.delete(f"celery-task-meta-{job_id}")
|
|
|
|
| 2 |
from contextlib import asynccontextmanager
|
| 3 |
|
| 4 |
from fastapi import FastAPI, File, UploadFile, Form
|
| 5 |
+
from fastapi import HTTPException
|
| 6 |
from fastapi.staticfiles import StaticFiles
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
import uvicorn
|
|
|
|
| 13 |
import config as config
|
| 14 |
from schemas import InpaintRequest, SegmentRequest
|
| 15 |
from services import job_lifecycle
|
| 16 |
+
from PIL import Image, UnidentifiedImageError
|
| 17 |
+
import numpy as np
|
| 18 |
+
from utils import mask_image_to_binary, save_visual_mask_from_binary
|
| 19 |
|
| 20 |
job_lifecycle.ensure_upload_dir()
|
| 21 |
|
|
|
|
| 81 |
return job_id
|
| 82 |
|
| 83 |
|
| 84 |
+
@app.post("/process/generate_mask/{job_id}")
|
| 85 |
+
async def generate_mask(job_id: str, prompt: str = Form(...)):
|
| 86 |
+
tasks.celery_app.backend.delete(f"celery-task-meta-{job_id}")
|
| 87 |
+
tasks.generate_mask.apply_async(args=[job_id, prompt], task_id=job_id)
|
| 88 |
+
return job_id
|
| 89 |
+
|
| 90 |
+
|
| 91 |
@app.post("/process/segment_objects/{job_id}")
|
| 92 |
async def segment_objects(job_id: str, data: SegmentRequest):
|
| 93 |
tasks.celery_app.backend.delete(f"celery-task-meta-{job_id}")
|
|
|
|
| 95 |
return job_id
|
| 96 |
|
| 97 |
|
| 98 |
+
@app.post("/api/upload-manual-mask")
|
| 99 |
+
async def upload_manual_mask(job_id: str = Form(...), mask: UploadFile = File(...)):
|
| 100 |
+
job_path = config.UPLOAD_DIR / job_id
|
| 101 |
+
input_path = job_path / config.INPUT_IMG_NAME
|
| 102 |
+
|
| 103 |
+
if not job_path.exists() or not input_path.exists():
|
| 104 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
mask_img = Image.open(mask.file)
|
| 108 |
+
mask_img.load()
|
| 109 |
+
except (UnidentifiedImageError, OSError) as exc:
|
| 110 |
+
raise HTTPException(status_code=400, detail="Invalid mask image") from exc
|
| 111 |
+
|
| 112 |
+
input_img = Image.open(input_path)
|
| 113 |
+
binary_mask = mask_image_to_binary(mask_img, size=input_img.size)
|
| 114 |
+
binary_mask.save(job_path / config.SEGMENTOR_OUT_BIN_PATH)
|
| 115 |
+
save_visual_mask_from_binary(
|
| 116 |
+
np.asarray(binary_mask) > 0,
|
| 117 |
+
job_path / config.SEGMENTOR_OUT_VISUAL_PATH,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
return {"job_id": job_id, "mask_uploaded": True}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
@app.post("/process/inpaint/{job_id}")
|
| 124 |
async def inpaint(job_id: str, data: InpaintRequest):
|
| 125 |
tasks.celery_app.backend.delete(f"celery-task-meta-{job_id}")
|
tasks.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
from celery import Celery
|
| 3 |
import config as config
|
| 4 |
import torch
|
| 5 |
-
from utils import get_prompt_list, plot_groundingdino_boxes, save_visual_mask, blur_img_with_mask
|
| 6 |
from PIL import Image
|
| 7 |
from transformers import BatchFeature
|
| 8 |
import numpy as np
|
|
@@ -30,8 +30,7 @@ celery_app.conf.update(
|
|
| 30 |
)
|
| 31 |
|
| 32 |
|
| 33 |
-
|
| 34 |
-
def detect_objects(job_id: str, prompt: str) -> dict:
|
| 35 |
prompt_list = get_prompt_list(prompt)
|
| 36 |
|
| 37 |
job_path = config.UPLOAD_DIR / job_id
|
|
@@ -73,29 +72,71 @@ def detect_objects(job_id: str, prompt: str) -> dict:
|
|
| 73 |
return result
|
| 74 |
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
job_path = config.UPLOAD_DIR / job_id
|
| 79 |
img = Image.open(job_path / config.INPUT_IMG_NAME)
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
model = model_manager.get_segmentor_model(MODELS)
|
| 82 |
results = model(img, bboxes=bboxes, points=points, labels=point_labels)
|
| 83 |
|
| 84 |
mask_data = results[0].masks.data.cpu().numpy() # n_masks x H x W
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
save_bin_path = job_path / config.SEGMENTOR_OUT_BIN_PATH
|
| 88 |
save_visual_path = job_path / config.SEGMENTOR_OUT_VISUAL_PATH
|
| 89 |
|
| 90 |
Image.fromarray(combined_mask).save(save_bin_path)
|
| 91 |
-
save_visual_mask(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
if self.request.id is None:
|
| 94 |
-
return
|
| 95 |
|
| 96 |
return True
|
| 97 |
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
@celery_app.task(bind=True)
|
| 100 |
def inpaint(
|
| 101 |
self,
|
|
|
|
| 2 |
from celery import Celery
|
| 3 |
import config as config
|
| 4 |
import torch
|
| 5 |
+
from utils import get_prompt_list, plot_groundingdino_boxes, save_visual_mask, save_visual_mask_from_binary, blur_img_with_mask
|
| 6 |
from PIL import Image
|
| 7 |
from transformers import BatchFeature
|
| 8 |
import numpy as np
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
|
| 33 |
+
def _detect_objects(job_id: str, prompt: str) -> dict:
|
|
|
|
| 34 |
prompt_list = get_prompt_list(prompt)
|
| 35 |
|
| 36 |
job_path = config.UPLOAD_DIR / job_id
|
|
|
|
| 72 |
return result
|
| 73 |
|
| 74 |
|
| 75 |
+
def _save_empty_mask(job_path, image_size):
|
| 76 |
+
width, height = image_size
|
| 77 |
+
combined_mask = np.zeros((height, width), dtype=np.uint8)
|
| 78 |
+
Image.fromarray(combined_mask, mode="L").save(job_path / config.SEGMENTOR_OUT_BIN_PATH)
|
| 79 |
+
save_visual_mask_from_binary(combined_mask, job_path / config.SEGMENTOR_OUT_VISUAL_PATH)
|
| 80 |
+
return combined_mask
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _segment_objects(job_id: str, bboxes=None, points=None, point_labels=None):
|
| 84 |
job_path = config.UPLOAD_DIR / job_id
|
| 85 |
img = Image.open(job_path / config.INPUT_IMG_NAME)
|
| 86 |
|
| 87 |
+
if not bboxes and not points:
|
| 88 |
+
_save_empty_mask(job_path, img.size)
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
model = model_manager.get_segmentor_model(MODELS)
|
| 92 |
results = model(img, bboxes=bboxes, points=points, labels=point_labels)
|
| 93 |
|
| 94 |
mask_data = results[0].masks.data.cpu().numpy() # n_masks x H x W
|
| 95 |
|
| 96 |
+
if mask_data.size == 0:
|
| 97 |
+
combined_mask = _save_empty_mask(job_path, img.size)
|
| 98 |
+
else:
|
| 99 |
+
combined_mask = np.any(mask_data, axis=0).astype(np.uint8) * 255
|
| 100 |
+
|
| 101 |
save_bin_path = job_path / config.SEGMENTOR_OUT_BIN_PATH
|
| 102 |
save_visual_path = job_path / config.SEGMENTOR_OUT_VISUAL_PATH
|
| 103 |
|
| 104 |
Image.fromarray(combined_mask).save(save_bin_path)
|
| 105 |
+
save_visual_mask(combined_mask, save_visual_path)
|
| 106 |
+
|
| 107 |
+
return results[0]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@celery_app.task
|
| 111 |
+
def detect_objects(job_id: str, prompt: str) -> dict:
|
| 112 |
+
return _detect_objects(job_id, prompt)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@celery_app.task(bind=True)
|
| 116 |
+
def segment_objects(self, job_id: str, bboxes=None, points=None, point_labels=None):
|
| 117 |
+
result = _segment_objects(job_id, bboxes=bboxes, points=points, point_labels=point_labels)
|
| 118 |
|
| 119 |
if self.request.id is None:
|
| 120 |
+
return result
|
| 121 |
|
| 122 |
return True
|
| 123 |
|
| 124 |
|
| 125 |
+
@celery_app.task(bind=True)
|
| 126 |
+
def generate_mask(self, job_id: str, prompt: str) -> dict:
|
| 127 |
+
detection_result = _detect_objects(job_id, prompt)
|
| 128 |
+
bboxes = detection_result.get("boxes", [])
|
| 129 |
+
_segment_objects(job_id, bboxes=bboxes)
|
| 130 |
+
|
| 131 |
+
if self.request.id is None:
|
| 132 |
+
return detection_result
|
| 133 |
+
|
| 134 |
+
return {
|
| 135 |
+
"boxes": len(bboxes),
|
| 136 |
+
"labels": detection_result.get("text_labels", []),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
@celery_app.task(bind=True)
|
| 141 |
def inpaint(
|
| 142 |
self,
|
utils.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import matplotlib.pyplot as plt
|
| 2 |
-
import colorsys
|
| 3 |
import matplotlib.patches as patches
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image, ImageFilter
|
|
@@ -43,32 +42,48 @@ def plot_groundingdino_boxes(img: Image.Image, result, figsize=(12, 8), show_sco
|
|
| 43 |
plt.show()
|
| 44 |
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
out = np.zeros((H, W, 4), dtype=np.uint8)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
if
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def blur_img_with_mask(
|
|
|
|
| 1 |
import matplotlib.pyplot as plt
|
|
|
|
| 2 |
import matplotlib.patches as patches
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image, ImageFilter
|
|
|
|
| 42 |
plt.show()
|
| 43 |
|
| 44 |
|
| 45 |
+
MASK_OVERLAY_RGBA = (225, 29, 72, int(0.58 * 255))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def save_visual_mask_from_binary(mask, out_path):
|
| 49 |
+
mask_bool = np.asarray(mask)
|
| 50 |
+
if mask_bool.ndim == 3:
|
| 51 |
+
mask_bool = np.any(mask_bool > 0, axis=0)
|
| 52 |
+
elif mask_bool.dtype != bool:
|
| 53 |
+
mask_bool = mask_bool > 0
|
| 54 |
|
| 55 |
+
H, W = mask_bool.shape
|
| 56 |
out = np.zeros((H, W, 4), dtype=np.uint8)
|
| 57 |
+
out[mask_bool] = MASK_OVERLAY_RGBA
|
| 58 |
+
Image.fromarray(out, mode="RGBA").save(out_path)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def save_visual_mask(mask_data, out_path):
|
| 62 |
+
masks = np.asarray(mask_data)
|
| 63 |
+
if masks.ndim == 2:
|
| 64 |
+
combined_mask = masks > 0
|
| 65 |
+
else:
|
| 66 |
+
masks = (masks > 0.5) if masks.dtype != bool else masks.astype(bool)
|
| 67 |
+
combined_mask = np.any(masks, axis=0) if masks.size else np.zeros(masks.shape[-2:], dtype=bool)
|
| 68 |
+
|
| 69 |
+
save_visual_mask_from_binary(combined_mask, out_path)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def mask_image_to_binary(mask_img: Image.Image, size=None) -> Image.Image:
|
| 73 |
+
rgba = mask_img.convert("RGBA")
|
| 74 |
+
if size is not None and rgba.size != size:
|
| 75 |
+
rgba = rgba.resize(size, Image.Resampling.NEAREST)
|
| 76 |
+
|
| 77 |
+
rgba_arr = np.asarray(rgba)
|
| 78 |
+
alpha = rgba_arr[..., 3]
|
| 79 |
+
|
| 80 |
+
if np.any(alpha < 255):
|
| 81 |
+
mask_bool = alpha > 12
|
| 82 |
+
else:
|
| 83 |
+
gray = np.asarray(rgba.convert("L"))
|
| 84 |
+
mask_bool = gray > 127
|
| 85 |
+
|
| 86 |
+
return Image.fromarray(mask_bool.astype(np.uint8) * 255, mode="L")
|
| 87 |
|
| 88 |
|
| 89 |
def blur_img_with_mask(
|