Spaces:
Running on Zero

clementBE commited on
Commit
d85699f
Β·
verified Β·
1 Parent(s): dc37c6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2489 -478
app.py CHANGED
@@ -26,25 +26,52 @@ from transformers import pipeline
26
 
27
  APP_TITLE = "Image Object, Face & Manual Coding Analysis"
28
 
 
 
29
  # YOLO
30
- YOLO_MODEL_NAME = "yolov8s.pt" # yolov8n.pt = faster, yolov8s.pt = better
 
 
31
  OBJECT_CONFIDENCE = 0.25
32
  IOU_THRESHOLD = 0.45
33
  MAX_OBJECTS_PER_IMAGE = 50
34
  MAX_FACES_PER_IMAGE = 30
35
 
36
- # Automatic perceived-gender classifier (first pass only, validate manually!)
 
 
 
 
37
  GENDER_MODEL_NAME = "dima806/fairface_gender_image_detection"
38
- GENDER_MIN_CONFIDENCE = 0.70 # below this -> "uncertain"
39
- MIN_FACE_PIXELS_FOR_GENDER = 40 # smaller faces -> "uncertain"
40
- GENDER_CROP_MARGIN = 0.15 # context added around face crop
41
 
 
 
42
  # Images
43
- IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
 
 
 
 
 
 
 
 
 
 
 
44
  THUMBNAIL_SIZE = (500, 500)
 
45
  MAX_OBJECT_CROPS = 150
46
  MAX_FACE_CROPS = 150
47
 
 
 
 
 
 
48
  FACE_COLUMNS_MANUAL = [
49
  "face_id",
50
  "filename",
@@ -63,6 +90,7 @@ FACE_COLUMNS_MANUAL = [
63
  "manual_notes",
64
  ]
65
 
 
66
  FACE_COLUMNS_ALL = [
67
  "filename",
68
  "relative_path",
@@ -71,8 +99,12 @@ FACE_COLUMNS_ALL = [
71
  "face_index",
72
  "face_id",
73
  "confidence",
74
- "x1", "y1", "x2", "y2",
75
- "width", "height",
 
 
 
 
76
  "area_pixels",
77
  "area_fraction",
78
  "horizontal_position",
@@ -85,11 +117,22 @@ FACE_COLUMNS_ALL = [
85
  "manual_notes",
86
  ]
87
 
 
88
  OBJECT_COLUMNS = [
89
- "filename", "relative_path", "category", "subcategory",
90
- "object", "confidence",
91
- "x1", "y1", "x2", "y2",
92
- "width", "height", "area_pixels", "area_fraction",
 
 
 
 
 
 
 
 
 
 
93
  ]
94
 
95
 
@@ -105,8 +148,10 @@ print("=" * 70)
105
  print("PyTorch:", torch.__version__)
106
  print("CUDA:", torch.cuda.is_available())
107
  print("Device:", DEVICE)
 
108
  if torch.cuda.is_available():
109
  print("GPU:", torch.cuda.get_device_name(0))
 
110
  print("=" * 70)
111
 
112
 
@@ -115,15 +160,20 @@ print("=" * 70)
115
  # ============================================================
116
 
117
  print("Loading YOLO...")
 
118
  yolo_model = YOLO(YOLO_MODEL_NAME)
 
119
  if DEVICE == "cuda":
120
  try:
121
  yolo_model.to("cuda")
122
  except Exception as e:
123
  print("Could not explicitly move YOLO to CUDA:", e)
 
124
  print("YOLO loaded.")
125
 
 
126
  print("Loading MTCNN...")
 
127
  mtcnn = MTCNN(
128
  image_size=160,
129
  margin=20,
@@ -134,14 +184,18 @@ mtcnn = MTCNN(
134
  keep_all=True,
135
  device=DEVICE,
136
  )
 
137
  print("MTCNN loaded.")
138
 
 
139
  print("Loading gender classifier...")
 
140
  gender_classifier = pipeline(
141
  "image-classification",
142
  model=GENDER_MODEL_NAME,
143
  device=0 if DEVICE == "cuda" else -1,
144
  )
 
145
  print("Gender classifier loaded.")
146
 
147
 
@@ -150,61 +204,120 @@ print("Gender classifier loaded.")
150
  # ============================================================
151
 
152
  def safe_open_image(path):
 
153
  try:
154
  with Image.open(path) as img:
 
155
  img = ImageOps.exif_transpose(img)
 
156
  return img.convert("RGB")
 
157
  except Exception as e:
 
158
  print(f"Could not open {path}: {e}")
 
159
  return None
160
 
161
 
162
  def create_thumbnail(image, max_size=THUMBNAIL_SIZE):
 
163
  img = image.copy()
 
164
  img.thumbnail(max_size)
 
165
  return img
166
 
167
 
168
  def list_images_recursive(root):
 
169
  images = []
 
170
  for current_root, _dirs, files in os.walk(root):
 
171
  for filename in files:
 
172
  if Path(filename).suffix.lower() in IMAGE_EXTENSIONS:
173
- images.append(os.path.join(current_root, filename))
 
 
 
 
174
  return sorted(images)
175
 
176
 
177
  def get_category_info(image_path, extraction_root):
178
- relative = os.path.relpath(image_path, extraction_root)
 
 
 
 
 
179
  parts = Path(relative).parts
180
- category = parts[0] if len(parts) >= 2 else "ROOT"
181
- subcategory = parts[1] if len(parts) >= 3 else ""
 
 
 
 
 
 
 
 
 
 
 
182
  return category, subcategory
183
 
184
 
185
- def get_box_position(x1, y1, x2, y2, image_width, image_height):
 
 
 
 
 
 
 
 
186
  cx = (x1 + x2) / 2 / image_width
187
  cy = (y1 + y2) / 2 / image_height
188
 
189
  if cx < 0.333:
 
190
  horizontal = "left"
 
191
  elif cx < 0.666:
 
192
  horizontal = "center"
 
193
  else:
 
194
  horizontal = "right"
195
 
 
196
  if cy < 0.333:
 
197
  vertical = "top"
 
198
  elif cy < 0.666:
 
199
  vertical = "middle"
 
200
  else:
 
201
  vertical = "bottom"
202
 
 
203
  return horizontal, vertical
204
 
205
 
206
- def clamp_box(box, image_width, image_height):
 
 
 
 
 
207
  x1, y1, x2, y2 = box
 
208
  return (
209
  max(0, int(x1)),
210
  max(0, int(y1)),
@@ -213,12 +326,34 @@ def clamp_box(box, image_width, image_height):
213
  )
214
 
215
 
216
- def draw_label(draw, xy, text, color):
 
 
 
 
 
 
217
  try:
218
- draw.rectangle(draw.textbbox(xy, text), fill=color)
 
 
 
 
 
 
 
 
 
 
219
  except Exception:
 
220
  pass
221
- draw.text(xy, text, fill="white")
 
 
 
 
 
222
 
223
 
224
  # ============================================================
@@ -226,29 +361,65 @@ def draw_label(draw, xy, text, color):
226
  # ============================================================
227
 
228
  def classify_gender(face_image):
 
229
  """
230
- Returns (label, confidence) for one face crop.
 
 
 
 
 
231
 
232
- The label is an automatic guess of PERCEIVED gender presentation
233
- from appearance. It is not gender identity. Low-confidence or very
234
- small faces are labelled "uncertain".
 
235
  """
 
236
  try:
 
237
  w, h = face_image.size
 
238
  if min(w, h) < MIN_FACE_PIXELS_FOR_GENDER:
 
239
  return "uncertain", None
240
 
241
- predictions = gender_classifier(face_image)
242
- best = max(predictions, key=lambda p: p["score"])
243
- score = float(best["score"])
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  if score < GENDER_MIN_CONFIDENCE:
246
- return "uncertain", round(score, 4)
247
 
248
- return str(best["label"]).lower(), round(score, 4)
 
 
 
 
 
 
 
 
 
 
249
 
250
  except Exception as e:
251
- print("Gender error:", repr(e))
 
 
 
 
 
252
  return "uncertain", None
253
 
254
 
@@ -258,64 +429,163 @@ def classify_gender(face_image):
258
 
259
  @spaces.GPU
260
  def detect_objects(image):
 
261
  if image is None:
 
262
  return [], image
263
 
 
264
  try:
 
265
  results = yolo_model.predict(
266
  source=np.array(image),
267
  conf=OBJECT_CONFIDENCE,
268
  iou=IOU_THRESHOLD,
269
- device=0 if DEVICE == "cuda" else "cpu",
 
 
 
 
270
  verbose=False,
271
  )
272
 
 
273
  if not results:
 
274
  return [], image
275
 
 
276
  result = results[0]
 
277
  names = result.names
 
278
  detections = []
 
279
  annotated = image.copy()
280
- draw = ImageDraw.Draw(annotated)
 
 
 
 
281
  image_width, image_height = image.size
282
 
 
283
  if result.boxes is None:
 
284
  return [], annotated
285
 
 
286
  boxes = result.boxes
287
- image_area = image_width * image_height
288
 
289
- for i in range(min(len(boxes), MAX_OBJECTS_PER_IMAGE)):
290
- cls_id = int(boxes.cls[i].item())
291
- confidence = float(boxes.conf[i].item())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  x1, y1, x2, y2 = clamp_box(
293
- boxes.xyxy[i].tolist(), image_width, image_height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  )
295
 
296
- box_width = max(0, x2 - x1)
297
- box_height = max(0, y2 - y1)
298
- area_pixels = box_width * box_height
299
- area_fraction = area_pixels / image_area if image_area > 0 else 0
300
- object_name = names.get(cls_id, str(cls_id))
301
 
302
  detections.append({
 
303
  "object": object_name,
304
- "confidence": round(confidence, 4),
305
- "x1": x1, "y1": y1, "x2": x2, "y2": y2,
 
 
 
 
 
 
 
 
 
306
  "width": box_width,
307
  "height": box_height,
 
308
  "area_pixels": area_pixels,
309
- "area_fraction": round(area_fraction, 6),
 
 
 
 
 
310
  })
311
 
312
- draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
313
- draw_label(draw, (x1, y1), f"{object_name} {confidence:.2f}", "red")
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  return detections, annotated
316
 
 
317
  except Exception as e:
318
- print("YOLO error:", repr(e))
 
 
 
 
 
319
  return [], image
320
 
321
 
@@ -325,188 +595,573 @@ def detect_objects(image):
325
 
326
  @spaces.GPU
327
  def detect_faces(image):
 
328
  """
329
- Detects faces and their locations, and adds an automatic
330
- perceived-gender guess (to be validated against manual coding).
 
 
 
 
 
331
  No age or identity inference.
332
  """
 
333
  if image is None:
 
334
  return [], image, []
335
 
 
336
  try:
337
- boxes, probabilities = mtcnn.detect(np.array(image))
 
 
 
 
338
 
339
  detections = []
 
340
  annotated = image.copy()
341
- draw = ImageDraw.Draw(annotated)
 
 
 
 
342
  face_crops = []
343
 
 
344
  if boxes is None:
 
345
  return [], annotated, []
346
 
 
347
  image_width, image_height = image.size
348
- image_area = image_width * image_height
 
 
 
 
 
349
 
350
  for i, box in enumerate(boxes):
 
351
  if i >= MAX_FACES_PER_IMAGE:
 
352
  break
353
 
354
- x1, y1, x2, y2 = clamp_box(box.tolist(), image_width, image_height)
 
 
 
 
 
 
355
 
356
  if x2 <= x1 or y2 <= y1:
 
357
  continue
358
 
 
359
  probability = (
360
- float(probabilities[i]) if probabilities is not None else np.nan
 
 
 
 
 
 
361
  )
362
 
 
363
  box_width = x2 - x1
 
364
  box_height = y2 - y1
365
- area_pixels = box_width * box_height
366
- area_fraction = area_pixels / image_area if image_area > 0 else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
  horizontal, vertical = get_box_position(
369
- x1, y1, x2, y2, image_width, image_height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  )
371
 
372
- face_id = f"face_{i + 1:03d}"
373
 
374
- # ---- Automatic perceived gender (crop with margin) ----
375
- margin = int(GENDER_CROP_MARGIN * max(box_width, box_height))
376
- gender_crop = image.crop((
377
- max(0, x1 - margin),
378
- max(0, y1 - margin),
379
- min(image_width, x2 + margin),
380
- min(image_height, y2 + margin),
381
- ))
382
- auto_gender, auto_gender_conf = classify_gender(gender_crop)
383
 
384
  detections.append({
 
385
  "face_index": i + 1,
 
386
  "face_id": face_id,
 
387
  "confidence": (
388
- round(probability, 4) if not np.isnan(probability) else None
 
 
 
 
 
 
 
 
 
389
  ),
390
- "x1": x1, "y1": y1, "x2": x2, "y2": y2,
 
 
 
 
 
391
  "width": box_width,
392
  "height": box_height,
 
393
  "area_pixels": area_pixels,
394
- "area_fraction": round(area_fraction, 6),
 
 
 
 
 
395
  "horizontal_position": horizontal,
 
396
  "vertical_position": vertical,
397
 
398
- # Automatic first-pass prediction
399
  "auto_perceived_gender": auto_gender,
 
400
  "auto_gender_confidence": auto_gender_conf,
401
 
402
- # Manual coding fields (intentionally blank)
403
  "manual_gender": "",
 
404
  "manual_age": "",
 
405
  "manual_age_group": "",
 
406
  "manual_notes": "",
 
407
  })
408
 
409
- # ---- Face crop for gallery ----
410
- crop = create_thumbnail(image.crop((x1, y1, x2, y2)), (300, 300))
411
- prob_text = f"{probability:.2f}" if not np.isnan(probability) else "n/a"
412
- face_crops.append((crop, f"{face_id} | {prob_text} | {auto_gender}"))
413
 
414
- # ---- Draw face ----
415
- draw.rectangle([x1, y1, x2, y2], outline="blue", width=4)
416
- draw_label(draw, (x1, y1), f"{face_id} {prob_text}", "blue")
417
 
418
- return detections, annotated, face_crops
 
 
 
 
 
 
 
 
 
 
419
 
420
- except Exception as e:
421
- print("MTCNN error:", repr(e))
422
- return [], image, []
423
 
 
424
 
425
- # ============================================================
426
- # OBJECT CROPS
427
- # ============================================================
428
 
429
- def create_object_crops(image, detections):
430
- crops = []
431
 
432
- for d in detections:
433
- x1, y1, x2, y2 = d["x1"], d["y1"], d["x2"], d["y2"]
434
- if x2 <= x1 or y2 <= y1:
435
- continue
436
 
437
- crop = create_thumbnail(image.crop((x1, y1, x2, y2)), (300, 300))
438
- crops.append((crop, f"{d['object']} | {d['confidence']:.2f}"))
439
 
440
- if len(crops) >= MAX_OBJECT_CROPS:
441
- break
442
 
443
- return crops
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
 
445
 
446
  # ============================================================
447
- # PROCESS ONE IMAGE
448
- # ============================================================
 
 
 
 
 
449
 
450
- def process_single_image(image_path, extraction_root):
451
  start = time.time()
452
 
453
- image = safe_open_image(image_path)
 
 
 
 
 
454
  if image is None:
455
- return None, [], [], None, [], [], 0
456
 
457
- filename = os.path.basename(image_path)
458
- relative_path = os.path.relpath(image_path, extraction_root)
459
- category, subcategory = get_category_info(image_path, extraction_root)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  width, height = image.size
461
 
462
- object_detections, _ = detect_objects(image)
463
- face_detections, _, face_crops = detect_faces(image)
464
- object_crops = create_object_crops(image, object_detections)
465
 
466
- # Combined annotation: objects = red, faces = blue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  combined = image.copy()
468
- draw = ImageDraw.Draw(combined)
 
 
 
 
469
 
470
  for d in object_detections:
471
- draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline="red", width=3)
 
 
 
 
 
 
 
 
 
 
 
472
 
473
  for d in face_detections:
474
- draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline="blue", width=4)
475
 
476
- combined = create_thumbnail(combined)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477
 
478
  gender_counts = pd.Series(
479
- [d["auto_perceived_gender"] for d in face_detections], dtype="object"
 
 
 
 
480
  ).value_counts()
481
 
 
 
 
 
 
482
  image_row = {
 
483
  "filename": filename,
 
484
  "relative_path": relative_path,
 
485
  "category": category,
 
486
  "subcategory": subcategory,
 
487
  "width": width,
 
488
  "height": height,
489
- "objects_detected": len(object_detections),
490
- "faces_detected": len(face_detections),
491
- "auto_female_faces": int(gender_counts.get("female", 0)),
492
- "auto_male_faces": int(gender_counts.get("male", 0)),
493
- "auto_uncertain_faces": int(gender_counts.get("uncertain", 0)),
494
- "object_types": ", ".join(sorted({d["object"] for d in object_detections})),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
  "processing_seconds": 0,
 
496
  }
497
 
 
498
  base = {
 
499
  "filename": filename,
 
500
  "relative_path": relative_path,
 
501
  "category": category,
 
502
  "subcategory": subcategory,
 
503
  }
504
 
505
- object_rows = [{**base, **d} for d in object_detections]
506
- face_rows = [{**base, **d} for d in face_detections]
507
 
508
- elapsed = time.time() - start
509
- image_row["processing_seconds"] = round(elapsed, 3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
 
511
  return (
512
  image_row,
@@ -520,399 +1175,1594 @@ def process_single_image(image_path, extraction_root):
520
 
521
 
522
  # ============================================================
523
- # PLOTS
524
  # ============================================================
525
 
526
  def empty_plot(title):
527
- fig, ax = plt.subplots(figsize=(9, 5))
 
 
 
 
528
  ax.set_title(title)
529
- ax.text(0.5, 0.5, "No data available", ha="center", va="center",
530
- transform=ax.transAxes)
 
 
 
 
 
 
 
 
531
  ax.axis("off")
 
532
  return fig
533
 
534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  def plot_top_objects(objects_df):
 
536
  if objects_df.empty:
537
- return empty_plot("Most frequently detected objects")
538
-
539
- counts = objects_df["object"].value_counts().head(20).sort_values()
540
- fig, ax = plt.subplots(figsize=(10, 7))
541
- counts.plot(kind="barh", ax=ax)
542
- ax.set_title("Most frequently detected objects")
543
- ax.set_xlabel("Number of detections")
544
- ax.set_ylabel("Object")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545
  plt.tight_layout()
 
546
  return fig
547
 
548
 
549
  def plot_objects_per_image(images_df):
 
550
  if images_df.empty:
551
- return empty_plot("Objects per image")
552
 
553
- fig, ax = plt.subplots(figsize=(9, 5))
554
- ax.hist(images_df["objects_detected"], bins=20)
555
- ax.set_title("Objects detected per image")
556
- ax.set_xlabel("Number of objects")
557
- ax.set_ylabel("Number of images")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  plt.tight_layout()
 
559
  return fig
560
 
561
 
562
  def plot_objects_by_category(objects_df):
 
563
  if objects_df.empty:
564
- return empty_plot("Objects by category")
565
 
566
- table = pd.crosstab(objects_df["category"], objects_df["object"])
 
 
 
 
 
 
 
 
 
 
567
  if table.empty:
568
- return empty_plot("Objects by category")
569
 
570
- top_objects = objects_df["object"].value_counts().head(12).index
571
- table = table[[x for x in top_objects if x in table.columns]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
 
573
- fig, ax = plt.subplots(figsize=(12, 7))
574
- table.plot(kind="bar", ax=ax)
575
- ax.set_title("Detected objects by ZIP category")
576
- ax.set_xlabel("Category")
577
- ax.set_ylabel("Number of detections")
578
- ax.legend(title="Object", bbox_to_anchor=(1.02, 1), loc="upper left")
579
- plt.tight_layout()
580
- return fig
581
 
 
 
 
582
 
583
- def plot_faces_by_category(faces_df):
584
- if faces_df.empty:
585
- return empty_plot("Face detections by category")
586
-
587
- counts = faces_df.groupby("category").size().sort_values()
588
- fig, ax = plt.subplots(figsize=(10, 6))
589
- counts.plot(kind="barh", ax=ax)
590
- ax.set_title("Face detections by category")
591
- ax.set_xlabel("Number of detected faces")
592
- ax.set_ylabel("Category")
593
- plt.tight_layout()
594
- return fig
595
 
 
 
 
596
 
597
- def plot_faces_per_image(images_df):
598
- if images_df.empty:
599
- return empty_plot("Faces per image")
600
-
601
- fig, ax = plt.subplots(figsize=(9, 5))
602
- max_faces = int(images_df["faces_detected"].max())
603
- ax.hist(images_df["faces_detected"], bins=range(0, max_faces + 2), align="left")
604
- ax.set_title("Detected faces per image")
605
- ax.set_xlabel("Number of faces")
606
- ax.set_ylabel("Number of images")
607
- plt.tight_layout()
608
- return fig
609
 
 
 
 
610
 
611
- def plot_face_position(faces_df):
612
- if faces_df.empty:
613
- return empty_plot("Face position")
614
-
615
- table = pd.crosstab(faces_df["horizontal_position"], faces_df["vertical_position"])
616
- fig, ax = plt.subplots(figsize=(8, 6))
617
- table.plot(kind="bar", ax=ax)
618
- ax.set_title("Detected face positions")
619
- ax.set_xlabel("Horizontal position")
620
- ax.set_ylabel("Number of faces")
621
- ax.legend(title="Vertical position")
622
- plt.tight_layout()
623
- return fig
624
 
625
 
626
- def plot_face_area(faces_df):
627
- if faces_df.empty:
628
- return empty_plot("Face area")
629
 
630
- fig, ax = plt.subplots(figsize=(9, 5))
631
- ax.hist(faces_df["area_fraction"] * 100, bins=20)
632
- ax.set_title("Face size relative to image")
633
- ax.set_xlabel("Face area (% of image)")
634
- ax.set_ylabel("Number of faces")
635
- plt.tight_layout()
636
- return fig
637
 
 
638
 
639
- def plot_gender_by_category(faces_df):
640
- if faces_df.empty:
641
- return empty_plot("Automatically perceived gender by category")
642
-
643
- table = pd.crosstab(faces_df["category"], faces_df["auto_perceived_gender"])
644
- fig, ax = plt.subplots(figsize=(10, 6))
645
- table.plot(kind="bar", stacked=True, ax=ax)
646
- ax.set_title("Automatically perceived gender by category (unvalidated)")
647
- ax.set_xlabel("Category")
648
- ax.set_ylabel("Number of faces")
649
- ax.legend(title="Auto label")
650
- plt.tight_layout()
651
- return fig
652
 
 
653
 
654
- # ============================================================
655
- # EXCEL EXPORT
656
- # ============================================================
657
 
658
- def create_excel(images_df, objects_df, faces_df):
659
- output = io.BytesIO()
660
 
661
- with pd.ExcelWriter(output, engine="openpyxl") as writer:
 
 
662
 
663
- images_df.to_excel(writer, sheet_name="Images", index=False)
664
- objects_df.to_excel(writer, sheet_name="Objects", index=False)
665
- faces_df.to_excel(writer, sheet_name="Faces", index=False)
666
 
667
- # Object summary
668
- if not objects_df.empty:
669
- object_summary = (
670
- objects_df.groupby("object")
671
- .agg(
672
- detections=("object", "size"),
673
- mean_confidence=("confidence", "mean"),
674
- mean_area_fraction=("area_fraction", "mean"),
675
- )
676
- .sort_values("detections", ascending=False)
677
- .reset_index()
678
- )
679
- else:
680
- object_summary = pd.DataFrame()
681
- object_summary.to_excel(writer, sheet_name="Object Summary", index=False)
682
 
683
- # Objects by category
684
- if not objects_df.empty:
685
- objects_by_category = (
686
- pd.crosstab(objects_df["category"], objects_df["object"]).reset_index()
687
- )
688
- else:
689
- objects_by_category = pd.DataFrame()
690
- objects_by_category.to_excel(
691
- writer, sheet_name="Objects by Category", index=False
692
  )
693
 
694
- # Faces by category
695
- if not faces_df.empty:
696
- faces_by_category = (
697
- faces_df.groupby("category").size().reset_index(name="detected_faces")
698
- )
699
- else:
700
- faces_by_category = pd.DataFrame()
701
- faces_by_category.to_excel(writer, sheet_name="Faces by Category", index=False)
702
 
703
- # Face positions
704
- if not faces_df.empty:
705
- face_positions = pd.crosstab(
706
- faces_df["horizontal_position"], faces_df["vertical_position"]
707
- ).reset_index()
708
- else:
709
- face_positions = pd.DataFrame()
710
- face_positions.to_excel(writer, sheet_name="Face Positions", index=False)
711
 
712
- # Auto gender by category
713
- if not faces_df.empty:
714
- gender_by_category = pd.crosstab(
715
- faces_df["category"], faces_df["auto_perceived_gender"]
716
- ).reset_index()
717
- else:
718
- gender_by_category = pd.DataFrame()
719
- gender_by_category.to_excel(
720
- writer, sheet_name="Auto Gender by Category", index=False
721
- )
722
 
723
- # Category summary
724
- if not images_df.empty:
725
- category_summary = (
726
- images_df.groupby("category")
727
- .agg(
728
- images=("filename", "count"),
729
- total_objects=("objects_detected", "sum"),
730
- mean_objects=("objects_detected", "mean"),
731
- total_faces=("faces_detected", "sum"),
732
- mean_faces=("faces_detected", "mean"),
733
- auto_female_faces=("auto_female_faces", "sum"),
734
- auto_male_faces=("auto_male_faces", "sum"),
735
- auto_uncertain_faces=("auto_uncertain_faces", "sum"),
736
- mean_processing_seconds=("processing_seconds", "mean"),
737
- )
738
- .reset_index()
739
- )
740
- else:
741
- category_summary = pd.DataFrame()
742
- category_summary.to_excel(writer, sheet_name="Category Summary", index=False)
743
 
744
- # Manual coding template (auto prediction sits next to manual field)
745
- if not faces_df.empty:
746
- manual_coding = faces_df[FACE_COLUMNS_MANUAL].copy()
747
- else:
748
- manual_coding = pd.DataFrame(columns=FACE_COLUMNS_MANUAL)
749
- manual_coding.to_excel(writer, sheet_name="Manual Coding", index=False)
750
 
751
- # Global summary
752
- summary = pd.DataFrame({
753
- "metric": [
754
- "Images",
755
- "Object detections",
756
- "Unique object classes",
757
- "Face detections",
758
- "Faces auto-labelled female",
759
- "Faces auto-labelled male",
760
- "Faces auto-labelled uncertain",
761
- "Categories",
762
- "Average objects/image",
763
- "Average faces/image",
764
- "Average face area (%)",
765
- ],
766
- "value": [
767
- len(images_df),
768
- len(objects_df),
769
- objects_df["object"].nunique() if not objects_df.empty else 0,
770
- len(faces_df),
771
- int((faces_df["auto_perceived_gender"] == "female").sum())
772
- if not faces_df.empty else 0,
773
- int((faces_df["auto_perceived_gender"] == "male").sum())
774
- if not faces_df.empty else 0,
775
- int((faces_df["auto_perceived_gender"] == "uncertain").sum())
776
- if not faces_df.empty else 0,
777
- images_df["category"].nunique() if not images_df.empty else 0,
778
- images_df["objects_detected"].mean() if not images_df.empty else 0,
779
- images_df["faces_detected"].mean() if not images_df.empty else 0,
780
- faces_df["area_fraction"].mean() * 100 if not faces_df.empty else 0,
781
- ],
782
- })
783
- summary.to_excel(writer, sheet_name="Summary", index=False)
784
 
785
- output.seek(0)
786
- return output
787
 
 
788
 
789
- # ============================================================
790
- # MAIN ZIP ANALYSIS
791
- # ============================================================
792
 
793
- @spaces.GPU
794
- def analyze_zip(zip_file, progress=gr.Progress()):
795
 
796
- if zip_file is None:
797
- raise gr.Error("Please upload a ZIP file.")
798
 
799
- start_total = time.time()
800
- temp_dir = tempfile.mkdtemp(prefix="image_analysis_")
801
 
802
- try:
803
- progress(0.02, desc="Extracting ZIP...")
804
 
805
- zip_path = zip_file if isinstance(zip_file, str) else zip_file.name
806
 
807
- with zipfile.ZipFile(zip_path, "r") as archive:
808
- archive.extractall(temp_dir)
 
809
 
810
- image_paths = list_images_recursive(temp_dir)
811
 
812
- if not image_paths:
813
- raise gr.Error("No supported images were found.")
814
 
815
- total = len(image_paths)
816
- print(f"Found {total} images.")
817
 
818
- image_rows = []
819
- object_rows = []
820
- face_rows = []
821
- annotated_gallery = []
822
- object_gallery = []
823
- face_gallery = []
824
 
825
- for index, image_path in enumerate(image_paths):
826
 
827
- progress(
828
- 0.05 + 0.75 * (index / total),
829
- desc=f"Processing {index + 1}/{total}",
830
- )
831
 
832
- (
833
- image_row,
834
- image_objects,
835
- image_faces,
836
- annotated,
837
- object_crops,
838
- face_crops,
839
- _elapsed,
840
- ) = process_single_image(image_path, temp_dir)
841
 
842
- if image_row is None:
843
- continue
844
 
845
- image_rows.append(image_row)
846
- object_rows.extend(image_objects)
847
- face_rows.extend(image_faces)
848
 
849
- annotated_gallery.append((annotated, os.path.basename(image_path)))
850
 
851
- for crop, label in object_crops:
852
- if len(object_gallery) < MAX_OBJECT_CROPS:
853
- object_gallery.append((crop, label))
 
 
 
 
 
854
 
855
- for crop, label in face_crops:
856
- if len(face_gallery) < MAX_FACE_CROPS:
857
- face_gallery.append((crop, label))
858
 
859
- # ---------------- DataFrames ----------------
860
- images_df = pd.DataFrame(image_rows)
861
- objects_df = pd.DataFrame(object_rows)
862
- faces_df = pd.DataFrame(face_rows)
 
 
 
 
863
 
864
- if objects_df.empty:
865
- objects_df = pd.DataFrame(columns=OBJECT_COLUMNS)
866
 
867
- if faces_df.empty:
868
- faces_df = pd.DataFrame(columns=FACE_COLUMNS_ALL)
869
-
870
- # ---------------- Excel ----------------
871
- progress(0.84, desc="Creating Excel report...")
872
-
873
- excel_bytes = create_excel(images_df, objects_df, faces_df)
874
- output_xlsx = os.path.join(temp_dir, "image_analysis_results.xlsx")
875
- with open(output_xlsx, "wb") as f:
876
- f.write(excel_bytes.getvalue())
877
-
878
- # ---------------- Plots ----------------
879
- progress(0.90, desc="Creating plots...")
880
-
881
- plot_objects = plot_top_objects(objects_df)
882
- plot_per_image = plot_objects_per_image(images_df)
883
- plot_category = plot_objects_by_category(objects_df)
884
- plot_faces_category = plot_faces_by_category(faces_df)
885
- plot_faces_image = plot_faces_per_image(images_df)
886
- plot_position = plot_face_position(faces_df)
887
- plot_face_size = plot_face_area(faces_df)
888
- plot_gender = plot_gender_by_category(faces_df)
889
-
890
- # ---------------- Summary ----------------
891
- elapsed_total = time.time() - start_total
892
-
893
- unique_objects = objects_df["object"].nunique() if not objects_df.empty else 0
894
- mean_objects = images_df["objects_detected"].mean() if not images_df.empty else 0
895
- mean_faces = images_df["faces_detected"].mean() if not images_df.empty else 0
896
- mean_face_area = (
897
- faces_df["area_fraction"].mean() * 100 if not faces_df.empty else 0
898
  )
899
- n_categories = images_df["category"].nunique() if not images_df.empty else 0
900
- avg_time = elapsed_total / len(images_df) if len(images_df) > 0 else 0
901
 
902
- n_female = int((faces_df["auto_perceived_gender"] == "female").sum())
903
- n_male = int((faces_df["auto_perceived_gender"] == "male").sum())
904
- n_uncertain = int((faces_df["auto_perceived_gender"] == "uncertain").sum())
905
 
906
  summary_text = f"""
 
907
  # Analysis completed
908
 
909
- ### Dataset
910
 
911
  **Images:** {len(images_df):,}
912
 
913
  **Categories:** {n_categories}
914
 
915
- ### Objects
 
 
916
 
917
  **Object detections:** {len(objects_df):,}
918
 
@@ -920,7 +2770,9 @@ def analyze_zip(zip_file, progress=gr.Progress()):
920
 
921
  **Average objects/image:** {mean_objects:.2f}
922
 
923
- ### Faces
 
 
924
 
925
  **Detected faces:** {len(faces_df):,}
926
 
@@ -928,16 +2780,25 @@ def analyze_zip(zip_file, progress=gr.Progress()):
928
 
929
  **Mean face area:** {mean_face_area:.2f}% of image
930
 
931
- ### Automatic perceived gender (unvalidated first pass)
 
 
 
 
 
 
932
 
933
- **Female:** {n_female:,} | **Male:** {n_male:,} | **Uncertain:** {n_uncertain:,}
 
934
 
935
- These labels are automatic guesses of perceived gender presentation from
936
- appearance, not gender identity. Error rates can differ by skin tone, age
937
- and image quality. Validate against your manual coding on a sample and
938
- report the agreement rate.
939
 
940
- ### Performance
 
 
 
 
 
941
 
942
  **Total time:** {elapsed_total:.1f} seconds
943
 
@@ -949,17 +2810,28 @@ report the agreement rate.
949
 
950
  **Face detector:** MTCNN
951
 
952
- **Gender classifier:** `{GENDER_MODEL_NAME}` (min. confidence {GENDER_MIN_CONFIDENCE})
 
 
953
 
954
  ---
955
 
956
- ### Manual coding
957
 
958
  The Excel file contains a **Manual Coding** sheet.
959
 
960
- Each detected face receives a unique identifier such as `face_001`.
961
- The automatic prediction (`auto_perceived_gender`, `auto_gender_confidence`)
962
- sits next to blank fields for:
 
 
 
 
 
 
 
 
 
963
 
964
  - `manual_gender`
965
  - `manual_age`
@@ -967,41 +2839,75 @@ sits next to blank fields for:
967
  - `manual_notes`
968
  """
969
 
970
- progress(1.0, desc="Completed")
 
 
 
 
 
971
 
972
  return (
 
973
  images_df,
 
974
  output_xlsx,
 
975
  annotated_gallery,
 
976
  object_gallery,
 
977
  face_gallery,
 
978
  plot_objects,
 
979
  plot_per_image,
 
980
  plot_category,
 
981
  plot_faces_category,
 
982
  plot_faces_image,
 
983
  plot_position,
 
984
  plot_face_size,
 
985
  plot_gender,
 
986
  summary_text,
 
987
  )
988
 
 
989
  except gr.Error:
 
990
  raise
991
 
 
992
  except Exception as e:
993
- print("ANALYSIS ERROR:", repr(e))
994
- raise gr.Error(f"Analysis failed: {e}")
995
 
996
- # The temp directory is intentionally not deleted, because the XLSX
997
- # output lives in it and Gradio must serve it.
 
 
 
 
 
 
 
 
 
 
998
 
999
 
1000
  # ============================================================
1001
  # GRADIO UI
1002
  # ============================================================
1003
 
1004
- with gr.Blocks(title=APP_TITLE) as demo:
 
 
 
1005
 
1006
  gr.Markdown(
1007
  """
@@ -1011,49 +2917,71 @@ Upload a ZIP containing photographs.
1011
 
1012
  ### Automatic analysis
1013
 
1014
- - YOLO object detection (multiple objects per image, confidence, boxes, size)
1015
- - Face detection (confidence, position, size)
1016
- - Automatic perceived-gender guess per face (female / male / uncertain)
 
 
 
 
 
 
 
1017
  - ZIP folder/category analysis
1018
 
1019
  ### Research coding
1020
 
1021
- Detected faces receive unique IDs and are exported as face crops for manual
1022
- coding. The Excel report contains a **Manual Coding** sheet where the automatic
1023
- prediction sits next to your manual fields, so you can check agreement.
1024
 
1025
- > ⚠️ Automatic gender labels are *perceived gender presentation* guesses, not
1026
- > gender identity. Treat them as a first pass and validate them manually.
 
 
 
 
1027
  """
1028
  )
1029
 
 
1030
  zip_input = gr.File(
1031
  label="ZIP file containing images",
1032
  file_types=[".zip"],
1033
  )
1034
 
1035
- analyze_button = gr.Button("πŸš€ Analyze images", variant="primary")
 
 
 
 
 
1036
 
1037
  status = gr.Markdown()
1038
 
 
1039
  results_dataframe = gr.Dataframe(
1040
  label="Image-level results",
1041
  interactive=False,
1042
  wrap=True,
1043
  )
1044
 
1045
- excel_output = gr.File(label="Download Excel report")
 
 
 
 
1046
 
1047
  gr.Markdown(
1048
  """
1049
  ## πŸ”΄ Objects + πŸ”΅ Faces
1050
 
1051
- Red boxes = detected objects
1052
 
1053
- Blue boxes = detected faces
1054
  """
1055
  )
1056
 
 
1057
  annotated_gallery = gr.Gallery(
1058
  label="Annotated images",
1059
  columns=4,
@@ -1062,7 +2990,11 @@ Blue boxes = detected faces
1062
  object_fit="contain",
1063
  )
1064
 
1065
- gr.Markdown("## Detected objects")
 
 
 
 
1066
 
1067
  object_gallery = gr.Gallery(
1068
  label="Object crops",
@@ -1072,15 +3004,23 @@ Blue boxes = detected faces
1072
  object_fit="contain",
1073
  )
1074
 
 
1075
  gr.Markdown(
1076
  """
1077
- ## Detected faces
 
 
1078
 
1079
- Each crop has a `face_id | confidence | auto gender` label. The `face_id`
1080
- corresponds to the **Manual Coding** sheet in the Excel file.
 
 
 
 
1081
  """
1082
  )
1083
 
 
1084
  face_gallery = gr.Gallery(
1085
  label="Face crops",
1086
  columns=6,
@@ -1089,44 +3029,110 @@ corresponds to the **Manual Coding** sheet in the Excel file.
1089
  object_fit="contain",
1090
  )
1091
 
1092
- gr.Markdown("## πŸ“Š Object analysis")
 
 
 
 
 
 
 
 
1093
 
1094
  with gr.Row():
1095
- plot_objects_output = gr.Plot(label="Most frequent objects")
1096
- plot_per_image_output = gr.Plot(label="Objects per image")
1097
 
1098
- plot_category_output = gr.Plot(label="Objects by category")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
 
1100
- gr.Markdown("## πŸ‘€ Face detection analysis")
1101
 
1102
  with gr.Row():
1103
- plot_faces_category_output = gr.Plot(label="Faces by category")
1104
- plot_faces_image_output = gr.Plot(label="Faces per image")
 
 
 
 
 
 
 
1105
 
1106
  with gr.Row():
1107
- plot_position_output = gr.Plot(label="Face position")
1108
- plot_face_size_output = gr.Plot(label="Face size")
1109
 
1110
- plot_gender_output = gr.Plot(label="Automatically perceived gender by category")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1111
 
1112
  analyze_button.click(
 
1113
  fn=analyze_zip,
1114
- inputs=[zip_input],
 
 
 
 
1115
  outputs=[
 
1116
  results_dataframe,
 
1117
  excel_output,
 
1118
  annotated_gallery,
 
1119
  object_gallery,
 
1120
  face_gallery,
 
1121
  plot_objects_output,
 
1122
  plot_per_image_output,
 
1123
  plot_category_output,
 
1124
  plot_faces_category_output,
 
1125
  plot_faces_image_output,
 
1126
  plot_position_output,
 
1127
  plot_face_size_output,
 
1128
  plot_gender_output,
 
1129
  status,
 
1130
  ],
1131
  )
1132
 
@@ -1136,8 +3142,13 @@ corresponds to the **Manual Coding** sheet in the Excel file.
1136
  # ============================================================
1137
 
1138
  if __name__ == "__main__":
 
1139
  demo.launch(
 
1140
  server_name="0.0.0.0",
 
1141
  server_port=7860,
 
1142
  show_error=True,
 
1143
  )
 
26
 
27
  APP_TITLE = "Image Object, Face & Manual Coding Analysis"
28
 
29
+
30
+ # ------------------------------------------------------------
31
  # YOLO
32
+ # ------------------------------------------------------------
33
+
34
+ YOLO_MODEL_NAME = "yolov8s.pt"
35
  OBJECT_CONFIDENCE = 0.25
36
  IOU_THRESHOLD = 0.45
37
  MAX_OBJECTS_PER_IMAGE = 50
38
  MAX_FACES_PER_IMAGE = 30
39
 
40
+
41
+ # ------------------------------------------------------------
42
+ # Automatic perceived-gender classifier
43
+ # ------------------------------------------------------------
44
+
45
  GENDER_MODEL_NAME = "dima806/fairface_gender_image_detection"
46
+ GENDER_MIN_CONFIDENCE = 0.70
47
+ MIN_FACE_PIXELS_FOR_GENDER = 40
48
+ GENDER_CROP_MARGIN = 0.15
49
 
50
+
51
+ # ------------------------------------------------------------
52
  # Images
53
+ # ------------------------------------------------------------
54
+
55
+ IMAGE_EXTENSIONS = {
56
+ ".jpg",
57
+ ".jpeg",
58
+ ".png",
59
+ ".webp",
60
+ ".bmp",
61
+ ".tif",
62
+ ".tiff",
63
+ }
64
+
65
  THUMBNAIL_SIZE = (500, 500)
66
+
67
  MAX_OBJECT_CROPS = 150
68
  MAX_FACE_CROPS = 150
69
 
70
+
71
+ # ------------------------------------------------------------
72
+ # Face columns
73
+ # ------------------------------------------------------------
74
+
75
  FACE_COLUMNS_MANUAL = [
76
  "face_id",
77
  "filename",
 
90
  "manual_notes",
91
  ]
92
 
93
+
94
  FACE_COLUMNS_ALL = [
95
  "filename",
96
  "relative_path",
 
99
  "face_index",
100
  "face_id",
101
  "confidence",
102
+ "x1",
103
+ "y1",
104
+ "x2",
105
+ "y2",
106
+ "width",
107
+ "height",
108
  "area_pixels",
109
  "area_fraction",
110
  "horizontal_position",
 
117
  "manual_notes",
118
  ]
119
 
120
+
121
  OBJECT_COLUMNS = [
122
+ "filename",
123
+ "relative_path",
124
+ "category",
125
+ "subcategory",
126
+ "object",
127
+ "confidence",
128
+ "x1",
129
+ "y1",
130
+ "x2",
131
+ "y2",
132
+ "width",
133
+ "height",
134
+ "area_pixels",
135
+ "area_fraction",
136
  ]
137
 
138
 
 
148
  print("PyTorch:", torch.__version__)
149
  print("CUDA:", torch.cuda.is_available())
150
  print("Device:", DEVICE)
151
+
152
  if torch.cuda.is_available():
153
  print("GPU:", torch.cuda.get_device_name(0))
154
+
155
  print("=" * 70)
156
 
157
 
 
160
  # ============================================================
161
 
162
  print("Loading YOLO...")
163
+
164
  yolo_model = YOLO(YOLO_MODEL_NAME)
165
+
166
  if DEVICE == "cuda":
167
  try:
168
  yolo_model.to("cuda")
169
  except Exception as e:
170
  print("Could not explicitly move YOLO to CUDA:", e)
171
+
172
  print("YOLO loaded.")
173
 
174
+
175
  print("Loading MTCNN...")
176
+
177
  mtcnn = MTCNN(
178
  image_size=160,
179
  margin=20,
 
184
  keep_all=True,
185
  device=DEVICE,
186
  )
187
+
188
  print("MTCNN loaded.")
189
 
190
+
191
  print("Loading gender classifier...")
192
+
193
  gender_classifier = pipeline(
194
  "image-classification",
195
  model=GENDER_MODEL_NAME,
196
  device=0 if DEVICE == "cuda" else -1,
197
  )
198
+
199
  print("Gender classifier loaded.")
200
 
201
 
 
204
  # ============================================================
205
 
206
  def safe_open_image(path):
207
+
208
  try:
209
  with Image.open(path) as img:
210
+
211
  img = ImageOps.exif_transpose(img)
212
+
213
  return img.convert("RGB")
214
+
215
  except Exception as e:
216
+
217
  print(f"Could not open {path}: {e}")
218
+
219
  return None
220
 
221
 
222
  def create_thumbnail(image, max_size=THUMBNAIL_SIZE):
223
+
224
  img = image.copy()
225
+
226
  img.thumbnail(max_size)
227
+
228
  return img
229
 
230
 
231
  def list_images_recursive(root):
232
+
233
  images = []
234
+
235
  for current_root, _dirs, files in os.walk(root):
236
+
237
  for filename in files:
238
+
239
  if Path(filename).suffix.lower() in IMAGE_EXTENSIONS:
240
+
241
+ images.append(
242
+ os.path.join(current_root, filename)
243
+ )
244
+
245
  return sorted(images)
246
 
247
 
248
  def get_category_info(image_path, extraction_root):
249
+
250
+ relative = os.path.relpath(
251
+ image_path,
252
+ extraction_root
253
+ )
254
+
255
  parts = Path(relative).parts
256
+
257
+ category = (
258
+ parts[0]
259
+ if len(parts) >= 2
260
+ else "ROOT"
261
+ )
262
+
263
+ subcategory = (
264
+ parts[1]
265
+ if len(parts) >= 3
266
+ else ""
267
+ )
268
+
269
  return category, subcategory
270
 
271
 
272
+ def get_box_position(
273
+ x1,
274
+ y1,
275
+ x2,
276
+ y2,
277
+ image_width,
278
+ image_height
279
+ ):
280
+
281
  cx = (x1 + x2) / 2 / image_width
282
  cy = (y1 + y2) / 2 / image_height
283
 
284
  if cx < 0.333:
285
+
286
  horizontal = "left"
287
+
288
  elif cx < 0.666:
289
+
290
  horizontal = "center"
291
+
292
  else:
293
+
294
  horizontal = "right"
295
 
296
+
297
  if cy < 0.333:
298
+
299
  vertical = "top"
300
+
301
  elif cy < 0.666:
302
+
303
  vertical = "middle"
304
+
305
  else:
306
+
307
  vertical = "bottom"
308
 
309
+
310
  return horizontal, vertical
311
 
312
 
313
+ def clamp_box(
314
+ box,
315
+ image_width,
316
+ image_height
317
+ ):
318
+
319
  x1, y1, x2, y2 = box
320
+
321
  return (
322
  max(0, int(x1)),
323
  max(0, int(y1)),
 
326
  )
327
 
328
 
329
+ def draw_label(
330
+ draw,
331
+ xy,
332
+ text,
333
+ color
334
+ ):
335
+
336
  try:
337
+
338
+ bbox = draw.textbbox(
339
+ xy,
340
+ text
341
+ )
342
+
343
+ draw.rectangle(
344
+ bbox,
345
+ fill=color
346
+ )
347
+
348
  except Exception:
349
+
350
  pass
351
+
352
+ draw.text(
353
+ xy,
354
+ text,
355
+ fill="white"
356
+ )
357
 
358
 
359
  # ============================================================
 
361
  # ============================================================
362
 
363
  def classify_gender(face_image):
364
+
365
  """
366
+ Returns:
367
+
368
+ (label, confidence)
369
+
370
+ The label is an automatic guess of
371
+ PERCEIVED gender presentation from appearance.
372
 
373
+ It is not gender identity.
374
+
375
+ Low-confidence or very small faces are labelled
376
+ "uncertain".
377
  """
378
+
379
  try:
380
+
381
  w, h = face_image.size
382
+
383
  if min(w, h) < MIN_FACE_PIXELS_FOR_GENDER:
384
+
385
  return "uncertain", None
386
 
387
+
388
+ predictions = gender_classifier(
389
+ face_image
390
+ )
391
+
392
+ best = max(
393
+ predictions,
394
+ key=lambda p: p["score"]
395
+ )
396
+
397
+ score = float(
398
+ best["score"]
399
+ )
400
+
401
 
402
  if score < GENDER_MIN_CONFIDENCE:
 
403
 
404
+ return (
405
+ "uncertain",
406
+ round(score, 4)
407
+ )
408
+
409
+
410
+ return (
411
+ str(best["label"]).lower(),
412
+ round(score, 4)
413
+ )
414
+
415
 
416
  except Exception as e:
417
+
418
+ print(
419
+ "Gender error:",
420
+ repr(e)
421
+ )
422
+
423
  return "uncertain", None
424
 
425
 
 
429
 
430
  @spaces.GPU
431
  def detect_objects(image):
432
+
433
  if image is None:
434
+
435
  return [], image
436
 
437
+
438
  try:
439
+
440
  results = yolo_model.predict(
441
  source=np.array(image),
442
  conf=OBJECT_CONFIDENCE,
443
  iou=IOU_THRESHOLD,
444
+ device=(
445
+ 0
446
+ if DEVICE == "cuda"
447
+ else "cpu"
448
+ ),
449
  verbose=False,
450
  )
451
 
452
+
453
  if not results:
454
+
455
  return [], image
456
 
457
+
458
  result = results[0]
459
+
460
  names = result.names
461
+
462
  detections = []
463
+
464
  annotated = image.copy()
465
+
466
+ draw = ImageDraw.Draw(
467
+ annotated
468
+ )
469
+
470
  image_width, image_height = image.size
471
 
472
+
473
  if result.boxes is None:
474
+
475
  return [], annotated
476
 
477
+
478
  boxes = result.boxes
 
479
 
480
+ image_area = (
481
+ image_width *
482
+ image_height
483
+ )
484
+
485
+
486
+ for i in range(
487
+ min(
488
+ len(boxes),
489
+ MAX_OBJECTS_PER_IMAGE
490
+ )
491
+ ):
492
+
493
+ cls_id = int(
494
+ boxes.cls[i].item()
495
+ )
496
+
497
+ confidence = float(
498
+ boxes.conf[i].item()
499
+ )
500
+
501
+
502
  x1, y1, x2, y2 = clamp_box(
503
+ boxes.xyxy[i].tolist(),
504
+ image_width,
505
+ image_height
506
+ )
507
+
508
+
509
+ box_width = max(
510
+ 0,
511
+ x2 - x1
512
+ )
513
+
514
+ box_height = max(
515
+ 0,
516
+ y2 - y1
517
+ )
518
+
519
+ area_pixels = (
520
+ box_width *
521
+ box_height
522
+ )
523
+
524
+ area_fraction = (
525
+ area_pixels / image_area
526
+ if image_area > 0
527
+ else 0
528
+ )
529
+
530
+
531
+ object_name = names.get(
532
+ cls_id,
533
+ str(cls_id)
534
  )
535
 
 
 
 
 
 
536
 
537
  detections.append({
538
+
539
  "object": object_name,
540
+
541
+ "confidence": round(
542
+ confidence,
543
+ 4
544
+ ),
545
+
546
+ "x1": x1,
547
+ "y1": y1,
548
+ "x2": x2,
549
+ "y2": y2,
550
+
551
  "width": box_width,
552
  "height": box_height,
553
+
554
  "area_pixels": area_pixels,
555
+
556
+ "area_fraction": round(
557
+ area_fraction,
558
+ 6
559
+ ),
560
+
561
  })
562
 
563
+
564
+ draw.rectangle(
565
+ [x1, y1, x2, y2],
566
+ outline="red",
567
+ width=3
568
+ )
569
+
570
+
571
+ draw_label(
572
+ draw,
573
+ (x1, y1),
574
+ f"{object_name} {confidence:.2f}",
575
+ "red"
576
+ )
577
+
578
 
579
  return detections, annotated
580
 
581
+
582
  except Exception as e:
583
+
584
+ print(
585
+ "YOLO error:",
586
+ repr(e)
587
+ )
588
+
589
  return [], image
590
 
591
 
 
595
 
596
  @spaces.GPU
597
  def detect_faces(image):
598
+
599
  """
600
+ Detects faces and their locations.
601
+
602
+ Adds an automatic perceived-gender guess.
603
+
604
+ This prediction is intended as a first pass
605
+ for manual validation.
606
+
607
  No age or identity inference.
608
  """
609
+
610
  if image is None:
611
+
612
  return [], image, []
613
 
614
+
615
  try:
616
+
617
+ boxes, probabilities = mtcnn.detect(
618
+ np.array(image)
619
+ )
620
+
621
 
622
  detections = []
623
+
624
  annotated = image.copy()
625
+
626
+ draw = ImageDraw.Draw(
627
+ annotated
628
+ )
629
+
630
  face_crops = []
631
 
632
+
633
  if boxes is None:
634
+
635
  return [], annotated, []
636
 
637
+
638
  image_width, image_height = image.size
639
+
640
+ image_area = (
641
+ image_width *
642
+ image_height
643
+ )
644
+
645
 
646
  for i, box in enumerate(boxes):
647
+
648
  if i >= MAX_FACES_PER_IMAGE:
649
+
650
  break
651
 
652
+
653
+ x1, y1, x2, y2 = clamp_box(
654
+ box.tolist(),
655
+ image_width,
656
+ image_height
657
+ )
658
+
659
 
660
  if x2 <= x1 or y2 <= y1:
661
+
662
  continue
663
 
664
+
665
  probability = (
666
+
667
+ float(probabilities[i])
668
+
669
+ if probabilities is not None
670
+
671
+ else np.nan
672
+
673
  )
674
 
675
+
676
  box_width = x2 - x1
677
+
678
  box_height = y2 - y1
679
+
680
+ area_pixels = (
681
+ box_width *
682
+ box_height
683
+ )
684
+
685
+ area_fraction = (
686
+
687
+ area_pixels /
688
+ image_area
689
+
690
+ if image_area > 0
691
+
692
+ else 0
693
+
694
+ )
695
+
696
 
697
  horizontal, vertical = get_box_position(
698
+ x1,
699
+ y1,
700
+ x2,
701
+ y2,
702
+ image_width,
703
+ image_height
704
+ )
705
+
706
+
707
+ face_id = (
708
+ f"face_{i + 1:03d}"
709
+ )
710
+
711
+
712
+ # ------------------------------------------------
713
+ # Gender crop
714
+ # ------------------------------------------------
715
+
716
+ margin = int(
717
+ GENDER_CROP_MARGIN *
718
+ max(
719
+ box_width,
720
+ box_height
721
+ )
722
+ )
723
+
724
+
725
+ gender_crop = image.crop(
726
+ (
727
+ max(
728
+ 0,
729
+ x1 - margin
730
+ ),
731
+
732
+ max(
733
+ 0,
734
+ y1 - margin
735
+ ),
736
+
737
+ min(
738
+ image_width,
739
+ x2 + margin
740
+ ),
741
+
742
+ min(
743
+ image_height,
744
+ y2 + margin
745
+ ),
746
+ )
747
  )
748
 
 
749
 
750
+ auto_gender, auto_gender_conf = classify_gender(
751
+ gender_crop
752
+ )
753
+
 
 
 
 
 
754
 
755
  detections.append({
756
+
757
  "face_index": i + 1,
758
+
759
  "face_id": face_id,
760
+
761
  "confidence": (
762
+
763
+ round(
764
+ probability,
765
+ 4
766
+ )
767
+
768
+ if not np.isnan(probability)
769
+
770
+ else None
771
+
772
  ),
773
+
774
+ "x1": x1,
775
+ "y1": y1,
776
+ "x2": x2,
777
+ "y2": y2,
778
+
779
  "width": box_width,
780
  "height": box_height,
781
+
782
  "area_pixels": area_pixels,
783
+
784
+ "area_fraction": round(
785
+ area_fraction,
786
+ 6
787
+ ),
788
+
789
  "horizontal_position": horizontal,
790
+
791
  "vertical_position": vertical,
792
 
 
793
  "auto_perceived_gender": auto_gender,
794
+
795
  "auto_gender_confidence": auto_gender_conf,
796
 
 
797
  "manual_gender": "",
798
+
799
  "manual_age": "",
800
+
801
  "manual_age_group": "",
802
+
803
  "manual_notes": "",
804
+
805
  })
806
 
 
 
 
 
807
 
808
+ # ------------------------------------------------
809
+ # Face gallery
810
+ # ------------------------------------------------
811
 
812
+ crop = create_thumbnail(
813
+ image.crop(
814
+ (
815
+ x1,
816
+ y1,
817
+ x2,
818
+ y2
819
+ )
820
+ ),
821
+ (300, 300)
822
+ )
823
 
 
 
 
824
 
825
+ prob_text = (
826
 
827
+ f"{probability:.2f}"
 
 
828
 
829
+ if not np.isnan(probability)
 
830
 
831
+ else "n/a"
 
 
 
832
 
833
+ )
 
834
 
 
 
835
 
836
+ face_crops.append(
837
+ (
838
+ crop,
839
+ f"{face_id} | "
840
+ f"{prob_text} | "
841
+ f"{auto_gender}"
842
+ )
843
+ )
844
+
845
+
846
+ # ------------------------------------------------
847
+ # Draw face
848
+ # ------------------------------------------------
849
+
850
+ draw.rectangle(
851
+ [x1, y1, x2, y2],
852
+ outline="blue",
853
+ width=4
854
+ )
855
+
856
+
857
+ draw_label(
858
+ draw,
859
+ (x1, y1),
860
+ f"{face_id} {prob_text}",
861
+ "blue"
862
+ )
863
+
864
+
865
+ return (
866
+ detections,
867
+ annotated,
868
+ face_crops
869
+ )
870
+
871
+
872
+ except Exception as e:
873
+
874
+ print(
875
+ "MTCNN error:",
876
+ repr(e)
877
+ )
878
+
879
+ return [], image, []
880
+
881
+
882
+ # ============================================================
883
+ # OBJECT CROPS
884
+ # ============================================================
885
+
886
+ def create_object_crops(
887
+ image,
888
+ detections
889
+ ):
890
+
891
+ crops = []
892
+
893
+
894
+ for d in detections:
895
+
896
+ x1 = d["x1"]
897
+ y1 = d["y1"]
898
+ x2 = d["x2"]
899
+ y2 = d["y2"]
900
+
901
+
902
+ if x2 <= x1 or y2 <= y1:
903
+
904
+ continue
905
+
906
+
907
+ crop = create_thumbnail(
908
+ image.crop(
909
+ (
910
+ x1,
911
+ y1,
912
+ x2,
913
+ y2
914
+ )
915
+ ),
916
+ (300, 300)
917
+ )
918
+
919
+
920
+ crops.append(
921
+ (
922
+ crop,
923
+ f"{d['object']} | "
924
+ f"{d['confidence']:.2f}"
925
+ )
926
+ )
927
+
928
+
929
+ if len(crops) >= MAX_OBJECT_CROPS:
930
+
931
+ break
932
+
933
+
934
+ return crops
935
 
936
 
937
  # ============================================================
938
+ # PROCESS ONE IMAGE
939
+ # ============================================================
940
+
941
+ def process_single_image(
942
+ image_path,
943
+ extraction_root
944
+ ):
945
 
 
946
  start = time.time()
947
 
948
+
949
+ image = safe_open_image(
950
+ image_path
951
+ )
952
+
953
+
954
  if image is None:
 
955
 
956
+ return (
957
+ None,
958
+ [],
959
+ [],
960
+ None,
961
+ [],
962
+ [],
963
+ 0
964
+ )
965
+
966
+
967
+ filename = os.path.basename(
968
+ image_path
969
+ )
970
+
971
+
972
+ relative_path = os.path.relpath(
973
+ image_path,
974
+ extraction_root
975
+ )
976
+
977
+
978
+ category, subcategory = get_category_info(
979
+ image_path,
980
+ extraction_root
981
+ )
982
+
983
+
984
  width, height = image.size
985
 
 
 
 
986
 
987
+ object_detections, _ = detect_objects(
988
+ image
989
+ )
990
+
991
+
992
+ face_detections, _, face_crops = detect_faces(
993
+ image
994
+ )
995
+
996
+
997
+ object_crops = create_object_crops(
998
+ image,
999
+ object_detections
1000
+ )
1001
+
1002
+
1003
+ # --------------------------------------------------------
1004
+ # Combined annotation
1005
+ # --------------------------------------------------------
1006
+
1007
  combined = image.copy()
1008
+
1009
+ draw = ImageDraw.Draw(
1010
+ combined
1011
+ )
1012
+
1013
 
1014
  for d in object_detections:
1015
+
1016
+ draw.rectangle(
1017
+ [
1018
+ d["x1"],
1019
+ d["y1"],
1020
+ d["x2"],
1021
+ d["y2"]
1022
+ ],
1023
+ outline="red",
1024
+ width=3
1025
+ )
1026
+
1027
 
1028
  for d in face_detections:
 
1029
 
1030
+ draw.rectangle(
1031
+ [
1032
+ d["x1"],
1033
+ d["y1"],
1034
+ d["x2"],
1035
+ d["y2"]
1036
+ ],
1037
+ outline="blue",
1038
+ width=4
1039
+ )
1040
+
1041
+
1042
+ combined = create_thumbnail(
1043
+ combined
1044
+ )
1045
+
1046
+
1047
+ # --------------------------------------------------------
1048
+ # Gender counts
1049
+ # --------------------------------------------------------
1050
 
1051
  gender_counts = pd.Series(
1052
+ [
1053
+ d["auto_perceived_gender"]
1054
+ for d in face_detections
1055
+ ],
1056
+ dtype="object"
1057
  ).value_counts()
1058
 
1059
+
1060
+ # --------------------------------------------------------
1061
+ # Image row
1062
+ # --------------------------------------------------------
1063
+
1064
  image_row = {
1065
+
1066
  "filename": filename,
1067
+
1068
  "relative_path": relative_path,
1069
+
1070
  "category": category,
1071
+
1072
  "subcategory": subcategory,
1073
+
1074
  "width": width,
1075
+
1076
  "height": height,
1077
+
1078
+ "objects_detected": len(
1079
+ object_detections
1080
+ ),
1081
+
1082
+ "faces_detected": len(
1083
+ face_detections
1084
+ ),
1085
+
1086
+ "auto_female_faces": int(
1087
+ gender_counts.get(
1088
+ "female",
1089
+ 0
1090
+ )
1091
+ ),
1092
+
1093
+ "auto_male_faces": int(
1094
+ gender_counts.get(
1095
+ "male",
1096
+ 0
1097
+ )
1098
+ ),
1099
+
1100
+ "auto_uncertain_faces": int(
1101
+ gender_counts.get(
1102
+ "uncertain",
1103
+ 0
1104
+ )
1105
+ ),
1106
+
1107
+ "object_types": ", ".join(
1108
+ sorted(
1109
+ {
1110
+ d["object"]
1111
+ for d in object_detections
1112
+ }
1113
+ )
1114
+ ),
1115
+
1116
  "processing_seconds": 0,
1117
+
1118
  }
1119
 
1120
+
1121
  base = {
1122
+
1123
  "filename": filename,
1124
+
1125
  "relative_path": relative_path,
1126
+
1127
  "category": category,
1128
+
1129
  "subcategory": subcategory,
1130
+
1131
  }
1132
 
 
 
1133
 
1134
+ object_rows = [
1135
+ {
1136
+ **base,
1137
+ **d
1138
+ }
1139
+ for d in object_detections
1140
+ ]
1141
+
1142
+
1143
+ face_rows = [
1144
+ {
1145
+ **base,
1146
+ **d
1147
+ }
1148
+ for d in face_detections
1149
+ ]
1150
+
1151
+
1152
+ elapsed = (
1153
+ time.time() -
1154
+ start
1155
+ )
1156
+
1157
+
1158
+ image_row[
1159
+ "processing_seconds"
1160
+ ] = round(
1161
+ elapsed,
1162
+ 3
1163
+ )
1164
+
1165
 
1166
  return (
1167
  image_row,
 
1175
 
1176
 
1177
  # ============================================================
1178
+ # PLOT UTILITIES
1179
  # ============================================================
1180
 
1181
  def empty_plot(title):
1182
+
1183
+ fig, ax = plt.subplots(
1184
+ figsize=(9, 5)
1185
+ )
1186
+
1187
  ax.set_title(title)
1188
+
1189
+ ax.text(
1190
+ 0.5,
1191
+ 0.5,
1192
+ "No data available",
1193
+ ha="center",
1194
+ va="center",
1195
+ transform=ax.transAxes
1196
+ )
1197
+
1198
  ax.axis("off")
1199
+
1200
  return fig
1201
 
1202
 
1203
+ def add_bar_labels(
1204
+ ax,
1205
+ bars,
1206
+ orientation="vertical",
1207
+ fmt="{:.0f}",
1208
+ padding=3
1209
+ ):
1210
+
1211
+ """
1212
+ Add numerical values directly onto bars.
1213
+
1214
+ orientation:
1215
+ vertical
1216
+ horizontal
1217
+ """
1218
+
1219
+ for bar in bars:
1220
+
1221
+ value = (
1222
+ bar.get_height()
1223
+ if orientation == "vertical"
1224
+ else bar.get_width()
1225
+ )
1226
+
1227
+
1228
+ if orientation == "vertical":
1229
+
1230
+ x = (
1231
+ bar.get_x()
1232
+ +
1233
+ bar.get_width() / 2
1234
+ )
1235
+
1236
+ y = bar.get_height()
1237
+
1238
+
1239
+ ax.annotate(
1240
+ fmt.format(value),
1241
+ (
1242
+ x,
1243
+ y
1244
+ ),
1245
+ xytext=(
1246
+ 0,
1247
+ padding
1248
+ ),
1249
+ textcoords="offset points",
1250
+ ha="center",
1251
+ va="bottom",
1252
+ fontsize=9,
1253
+ fontweight="bold"
1254
+ )
1255
+
1256
+
1257
+ else:
1258
+
1259
+ x = bar.get_width()
1260
+
1261
+ y = (
1262
+ bar.get_y()
1263
+ +
1264
+ bar.get_height() / 2
1265
+ )
1266
+
1267
+
1268
+ ax.annotate(
1269
+ fmt.format(value),
1270
+ (
1271
+ x,
1272
+ y
1273
+ ),
1274
+ xytext=(
1275
+ padding,
1276
+ 0
1277
+ ),
1278
+ textcoords="offset points",
1279
+ ha="left",
1280
+ va="center",
1281
+ fontsize=9,
1282
+ fontweight="bold"
1283
+ )
1284
+
1285
+
1286
+ def add_histogram_labels(
1287
+ ax,
1288
+ counts,
1289
+ bins,
1290
+ fmt="{:.0f}"
1291
+ ):
1292
+
1293
+ """
1294
+ Add counts above histogram bars.
1295
+ """
1296
+
1297
+ for i, count in enumerate(counts):
1298
+
1299
+ if count <= 0:
1300
+
1301
+ continue
1302
+
1303
+
1304
+ left = bins[i]
1305
+
1306
+ right = bins[i + 1]
1307
+
1308
+ center = (
1309
+ left + right
1310
+ ) / 2
1311
+
1312
+
1313
+ ax.annotate(
1314
+ fmt.format(count),
1315
+ (
1316
+ center,
1317
+ count
1318
+ ),
1319
+ xytext=(
1320
+ 0,
1321
+ 3
1322
+ ),
1323
+ textcoords="offset points",
1324
+ ha="center",
1325
+ va="bottom",
1326
+ fontsize=8,
1327
+ fontweight="bold"
1328
+ )
1329
+
1330
+
1331
+ # ============================================================
1332
+ # PLOTS
1333
+ # ============================================================
1334
+
1335
  def plot_top_objects(objects_df):
1336
+
1337
  if objects_df.empty:
1338
+
1339
+ return empty_plot(
1340
+ "Most frequently detected objects"
1341
+ )
1342
+
1343
+
1344
+ counts = (
1345
+ objects_df["object"]
1346
+ .value_counts()
1347
+ .head(20)
1348
+ .sort_values()
1349
+ )
1350
+
1351
+
1352
+ fig, ax = plt.subplots(
1353
+ figsize=(10, 7)
1354
+ )
1355
+
1356
+
1357
+ bars = ax.barh(
1358
+ counts.index,
1359
+ counts.values
1360
+ )
1361
+
1362
+
1363
+ ax.set_title(
1364
+ "Most frequently detected objects",
1365
+ fontsize=14,
1366
+ fontweight="bold"
1367
+ )
1368
+
1369
+ ax.set_xlabel(
1370
+ "Number of detections"
1371
+ )
1372
+
1373
+ ax.set_ylabel(
1374
+ "Object"
1375
+ )
1376
+
1377
+
1378
+ # Numerical values
1379
+ add_bar_labels(
1380
+ ax,
1381
+ bars,
1382
+ orientation="horizontal"
1383
+ )
1384
+
1385
+
1386
+ # Leave room for labels
1387
+ ax.set_xlim(
1388
+ 0,
1389
+ counts.max() * 1.15
1390
+ )
1391
+
1392
+
1393
  plt.tight_layout()
1394
+
1395
  return fig
1396
 
1397
 
1398
  def plot_objects_per_image(images_df):
1399
+
1400
  if images_df.empty:
 
1401
 
1402
+ return empty_plot(
1403
+ "Objects per image"
1404
+ )
1405
+
1406
+
1407
+ values = images_df[
1408
+ "objects_detected"
1409
+ ].dropna()
1410
+
1411
+
1412
+ fig, ax = plt.subplots(
1413
+ figsize=(9, 5)
1414
+ )
1415
+
1416
+
1417
+ counts, bins, patches = ax.hist(
1418
+ values,
1419
+ bins=20
1420
+ )
1421
+
1422
+
1423
+ ax.set_title(
1424
+ "Objects detected per image",
1425
+ fontsize=14,
1426
+ fontweight="bold"
1427
+ )
1428
+
1429
+ ax.set_xlabel(
1430
+ "Number of objects"
1431
+ )
1432
+
1433
+ ax.set_ylabel(
1434
+ "Number of images"
1435
+ )
1436
+
1437
+
1438
+ add_histogram_labels(
1439
+ ax,
1440
+ counts,
1441
+ bins
1442
+ )
1443
+
1444
+
1445
  plt.tight_layout()
1446
+
1447
  return fig
1448
 
1449
 
1450
  def plot_objects_by_category(objects_df):
1451
+
1452
  if objects_df.empty:
 
1453
 
1454
+ return empty_plot(
1455
+ "Objects by category"
1456
+ )
1457
+
1458
+
1459
+ table = pd.crosstab(
1460
+ objects_df["category"],
1461
+ objects_df["object"]
1462
+ )
1463
+
1464
+
1465
  if table.empty:
 
1466
 
1467
+ return empty_plot(
1468
+ "Objects by category"
1469
+ )
1470
+
1471
+
1472
+ top_objects = (
1473
+ objects_df["object"]
1474
+ .value_counts()
1475
+ .head(12)
1476
+ .index
1477
+ )
1478
+
1479
+
1480
+ table = table[
1481
+ [
1482
+ x
1483
+ for x in top_objects
1484
+ if x in table.columns
1485
+ ]
1486
+ ]
1487
+
1488
+
1489
+ fig, ax = plt.subplots(
1490
+ figsize=(13, 8)
1491
+ )
1492
+
1493
+
1494
+ table.plot(
1495
+ kind="bar",
1496
+ ax=ax
1497
+ )
1498
+
1499
+
1500
+ ax.set_title(
1501
+ "Detected objects by ZIP category",
1502
+ fontsize=14,
1503
+ fontweight="bold"
1504
+ )
1505
+
1506
+ ax.set_xlabel(
1507
+ "Category"
1508
+ )
1509
+
1510
+ ax.set_ylabel(
1511
+ "Number of detections"
1512
+ )
1513
+
1514
+
1515
+ ax.legend(
1516
+ title="Object",
1517
+ bbox_to_anchor=(1.02, 1),
1518
+ loc="upper left"
1519
+ )
1520
+
1521
+
1522
+ # --------------------------------------------------------
1523
+ # Numerical labels on grouped bars
1524
+ # --------------------------------------------------------
1525
+
1526
+ for container in ax.containers:
1527
+
1528
+ labels = []
1529
+
1530
+ for bar in container:
1531
+
1532
+ value = bar.get_height()
1533
+
1534
+ if value == 0:
1535
+
1536
+ labels.append("")
1537
+
1538
+ else:
1539
+
1540
+ labels.append(
1541
+ f"{int(value)}"
1542
+ )
1543
+
1544
+
1545
+ ax.bar_label(
1546
+ container,
1547
+ labels=labels,
1548
+ padding=2,
1549
+ fontsize=8
1550
+ )
1551
+
1552
+
1553
+ plt.tight_layout()
1554
+
1555
+ return fig
1556
+
1557
+
1558
+ def plot_faces_by_category(faces_df):
1559
+
1560
+ if faces_df.empty:
1561
+
1562
+ return empty_plot(
1563
+ "Face detections by category"
1564
+ )
1565
+
1566
+
1567
+ counts = (
1568
+ faces_df
1569
+ .groupby("category")
1570
+ .size()
1571
+ .sort_values()
1572
+ )
1573
+
1574
+
1575
+ fig, ax = plt.subplots(
1576
+ figsize=(10, 6)
1577
+ )
1578
+
1579
+
1580
+ bars = ax.barh(
1581
+ counts.index,
1582
+ counts.values
1583
+ )
1584
+
1585
+
1586
+ ax.set_title(
1587
+ "Face detections by category",
1588
+ fontsize=14,
1589
+ fontweight="bold"
1590
+ )
1591
+
1592
+ ax.set_xlabel(
1593
+ "Number of detected faces"
1594
+ )
1595
+
1596
+ ax.set_ylabel(
1597
+ "Category"
1598
+ )
1599
+
1600
+
1601
+ add_bar_labels(
1602
+ ax,
1603
+ bars,
1604
+ orientation="horizontal"
1605
+ )
1606
+
1607
+
1608
+ ax.set_xlim(
1609
+ 0,
1610
+ counts.max() * 1.15
1611
+ )
1612
+
1613
+
1614
+ plt.tight_layout()
1615
+
1616
+ return fig
1617
+
1618
+
1619
+ def plot_faces_per_image(images_df):
1620
+
1621
+ if images_df.empty:
1622
+
1623
+ return empty_plot(
1624
+ "Faces per image"
1625
+ )
1626
+
1627
+
1628
+ values = images_df[
1629
+ "faces_detected"
1630
+ ].dropna()
1631
+
1632
+
1633
+ fig, ax = plt.subplots(
1634
+ figsize=(9, 5)
1635
+ )
1636
+
1637
+
1638
+ max_faces = int(
1639
+ images_df[
1640
+ "faces_detected"
1641
+ ].max()
1642
+ )
1643
+
1644
+
1645
+ counts, bins, patches = ax.hist(
1646
+ values,
1647
+ bins=range(
1648
+ 0,
1649
+ max_faces + 2
1650
+ ),
1651
+ align="left"
1652
+ )
1653
+
1654
+
1655
+ ax.set_title(
1656
+ "Detected faces per image",
1657
+ fontsize=14,
1658
+ fontweight="bold"
1659
+ )
1660
+
1661
+ ax.set_xlabel(
1662
+ "Number of faces"
1663
+ )
1664
+
1665
+ ax.set_ylabel(
1666
+ "Number of images"
1667
+ )
1668
+
1669
+
1670
+ add_histogram_labels(
1671
+ ax,
1672
+ counts,
1673
+ bins
1674
+ )
1675
+
1676
+
1677
+ plt.tight_layout()
1678
+
1679
+ return fig
1680
+
1681
+
1682
+ def plot_face_position(faces_df):
1683
+
1684
+ if faces_df.empty:
1685
+
1686
+ return empty_plot(
1687
+ "Face position"
1688
+ )
1689
+
1690
+
1691
+ table = pd.crosstab(
1692
+ faces_df["horizontal_position"],
1693
+ faces_df["vertical_position"]
1694
+ )
1695
+
1696
+
1697
+ fig, ax = plt.subplots(
1698
+ figsize=(9, 6)
1699
+ )
1700
+
1701
+
1702
+ table.plot(
1703
+ kind="bar",
1704
+ ax=ax
1705
+ )
1706
+
1707
+
1708
+ ax.set_title(
1709
+ "Detected face positions",
1710
+ fontsize=14,
1711
+ fontweight="bold"
1712
+ )
1713
+
1714
+ ax.set_xlabel(
1715
+ "Horizontal position"
1716
+ )
1717
+
1718
+ ax.set_ylabel(
1719
+ "Number of faces"
1720
+ )
1721
+
1722
+
1723
+ ax.legend(
1724
+ title="Vertical position"
1725
+ )
1726
+
1727
+
1728
+ # --------------------------------------------------------
1729
+ # Numerical values
1730
+ # --------------------------------------------------------
1731
+
1732
+ for container in ax.containers:
1733
+
1734
+ labels = []
1735
+
1736
+ for bar in container:
1737
+
1738
+ value = bar.get_height()
1739
+
1740
+ if value == 0:
1741
+
1742
+ labels.append("")
1743
+
1744
+ else:
1745
+
1746
+ labels.append(
1747
+ f"{int(value)}"
1748
+ )
1749
+
1750
+
1751
+ ax.bar_label(
1752
+ container,
1753
+ labels=labels,
1754
+ padding=2,
1755
+ fontsize=8
1756
+ )
1757
+
1758
+
1759
+ plt.tight_layout()
1760
+
1761
+ return fig
1762
+
1763
+
1764
+ def plot_face_area(faces_df):
1765
+
1766
+ if faces_df.empty:
1767
+
1768
+ return empty_plot(
1769
+ "Face area"
1770
+ )
1771
+
1772
+
1773
+ values = (
1774
+ faces_df["area_fraction"]
1775
+ * 100
1776
+ ).dropna()
1777
+
1778
+
1779
+ fig, ax = plt.subplots(
1780
+ figsize=(9, 5)
1781
+ )
1782
+
1783
+
1784
+ counts, bins, patches = ax.hist(
1785
+ values,
1786
+ bins=20
1787
+ )
1788
+
1789
+
1790
+ ax.set_title(
1791
+ "Face size relative to image",
1792
+ fontsize=14,
1793
+ fontweight="bold"
1794
+ )
1795
+
1796
+ ax.set_xlabel(
1797
+ "Face area (% of image)"
1798
+ )
1799
+
1800
+ ax.set_ylabel(
1801
+ "Number of faces"
1802
+ )
1803
+
1804
+
1805
+ add_histogram_labels(
1806
+ ax,
1807
+ counts,
1808
+ bins
1809
+ )
1810
+
1811
+
1812
+ plt.tight_layout()
1813
+
1814
+ return fig
1815
+
1816
+
1817
+ def plot_gender_by_category(faces_df):
1818
+
1819
+ if faces_df.empty:
1820
+
1821
+ return empty_plot(
1822
+ "Automatically perceived gender by category"
1823
+ )
1824
+
1825
+
1826
+ table = pd.crosstab(
1827
+ faces_df["category"],
1828
+ faces_df["auto_perceived_gender"]
1829
+ )
1830
+
1831
+
1832
+ fig, ax = plt.subplots(
1833
+ figsize=(11, 7)
1834
+ )
1835
+
1836
+
1837
+ table.plot(
1838
+ kind="bar",
1839
+ stacked=True,
1840
+ ax=ax
1841
+ )
1842
+
1843
+
1844
+ ax.set_title(
1845
+ "Automatically perceived gender by category (unvalidated)",
1846
+ fontsize=14,
1847
+ fontweight="bold"
1848
+ )
1849
+
1850
+ ax.set_xlabel(
1851
+ "Category"
1852
+ )
1853
+
1854
+ ax.set_ylabel(
1855
+ "Number of faces"
1856
+ )
1857
+
1858
+
1859
+ ax.legend(
1860
+ title="Auto label"
1861
+ )
1862
+
1863
+
1864
+ # --------------------------------------------------------
1865
+ # Numerical labels on stacked bars
1866
+ # --------------------------------------------------------
1867
+
1868
+ for container in ax.containers:
1869
+
1870
+ labels = []
1871
+
1872
+ for bar in container:
1873
+
1874
+ value = bar.get_height()
1875
+
1876
+ if value <= 0:
1877
+
1878
+ labels.append("")
1879
+
1880
+ else:
1881
+
1882
+ labels.append(
1883
+ f"{int(value)}"
1884
+ )
1885
+
1886
+
1887
+ ax.bar_label(
1888
+ container,
1889
+ labels=labels,
1890
+ label_type="center",
1891
+ fontsize=8,
1892
+ fontweight="bold"
1893
+ )
1894
+
1895
+
1896
+ plt.tight_layout()
1897
+
1898
+ return fig
1899
+
1900
+
1901
+ # ============================================================
1902
+ # EXCEL EXPORT
1903
+ # ============================================================
1904
+
1905
+ def create_excel(
1906
+ images_df,
1907
+ objects_df,
1908
+ faces_df
1909
+ ):
1910
+
1911
+ output = io.BytesIO()
1912
+
1913
+
1914
+ with pd.ExcelWriter(
1915
+ output,
1916
+ engine="openpyxl"
1917
+ ):
1918
+
1919
+
1920
+ # ----------------------------------------------------
1921
+ # Raw data
1922
+ # ----------------------------------------------------
1923
+
1924
+ images_df.to_excel(
1925
+ writer,
1926
+ sheet_name="Images",
1927
+ index=False
1928
+ )
1929
+
1930
+ objects_df.to_excel(
1931
+ writer,
1932
+ sheet_name="Objects",
1933
+ index=False
1934
+ )
1935
+
1936
+ faces_df.to_excel(
1937
+ writer,
1938
+ sheet_name="Faces",
1939
+ index=False
1940
+ )
1941
+
1942
+
1943
+ # ----------------------------------------------------
1944
+ # Object summary
1945
+ # ----------------------------------------------------
1946
+
1947
+ if not objects_df.empty:
1948
+
1949
+ object_summary = (
1950
+
1951
+ objects_df
1952
+ .groupby("object")
1953
+ .agg(
1954
+
1955
+ detections=(
1956
+ "object",
1957
+ "size"
1958
+ ),
1959
+
1960
+ mean_confidence=(
1961
+ "confidence",
1962
+ "mean"
1963
+ ),
1964
+
1965
+ mean_area_fraction=(
1966
+ "area_fraction",
1967
+ "mean"
1968
+ ),
1969
+
1970
+ )
1971
+
1972
+ .sort_values(
1973
+ "detections",
1974
+ ascending=False
1975
+ )
1976
+
1977
+ .reset_index()
1978
+
1979
+ )
1980
+
1981
+ else:
1982
+
1983
+ object_summary = pd.DataFrame()
1984
+
1985
+
1986
+ object_summary.to_excel(
1987
+ writer,
1988
+ sheet_name="Object Summary",
1989
+ index=False
1990
+ )
1991
+
1992
+
1993
+ # ----------------------------------------------------
1994
+ # Objects by category
1995
+ # ----------------------------------------------------
1996
+
1997
+ if not objects_df.empty:
1998
+
1999
+ objects_by_category = (
2000
+
2001
+ pd.crosstab(
2002
+ objects_df["category"],
2003
+ objects_df["object"]
2004
+ )
2005
+
2006
+ .reset_index()
2007
+
2008
+ )
2009
+
2010
+ else:
2011
+
2012
+ objects_by_category = pd.DataFrame()
2013
+
2014
+
2015
+ objects_by_category.to_excel(
2016
+ writer,
2017
+ sheet_name="Objects by Category",
2018
+ index=False
2019
+ )
2020
+
2021
+
2022
+ # ----------------------------------------------------
2023
+ # Faces by category
2024
+ # ----------------------------------------------------
2025
+
2026
+ if not faces_df.empty:
2027
+
2028
+ faces_by_category = (
2029
+
2030
+ faces_df
2031
+ .groupby("category")
2032
+ .size()
2033
+ .reset_index(
2034
+ name="detected_faces"
2035
+ )
2036
+
2037
+ )
2038
+
2039
+ else:
2040
+
2041
+ faces_by_category = pd.DataFrame()
2042
+
2043
+
2044
+ faces_by_category.to_excel(
2045
+ writer,
2046
+ sheet_name="Faces by Category",
2047
+ index=False
2048
+ )
2049
+
2050
+
2051
+ # ----------------------------------------------------
2052
+ # Face positions
2053
+ # ----------------------------------------------------
2054
+
2055
+ if not faces_df.empty:
2056
+
2057
+ face_positions = (
2058
+
2059
+ pd.crosstab(
2060
+ faces_df["horizontal_position"],
2061
+ faces_df["vertical_position"]
2062
+ )
2063
+
2064
+ .reset_index()
2065
+
2066
+ )
2067
+
2068
+ else:
2069
+
2070
+ face_positions = pd.DataFrame()
2071
+
2072
+
2073
+ face_positions.to_excel(
2074
+ writer,
2075
+ sheet_name="Face Positions",
2076
+ index=False
2077
+ )
2078
+
2079
+
2080
+ # ----------------------------------------------------
2081
+ # Auto gender by category
2082
+ # ----------------------------------------------------
2083
+
2084
+ if not faces_df.empty:
2085
+
2086
+ gender_by_category = (
2087
+
2088
+ pd.crosstab(
2089
+ faces_df["category"],
2090
+ faces_df["auto_perceived_gender"]
2091
+ )
2092
+
2093
+ .reset_index()
2094
+
2095
+ )
2096
+
2097
+ else:
2098
+
2099
+ gender_by_category = pd.DataFrame()
2100
+
2101
+
2102
+ gender_by_category.to_excel(
2103
+ writer,
2104
+ sheet_name="Auto Gender by Category",
2105
+ index=False
2106
+ )
2107
+
2108
+
2109
+ # ----------------------------------------------------
2110
+ # Category summary
2111
+ # ----------------------------------------------------
2112
+
2113
+ if not images_df.empty:
2114
+
2115
+ category_summary = (
2116
+
2117
+ images_df
2118
+ .groupby("category")
2119
+ .agg(
2120
+
2121
+ images=(
2122
+ "filename",
2123
+ "count"
2124
+ ),
2125
+
2126
+ total_objects=(
2127
+ "objects_detected",
2128
+ "sum"
2129
+ ),
2130
+
2131
+ mean_objects=(
2132
+ "objects_detected",
2133
+ "mean"
2134
+ ),
2135
+
2136
+ total_faces=(
2137
+ "faces_detected",
2138
+ "sum"
2139
+ ),
2140
+
2141
+ mean_faces=(
2142
+ "faces_detected",
2143
+ "mean"
2144
+ ),
2145
+
2146
+ auto_female_faces=(
2147
+ "auto_female_faces",
2148
+ "sum"
2149
+ ),
2150
+
2151
+ auto_male_faces=(
2152
+ "auto_male_faces",
2153
+ "sum"
2154
+ ),
2155
+
2156
+ auto_uncertain_faces=(
2157
+ "auto_uncertain_faces",
2158
+ "sum"
2159
+ ),
2160
+
2161
+ mean_processing_seconds=(
2162
+ "processing_seconds",
2163
+ "mean"
2164
+ ),
2165
+
2166
+ )
2167
+
2168
+ .reset_index()
2169
+
2170
+ )
2171
+
2172
+ else:
2173
+
2174
+ category_summary = pd.DataFrame()
2175
+
2176
+
2177
+ category_summary.to_excel(
2178
+ writer,
2179
+ sheet_name="Category Summary",
2180
+ index=False
2181
+ )
2182
+
2183
+
2184
+ # ----------------------------------------------------
2185
+ # Manual coding
2186
+ # ----------------------------------------------------
2187
+
2188
+ if not faces_df.empty:
2189
+
2190
+ manual_coding = faces_df[
2191
+ FACE_COLUMNS_MANUAL
2192
+ ].copy()
2193
+
2194
+ else:
2195
+
2196
+ manual_coding = pd.DataFrame(
2197
+ columns=FACE_COLUMNS_MANUAL
2198
+ )
2199
+
2200
+
2201
+ manual_coding.to_excel(
2202
+ writer,
2203
+ sheet_name="Manual Coding",
2204
+ index=False
2205
+ )
2206
+
2207
+
2208
+ # ----------------------------------------------------
2209
+ # Global summary
2210
+ # ----------------------------------------------------
2211
+
2212
+ summary = pd.DataFrame({
2213
+
2214
+ "metric": [
2215
+
2216
+ "Images",
2217
+
2218
+ "Object detections",
2219
+
2220
+ "Unique object classes",
2221
+
2222
+ "Face detections",
2223
+
2224
+ "Faces auto-labelled female",
2225
+
2226
+ "Faces auto-labelled male",
2227
+
2228
+ "Faces auto-labelled uncertain",
2229
+
2230
+ "Categories",
2231
+
2232
+ "Average objects/image",
2233
+
2234
+ "Average faces/image",
2235
+
2236
+ "Average face area (%)",
2237
+
2238
+ ],
2239
+
2240
+ "value": [
2241
+
2242
+ len(images_df),
2243
+
2244
+ len(objects_df),
2245
+
2246
+ (
2247
+ objects_df["object"].nunique()
2248
+ if not objects_df.empty
2249
+ else 0
2250
+ ),
2251
+
2252
+ len(faces_df),
2253
+
2254
+ (
2255
+ int(
2256
+ (
2257
+ faces_df[
2258
+ "auto_perceived_gender"
2259
+ ]
2260
+ == "female"
2261
+ ).sum()
2262
+ )
2263
+
2264
+ if not faces_df.empty
2265
+
2266
+ else 0
2267
+ ),
2268
+
2269
+ (
2270
+ int(
2271
+ (
2272
+ faces_df[
2273
+ "auto_perceived_gender"
2274
+ ]
2275
+ == "male"
2276
+ ).sum()
2277
+ )
2278
+
2279
+ if not faces_df.empty
2280
+
2281
+ else 0
2282
+ ),
2283
+
2284
+ (
2285
+ int(
2286
+ (
2287
+ faces_df[
2288
+ "auto_perceived_gender"
2289
+ ]
2290
+ == "uncertain"
2291
+ ).sum()
2292
+ )
2293
+
2294
+ if not faces_df.empty
2295
+
2296
+ else 0
2297
+ ),
2298
+
2299
+ (
2300
+ images_df[
2301
+ "category"
2302
+ ].nunique()
2303
+
2304
+ if not images_df.empty
2305
+
2306
+ else 0
2307
+ ),
2308
+
2309
+ (
2310
+ images_df[
2311
+ "objects_detected"
2312
+ ].mean()
2313
+
2314
+ if not images_df.empty
2315
+
2316
+ else 0
2317
+ ),
2318
+
2319
+ (
2320
+ images_df[
2321
+ "faces_detected"
2322
+ ].mean()
2323
+
2324
+ if not images_df.empty
2325
+
2326
+ else 0
2327
+ ),
2328
+
2329
+ (
2330
+ faces_df[
2331
+ "area_fraction"
2332
+ ].mean() * 100
2333
+
2334
+ if not faces_df.empty
2335
+
2336
+ else 0
2337
+ ),
2338
+
2339
+ ],
2340
+
2341
+ })
2342
+
2343
+
2344
+ summary.to_excel(
2345
+ writer,
2346
+ sheet_name="Summary",
2347
+ index=False
2348
+ )
2349
+
2350
+
2351
+ output.seek(0)
2352
+
2353
+ return output
2354
+
2355
+
2356
+ # ============================================================
2357
+ # MAIN ZIP ANALYSIS
2358
+ # ============================================================
2359
+
2360
+ @spaces.GPU
2361
+ def analyze_zip(
2362
+ zip_file,
2363
+ progress=gr.Progress()
2364
+ ):
2365
+
2366
+ if zip_file is None:
2367
+
2368
+ raise gr.Error(
2369
+ "Please upload a ZIP file."
2370
+ )
2371
+
2372
+
2373
+ start_total = time.time()
2374
+
2375
+
2376
+ temp_dir = tempfile.mkdtemp(
2377
+ prefix="image_analysis_"
2378
+ )
2379
+
2380
+
2381
+ try:
2382
+
2383
+ progress(
2384
+ 0.02,
2385
+ desc="Extracting ZIP..."
2386
+ )
2387
+
2388
+
2389
+ zip_path = (
2390
+ zip_file
2391
+ if isinstance(zip_file, str)
2392
+ else zip_file.name
2393
+ )
2394
+
2395
+
2396
+ with zipfile.ZipFile(
2397
+ zip_path,
2398
+ "r"
2399
+ ) as archive:
2400
+
2401
+ archive.extractall(
2402
+ temp_dir
2403
+ )
2404
+
2405
+
2406
+ image_paths = list_images_recursive(
2407
+ temp_dir
2408
+ )
2409
+
2410
+
2411
+ if not image_paths:
2412
+
2413
+ raise gr.Error(
2414
+ "No supported images were found."
2415
+ )
2416
+
2417
+
2418
+ total = len(
2419
+ image_paths
2420
+ )
2421
+
2422
+
2423
+ print(
2424
+ f"Found {total} images."
2425
+ )
2426
+
2427
+
2428
+ image_rows = []
2429
+
2430
+ object_rows = []
2431
+
2432
+ face_rows = []
2433
+
2434
+ annotated_gallery = []
2435
+
2436
+ object_gallery = []
2437
+
2438
+ face_gallery = []
2439
+
2440
+
2441
+ for index, image_path in enumerate(
2442
+ image_paths
2443
+ ):
2444
+
2445
+
2446
+ progress(
2447
+ 0.05 +
2448
+ 0.75 *
2449
+ (index / total),
2450
+
2451
+ desc=(
2452
+ f"Processing "
2453
+ f"{index + 1}/{total}"
2454
+ )
2455
+ )
2456
+
2457
+
2458
+ (
2459
+ image_row,
2460
+ image_objects,
2461
+ image_faces,
2462
+ annotated,
2463
+ object_crops,
2464
+ face_crops,
2465
+ _elapsed,
2466
+ ) = process_single_image(
2467
+ image_path,
2468
+ temp_dir
2469
+ )
2470
+
2471
+
2472
+ if image_row is None:
2473
+
2474
+ continue
2475
+
2476
+
2477
+ image_rows.append(
2478
+ image_row
2479
+ )
2480
+
2481
+ object_rows.extend(
2482
+ image_objects
2483
+ )
2484
+
2485
+ face_rows.extend(
2486
+ image_faces
2487
+ )
2488
+
2489
+
2490
+ annotated_gallery.append(
2491
+ (
2492
+ annotated,
2493
+ os.path.basename(
2494
+ image_path
2495
+ )
2496
+ )
2497
+ )
2498
+
2499
+
2500
+ for crop, label in object_crops:
2501
+
2502
+ if len(object_gallery) < MAX_OBJECT_CROPS:
2503
+
2504
+ object_gallery.append(
2505
+ (
2506
+ crop,
2507
+ label
2508
+ )
2509
+ )
2510
+
2511
+
2512
+ for crop, label in face_crops:
2513
+
2514
+ if len(face_gallery) < MAX_FACE_CROPS:
2515
+
2516
+ face_gallery.append(
2517
+ (
2518
+ crop,
2519
+ label
2520
+ )
2521
+ )
2522
+
2523
+
2524
+ # ----------------------------------------------------
2525
+ # DataFrames
2526
+ # ----------------------------------------------------
2527
+
2528
+ images_df = pd.DataFrame(
2529
+ image_rows
2530
+ )
2531
+
2532
+ objects_df = pd.DataFrame(
2533
+ object_rows
2534
+ )
2535
+
2536
+ faces_df = pd.DataFrame(
2537
+ face_rows
2538
+ )
2539
+
2540
+
2541
+ if objects_df.empty:
2542
+
2543
+ objects_df = pd.DataFrame(
2544
+ columns=OBJECT_COLUMNS
2545
+ )
2546
+
2547
+
2548
+ if faces_df.empty:
2549
+
2550
+ faces_df = pd.DataFrame(
2551
+ columns=FACE_COLUMNS_ALL
2552
+ )
2553
+
2554
+
2555
+ # ----------------------------------------------------
2556
+ # Excel
2557
+ # ----------------------------------------------------
2558
+
2559
+ progress(
2560
+ 0.84,
2561
+ desc="Creating Excel report..."
2562
+ )
2563
+
2564
+
2565
+ excel_bytes = create_excel(
2566
+ images_df,
2567
+ objects_df,
2568
+ faces_df
2569
+ )
2570
+
2571
+
2572
+ output_xlsx = os.path.join(
2573
+ temp_dir,
2574
+ "image_analysis_results.xlsx"
2575
+ )
2576
+
2577
+
2578
+ with open(
2579
+ output_xlsx,
2580
+ "wb"
2581
+ ) as f:
2582
+
2583
+ f.write(
2584
+ excel_bytes.getvalue()
2585
+ )
2586
+
2587
+
2588
+ # ----------------------------------------------------
2589
+ # Plots
2590
+ # ----------------------------------------------------
2591
+
2592
+ progress(
2593
+ 0.90,
2594
+ desc="Creating plots..."
2595
+ )
2596
+
2597
+
2598
+ plot_objects = plot_top_objects(
2599
+ objects_df
2600
+ )
2601
+
2602
+
2603
+ plot_per_image = plot_objects_per_image(
2604
+ images_df
2605
+ )
2606
+
2607
+
2608
+ plot_category = plot_objects_by_category(
2609
+ objects_df
2610
+ )
2611
+
2612
+
2613
+ plot_faces_category = plot_faces_by_category(
2614
+ faces_df
2615
+ )
2616
+
2617
+
2618
+ plot_faces_image = plot_faces_per_image(
2619
+ images_df
2620
+ )
2621
+
2622
+
2623
+ plot_position = plot_face_position(
2624
+ faces_df
2625
+ )
2626
 
 
 
 
 
 
 
 
 
2627
 
2628
+ plot_face_size = plot_face_area(
2629
+ faces_df
2630
+ )
2631
 
 
 
 
 
 
 
 
 
 
 
 
 
2632
 
2633
+ plot_gender = plot_gender_by_category(
2634
+ faces_df
2635
+ )
2636
 
 
 
 
 
 
 
 
 
 
 
 
 
2637
 
2638
+ # ----------------------------------------------------
2639
+ # Summary
2640
+ # ----------------------------------------------------
2641
 
2642
+ elapsed_total = (
2643
+ time.time() -
2644
+ start_total
2645
+ )
 
 
 
 
 
 
 
 
 
2646
 
2647
 
2648
+ unique_objects = (
 
 
2649
 
2650
+ objects_df["object"].nunique()
 
 
 
 
 
 
2651
 
2652
+ if not objects_df.empty
2653
 
2654
+ else 0
 
 
 
 
 
 
 
 
 
 
 
 
2655
 
2656
+ )
2657
 
 
 
 
2658
 
2659
+ mean_objects = (
 
2660
 
2661
+ images_df[
2662
+ "objects_detected"
2663
+ ].mean()
2664
 
2665
+ if not images_df.empty
 
 
2666
 
2667
+ else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2668
 
 
 
 
 
 
 
 
 
 
2669
  )
2670
 
 
 
 
 
 
 
 
 
2671
 
2672
+ mean_faces = (
 
 
 
 
 
 
 
2673
 
2674
+ images_df[
2675
+ "faces_detected"
2676
+ ].mean()
 
 
 
 
 
 
 
2677
 
2678
+ if not images_df.empty
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2679
 
2680
+ else 0
 
 
 
 
 
2681
 
2682
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2683
 
 
 
2684
 
2685
+ mean_face_area = (
2686
 
2687
+ faces_df[
2688
+ "area_fraction"
2689
+ ].mean() * 100
2690
 
2691
+ if not faces_df.empty
 
2692
 
2693
+ else 0
 
2694
 
2695
+ )
 
2696
 
 
 
2697
 
2698
+ n_categories = (
2699
 
2700
+ images_df[
2701
+ "category"
2702
+ ].nunique()
2703
 
2704
+ if not images_df.empty
2705
 
2706
+ else 0
 
2707
 
2708
+ )
 
2709
 
 
 
 
 
 
 
2710
 
2711
+ avg_time = (
2712
 
2713
+ elapsed_total /
2714
+ len(images_df)
 
 
2715
 
2716
+ if len(images_df) > 0
 
 
 
 
 
 
 
 
2717
 
2718
+ else 0
 
2719
 
2720
+ )
 
 
2721
 
 
2722
 
2723
+ n_female = int(
2724
+ (
2725
+ faces_df[
2726
+ "auto_perceived_gender"
2727
+ ]
2728
+ == "female"
2729
+ ).sum()
2730
+ )
2731
 
 
 
 
2732
 
2733
+ n_male = int(
2734
+ (
2735
+ faces_df[
2736
+ "auto_perceived_gender"
2737
+ ]
2738
+ == "male"
2739
+ ).sum()
2740
+ )
2741
 
 
 
2742
 
2743
+ n_uncertain = int(
2744
+ (
2745
+ faces_df[
2746
+ "auto_perceived_gender"
2747
+ ]
2748
+ == "uncertain"
2749
+ ).sum()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2750
  )
 
 
2751
 
 
 
 
2752
 
2753
  summary_text = f"""
2754
+
2755
  # Analysis completed
2756
 
2757
+ ## Dataset
2758
 
2759
  **Images:** {len(images_df):,}
2760
 
2761
  **Categories:** {n_categories}
2762
 
2763
+ ---
2764
+
2765
+ ## Objects
2766
 
2767
  **Object detections:** {len(objects_df):,}
2768
 
 
2770
 
2771
  **Average objects/image:** {mean_objects:.2f}
2772
 
2773
+ ---
2774
+
2775
+ ## Faces
2776
 
2777
  **Detected faces:** {len(faces_df):,}
2778
 
 
2780
 
2781
  **Mean face area:** {mean_face_area:.2f}% of image
2782
 
2783
+ ---
2784
+
2785
+ ## Automatic perceived gender
2786
+
2787
+ **Female:** {n_female:,}
2788
+ **Male:** {n_male:,}
2789
+ **Uncertain:** {n_uncertain:,}
2790
 
2791
+ These labels are automatic guesses of perceived gender
2792
+ presentation from appearance, not gender identity.
2793
 
2794
+ Error rates can differ by skin tone, age and image quality.
 
 
 
2795
 
2796
+ Validate against your manual coding on a sample and report
2797
+ the agreement rate.
2798
+
2799
+ ---
2800
+
2801
+ ## Performance
2802
 
2803
  **Total time:** {elapsed_total:.1f} seconds
2804
 
 
2810
 
2811
  **Face detector:** MTCNN
2812
 
2813
+ **Gender classifier:** `{GENDER_MODEL_NAME}`
2814
+
2815
+ **Minimum gender confidence:** {GENDER_MIN_CONFIDENCE}
2816
 
2817
  ---
2818
 
2819
+ ## Manual coding
2820
 
2821
  The Excel file contains a **Manual Coding** sheet.
2822
 
2823
+ Each detected face receives a unique identifier such as
2824
+ `face_001`.
2825
+
2826
+ The automatic prediction
2827
+
2828
+ `auto_perceived_gender`
2829
+
2830
+ and
2831
+
2832
+ `auto_gender_confidence`
2833
+
2834
+ sit next to blank fields for:
2835
 
2836
  - `manual_gender`
2837
  - `manual_age`
 
2839
  - `manual_notes`
2840
  """
2841
 
2842
+
2843
+ progress(
2844
+ 1.0,
2845
+ desc="Completed"
2846
+ )
2847
+
2848
 
2849
  return (
2850
+
2851
  images_df,
2852
+
2853
  output_xlsx,
2854
+
2855
  annotated_gallery,
2856
+
2857
  object_gallery,
2858
+
2859
  face_gallery,
2860
+
2861
  plot_objects,
2862
+
2863
  plot_per_image,
2864
+
2865
  plot_category,
2866
+
2867
  plot_faces_category,
2868
+
2869
  plot_faces_image,
2870
+
2871
  plot_position,
2872
+
2873
  plot_face_size,
2874
+
2875
  plot_gender,
2876
+
2877
  summary_text,
2878
+
2879
  )
2880
 
2881
+
2882
  except gr.Error:
2883
+
2884
  raise
2885
 
2886
+
2887
  except Exception as e:
 
 
2888
 
2889
+ print(
2890
+ "ANALYSIS ERROR:",
2891
+ repr(e)
2892
+ )
2893
+
2894
+ raise gr.Error(
2895
+ f"Analysis failed: {e}"
2896
+ )
2897
+
2898
+
2899
+ # Temporary directory intentionally
2900
+ # remains because the XLSX output lives there.
2901
 
2902
 
2903
  # ============================================================
2904
  # GRADIO UI
2905
  # ============================================================
2906
 
2907
+ with gr.Blocks(
2908
+ title=APP_TITLE
2909
+ ) as demo:
2910
+
2911
 
2912
  gr.Markdown(
2913
  """
 
2917
 
2918
  ### Automatic analysis
2919
 
2920
+ - YOLO object detection
2921
+ - Multiple objects per image
2922
+ - Object confidence
2923
+ - Object bounding boxes
2924
+ - Object size
2925
+ - Face detection
2926
+ - Face confidence
2927
+ - Face position
2928
+ - Face size
2929
+ - Automatic perceived-gender guess
2930
  - ZIP folder/category analysis
2931
 
2932
  ### Research coding
2933
 
2934
+ Detected faces receive unique IDs and are exported as
2935
+ face crops for manual coding.
 
2936
 
2937
+ The Excel report contains a **Manual Coding** sheet where
2938
+ the automatic prediction sits next to your manual fields.
2939
+
2940
+ > ⚠️ Automatic gender labels are *perceived gender
2941
+ > presentation* guesses, not gender identity.
2942
+ > Treat them as a first pass and validate them manually.
2943
  """
2944
  )
2945
 
2946
+
2947
  zip_input = gr.File(
2948
  label="ZIP file containing images",
2949
  file_types=[".zip"],
2950
  )
2951
 
2952
+
2953
+ analyze_button = gr.Button(
2954
+ "πŸš€ Analyze images",
2955
+ variant="primary"
2956
+ )
2957
+
2958
 
2959
  status = gr.Markdown()
2960
 
2961
+
2962
  results_dataframe = gr.Dataframe(
2963
  label="Image-level results",
2964
  interactive=False,
2965
  wrap=True,
2966
  )
2967
 
2968
+
2969
+ excel_output = gr.File(
2970
+ label="Download Excel report"
2971
+ )
2972
+
2973
 
2974
  gr.Markdown(
2975
  """
2976
  ## πŸ”΄ Objects + πŸ”΅ Faces
2977
 
2978
+ πŸ”΄ Red boxes = detected objects
2979
 
2980
+ πŸ”΅ Blue boxes = detected faces
2981
  """
2982
  )
2983
 
2984
+
2985
  annotated_gallery = gr.Gallery(
2986
  label="Annotated images",
2987
  columns=4,
 
2990
  object_fit="contain",
2991
  )
2992
 
2993
+
2994
+ gr.Markdown(
2995
+ "## Detected objects"
2996
+ )
2997
+
2998
 
2999
  object_gallery = gr.Gallery(
3000
  label="Object crops",
 
3004
  object_fit="contain",
3005
  )
3006
 
3007
+
3008
  gr.Markdown(
3009
  """
3010
+ ## πŸ‘€ Detected faces
3011
+
3012
+ Each crop has a
3013
 
3014
+ `face_id | confidence | auto gender`
3015
+
3016
+ label.
3017
+
3018
+ The `face_id` corresponds to the
3019
+ **Manual Coding** sheet in the Excel file.
3020
  """
3021
  )
3022
 
3023
+
3024
  face_gallery = gr.Gallery(
3025
  label="Face crops",
3026
  columns=6,
 
3029
  object_fit="contain",
3030
  )
3031
 
3032
+
3033
+ # ========================================================
3034
+ # OBJECT PLOTS
3035
+ # ========================================================
3036
+
3037
+ gr.Markdown(
3038
+ "## πŸ“Š Object analysis"
3039
+ )
3040
+
3041
 
3042
  with gr.Row():
 
 
3043
 
3044
+ plot_objects_output = gr.Plot(
3045
+ label="Most frequent objects"
3046
+ )
3047
+
3048
+ plot_per_image_output = gr.Plot(
3049
+ label="Objects per image"
3050
+ )
3051
+
3052
+
3053
+ plot_category_output = gr.Plot(
3054
+ label="Objects by category"
3055
+ )
3056
+
3057
+
3058
+ # ========================================================
3059
+ # FACE PLOTS
3060
+ # ========================================================
3061
+
3062
+ gr.Markdown(
3063
+ "## πŸ‘€ Face detection analysis"
3064
+ )
3065
 
 
3066
 
3067
  with gr.Row():
3068
+
3069
+ plot_faces_category_output = gr.Plot(
3070
+ label="Faces by category"
3071
+ )
3072
+
3073
+ plot_faces_image_output = gr.Plot(
3074
+ label="Faces per image"
3075
+ )
3076
+
3077
 
3078
  with gr.Row():
 
 
3079
 
3080
+ plot_position_output = gr.Plot(
3081
+ label="Face position"
3082
+ )
3083
+
3084
+ plot_face_size_output = gr.Plot(
3085
+ label="Face size"
3086
+ )
3087
+
3088
+
3089
+ plot_gender_output = gr.Plot(
3090
+ label="Automatically perceived gender by category"
3091
+ )
3092
+
3093
+
3094
+ # ========================================================
3095
+ # BUTTON ACTION
3096
+ # ========================================================
3097
 
3098
  analyze_button.click(
3099
+
3100
  fn=analyze_zip,
3101
+
3102
+ inputs=[
3103
+ zip_input
3104
+ ],
3105
+
3106
  outputs=[
3107
+
3108
  results_dataframe,
3109
+
3110
  excel_output,
3111
+
3112
  annotated_gallery,
3113
+
3114
  object_gallery,
3115
+
3116
  face_gallery,
3117
+
3118
  plot_objects_output,
3119
+
3120
  plot_per_image_output,
3121
+
3122
  plot_category_output,
3123
+
3124
  plot_faces_category_output,
3125
+
3126
  plot_faces_image_output,
3127
+
3128
  plot_position_output,
3129
+
3130
  plot_face_size_output,
3131
+
3132
  plot_gender_output,
3133
+
3134
  status,
3135
+
3136
  ],
3137
  )
3138
 
 
3142
  # ============================================================
3143
 
3144
  if __name__ == "__main__":
3145
+
3146
  demo.launch(
3147
+
3148
  server_name="0.0.0.0",
3149
+
3150
  server_port=7860,
3151
+
3152
  show_error=True,
3153
+
3154
  )