Spaces:
Running on Zero

clementBE commited on
Commit
433b192
·
verified ·
1 Parent(s): 375d6de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -2617
app.py CHANGED
@@ -7,7 +7,7 @@ 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
@@ -17,6 +17,7 @@ import spaces
17
 
18
  from ultralytics import YOLO
19
  from facenet_pytorch import MTCNN
 
20
 
21
 
22
  # ============================================================
@@ -25,44 +26,72 @@ from facenet_pytorch import MTCNN
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",
54
- ".png",
55
- ".webp",
56
- ".bmp",
57
- ".tif",
58
- ".tiff",
59
- }
60
 
 
 
61
  THUMBNAIL_SIZE = (500, 500)
62
-
63
  MAX_OBJECT_CROPS = 150
64
  MAX_FACE_CROPS = 150
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # ============================================================
68
  # DEVICE
@@ -73,17 +102,11 @@ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
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
 
@@ -92,212 +115,141 @@ print("=" * 70)
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,2510 +258,125 @@ def get_face_position(
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]
338
-
339
  names = result.names
340
-
341
  detections = []
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
  # ============================================================
538
- # FACE DETECTION
539
  # ============================================================
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
-
916
- # ============================================================
917
- # PROCESS ONE IMAGE
918
- # ============================================================
919
-
920
- def process_single_image(
921
- image_path,
922
- extraction_root,
923
- ):
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
1120
- # --------------------------------------------------------
1121
-
1122
- face_rows = []
1123
-
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,
1163
- object_rows,
1164
- face_rows,
1165
- combined,
1166
- object_crops,
1167
- face_crops,
1168
- elapsed,
1169
- )
1170
-
1171
-
1172
- # ============================================================
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,
1188
- 0.5,
1189
- "No data available",
1190
- ha="center",
1191
- va="center",
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()
1219
- )
1220
-
1221
- fig, ax = plt.subplots(
1222
- figsize=(10, 7)
1223
- )
1224
-
1225
- counts.plot(
1226
- kind="barh",
1227
- ax=ax
1228
- )
1229
-
1230
- ax.set_title(
1231
- "Most frequently detected objects"
1232
- )
1233
-
1234
- ax.set_xlabel(
1235
- "Number of detections"
1236
- )
1237
-
1238
- ax.set_ylabel(
1239
- "Object"
1240
- )
1241
-
1242
- plt.tight_layout()
1243
-
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
-
1257
- fig, ax = plt.subplots(
1258
- figsize=(9, 5)
1259
- )
1260
-
1261
- ax.hist(
1262
- images_df[
1263
- "objects_detected"
1264
- ],
1265
- bins=20
1266
- )
1267
-
1268
- ax.set_title(
1269
- "Objects detected per image"
1270
- )
1271
-
1272
- ax.set_xlabel(
1273
- "Number of objects"
1274
- )
1275
-
1276
- ax.set_ylabel(
1277
- "Number of images"
1278
- )
1279
-
1280
- plt.tight_layout()
1281
-
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
1319
- )
1320
-
1321
- table = table[
1322
- [
1323
- x
1324
- for x in top_objects
1325
- if x in table.columns
1326
- ]
1327
- ]
1328
-
1329
- fig, ax = plt.subplots(
1330
- figsize=(12, 7)
1331
- )
1332
-
1333
- table.plot(
1334
- kind="bar",
1335
- ax=ax
1336
- )
1337
-
1338
- ax.set_title(
1339
- "Detected objects by ZIP category"
1340
- )
1341
-
1342
- ax.set_xlabel(
1343
- "Category"
1344
- )
1345
-
1346
- ax.set_ylabel(
1347
- "Number of detections"
1348
- )
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()
1360
-
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
- )
1382
-
1383
- fig, ax = plt.subplots(
1384
- figsize=(10, 6)
1385
- )
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(
1397
- "Number of detected faces"
1398
- )
1399
-
1400
- ax.set_ylabel(
1401
- "Category"
1402
- )
1403
-
1404
- plt.tight_layout()
1405
-
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
-
1419
- fig, ax = plt.subplots(
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(
1444
- "Detected faces per image"
1445
- )
1446
-
1447
- ax.set_xlabel(
1448
- "Number of faces"
1449
- )
1450
-
1451
- ax.set_ylabel(
1452
- "Number of images"
1453
- )
1454
-
1455
- plt.tight_layout()
1456
-
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
- # ============================================================
1552
-
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
- # ----------------------------------------------------
1606
- # Object summary
1607
- # ----------------------------------------------------
1608
-
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
- # ----------------------------------------------------
1659
- # Objects by category
1660
- # ----------------------------------------------------
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
- )
1714
- )
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
- # ----------------------------------------------------
1904
- # Global summary
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)
2004
-
2005
- return output
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()
2025
-
2026
- temp_dir = tempfile.mkdtemp(
2027
- prefix="image_analysis_"
2028
- )
2029
-
2030
- try:
2031
-
2032
- # ----------------------------------------------------
2033
- # Extract
2034
- # ----------------------------------------------------
2035
-
2036
- progress(
2037
- 0.02,
2038
- desc="Extracting ZIP..."
2039
- )
2040
-
2041
- if isinstance(
2042
- zip_file,
2043
- str
2044
- ):
2045
-
2046
- zip_path = zip_file
2047
-
2048
- else:
2049
-
2050
- zip_path = zip_file.name
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
2109
- ):
2110
-
2111
- fraction = (
2112
- index / total
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
- (
2136
- image_row,
2137
- image_objects,
2138
- image_faces,
2139
- annotated,
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(
2150
- image_row
2151
- )
2152
-
2153
- object_rows.extend(
2154
- image_objects
2155
- )
2156
-
2157
- face_rows.extend(
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
2220
- )
2221
-
2222
- objects_df = pd.DataFrame(
2223
- object_rows
2224
- )
2225
-
2226
- faces_df = pd.DataFrame(
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",
2243
- "subcategory",
2244
- "object",
2245
- "confidence",
2246
- "x1",
2247
- "y1",
2248
- "x2",
2249
- "y2",
2250
- "width",
2251
- "height",
2252
- "area_pixels",
2253
- "area_fraction",
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()
2446
- if not images_df.empty
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)
2472
- if len(images_df) > 0
2473
- else 0
2474
- :.2f} seconds
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
-
2536
- except Exception as e:
2537
-
2538
- print(
2539
- "ANALYSIS ERROR:",
2540
- repr(e)
2541
- )
2542
-
2543
- raise gr.Error(
2544
- f"Analysis failed: {e}"
2545
- )
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(
2564
- title=APP_TITLE
2565
- ) as demo:
2566
-
2567
- gr.Markdown(
2568
- """
2569
- # 📷 Image Object & Face Analysis
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"
2715
- )
2716
-
2717
- with gr.Row():
2718
-
2719
- plot_objects_output = gr.Plot(
2720
- label="Most frequent objects"
2721
- )
2722
-
2723
- plot_per_image_output = gr.Plot(
2724
- label="Objects per image"
2725
- )
2726
-
2727
- plot_category_output = gr.Plot(
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():
2740
-
2741
- plot_faces_category_output = gr.Plot(
2742
- label="Faces by category"
2743
- )
2744
-
2745
- plot_faces_image_output = gr.Plot(
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
-
2802
- # ============================================================
2803
- # LAUNCH
2804
- # ============================================================
2805
-
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
- )
 
 
 
 
 
 
 
 
7
 
8
  import numpy as np
9
  import pandas as pd
10
+ from PIL import Image, ImageOps, ImageDraw
11
 
12
  import torch
13
  import matplotlib.pyplot as plt
 
17
 
18
  from ultralytics import YOLO
19
  from facenet_pytorch import MTCNN
20
+ from transformers import pipeline
21
 
22
 
23
  # ============================================================
 
26
 
27
  APP_TITLE = "Image Object, Face & Manual Coding Analysis"
28
 
 
29
  # YOLO
30
+ YOLO_MODEL_NAME = "yolov8s.pt" # yolov8n.pt = faster, yolov8s.pt = better
 
 
 
 
 
 
 
 
 
 
31
  OBJECT_CONFIDENCE = 0.25
32
  IOU_THRESHOLD = 0.45
 
33
  MAX_OBJECTS_PER_IMAGE = 50
34
  MAX_FACES_PER_IMAGE = 30
35
 
36
+ # Automatic perceived-gender classifier (first pass only, validate manually!)
37
+ GENDER_MODEL_NAME = "dima806/fairface_gender_image_detection"
38
+ GENDER_MIN_CONFIDENCE = 0.70 # below this -> "uncertain"
39
+ MIN_FACE_PIXELS_FOR_GENDER = 40 # smaller faces -> "uncertain"
40
+ GENDER_CROP_MARGIN = 0.15 # context added around face crop
 
 
 
 
 
 
 
 
41
 
42
+ # Images
43
+ IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
44
  THUMBNAIL_SIZE = (500, 500)
 
45
  MAX_OBJECT_CROPS = 150
46
  MAX_FACE_CROPS = 150
47
 
48
+ FACE_COLUMNS_MANUAL = [
49
+ "face_id",
50
+ "filename",
51
+ "relative_path",
52
+ "category",
53
+ "subcategory",
54
+ "confidence",
55
+ "horizontal_position",
56
+ "vertical_position",
57
+ "area_fraction",
58
+ "auto_perceived_gender",
59
+ "auto_gender_confidence",
60
+ "manual_gender",
61
+ "manual_age",
62
+ "manual_age_group",
63
+ "manual_notes",
64
+ ]
65
+
66
+ FACE_COLUMNS_ALL = [
67
+ "filename",
68
+ "relative_path",
69
+ "category",
70
+ "subcategory",
71
+ "face_index",
72
+ "face_id",
73
+ "confidence",
74
+ "x1", "y1", "x2", "y2",
75
+ "width", "height",
76
+ "area_pixels",
77
+ "area_fraction",
78
+ "horizontal_position",
79
+ "vertical_position",
80
+ "auto_perceived_gender",
81
+ "auto_gender_confidence",
82
+ "manual_gender",
83
+ "manual_age",
84
+ "manual_age_group",
85
+ "manual_notes",
86
+ ]
87
+
88
+ OBJECT_COLUMNS = [
89
+ "filename", "relative_path", "category", "subcategory",
90
+ "object", "confidence",
91
+ "x1", "y1", "x2", "y2",
92
+ "width", "height", "area_pixels", "area_fraction",
93
+ ]
94
+
95
 
96
  # ============================================================
97
  # DEVICE
 
102
  print("=" * 70)
103
  print("IMAGE ANALYSIS APPLICATION")
104
  print("=" * 70)
 
105
  print("PyTorch:", torch.__version__)
106
  print("CUDA:", torch.cuda.is_available())
107
  print("Device:", DEVICE)
 
108
  if torch.cuda.is_available():
109
+ print("GPU:", torch.cuda.get_device_name(0))
 
 
 
 
110
  print("=" * 70)
111
 
112
 
 
115
  # ============================================================
116
 
117
  print("Loading YOLO...")
118
+ yolo_model = YOLO(YOLO_MODEL_NAME)
 
 
 
 
119
  if DEVICE == "cuda":
 
120
  try:
121
  yolo_model.to("cuda")
122
  except Exception as e:
123
+ print("Could not explicitly move YOLO to CUDA:", e)
 
 
 
 
124
  print("YOLO loaded.")
125
 
 
 
 
 
 
126
  print("Loading MTCNN...")
 
127
  mtcnn = MTCNN(
128
  image_size=160,
129
  margin=20,
130
  min_face_size=20,
131
+ thresholds=[0.60, 0.70, 0.70],
 
 
 
 
132
  factor=0.709,
133
  post_process=False,
134
  keep_all=True,
135
  device=DEVICE,
136
  )
 
137
  print("MTCNN loaded.")
138
 
139
+ print("Loading gender classifier...")
140
+ gender_classifier = pipeline(
141
+ "image-classification",
142
+ model=GENDER_MODEL_NAME,
143
+ device=0 if DEVICE == "cuda" else -1,
144
+ )
145
+ print("Gender classifier loaded.")
146
+
147
 
148
  # ============================================================
149
  # GENERAL UTILITIES
150
  # ============================================================
151
 
152
  def safe_open_image(path):
 
153
  try:
 
154
  with Image.open(path) as img:
155
+ img = ImageOps.exif_transpose(img)
 
 
 
 
156
  return img.convert("RGB")
 
157
  except Exception as e:
158
+ print(f"Could not open {path}: {e}")
 
 
 
 
159
  return None
160
 
161
 
162
+ def create_thumbnail(image, max_size=THUMBNAIL_SIZE):
 
 
 
 
163
  img = image.copy()
164
+ img.thumbnail(max_size)
 
 
 
 
165
  return img
166
 
167
 
168
  def list_images_recursive(root):
 
169
  images = []
170
+ for current_root, _dirs, files in os.walk(root):
 
 
 
 
171
  for filename in files:
172
+ if Path(filename).suffix.lower() in IMAGE_EXTENSIONS:
173
+ images.append(os.path.join(current_root, filename))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  return sorted(images)
175
 
176
 
177
+ def get_category_info(image_path, extraction_root):
178
+ relative = os.path.relpath(image_path, extraction_root)
179
+ parts = Path(relative).parts
180
+ category = parts[0] if len(parts) >= 2 else "ROOT"
181
+ subcategory = parts[1] if len(parts) >= 3 else ""
182
+ return category, subcategory
 
 
 
 
 
 
 
183
 
 
184
 
185
+ def get_box_position(x1, y1, x2, y2, image_width, image_height):
186
+ cx = (x1 + x2) / 2 / image_width
187
+ cy = (y1 + y2) / 2 / image_height
188
 
189
+ if cx < 0.333:
190
+ horizontal = "left"
191
+ elif cx < 0.666:
192
+ horizontal = "center"
193
  else:
194
+ horizontal = "right"
195
 
196
+ if cy < 0.333:
197
+ vertical = "top"
198
+ elif cy < 0.666:
199
+ vertical = "middle"
 
 
200
  else:
201
+ vertical = "bottom"
202
 
203
+ return horizontal, vertical
 
 
 
 
 
 
 
 
 
 
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
+ def clamp_box(box, image_width, image_height):
207
+ x1, y1, x2, y2 = box
208
+ return (
209
+ max(0, int(x1)),
210
+ max(0, int(y1)),
211
+ min(image_width, int(x2)),
212
+ min(image_height, int(y2)),
213
  )
214
 
 
 
 
 
 
 
 
 
215
 
216
+ def draw_label(draw, xy, text, color):
217
+ try:
218
+ draw.rectangle(draw.textbbox(xy, text), fill=color)
219
+ except Exception:
220
+ pass
221
+ draw.text(xy, text, fill="white")
222
 
 
223
 
224
+ # ============================================================
225
+ # GENDER CLASSIFICATION
226
+ # ============================================================
227
 
228
+ def classify_gender(face_image):
229
+ """
230
+ Returns (label, confidence) for one face crop.
231
 
232
+ The label is an automatic guess of PERCEIVED gender presentation
233
+ from appearance. It is not gender identity. Low-confidence or very
234
+ small faces are labelled "uncertain".
235
+ """
236
+ try:
237
+ w, h = face_image.size
238
+ if min(w, h) < MIN_FACE_PIXELS_FOR_GENDER:
239
+ return "uncertain", None
240
 
241
+ predictions = gender_classifier(face_image)
242
+ best = max(predictions, key=lambda p: p["score"])
243
+ score = float(best["score"])
244
 
245
+ if score < GENDER_MIN_CONFIDENCE:
246
+ return "uncertain", round(score, 4)
247
 
248
+ return str(best["label"]).lower(), round(score, 4)
249
 
250
+ except Exception as e:
251
+ print("Gender error:", repr(e))
252
+ return "uncertain", None
 
253
 
254
 
255
  # ============================================================
 
258
 
259
  @spaces.GPU
260
  def detect_objects(image):
 
261
  if image is None:
 
262
  return [], image
263
 
264
  try:
 
265
  results = yolo_model.predict(
 
266
  source=np.array(image),
 
267
  conf=OBJECT_CONFIDENCE,
 
268
  iou=IOU_THRESHOLD,
269
+ device=0 if DEVICE == "cuda" else "cpu",
 
 
 
 
 
 
270
  verbose=False,
271
  )
272
 
273
  if not results:
 
274
  return [], image
275
 
276
  result = results[0]
 
277
  names = result.names
 
278
  detections = []
 
279
  annotated = image.copy()
280
+ draw = ImageDraw.Draw(annotated)
281
+ image_width, image_height = image.size
 
 
 
 
 
 
282
 
283
  if result.boxes is None:
 
284
  return [], annotated
285
 
286
  boxes = result.boxes
287
+ image_area = image_width * image_height
288
 
289
+ for i in range(min(len(boxes), MAX_OBJECTS_PER_IMAGE)):
290
+ cls_id = int(boxes.cls[i].item())
291
+ confidence = float(boxes.conf[i].item())
292
+ x1, y1, x2, y2 = clamp_box(
293
+ boxes.xyxy[i].tolist(), image_width, image_height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  )
295
 
296
+ box_width = max(0, x2 - x1)
297
+ box_height = max(0, y2 - y1)
298
+ area_pixels = box_width * box_height
299
+ area_fraction = area_pixels / image_area if image_area > 0 else 0
300
+ object_name = names.get(cls_id, str(cls_id))
 
 
 
 
 
301
 
302
  detections.append({
 
303
  "object": object_name,
304
+ "confidence": round(confidence, 4),
305
+ "x1": x1, "y1": y1, "x2": x2, "y2": y2,
 
 
 
 
 
 
 
 
 
306
  "width": box_width,
307
  "height": box_height,
308
+ "area_pixels": area_pixels,
309
+ "area_fraction": round(area_fraction, 6),
 
 
 
 
 
 
 
310
  })
311
 
312
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
313
+ draw_label(draw, (x1, y1), f"{object_name} {confidence:.2f}", "red")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
+ return detections, annotated
 
 
 
316
 
317
  except Exception as e:
318
+ print("YOLO error:", repr(e))
319
+ return [], image
 
 
 
 
 
 
 
 
320
 
321
 
322
  # ============================================================
323
+ # FACE DETECTION + AUTOMATIC GENDER
324
  # ============================================================
325
 
326
  @spaces.GPU
327
  def detect_faces(image):
 
328
  """
329
+ Detects faces and their locations, and adds an automatic
330
+ perceived-gender guess (to be validated against manual coding).
331
+ No age or identity inference.
332
  """
 
333
  if image is None:
334
+ return [], image, []
 
 
 
 
 
335
 
336
  try:
337
+ boxes, probabilities = mtcnn.detect(np.array(image))
 
 
 
 
 
 
 
 
 
338
 
339
  detections = []
 
340
  annotated = image.copy()
341
+ draw = ImageDraw.Draw(annotated)
 
 
 
 
342
  face_crops = []
343
 
344
  if boxes is None:
345
+ return [], annotated, []
346
 
347
+ image_width, image_height = image.size
348
+ image_area = image_width * image_height
 
 
 
 
 
 
 
 
 
 
 
349
 
350
+ for i, box in enumerate(boxes):
351
  if i >= MAX_FACES_PER_IMAGE:
 
352
  break
353
 
354
+ x1, y1, x2, y2 = clamp_box(box.tolist(), image_width, image_height)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
  if x2 <= x1 or y2 <= y1:
 
357
  continue
358
 
359
  probability = (
360
+ float(probabilities[i]) if probabilities is not None else np.nan
 
 
 
 
 
 
 
 
 
 
 
361
  )
362
 
363
+ box_width = x2 - x1
364
+ box_height = y2 - y1
365
+ area_pixels = box_width * box_height
366
+ area_fraction = area_pixels / image_area if image_area > 0 else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
+ horizontal, vertical = get_box_position(
369
+ x1, y1, x2, y2, image_width, image_height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  )
371
 
372
+ face_id = f"face_{i + 1:03d}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
 
374
+ # ---- Automatic perceived gender (crop with margin) ----
375
+ margin = int(GENDER_CROP_MARGIN * max(box_width, box_height))
376
+ gender_crop = image.crop((
377
+ max(0, x1 - margin),
378
+ max(0, y1 - margin),
379
+ min(image_width, x2 + margin),
380
+ min(image_height, y2 + margin),
381
+ ))
382
+ auto_gender,