Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import asyncio
|
| 2 |
import io
|
| 3 |
import os
|
| 4 |
-
import re
|
| 5 |
import socket
|
| 6 |
import time
|
| 7 |
from contextlib import asynccontextmanager
|
|
@@ -20,24 +19,57 @@ from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
|
|
| 20 |
|
| 21 |
MODEL_ID = "IDEA-Research/grounding-dino-base"
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
MATCH_CONTAINMENT_THRESHOLD = float(os.getenv("MATCH_CONTAINMENT_THRESHOLD", "0.80"))
|
| 42 |
IMAGE_SHORT_EDGE = int(os.getenv("IMAGE_SHORT_EDGE", "512"))
|
| 43 |
IMAGE_LONG_EDGE = int(os.getenv("IMAGE_LONG_EDGE", "768"))
|
|
@@ -46,11 +78,13 @@ MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", str(20_000_000)))
|
|
| 46 |
REQUEST_TIMEOUT_SECONDS = float(os.getenv("REQUEST_TIMEOUT_SECONDS", "20"))
|
| 47 |
|
| 48 |
for threshold_name, threshold_value in {
|
| 49 |
-
"
|
| 50 |
-
"
|
| 51 |
-
"CLASS_THRESHOLD": CLASS_THRESHOLD,
|
| 52 |
"PART_THRESHOLD": PART_THRESHOLD,
|
|
|
|
| 53 |
"GENDER_MARGIN": GENDER_MARGIN,
|
|
|
|
|
|
|
| 54 |
"MATCH_IOU_THRESHOLD": MATCH_IOU_THRESHOLD,
|
| 55 |
"MATCH_CONTAINMENT_THRESHOLD": MATCH_CONTAINMENT_THRESHOLD,
|
| 56 |
}.items():
|
|
@@ -59,14 +93,6 @@ for threshold_name, threshold_value in {
|
|
| 59 |
if IMAGE_SHORT_EDGE <= 0 or IMAGE_LONG_EDGE < IMAGE_SHORT_EDGE:
|
| 60 |
raise RuntimeError("Invalid image resize configuration")
|
| 61 |
|
| 62 |
-
_prompt_words = set(re.findall(r"[a-z]+", DETECTION_PROMPT))
|
| 63 |
-
if not (_prompt_words & {"man", "boy", "male"}):
|
| 64 |
-
raise RuntimeError("DETECTION_PROMPT must contain at least one male class")
|
| 65 |
-
if not (_prompt_words & {"woman", "girl", "female"}):
|
| 66 |
-
raise RuntimeError("DETECTION_PROMPT must contain at least one female class")
|
| 67 |
-
if not (_prompt_words & {"face", "body", "arm", "hand", "leg", "foot"}):
|
| 68 |
-
raise RuntimeError("DETECTION_PROMPT must contain at least one human body-part class")
|
| 69 |
-
|
| 70 |
# Avoid CPU oversubscription on the 2-vCPU Space.
|
| 71 |
torch.set_num_threads(max(1, int(os.getenv("TORCH_NUM_THREADS", "2"))))
|
| 72 |
try:
|
|
@@ -195,7 +221,6 @@ def _load_model() -> None:
|
|
| 195 |
print(f"Loading {MODEL_ID} on CPU...")
|
| 196 |
|
| 197 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 198 |
-
# A smaller input resolution improves latency on the free CPU Space.
|
| 199 |
if hasattr(processor, "image_processor"):
|
| 200 |
processor.image_processor.size = {
|
| 201 |
"shortest_edge": IMAGE_SHORT_EDGE,
|
|
@@ -208,31 +233,51 @@ def _load_model() -> None:
|
|
| 208 |
low_cpu_mem_usage=True,
|
| 209 |
).eval()
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
MODEL_DATA["processor"] = processor
|
| 212 |
MODEL_DATA["model"] = model
|
|
|
|
| 213 |
print(f"Grounding DINO ready in {time.perf_counter() - started:.1f}s")
|
| 214 |
|
| 215 |
|
| 216 |
-
def
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
return "person"
|
| 235 |
-
return "other"
|
| 236 |
|
| 237 |
|
| 238 |
def _boxes_match(first: dict[str, float], second: dict[str, float]) -> bool:
|
|
@@ -251,169 +296,225 @@ def _boxes_match(first: dict[str, float], second: dict[str, float]) -> bool:
|
|
| 251 |
second_area = max(0.0, second["x_max"] - second["x_min"]) * max(
|
| 252 |
0.0, second["y_max"] - second["y_min"]
|
| 253 |
)
|
| 254 |
-
union = first_area + second_area - intersection
|
| 255 |
-
iou = intersection / union if union > 0.0 else 0.0
|
| 256 |
smaller_area = min(first_area, second_area)
|
| 257 |
containment = intersection / smaller_area if smaller_area > 0.0 else 0.0
|
| 258 |
-
return
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
|
| 261 |
-
def
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
]
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
|
| 272 |
def _run_grounding_dino(image: Image.Image) -> dict[str, Any]:
|
| 273 |
processor = MODEL_DATA["processor"]
|
| 274 |
model = MODEL_DATA["model"]
|
|
|
|
| 275 |
started = time.perf_counter()
|
| 276 |
|
| 277 |
inputs = processor(images=image, text=DETECTION_PROMPT, return_tensors="pt")
|
| 278 |
with torch.inference_mode():
|
| 279 |
outputs = model(**inputs)
|
| 280 |
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
continue
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
{
|
| 302 |
-
"label":
|
| 303 |
-
"
|
| 304 |
-
"
|
| 305 |
-
"score": round(
|
| 306 |
-
"
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
}
|
| 313 |
)
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
item for item in person_detections if item["gender_hint"] == "female"
|
| 319 |
]
|
| 320 |
-
|
| 321 |
-
item for item in
|
|
|
|
|
|
|
|
|
|
| 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 |
-
body_parts = [
|
| 353 |
-
item
|
| 354 |
-
for item in detections
|
| 355 |
-
if item["kind"] == "body_part" and item["score"] >= PART_THRESHOLD
|
| 356 |
-
]
|
| 357 |
-
unassigned_parts: list[dict[str, Any]] = []
|
| 358 |
for part in body_parts:
|
| 359 |
-
|
| 360 |
-
_boxes_match(part["box"], person["box"]) for person in confirmed_females
|
| 361 |
-
)
|
| 362 |
-
inside_male = any(
|
| 363 |
-
_boxes_match(part["box"], person["box"]) for person in confirmed_males
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
if inside_female:
|
| 367 |
part["attribution"] = "female"
|
| 368 |
-
|
|
|
|
| 369 |
part["attribution"] = "male"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
else:
|
| 371 |
-
part["attribution"] = "
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
| 373 |
|
| 374 |
if confirmed_females:
|
| 375 |
decision = "BLOCK"
|
| 376 |
gender = "female"
|
| 377 |
-
reason = "
|
| 378 |
-
elif
|
| 379 |
decision = "BLOCK"
|
| 380 |
-
gender = "
|
| 381 |
-
reason = "
|
| 382 |
elif confirmed_males:
|
| 383 |
decision = "ALLOW"
|
| 384 |
gender = "male"
|
| 385 |
-
reason = "
|
| 386 |
-
elif
|
| 387 |
decision = "ALLOW"
|
| 388 |
-
gender = "
|
| 389 |
-
reason = "
|
| 390 |
else:
|
| 391 |
decision = "ALLOW"
|
| 392 |
-
gender = "
|
| 393 |
-
reason = "
|
| 394 |
|
| 395 |
-
female_score = max((item["
|
| 396 |
-
male_score = max((item["
|
|
|
|
|
|
|
| 397 |
return {
|
| 398 |
"decision": decision,
|
| 399 |
"reason": reason,
|
| 400 |
"gender": gender,
|
| 401 |
"male_score": round(male_score, 4),
|
| 402 |
"female_score": round(female_score, 4),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
"detections": detections,
|
| 404 |
"detection_count": len(detections),
|
| 405 |
"confirmed_male_count": len(confirmed_males),
|
| 406 |
"confirmed_female_count": len(confirmed_females),
|
| 407 |
-
"
|
| 408 |
-
"
|
| 409 |
-
"
|
| 410 |
"top_score": detections[0]["score"] if detections else None,
|
| 411 |
"prompt": DETECTION_PROMPT,
|
| 412 |
-
"
|
| 413 |
-
"
|
| 414 |
-
"class_threshold": CLASS_THRESHOLD,
|
| 415 |
"part_threshold": PART_THRESHOLD,
|
|
|
|
| 416 |
"gender_margin": GENDER_MARGIN,
|
|
|
|
|
|
|
| 417 |
"match_iou_threshold": MATCH_IOU_THRESHOLD,
|
| 418 |
"match_containment_threshold": MATCH_CONTAINMENT_THRESHOLD,
|
| 419 |
"image": {"width": image.width, "height": image.height},
|
|
@@ -437,8 +538,8 @@ async def lifespan(_: FastAPI):
|
|
| 437 |
|
| 438 |
app = FastAPI(
|
| 439 |
title="AI Shield - Grounding DINO Base",
|
| 440 |
-
description="Single-pass female-person and
|
| 441 |
-
version="1.
|
| 442 |
lifespan=lifespan,
|
| 443 |
)
|
| 444 |
|
|
@@ -493,4 +594,4 @@ async def analyze(request: Request) -> dict[str, Any]:
|
|
| 493 |
@app.post("/analyze-file")
|
| 494 |
async def analyze_file(file: UploadFile = File(...)) -> dict[str, Any]:
|
| 495 |
image = await _read_uploaded_image(file)
|
| 496 |
-
return await _analyze_image(image)
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import io
|
| 3 |
import os
|
|
|
|
| 4 |
import socket
|
| 5 |
import time
|
| 6 |
from contextlib import asynccontextmanager
|
|
|
|
| 19 |
|
| 20 |
MODEL_ID = "IDEA-Research/grounding-dino-base"
|
| 21 |
|
| 22 |
+
# Female/male alternatives are deliberately sent together. We read every
|
| 23 |
+
# phrase's tokens ourselves instead of accepting Grounding DINO's merged labels
|
| 24 |
+
# (for example, "female face male face"). This still uses one forward pass.
|
| 25 |
+
PERSON_PHRASES = {
|
| 26 |
+
"female": ("woman", "female person"),
|
| 27 |
+
"male": ("man", "male person"),
|
| 28 |
+
"child": ("young child", "baby", "toddler", "little kid"),
|
| 29 |
+
}
|
| 30 |
+
PART_TYPES = ("face", "hand", "chest", "torso", "arm", "body", "leg", "thigh", "foot")
|
| 31 |
+
|
| 32 |
+
PHRASE_SPECS: list[dict[str, str]] = []
|
| 33 |
+
for phrase in PERSON_PHRASES["female"]:
|
| 34 |
+
PHRASE_SPECS.append({"key": f"person:female:{phrase}", "phrase": phrase})
|
| 35 |
+
for phrase in PERSON_PHRASES["male"]:
|
| 36 |
+
PHRASE_SPECS.append({"key": f"person:male:{phrase}", "phrase": phrase})
|
| 37 |
+
for part_type in PART_TYPES:
|
| 38 |
+
PHRASE_SPECS.append(
|
| 39 |
+
{"key": f"part:{part_type}:female", "phrase": f"female {part_type}"}
|
| 40 |
+
)
|
| 41 |
+
PHRASE_SPECS.append(
|
| 42 |
+
{"key": f"part:{part_type}:male", "phrase": f"male {part_type}"}
|
| 43 |
+
)
|
| 44 |
+
for phrase in PERSON_PHRASES["child"]:
|
| 45 |
+
PHRASE_SPECS.append({"key": f"person:child:{phrase}", "phrase": phrase})
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _make_prompt() -> tuple[str, dict[str, tuple[int, int]]]:
|
| 49 |
+
chunks: list[str] = []
|
| 50 |
+
spans: dict[str, tuple[int, int]] = {}
|
| 51 |
+
cursor = 0
|
| 52 |
+
for spec in PHRASE_SPECS:
|
| 53 |
+
phrase = spec["phrase"]
|
| 54 |
+
spans[spec["key"]] = (cursor, cursor + len(phrase))
|
| 55 |
+
chunk = f"{phrase}. "
|
| 56 |
+
chunks.append(chunk)
|
| 57 |
+
cursor += len(chunk)
|
| 58 |
+
return "".join(chunks).strip(), spans
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
DETECTION_PROMPT, PHRASE_CHAR_SPANS = _make_prompt()
|
| 62 |
+
|
| 63 |
+
# 0.20 keeps weak cropped body parts. Person/child margins prevent a close
|
| 64 |
+
# male/female tie from becoming a confident owner classification.
|
| 65 |
+
CANDIDATE_THRESHOLD = float(os.getenv("CANDIDATE_THRESHOLD", "0.15"))
|
| 66 |
+
PERSON_THRESHOLD = float(os.getenv("PERSON_THRESHOLD", "0.25"))
|
| 67 |
+
PART_THRESHOLD = float(os.getenv("PART_THRESHOLD", "0.20"))
|
| 68 |
+
CHILD_THRESHOLD = float(os.getenv("CHILD_THRESHOLD", "0.25"))
|
| 69 |
+
GENDER_MARGIN = float(os.getenv("GENDER_MARGIN", "0.05"))
|
| 70 |
+
CHILD_MARGIN = float(os.getenv("CHILD_MARGIN", "0.05"))
|
| 71 |
+
NMS_IOU_THRESHOLD = float(os.getenv("NMS_IOU_THRESHOLD", "0.75"))
|
| 72 |
+
MATCH_IOU_THRESHOLD = float(os.getenv("MATCH_IOU_THRESHOLD", "0.25"))
|
| 73 |
MATCH_CONTAINMENT_THRESHOLD = float(os.getenv("MATCH_CONTAINMENT_THRESHOLD", "0.80"))
|
| 74 |
IMAGE_SHORT_EDGE = int(os.getenv("IMAGE_SHORT_EDGE", "512"))
|
| 75 |
IMAGE_LONG_EDGE = int(os.getenv("IMAGE_LONG_EDGE", "768"))
|
|
|
|
| 78 |
REQUEST_TIMEOUT_SECONDS = float(os.getenv("REQUEST_TIMEOUT_SECONDS", "20"))
|
| 79 |
|
| 80 |
for threshold_name, threshold_value in {
|
| 81 |
+
"CANDIDATE_THRESHOLD": CANDIDATE_THRESHOLD,
|
| 82 |
+
"PERSON_THRESHOLD": PERSON_THRESHOLD,
|
|
|
|
| 83 |
"PART_THRESHOLD": PART_THRESHOLD,
|
| 84 |
+
"CHILD_THRESHOLD": CHILD_THRESHOLD,
|
| 85 |
"GENDER_MARGIN": GENDER_MARGIN,
|
| 86 |
+
"CHILD_MARGIN": CHILD_MARGIN,
|
| 87 |
+
"NMS_IOU_THRESHOLD": NMS_IOU_THRESHOLD,
|
| 88 |
"MATCH_IOU_THRESHOLD": MATCH_IOU_THRESHOLD,
|
| 89 |
"MATCH_CONTAINMENT_THRESHOLD": MATCH_CONTAINMENT_THRESHOLD,
|
| 90 |
}.items():
|
|
|
|
| 93 |
if IMAGE_SHORT_EDGE <= 0 or IMAGE_LONG_EDGE < IMAGE_SHORT_EDGE:
|
| 94 |
raise RuntimeError("Invalid image resize configuration")
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
# Avoid CPU oversubscription on the 2-vCPU Space.
|
| 97 |
torch.set_num_threads(max(1, int(os.getenv("TORCH_NUM_THREADS", "2"))))
|
| 98 |
try:
|
|
|
|
| 221 |
print(f"Loading {MODEL_ID} on CPU...")
|
| 222 |
|
| 223 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
|
|
|
| 224 |
if hasattr(processor, "image_processor"):
|
| 225 |
processor.image_processor.size = {
|
| 226 |
"shortest_edge": IMAGE_SHORT_EDGE,
|
|
|
|
| 233 |
low_cpu_mem_usage=True,
|
| 234 |
).eval()
|
| 235 |
|
| 236 |
+
# Extract complete phrase spans ourselves. The stock post-processor may
|
| 237 |
+
# merge alternatives into a label such as "female face male face".
|
| 238 |
+
encoded_prompt = processor.tokenizer(
|
| 239 |
+
DETECTION_PROMPT,
|
| 240 |
+
return_offsets_mapping=True,
|
| 241 |
+
add_special_tokens=True,
|
| 242 |
+
)
|
| 243 |
+
offsets = encoded_prompt["offset_mapping"]
|
| 244 |
+
phrase_token_indices: dict[str, list[int]] = {}
|
| 245 |
+
for key, (phrase_start, phrase_end) in PHRASE_CHAR_SPANS.items():
|
| 246 |
+
token_indices = [
|
| 247 |
+
index
|
| 248 |
+
for index, (token_start, token_end) in enumerate(offsets)
|
| 249 |
+
if token_end > token_start
|
| 250 |
+
and token_start >= phrase_start
|
| 251 |
+
and token_end <= phrase_end
|
| 252 |
+
]
|
| 253 |
+
if not token_indices:
|
| 254 |
+
raise RuntimeError(f"Could not tokenize prompt phrase: {key}")
|
| 255 |
+
phrase_token_indices[key] = token_indices
|
| 256 |
+
|
| 257 |
MODEL_DATA["processor"] = processor
|
| 258 |
MODEL_DATA["model"] = model
|
| 259 |
+
MODEL_DATA["phrase_token_indices"] = phrase_token_indices
|
| 260 |
print(f"Grounding DINO ready in {time.perf_counter() - started:.1f}s")
|
| 261 |
|
| 262 |
|
| 263 |
+
def _box_iou(first: dict[str, float], second: dict[str, float]) -> float:
|
| 264 |
+
intersection_width = max(
|
| 265 |
+
0.0,
|
| 266 |
+
min(first["x_max"], second["x_max"]) - max(first["x_min"], second["x_min"]),
|
| 267 |
+
)
|
| 268 |
+
intersection_height = max(
|
| 269 |
+
0.0,
|
| 270 |
+
min(first["y_max"], second["y_max"]) - max(first["y_min"], second["y_min"]),
|
| 271 |
+
)
|
| 272 |
+
intersection = intersection_width * intersection_height
|
| 273 |
+
first_area = max(0.0, first["x_max"] - first["x_min"]) * max(
|
| 274 |
+
0.0, first["y_max"] - first["y_min"]
|
| 275 |
+
)
|
| 276 |
+
second_area = max(0.0, second["x_max"] - second["x_min"]) * max(
|
| 277 |
+
0.0, second["y_max"] - second["y_min"]
|
| 278 |
+
)
|
| 279 |
+
union = first_area + second_area - intersection
|
| 280 |
+
return intersection / union if union > 0.0 else 0.0
|
|
|
|
|
|
|
| 281 |
|
| 282 |
|
| 283 |
def _boxes_match(first: dict[str, float], second: dict[str, float]) -> bool:
|
|
|
|
| 296 |
second_area = max(0.0, second["x_max"] - second["x_min"]) * max(
|
| 297 |
0.0, second["y_max"] - second["y_min"]
|
| 298 |
)
|
|
|
|
|
|
|
| 299 |
smaller_area = min(first_area, second_area)
|
| 300 |
containment = intersection / smaller_area if smaller_area > 0.0 else 0.0
|
| 301 |
+
return (
|
| 302 |
+
_box_iou(first, second) >= MATCH_IOU_THRESHOLD
|
| 303 |
+
or containment >= MATCH_CONTAINMENT_THRESHOLD
|
| 304 |
+
)
|
| 305 |
|
| 306 |
|
| 307 |
+
def _nms(detections: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 308 |
+
kept: list[dict[str, Any]] = []
|
| 309 |
+
for detection in sorted(
|
| 310 |
+
detections,
|
| 311 |
+
key=lambda item: (item.get("confirmed", True), item["score"]),
|
| 312 |
+
reverse=True,
|
| 313 |
+
):
|
| 314 |
+
if all(
|
| 315 |
+
_box_iou(detection["box"], existing["box"]) < NMS_IOU_THRESHOLD
|
| 316 |
+
for existing in kept
|
| 317 |
+
):
|
| 318 |
+
kept.append(detection)
|
| 319 |
+
return kept
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _box_from_normalized(
|
| 323 |
+
normalized_box: torch.Tensor, image_width: int, image_height: int
|
| 324 |
+
) -> dict[str, float] | None:
|
| 325 |
+
center_x, center_y, box_width, box_height = [
|
| 326 |
+
float(value) for value in normalized_box.tolist()
|
| 327 |
]
|
| 328 |
+
x_min = max(0.0, min(float(image_width), (center_x - box_width / 2.0) * image_width))
|
| 329 |
+
y_min = max(0.0, min(float(image_height), (center_y - box_height / 2.0) * image_height))
|
| 330 |
+
x_max = max(0.0, min(float(image_width), (center_x + box_width / 2.0) * image_width))
|
| 331 |
+
y_max = max(0.0, min(float(image_height), (center_y + box_height / 2.0) * image_height))
|
| 332 |
+
if x_max <= x_min or y_max <= y_min:
|
| 333 |
+
return None
|
| 334 |
+
return {
|
| 335 |
+
"x_min": round(x_min, 2),
|
| 336 |
+
"y_min": round(y_min, 2),
|
| 337 |
+
"x_max": round(x_max, 2),
|
| 338 |
+
"y_max": round(y_max, 2),
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _max_phrase_score(
|
| 343 |
+
phrase_scores: dict[str, torch.Tensor], keys: list[str], query_index: int
|
| 344 |
+
) -> float:
|
| 345 |
+
return max(float(phrase_scores[key][query_index]) for key in keys)
|
| 346 |
|
| 347 |
|
| 348 |
def _run_grounding_dino(image: Image.Image) -> dict[str, Any]:
|
| 349 |
processor = MODEL_DATA["processor"]
|
| 350 |
model = MODEL_DATA["model"]
|
| 351 |
+
phrase_token_indices = MODEL_DATA["phrase_token_indices"]
|
| 352 |
started = time.perf_counter()
|
| 353 |
|
| 354 |
inputs = processor(images=image, text=DETECTION_PROMPT, return_tensors="pt")
|
| 355 |
with torch.inference_mode():
|
| 356 |
outputs = model(**inputs)
|
| 357 |
|
| 358 |
+
logits = outputs.logits[0].sigmoid()
|
| 359 |
+
normalized_boxes = outputs.pred_boxes[0]
|
| 360 |
+
pixel_boxes = [
|
| 361 |
+
_box_from_normalized(box, image.width, image.height) for box in normalized_boxes
|
| 362 |
+
]
|
| 363 |
+
phrase_scores = {
|
| 364 |
+
key: logits[:, token_indices].mean(dim=1)
|
| 365 |
+
for key, token_indices in phrase_token_indices.items()
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
person_keys = {
|
| 369 |
+
gender: [f"person:{gender}:{phrase}" for phrase in phrases]
|
| 370 |
+
for gender, phrases in PERSON_PHRASES.items()
|
| 371 |
+
}
|
| 372 |
+
person_candidates: list[dict[str, Any]] = []
|
| 373 |
+
for query_index in range(normalized_boxes.shape[0]):
|
| 374 |
+
scores = {
|
| 375 |
+
gender: _max_phrase_score(phrase_scores, keys, query_index)
|
| 376 |
+
for gender, keys in person_keys.items()
|
| 377 |
+
}
|
| 378 |
+
score = max(scores.values())
|
| 379 |
+
if score < CANDIDATE_THRESHOLD:
|
| 380 |
+
continue
|
| 381 |
+
box = pixel_boxes[query_index]
|
| 382 |
+
if box is None:
|
| 383 |
continue
|
| 384 |
|
| 385 |
+
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
|
| 386 |
+
winner, winner_score = ranked[0]
|
| 387 |
+
runner_up_score = ranked[1][1]
|
| 388 |
+
required_threshold = CHILD_THRESHOLD if winner == "child" else PERSON_THRESHOLD
|
| 389 |
+
required_margin = CHILD_MARGIN if winner == "child" else GENDER_MARGIN
|
| 390 |
+
confirmed = (
|
| 391 |
+
winner_score >= required_threshold
|
| 392 |
+
and winner_score - runner_up_score >= required_margin
|
| 393 |
+
)
|
| 394 |
+
person_candidates.append(
|
| 395 |
{
|
| 396 |
+
"label": winner if confirmed else "ambiguous person",
|
| 397 |
+
"kind": "person",
|
| 398 |
+
"gender": winner if confirmed else "ambiguous",
|
| 399 |
+
"score": round(winner_score, 4),
|
| 400 |
+
"female_score": round(scores["female"], 4),
|
| 401 |
+
"male_score": round(scores["male"], 4),
|
| 402 |
+
"child_score": round(scores["child"], 4),
|
| 403 |
+
"score_margin": round(winner_score - runner_up_score, 4),
|
| 404 |
+
"confirmed": confirmed,
|
| 405 |
+
"box": box,
|
| 406 |
}
|
| 407 |
)
|
| 408 |
|
| 409 |
+
persons = _nms(person_candidates)
|
| 410 |
+
confirmed_females = [
|
| 411 |
+
item for item in persons if item["confirmed"] and item["gender"] == "female"
|
|
|
|
| 412 |
]
|
| 413 |
+
confirmed_males = [
|
| 414 |
+
item for item in persons if item["confirmed"] and item["gender"] == "male"
|
| 415 |
+
]
|
| 416 |
+
confirmed_children = [
|
| 417 |
+
item for item in persons if item["confirmed"] and item["gender"] == "child"
|
| 418 |
]
|
| 419 |
|
| 420 |
+
body_parts: list[dict[str, Any]] = []
|
| 421 |
+
for part_type in PART_TYPES:
|
| 422 |
+
female_key = f"part:{part_type}:female"
|
| 423 |
+
male_key = f"part:{part_type}:male"
|
| 424 |
+
part_candidates: list[dict[str, Any]] = []
|
| 425 |
+
for query_index in range(normalized_boxes.shape[0]):
|
| 426 |
+
female_score = float(phrase_scores[female_key][query_index])
|
| 427 |
+
male_score = float(phrase_scores[male_key][query_index])
|
| 428 |
+
score = max(female_score, male_score)
|
| 429 |
+
if score < PART_THRESHOLD:
|
| 430 |
+
continue
|
| 431 |
+
box = pixel_boxes[query_index]
|
| 432 |
+
if box is None:
|
| 433 |
+
continue
|
| 434 |
+
raw_gender = "female" if female_score >= male_score else "male"
|
| 435 |
+
part_candidates.append(
|
| 436 |
+
{
|
| 437 |
+
"label": f"{raw_gender} {part_type}",
|
| 438 |
+
"kind": "body_part",
|
| 439 |
+
"part": part_type,
|
| 440 |
+
"raw_gender": raw_gender,
|
| 441 |
+
"score": round(score, 4),
|
| 442 |
+
"female_score": round(female_score, 4),
|
| 443 |
+
"male_score": round(male_score, 4),
|
| 444 |
+
"score_margin": round(abs(female_score - male_score), 4),
|
| 445 |
+
"box": box,
|
| 446 |
+
}
|
| 447 |
+
)
|
| 448 |
+
body_parts.extend(_nms(part_candidates))
|
| 449 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
for part in body_parts:
|
| 451 |
+
if any(_boxes_match(part["box"], owner["box"]) for owner in confirmed_females):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
part["attribution"] = "female"
|
| 453 |
+
part["attribution_source"] = "female_person_box"
|
| 454 |
+
elif any(_boxes_match(part["box"], owner["box"]) for owner in confirmed_males):
|
| 455 |
part["attribution"] = "male"
|
| 456 |
+
part["attribution_source"] = "male_person_box"
|
| 457 |
+
elif any(_boxes_match(part["box"], owner["box"]) for owner in confirmed_children):
|
| 458 |
+
part["attribution"] = "child"
|
| 459 |
+
part["attribution_source"] = "young_child_box"
|
| 460 |
else:
|
| 461 |
+
part["attribution"] = part["raw_gender"]
|
| 462 |
+
part["attribution_source"] = "contrastive_part_score"
|
| 463 |
+
|
| 464 |
+
body_parts.sort(key=lambda item: item["score"], reverse=True)
|
| 465 |
+
female_parts = [item for item in body_parts if item["attribution"] == "female"]
|
| 466 |
|
| 467 |
if confirmed_females:
|
| 468 |
decision = "BLOCK"
|
| 469 |
gender = "female"
|
| 470 |
+
reason = "confirmed_female_person"
|
| 471 |
+
elif female_parts:
|
| 472 |
decision = "BLOCK"
|
| 473 |
+
gender = "female_part"
|
| 474 |
+
reason = "confirmed_or_contrastive_female_body_part"
|
| 475 |
elif confirmed_males:
|
| 476 |
decision = "ALLOW"
|
| 477 |
gender = "male"
|
| 478 |
+
reason = "male_won_and_no_female_evidence"
|
| 479 |
+
elif confirmed_children:
|
| 480 |
decision = "ALLOW"
|
| 481 |
+
gender = "young_child"
|
| 482 |
+
reason = "young_child_won_and_no_female_evidence"
|
| 483 |
else:
|
| 484 |
decision = "ALLOW"
|
| 485 |
+
gender = "none_or_uncertain"
|
| 486 |
+
reason = "no_female_person_or_female_body_part"
|
| 487 |
|
| 488 |
+
female_score = max((item["female_score"] for item in persons), default=0.0)
|
| 489 |
+
male_score = max((item["male_score"] for item in persons), default=0.0)
|
| 490 |
+
child_score = max((item["child_score"] for item in persons), default=0.0)
|
| 491 |
+
detections = sorted(persons + body_parts, key=lambda item: item["score"], reverse=True)
|
| 492 |
return {
|
| 493 |
"decision": decision,
|
| 494 |
"reason": reason,
|
| 495 |
"gender": gender,
|
| 496 |
"male_score": round(male_score, 4),
|
| 497 |
"female_score": round(female_score, 4),
|
| 498 |
+
"child_score": round(child_score, 4),
|
| 499 |
+
"persons": persons,
|
| 500 |
+
"body_parts": body_parts,
|
| 501 |
+
"female_evidence": confirmed_females + female_parts,
|
| 502 |
"detections": detections,
|
| 503 |
"detection_count": len(detections),
|
| 504 |
"confirmed_male_count": len(confirmed_males),
|
| 505 |
"confirmed_female_count": len(confirmed_females),
|
| 506 |
+
"confirmed_child_count": len(confirmed_children),
|
| 507 |
+
"body_part_count": len(body_parts),
|
| 508 |
+
"female_body_part_count": len(female_parts),
|
| 509 |
"top_score": detections[0]["score"] if detections else None,
|
| 510 |
"prompt": DETECTION_PROMPT,
|
| 511 |
+
"candidate_threshold": CANDIDATE_THRESHOLD,
|
| 512 |
+
"person_threshold": PERSON_THRESHOLD,
|
|
|
|
| 513 |
"part_threshold": PART_THRESHOLD,
|
| 514 |
+
"child_threshold": CHILD_THRESHOLD,
|
| 515 |
"gender_margin": GENDER_MARGIN,
|
| 516 |
+
"child_margin": CHILD_MARGIN,
|
| 517 |
+
"nms_iou_threshold": NMS_IOU_THRESHOLD,
|
| 518 |
"match_iou_threshold": MATCH_IOU_THRESHOLD,
|
| 519 |
"match_containment_threshold": MATCH_CONTAINMENT_THRESHOLD,
|
| 520 |
"image": {"width": image.width, "height": image.height},
|
|
|
|
| 538 |
|
| 539 |
app = FastAPI(
|
| 540 |
title="AI Shield - Grounding DINO Base",
|
| 541 |
+
description="Single-pass contrastive female-person and female body-part detector",
|
| 542 |
+
version="1.3.0",
|
| 543 |
lifespan=lifespan,
|
| 544 |
)
|
| 545 |
|
|
|
|
| 594 |
@app.post("/analyze-file")
|
| 595 |
async def analyze_file(file: UploadFile = File(...)) -> dict[str, Any]:
|
| 596 |
image = await _read_uploaded_image(file)
|
| 597 |
+
return await _analyze_image(image)
|