Spaces:
Running on Zero

clementBE commited on
Commit
375d6de
Β·
verified Β·
1 Parent(s): 1e82299

Update app.py

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