Spaces:
Running on Zero

clementBE commited on
Commit
e5b81cc
·
verified ·
1 Parent(s): 60b32f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1479 -1021
app.py CHANGED
@@ -1,25 +1,30 @@
1
  # ============================================================
2
- # ZIP IMAGE ANALYSIS
3
  # ============================================================
4
  #
5
- # Features
6
  # ------------------------------------------------------------
7
- # 1. Recursive ZIP image extraction
8
- # 2. ResNet50 ImageNet classification
9
- # 3. Dominant color detection
10
- # 4. Face detection with DeepFace
11
- # 5. Age estimation with DeepFace
12
- # 6. Existing folder/category extraction
13
- # 7. Age × category analysis
14
- # 8. Face count analysis
15
- # 9. Diagnostic error reporting
16
- # 10. XLSX export with multiple sheets
17
- # 11. Gradio interface
 
 
 
 
 
18
  #
19
  # IMPORTANT
20
  # ------------------------------------------------------------
21
- # Categories are taken from the EXISTING folder structure.
22
- # They are not inferred from facial appearance.
23
  #
24
  # Example:
25
  #
@@ -27,6 +32,7 @@
27
  # Men/
28
  # image1.jpg
29
  # image2.jpg
 
30
  # Women/
31
  # image3.jpg
32
  # image4.jpg
@@ -36,6 +42,21 @@
36
  # ============================================================
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  # ============================================================
40
  # IMPORTS
41
  # ============================================================
@@ -49,30 +70,25 @@ import traceback
49
  import numpy as np
50
  import pandas as pd
51
 
52
- from PIL import Image
53
-
54
- import torch
55
- import torch.nn.functional as F
56
 
57
- from torchvision import transforms
58
- from torchvision.models import resnet50, ResNet50_Weights
59
 
60
- from sklearn.cluster import MiniBatchKMeans
61
 
62
- import matplotlib.pyplot as plt
63
 
64
  import gradio as gr
65
 
 
 
66
  from deepface import DeepFace
67
- import cv2
68
 
69
 
70
  # ============================================================
71
  # CONFIGURATION
72
  # ============================================================
73
 
74
- FACE_DETECTOR = "opencv"
75
-
76
  IMAGE_EXTENSIONS = (
77
  ".png",
78
  ".jpg",
@@ -83,6 +99,29 @@ IMAGE_EXTENSIONS = (
83
  ".tiff"
84
  )
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  # ============================================================
88
  # DEVICE
@@ -90,84 +129,38 @@ IMAGE_EXTENSIONS = (
90
 
91
  if torch.cuda.is_available():
92
 
93
- device = torch.device("cuda")
94
 
95
  else:
96
 
97
- device = torch.device("cpu")
98
 
99
 
100
  print("=" * 80)
101
- print("ZIP IMAGE ANALYSIS APPLICATION")
102
  print("=" * 80)
103
 
104
  print(
105
  f"PyTorch device: {device}"
106
  )
107
 
108
- print(
109
- f"CUDA available: {torch.cuda.is_available()}"
110
- )
111
-
112
  print("=" * 80)
113
 
114
 
115
  # ============================================================
116
- # RESNET50
117
  # ============================================================
118
 
119
- print("Loading ResNet50...")
120
-
121
- weights = ResNet50_Weights.DEFAULT
122
-
123
- model = resnet50(
124
- weights=weights
125
  )
126
 
127
- model = model.to(device)
128
-
129
- model.eval()
130
-
131
- print("ResNet50 loaded.")
132
-
133
-
134
- # ============================================================
135
- # IMAGE TRANSFORM
136
- # ============================================================
137
-
138
- transform = transforms.Compose([
139
-
140
- transforms.Resize(256),
141
-
142
- transforms.CenterCrop(224),
143
-
144
- transforms.ToTensor(),
145
-
146
- transforms.Normalize(
147
-
148
- mean=[
149
- 0.485,
150
- 0.456,
151
- 0.406
152
- ],
153
-
154
- std=[
155
- 0.229,
156
- 0.224,
157
- 0.225
158
- ]
159
- )
160
- ])
161
-
162
-
163
- # ============================================================
164
- # IMAGENET LABELS
165
- # ============================================================
166
-
167
- imagenet_classes = weights.meta["categories"]
168
 
169
  print(
170
- f"Loaded {len(imagenet_classes)} ImageNet labels."
171
  )
172
 
173
 
@@ -207,16 +200,16 @@ BASIC_COLORS = {
207
 
208
 
209
  # ============================================================
210
- # CLOSEST BASIC COLOR
211
  # ============================================================
212
 
213
  def closest_basic_color(rgb):
214
 
215
  r, g, b = rgb
216
 
217
- min_distance = float("inf")
218
 
219
- closest = None
220
 
221
  for name, color in BASIC_COLORS.items():
222
 
@@ -231,13 +224,13 @@ def closest_basic_color(rgb):
231
  (b - cb) ** 2
232
  )
233
 
234
- if distance < min_distance:
235
 
236
- min_distance = distance
237
 
238
- closest = name
239
 
240
- return closest
241
 
242
 
243
  # ============================================================
@@ -259,22 +252,16 @@ def get_dominant_color(
259
  image_small
260
  )
261
 
262
- if pixels.ndim != 3:
263
-
264
- raise ValueError(
265
- "Image does not contain RGB channels."
266
- )
267
-
268
  pixels = pixels.reshape(
269
  -1,
270
  3
271
  )
272
 
273
- # Limit KMeans computation
274
-
275
  if len(pixels) > 50000:
276
 
277
- rng = np.random.default_rng(0)
 
 
278
 
279
  indices = rng.choice(
280
 
@@ -287,133 +274,102 @@ def get_dominant_color(
287
 
288
  pixels = pixels[indices]
289
 
290
- kmeans = MiniBatchKMeans(
291
-
292
- n_clusters=num_colors,
293
 
294
- random_state=0,
 
 
295
 
296
- n_init=5
297
- )
298
 
299
- kmeans.fit(pixels)
300
 
301
- labels = kmeans.labels_
302
 
303
- counts = np.bincount(
304
- labels
305
  )
306
 
307
- dominant_color = (
308
- kmeans.cluster_centers_[
309
- np.argmax(counts)
310
- ]
311
  )
312
 
313
- dominant_color = tuple(
314
- dominant_color.astype(int)
 
 
315
  )
316
 
317
  hex_color = (
318
 
319
- f"#{dominant_color[0]:02x}"
320
 
321
- f"{dominant_color[1]:02x}"
322
 
323
- f"{dominant_color[2]:02x}"
324
  )
325
 
326
  return (
327
- dominant_color,
328
  hex_color
329
  )
330
 
331
 
332
  # ============================================================
333
- # RESNET CLASSIFICATION
334
  # ============================================================
335
 
336
- def classify_image(image):
337
-
338
- input_tensor = transform(
339
- image
340
- )
341
-
342
- input_tensor = (
343
- input_tensor
344
- .unsqueeze(0)
345
- .to(device)
346
- )
347
-
348
- with torch.no_grad():
349
-
350
- output = model(
351
- input_tensor
352
- )
353
-
354
- probabilities = F.softmax(
355
- output,
356
- dim=1
357
- )[0]
358
-
359
- top_probabilities, top_indices = (
360
- torch.topk(
361
- probabilities,
362
- 3
363
- )
364
- )
365
 
366
- predictions = []
367
 
368
- for index, probability in zip(
369
- top_indices,
370
- top_probabilities
371
  ):
372
 
373
- index = int(
374
- index.item()
375
- )
376
 
377
- predictions.append({
 
 
378
 
379
- "label":
380
- imagenet_classes[index],
381
 
382
- "confidence":
383
- float(
384
- probability.item()
385
- * 100
386
  )
387
- })
388
 
389
- return predictions
 
 
390
 
391
 
392
  # ============================================================
393
- # EXTRACT CATEGORY FROM PATH
394
  # ============================================================
395
 
396
- def extract_category(
397
- relative_path
 
398
  ):
399
 
400
- """
401
- Uses the first directory inside the ZIP
402
- as the category.
403
-
404
- Example:
405
-
406
- Men/photo1.jpg
407
- -> Men
408
 
409
- Women/photo2.jpg
410
- -> Women
411
 
412
- If the image is directly at the root:
 
 
413
 
414
- photo3.jpg
415
- -> ROOT
416
- """
417
 
418
  normalized = relative_path.replace(
419
  "\\",
@@ -430,25 +386,13 @@ def extract_category(
430
 
431
 
432
  # ============================================================
433
- # EXTRACT SUBCATEGORY
434
  # ============================================================
435
 
436
  def extract_subcategory(
437
  relative_path
438
  ):
439
 
440
- """
441
- Returns the complete directory path.
442
-
443
- Example:
444
-
445
- Men/Paris/photo1.jpg
446
-
447
- becomes:
448
-
449
- Men/Paris
450
- """
451
-
452
  normalized = relative_path.replace(
453
  "\\",
454
  "/"
@@ -466,262 +410,771 @@ def extract_subcategory(
466
 
467
 
468
  # ============================================================
469
- # FIND IMAGES RECURSIVELY
470
  # ============================================================
471
 
472
- def find_images(
473
- root_directory
474
  ):
475
 
476
- image_files = []
477
-
478
- for root, dirs, files in os.walk(
479
- root_directory
480
- ):
481
 
482
- for filename in files:
483
 
484
- if filename.lower().endswith(
485
- IMAGE_EXTENSIONS
486
- ):
487
 
488
- image_files.append(
 
 
489
 
490
- os.path.join(
491
- root,
492
- filename
493
- )
494
- )
495
 
496
- return sorted(
497
- image_files
498
- )
499
 
 
500
 
501
- # ============================================================
502
- # RELATIVE PATH
503
- # ============================================================
504
 
505
- def get_relative_filename(
506
- filepath,
507
- root
508
- ):
509
 
510
- return os.path.relpath(
511
- filepath,
512
- root
513
- )
514
 
 
515
 
516
- # ============================================================
517
- # DEEPFACE FACE + AGE ANALYSIS
518
- # ============================================================
519
 
520
- def analyze_faces(
521
- image
522
- ):
523
 
524
- result = {
525
 
526
- "faces": [],
527
 
528
- "face_count": 0,
529
 
530
- "error": ""
531
- }
532
 
533
- try:
 
 
 
 
 
534
 
535
- img_array = np.array(
536
- image
537
- )
538
 
539
- img_cv2 = cv2.cvtColor(
540
 
541
- img_array,
 
 
 
542
 
543
- cv2.COLOR_RGB2BGR
544
- )
545
 
546
- analysis = DeepFace.analyze(
 
 
 
547
 
548
- img_cv2,
 
 
549
 
550
- actions=[
551
- "age"
552
- ],
553
 
554
- enforce_detection=False,
 
 
555
 
556
- detector_backend=FACE_DETECTOR,
557
 
558
- silent=True
559
- )
560
 
561
- # ----------------------------------------------------
562
- # DeepFace can return either a dict or list
563
- # ----------------------------------------------------
564
 
565
- if isinstance(
566
- analysis,
567
- dict
568
- ):
569
 
570
- analysis = [
571
- analysis
572
- ]
573
 
574
- elif not isinstance(
575
- analysis,
576
- list
577
- ):
578
 
579
- analysis = []
 
580
 
581
- # ----------------------------------------------------
582
- # Process each detected face
583
- # ----------------------------------------------------
584
 
585
- for face in analysis:
 
 
586
 
587
- if not isinstance(
588
- face,
589
- dict
590
- ):
591
 
592
  continue
593
 
594
- age = face.get(
595
- "age"
596
- )
597
-
598
- region = face.get(
599
- "region",
600
- {}
601
- )
602
-
603
- result[
604
- "faces"
605
- ].append({
606
-
607
- "age": age,
608
-
609
- "region": region
610
- })
611
-
612
- result[
613
- "face_count"
614
- ] = len(
615
- result["faces"]
616
- )
617
-
618
  except Exception as e:
619
 
620
- result[
621
- "error"
622
- ] = (
623
 
624
  f"{type(e).__name__}: "
625
 
626
  f"{str(e)}"
627
  )
628
 
629
- print(
630
- "DeepFace error:",
631
- result["error"]
632
- )
633
-
634
- return result
635
 
636
 
637
  # ============================================================
638
- # DRAW FACE BOXES
639
  # ============================================================
640
 
641
- def draw_face_boxes(
642
  image,
643
- faces
644
  ):
645
 
646
- """
647
- Creates a diagnostic image showing
648
- detected face bounding boxes.
649
- """
650
-
651
  output = image.copy()
652
 
653
- for face in faces:
 
 
 
 
654
 
655
- region = face.get(
656
- "region",
657
- {}
658
  )
659
 
660
- try:
 
 
661
 
662
- x = int(
663
- region.get("x", 0)
664
- )
665
 
666
- y = int(
667
- region.get("y", 0)
668
- )
669
 
670
- w = int(
671
- region.get("w", 0)
672
- )
 
673
 
674
- h = int(
675
- region.get("h", 0)
676
- )
677
 
678
- if w > 0 and h > 0:
 
 
 
 
 
679
 
680
- # PIL drawing without extra
681
- # dependencies
682
 
683
- from PIL import ImageDraw
 
684
 
685
- draw = ImageDraw.Draw(
686
- output
687
- )
688
 
689
- draw.rectangle(
690
 
691
- [
692
- x,
693
- y,
694
- x + w,
695
- y + h
696
- ],
697
 
698
- outline="red",
 
 
 
699
 
700
- width=4
701
- )
 
 
 
702
 
703
  except Exception:
 
704
  pass
705
 
706
  return output
707
 
708
 
709
  # ============================================================
710
- # MAIN FUNCTION
711
  # ============================================================
712
 
713
- def classify_zip_and_analyze(
714
- zip_file,
715
- progress=gr.Progress()
716
  ):
717
 
718
- if zip_file is None:
719
 
720
- raise gr.Error(
721
- "Please upload a ZIP file."
722
- )
723
 
724
- zip_path = zip_file.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725
 
726
  zip_basename = os.path.splitext(
727
 
@@ -732,53 +1185,48 @@ def classify_zip_and_analyze(
732
 
733
  print()
734
  print("=" * 80)
735
-
736
  print(
737
- f"Processing: {zip_basename}"
738
  )
739
-
740
  print("=" * 80)
741
 
742
- results = []
 
 
 
 
743
 
744
  thumbnails = []
745
 
746
  face_gallery = []
747
 
 
 
748
  # ========================================================
749
- # TEMPORARY DIRECTORY
750
  # ========================================================
751
 
752
  with tempfile.TemporaryDirectory() as tmpdir:
753
 
754
- # ----------------------------------------------------
755
- # Extract ZIP
756
- # ----------------------------------------------------
757
-
758
- print(
759
- "Extracting ZIP..."
760
- )
761
-
762
  try:
763
 
764
  with zipfile.ZipFile(
765
  zip_path,
766
  "r"
767
- ) as zip_ref:
768
 
769
- zip_ref.extractall(
770
  tmpdir
771
  )
772
 
773
  except Exception as e:
774
 
775
  raise gr.Error(
776
-
777
- f"Could not extract ZIP: {e}"
778
  )
779
 
780
  # ----------------------------------------------------
781
- # Find all images recursively
782
  # ----------------------------------------------------
783
 
784
  image_files = find_images(
@@ -790,45 +1238,43 @@ def classify_zip_and_analyze(
790
  f"{len(image_files)}"
791
  )
792
 
793
- if len(image_files) == 0:
794
 
795
  raise gr.Error(
796
- "No images were found in the ZIP."
797
  )
798
 
799
  # ====================================================
800
- # PROCESS IMAGES
801
  # ====================================================
802
 
803
- for i, img_path in enumerate(
804
  image_files
805
  ):
806
 
807
  progress(
808
 
809
- (i + 1)
810
  /
811
  len(image_files),
812
 
813
  desc=(
814
 
815
- f"Processing "
816
-
817
- f"{i + 1}/"
818
-
819
  f"{len(image_files)}"
820
  )
821
  )
822
 
823
  relative_path = (
824
- get_relative_filename(
825
- img_path,
826
  tmpdir
827
  )
828
  )
829
 
830
  filename = os.path.basename(
831
- img_path
832
  )
833
 
834
  category = (
@@ -844,204 +1290,149 @@ def classify_zip_and_analyze(
844
  )
845
 
846
  print(
847
- f"[{i + 1}/"
848
  f"{len(image_files)}] "
849
  f"{relative_path}"
850
  )
851
 
852
  # ------------------------------------------------
853
- # Open image
854
  # ------------------------------------------------
855
 
856
  try:
857
 
858
  image = Image.open(
859
- img_path
860
  ).convert("RGB")
861
 
862
  except Exception as e:
863
 
864
  print(
865
- f"Image error: {e}"
866
  )
867
 
868
- results.append({
869
-
870
- "Filename":
871
- filename,
872
-
873
- "Relative Path":
874
- relative_path,
875
-
876
- "Category":
877
- category,
878
-
879
- "Subcategory":
880
- subcategory,
881
-
882
- "Top 1 Prediction":
883
- "",
884
-
885
- "Top 1 Confidence":
886
- np.nan,
887
-
888
- "Top 2 Prediction":
889
- "",
890
-
891
- "Top 2 Confidence":
892
- np.nan,
893
-
894
- "Top 3 Prediction":
895
- "",
896
-
897
- "Top 3 Confidence":
898
- np.nan,
899
-
900
- "Dominant Color":
901
- "",
902
-
903
- "Basic Color":
904
- "",
905
-
906
- "Face Count":
907
- 0,
908
-
909
- "Age Estimates":
910
- "",
911
-
912
- "Mean Estimated Age":
913
- np.nan,
914
-
915
- "Face Analysis Error":
916
- f"Image error: {e}"
917
- })
918
-
919
  continue
920
 
921
  # ------------------------------------------------
922
- # Thumbnail
923
  # ------------------------------------------------
924
 
925
  thumb = image.copy()
926
 
927
  thumb.thumbnail(
928
- (300, 300),
929
- Image.LANCZOS
930
  )
931
 
932
  thumbnails.append(
 
933
  (
934
  thumb,
935
- f"{category} | {filename}"
 
 
936
  )
937
  )
938
 
939
- # ------------------------------------------------
940
- # ResNet
941
- # ------------------------------------------------
942
-
943
- try:
944
 
945
- predictions = classify_image(
 
946
  image
947
  )
 
948
 
949
- except Exception as e:
950
-
951
- print(
952
- f"ResNet error: {e}"
953
- )
954
-
955
- predictions = []
956
 
957
- # ------------------------------------------------
958
- # Color
959
- # ------------------------------------------------
 
960
 
961
- try:
962
 
963
- rgb, hex_color = (
964
- get_dominant_color(
965
- image
966
- )
967
- )
968
 
969
- basic_color = (
970
- closest_basic_color(
971
- rgb
972
- )
973
- )
974
 
975
- except Exception as e:
 
976
 
977
- print(
978
- f"Color error: {e}"
979
- )
980
 
981
- hex_color = ""
 
982
 
983
- basic_color = ""
 
984
 
985
- # ------------------------------------------------
986
- # DeepFace
987
- # ------------------------------------------------
988
 
989
- face_result = (
990
- analyze_faces(
991
- image
992
- )
993
- )
994
 
995
- faces = face_result[
996
- "faces"
997
- ]
998
 
999
- face_count = face_result[
1000
- "face_count"
1001
- ]
1002
 
1003
- face_error = face_result[
1004
- "error"
1005
- ]
1006
 
1007
- # ------------------------------------------------
1008
- # Ages
1009
- # ------------------------------------------------
1010
 
1011
- ages = []
 
 
1012
 
1013
- for face in faces:
1014
 
1015
- age = face.get(
1016
- "age"
 
 
 
1017
  )
1018
 
1019
- if age is not None:
1020
-
1021
- try:
1022
-
1023
- ages.append(
1024
- float(age)
1025
- )
1026
 
1027
- except Exception:
1028
- pass
1029
 
1030
- if ages:
1031
 
1032
- mean_age = float(
1033
- np.mean(ages)
 
 
 
 
1034
  )
1035
 
1036
- else:
 
 
1037
 
1038
- mean_age = np.nan
 
 
 
 
1039
 
1040
- # ------------------------------------------------
1041
- # Face diagnostic gallery
1042
- # ------------------------------------------------
1043
 
1044
- if face_count > 0:
1045
 
1046
  face_image = (
1047
  draw_face_boxes(
@@ -1053,62 +1444,135 @@ def classify_zip_and_analyze(
1053
  face_gallery.append(
1054
 
1055
  (
 
1056
  face_image,
1057
 
1058
  (
1059
  f"{category} | "
1060
  f"{filename} | "
1061
- f"{face_count} face(s)"
 
1062
  )
1063
  )
1064
  )
1065
 
1066
- # ------------------------------------------------
1067
- # Predictions
1068
- # ------------------------------------------------
1069
-
1070
- prediction_values = [
1071
- "",
1072
- "",
1073
- ""
1074
- ]
1075
 
1076
- confidence_values = [
1077
- np.nan,
1078
- np.nan,
1079
- np.nan
1080
- ]
1081
 
1082
- for j, prediction in enumerate(
1083
- predictions[:3]
 
1084
  ):
1085
 
1086
- prediction_values[j] = (
1087
- prediction["label"]
1088
- )
1089
 
1090
- confidence_values[j] = (
1091
- prediction["confidence"]
1092
- )
 
1093
 
1094
- # ------------------------------------------------
1095
- # Ages as text
1096
- # ------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1097
 
1098
- age_text = ", ".join(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
 
1100
- str(
1101
- round(age)
 
 
 
 
 
 
 
 
 
 
 
 
1102
  )
1103
 
1104
- for age in ages
1105
- )
 
 
 
1106
 
1107
- # ------------------------------------------------
1108
- # Result
1109
- # ------------------------------------------------
1110
 
1111
- results.append({
 
 
 
 
 
 
1112
 
1113
  "Filename":
1114
  filename,
@@ -1122,23 +1586,52 @@ def classify_zip_and_analyze(
1122
  "Subcategory":
1123
  subcategory,
1124
 
1125
- "Top 1 Prediction":
1126
- prediction_values[0],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1127
 
1128
- "Top 1 Confidence":
1129
- confidence_values[0],
1130
 
1131
- "Top 2 Prediction":
1132
- prediction_values[1],
1133
 
1134
- "Top 2 Confidence":
1135
- confidence_values[1],
 
 
1136
 
1137
- "Top 3 Prediction":
1138
- prediction_values[2],
1139
 
1140
- "Top 3 Confidence":
1141
- confidence_values[2],
1142
 
1143
  "Dominant Color":
1144
  hex_color,
@@ -1146,108 +1639,122 @@ def classify_zip_and_analyze(
1146
  "Basic Color":
1147
  basic_color,
1148
 
1149
- "Face Count":
1150
- face_count,
1151
-
1152
- "Age Estimates":
1153
- age_text,
1154
-
1155
- "Mean Estimated Age":
1156
- mean_age,
1157
 
1158
- "Face Analysis Error":
1159
  face_error
1160
  })
1161
 
1162
  # ========================================================
1163
- # DATAFRAME
1164
  # ========================================================
1165
 
1166
- df = pd.DataFrame(
1167
- results
 
 
 
 
 
 
 
 
1168
  )
1169
 
1170
  # ========================================================
1171
- # FACE-LEVEL DATAFRAME
1172
  # ========================================================
1173
 
1174
- face_rows = []
1175
-
1176
- for _, row in df.iterrows():
1177
 
1178
- age_text = row[
1179
- "Age Estimates"
1180
- ]
1181
 
1182
- if not isinstance(
1183
- age_text,
1184
- str
1185
- ):
1186
 
1187
- continue
 
 
1188
 
1189
- if not age_text.strip():
1190
 
1191
- continue
 
 
 
1192
 
1193
- ages = []
 
 
 
 
1194
 
1195
- for value in age_text.split(","):
1196
 
1197
- try:
 
 
 
 
1198
 
1199
- ages.append(
1200
- float(
1201
- value.strip()
1202
- )
1203
- )
1204
 
1205
- except Exception:
1206
- pass
1207
 
1208
- for face_number, age in enumerate(
1209
- ages,
1210
- start=1
1211
- ):
 
 
1212
 
1213
- face_rows.append({
 
 
1214
 
1215
- "Filename":
1216
- row["Filename"],
1217
 
1218
- "Relative Path":
1219
- row["Relative Path"],
1220
 
1221
- "Category":
1222
- row["Category"],
 
1223
 
1224
- "Subcategory":
1225
- row["Subcategory"],
 
 
1226
 
1227
- "Face Number":
1228
- face_number,
 
 
1229
 
1230
- "Estimated Age":
1231
- age
1232
- })
1233
 
1234
- faces_df = pd.DataFrame(
1235
- face_rows
1236
- )
1237
 
1238
  # ========================================================
1239
- # AGE × CATEGORY SUMMARY
1240
  # ========================================================
1241
 
1242
  if len(faces_df) > 0:
1243
 
1244
- age_category_summary = (
1245
 
1246
  faces_df
1247
 
 
 
 
 
 
 
1248
  .groupby(
1249
  "Category"
1250
- )["Estimated Age"]
 
 
1251
 
1252
  .agg(
1253
  [
@@ -1263,52 +1770,35 @@ def classify_zip_and_analyze(
1263
  .reset_index()
1264
  )
1265
 
1266
- age_category_summary = (
1267
- age_category_summary
1268
- .rename(
1269
- columns={
1270
- "count":
1271
- "Face Count",
1272
 
1273
- "mean":
1274
- "Mean Age",
1275
 
1276
- "median":
1277
- "Median Age",
1278
 
1279
- "std":
1280
- "SD Age",
1281
 
1282
- "min":
1283
- "Minimum Age",
1284
 
1285
- "max":
1286
- "Maximum Age"
1287
- }
1288
- )
1289
- )
 
1290
 
1291
  else:
1292
 
1293
- age_category_summary = pd.DataFrame(
1294
- columns=[
1295
- "Category",
1296
- "Face Count",
1297
- "Mean Age",
1298
- "Median Age",
1299
- "SD Age",
1300
- "Minimum Age",
1301
- "Maximum Age"
1302
- ]
1303
- )
1304
 
1305
  # ========================================================
1306
- # AGE BINS × CATEGORY
1307
  # ========================================================
1308
 
1309
  if len(faces_df) > 0:
1310
 
1311
  age_bins = [
 
1312
  0,
1313
  18,
1314
  25,
@@ -1321,13 +1811,21 @@ def classify_zip_and_analyze(
1321
  ]
1322
 
1323
  age_labels = [
 
1324
  "<18",
 
1325
  "18–24",
 
1326
  "25–34",
 
1327
  "35–44",
 
1328
  "45–54",
 
1329
  "55–64",
 
1330
  "65–74",
 
1331
  "75+"
1332
  ]
1333
 
@@ -1355,51 +1853,60 @@ def classify_zip_and_analyze(
1355
  faces_df[
1356
  "Category"
1357
  ]
1358
- )
1359
-
1360
- age_group_category = (
1361
- age_group_category
1362
- .reset_index()
1363
- )
1364
 
1365
  else:
1366
 
1367
- age_group_category = (
1368
- pd.DataFrame()
1369
- )
1370
 
1371
  # ========================================================
1372
  # SUMMARY
1373
  # ========================================================
1374
 
1375
- total_images = len(df)
 
 
1376
 
1377
- images_with_faces = int(
1378
 
1379
- (
1380
- df[
1381
- "Face Count"
1382
- ] > 0
1383
- ).sum()
1384
  )
1385
 
1386
- total_faces = int(
 
 
1387
 
1388
- df[
1389
- "Face Count"
1390
- ].sum()
 
 
 
 
 
 
 
1391
  )
1392
 
1393
- face_errors = int(
1394
 
1395
- df[
1396
- "Face Analysis Error"
1397
- ]
1398
- .fillna("")
1399
- .astype(str)
1400
- .str.len()
1401
- .gt(0)
1402
- .sum()
 
 
 
 
 
 
 
 
 
1403
  )
1404
 
1405
  summary_df = pd.DataFrame({
@@ -1408,13 +1915,17 @@ def classify_zip_and_analyze(
1408
 
1409
  "Images processed",
1410
 
1411
- "Images containing faces",
1412
 
1413
  "Total detected faces",
1414
 
1415
- "Images with DeepFace errors",
1416
 
1417
- "Categories found"
 
 
 
 
1418
  ],
1419
 
1420
  "Value": [
@@ -1425,47 +1936,31 @@ def classify_zip_and_analyze(
1425
 
1426
  total_faces,
1427
 
1428
- face_errors,
1429
-
1430
- df[
1431
- "Category"
1432
- ].nunique()
1433
- ]
1434
- })
1435
 
1436
- print()
1437
- print("=" * 80)
1438
- print("SUMMARY")
1439
- print("=" * 80)
1440
 
1441
- print(
1442
- f"Images: {total_images}"
1443
- )
 
1444
 
1445
- print(
1446
- f"Images with faces: "
1447
- f"{images_with_faces}"
1448
- )
1449
 
1450
- print(
1451
- f"Detected faces: "
1452
- f"{total_faces}"
1453
- )
1454
 
1455
- print(
1456
- f"DeepFace errors: "
1457
- f"{face_errors}"
1458
- )
1459
 
1460
- print(
1461
- "Categories:"
1462
- )
1463
 
1464
- print(
1465
- df[
1466
- "Category"
1467
- ].value_counts()
1468
- )
1469
 
1470
  # ========================================================
1471
  # XLSX
@@ -1475,7 +1970,7 @@ def classify_zip_and_analyze(
1475
 
1476
  tempfile.gettempdir(),
1477
 
1478
- f"{zip_basename}_results.xlsx"
1479
  )
1480
 
1481
  with pd.ExcelWriter(
@@ -1485,11 +1980,11 @@ def classify_zip_and_analyze(
1485
  engine="openpyxl"
1486
  ) as writer:
1487
 
1488
- df.to_excel(
1489
 
1490
  writer,
1491
 
1492
- sheet_name="Image Analysis",
1493
 
1494
  index=False
1495
  )
@@ -1498,12 +1993,39 @@ def classify_zip_and_analyze(
1498
 
1499
  writer,
1500
 
1501
- sheet_name="Face Level",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1502
 
1503
  index=False
1504
  )
1505
 
1506
- age_category_summary.to_excel(
 
 
 
 
 
 
 
 
 
1507
 
1508
  writer,
1509
 
@@ -1531,49 +2053,40 @@ def classify_zip_and_analyze(
1531
  )
1532
 
1533
  # ========================================================
1534
- # PLOT 1 — BASIC COLORS
1535
  # ========================================================
1536
 
1537
  fig1, ax1 = plt.subplots(
1538
- figsize=(9, 5)
1539
  )
1540
 
1541
- color_counts = (
1542
-
1543
- df[
1544
- "Basic Color"
1545
- ]
1546
 
1547
- .replace(
1548
- "",
1549
- np.nan
 
 
 
1550
  )
1551
 
1552
- .dropna()
1553
-
1554
- .value_counts()
1555
- )
1556
-
1557
- if len(color_counts) > 0:
1558
 
1559
- ax1.bar(
1560
-
1561
- color_counts.index,
1562
 
1563
- color_counts.values
 
 
1564
  )
1565
 
1566
  ax1.set_title(
1567
- "Basic Color Frequency"
1568
- )
1569
-
1570
- ax1.set_ylabel(
1571
- "Number of images"
1572
  )
1573
 
1574
- ax1.tick_params(
1575
- axis="x",
1576
- rotation=45
1577
  )
1578
 
1579
  else:
@@ -1583,7 +2096,7 @@ def classify_zip_and_analyze(
1583
  0.5,
1584
  0.5,
1585
 
1586
- "No color data available",
1587
 
1588
  ha="center",
1589
  va="center"
@@ -1610,86 +2123,52 @@ def classify_zip_and_analyze(
1610
 
1611
  buf1.seek(0)
1612
 
1613
- plot1_img = Image.open(
1614
  buf1
1615
  ).convert("RGB")
1616
 
1617
  # ========================================================
1618
- # PLOT 2 — IMAGENET PREDICTIONS
1619
  # ========================================================
1620
 
1621
  fig2, ax2 = plt.subplots(
1622
- figsize=(10, 7)
1623
  )
1624
 
1625
- preds_flat = []
1626
-
1627
- for column in [
1628
-
1629
- "Top 1 Prediction",
1630
-
1631
- "Top 2 Prediction",
1632
-
1633
- "Top 3 Prediction"
1634
- ]:
1635
-
1636
- preds_flat.extend(
1637
-
1638
- df[column]
1639
 
1640
- .replace(
1641
- "",
1642
- np.nan
1643
- )
1644
-
1645
- .dropna()
1646
-
1647
- .tolist()
1648
- )
1649
-
1650
- if preds_flat:
1651
 
1652
- pred_counts = (
1653
-
1654
- pd.Series(
1655
- preds_flat
1656
- )
1657
 
1658
  .value_counts()
1659
 
1660
- .head(20)
1661
  )
1662
 
1663
- ax2.barh(
1664
 
1665
- pred_counts.index[::-1],
 
 
1666
 
1667
- pred_counts.values[::-1]
1668
  )
1669
 
1670
  ax2.set_title(
1671
- "ImageNet Prediction Distribution"
1672
  )
1673
 
1674
  ax2.set_xlabel(
1675
- "Count"
1676
  )
1677
 
1678
- else:
1679
-
1680
- ax2.text(
1681
-
1682
- 0.5,
1683
- 0.5,
1684
-
1685
- "No prediction data available",
1686
-
1687
- ha="center",
1688
- va="center"
1689
  )
1690
 
1691
- ax2.set_axis_off()
1692
-
1693
  fig2.tight_layout()
1694
 
1695
  buf2 = io.BytesIO()
@@ -1709,7 +2188,7 @@ def classify_zip_and_analyze(
1709
 
1710
  buf2.seek(0)
1711
 
1712
- plot2_img = Image.open(
1713
  buf2
1714
  ).convert("RGB")
1715
 
@@ -1721,19 +2200,22 @@ def classify_zip_and_analyze(
1721
  figsize=(8, 5)
1722
  )
1723
 
 
 
 
 
 
 
1724
  ax3.bar(
1725
 
1726
  [
1727
- "Images with faces",
1728
-
1729
- "Images without faces"
1730
  ],
1731
 
1732
  [
1733
  images_with_faces,
1734
-
1735
- total_images -
1736
- images_with_faces
1737
  ]
1738
  )
1739
 
@@ -1745,11 +2227,6 @@ def classify_zip_and_analyze(
1745
  "Number of images"
1746
  )
1747
 
1748
- ax3.tick_params(
1749
- axis="x",
1750
- rotation=20
1751
- )
1752
-
1753
  fig3.tight_layout()
1754
 
1755
  buf3 = io.BytesIO()
@@ -1769,130 +2246,89 @@ def classify_zip_and_analyze(
1769
 
1770
  buf3.seek(0)
1771
 
1772
- plot3_img = Image.open(
1773
  buf3
1774
  ).convert("RGB")
1775
 
1776
  # ========================================================
1777
- # PLOT 4 — FACES PER IMAGE
1778
  # ========================================================
1779
 
1780
  fig4, ax4 = plt.subplots(
1781
- figsize=(8, 5)
1782
- )
1783
-
1784
- face_distribution = (
1785
-
1786
- df[
1787
- "Face Count"
1788
- ]
1789
-
1790
- .value_counts()
1791
-
1792
- .sort_index()
1793
- )
1794
-
1795
- ax4.bar(
1796
-
1797
- face_distribution.index.astype(
1798
- str
1799
- ),
1800
-
1801
- face_distribution.values
1802
- )
1803
-
1804
- ax4.set_title(
1805
- "Detected Faces per Image"
1806
- )
1807
-
1808
- ax4.set_xlabel(
1809
- "Number of faces"
1810
- )
1811
-
1812
- ax4.set_ylabel(
1813
- "Number of images"
1814
  )
1815
 
1816
- fig4.tight_layout()
1817
-
1818
- buf4 = io.BytesIO()
1819
-
1820
- fig4.savefig(
1821
 
1822
- buf4,
 
 
 
 
 
1823
 
1824
- format="png",
1825
 
1826
- dpi=150,
1827
 
1828
- bbox_inches="tight"
1829
- )
1830
 
1831
- plt.close(fig4)
 
 
 
 
 
1832
 
1833
- buf4.seek(0)
 
 
1834
 
1835
- plot4_img = Image.open(
1836
- buf4
1837
- ).convert("RGB")
1838
 
1839
- # ========================================================
1840
- # PLOT 5 — OVERALL AGE DISTRIBUTION
1841
- # ========================================================
1842
 
1843
- fig5, ax5 = plt.subplots(
1844
- figsize=(9, 5)
1845
- )
1846
 
1847
- if len(faces_df) > 0:
1848
 
1849
- ax5.hist(
 
1850
 
1851
- faces_df[
1852
- "Estimated Age"
1853
- ],
1854
 
1855
- bins=range(
1856
- 0,
1857
- 101,
1858
- 5
1859
  )
1860
- )
1861
-
1862
- ax5.set_title(
1863
- "Estimated Age Distribution"
1864
- )
1865
 
1866
- ax5.set_xlabel(
1867
- "Estimated age"
1868
- )
1869
-
1870
- ax5.set_ylabel(
1871
- "Number of detected faces"
1872
- )
1873
 
1874
  else:
1875
 
1876
- ax5.text(
1877
 
1878
  0.5,
1879
  0.5,
1880
 
1881
- "No age estimates available",
1882
 
1883
  ha="center",
1884
  va="center"
1885
  )
1886
 
1887
- ax5.set_axis_off()
1888
 
1889
- fig5.tight_layout()
1890
 
1891
- buf5 = io.BytesIO()
1892
 
1893
- fig5.savefig(
1894
 
1895
- buf5,
1896
 
1897
  format="png",
1898
 
@@ -1901,38 +2337,34 @@ def classify_zip_and_analyze(
1901
  bbox_inches="tight"
1902
  )
1903
 
1904
- plt.close(fig5)
1905
 
1906
- buf5.seek(0)
1907
 
1908
- plot5_img = Image.open(
1909
- buf5
1910
  ).convert("RGB")
1911
 
1912
  # ========================================================
1913
- # PLOT 6 — AGE × CATEGORY
1914
  # ========================================================
1915
 
1916
- fig6, ax6 = plt.subplots(
1917
  figsize=(10, 6)
1918
  )
1919
 
1920
  if len(faces_df) > 0:
1921
 
1922
- categories = sorted(
1923
-
1924
- faces_df[
1925
- "Category"
1926
- ]
1927
- .dropna()
1928
- .unique()
1929
- )
1930
-
1931
- age_data = []
1932
 
1933
  labels = []
1934
 
1935
- for category in categories:
 
 
 
 
 
1936
 
1937
  values = (
1938
 
@@ -1951,7 +2383,7 @@ def classify_zip_and_analyze(
1951
 
1952
  if len(values) > 0:
1953
 
1954
- age_data.append(
1955
  values
1956
  )
1957
 
@@ -1959,30 +2391,30 @@ def classify_zip_and_analyze(
1959
  str(category)
1960
  )
1961
 
1962
- if age_data:
1963
 
1964
- ax6.boxplot(
1965
 
1966
- age_data,
1967
 
1968
  labels=labels,
1969
 
1970
  showmeans=True
1971
  )
1972
 
1973
- ax6.set_title(
1974
  "Estimated Age by Existing Image Category"
1975
  )
1976
 
1977
- ax6.set_xlabel(
1978
- "Image category"
1979
  )
1980
 
1981
- ax6.set_ylabel(
1982
  "Estimated age"
1983
  )
1984
 
1985
- ax6.tick_params(
1986
 
1987
  axis="x",
1988
 
@@ -1991,41 +2423,41 @@ def classify_zip_and_analyze(
1991
 
1992
  else:
1993
 
1994
- ax6.text(
1995
 
1996
  0.5,
1997
  0.5,
1998
 
1999
- "No category-level age data",
2000
 
2001
  ha="center",
2002
  va="center"
2003
  )
2004
 
2005
- ax6.set_axis_off()
2006
 
2007
  else:
2008
 
2009
- ax6.text(
2010
 
2011
  0.5,
2012
  0.5,
2013
 
2014
- "No age/category data available",
2015
 
2016
  ha="center",
2017
  va="center"
2018
  )
2019
 
2020
- ax6.set_axis_off()
2021
 
2022
- fig6.tight_layout()
2023
 
2024
- buf6 = io.BytesIO()
2025
 
2026
- fig6.savefig(
2027
 
2028
- buf6,
2029
 
2030
  format="png",
2031
 
@@ -2034,86 +2466,93 @@ def classify_zip_and_analyze(
2034
  bbox_inches="tight"
2035
  )
2036
 
2037
- plt.close(fig6)
2038
 
2039
- buf6.seek(0)
2040
 
2041
- plot6_img = Image.open(
2042
- buf6
2043
  ).convert("RGB")
2044
 
2045
  # ========================================================
2046
- # PLOT 7 — AGE GROUP × CATEGORY
2047
  # ========================================================
2048
 
2049
- fig7, ax7 = plt.subplots(
2050
  figsize=(11, 6)
2051
  )
2052
 
2053
  if len(age_group_category) > 0:
2054
 
2055
- plot_data = (
 
2056
  age_group_category
 
2057
  .set_index(
2058
  "Age Group"
2059
  )
2060
  )
2061
 
2062
- plot_data.plot(
2063
 
2064
  kind="bar",
2065
 
2066
- ax=ax7
2067
  )
2068
 
2069
- ax7.set_title(
2070
  "Age Groups by Existing Image Category"
2071
  )
2072
 
2073
- ax7.set_xlabel(
2074
  "Estimated age group"
2075
  )
2076
 
2077
- ax7.set_ylabel(
2078
- "Number of detected faces"
 
 
 
 
 
 
 
2079
  )
2080
 
2081
- ax7.legend(
 
2082
  title="Category",
 
2083
  bbox_to_anchor=(
2084
  1.02,
2085
  1
2086
  ),
2087
- loc="upper left"
2088
- )
2089
 
2090
- ax7.tick_params(
2091
- axis="x",
2092
- rotation=45
2093
  )
2094
 
2095
  else:
2096
 
2097
- ax7.text(
2098
 
2099
  0.5,
2100
  0.5,
2101
 
2102
- "No age-group/category data available",
2103
 
2104
  ha="center",
2105
  va="center"
2106
  )
2107
 
2108
- ax7.set_axis_off()
2109
 
2110
- fig7.tight_layout()
2111
 
2112
- buf7 = io.BytesIO()
2113
 
2114
- fig7.savefig(
2115
 
2116
- buf7,
2117
 
2118
  format="png",
2119
 
@@ -2122,26 +2561,40 @@ def classify_zip_and_analyze(
2122
  bbox_inches="tight"
2123
  )
2124
 
2125
- plt.close(fig7)
2126
 
2127
- buf7.seek(0)
2128
 
2129
- plot7_img = Image.open(
2130
- buf7
2131
  ).convert("RGB")
2132
 
2133
  # ========================================================
2134
- # FINAL
2135
  # ========================================================
2136
 
2137
  print()
2138
  print("=" * 80)
2139
- print("PROCESSING COMPLETE")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2140
  print("=" * 80)
2141
 
2142
  return (
2143
 
2144
- df,
2145
 
2146
  out_xlsx,
2147
 
@@ -2149,29 +2602,29 @@ def classify_zip_and_analyze(
2149
 
2150
  face_gallery,
2151
 
2152
- plot1_img,
2153
 
2154
- plot2_img,
2155
 
2156
- plot3_img,
2157
 
2158
- plot4_img,
2159
 
2160
- plot5_img,
2161
 
2162
- plot6_img,
2163
 
2164
- plot7_img
2165
  )
2166
 
2167
 
2168
  # ============================================================
2169
- # GRADIO
2170
  # ============================================================
2171
 
2172
  demo = gr.Interface(
2173
 
2174
- fn=classify_zip_and_analyze,
2175
 
2176
  inputs=[
2177
 
@@ -2186,30 +2639,32 @@ demo = gr.Interface(
2186
  outputs=[
2187
 
2188
  # ----------------------------------------------------
2189
- # Data
2190
  # ----------------------------------------------------
2191
 
2192
  gr.Dataframe(
2193
 
2194
- label="Image Analysis",
2195
 
2196
  interactive=False
2197
  ),
2198
 
 
 
 
 
2199
  gr.File(
2200
 
2201
- label="Download XLSX"
2202
  ),
2203
 
2204
  # ----------------------------------------------------
2205
- # General thumbnails
2206
  # ----------------------------------------------------
2207
 
2208
  gr.Gallery(
2209
 
2210
- label="Thumbnails",
2211
-
2212
- show_label=True,
2213
 
2214
  columns=5,
2215
 
@@ -2219,94 +2674,97 @@ demo = gr.Interface(
2219
  ),
2220
 
2221
  # ----------------------------------------------------
2222
- # Face diagnostic gallery
2223
  # ----------------------------------------------------
2224
 
2225
  gr.Gallery(
2226
 
2227
- label="Detected Faces — Diagnostic",
2228
-
2229
- show_label=True,
2230
 
2231
  columns=4,
2232
 
2233
- rows=2,
2234
 
2235
  height="auto"
2236
  ),
2237
 
2238
  # ----------------------------------------------------
2239
- # Plots
2240
  # ----------------------------------------------------
2241
 
2242
- gr.Image(
2243
 
2244
- type="pil",
 
 
2245
 
2246
- label="Basic Color Frequency"
 
 
2247
  ),
2248
 
 
 
 
 
2249
  gr.Image(
2250
 
2251
  type="pil",
2252
 
2253
- label="ImageNet Prediction Distribution"
2254
  ),
2255
 
2256
  gr.Image(
2257
 
2258
  type="pil",
2259
 
2260
- label="Face Detection"
2261
  ),
2262
 
2263
  gr.Image(
2264
 
2265
  type="pil",
2266
 
2267
- label="Detected Faces per Image"
2268
  ),
2269
 
2270
  gr.Image(
2271
 
2272
  type="pil",
2273
 
2274
- label="Overall Estimated Age Distribution"
2275
  ),
2276
 
2277
  gr.Image(
2278
 
2279
  type="pil",
2280
 
2281
- label="Estimated Age by Existing Image Category"
2282
  ),
2283
 
2284
  gr.Image(
2285
 
2286
  type="pil",
2287
 
2288
- label="Age Groups by Existing Image Category"
2289
  )
2290
  ],
2291
 
2292
  title=(
2293
- "ZIP Image Classifier, "
2294
- "Color & Face Analysis"
2295
  ),
2296
 
2297
  description=(
2298
 
2299
- "Upload a ZIP containing images. "
2300
 
2301
- "Images are recursively detected and classified "
2302
- "with ResNet50. Dominant colors, face detection "
2303
- "and age estimates are calculated. "
2304
 
2305
- "Existing folder categories are retained for "
2306
- "cross-category age analysis. "
2307
 
2308
- "Categories are taken from the ZIP structure "
2309
- "and are not inferred from faces."
2310
  )
2311
  )
2312
 
 
1
  # ============================================================
2
+ # MULTI-MODEL IMAGE ANALYSIS
3
  # ============================================================
4
  #
5
+ # FEATURES
6
  # ------------------------------------------------------------
7
+ # 1. Recursive ZIP extraction
8
+ # 2. YOLO object detection
9
+ # 3. Multiple objects per image
10
+ # 4. Object bounding boxes
11
+ # 5. Object confidence
12
+ # 6. Face detection
13
+ # 7. Multiple face-detection fallbacks
14
+ # 8. Image upscaling for small faces
15
+ # 9. Face crops
16
+ # 10. Age estimation
17
+ # 11. Existing folder/category extraction
18
+ # 12. Age × existing category analysis
19
+ # 13. Object frequency analysis
20
+ # 14. Object × category analysis
21
+ # 15. XLSX export
22
+ # 16. Diagnostic galleries
23
  #
24
  # IMPORTANT
25
  # ------------------------------------------------------------
26
+ # Categories come from the existing ZIP folder structure.
27
+ # They are NOT inferred from faces.
28
  #
29
  # Example:
30
  #
 
32
  # Men/
33
  # image1.jpg
34
  # image2.jpg
35
+ #
36
  # Women/
37
  # image3.jpg
38
  # image4.jpg
 
42
  # ============================================================
43
 
44
 
45
+ # ============================================================
46
+ # INSTALLATION
47
+ # ============================================================
48
+ #
49
+ # On Hugging Face / Colab / Jupyter, install:
50
+ #
51
+ # pip install ultralytics deepface mtcnn openpyxl
52
+ #
53
+ # Depending on your environment, you may also need:
54
+ #
55
+ # pip install tensorflow
56
+ #
57
+ # ============================================================
58
+
59
+
60
  # ============================================================
61
  # IMPORTS
62
  # ============================================================
 
70
  import numpy as np
71
  import pandas as pd
72
 
73
+ from PIL import Image, ImageDraw
 
 
 
74
 
75
+ import matplotlib.pyplot as plt
 
76
 
77
+ import cv2
78
 
79
+ import torch
80
 
81
  import gradio as gr
82
 
83
+ from ultralytics import YOLO
84
+
85
  from deepface import DeepFace
 
86
 
87
 
88
  # ============================================================
89
  # CONFIGURATION
90
  # ============================================================
91
 
 
 
92
  IMAGE_EXTENSIONS = (
93
  ".png",
94
  ".jpg",
 
99
  ".tiff"
100
  )
101
 
102
+ # ------------------------------------------------------------
103
+ # YOLO model
104
+ # ------------------------------------------------------------
105
+ #
106
+ # yolov8n.pt = fast / CPU friendly
107
+ #
108
+ # You can later try:
109
+ #
110
+ # yolov8s.pt
111
+ # yolov8m.pt
112
+ #
113
+ # for potentially better detection.
114
+ #
115
+ # ------------------------------------------------------------
116
+
117
+ YOLO_MODEL_NAME = "yolov8s.pt"
118
+
119
+ OBJECT_CONFIDENCE = 0.25
120
+
121
+ FACE_MIN_SIZE = 30
122
+
123
+ UPSCALE_FACTOR = 2.0
124
+
125
 
126
  # ============================================================
127
  # DEVICE
 
129
 
130
  if torch.cuda.is_available():
131
 
132
+ device = "cuda"
133
 
134
  else:
135
 
136
+ device = "cpu"
137
 
138
 
139
  print("=" * 80)
140
+ print("MULTI-MODEL IMAGE ANALYSIS")
141
  print("=" * 80)
142
 
143
  print(
144
  f"PyTorch device: {device}"
145
  )
146
 
 
 
 
 
147
  print("=" * 80)
148
 
149
 
150
  # ============================================================
151
+ # LOAD YOLO
152
  # ============================================================
153
 
154
+ print(
155
+ f"Loading YOLO model: {YOLO_MODEL_NAME}"
 
 
 
 
156
  )
157
 
158
+ yolo_model = YOLO(
159
+ YOLO_MODEL_NAME
160
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  print(
163
+ "YOLO loaded."
164
  )
165
 
166
 
 
200
 
201
 
202
  # ============================================================
203
+ # COLOR FUNCTION
204
  # ============================================================
205
 
206
  def closest_basic_color(rgb):
207
 
208
  r, g, b = rgb
209
 
210
+ minimum = float("inf")
211
 
212
+ result = None
213
 
214
  for name, color in BASIC_COLORS.items():
215
 
 
224
  (b - cb) ** 2
225
  )
226
 
227
+ if distance < minimum:
228
 
229
+ minimum = distance
230
 
231
+ result = name
232
 
233
+ return result
234
 
235
 
236
  # ============================================================
 
252
  image_small
253
  )
254
 
 
 
 
 
 
 
255
  pixels = pixels.reshape(
256
  -1,
257
  3
258
  )
259
 
 
 
260
  if len(pixels) > 50000:
261
 
262
+ rng = np.random.default_rng(
263
+ 0
264
+ )
265
 
266
  indices = rng.choice(
267
 
 
274
 
275
  pixels = pixels[indices]
276
 
277
+ # Use simple color quantization rather
278
+ # than KMeans to reduce dependencies/time.
 
279
 
280
+ pixels_small = (
281
+ pixels // 32
282
+ ) * 32
283
 
284
+ unique, counts = np.unique(
 
285
 
286
+ pixels_small,
287
 
288
+ axis=0,
289
 
290
+ return_counts=True
 
291
  )
292
 
293
+ index = np.argmax(
294
+ counts
 
 
295
  )
296
 
297
+ dominant = unique[index]
298
+
299
+ dominant = tuple(
300
+ dominant.astype(int)
301
  )
302
 
303
  hex_color = (
304
 
305
+ f"#{dominant[0]:02x}"
306
 
307
+ f"{dominant[1]:02x}"
308
 
309
+ f"{dominant[2]:02x}"
310
  )
311
 
312
  return (
313
+ dominant,
314
  hex_color
315
  )
316
 
317
 
318
  # ============================================================
319
+ # FIND IMAGES
320
  # ============================================================
321
 
322
+ def find_images(
323
+ root_directory
324
+ ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
 
326
+ image_files = []
327
 
328
+ for root, dirs, files in os.walk(
329
+ root_directory
 
330
  ):
331
 
332
+ for filename in files:
 
 
333
 
334
+ if filename.lower().endswith(
335
+ IMAGE_EXTENSIONS
336
+ ):
337
 
338
+ image_files.append(
 
339
 
340
+ os.path.join(
341
+ root,
342
+ filename
343
+ )
344
  )
 
345
 
346
+ return sorted(
347
+ image_files
348
+ )
349
 
350
 
351
  # ============================================================
352
+ # RELATIVE PATH
353
  # ============================================================
354
 
355
+ def get_relative_path(
356
+ filepath,
357
+ root
358
  ):
359
 
360
+ return os.path.relpath(
361
+ filepath,
362
+ root
363
+ )
 
 
 
 
364
 
 
 
365
 
366
+ # ============================================================
367
+ # CATEGORY
368
+ # ============================================================
369
 
370
+ def extract_category(
371
+ relative_path
372
+ ):
373
 
374
  normalized = relative_path.replace(
375
  "\\",
 
386
 
387
 
388
  # ============================================================
389
+ # SUBCATEGORY
390
  # ============================================================
391
 
392
  def extract_subcategory(
393
  relative_path
394
  ):
395
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  normalized = relative_path.replace(
397
  "\\",
398
  "/"
 
410
 
411
 
412
  # ============================================================
413
+ # YOLO OBJECT DETECTION
414
  # ============================================================
415
 
416
+ def detect_objects(
417
+ image
418
  ):
419
 
420
+ objects = []
 
 
 
 
421
 
422
+ error = ""
423
 
424
+ try:
 
 
425
 
426
+ image_np = np.array(
427
+ image
428
+ )
429
 
430
+ results = yolo_model.predict(
 
 
 
 
431
 
432
+ source=image_np,
 
 
433
 
434
+ conf=OBJECT_CONFIDENCE,
435
 
436
+ device=device,
 
 
437
 
438
+ verbose=False
439
+ )
 
 
440
 
441
+ if not results:
 
 
 
442
 
443
+ return objects, ""
444
 
445
+ result = results[0]
 
 
446
 
447
+ names = result.names
 
 
448
 
449
+ if result.boxes is None:
450
 
451
+ return objects, ""
452
 
453
+ for box in result.boxes:
454
 
455
+ try:
 
456
 
457
+ xyxy = (
458
+ box.xyxy[0]
459
+ .cpu()
460
+ .numpy()
461
+ .astype(int)
462
+ )
463
 
464
+ x1, y1, x2, y2 = (
465
+ xyxy
466
+ )
467
 
468
+ confidence = float(
469
 
470
+ box.conf[0]
471
+ .cpu()
472
+ .item()
473
+ )
474
 
475
+ class_id = int(
 
476
 
477
+ box.cls[0]
478
+ .cpu()
479
+ .item()
480
+ )
481
 
482
+ label = names[
483
+ class_id
484
+ ]
485
 
486
+ width = (
487
+ x2 - x1
488
+ )
489
 
490
+ height = (
491
+ y2 - y1
492
+ )
493
 
494
+ objects.append({
495
 
496
+ "object":
497
+ label,
498
 
499
+ "confidence":
500
+ confidence * 100,
 
501
 
502
+ "x1":
503
+ x1,
 
 
504
 
505
+ "y1":
506
+ y1,
 
507
 
508
+ "x2":
509
+ x2,
 
 
510
 
511
+ "y2":
512
+ y2,
513
 
514
+ "width":
515
+ width,
 
516
 
517
+ "height":
518
+ height
519
+ })
520
 
521
+ except Exception:
 
 
 
522
 
523
  continue
524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  except Exception as e:
526
 
527
+ error = (
 
 
528
 
529
  f"{type(e).__name__}: "
530
 
531
  f"{str(e)}"
532
  )
533
 
534
+ return (
535
+ objects,
536
+ error
537
+ )
 
 
538
 
539
 
540
  # ============================================================
541
+ # DRAW OBJECT BOXES
542
  # ============================================================
543
 
544
+ def draw_object_boxes(
545
  image,
546
+ objects
547
  ):
548
 
 
 
 
 
 
549
  output = image.copy()
550
 
551
+ draw = ImageDraw.Draw(
552
+ output
553
+ )
554
+
555
+ for obj in objects:
556
 
557
+ x1 = int(
558
+ obj["x1"]
 
559
  )
560
 
561
+ y1 = int(
562
+ obj["y1"]
563
+ )
564
 
565
+ x2 = int(
566
+ obj["x2"]
567
+ )
568
 
569
+ y2 = int(
570
+ obj["y2"]
571
+ )
572
 
573
+ label = (
574
+ f'{obj["object"]} '
575
+ f'{obj["confidence"]:.0f}%'
576
+ )
577
 
578
+ draw.rectangle(
 
 
579
 
580
+ [
581
+ x1,
582
+ y1,
583
+ x2,
584
+ y2
585
+ ],
586
 
587
+ outline="red",
 
588
 
589
+ width=3
590
+ )
591
 
592
+ # ----------------------------------------------------
593
+ # Label background
594
+ # ----------------------------------------------------
595
 
596
+ try:
597
 
598
+ bbox = draw.textbbox(
599
+ (x1, y1),
600
+ label
601
+ )
 
 
602
 
603
+ draw.rectangle(
604
+ bbox,
605
+ fill="red"
606
+ )
607
 
608
+ draw.text(
609
+ (x1, y1),
610
+ label,
611
+ fill="white"
612
+ )
613
 
614
  except Exception:
615
+
616
  pass
617
 
618
  return output
619
 
620
 
621
  # ============================================================
622
+ # FACE DETECTION — OPENCV
623
  # ============================================================
624
 
625
+ def detect_faces_opencv(
626
+ image
 
627
  ):
628
 
629
+ faces = []
630
 
631
+ error = ""
 
 
632
 
633
+ try:
634
+
635
+ gray = cv2.cvtColor(
636
+
637
+ np.array(image),
638
+
639
+ cv2.COLOR_RGB2GRAY
640
+ )
641
+
642
+ cascade_path = cv2.data.haarcascades + (
643
+ "haarcascade_frontalface_default.xml"
644
+ )
645
+
646
+ detector = cv2.CascadeClassifier(
647
+ cascade_path
648
+ )
649
+
650
+ detected = detector.detectMultiScale(
651
+
652
+ gray,
653
+
654
+ scaleFactor=1.1,
655
+
656
+ minNeighbors=5,
657
+
658
+ minSize=(
659
+ FACE_MIN_SIZE,
660
+ FACE_MIN_SIZE
661
+ )
662
+ )
663
+
664
+ for x, y, w, h in detected:
665
+
666
+ faces.append({
667
+
668
+ "x": int(x),
669
+
670
+ "y": int(y),
671
+
672
+ "w": int(w),
673
+
674
+ "h": int(h),
675
+
676
+ "detector":
677
+ "OpenCV"
678
+ })
679
+
680
+ except Exception as e:
681
+
682
+ error = str(e)
683
+
684
+ return (
685
+ faces,
686
+ error
687
+ )
688
+
689
+
690
+ # ============================================================
691
+ # FACE DETECTION — DEEPFACE
692
+ # ============================================================
693
+
694
+ def detect_faces_deepface(
695
+ image
696
+ ):
697
+
698
+ faces = []
699
+
700
+ error = ""
701
+
702
+ try:
703
+
704
+ img_cv2 = cv2.cvtColor(
705
+
706
+ np.array(image),
707
+
708
+ cv2.COLOR_RGB2BGR
709
+ )
710
+
711
+ result = DeepFace.extract_faces(
712
+
713
+ img_path=img_cv2,
714
+
715
+ detector_backend="retinaface",
716
+
717
+ enforce_detection=False,
718
+
719
+ align=True
720
+ )
721
+
722
+ for item in result:
723
+
724
+ area = item.get(
725
+ "facial_area",
726
+ {}
727
+ )
728
+
729
+ x = int(
730
+ area.get(
731
+ "x",
732
+ 0
733
+ )
734
+ )
735
+
736
+ y = int(
737
+ area.get(
738
+ "y",
739
+ 0
740
+ )
741
+ )
742
+
743
+ w = int(
744
+ area.get(
745
+ "w",
746
+ 0
747
+ )
748
+ )
749
+
750
+ h = int(
751
+ area.get(
752
+ "h",
753
+ 0
754
+ )
755
+ )
756
+
757
+ if w >= FACE_MIN_SIZE and h >= FACE_MIN_SIZE:
758
+
759
+ faces.append({
760
+
761
+ "x": x,
762
+
763
+ "y": y,
764
+
765
+ "w": w,
766
+
767
+ "h": h,
768
+
769
+ "detector":
770
+ "RetinaFace"
771
+ })
772
+
773
+ except Exception as e:
774
+
775
+ error = (
776
+
777
+ f"{type(e).__name__}: "
778
+
779
+ f"{str(e)}"
780
+ )
781
+
782
+ return (
783
+ faces,
784
+ error
785
+ )
786
+
787
+
788
+ # ============================================================
789
+ # UPSCALE IMAGE
790
+ # ============================================================
791
+
792
+ def upscale_image(
793
+ image,
794
+ factor=UPSCALE_FACTOR
795
+ ):
796
+
797
+ width, height = image.size
798
+
799
+ new_size = (
800
+
801
+ int(width * factor),
802
+
803
+ int(height * factor)
804
+ )
805
+
806
+ return image.resize(
807
+
808
+ new_size,
809
+
810
+ Image.Resampling.LANCZOS
811
+ )
812
+
813
+
814
+ # ============================================================
815
+ # FACE DETECTION WITH FALLBACKS
816
+ # ============================================================
817
+
818
+ def detect_faces(
819
+ image
820
+ ):
821
+
822
+ # --------------------------------------------------------
823
+ # 1. RetinaFace
824
+ # --------------------------------------------------------
825
+
826
+ faces, error_retina = (
827
+ detect_faces_deepface(
828
+ image
829
+ )
830
+ )
831
+
832
+ if faces:
833
+
834
+ return (
835
+ faces,
836
+ "RetinaFace",
837
+ ""
838
+ )
839
+
840
+ # --------------------------------------------------------
841
+ # 2. OpenCV original
842
+ # --------------------------------------------------------
843
+
844
+ faces, error_opencv = (
845
+ detect_faces_opencv(
846
+ image
847
+ )
848
+ )
849
+
850
+ if faces:
851
+
852
+ return (
853
+ faces,
854
+ "OpenCV",
855
+ ""
856
+ )
857
+
858
+ # --------------------------------------------------------
859
+ # 3. Upscaled image
860
+ # --------------------------------------------------------
861
+
862
+ try:
863
+
864
+ enlarged = upscale_image(
865
+ image
866
+ )
867
+
868
+ faces, error_upscaled = (
869
+ detect_faces_deepface(
870
+ enlarged
871
+ )
872
+ )
873
+
874
+ if faces:
875
+
876
+ # Convert coordinates back
877
+ # to original scale.
878
+
879
+ converted = []
880
+
881
+ for face in faces:
882
+
883
+ converted.append({
884
+
885
+ "x":
886
+ int(
887
+ face["x"]
888
+ / UPSCALE_FACTOR
889
+ ),
890
+
891
+ "y":
892
+ int(
893
+ face["y"]
894
+ / UPSCALE_FACTOR
895
+ ),
896
+
897
+ "w":
898
+ int(
899
+ face["w"]
900
+ / UPSCALE_FACTOR
901
+ ),
902
+
903
+ "h":
904
+ int(
905
+ face["h"]
906
+ / UPSCALE_FACTOR
907
+ ),
908
+
909
+ "detector":
910
+ "RetinaFace-upscaled"
911
+ })
912
+
913
+ return (
914
+ converted,
915
+ "RetinaFace-upscaled",
916
+ ""
917
+ )
918
+
919
+ except Exception as e:
920
+
921
+ error_upscaled = str(e)
922
+
923
+ # --------------------------------------------------------
924
+ # Nothing found
925
+ # --------------------------------------------------------
926
+
927
+ diagnostic = (
928
+ "No face detected. "
929
+ f"RetinaFace: {error_retina or 'no face'}; "
930
+ f"OpenCV: {error_opencv or 'no face'}"
931
+ )
932
+
933
+ return (
934
+ [],
935
+ "None",
936
+ diagnostic
937
+ )
938
+
939
+
940
+ # ============================================================
941
+ # CROP FACE
942
+ # ============================================================
943
+
944
+ def crop_face(
945
+ image,
946
+ face,
947
+ margin=0.30
948
+ ):
949
+
950
+ x = face["x"]
951
+ y = face["y"]
952
+ w = face["w"]
953
+ h = face["h"]
954
+
955
+ image_width, image_height = (
956
+ image.size
957
+ )
958
+
959
+ mx = int(
960
+ w * margin
961
+ )
962
+
963
+ my = int(
964
+ h * margin
965
+ )
966
+
967
+ x1 = max(
968
+ 0,
969
+ x - mx
970
+ )
971
+
972
+ y1 = max(
973
+ 0,
974
+ y - my
975
+ )
976
+
977
+ x2 = min(
978
+ image_width,
979
+ x + w + mx
980
+ )
981
+
982
+ y2 = min(
983
+ image_height,
984
+ y + h + my
985
+ )
986
+
987
+ return image.crop(
988
+ (
989
+ x1,
990
+ y1,
991
+ x2,
992
+ y2
993
+ )
994
+ )
995
+
996
+
997
+ # ============================================================
998
+ # AGE ESTIMATION
999
+ # ============================================================
1000
+
1001
+ def estimate_age(
1002
+ face_crop
1003
+ ):
1004
+
1005
+ """
1006
+ Runs DeepFace age estimation on an
1007
+ already-detected face crop.
1008
+ """
1009
+
1010
+ try:
1011
+
1012
+ crop_cv2 = cv2.cvtColor(
1013
+
1014
+ np.array(face_crop),
1015
+
1016
+ cv2.COLOR_RGB2BGR
1017
+ )
1018
+
1019
+ result = DeepFace.analyze(
1020
+
1021
+ crop_cv2,
1022
+
1023
+ actions=[
1024
+ "age"
1025
+ ],
1026
+
1027
+ enforce_detection=False,
1028
+
1029
+ detector_backend="skip",
1030
+
1031
+ silent=True
1032
+ )
1033
+
1034
+ if isinstance(
1035
+ result,
1036
+ list
1037
+ ):
1038
+
1039
+ if not result:
1040
+
1041
+ return (
1042
+ None,
1043
+ "No age result"
1044
+ )
1045
+
1046
+ result = result[0]
1047
+
1048
+ if isinstance(
1049
+ result,
1050
+ dict
1051
+ ):
1052
+
1053
+ age = result.get(
1054
+ "age"
1055
+ )
1056
+
1057
+ if age is not None:
1058
+
1059
+ return (
1060
+ float(age),
1061
+ ""
1062
+ )
1063
+
1064
+ return (
1065
+ None,
1066
+ "DeepFace returned no age"
1067
+ )
1068
+
1069
+ except Exception as e:
1070
+
1071
+ return (
1072
+
1073
+ None,
1074
+
1075
+ f"{type(e).__name__}: {str(e)}"
1076
+ )
1077
+
1078
+
1079
+ # ============================================================
1080
+ # DRAW FACE BOXES
1081
+ # ============================================================
1082
+
1083
+ def draw_face_boxes(
1084
+ image,
1085
+ faces
1086
+ ):
1087
+
1088
+ output = image.copy()
1089
+
1090
+ draw = ImageDraw.Draw(
1091
+ output
1092
+ )
1093
+
1094
+ for i, face in enumerate(
1095
+ faces,
1096
+ start=1
1097
+ ):
1098
+
1099
+ x = int(
1100
+ face["x"]
1101
+ )
1102
+
1103
+ y = int(
1104
+ face["y"]
1105
+ )
1106
+
1107
+ w = int(
1108
+ face["w"]
1109
+ )
1110
+
1111
+ h = int(
1112
+ face["h"]
1113
+ )
1114
+
1115
+ draw.rectangle(
1116
+
1117
+ [
1118
+ x,
1119
+ y,
1120
+ x + w,
1121
+ y + h
1122
+ ],
1123
+
1124
+ outline="lime",
1125
+
1126
+ width=4
1127
+ )
1128
+
1129
+ label = (
1130
+ f"Face {i} "
1131
+ f"({face['detector']})"
1132
+ )
1133
+
1134
+ try:
1135
+
1136
+ bbox = draw.textbbox(
1137
+ (x, y),
1138
+ label
1139
+ )
1140
+
1141
+ draw.rectangle(
1142
+ bbox,
1143
+ fill="lime"
1144
+ )
1145
+
1146
+ draw.text(
1147
+
1148
+ (x, y),
1149
+
1150
+ label,
1151
+
1152
+ fill="black"
1153
+ )
1154
+
1155
+ except Exception:
1156
+
1157
+ pass
1158
+
1159
+ return output
1160
+
1161
+
1162
+ # ============================================================
1163
+ # MAIN ANALYSIS
1164
+ # ============================================================
1165
+
1166
+ def analyze_zip(
1167
+ zip_file,
1168
+ progress=gr.Progress()
1169
+ ):
1170
+
1171
+ if zip_file is None:
1172
+
1173
+ raise gr.Error(
1174
+ "Please upload a ZIP file."
1175
+ )
1176
+
1177
+ zip_path = zip_file.name
1178
 
1179
  zip_basename = os.path.splitext(
1180
 
 
1185
 
1186
  print()
1187
  print("=" * 80)
 
1188
  print(
1189
+ f"Processing {zip_basename}"
1190
  )
 
1191
  print("=" * 80)
1192
 
1193
+ image_rows = []
1194
+
1195
+ face_rows = []
1196
+
1197
+ object_rows = []
1198
 
1199
  thumbnails = []
1200
 
1201
  face_gallery = []
1202
 
1203
+ object_gallery = []
1204
+
1205
  # ========================================================
1206
+ # EXTRACT ZIP
1207
  # ========================================================
1208
 
1209
  with tempfile.TemporaryDirectory() as tmpdir:
1210
 
 
 
 
 
 
 
 
 
1211
  try:
1212
 
1213
  with zipfile.ZipFile(
1214
  zip_path,
1215
  "r"
1216
+ ) as z:
1217
 
1218
+ z.extractall(
1219
  tmpdir
1220
  )
1221
 
1222
  except Exception as e:
1223
 
1224
  raise gr.Error(
1225
+ f"ZIP extraction failed: {e}"
 
1226
  )
1227
 
1228
  # ----------------------------------------------------
1229
+ # Find images
1230
  # ----------------------------------------------------
1231
 
1232
  image_files = find_images(
 
1238
  f"{len(image_files)}"
1239
  )
1240
 
1241
+ if not image_files:
1242
 
1243
  raise gr.Error(
1244
+ "No images found."
1245
  )
1246
 
1247
  # ====================================================
1248
+ # IMAGE LOOP
1249
  # ====================================================
1250
 
1251
+ for index, image_path in enumerate(
1252
  image_files
1253
  ):
1254
 
1255
  progress(
1256
 
1257
+ (index + 1)
1258
  /
1259
  len(image_files),
1260
 
1261
  desc=(
1262
 
1263
+ f"Image "
1264
+ f"{index + 1}/"
 
 
1265
  f"{len(image_files)}"
1266
  )
1267
  )
1268
 
1269
  relative_path = (
1270
+ get_relative_path(
1271
+ image_path,
1272
  tmpdir
1273
  )
1274
  )
1275
 
1276
  filename = os.path.basename(
1277
+ image_path
1278
  )
1279
 
1280
  category = (
 
1290
  )
1291
 
1292
  print(
1293
+ f"[{index + 1}/"
1294
  f"{len(image_files)}] "
1295
  f"{relative_path}"
1296
  )
1297
 
1298
  # ------------------------------------------------
1299
+ # LOAD IMAGE
1300
  # ------------------------------------------------
1301
 
1302
  try:
1303
 
1304
  image = Image.open(
1305
+ image_path
1306
  ).convert("RGB")
1307
 
1308
  except Exception as e:
1309
 
1310
  print(
1311
+ f"Image failed: {e}"
1312
  )
1313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1314
  continue
1315
 
1316
  # ------------------------------------------------
1317
+ # THUMBNAIL
1318
  # ------------------------------------------------
1319
 
1320
  thumb = image.copy()
1321
 
1322
  thumb.thumbnail(
1323
+ (300, 300)
 
1324
  )
1325
 
1326
  thumbnails.append(
1327
+
1328
  (
1329
  thumb,
1330
+
1331
+ f"{category} | "
1332
+ f"{filename}"
1333
  )
1334
  )
1335
 
1336
+ # =================================================
1337
+ # OBJECT DETECTION
1338
+ # =================================================
 
 
1339
 
1340
+ objects, object_error = (
1341
+ detect_objects(
1342
  image
1343
  )
1344
+ )
1345
 
1346
+ # -------------------------------------------------
1347
+ # Object records
1348
+ # -------------------------------------------------
 
 
 
 
1349
 
1350
+ for obj_index, obj in enumerate(
1351
+ objects,
1352
+ start=1
1353
+ ):
1354
 
1355
+ object_rows.append({
1356
 
1357
+ "Filename":
1358
+ filename,
 
 
 
1359
 
1360
+ "Relative Path":
1361
+ relative_path,
 
 
 
1362
 
1363
+ "Category":
1364
+ category,
1365
 
1366
+ "Object Number":
1367
+ obj_index,
 
1368
 
1369
+ "Object":
1370
+ obj["object"],
1371
 
1372
+ "Confidence":
1373
+ obj["confidence"],
1374
 
1375
+ "X1":
1376
+ obj["x1"],
 
1377
 
1378
+ "Y1":
1379
+ obj["y1"],
 
 
 
1380
 
1381
+ "X2":
1382
+ obj["x2"],
 
1383
 
1384
+ "Y2":
1385
+ obj["y2"],
 
1386
 
1387
+ "Width":
1388
+ obj["width"],
 
1389
 
1390
+ "Height":
1391
+ obj["height"]
1392
+ })
1393
 
1394
+ # -------------------------------------------------
1395
+ # Object diagnostic image
1396
+ # -------------------------------------------------
1397
 
1398
+ if objects:
1399
 
1400
+ object_image = (
1401
+ draw_object_boxes(
1402
+ image,
1403
+ objects
1404
+ )
1405
  )
1406
 
1407
+ object_gallery.append(
 
 
 
 
 
 
1408
 
1409
+ (
 
1410
 
1411
+ object_image,
1412
 
1413
+ (
1414
+ f"{category} | "
1415
+ f"{filename} | "
1416
+ f"{len(objects)} objects"
1417
+ )
1418
+ )
1419
  )
1420
 
1421
+ # =================================================
1422
+ # FACE DETECTION
1423
+ # =================================================
1424
 
1425
+ faces, detector_used, face_error = (
1426
+ detect_faces(
1427
+ image
1428
+ )
1429
+ )
1430
 
1431
+ # -------------------------------------------------
1432
+ # Face diagnostic image
1433
+ # -------------------------------------------------
1434
 
1435
+ if faces:
1436
 
1437
  face_image = (
1438
  draw_face_boxes(
 
1444
  face_gallery.append(
1445
 
1446
  (
1447
+
1448
  face_image,
1449
 
1450
  (
1451
  f"{category} | "
1452
  f"{filename} | "
1453
+ f"{len(faces)} face(s) | "
1454
+ f"{detector_used}"
1455
  )
1456
  )
1457
  )
1458
 
1459
+ # =================================================
1460
+ # AGE ESTIMATION
1461
+ # =================================================
 
 
 
 
 
 
1462
 
1463
+ image_ages = []
 
 
 
 
1464
 
1465
+ for face_number, face in enumerate(
1466
+ faces,
1467
+ start=1
1468
  ):
1469
 
1470
+ try:
 
 
1471
 
1472
+ face_crop = crop_face(
1473
+ image,
1474
+ face
1475
+ )
1476
 
1477
+ age, age_error = (
1478
+ estimate_age(
1479
+ face_crop
1480
+ )
1481
+ )
1482
+
1483
+ except Exception as e:
1484
+
1485
+ age = None
1486
+
1487
+ age_error = str(e)
1488
+
1489
+ # ------------------------------------------------
1490
+ # Save face crop
1491
+ # ------------------------------------------------
1492
+
1493
+ if age is not None:
1494
+
1495
+ age_text = (
1496
+ f"age≈{age:.0f}"
1497
+ )
1498
+
1499
+ else:
1500
+
1501
+ age_text = (
1502
+ "age unavailable"
1503
+ )
1504
+
1505
+ face_rows.append({
1506
+
1507
+ "Filename":
1508
+ filename,
1509
 
1510
+ "Relative Path":
1511
+ relative_path,
1512
+
1513
+ "Category":
1514
+ category,
1515
+
1516
+ "Face Number":
1517
+ face_number,
1518
+
1519
+ "Detector":
1520
+ detector_used,
1521
+
1522
+ "X":
1523
+ face["x"],
1524
+
1525
+ "Y":
1526
+ face["y"],
1527
+
1528
+ "Width":
1529
+ face["w"],
1530
+
1531
+ "Height":
1532
+ face["h"],
1533
+
1534
+ "Estimated Age":
1535
+ age,
1536
+
1537
+ "Age Error":
1538
+ age_error
1539
+ })
1540
+
1541
+ if age is not None:
1542
 
1543
+ image_ages.append(
1544
+ float(age)
1545
+ )
1546
+
1547
+ # =================================================
1548
+ # COLOR
1549
+ # =================================================
1550
+
1551
+ try:
1552
+
1553
+ rgb, hex_color = (
1554
+ get_dominant_color(
1555
+ image
1556
+ )
1557
  )
1558
 
1559
+ basic_color = (
1560
+ closest_basic_color(
1561
+ rgb
1562
+ )
1563
+ )
1564
 
1565
+ except Exception:
1566
+
1567
+ hex_color = ""
1568
 
1569
+ basic_color = ""
1570
+
1571
+ # =================================================
1572
+ # IMAGE ROW
1573
+ # =================================================
1574
+
1575
+ image_rows.append({
1576
 
1577
  "Filename":
1578
  filename,
 
1586
  "Subcategory":
1587
  subcategory,
1588
 
1589
+ "Width":
1590
+ image.width,
1591
+
1592
+ "Height":
1593
+ image.height,
1594
+
1595
+ "Objects Detected":
1596
+ len(objects),
1597
+
1598
+ "Object Labels":
1599
+ ", ".join(
1600
+ sorted(
1601
+ set(
1602
+ obj["object"]
1603
+ for obj in objects
1604
+ )
1605
+ )
1606
+ ),
1607
+
1608
+ "Face Count":
1609
+ len(faces),
1610
+
1611
+ "Face Detector":
1612
+ detector_used,
1613
+
1614
+ "Estimated Ages":
1615
+ ", ".join(
1616
+
1617
+ str(
1618
+ round(age)
1619
+ )
1620
 
1621
+ for age in image_ages
1622
+ ),
1623
 
1624
+ "Mean Estimated Age":
 
1625
 
1626
+ (
1627
+ np.mean(
1628
+ image_ages
1629
+ )
1630
 
1631
+ if image_ages
 
1632
 
1633
+ else np.nan
1634
+ ),
1635
 
1636
  "Dominant Color":
1637
  hex_color,
 
1639
  "Basic Color":
1640
  basic_color,
1641
 
1642
+ "Object Detection Error":
1643
+ object_error,
 
 
 
 
 
 
1644
 
1645
+ "Face Detection Error":
1646
  face_error
1647
  })
1648
 
1649
  # ========================================================
1650
+ # DATAFRAMES
1651
  # ========================================================
1652
 
1653
+ images_df = pd.DataFrame(
1654
+ image_rows
1655
+ )
1656
+
1657
+ faces_df = pd.DataFrame(
1658
+ face_rows
1659
+ )
1660
+
1661
+ objects_df = pd.DataFrame(
1662
+ object_rows
1663
  )
1664
 
1665
  # ========================================================
1666
+ # OBJECT SUMMARY
1667
  # ========================================================
1668
 
1669
+ if len(objects_df) > 0:
 
 
1670
 
1671
+ object_summary = (
 
 
1672
 
1673
+ objects_df
 
 
 
1674
 
1675
+ .groupby(
1676
+ "Object"
1677
+ )
1678
 
1679
+ .agg(
1680
 
1681
+ Count=(
1682
+ "Object",
1683
+ "size"
1684
+ ),
1685
 
1686
+ Mean_Confidence=(
1687
+ "Confidence",
1688
+ "mean"
1689
+ )
1690
+ )
1691
 
1692
+ .reset_index()
1693
 
1694
+ .sort_values(
1695
+ "Count",
1696
+ ascending=False
1697
+ )
1698
+ )
1699
 
1700
+ else:
 
 
 
 
1701
 
1702
+ object_summary = pd.DataFrame(
 
1703
 
1704
+ columns=[
1705
+ "Object",
1706
+ "Count",
1707
+ "Mean_Confidence"
1708
+ ]
1709
+ )
1710
 
1711
+ # ========================================================
1712
+ # OBJECT × CATEGORY
1713
+ # ========================================================
1714
 
1715
+ if len(objects_df) > 0:
 
1716
 
1717
+ object_category = pd.crosstab(
 
1718
 
1719
+ objects_df[
1720
+ "Object"
1721
+ ],
1722
 
1723
+ objects_df[
1724
+ "Category"
1725
+ ]
1726
+ )
1727
 
1728
+ object_category = (
1729
+ object_category
1730
+ .reset_index()
1731
+ )
1732
 
1733
+ else:
 
 
1734
 
1735
+ object_category = pd.DataFrame()
 
 
1736
 
1737
  # ========================================================
1738
+ # AGE × CATEGORY
1739
  # ========================================================
1740
 
1741
  if len(faces_df) > 0:
1742
 
1743
+ age_category = (
1744
 
1745
  faces_df
1746
 
1747
+ .dropna(
1748
+ subset=[
1749
+ "Estimated Age"
1750
+ ]
1751
+ )
1752
+
1753
  .groupby(
1754
  "Category"
1755
+ )[
1756
+ "Estimated Age"
1757
+ ]
1758
 
1759
  .agg(
1760
  [
 
1770
  .reset_index()
1771
  )
1772
 
1773
+ age_category.columns = [
 
 
 
 
 
1774
 
1775
+ "Category",
 
1776
 
1777
+ "Face Count",
 
1778
 
1779
+ "Mean Age",
 
1780
 
1781
+ "Median Age",
 
1782
 
1783
+ "SD Age",
1784
+
1785
+ "Minimum Age",
1786
+
1787
+ "Maximum Age"
1788
+ ]
1789
 
1790
  else:
1791
 
1792
+ age_category = pd.DataFrame()
 
 
 
 
 
 
 
 
 
 
1793
 
1794
  # ========================================================
1795
+ # AGE GROUP × CATEGORY
1796
  # ========================================================
1797
 
1798
  if len(faces_df) > 0:
1799
 
1800
  age_bins = [
1801
+
1802
  0,
1803
  18,
1804
  25,
 
1811
  ]
1812
 
1813
  age_labels = [
1814
+
1815
  "<18",
1816
+
1817
  "18–24",
1818
+
1819
  "25–34",
1820
+
1821
  "35–44",
1822
+
1823
  "45–54",
1824
+
1825
  "55–64",
1826
+
1827
  "65–74",
1828
+
1829
  "75+"
1830
  ]
1831
 
 
1853
  faces_df[
1854
  "Category"
1855
  ]
1856
+ ).reset_index()
 
 
 
 
 
1857
 
1858
  else:
1859
 
1860
+ age_group_category = pd.DataFrame()
 
 
1861
 
1862
  # ========================================================
1863
  # SUMMARY
1864
  # ========================================================
1865
 
1866
+ total_images = len(
1867
+ images_df
1868
+ )
1869
 
1870
+ total_faces = (
1871
 
1872
+ len(faces_df)
 
 
 
 
1873
  )
1874
 
1875
+ images_with_faces = (
1876
+
1877
+ int(
1878
 
1879
+ (
1880
+ images_df[
1881
+ "Face Count"
1882
+ ] > 0
1883
+ ).sum()
1884
+ )
1885
+
1886
+ if len(images_df) > 0
1887
+
1888
+ else 0
1889
  )
1890
 
1891
+ total_objects = (
1892
 
1893
+ len(objects_df)
1894
+ )
1895
+
1896
+ images_with_objects = (
1897
+
1898
+ int(
1899
+
1900
+ (
1901
+ images_df[
1902
+ "Objects Detected"
1903
+ ] > 0
1904
+ ).sum()
1905
+ )
1906
+
1907
+ if len(images_df) > 0
1908
+
1909
+ else 0
1910
  )
1911
 
1912
  summary_df = pd.DataFrame({
 
1915
 
1916
  "Images processed",
1917
 
1918
+ "Images with faces",
1919
 
1920
  "Total detected faces",
1921
 
1922
+ "Images with objects",
1923
 
1924
+ "Total detected objects",
1925
+
1926
+ "Distinct object classes",
1927
+
1928
+ "Distinct categories"
1929
  ],
1930
 
1931
  "Value": [
 
1936
 
1937
  total_faces,
1938
 
1939
+ images_with_objects,
 
 
 
 
 
 
1940
 
1941
+ total_objects,
 
 
 
1942
 
1943
+ (
1944
+ objects_df[
1945
+ "Object"
1946
+ ].nunique()
1947
 
1948
+ if len(objects_df) > 0
 
 
 
1949
 
1950
+ else 0
1951
+ ),
 
 
1952
 
1953
+ (
1954
+ images_df[
1955
+ "Category"
1956
+ ].nunique()
1957
 
1958
+ if len(images_df) > 0
 
 
1959
 
1960
+ else 0
1961
+ )
1962
+ ]
1963
+ })
 
1964
 
1965
  # ========================================================
1966
  # XLSX
 
1970
 
1971
  tempfile.gettempdir(),
1972
 
1973
+ f"{zip_basename}_analysis.xlsx"
1974
  )
1975
 
1976
  with pd.ExcelWriter(
 
1980
  engine="openpyxl"
1981
  ) as writer:
1982
 
1983
+ images_df.to_excel(
1984
 
1985
  writer,
1986
 
1987
+ sheet_name="Images",
1988
 
1989
  index=False
1990
  )
 
1993
 
1994
  writer,
1995
 
1996
+ sheet_name="Faces",
1997
+
1998
+ index=False
1999
+ )
2000
+
2001
+ objects_df.to_excel(
2002
+
2003
+ writer,
2004
+
2005
+ sheet_name="Objects",
2006
+
2007
+ index=False
2008
+ )
2009
+
2010
+ object_summary.to_excel(
2011
+
2012
+ writer,
2013
+
2014
+ sheet_name="Object Summary",
2015
 
2016
  index=False
2017
  )
2018
 
2019
+ object_category.to_excel(
2020
+
2021
+ writer,
2022
+
2023
+ sheet_name="Objects by Category",
2024
+
2025
+ index=False
2026
+ )
2027
+
2028
+ age_category.to_excel(
2029
 
2030
  writer,
2031
 
 
2053
  )
2054
 
2055
  # ========================================================
2056
+ # PLOT 1 — OBJECT FREQUENCY
2057
  # ========================================================
2058
 
2059
  fig1, ax1 = plt.subplots(
2060
+ figsize=(10, 7)
2061
  )
2062
 
2063
+ if len(object_summary) > 0:
 
 
 
 
2064
 
2065
+ plot_data = (
2066
+ object_summary
2067
+ .head(25)
2068
+ .sort_values(
2069
+ "Count"
2070
+ )
2071
  )
2072
 
2073
+ ax1.barh(
 
 
 
 
 
2074
 
2075
+ plot_data[
2076
+ "Object"
2077
+ ],
2078
 
2079
+ plot_data[
2080
+ "Count"
2081
+ ]
2082
  )
2083
 
2084
  ax1.set_title(
2085
+ "Most Frequently Detected Objects"
 
 
 
 
2086
  )
2087
 
2088
+ ax1.set_xlabel(
2089
+ "Number of detections"
 
2090
  )
2091
 
2092
  else:
 
2096
  0.5,
2097
  0.5,
2098
 
2099
+ "No objects detected",
2100
 
2101
  ha="center",
2102
  va="center"
 
2123
 
2124
  buf1.seek(0)
2125
 
2126
+ plot1 = Image.open(
2127
  buf1
2128
  ).convert("RGB")
2129
 
2130
  # ========================================================
2131
+ # PLOT 2 — OBJECTS PER IMAGE
2132
  # ========================================================
2133
 
2134
  fig2, ax2 = plt.subplots(
2135
+ figsize=(8, 5)
2136
  )
2137
 
2138
+ if len(images_df) > 0:
 
 
 
 
 
 
 
 
 
 
 
 
 
2139
 
2140
+ distribution = (
 
 
 
 
 
 
 
 
 
 
2141
 
2142
+ images_df[
2143
+ "Objects Detected"
2144
+ ]
 
 
2145
 
2146
  .value_counts()
2147
 
2148
+ .sort_index()
2149
  )
2150
 
2151
+ ax2.bar(
2152
 
2153
+ distribution.index.astype(
2154
+ str
2155
+ ),
2156
 
2157
+ distribution.values
2158
  )
2159
 
2160
  ax2.set_title(
2161
+ "Detected Objects per Image"
2162
  )
2163
 
2164
  ax2.set_xlabel(
2165
+ "Number of objects"
2166
  )
2167
 
2168
+ ax2.set_ylabel(
2169
+ "Number of images"
 
 
 
 
 
 
 
 
 
2170
  )
2171
 
 
 
2172
  fig2.tight_layout()
2173
 
2174
  buf2 = io.BytesIO()
 
2188
 
2189
  buf2.seek(0)
2190
 
2191
+ plot2 = Image.open(
2192
  buf2
2193
  ).convert("RGB")
2194
 
 
2200
  figsize=(8, 5)
2201
  )
2202
 
2203
+ no_face = (
2204
+
2205
+ total_images -
2206
+ images_with_faces
2207
+ )
2208
+
2209
  ax3.bar(
2210
 
2211
  [
2212
+ "Faces detected",
2213
+ "No faces"
 
2214
  ],
2215
 
2216
  [
2217
  images_with_faces,
2218
+ no_face
 
 
2219
  ]
2220
  )
2221
 
 
2227
  "Number of images"
2228
  )
2229
 
 
 
 
 
 
2230
  fig3.tight_layout()
2231
 
2232
  buf3 = io.BytesIO()
 
2246
 
2247
  buf3.seek(0)
2248
 
2249
+ plot3 = Image.open(
2250
  buf3
2251
  ).convert("RGB")
2252
 
2253
  # ========================================================
2254
+ # PLOT 4 — AGE DISTRIBUTION
2255
  # ========================================================
2256
 
2257
  fig4, ax4 = plt.subplots(
2258
+ figsize=(9, 5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2259
  )
2260
 
2261
+ if len(faces_df) > 0:
 
 
 
 
2262
 
2263
+ ages = (
2264
+ faces_df[
2265
+ "Estimated Age"
2266
+ ]
2267
+ .dropna()
2268
+ )
2269
 
2270
+ if len(ages) > 0:
2271
 
2272
+ ax4.hist(
2273
 
2274
+ ages,
 
2275
 
2276
+ bins=range(
2277
+ 0,
2278
+ 101,
2279
+ 5
2280
+ )
2281
+ )
2282
 
2283
+ ax4.set_title(
2284
+ "Estimated Age Distribution"
2285
+ )
2286
 
2287
+ ax4.set_xlabel(
2288
+ "Estimated age"
2289
+ )
2290
 
2291
+ ax4.set_ylabel(
2292
+ "Detected faces"
2293
+ )
2294
 
2295
+ else:
 
 
2296
 
2297
+ ax4.text(
2298
 
2299
+ 0.5,
2300
+ 0.5,
2301
 
2302
+ "Age estimation failed",
 
 
2303
 
2304
+ ha="center",
2305
+ va="center"
 
 
2306
  )
 
 
 
 
 
2307
 
2308
+ ax4.set_axis_off()
 
 
 
 
 
 
2309
 
2310
  else:
2311
 
2312
+ ax4.text(
2313
 
2314
  0.5,
2315
  0.5,
2316
 
2317
+ "No faces detected",
2318
 
2319
  ha="center",
2320
  va="center"
2321
  )
2322
 
2323
+ ax4.set_axis_off()
2324
 
2325
+ fig4.tight_layout()
2326
 
2327
+ buf4 = io.BytesIO()
2328
 
2329
+ fig4.savefig(
2330
 
2331
+ buf4,
2332
 
2333
  format="png",
2334
 
 
2337
  bbox_inches="tight"
2338
  )
2339
 
2340
+ plt.close(fig4)
2341
 
2342
+ buf4.seek(0)
2343
 
2344
+ plot4 = Image.open(
2345
+ buf4
2346
  ).convert("RGB")
2347
 
2348
  # ========================================================
2349
+ # PLOT 5 — AGE × CATEGORY
2350
  # ========================================================
2351
 
2352
+ fig5, ax5 = plt.subplots(
2353
  figsize=(10, 6)
2354
  )
2355
 
2356
  if len(faces_df) > 0:
2357
 
2358
+ groups = []
 
 
 
 
 
 
 
 
 
2359
 
2360
  labels = []
2361
 
2362
+ for category in sorted(
2363
+
2364
+ faces_df[
2365
+ "Category"
2366
+ ].dropna().unique()
2367
+ ):
2368
 
2369
  values = (
2370
 
 
2383
 
2384
  if len(values) > 0:
2385
 
2386
+ groups.append(
2387
  values
2388
  )
2389
 
 
2391
  str(category)
2392
  )
2393
 
2394
+ if groups:
2395
 
2396
+ ax5.boxplot(
2397
 
2398
+ groups,
2399
 
2400
  labels=labels,
2401
 
2402
  showmeans=True
2403
  )
2404
 
2405
+ ax5.set_title(
2406
  "Estimated Age by Existing Image Category"
2407
  )
2408
 
2409
+ ax5.set_xlabel(
2410
+ "Category"
2411
  )
2412
 
2413
+ ax5.set_ylabel(
2414
  "Estimated age"
2415
  )
2416
 
2417
+ ax5.tick_params(
2418
 
2419
  axis="x",
2420
 
 
2423
 
2424
  else:
2425
 
2426
+ ax5.text(
2427
 
2428
  0.5,
2429
  0.5,
2430
 
2431
+ "No age/category data",
2432
 
2433
  ha="center",
2434
  va="center"
2435
  )
2436
 
2437
+ ax5.set_axis_off()
2438
 
2439
  else:
2440
 
2441
+ ax5.text(
2442
 
2443
  0.5,
2444
  0.5,
2445
 
2446
+ "No age data",
2447
 
2448
  ha="center",
2449
  va="center"
2450
  )
2451
 
2452
+ ax5.set_axis_off()
2453
 
2454
+ fig5.tight_layout()
2455
 
2456
+ buf5 = io.BytesIO()
2457
 
2458
+ fig5.savefig(
2459
 
2460
+ buf5,
2461
 
2462
  format="png",
2463
 
 
2466
  bbox_inches="tight"
2467
  )
2468
 
2469
+ plt.close(fig5)
2470
 
2471
+ buf5.seek(0)
2472
 
2473
+ plot5 = Image.open(
2474
+ buf5
2475
  ).convert("RGB")
2476
 
2477
  # ========================================================
2478
+ # PLOT 6 — AGE GROUP × CATEGORY
2479
  # ========================================================
2480
 
2481
+ fig6, ax6 = plt.subplots(
2482
  figsize=(11, 6)
2483
  )
2484
 
2485
  if len(age_group_category) > 0:
2486
 
2487
+ data = (
2488
+
2489
  age_group_category
2490
+
2491
  .set_index(
2492
  "Age Group"
2493
  )
2494
  )
2495
 
2496
+ data.plot(
2497
 
2498
  kind="bar",
2499
 
2500
+ ax=ax6
2501
  )
2502
 
2503
+ ax6.set_title(
2504
  "Age Groups by Existing Image Category"
2505
  )
2506
 
2507
+ ax6.set_xlabel(
2508
  "Estimated age group"
2509
  )
2510
 
2511
+ ax6.set_ylabel(
2512
+ "Number of faces"
2513
+ )
2514
+
2515
+ ax6.tick_params(
2516
+
2517
+ axis="x",
2518
+
2519
+ rotation=45
2520
  )
2521
 
2522
+ ax6.legend(
2523
+
2524
  title="Category",
2525
+
2526
  bbox_to_anchor=(
2527
  1.02,
2528
  1
2529
  ),
 
 
2530
 
2531
+ loc="upper left"
 
 
2532
  )
2533
 
2534
  else:
2535
 
2536
+ ax6.text(
2537
 
2538
  0.5,
2539
  0.5,
2540
 
2541
+ "No age-group/category data",
2542
 
2543
  ha="center",
2544
  va="center"
2545
  )
2546
 
2547
+ ax6.set_axis_off()
2548
 
2549
+ fig6.tight_layout()
2550
 
2551
+ buf6 = io.BytesIO()
2552
 
2553
+ fig6.savefig(
2554
 
2555
+ buf6,
2556
 
2557
  format="png",
2558
 
 
2561
  bbox_inches="tight"
2562
  )
2563
 
2564
+ plt.close(fig6)
2565
 
2566
+ buf6.seek(0)
2567
 
2568
+ plot6 = Image.open(
2569
+ buf6
2570
  ).convert("RGB")
2571
 
2572
  # ========================================================
2573
+ # RETURN
2574
  # ========================================================
2575
 
2576
  print()
2577
  print("=" * 80)
2578
+ print("COMPLETE")
2579
+ print("=" * 80)
2580
+
2581
+ print(
2582
+ f"Images: {total_images}"
2583
+ )
2584
+
2585
+ print(
2586
+ f"Faces: {total_faces}"
2587
+ )
2588
+
2589
+ print(
2590
+ f"Objects: {total_objects}"
2591
+ )
2592
+
2593
  print("=" * 80)
2594
 
2595
  return (
2596
 
2597
+ images_df,
2598
 
2599
  out_xlsx,
2600
 
 
2602
 
2603
  face_gallery,
2604
 
2605
+ object_gallery,
2606
 
2607
+ plot1,
2608
 
2609
+ plot2,
2610
 
2611
+ plot3,
2612
 
2613
+ plot4,
2614
 
2615
+ plot5,
2616
 
2617
+ plot6
2618
  )
2619
 
2620
 
2621
  # ============================================================
2622
+ # GRADIO INTERFACE
2623
  # ============================================================
2624
 
2625
  demo = gr.Interface(
2626
 
2627
+ fn=analyze_zip,
2628
 
2629
  inputs=[
2630
 
 
2639
  outputs=[
2640
 
2641
  # ----------------------------------------------------
2642
+ # DATAFRAME
2643
  # ----------------------------------------------------
2644
 
2645
  gr.Dataframe(
2646
 
2647
+ label="Image-level analysis",
2648
 
2649
  interactive=False
2650
  ),
2651
 
2652
+ # ----------------------------------------------------
2653
+ # XLSX
2654
+ # ----------------------------------------------------
2655
+
2656
  gr.File(
2657
 
2658
+ label="Download complete XLSX"
2659
  ),
2660
 
2661
  # ----------------------------------------------------
2662
+ # THUMBNAILS
2663
  # ----------------------------------------------------
2664
 
2665
  gr.Gallery(
2666
 
2667
+ label="Image thumbnails",
 
 
2668
 
2669
  columns=5,
2670
 
 
2674
  ),
2675
 
2676
  # ----------------------------------------------------
2677
+ # FACE GALLERY
2678
  # ----------------------------------------------------
2679
 
2680
  gr.Gallery(
2681
 
2682
+ label="Detected faces — diagnostic",
 
 
2683
 
2684
  columns=4,
2685
 
2686
+ rows=3,
2687
 
2688
  height="auto"
2689
  ),
2690
 
2691
  # ----------------------------------------------------
2692
+ # OBJECT GALLERY
2693
  # ----------------------------------------------------
2694
 
2695
+ gr.Gallery(
2696
 
2697
+ label="Detected objects — diagnostic",
2698
+
2699
+ columns=4,
2700
 
2701
+ rows=3,
2702
+
2703
+ height="auto"
2704
  ),
2705
 
2706
+ # ----------------------------------------------------
2707
+ # PLOTS
2708
+ # ----------------------------------------------------
2709
+
2710
  gr.Image(
2711
 
2712
  type="pil",
2713
 
2714
+ label="Most frequently detected objects"
2715
  ),
2716
 
2717
  gr.Image(
2718
 
2719
  type="pil",
2720
 
2721
+ label="Objects per image"
2722
  ),
2723
 
2724
  gr.Image(
2725
 
2726
  type="pil",
2727
 
2728
+ label="Face detection"
2729
  ),
2730
 
2731
  gr.Image(
2732
 
2733
  type="pil",
2734
 
2735
+ label="Estimated age distribution"
2736
  ),
2737
 
2738
  gr.Image(
2739
 
2740
  type="pil",
2741
 
2742
+ label="Estimated age by existing category"
2743
  ),
2744
 
2745
  gr.Image(
2746
 
2747
  type="pil",
2748
 
2749
+ label="Age groups by existing category"
2750
  )
2751
  ],
2752
 
2753
  title=(
2754
+ "Multi-Model Image Analysis"
 
2755
  ),
2756
 
2757
  description=(
2758
 
2759
+ "Upload a ZIP of photographs. "
2760
 
2761
+ "YOLO detects multiple objects and their locations. "
 
 
2762
 
2763
+ "Multiple face-detection methods are attempted, "
2764
+ "followed by age estimation on detected face crops. "
2765
 
2766
+ "Existing folder categories are retained for "
2767
+ "cross-category analysis."
2768
  )
2769
  )
2770