webolavo commited on
Commit
d09a28f
·
verified ·
1 Parent(s): f74ad4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -161
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
- # One balanced prompt keeps the API to a single model forward pass. Generic
24
- # body parts are attributed spatially to confirmed male/female person boxes.
25
- DEFAULT_PROMPT = (
26
- "adult man. adult woman. boy. girl. human face. human body. "
27
- "human arm. human hand. human leg. human foot."
28
- )
29
- DETECTION_PROMPT = os.getenv("DETECTION_PROMPT", DEFAULT_PROMPT).strip().lower()
30
- if not DETECTION_PROMPT.endswith("."):
31
- DETECTION_PROMPT += "."
32
-
33
- # Low candidate thresholds retain competing labels. CLASS_THRESHOLD and
34
- # GENDER_MARGIN make the final decision after male/female comparison.
35
- CANDIDATE_BOX_THRESHOLD = float(os.getenv("CANDIDATE_BOX_THRESHOLD", "0.10"))
36
- CANDIDATE_TEXT_THRESHOLD = float(os.getenv("CANDIDATE_TEXT_THRESHOLD", "0.10"))
37
- CLASS_THRESHOLD = float(os.getenv("CLASS_THRESHOLD", "0.30"))
38
- PART_THRESHOLD = float(os.getenv("PART_THRESHOLD", "0.30"))
39
- GENDER_MARGIN = float(os.getenv("GENDER_MARGIN", "0.10"))
40
- MATCH_IOU_THRESHOLD = float(os.getenv("MATCH_IOU_THRESHOLD", "0.45"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- "CANDIDATE_BOX_THRESHOLD": CANDIDATE_BOX_THRESHOLD,
50
- "CANDIDATE_TEXT_THRESHOLD": CANDIDATE_TEXT_THRESHOLD,
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 _label_gender(label: str) -> str:
217
- words = set(re.findall(r"[a-z]+", label.lower()))
218
- has_female = bool(words & {"woman", "girl", "female"})
219
- has_male = bool(words & {"man", "boy", "male"})
220
- if has_female and not has_male:
221
- return "female"
222
- if has_male and not has_female:
223
- return "male"
224
- return "ambiguous"
225
-
226
-
227
- def _label_kind(label: str) -> str:
228
- words = set(re.findall(r"[a-z]+", label.lower()))
229
- # A merged label such as "boy human body" remains a body part and cannot
230
- # become a trusted male owner box by itself.
231
- if words & {"face", "body", "arm", "hand", "leg", "foot"}:
232
- return "body_part"
233
- if words & {"man", "woman", "boy", "girl"}:
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 iou >= MATCH_IOU_THRESHOLD or containment >= MATCH_CONTAINMENT_THRESHOLD
 
 
 
259
 
260
 
261
- def _best_overlapping_score(
262
- detection: dict[str, Any], opposite_detections: list[dict[str, Any]]
263
- ) -> float:
264
- scores = [
265
- opposite["score"]
266
- for opposite in opposite_detections
267
- if _boxes_match(detection["box"], opposite["box"])
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  ]
269
- return max(scores, default=0.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- result = processor.post_process_grounded_object_detection(
282
- outputs,
283
- inputs.input_ids,
284
- box_threshold=CANDIDATE_BOX_THRESHOLD,
285
- text_threshold=CANDIDATE_TEXT_THRESHOLD,
286
- target_sizes=[(image.height, image.width)],
287
- )[0]
288
-
289
- detections: list[dict[str, Any]] = []
290
- for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
291
- raw_x_min, raw_y_min, raw_x_max, raw_y_max = [float(value) for value in box.tolist()]
292
- x_min = round(max(0.0, min(float(image.width), raw_x_min)), 2)
293
- y_min = round(max(0.0, min(float(image.height), raw_y_min)), 2)
294
- x_max = round(max(0.0, min(float(image.width), raw_x_max)), 2)
295
- y_max = round(max(0.0, min(float(image.height), raw_y_max)), 2)
296
- if x_max <= x_min or y_max <= y_min:
 
 
 
 
 
 
 
 
 
297
  continue
298
 
299
- label_text = str(label)
300
- detections.append(
 
 
 
 
 
 
 
 
301
  {
302
- "label": label_text,
303
- "gender_hint": _label_gender(label_text),
304
- "kind": _label_kind(label_text),
305
- "score": round(float(score), 4),
306
- "box": {
307
- "x_min": x_min,
308
- "y_min": y_min,
309
- "x_max": x_max,
310
- "y_max": y_max,
311
- },
312
  }
313
  )
314
 
315
- detections.sort(key=lambda item: item["score"], reverse=True)
316
- person_detections = [item for item in detections if item["kind"] == "person"]
317
- female_detections = [
318
- item for item in person_detections if item["gender_hint"] == "female"
319
  ]
320
- male_detections = [
321
- item for item in person_detections if item["gender_hint"] == "male"
 
 
 
322
  ]
323
 
324
- for detection in detections:
325
- if detection["kind"] != "person":
326
- detection["opposing_score"] = None
327
- detection["score_margin"] = None
328
- detection["confirmed"] = False
329
- elif detection["gender_hint"] == "female":
330
- opposing_score = _best_overlapping_score(detection, male_detections)
331
- elif detection["gender_hint"] == "male":
332
- opposing_score = _best_overlapping_score(detection, female_detections)
333
- else:
334
- detection["opposing_score"] = None
335
- detection["score_margin"] = None
336
- detection["confirmed"] = False
337
- continue
338
-
339
- if detection["kind"] != "person":
340
- continue
341
-
342
- score_margin = detection["score"] - opposing_score
343
- detection["opposing_score"] = round(opposing_score, 4)
344
- detection["score_margin"] = round(score_margin, 4)
345
- detection["confirmed"] = (
346
- detection["score"] >= CLASS_THRESHOLD and score_margin >= GENDER_MARGIN
347
- )
348
-
349
- confirmed_females = [item for item in female_detections if item["confirmed"]]
350
- confirmed_males = [item for item in male_detections if item["confirmed"]]
 
 
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
- inside_female = any(
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
- elif inside_male:
 
369
  part["attribution"] = "male"
 
 
 
 
370
  else:
371
- part["attribution"] = "unassigned"
372
- unassigned_parts.append(part)
 
 
 
373
 
374
  if confirmed_females:
375
  decision = "BLOCK"
376
  gender = "female"
377
- reason = "female_detection_won_comparison"
378
- elif unassigned_parts:
379
  decision = "BLOCK"
380
- gender = "unknown_body_part"
381
- reason = "human_body_part_not_attributed_to_confirmed_male"
382
  elif confirmed_males:
383
  decision = "ALLOW"
384
  gender = "male"
385
- reason = "only_confirmed_male_and_attributed_parts"
386
- elif any(item["score"] >= CLASS_THRESHOLD for item in person_detections):
387
  decision = "ALLOW"
388
- gender = "uncertain"
389
- reason = "no_confirmed_female_or_unassigned_body_part"
390
  else:
391
  decision = "ALLOW"
392
- gender = "none"
393
- reason = "no_female_person_or_human_body_part_detected"
394
 
395
- female_score = max((item["score"] for item in female_detections), default=0.0)
396
- male_score = max((item["score"] for item in male_detections), default=0.0)
 
 
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
- "strong_body_part_count": len(body_parts),
408
- "unassigned_body_part_count": len(unassigned_parts),
409
- "unassigned_body_parts": unassigned_parts,
410
  "top_score": detections[0]["score"] if detections else None,
411
  "prompt": DETECTION_PROMPT,
412
- "candidate_box_threshold": CANDIDATE_BOX_THRESHOLD,
413
- "candidate_text_threshold": CANDIDATE_TEXT_THRESHOLD,
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 unassigned human body-part detector",
441
- version="1.2.0",
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)