-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3799 lines (3481 loc) · 163 KB
/
app.py
File metadata and controls
3799 lines (3481 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Interactive Shortcut Detection Dashboard
Gradio-based web interface for detecting shortcuts in embedding spaces
"""
import os
import subprocess
import sys
import tempfile
from datetime import datetime
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
import torch
from pandas.errors import EmptyDataError, ParserError
from PIL import Image
# On macOS, ensure Homebrew system libraries (glib, pango) are discoverable
# so weasyprint PDF generation works inside conda/venv environments.
if sys.platform == "darwin":
try:
_brew_prefix = subprocess.check_output(
["brew", "--prefix"],
stderr=subprocess.DEVNULL,
text=True,
).strip()
_brew_lib = os.path.join(_brew_prefix, "lib")
_fallback = os.environ.get("DYLD_FALLBACK_LIBRARY_PATH", "")
if _brew_lib not in _fallback:
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = (
f"{_brew_lib}:{_fallback}" if _fallback else _brew_lib
)
except (FileNotFoundError, subprocess.CalledProcessError):
pass
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from shortcut_detect import ( # noqa: E402
AdversarialDebiasing,
BackgroundRandomizer,
ContrastiveDebiasing,
ExplanationRegularization,
GradCAMHeatmapGenerator,
HuggingFaceEmbeddingSource,
LastLayerRetraining,
ModelComparisonRunner,
ShortcutDetector,
ShortcutMasker,
SpRAyDetector,
generate_parametric_shortcut_dataset,
get_embedding_registry,
)
from shortcut_detect.reporting.comparison_report import ComparisonReportBuilder # noqa: E402
from shortcut_detect.reporting.csv_export import export_comparison_to_csv # noqa: E402
REPORT_CONTRAST_CSS = """
/* Force detection report to black text on light background (Gradio 5/6 use different wrappers) */
.gr-html .container, .gr-html .container *,
.gr-html .shortcut-report, .gr-html .shortcut-report *,
main .container, main .container *,
main .shortcut-report, main .shortcut-report *,
[class*="html"] .container, [class*="html"] .container *,
[class*="html"] .shortcut-report, [class*="html"] .shortcut-report * { color: #000 !important; }
.gr-html .container, .gr-html .shortcut-report,
main .container, main .shortcut-report,
[class*="html"] .container, [class*="html"] .shortcut-report { background: #fff !important; }
.gr-html .shortcut-report th, main .shortcut-report th, [class*="html"] .shortcut-report th { background: #1d4ed8 !important; color: #fff !important; }
.gr-html .shortcut-report code, main .shortcut-report code, [class*="html"] .shortcut-report code { background: unset !important; background-color: rgba(255, 255, 255, 1) !important; color: rgba(21, 87, 36, 1) !important; background-clip: unset; -webkit-background-clip: unset; box-shadow: none !important; }
.gr-html .shortcut-report::selection, .gr-html .shortcut-report *::selection,
main .shortcut-report::selection, main .shortcut-report *::selection,
[class*="html"] .shortcut-report::selection, [class*="html"] .shortcut-report *::selection { background: #b4d5fe; color: #000; }
"""
def find_data_dir():
"""Find the data directory in the project"""
current = Path(__file__).parent
for _ in range(5):
data_path = current / "data"
if data_path.exists():
return data_path
current = current.parent
return None
def load_sample_data(use_real_embeddings: bool = False):
"""
Load CheXpert data with optional real or synthetic embeddings.
When use_real_embeddings=True and data/chest_*.npy exist, loads pre-computed
embeddings. Otherwise uses synthetic embeddings with real CheXpert metadata
and demographics (train.csv + CHEXPERT DEMO.xlsx).
Returns: embeddings, task_labels, group_labels, extra_labels, attributes, metadata_df
"""
data_dir = find_data_dir()
if data_dir is None:
raise FileNotFoundError("Could not find data directory")
# Optionally use real pre-computed embeddings (chest_*.npy from benchmark)
if use_real_embeddings:
emb_path = data_dir / "chest_embeddings.npy"
lbl_path = data_dir / "chest_labels.npy"
grp_path = data_dir / "chest_group_labels.npy"
if emb_path.exists() and lbl_path.exists() and grp_path.exists():
embeddings = np.load(str(emb_path))
task_labels = np.load(str(lbl_path))
group_labels = np.load(str(grp_path))
if embeddings.ndim != 2 or task_labels.ndim != 1 or group_labels.ndim != 1:
raise ValueError("Chest embeddings must be 2D; labels/group_labels must be 1D")
n = embeddings.shape[0]
if task_labels.shape[0] != n or group_labels.shape[0] != n:
raise ValueError("Chest arrays must have matching length")
# Ensure binary labels
task_labels = (np.asarray(task_labels).astype(float) > 0).astype(int)
# Convert group_labels to strings if needed
group_labels = np.asarray(group_labels, dtype=object)
extra_labels = {"group": group_labels}
codes = pd.Categorical(group_labels).codes
attributes = {"group": np.asarray(codes)}
return embeddings, task_labels, group_labels, extra_labels, attributes, None
# Load real CheXpert metadata and demographics
train_csv = data_dir / "train.csv"
demo_xlsx = data_dir / "CHEXPERT DEMO.xlsx"
if not train_csv.exists():
raise FileNotFoundError(f"train.csv not found at {train_csv}")
# Load training data
data_df = pd.read_csv(train_csv)
# Extract patient ID from Path column
# Path format: "CheXpert-v1.0-small/train/patient00001/study1/..."
data_df["PATIENT"] = data_df["Path"].str.extract(r"(patient\d+)", expand=False)
# Load demographics if available
if demo_xlsx.exists():
demo_df = pd.read_excel(demo_xlsx, engine="openpyxl")
# Merge demographics
data_df = data_df.merge(
demo_df[["PATIENT", "PRIMARY_RACE", "GENDER"]], on="PATIENT", how="left"
)
# Process race labels
if "PRIMARY_RACE" in data_df.columns:
data_df["race"] = "OTHER"
mask_asian = data_df.PRIMARY_RACE.str.contains("Asian", na=False)
data_df.loc[mask_asian, "race"] = "ASIAN"
mask_black = data_df.PRIMARY_RACE.str.contains("Black", na=False)
data_df.loc[mask_black, "race"] = "BLACK/AFRICAN AMERICAN"
mask_white = data_df.PRIMARY_RACE.str.contains("White", na=False)
data_df.loc[mask_white, "race"] = "WHITE"
else:
# If no demographics, create synthetic groups
data_df["race"] = np.random.choice(
["ASIAN", "BLACK/AFRICAN AMERICAN", "WHITE"], size=len(data_df)
)
# Sample 2000 random samples for lightweight demo
if len(data_df) > 2000:
data_df = data_df.sample(n=2000, random_state=42).reset_index(drop=True)
n_samples = len(data_df)
# Generate lightweight embeddings (512-dim instead of 2048)
embedding_dim = 512
shortcut_dims = 10 # First 10 dimensions contain shortcuts
# Create task labels (binary classification: Cardiomegaly)
if "Cardiomegaly" in data_df.columns:
task_labels = data_df["Cardiomegaly"].fillna(0).astype(int).values
else:
# Synthetic task labels if column doesn't exist
task_labels = np.random.randint(0, 2, size=n_samples)
# Ensure binary labels (map {-1,0,1} and other positives -> {0,1})
task_labels = (task_labels > 0).astype(int)
# Generate embeddings with shortcuts correlated to race
synthetic_dataset = generate_parametric_shortcut_dataset(
n_samples=n_samples, embedding_dim=embedding_dim, shortcut_dims=shortcut_dims, seed=42
)
embeddings = synthetic_dataset.embeddings
# Get group labels (race)
group_labels = data_df["race"].values
# Build extra_labels for intersectional analysis (race + gender when both present)
extra_labels = None
if "GENDER" in data_df.columns and "race" in data_df.columns:
gender = data_df["GENDER"].fillna("Unknown").astype(str).str.strip()
# Normalize common gender values
gender = gender.replace({"M": "Male", "F": "Female", "m": "Male", "f": "Female"})
# Exclude rows with missing/unknown for intersectional (detector will filter)
extra_labels = {
"race": data_df["race"].values,
"gender": gender.values,
}
# Attributes for causal_effect: race (encoded) + synthetic second attribute
race_codes = pd.Categorical(data_df["race"]).codes
rng = np.random.default_rng(42)
attr_gender = rng.integers(0, 2, size=n_samples)
attributes = {"race": np.asarray(race_codes), "gender": attr_gender}
return embeddings, task_labels, group_labels, extra_labels, attributes, data_df
def _parse_attr_columns(df, attr_cols):
"""Parse attr_* columns into attributes dict for causal_effect."""
if not attr_cols:
return None
attrs = {}
for c in attr_cols:
name = c[5:].strip() if len(c) > 5 else ""
if not name:
continue # skip malformed columns like "attr_" (no suffix)
col = df[c]
if pd.api.types.is_numeric_dtype(col):
arr = np.asarray(col.fillna(-1).astype(int))
else:
arr = np.asarray(pd.Categorical(col).codes)
attrs[name] = arr
return attrs
def _add_intersectional_extra_labels(df, attr_cols, group_labels, extra_labels):
"""Add demographic attributes to extra_labels for intersectional and multi-attribute analysis.
Adds all attr_* columns and group_label (as "group") when present.
Intersectional detector requires 2+ attributes; multi-attribute single-attribute
methods use all attributes for per-attribute analysis.
"""
extra = dict(extra_labels) if extra_labels else {}
# Add group_label as "group" when present
if group_labels is not None:
extra["group"] = np.asarray(group_labels, dtype=object)
# Add all attr_* columns (attr_race -> "race", attr_gender -> "gender", etc.)
for c in attr_cols:
name = c[5:].strip() if len(c) > 5 else ""
if name:
extra[name] = np.asarray(df[c].fillna("").astype(str).values)
# Return updated if we added any demographic attributes
if len([k for k in extra if k not in ("spurious", "early_epoch_reps")]) >= 1:
return extra
return extra_labels
def load_custom_csv(csv_file, is_raw_data=False):
"""
Load custom CSV file uploaded by user
If is_raw_data=False (embeddings mode):
Expected columns: embedding_0, embedding_1, ..., task_label, group_label
If is_raw_data=True (raw data mode):
Expected columns: text, task_label, group_label
Optional columns:
spurious_label (for SSA extra supervision)
attr_<name> (for causal_effect, intersectional, and multi-attribute: e.g., attr_race, attr_gender, attr_age)
"""
if csv_file is None:
raise ValueError("No CSV file provided")
# Handle both Gradio file object and string path
file_path = csv_file.name if hasattr(csv_file, "name") else csv_file
try:
df = pd.read_csv(file_path)
except EmptyDataError as exc:
raise ValueError(
"CSV file is empty. Please upload a file with a header row and data rows."
) from exc
except ParserError as exc:
raise ValueError(
"Unable to parse CSV format. Check that rows have consistent columns and values are properly quoted."
) from exc
except UnicodeDecodeError as exc:
raise ValueError("CSV file must be UTF-8 encoded text.") from exc
if df.empty:
raise ValueError("CSV has headers but no data rows. Add at least one sample row.")
# Common wrong-delimiter signal: entire header parsed as one column.
if len(df.columns) == 1:
header_col = str(df.columns[0])
if ";" in header_col or "\t" in header_col or "|" in header_col:
raise ValueError(
"CSV appears to use the wrong delimiter. Please upload a comma-separated file (`,` delimiter)."
)
if is_raw_data:
# Raw data mode: expect text column
if "text" not in df.columns:
raise ValueError("Raw data CSV must have a 'text' column containing the raw text data")
# Get text data
raw_texts = df["text"].astype(str).tolist()
# Get labels
if "task_label" not in df.columns:
raise ValueError("CSV must have a 'task_label' column")
task_labels = df["task_label"].values
if pd.isna(df["task_label"]).any():
raise ValueError(
"Column 'task_label' contains empty values. Every row must include a label."
)
if "group_label" in df.columns:
group_labels = df["group_label"].values
else:
group_labels = None
if "group_label" in df.columns and pd.isna(df["group_label"]).any():
raise ValueError(
"Column 'group_label' contains empty values. Fill missing values or remove the column."
)
if df["text"].astype(str).str.strip().eq("").any():
raise ValueError(
"Column 'text' contains empty values. Every row must include non-empty text."
)
# Validate lengths match
if len(raw_texts) != len(task_labels):
raise ValueError(
f"Length mismatch: {len(raw_texts)} text entries but {len(task_labels)} task labels. "
"Each row must have both text and task_label."
)
if group_labels is not None and len(raw_texts) != len(group_labels):
raise ValueError(
f"Length mismatch: {len(raw_texts)} text entries but {len(group_labels)} group labels. "
"Each row must have text, task_label, and group_label."
)
if "spurious_label" in df.columns:
extra_labels = {"spurious": df["spurious_label"].values}
attr_cols = [c for c in df.columns if c.startswith("attr_")]
# Add demographic attributes for intersectional (need 2+ attr_* or group_label + attr_*)
extra_labels = _add_intersectional_extra_labels(df, attr_cols, group_labels, extra_labels)
attributes = _parse_attr_columns(df, attr_cols)
return raw_texts, task_labels, group_labels, extra_labels, attributes, df
else:
# Embeddings mode: extract embedding columns (exclude attr_*)
embedding_cols = [col for col in df.columns if col.startswith("embedding_")]
if len(embedding_cols) == 0:
# Try to use all numeric columns except labels and attr_*
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
exclude = {"task_label", "group_label"} | {
c for c in df.columns if c.startswith("attr_")
}
embedding_cols = [col for col in numeric_cols if col not in exclude]
if len(embedding_cols) == 0:
raise ValueError(
"No embedding columns found. Expected columns like 'embedding_0', 'embedding_1', etc."
)
if any(pd.isna(df[col]).any() for col in embedding_cols):
raise ValueError(
"Embedding columns contain empty values. Fill missing values in embedding features."
)
non_numeric_cols = [
col for col in embedding_cols if not pd.api.types.is_numeric_dtype(df[col])
]
if non_numeric_cols:
bad_cols = ", ".join(non_numeric_cols[:3])
if len(non_numeric_cols) > 3:
bad_cols += ", ..."
raise ValueError(
f"Embedding columns must be numeric. Non-numeric columns detected: {bad_cols}"
)
embeddings = df[embedding_cols].values
# Get labels
if "task_label" not in df.columns:
raise ValueError("CSV must have a 'task_label' column")
task_labels = df["task_label"].values
if pd.isna(df["task_label"]).any():
raise ValueError(
"Column 'task_label' contains empty values. Every row must include a label."
)
if "group_label" in df.columns:
group_labels = df["group_label"].values
else:
group_labels = None
if "group_label" in df.columns and pd.isna(df["group_label"]).any():
raise ValueError(
"Column 'group_label' contains empty values. Fill missing values or remove the column."
)
extra_labels = None
if "spurious_label" in df.columns:
extra_labels = {"spurious": df["spurious_label"].values}
attr_cols = [c for c in df.columns if c.startswith("attr_")]
extra_labels = _add_intersectional_extra_labels(df, attr_cols, group_labels, extra_labels)
attributes = _parse_attr_columns(df, attr_cols)
return embeddings, task_labels, group_labels, extra_labels, attributes, df
def _build_ssa_splits(
n_samples: int, labeled_fraction: float, seed: int = 42
) -> dict[str, np.ndarray]:
if n_samples < 2:
raise ValueError("SSA requires at least 2 samples to create labeled/unlabeled splits.")
if labeled_fraction <= 0 or labeled_fraction >= 1:
raise ValueError("SSA labeled fraction must be between 0 and 1.")
rng = np.random.default_rng(seed)
indices = np.arange(n_samples)
rng.shuffle(indices)
n_labeled = int(round(n_samples * labeled_fraction))
n_labeled = max(1, min(n_labeled, n_samples - 1))
train_l = np.sort(indices[:n_labeled])
train_u = np.sort(indices[n_labeled:])
return {"train_l": train_l, "train_u": train_u}
def _load_torch_model(model_file) -> torch.nn.Module:
"""Load a serialized PyTorch module from a Gradio file upload."""
if model_file is None:
raise ValueError("Please upload a PyTorch model file (.pt or .pth).")
path = model_file.name if hasattr(model_file, "name") else model_file
# PyTorch 2.6+ requires weights_only=False for loading full models
model = torch.load(path, map_location="cpu", weights_only=False)
if isinstance(model, torch.nn.Module):
return model
raise TypeError(
"Loaded object is not a torch.nn.Module. Please upload a serialized model (not a state_dict)."
)
def _parse_head_identifier(value: str | None, fallback: str | int) -> str | int:
"""Convert user-provided head identifier text into str/int used by GradCAM."""
if value is None:
return fallback
text = str(value).strip()
if text == "":
return fallback
if text.lstrip("-").isdigit():
return int(text)
return text
def _parse_optional_int(value: int | float | None) -> int | None:
if value is None or (isinstance(value, str) and value.strip() == ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValueError("Target indices must be integers.") from exc
def _preprocess_gradcam_image(image_file, image_size: int, color_mode: str):
if image_file is None:
raise ValueError("Please upload an image for GradCAM analysis.")
if image_size <= 0:
raise ValueError("Image size must be a positive integer.")
mode = "L" if color_mode == "Grayscale" else "RGB"
with Image.open(image_file.name if hasattr(image_file, "name") else image_file) as img:
img = img.convert(mode)
img = img.resize((image_size, image_size))
if mode == "L":
arr = np.array(img, dtype=np.float32) / 255.0
display = np.stack([arr, arr, arr], axis=-1)
tensor = torch.from_numpy(arr).unsqueeze(0).unsqueeze(0)
else:
arr = np.array(img, dtype=np.float32) / 255.0
display = arr
tensor = torch.from_numpy(arr.transpose(2, 0, 1)).unsqueeze(0)
tensor = tensor.float()
tensor.requires_grad_(True)
return display, tensor
def _overlay_heatmap(
base_image: np.ndarray, heatmap: np.ndarray, alpha: float = 0.45
) -> np.ndarray:
import matplotlib
base = np.clip(base_image, 0.0, 1.0)
cmap = matplotlib.colormaps["jet"]
heat = np.clip(heatmap, 0.0, 1.0)
colored = cmap(heat)[..., :3]
overlay = np.clip((1 - alpha) * base + alpha * colored, 0.0, 1.0)
return (overlay * 255).astype(np.uint8)
def _colorize_heatmap(heatmap: np.ndarray, cmap_name: str = "magma") -> np.ndarray:
import matplotlib
cmap = matplotlib.colormaps[cmap_name]
heat = np.clip(heatmap, 0.0, 1.0)
colored = cmap(heat)[..., :3]
return (colored * 255).astype(np.uint8)
def _load_heatmap_file(file_obj):
if file_obj is None:
raise ValueError("Please upload a heatmap file (.npz or .npy).")
path = file_obj.name if hasattr(file_obj, "name") else file_obj
if path.endswith(".npz"):
data = np.load(path, allow_pickle=True)
if "heatmaps" in data:
heatmaps = data["heatmaps"]
else:
keys = list(data.keys())
if not keys:
raise ValueError("No arrays found in .npz file.")
heatmaps = data[keys[0]]
labels = data["labels"] if "labels" in data else None
group_labels = data["group_labels"] if "group_labels" in data else None
return heatmaps, labels, group_labels
if path.endswith(".npy"):
heatmaps = np.load(path, allow_pickle=True)
return heatmaps, None, None
raise ValueError("Unsupported file format. Use .npz or .npy.")
def _preprocess_gradcam_images(image_files, image_size: int, color_mode: str) -> torch.Tensor:
if not image_files:
raise ValueError("Please upload one or more images.")
tensors = []
for image_file in image_files:
_, tensor = _preprocess_gradcam_image(image_file, image_size, color_mode)
tensors.append(tensor)
return torch.cat(tensors, dim=0)
def _preprocess_mask_images(mask_files, image_size: int) -> np.ndarray:
if not mask_files:
raise ValueError("Please upload one or more mask images.")
masks = []
for mask_file in mask_files:
with Image.open(mask_file.name if hasattr(mask_file, "name") else mask_file) as img:
img = img.convert("L")
img = img.resize((image_size, image_size))
arr = np.array(img, dtype=np.float32) / 255.0
masks.append(arr)
return np.stack(masks, axis=0)
def run_gradcam_analysis(
model_file,
image_file,
target_layer: str,
disease_head: str,
attribute_head: str,
disease_target: int | float | None,
attribute_target: int | float | None,
threshold: float,
image_size: int,
color_mode: str,
):
"""Gradio callback that computes GradCAM heatmaps and overlap metrics."""
if not target_layer or target_layer.strip() == "":
error_html = """
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>GradCAM Error:</strong> Please provide a valid target layer path.
</div>
"""
return error_html, None, None, None
try:
model = _load_torch_model(model_file)
base_image, tensor_input = _preprocess_gradcam_image(
image_file, int(image_size), color_mode
)
disease_identifier = _parse_head_identifier(disease_head, "disease")
attribute_identifier = _parse_head_identifier(attribute_head, "attribute")
disease_idx = _parse_optional_int(disease_target)
attribute_idx = _parse_optional_int(attribute_target)
generator = GradCAMHeatmapGenerator(model, target_layer=target_layer.strip())
result = generator.generate_attention_overlap(
tensor_input,
disease_target=disease_idx,
attribute_target=attribute_idx,
disease_head=disease_identifier,
attribute_head=attribute_identifier,
threshold=float(threshold),
)
generator.close()
disease_overlay = _overlay_heatmap(base_image, result.disease_heatmap[0])
attribute_overlay = _overlay_heatmap(base_image, result.attribute_heatmap[0])
metrics = result.metrics
html = f"""
<div style="background-color:#e8f5e9;border:1px solid #c8e6c9;border-radius:5px;padding:12px;color:#155724;">
<strong>GradCAM complete.</strong>
<ul style="margin:8px 0 0 16px;padding:0;">
<li>Dice overlap: {metrics.get('dice', 0.0):.3f}</li>
<li>IoU overlap: {metrics.get('iou', 0.0):.3f}</li>
<li>Cosine similarity: {metrics.get('cosine', 0.0):.3f}</li>
</ul>
</div>
"""
return html, disease_overlay, attribute_overlay, metrics
except Exception as exc:
error_html = f"""
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>GradCAM Error:</strong> {str(exc)}
</div>
"""
return error_html, None, None, None
def run_gradcam_mask_overlap_analysis(
model_file,
image_files,
mask_files,
target_layer: str,
head: str,
target_index: int | float | None,
threshold: float,
mask_threshold: float,
image_size: int,
color_mode: str,
batch_size: int,
):
if not target_layer or target_layer.strip() == "":
error_html = """
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>GradCAM Mask Overlap Error:</strong> Please provide a valid target layer path.
</div>
"""
return error_html, None
try:
model = _load_torch_model(model_file)
images = image_files or []
masks = mask_files or []
if len(images) != len(masks):
raise ValueError("Number of images must match number of masks.")
tensor_inputs = _preprocess_gradcam_images(images, int(image_size), color_mode)
mask_arrays = _preprocess_mask_images(masks, int(image_size))
head_id = _parse_head_identifier(head, "logits")
target_idx = _parse_optional_int(target_index)
detector = ShortcutDetector(
methods=["gradcam_mask_overlap"],
gradcam_overlap_threshold=float(threshold),
gradcam_mask_threshold=float(mask_threshold),
gradcam_overlap_batch_size=int(batch_size),
)
def _loader():
return {
"inputs": tensor_inputs,
"masks": mask_arrays,
"model": model,
"target_layer": target_layer.strip(),
"head": head_id,
"target_index": target_idx,
"batch_size": int(batch_size),
}
detector.fit_from_loaders({"gradcam_mask_overlap": _loader})
result = detector.get_results().get("gradcam_mask_overlap", {})
metrics = result.get("metrics", {})
report = result.get("report", {})
html = f"""
<div style="background-color:#e8f5e9;border:1px solid #c8e6c9;border-radius:5px;padding:12px;color:#155724;">
<strong>GradCAM mask overlap complete.</strong>
<ul style="margin:8px 0 0 16px;padding:0;">
<li>Samples: {metrics.get('n_samples', 0)}</li>
<li>Attention-in-mask (mean): {metrics.get('attention_in_mask_mean', 0.0):.3f}</li>
<li>Dice (mean): {metrics.get('dice_mean', 0.0):.3f}</li>
<li>IoU (mean): {metrics.get('iou_mean', 0.0):.3f}</li>
</ul>
</div>
"""
payload = {
"metrics": metrics,
"top_samples": report.get("top_samples", []),
"bottom_samples": report.get("bottom_samples", []),
}
return html, payload
except Exception as exc:
error_html = f"""
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>GradCAM Mask Overlap Error:</strong> {str(exc)}
</div>
"""
return error_html, None
def run_spray_analysis(
spray_input_mode: str,
heatmap_file,
model_file,
image_files,
target_layer: str,
head: str,
target_index: int | float | None,
image_size: int,
color_mode: str,
affinity: str,
cluster_selection: str,
n_clusters: int | float | None,
min_clusters: int,
max_clusters: int,
downsample_size: int | float | None,
):
try:
if spray_input_mode == "Upload Heatmaps (.npz/.npy)":
heatmaps, labels, group_labels = _load_heatmap_file(heatmap_file)
else:
if not target_layer or target_layer.strip() == "":
raise ValueError("Please provide a target layer for GradCAM heatmap generation.")
model = _load_torch_model(model_file)
images = image_files or []
tensor_inputs = _preprocess_gradcam_images(images, int(image_size), color_mode)
generator = GradCAMHeatmapGenerator(model, target_layer=target_layer.strip())
head_id = _parse_head_identifier(head, "logits")
idx = _parse_optional_int(target_index)
heatmaps = generator.generate_heatmap(
tensor_inputs,
head=head_id,
target_index=idx,
)
generator.close()
labels = None
group_labels = None
n_clusters_val = _parse_optional_int(n_clusters)
if n_clusters_val is not None and n_clusters_val <= 0:
n_clusters_val = None
downsample_val = _parse_optional_int(downsample_size)
if downsample_val is not None and downsample_val <= 0:
downsample_val = None
detector = SpRAyDetector(
affinity=affinity,
cluster_selection=cluster_selection,
n_clusters=n_clusters_val,
min_clusters=int(min_clusters),
max_clusters=int(max_clusters),
downsample_size=downsample_val,
random_state=42,
)
detector.fit(heatmaps=heatmaps, labels=labels, group_labels=group_labels)
report = detector.get_report()
clever = report.get("report", {}).get("clever_hans", {})
metrics = report.get("metrics", {})
summary_html = f"""
<div style="background-color:#e3f2fd;border:1px solid #bbdefb;border-radius:5px;padding:12px;color:#0d47a1;">
<strong>SpRAy complete.</strong>
<ul style="margin:8px 0 0 16px;padding:0;">
<li>Shortcut detected: {clever.get('shortcut_detected')}</li>
<li>Risk: {str(clever.get('risk_level', 'unknown')).title()}</li>
<li>Flags: {', '.join(clever.get('flags', [])) or 'None'}</li>
<li>Clusters: {metrics.get('n_clusters')}</li>
<li>Silhouette: {metrics.get('silhouette')}</li>
</ul>
</div>
"""
gallery = []
for cluster_id, heatmap in sorted(detector.representative_heatmaps_.items()):
gallery.append((_colorize_heatmap(heatmap), f"Cluster {cluster_id}"))
return summary_html, report.get("report", {}), gallery
except Exception as exc:
error_html = f"""
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>SpRAy Error:</strong> {str(exc)}
</div>
"""
return error_html, None, []
def _load_cav_bundle(bundle_file):
"""Load CAV concept bundle from .npz/.npy upload."""
if bundle_file is None:
raise ValueError("Please upload a CAV bundle (.npz or .npy).")
path = bundle_file.name if hasattr(bundle_file, "name") else bundle_file
ext = str(path).lower()
concept_sets = {}
random_set = None
target_activations = None
target_directional_derivatives = None
if ext.endswith(".npz"):
with np.load(path, allow_pickle=True) as data:
keys = list(data.keys())
for key in keys:
if key.startswith("concept_"):
concept_name = key[len("concept_") :].strip() or "unnamed_concept"
concept_sets[concept_name] = np.asarray(data[key], dtype=float)
elif key == "concept_sets":
maybe_dict = data[key]
if isinstance(maybe_dict, np.ndarray) and maybe_dict.dtype == object:
maybe_dict = maybe_dict.item()
if isinstance(maybe_dict, dict):
for name, arr in maybe_dict.items():
concept_sets[str(name)] = np.asarray(arr, dtype=float)
elif key == "random_set":
random_set = np.asarray(data[key], dtype=float)
elif key == "target_activations":
target_activations = np.asarray(data[key], dtype=float)
elif key == "target_directional_derivatives":
target_directional_derivatives = np.asarray(data[key], dtype=float)
elif ext.endswith(".npy"):
payload = np.load(path, allow_pickle=True)
if isinstance(payload, np.ndarray) and payload.dtype == object:
payload = payload.item()
if not isinstance(payload, dict):
raise ValueError(".npy CAV bundle must store a dict payload.")
raw_concepts = payload.get("concept_sets", {})
if not isinstance(raw_concepts, dict):
raise ValueError("CAV bundle field 'concept_sets' must be a dict.")
for name, arr in raw_concepts.items():
concept_sets[str(name)] = np.asarray(arr, dtype=float)
random_set = payload.get("random_set")
if random_set is not None:
random_set = np.asarray(random_set, dtype=float)
if payload.get("target_activations") is not None:
target_activations = np.asarray(payload["target_activations"], dtype=float)
if payload.get("target_directional_derivatives") is not None:
target_directional_derivatives = np.asarray(
payload["target_directional_derivatives"],
dtype=float,
)
else:
raise ValueError("Unsupported CAV bundle format. Please upload .npz or .npy.")
if not concept_sets:
raise ValueError(
"No concepts found. Provide keys like 'concept_<name>' or a 'concept_sets' dictionary."
)
if random_set is None:
raise ValueError("Missing 'random_set' in CAV bundle.")
return {
"concept_sets": concept_sets,
"random_set": random_set,
"target_activations": target_activations,
"target_directional_derivatives": target_directional_derivatives,
}
def run_vae_analysis(
image_files,
labels_csv,
img_size: int,
channels: int,
num_classes: int,
latent_dim: int,
epochs: int,
classifier_epochs: int,
):
"""Run VAE shortcut detection on uploaded images."""
supported_img_sizes = {32, 64, 128}
try:
if not image_files:
raise ValueError("Please upload one or more images.")
if labels_csv is None:
raise ValueError("Please upload a labels CSV with task_label column.")
path = labels_csv.name if hasattr(labels_csv, "name") else labels_csv
labels_df = pd.read_csv(path)
if "task_label" not in labels_df.columns:
raise ValueError("Labels CSV must have 'task_label' column.")
labels = np.asarray(labels_df["task_label"].values)
if isinstance(image_files, list):
n_images = len(image_files)
else:
image_files = [image_files]
n_images = 1
if len(labels) != n_images:
raise ValueError(
f"Labels CSV has {len(labels)} rows but {n_images} images. "
"Each image must have a corresponding task_label."
)
img_size = int(img_size)
if img_size not in supported_img_sizes:
raise ValueError(
f"Unsupported image size {img_size}. "
f"Choose one of: {sorted(supported_img_sizes)}."
)
channels = int(channels)
num_classes = int(num_classes)
images_list = []
for f in image_files:
p = f.name if hasattr(f, "name") else f
with Image.open(p) as img:
img = img.convert("L" if channels == 1 else "RGB")
img = img.resize((img_size, img_size))
arr = np.array(img, dtype=np.float32) / 255.0
if channels == 1:
arr = arr[np.newaxis, ...]
else:
arr = np.transpose(arr, (2, 0, 1))
images_list.append(arr)
images_np = np.stack(images_list, axis=0)
images_t = torch.from_numpy(images_np).float()
loader = {
"images": images_t,
"labels": labels.astype(np.int64),
"img_size": img_size,
"channels": channels,
"num_classes": num_classes,
}
detector = ShortcutDetector(
methods=["vae"],
vae_latent_dim=int(latent_dim),
vae_epochs=int(epochs),
vae_classifier_epochs=int(classifier_epochs),
vae_batch_size=min(16, n_images),
)
detector.fit_from_loaders({"vae": loader})
result = detector.get_results().get("vae", {})
if not result.get("success"):
raise RuntimeError(result.get("error", "VAE analysis failed"))
metrics = result.get("metrics", {})
report = result.get("report", {})
n_flagged = metrics.get("n_flagged", 0)
max_pred = metrics.get("max_predictiveness")
max_pred_str = f"{max_pred:.3f}" if max_pred is not None else "N/A"
risk_label = result.get("risk_label", "Unknown")
summary_html = f"""
<div style="background-color:#e8f5e9;border:1px solid #c8e6c9;border-radius:5px;padding:12px;color:#155724;">
<strong>VAE complete.</strong><br/>
Latent dims: {metrics.get('latent_dim', 0)} | Flagged: {n_flagged}<br/>
Max predictiveness: {max_pred_str}<br/>
Risk: {risk_label}
</div>
"""
return summary_html, {
"metrics": metrics,
"per_dimension": report.get("per_dimension", []),
"risk": risk_label,
}
except Exception as exc:
error_html = f"""
<div style="background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:5px;padding:12px;color:#721c24;">
<strong>VAE Error:</strong> {str(exc)}
</div>
"""
return error_html, None
def run_cav_analysis(
cav_bundle_file,
cav_quality_threshold: float,
cav_shortcut_threshold: float,
cav_test_size: float,
cav_min_examples: int,
):
"""Run CAV shortcut concept testing from precomputed activation bundle."""
try:
bundle = _load_cav_bundle(cav_bundle_file)
detector = ShortcutDetector(
methods=["cav"],
cav_quality_threshold=float(cav_quality_threshold),
cav_shortcut_threshold=float(cav_shortcut_threshold),
cav_test_size=float(cav_test_size),
cav_min_examples_per_set=int(cav_min_examples),
)
detector.fit_from_loaders({"cav": bundle})
result = detector.get_results().get("cav", {})
if not result.get("success"):
raise RuntimeError(result.get("error", "CAV analysis failed"))
metrics = result.get("metrics", {})
report = result.get("report", {})