Spaces:
Running on Zero

clementBE commited on
Commit
602afbd
Β·
verified Β·
1 Parent(s): 433b192

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +762 -1
app.py CHANGED
@@ -379,4 +379,765 @@ def detect_faces(image):
379
  min(image_width, x2 + margin),
380
  min(image_height, y2 + margin),
381
  ))
382
- auto_gender,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  min(image_width, x2 + margin),
380
  min(image_height, y2 + margin),
381
  ))
382
+ auto_gender, auto_gender_conf = classify_gender(gender_crop)
383
+
384
+ detections.append({
385
+ "face_index": i + 1,
386
+ "face_id": face_id,
387
+ "confidence": (
388
+ round(probability, 4) if not np.isnan(probability) else None
389
+ ),
390
+ "x1": x1, "y1": y1, "x2": x2, "y2": y2,
391
+ "width": box_width,
392
+ "height": box_height,
393
+ "area_pixels": area_pixels,
394
+ "area_fraction": round(area_fraction, 6),
395
+ "horizontal_position": horizontal,
396
+ "vertical_position": vertical,
397
+
398
+ # Automatic first-pass prediction
399
+ "auto_perceived_gender": auto_gender,
400
+ "auto_gender_confidence": auto_gender_conf,
401
+
402
+ # Manual coding fields (intentionally blank)
403
+ "manual_gender": "",
404
+ "manual_age": "",
405
+ "manual_age_group": "",
406
+ "manual_notes": "",
407
+ })
408
+
409
+ # ---- Face crop for gallery ----
410
+ crop = create_thumbnail(image.crop((x1, y1, x2, y2)), (300, 300))
411
+ prob_text = f"{probability:.2f}" if not np.isnan(probability) else "n/a"
412
+ face_crops.append((crop, f"{face_id} | {prob_text} | {auto_gender}"))
413
+
414
+ # ---- Draw face ----
415
+ draw.rectangle([x1, y1, x2, y2], outline="blue", width=4)
416
+ draw_label(draw, (x1, y1), f"{face_id} {prob_text}", "blue")
417
+
418
+ return detections, annotated, face_crops
419
+
420
+ except Exception as e:
421
+ print("MTCNN error:", repr(e))
422
+ return [], image, []
423
+
424
+
425
+ # ============================================================
426
+ # OBJECT CROPS
427
+ # ============================================================
428
+
429
+ def create_object_crops(image, detections):
430
+ crops = []
431
+
432
+ for d in detections:
433
+ x1, y1, x2, y2 = d["x1"], d["y1"], d["x2"], d["y2"]
434
+ if x2 <= x1 or y2 <= y1:
435
+ continue
436
+
437
+ crop = create_thumbnail(image.crop((x1, y1, x2, y2)), (300, 300))
438
+ crops.append((crop, f"{d['object']} | {d['confidence']:.2f}"))
439
+
440
+ if len(crops) >= MAX_OBJECT_CROPS:
441
+ break
442
+
443
+ return crops
444
+
445
+
446
+ # ============================================================
447
+ # PROCESS ONE IMAGE
448
+ # ============================================================
449
+
450
+ def process_single_image(image_path, extraction_root):
451
+ start = time.time()
452
+
453
+ image = safe_open_image(image_path)
454
+ if image is None:
455
+ return None, [], [], None, [], [], 0
456
+
457
+ filename = os.path.basename(image_path)
458
+ relative_path = os.path.relpath(image_path, extraction_root)
459
+ category, subcategory = get_category_info(image_path, extraction_root)
460
+ width, height = image.size
461
+
462
+ object_detections, _ = detect_objects(image)
463
+ face_detections, _, face_crops = detect_faces(image)
464
+ object_crops = create_object_crops(image, object_detections)
465
+
466
+ # Combined annotation: objects = red, faces = blue
467
+ combined = image.copy()
468
+ draw = ImageDraw.Draw(combined)
469
+
470
+ for d in object_detections:
471
+ draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline="red", width=3)
472
+
473
+ for d in face_detections:
474
+ draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline="blue", width=4)
475
+
476
+ combined = create_thumbnail(combined)
477
+
478
+ gender_counts = pd.Series(
479
+ [d["auto_perceived_gender"] for d in face_detections], dtype="object"
480
+ ).value_counts()
481
+
482
+ image_row = {
483
+ "filename": filename,
484
+ "relative_path": relative_path,
485
+ "category": category,
486
+ "subcategory": subcategory,
487
+ "width": width,
488
+ "height": height,
489
+ "objects_detected": len(object_detections),
490
+ "faces_detected": len(face_detections),
491
+ "auto_female_faces": int(gender_counts.get("female", 0)),
492
+ "auto_male_faces": int(gender_counts.get("male", 0)),
493
+ "auto_uncertain_faces": int(gender_counts.get("uncertain", 0)),
494
+ "object_types": ", ".join(sorted({d["object"] for d in object_detections})),
495
+ "processing_seconds": 0,
496
+ }
497
+
498
+ base = {
499
+ "filename": filename,
500
+ "relative_path": relative_path,
501
+ "category": category,
502
+ "subcategory": subcategory,
503
+ }
504
+
505
+ object_rows = [{**base, **d} for d in object_detections]
506
+ face_rows = [{**base, **d} for d in face_detections]
507
+
508
+ elapsed = time.time() - start
509
+ image_row["processing_seconds"] = round(elapsed, 3)
510
+
511
+ return (
512
+ image_row,
513
+ object_rows,
514
+ face_rows,
515
+ combined,
516
+ object_crops,
517
+ face_crops,
518
+ elapsed,
519
+ )
520
+
521
+
522
+ # ============================================================
523
+ # PLOTS
524
+ # ============================================================
525
+
526
+ def empty_plot(title):
527
+ fig, ax = plt.subplots(figsize=(9, 5))
528
+ ax.set_title(title)
529
+ ax.text(0.5, 0.5, "No data available", ha="center", va="center",
530
+ transform=ax.transAxes)
531
+ ax.axis("off")
532
+ return fig
533
+
534
+
535
+ def plot_top_objects(objects_df):
536
+ if objects_df.empty:
537
+ return empty_plot("Most frequently detected objects")
538
+
539
+ counts = objects_df["object"].value_counts().head(20).sort_values()
540
+ fig, ax = plt.subplots(figsize=(10, 7))
541
+ counts.plot(kind="barh", ax=ax)
542
+ ax.set_title("Most frequently detected objects")
543
+ ax.set_xlabel("Number of detections")
544
+ ax.set_ylabel("Object")
545
+ plt.tight_layout()
546
+ return fig
547
+
548
+
549
+ def plot_objects_per_image(images_df):
550
+ if images_df.empty:
551
+ return empty_plot("Objects per image")
552
+
553
+ fig, ax = plt.subplots(figsize=(9, 5))
554
+ ax.hist(images_df["objects_detected"], bins=20)
555
+ ax.set_title("Objects detected per image")
556
+ ax.set_xlabel("Number of objects")
557
+ ax.set_ylabel("Number of images")
558
+ plt.tight_layout()
559
+ return fig
560
+
561
+
562
+ def plot_objects_by_category(objects_df):
563
+ if objects_df.empty:
564
+ return empty_plot("Objects by category")
565
+
566
+ table = pd.crosstab(objects_df["category"], objects_df["object"])
567
+ if table.empty:
568
+ return empty_plot("Objects by category")
569
+
570
+ top_objects = objects_df["object"].value_counts().head(12).index
571
+ table = table[[x for x in top_objects if x in table.columns]]
572
+
573
+ fig, ax = plt.subplots(figsize=(12, 7))
574
+ table.plot(kind="bar", ax=ax)
575
+ ax.set_title("Detected objects by ZIP category")
576
+ ax.set_xlabel("Category")
577
+ ax.set_ylabel("Number of detections")
578
+ ax.legend(title="Object", bbox_to_anchor=(1.02, 1), loc="upper left")
579
+ plt.tight_layout()
580
+ return fig
581
+
582
+
583
+ def plot_faces_by_category(faces_df):
584
+ if faces_df.empty:
585
+ return empty_plot("Face detections by category")
586
+
587
+ counts = faces_df.groupby("category").size().sort_values()
588
+ fig, ax = plt.subplots(figsize=(10, 6))
589
+ counts.plot(kind="barh", ax=ax)
590
+ ax.set_title("Face detections by category")
591
+ ax.set_xlabel("Number of detected faces")
592
+ ax.set_ylabel("Category")
593
+ plt.tight_layout()
594
+ return fig
595
+
596
+
597
+ def plot_faces_per_image(images_df):
598
+ if images_df.empty:
599
+ return empty_plot("Faces per image")
600
+
601
+ fig, ax = plt.subplots(figsize=(9, 5))
602
+ max_faces = int(images_df["faces_detected"].max())
603
+ ax.hist(images_df["faces_detected"], bins=range(0, max_faces + 2), align="left")
604
+ ax.set_title("Detected faces per image")
605
+ ax.set_xlabel("Number of faces")
606
+ ax.set_ylabel("Number of images")
607
+ plt.tight_layout()
608
+ return fig
609
+
610
+
611
+ def plot_face_position(faces_df):
612
+ if faces_df.empty:
613
+ return empty_plot("Face position")
614
+
615
+ table = pd.crosstab(faces_df["horizontal_position"], faces_df["vertical_position"])
616
+ fig, ax = plt.subplots(figsize=(8, 6))
617
+ table.plot(kind="bar", ax=ax)
618
+ ax.set_title("Detected face positions")
619
+ ax.set_xlabel("Horizontal position")
620
+ ax.set_ylabel("Number of faces")
621
+ ax.legend(title="Vertical position")
622
+ plt.tight_layout()
623
+ return fig
624
+
625
+
626
+ def plot_face_area(faces_df):
627
+ if faces_df.empty:
628
+ return empty_plot("Face area")
629
+
630
+ fig, ax = plt.subplots(figsize=(9, 5))
631
+ ax.hist(faces_df["area_fraction"] * 100, bins=20)
632
+ ax.set_title("Face size relative to image")
633
+ ax.set_xlabel("Face area (% of image)")
634
+ ax.set_ylabel("Number of faces")
635
+ plt.tight_layout()
636
+ return fig
637
+
638
+
639
+ def plot_gender_by_category(faces_df):
640
+ if faces_df.empty:
641
+ return empty_plot("Automatically perceived gender by category")
642
+
643
+ table = pd.crosstab(faces_df["category"], faces_df["auto_perceived_gender"])
644
+ fig, ax = plt.subplots(figsize=(10, 6))
645
+ table.plot(kind="bar", stacked=True, ax=ax)
646
+ ax.set_title("Automatically perceived gender by category (unvalidated)")
647
+ ax.set_xlabel("Category")
648
+ ax.set_ylabel("Number of faces")
649
+ ax.legend(title="Auto label")
650
+ plt.tight_layout()
651
+ return fig
652
+
653
+
654
+ # ============================================================
655
+ # EXCEL EXPORT
656
+ # ============================================================
657
+
658
+ def create_excel(images_df, objects_df, faces_df):
659
+ output = io.BytesIO()
660
+
661
+ with pd.ExcelWriter(output, engine="openpyxl") as writer:
662
+
663
+ images_df.to_excel(writer, sheet_name="Images", index=False)
664
+ objects_df.to_excel(writer, sheet_name="Objects", index=False)
665
+ faces_df.to_excel(writer, sheet_name="Faces", index=False)
666
+
667
+ # Object summary
668
+ if not objects_df.empty:
669
+ object_summary = (
670
+ objects_df.groupby("object")
671
+ .agg(
672
+ detections=("object", "size"),
673
+ mean_confidence=("confidence", "mean"),
674
+ mean_area_fraction=("area_fraction", "mean"),
675
+ )
676
+ .sort_values("detections", ascending=False)
677
+ .reset_index()
678
+ )
679
+ else:
680
+ object_summary = pd.DataFrame()
681
+ object_summary.to_excel(writer, sheet_name="Object Summary", index=False)
682
+
683
+ # Objects by category
684
+ if not objects_df.empty:
685
+ objects_by_category = (
686
+ pd.crosstab(objects_df["category"], objects_df["object"]).reset_index()
687
+ )
688
+ else:
689
+ objects_by_category = pd.DataFrame()
690
+ objects_by_category.to_excel(
691
+ writer, sheet_name="Objects by Category", index=False
692
+ )
693
+
694
+ # Faces by category
695
+ if not faces_df.empty:
696
+ faces_by_category = (
697
+ faces_df.groupby("category").size().reset_index(name="detected_faces")
698
+ )
699
+ else:
700
+ faces_by_category = pd.DataFrame()
701
+ faces_by_category.to_excel(writer, sheet_name="Faces by Category", index=False)
702
+
703
+ # Face positions
704
+ if not faces_df.empty:
705
+ face_positions = pd.crosstab(
706
+ faces_df["horizontal_position"], faces_df["vertical_position"]
707
+ ).reset_index()
708
+ else:
709
+ face_positions = pd.DataFrame()
710
+ face_positions.to_excel(writer, sheet_name="Face Positions", index=False)
711
+
712
+ # Auto gender by category
713
+ if not faces_df.empty:
714
+ gender_by_category = pd.crosstab(
715
+ faces_df["category"], faces_df["auto_perceived_gender"]
716
+ ).reset_index()
717
+ else:
718
+ gender_by_category = pd.DataFrame()
719
+ gender_by_category.to_excel(
720
+ writer, sheet_name="Auto Gender by Category", index=False
721
+ )
722
+
723
+ # Category summary
724
+ if not images_df.empty:
725
+ category_summary = (
726
+ images_df.groupby("category")
727
+ .agg(
728
+ images=("filename", "count"),
729
+ total_objects=("objects_detected", "sum"),
730
+ mean_objects=("objects_detected", "mean"),
731
+ total_faces=("faces_detected", "sum"),
732
+ mean_faces=("faces_detected", "mean"),
733
+ auto_female_faces=("auto_female_faces", "sum"),
734
+ auto_male_faces=("auto_male_faces", "sum"),
735
+ auto_uncertain_faces=("auto_uncertain_faces", "sum"),
736
+ mean_processing_seconds=("processing_seconds", "mean"),
737
+ )
738
+ .reset_index()
739
+ )
740
+ else:
741
+ category_summary = pd.DataFrame()
742
+ category_summary.to_excel(writer, sheet_name="Category Summary", index=False)
743
+
744
+ # Manual coding template (auto prediction sits next to manual field)
745
+ if not faces_df.empty:
746
+ manual_coding = faces_df[FACE_COLUMNS_MANUAL].copy()
747
+ else:
748
+ manual_coding = pd.DataFrame(columns=FACE_COLUMNS_MANUAL)
749
+ manual_coding.to_excel(writer, sheet_name="Manual Coding", index=False)
750
+
751
+ # Global summary
752
+ summary = pd.DataFrame({
753
+ "metric": [
754
+ "Images",
755
+ "Object detections",
756
+ "Unique object classes",
757
+ "Face detections",
758
+ "Faces auto-labelled female",
759
+ "Faces auto-labelled male",
760
+ "Faces auto-labelled uncertain",
761
+ "Categories",
762
+ "Average objects/image",
763
+ "Average faces/image",
764
+ "Average face area (%)",
765
+ ],
766
+ "value": [
767
+ len(images_df),
768
+ len(objects_df),
769
+ objects_df["object"].nunique() if not objects_df.empty else 0,
770
+ len(faces_df),
771
+ int((faces_df["auto_perceived_gender"] == "female").sum())
772
+ if not faces_df.empty else 0,
773
+ int((faces_df["auto_perceived_gender"] == "male").sum())
774
+ if not faces_df.empty else 0,
775
+ int((faces_df["auto_perceived_gender"] == "uncertain").sum())
776
+ if not faces_df.empty else 0,
777
+ images_df["category"].nunique() if not images_df.empty else 0,
778
+ images_df["objects_detected"].mean() if not images_df.empty else 0,
779
+ images_df["faces_detected"].mean() if not images_df.empty else 0,
780
+ faces_df["area_fraction"].mean() * 100 if not faces_df.empty else 0,
781
+ ],
782
+ })
783
+ summary.to_excel(writer, sheet_name="Summary", index=False)
784
+
785
+ output.seek(0)
786
+ return output
787
+
788
+
789
+ # ============================================================
790
+ # MAIN ZIP ANALYSIS
791
+ # ============================================================
792
+
793
+ @spaces.GPU
794
+ def analyze_zip(zip_file, progress=gr.Progress()):
795
+
796
+ if zip_file is None:
797
+ raise gr.Error("Please upload a ZIP file.")
798
+
799
+ start_total = time.time()
800
+ temp_dir = tempfile.mkdtemp(prefix="image_analysis_")
801
+
802
+ try:
803
+ progress(0.02, desc="Extracting ZIP...")
804
+
805
+ zip_path = zip_file if isinstance(zip_file, str) else zip_file.name
806
+
807
+ with zipfile.ZipFile(zip_path, "r") as archive:
808
+ archive.extractall(temp_dir)
809
+
810
+ image_paths = list_images_recursive(temp_dir)
811
+
812
+ if not image_paths:
813
+ raise gr.Error("No supported images were found.")
814
+
815
+ total = len(image_paths)
816
+ print(f"Found {total} images.")
817
+
818
+ image_rows = []
819
+ object_rows = []
820
+ face_rows = []
821
+ annotated_gallery = []
822
+ object_gallery = []
823
+ face_gallery = []
824
+
825
+ for index, image_path in enumerate(image_paths):
826
+
827
+ progress(
828
+ 0.05 + 0.75 * (index / total),
829
+ desc=f"Processing {index + 1}/{total}",
830
+ )
831
+
832
+ (
833
+ image_row,
834
+ image_objects,
835
+ image_faces,
836
+ annotated,
837
+ object_crops,
838
+ face_crops,
839
+ _elapsed,
840
+ ) = process_single_image(image_path, temp_dir)
841
+
842
+ if image_row is None:
843
+ continue
844
+
845
+ image_rows.append(image_row)
846
+ object_rows.extend(image_objects)
847
+ face_rows.extend(image_faces)
848
+
849
+ annotated_gallery.append((annotated, os.path.basename(image_path)))
850
+
851
+ for crop, label in object_crops:
852
+ if len(object_gallery) < MAX_OBJECT_CROPS:
853
+ object_gallery.append((crop, label))
854
+
855
+ for crop, label in face_crops:
856
+ if len(face_gallery) < MAX_FACE_CROPS:
857
+ face_gallery.append((crop, label))
858
+
859
+ # ---------------- DataFrames ----------------
860
+ images_df = pd.DataFrame(image_rows)
861
+ objects_df = pd.DataFrame(object_rows)
862
+ faces_df = pd.DataFrame(face_rows)
863
+
864
+ if objects_df.empty:
865
+ objects_df = pd.DataFrame(columns=OBJECT_COLUMNS)
866
+
867
+ if faces_df.empty:
868
+ faces_df = pd.DataFrame(columns=FACE_COLUMNS_ALL)
869
+
870
+ # ---------------- Excel ----------------
871
+ progress(0.84, desc="Creating Excel report...")
872
+
873
+ excel_bytes = create_excel(images_df, objects_df, faces_df)
874
+ output_xlsx = os.path.join(temp_dir, "image_analysis_results.xlsx")
875
+ with open(output_xlsx, "wb") as f:
876
+ f.write(excel_bytes.getvalue())
877
+
878
+ # ---------------- Plots ----------------
879
+ progress(0.90, desc="Creating plots...")
880
+
881
+ plot_objects = plot_top_objects(objects_df)
882
+ plot_per_image = plot_objects_per_image(images_df)
883
+ plot_category = plot_objects_by_category(objects_df)
884
+ plot_faces_category = plot_faces_by_category(faces_df)
885
+ plot_faces_image = plot_faces_per_image(images_df)
886
+ plot_position = plot_face_position(faces_df)
887
+ plot_face_size = plot_face_area(faces_df)
888
+ plot_gender = plot_gender_by_category(faces_df)
889
+
890
+ # ---------------- Summary ----------------
891
+ elapsed_total = time.time() - start_total
892
+
893
+ unique_objects = objects_df["object"].nunique() if not objects_df.empty else 0
894
+ mean_objects = images_df["objects_detected"].mean() if not images_df.empty else 0
895
+ mean_faces = images_df["faces_detected"].mean() if not images_df.empty else 0
896
+ mean_face_area = (
897
+ faces_df["area_fraction"].mean() * 100 if not faces_df.empty else 0
898
+ )
899
+ n_categories = images_df["category"].nunique() if not images_df.empty else 0
900
+ avg_time = elapsed_total / len(images_df) if len(images_df) > 0 else 0
901
+
902
+ n_female = int((faces_df["auto_perceived_gender"] == "female").sum())
903
+ n_male = int((faces_df["auto_perceived_gender"] == "male").sum())
904
+ n_uncertain = int((faces_df["auto_perceived_gender"] == "uncertain").sum())
905
+
906
+ summary_text = f"""
907
+ # Analysis completed
908
+
909
+ ### Dataset
910
+
911
+ **Images:** {len(images_df):,}
912
+
913
+ **Categories:** {n_categories}
914
+
915
+ ### Objects
916
+
917
+ **Object detections:** {len(objects_df):,}
918
+
919
+ **Unique object classes:** {unique_objects:,}
920
+
921
+ **Average objects/image:** {mean_objects:.2f}
922
+
923
+ ### Faces
924
+
925
+ **Detected faces:** {len(faces_df):,}
926
+
927
+ **Average faces/image:** {mean_faces:.2f}
928
+
929
+ **Mean face area:** {mean_face_area:.2f}% of image
930
+
931
+ ### Automatic perceived gender (unvalidated first pass)
932
+
933
+ **Female:** {n_female:,} | **Male:** {n_male:,} | **Uncertain:** {n_uncertain:,}
934
+
935
+ These labels are automatic guesses of perceived gender presentation from
936
+ appearance, not gender identity. Error rates can differ by skin tone, age
937
+ and image quality. Validate against your manual coding on a sample and
938
+ report the agreement rate.
939
+
940
+ ### Performance
941
+
942
+ **Total time:** {elapsed_total:.1f} seconds
943
+
944
+ **Average time/image:** {avg_time:.2f} seconds
945
+
946
+ **Device:** `{DEVICE}`
947
+
948
+ **YOLO model:** `{YOLO_MODEL_NAME}`
949
+
950
+ **Face detector:** MTCNN
951
+
952
+ **Gender classifier:** `{GENDER_MODEL_NAME}` (min. confidence {GENDER_MIN_CONFIDENCE})
953
+
954
+ ---
955
+
956
+ ### Manual coding
957
+
958
+ The Excel file contains a **Manual Coding** sheet.
959
+
960
+ Each detected face receives a unique identifier such as `face_001`.
961
+ The automatic prediction (`auto_perceived_gender`, `auto_gender_confidence`)
962
+ sits next to blank fields for:
963
+
964
+ - `manual_gender`
965
+ - `manual_age`
966
+ - `manual_age_group`
967
+ - `manual_notes`
968
+ """
969
+
970
+ progress(1.0, desc="Completed")
971
+
972
+ return (
973
+ images_df,
974
+ output_xlsx,
975
+ annotated_gallery,
976
+ object_gallery,
977
+ face_gallery,
978
+ plot_objects,
979
+ plot_per_image,
980
+ plot_category,
981
+ plot_faces_category,
982
+ plot_faces_image,
983
+ plot_position,
984
+ plot_face_size,
985
+ plot_gender,
986
+ summary_text,
987
+ )
988
+
989
+ except gr.Error:
990
+ raise
991
+
992
+ except Exception as e:
993
+ print("ANALYSIS ERROR:", repr(e))
994
+ raise gr.Error(f"Analysis failed: {e}")
995
+
996
+ # The temp directory is intentionally not deleted, because the XLSX
997
+ # output lives in it and Gradio must serve it.
998
+
999
+
1000
+ # ============================================================
1001
+ # GRADIO UI
1002
+ # ============================================================
1003
+
1004
+ with gr.Blocks(title=APP_TITLE) as demo:
1005
+
1006
+ gr.Markdown(
1007
+ """
1008
+ # πŸ“· Image Object & Face Analysis
1009
+
1010
+ Upload a ZIP containing photographs.
1011
+
1012
+ ### Automatic analysis
1013
+
1014
+ - YOLO object detection (multiple objects per image, confidence, boxes, size)
1015
+ - Face detection (confidence, position, size)
1016
+ - Automatic perceived-gender guess per face (female / male / uncertain)
1017
+ - ZIP folder/category analysis
1018
+
1019
+ ### Research coding
1020
+
1021
+ Detected faces receive unique IDs and are exported as face crops for manual
1022
+ coding. The Excel report contains a **Manual Coding** sheet where the automatic
1023
+ prediction sits next to your manual fields, so you can check agreement.
1024
+
1025
+ > ⚠️ Automatic gender labels are *perceived gender presentation* guesses, not
1026
+ > gender identity. Treat them as a first pass and validate them manually.
1027
+ """
1028
+ )
1029
+
1030
+ zip_input = gr.File(
1031
+ label="ZIP file containing images",
1032
+ file_types=[".zip"],
1033
+ )
1034
+
1035
+ analyze_button = gr.Button("πŸš€ Analyze images", variant="primary")
1036
+
1037
+ status = gr.Markdown()
1038
+
1039
+ results_dataframe = gr.Dataframe(
1040
+ label="Image-level results",
1041
+ interactive=False,
1042
+ wrap=True,
1043
+ )
1044
+
1045
+ excel_output = gr.File(label="Download Excel report")
1046
+
1047
+ gr.Markdown(
1048
+ """
1049
+ ## πŸ”΄ Objects + πŸ”΅ Faces
1050
+
1051
+ Red boxes = detected objects
1052
+
1053
+ Blue boxes = detected faces
1054
+ """
1055
+ )
1056
+
1057
+ annotated_gallery = gr.Gallery(
1058
+ label="Annotated images",
1059
+ columns=4,
1060
+ rows=2,
1061
+ height="auto",
1062
+ object_fit="contain",
1063
+ )
1064
+
1065
+ gr.Markdown("## Detected objects")
1066
+
1067
+ object_gallery = gr.Gallery(
1068
+ label="Object crops",
1069
+ columns=6,
1070
+ rows=3,
1071
+ height="auto",
1072
+ object_fit="contain",
1073
+ )
1074
+
1075
+ gr.Markdown(
1076
+ """
1077
+ ## Detected faces
1078
+
1079
+ Each crop has a `face_id | confidence | auto gender` label. The `face_id`
1080
+ corresponds to the **Manual Coding** sheet in the Excel file.
1081
+ """
1082
+ )
1083
+
1084
+ face_gallery = gr.Gallery(
1085
+ label="Face crops",
1086
+ columns=6,
1087
+ rows=3,
1088
+ height="auto",
1089
+ object_fit="contain",
1090
+ )
1091
+
1092
+ gr.Markdown("## πŸ“Š Object analysis")
1093
+
1094
+ with gr.Row():
1095
+ plot_objects_output = gr.Plot(label="Most frequent objects")
1096
+ plot_per_image_output = gr.Plot(label="Objects per image")
1097
+
1098
+ plot_category_output = gr.Plot(label="Objects by category")
1099
+
1100
+ gr.Markdown("## πŸ‘€ Face detection analysis")
1101
+
1102
+ with gr.Row():
1103
+ plot_faces_category_output = gr.Plot(label="Faces by category")
1104
+ plot_faces_image_output = gr.Plot(label="Faces per image")
1105
+
1106
+ with gr.Row():
1107
+ plot_position_output = gr.Plot(label="Face position")
1108
+ plot_face_size_output = gr.Plot(label="Face size")
1109
+
1110
+ plot_gender_output = gr.Plot(label="Automatically perceived gender by category")
1111
+
1112
+ analyze_button.click(
1113
+ fn=analyze_zip,
1114
+ inputs=[zip_input],
1115
+ outputs=[
1116
+ results_dataframe,
1117
+ excel_output,
1118
+ annotated_gallery,
1119
+ object_gallery,
1120
+ face_gallery,
1121
+ plot_objects_output,
1122
+ plot_per_image_output,
1123
+ plot_category_output,
1124
+ plot_faces_category_output,
1125
+ plot_faces_image_output,
1126
+ plot_position_output,
1127
+ plot_face_size_output,
1128
+ plot_gender_output,
1129
+ status,
1130
+ ],
1131
+ )
1132
+
1133
+
1134
+ # ============================================================
1135
+ # LAUNCH
1136
+ # ============================================================
1137
+
1138
+ if __name__ == "__main__":
1139
+ demo.launch(
1140
+ server_name="0.0.0.0",
1141
+ server_port=7860,
1142
+ show_error=True,
1143
+ )