-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
2259 lines (1920 loc) · 78.5 KB
/
report.py
File metadata and controls
2259 lines (1920 loc) · 78.5 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
"""Generate detection rate report by category, generator, and detector."""
import argparse
from collections import defaultdict
import numpy as np
from scipy.stats import ttest_rel
from config import (
_connect,
normalize_model,
MAIN_MODELS,
MODEL_DISPLAY_NAMES,
_ADV_VERSIONS,
_VERSION_DISPLAY,
DETECTOR_DISPLAY_NAMES,
DATA_DIR,
)
DB_PATH = f"{DATA_DIR}/images.db"
THRESHOLD = 0.5
def _get_detectors(conn, ignore: list = None) -> list[str]:
"""Get canonical detector names from the database, optionally filtering."""
detectors = [
row[0]
for row in conn.execute(
"SELECT DISTINCT detector FROM norm_det ORDER BY detector"
).fetchall()
]
if ignore:
detectors = [d for d in detectors if d not in ignore]
return detectors
def get_dataset_stats(group: int = None):
"""Get dataset statistics: image counts by category and model."""
conn = _connect()
# Base images per category
base_query = """
SELECT category, COUNT(*) as count
FROM images
WHERE valid = 1
"""
base_params = []
if group is not None:
base_query += ' AND "group" = ?'
base_params.append(group)
base_query += " GROUP BY category ORDER BY category"
base_counts = {}
for row in conn.execute(base_query, base_params).fetchall():
base_counts[row["category"]] = row["count"]
# Generated images per category/model
gen_query = """
SELECT i.category, g.model, COUNT(*) as count
FROM generated_images g
JOIN images i ON g.base_image_id = i.id
WHERE i.valid = 1
"""
gen_params = []
if group is not None:
gen_query += ' AND i."group" = ?'
gen_params.append(group)
gen_query += " GROUP BY i.category, g.model ORDER BY i.category, g.model"
gen_counts = defaultdict(dict)
all_models = set()
for row in conn.execute(gen_query, gen_params).fetchall():
model = normalize_model(row["model"])
gen_counts[row["category"]][model] = (
gen_counts[row["category"]].get(model, 0) + row["count"]
)
all_models.add(model)
# Prompts per category
prompt_query = """
SELECT i.category, COUNT(*) as count
FROM image_prompts p
JOIN images i ON p.image_id = i.id
WHERE i.valid = 1
"""
prompt_params = []
if group is not None:
prompt_query += ' AND i."group" = ?'
prompt_params.append(group)
prompt_query += " GROUP BY i.category ORDER BY i.category"
prompt_counts = {}
for row in conn.execute(prompt_query, prompt_params).fetchall():
prompt_counts[row["category"]] = row["count"]
conn.close()
return base_counts, gen_counts, prompt_counts, sorted(all_models)
def print_dataset_stats(group: int = None, models_per_table: int = 6):
"""Print dataset statistics summary, splitting into multiple tables if needed."""
base_counts, gen_counts, prompt_counts, all_models = get_dataset_stats(group=group)
categories = sorted(set(base_counts.keys()) | set(gen_counts.keys()))
if not categories:
print("No data found.")
return
# Separate models into non-adversarial and adversarial
non_adv_models = sorted([m for m in all_models if not m.startswith("adversarial-")])
adv_models = sorted([m for m in all_models if m.startswith("adversarial-")])
model_order = non_adv_models + adv_models
# Calculate totals once
total_base = sum(base_counts.values())
total_prompts = sum(prompt_counts.values())
total_by_model = defaultdict(int)
for category in categories:
for model in model_order:
total_by_model[model] += gen_counts.get(category, {}).get(model, 0)
cat_width = max(16, max(len(c) for c in categories))
num_width = 6
# Split models into chunks
model_chunks = [
model_order[i : i + models_per_table]
for i in range(0, len(model_order), models_per_table)
]
if not model_chunks:
model_chunks = [[]]
for chunk_idx, models in enumerate(model_chunks):
# Header - include Base/Prompts only in first table
if chunk_idx == 0:
header = f"{'Category':<{cat_width}} | {'Base':>{num_width}} | {'Prompts':>{num_width}}"
else:
header = f"{'Category':<{cat_width}}"
for model in models:
header += f" | {model}"
if chunk_idx == 0:
print(f"\n{'=' * len(header)}")
print("DATASET SUMMARY (image counts)")
else:
print(f"\n{'=' * len(header)}")
print("DATASET SUMMARY (continued)")
print(f"{'=' * len(header)}")
print(header)
print("-" * len(header))
for category in categories:
if chunk_idx == 0:
base = base_counts.get(category, 0)
prompts = prompt_counts.get(category, 0)
row = f"{category:<{cat_width}} | {base:>{num_width}} | {prompts:>{num_width}}"
else:
row = f"{category:<{cat_width}}"
for model in models:
count = gen_counts.get(category, {}).get(model, 0)
model_width = len(model)
row += (
f" | {count:>{model_width}}"
if count > 0
else f" | {'-':>{model_width}}"
)
print(row)
# Totals row
print("-" * len(header))
if chunk_idx == 0:
row = f"{'TOTAL':<{cat_width}} | {total_base:>{num_width}} | {total_prompts:>{num_width}}"
else:
row = f"{'TOTAL':<{cat_width}}"
for model in models:
count = total_by_model[model]
model_width = len(model)
row += (
f" | {count:>{model_width}}"
if count > 0
else f" | {'-':>{model_width}}"
)
print(row)
def get_detection_rates(group: int = None, ignore_detectors: list = None):
"""Get detection rates grouped by category, generator, and detector."""
# Initialize the `norm det` table if it doesn't exist, fusing `truthscan` and `truthscan-noc2pa`
# detector headers.
conn = _connect()
# Get all detectors
detectors = _get_detectors(conn, ignore=ignore_detectors)
# Get generated image detection rates
# Join: detection_results -> image_refs -> generated_images -> images
generated_query = """
SELECT
i.category,
g.model,
d.detector,
COUNT(*) as total,
SUM(CASE WHEN d.ai_score >= ? THEN 1 ELSE 0 END) as detected
FROM norm_det d
JOIN generated_images g ON d.image_ref_id = g.image_ref_id
JOIN images i ON g.base_image_id = i.id
"""
gen_params = [THRESHOLD]
if group is not None:
generated_query += ' WHERE i."group" = ?'
gen_params.append(group)
generated_query += " GROUP BY i.category, g.model, d.detector"
# Get base image detection rates (false positives)
# Join: detection_results -> image_refs -> images
base_query = """
SELECT
i.category,
'base' as generator,
d.detector,
COUNT(*) as total,
SUM(CASE WHEN d.ai_score >= ? THEN 1 ELSE 0 END) as detected
FROM norm_det d
JOIN images i ON d.image_ref_id = i.image_ref_id
"""
base_params = [THRESHOLD]
if group is not None:
base_query += ' WHERE i."group" = ?'
base_params.append(group)
base_query += " GROUP BY i.category, d.detector"
# Collect all data
data = defaultdict(lambda: defaultdict(dict))
for row in conn.execute(generated_query, gen_params).fetchall():
category, model, detector, total, detected = row
model = normalize_model(model)
# detector already canonical via norm_det
existing = data[category][model].get(detector)
if existing:
total += existing["count"]
detected += existing["detected"]
rate = detected / total if total > 0 else 0
data[category][model][detector] = {
"rate": rate,
"count": total,
"detected": detected,
}
for row in conn.execute(base_query, base_params).fetchall():
category, model, detector, total, detected = row
# No need to call `normalize_model` since model is 'base' by construction.
# detector already canonical via norm_det
rate = detected / total if total > 0 else 0
data[category][model][detector] = {
"rate": rate,
"count": total,
"detected": detected,
}
conn.close()
return data, detectors
def calculate_auc(y_true, y_scores):
"""Calculate AUC using Mann-Whitney U statistic (handles ties correctly)."""
y_true = np.array(y_true)
y_scores = np.array(y_scores)
if len(y_true) == 0 or len(set(y_true)) < 2:
return None
pos_scores = y_scores[y_true == 1]
neg_scores = y_scores[y_true == 0]
n_pos = len(pos_scores)
n_neg = len(neg_scores)
if n_pos == 0 or n_neg == 0:
return None
# Count wins and ties
wins = 0
ties = 0
for p in pos_scores:
wins += np.sum(neg_scores < p)
ties += np.sum(neg_scores == p)
auc = (wins + 0.5 * ties) / (n_pos * n_neg)
return auc
def get_auc_data(group: int = None, ignore_detectors: list = None):
"""Get AUC for each model/detector combination."""
conn = _connect()
# Get all detectors
detectors = _get_detectors(conn, ignore=ignore_detectors)
# Get base image scores (label=0, should not be detected)
# Join: detection_results -> images (via image_ref_id)
base_scores = defaultdict(list)
base_query = """
SELECT d.detector, d.ai_score
FROM norm_det d
JOIN images i ON d.image_ref_id = i.image_ref_id
"""
base_params = []
if group is not None:
base_query += ' WHERE i."group" = ?'
base_params.append(group)
for row in conn.execute(base_query, base_params).fetchall():
det = row["detector"]
base_scores[det].append((0, row["ai_score"]))
# Get generated image scores by model (label=1, should be detected)
# Join: detection_results -> generated_images (via image_ref_id)
generated_scores = defaultdict(lambda: defaultdict(list))
gen_query = """
SELECT g.model, d.detector, d.ai_score
FROM norm_det d
JOIN generated_images g ON d.image_ref_id = g.image_ref_id
JOIN images i ON g.base_image_id = i.id
"""
gen_params = []
if group is not None:
gen_query += ' WHERE i."group" = ?'
gen_params.append(group)
for row in conn.execute(gen_query, gen_params).fetchall():
model = normalize_model(row["model"])
det = row["detector"]
generated_scores[model][det].append((1, row["ai_score"]))
conn.close()
# Calculate AUC for each model/detector
auc_data = defaultdict(dict)
all_models = set(generated_scores.keys())
for model in all_models:
for detector in detectors:
if detector not in generated_scores[model]:
continue
if detector not in base_scores:
continue
# Combine base (negative) and generated (positive) scores
all_labels = []
all_scores = []
for label, score in base_scores[detector]:
all_labels.append(label)
all_scores.append(score)
for label, score in generated_scores[model][detector]:
all_labels.append(label)
all_scores.append(score)
auc = calculate_auc(all_labels, all_scores)
if auc is not None:
auc_data[model][detector] = auc
return auc_data, detectors, all_models
# Map from canonical model name to the short generator name used in adversarial naming
_MODEL_TO_GENERATOR = {
"gemini-3-pro-image-preview": "gemini",
"gpt-image-1.5": "openai",
"grok-imagine-image-beta": "grok",
"qwen-image-2512": "qwen",
"seedream-v4.5-1k": "seedream",
}
def _find_adversarial_models(gen_scores, categories):
"""Find MAIN_MODELS that have adversarial data in gen_scores.
Returns list of (source_model, gen_short, display_name) tuples.
"""
result = []
for source_model in MAIN_MODELS:
gen_short = _MODEL_TO_GENERATOR.get(source_model)
if not gen_short:
continue
has_adv = any(
f"adversarial-{v}-{gen_short}" in gen_scores.get(cat, {})
for v in _ADV_VERSIONS
for cat in categories
)
if not has_adv:
continue
display = MODEL_DISPLAY_NAMES.get(source_model, source_model)
result.append((source_model, gen_short, display))
return result
def print_adversarial_auc(group: int = None, ignore_detectors: list = None):
"""Print AUC comparison: original vs adversarial (mild/strong) for each model."""
auc_data, detectors, all_models = get_auc_data(
group=group, ignore_detectors=ignore_detectors
)
# Find source models that have adversarial data
groups = [] # list of (display_name, [(variant_label, model_key), ...])
for model in MAIN_MODELS:
gen = _MODEL_TO_GENERATOR.get(model)
if not gen:
continue
adv_models = {}
for v in _ADV_VERSIONS:
adv_key = f"adversarial-{v}-{gen}"
if adv_key in auc_data:
adv_models[v] = adv_key
if not adv_models:
continue
display = MODEL_DISPLAY_NAMES.get(model, model)
variants = [(f"{display} (base)", model)]
for v in _ADV_VERSIONS:
if v in adv_models:
variants.append((f"{display} ({_VERSION_DISPLAY[v]})", adv_models[v]))
groups.append((display, variants))
if not groups:
print("\nNo adversarial AUC data available.")
return
# Print table
label_width = 24
det_width = 12
header = f"{'Model':<{label_width}}"
for det in detectors:
det_display = DETECTOR_DISPLAY_NAMES.get(det, det)
header += f" | {det_display:^{det_width}}"
header += f" | {'Avg':^{det_width}}"
separator = "-" * len(header)
print(f"\n{'=' * len(header)}")
print("ADVERSARIAL AUC COMPARISON (base vs mild/strong)")
print(f"{'=' * len(header)}")
print(header)
print(separator)
for display, variants in groups:
for label, model_key in variants:
row = f"{label:<{label_width}}"
aucs = []
for det in detectors:
auc = auc_data.get(model_key, {}).get(det)
if auc is not None:
row += f" | {auc:^{det_width}.3f}"
aucs.append(auc)
else:
row += f" | {'--':^{det_width}}"
# Average column
if aucs:
avg = sum(aucs) / len(aucs)
row += f" | {avg:^{det_width}.3f}"
else:
row += f" | {'--':^{det_width}}"
print(row)
print(separator)
print("\n* AUC = 1.0 means perfect separation; 0.5 = random guessing")
print("* Lower AUC on adversarial variants = successful evasion")
def plot_aggregate_roc(
output_path: str = "tmp/aggregate_roc.png",
group: int = None,
ignore_detectors: list = None,
):
"""Plot ROC curves using aggregate detector scores (avg, min, max).
For each image, computes the average, minimum, and maximum detector score
across all detectors. Plots base/mild/strong ROC curves for Grok using each
aggregate, one subplot per aggregate function.
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not installed. Install with: pip install matplotlib")
return
conn = _connect()
detectors = _get_detectors(conn, ignore=ignore_detectors)
det_set = set(detectors)
# Base image scores: image_ref_id -> {detector: score}
base_by_image = defaultdict(dict)
base_query = """
SELECT i.image_ref_id, d.detector, d.ai_score
FROM norm_det d
JOIN images i ON d.image_ref_id = i.image_ref_id
"""
base_params = []
if group is not None:
base_query += ' WHERE i."group" = ?'
base_params.append(group)
for row in conn.execute(base_query, base_params).fetchall():
det = row["detector"]
if det not in det_set:
continue
base_by_image[row["image_ref_id"]][det] = row["ai_score"]
# Generated image scores: model -> image_ref_id -> {detector: score}
gen_by_image = defaultdict(lambda: defaultdict(dict))
gen_query = """
SELECT g.model, g.image_ref_id, d.detector, d.ai_score
FROM norm_det d
JOIN generated_images g ON d.image_ref_id = g.image_ref_id
JOIN images i ON g.base_image_id = i.id
"""
gen_params = []
if group is not None:
gen_query += ' WHERE i."group" = ?'
gen_params.append(group)
for row in conn.execute(gen_query, gen_params).fetchall():
model = normalize_model(row["model"])
det = row["detector"]
if det not in det_set:
continue
gen_by_image[model][row["image_ref_id"]][det] = row["ai_score"]
conn.close()
agg_funcs = [
("Average", np.mean),
("Minimum", np.min),
("Maximum", np.max),
]
# Compute per-image aggregate scores for base images
# Only include images that have scores from all detectors
n_det = len(detectors)
base_agg = {} # agg_name -> array of scores
for agg_name, agg_fn in agg_funcs:
scores = []
for img_id, det_scores in base_by_image.items():
if len(det_scores) >= n_det:
scores.append(agg_fn(list(det_scores.values())))
base_agg[agg_name] = np.array(scores)
# Grok variants: base, mild, strong
source_model = "grok-imagine-image-beta"
gen_short = "grok"
variant_keys = [("Base", source_model)]
for v in _ADV_VERSIONS:
variant_keys.append((_VERSION_DISPLAY[v], f"adversarial-{v}-{gen_short}"))
# Compute per-image aggregate scores for each variant
gen_agg = {} # (variant_label, agg_name) -> array of scores
for variant_label, model_key in variant_keys:
if model_key not in gen_by_image:
continue
for agg_name, agg_fn in agg_funcs:
scores = []
for _, det_scores in gen_by_image[model_key].items():
if len(det_scores) >= n_det:
scores.append(agg_fn(list(det_scores.values())))
gen_agg[(variant_label, agg_name)] = np.array(scores)
# Plot: one subplot per aggregate function
variant_colors = {"Base": "#1f77b4", "Mild": "#2ca02c", "Strong": "#ff7f0e"}
n_cols = len(agg_funcs)
with plt.rc_context(_PLOT_RC):
fig, axes = plt.subplots(1, n_cols, figsize=(5.5 * n_cols, 5), squeeze=False)
for col_idx, (agg_name, _) in enumerate(agg_funcs):
ax = axes[0][col_idx]
ax.set_title(f"{agg_name} Detector Score", fontsize=12, fontweight="bold")
ax.plot([0, 1], [0, 1], "k--", alpha=0.3)
base = base_agg[agg_name]
for variant_label, model_key in variant_keys:
key = (variant_label, agg_name)
if key not in gen_agg or len(gen_agg[key]) == 0:
continue
gen = gen_agg[key]
thresholds = np.unique(
np.concatenate([[-1e-9], base, gen, [1.0 + 1e-9]])
)
tprs = []
fprs = []
for thresh in thresholds:
tp = np.sum(gen >= thresh)
fn = np.sum(gen < thresh)
fp = np.sum(base >= thresh)
tn = np.sum(base < thresh)
tprs.append(tp / (tp + fn) if (tp + fn) > 0 else 0)
fprs.append(fp / (fp + tn) if (fp + tn) > 0 else 0)
all_scores = np.concatenate([base, gen])
all_labels = np.concatenate([np.zeros(len(base)), np.ones(len(gen))])
auc = calculate_auc(all_labels.tolist(), all_scores.tolist())
label = f"{variant_label} (AUC={auc:.3f})" if auc else variant_label
color = variant_colors.get(variant_label, "gray")
ax.plot(fprs, tprs, color=color, label=label, linewidth=2)
ax.legend(loc="lower right", fontsize=10)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_xlabel("False Positive Rate", fontsize=10)
ax.set_ylabel("True Positive Rate", fontsize=10)
ax.grid(True, alpha=0.3)
fig.suptitle(
"Grok ROC Curves: Aggregate Detector Scores",
fontsize=14,
fontweight="bold",
)
fig.tight_layout()
fig.savefig(output_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Aggregate ROC curves saved to {output_path}")
def get_adversarial_comparison(
group: int = None, by_category: bool = False, ignore_detectors: list = None
):
"""Get adversarial vs original comparison data by generator+model.
Args:
group: Filter by group
by_category: If True, also return per-category breakdowns
ignore_detectors: Detectors to exclude
Returns:
Tuple of (comparisons, detectors) or (comparisons, category_comparisons, detectors)
"""
conn = _connect()
# Get all detectors
detectors = _get_detectors(conn, ignore=ignore_detectors)
# Query to get detection rates by generator+model (overall)
query = """
SELECT
g.generator,
g.model,
d.detector,
COUNT(*) as total,
SUM(CASE WHEN d.ai_score >= ? THEN 1 ELSE 0 END) as detected
FROM norm_det d
JOIN generated_images g ON d.image_ref_id = g.image_ref_id
JOIN images i ON g.base_image_id = i.id
"""
params = [THRESHOLD]
if group is not None:
query += ' WHERE i."group" = ?'
params.append(group)
query += " GROUP BY g.generator, g.model, d.detector"
# Collect data keyed by (generator, model)
data = defaultdict(lambda: defaultdict(dict))
for row in conn.execute(query, params).fetchall():
generator, model, detector, total, detected = row
model = normalize_model(model)
# detector already canonical via norm_det
existing = data[(generator, model)].get(detector)
if existing:
total += existing["count"]
detected += existing["detected"]
rate = detected / total if total > 0 else 0
data[(generator, model)][detector] = {
"rate": rate,
"count": total,
"detected": detected,
}
# If by_category, also query per-category data
category_data = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
if by_category:
cat_query = """
SELECT
i.category,
g.generator,
g.model,
d.detector,
COUNT(*) as total,
SUM(CASE WHEN d.ai_score >= ? THEN 1 ELSE 0 END) as detected
FROM norm_det d
JOIN generated_images g ON d.image_ref_id = g.image_ref_id
JOIN images i ON g.base_image_id = i.id
"""
cat_params = [THRESHOLD]
if group is not None:
cat_query += ' WHERE i."group" = ?'
cat_params.append(group)
cat_query += " GROUP BY i.category, g.generator, g.model, d.detector"
for row in conn.execute(cat_query, cat_params).fetchall():
category, generator, model, detector, total, detected = row
model = normalize_model(model)
# detector already canonical via norm_det
existing = category_data[category][(generator, model)].get(detector)
if existing:
total += existing["count"]
detected += existing["detected"]
rate = detected / total if total > 0 else 0
category_data[category][(generator, model)][detector] = {
"rate": rate,
"count": total,
"detected": detected,
}
conn.close()
def build_comparisons(data_dict):
"""Build comparison list from data dictionary."""
comparisons = []
for (generator, model), det_data in data_dict.items():
if generator == "adversarial" and model.startswith("adversarial-"):
source_gen = model.replace("adversarial-", "", 1)
# Find the source model in data
source_entry = None
for (gen, mod), sdata in data_dict.items():
if gen == source_gen:
source_entry = (gen, mod, sdata)
break
if source_entry:
comparisons.append(
{
"source_generator": source_entry[0],
"source_model": source_entry[1],
"source_data": source_entry[2],
"adversarial_model": model,
"adversarial_data": det_data,
}
)
return comparisons
comparisons = build_comparisons(data)
if by_category:
cat_comparisons = {}
for category, cat_data_dict in category_data.items():
cat_comparisons[category] = build_comparisons(cat_data_dict)
return comparisons, cat_comparisons, detectors
return comparisons, detectors
def _print_comparison_rows(comparisons, detectors, model_width=26, det_width=24):
"""Helper to print comparison rows (no header)."""
for comp in sorted(comparisons, key=lambda x: x["source_generator"]):
label = comp["source_generator"]
row = f"{label:<{model_width}}"
for det in detectors:
orig_data = comp["source_data"].get(det)
adv_data = comp["adversarial_data"].get(det)
if orig_data and adv_data:
orig_rate = orig_data["rate"]
adv_rate = adv_data["rate"]
delta = adv_rate - orig_rate
cell = f"{orig_rate:>5.1%} → {adv_rate:>5.1%} ({delta:>+5.1%})"
row += f" | {cell:^{det_width}}"
elif orig_data:
cell = f"{orig_data['rate']:>5.1%} → {'--':>5}"
row += f" | {cell:^{det_width}}"
elif adv_data:
cell = f"{'--':>5} → {adv_data['rate']:>5.1%}"
row += f" | {cell:^{det_width}}"
else:
row += f" | {'--':^{det_width}}"
print(row)
def print_adversarial_comparison(group: int = None, ignore_detectors: list = None):
"""Print adversarial vs original comparison."""
comparisons, cat_comparisons, detectors = get_adversarial_comparison(
group=group, by_category=True, ignore_detectors=ignore_detectors
)
if not comparisons:
print("\nNo adversarial comparisons available.")
return
model_width = 26
det_width = 24
# Build header
header = f"{'Category/Source':<{model_width}}"
for det in detectors:
header += f" | {det:^{det_width}}"
separator = "-" * len(header)
# Print section header
print(f"\n{'=' * len(header)}")
print("ADVERSARIAL COMPARISON (Original → Adversarial)")
print(f"{'=' * len(header)}")
print(header)
print(separator)
# Print per-category comparisons compactly
first_category = True
for category in sorted(cat_comparisons.keys()):
cat_comps = cat_comparisons[category]
if not cat_comps:
continue
# Add blank line between categories (but not before first)
if not first_category:
print()
first_category = False
# Category label row
print(f"{category.upper():<{model_width}}" + " |" * len(detectors))
_print_comparison_rows(cat_comps, detectors, model_width, det_width)
# Print overall
print()
print(separator)
print(f"{'OVERALL':<{model_width}}" + " |" * len(detectors))
_print_comparison_rows(comparisons, detectors, model_width, det_width)
print("\n* Negative delta = adversarial is LESS detected (evasion success)")
print("* Positive delta = adversarial is MORE detected")
def print_report(group: int = None, ignore_detectors: list = None):
"""Print formatted detection rate report."""
data, detectors = get_detection_rates(
group=group, ignore_detectors=ignore_detectors
)
# Get all models from data and define display order
all_models = set()
for category in data:
all_models.update(data[category].keys())
# Define display order: base first, then non-adversarial sorted, then adversarial sorted
non_adv_models = sorted(
[m for m in all_models if m != "base" and not m.startswith("adversarial-")]
)
adv_models = sorted([m for m in all_models if m.startswith("adversarial-")])
model_order = ["base"] + non_adv_models + adv_models
categories = sorted(data.keys())
# Calculate column widths
cat_width = max(24, max((len(c) for c in categories), default=12))
det_width = 18
# Print header template
header = f"{'Category':<{cat_width}}"
for det in detectors:
header += f" | {det:^{det_width}}"
separator = "-" * len(header)
# Track totals
overall_totals = defaultdict(lambda: {"detected": 0, "count": 0})
# Reorganize data by model -> category
data_by_model = defaultdict(lambda: defaultdict(dict))
for category in data:
for model in data[category]:
for det in data[category][model]:
data_by_model[model][category][det] = data[category][model][det]
for model in model_order:
if model not in data_by_model:
continue
print(f"\n{'=' * len(header)}")
print(f"MODEL: {model}")
print(f"{'=' * len(header)}")
print(header)
print(separator)
model_totals = defaultdict(lambda: {"detected": 0, "count": 0})
for category in categories:
if category not in data_by_model[model]:
continue
row = f"{category:<{cat_width}}"
for det in detectors:
if det in data_by_model[model][category]:
d = data_by_model[model][category][det]
rate = d["rate"]
count = d["count"]
detected = d["detected"]
row += f" | {rate:>6.1%} ({detected:>4}/{count:<4})"
# Add to totals
model_totals[det]["detected"] += detected
model_totals[det]["count"] += count
overall_totals[det]["detected"] += detected
overall_totals[det]["count"] += count
else:
row += f" | {'--':^18}"
print(row)
# Model totals
print(separator)
row = f"{'TOTAL':<{cat_width}}"
for det in detectors:
if model_totals[det]["count"] > 0:
rate = model_totals[det]["detected"] / model_totals[det]["count"]
count = model_totals[det]["count"]
detected = model_totals[det]["detected"]
row += f" | {rate:>6.1%} ({detected:>4}/{count:<4})"
else:
row += f" | {'--':^18}"
print(row)
# Add base (FPR) reference row for non-base models
if model != "base" and "base" in data_by_model:
base_totals = defaultdict(lambda: {"detected": 0, "count": 0})
for category in categories:
if category not in data_by_model["base"]:
continue
for det in detectors:
if det in data_by_model["base"][category]:
d = data_by_model["base"][category][det]
base_totals[det]["detected"] += d["detected"]
base_totals[det]["count"] += d["count"]
row = f"{'base (FPR)':<{cat_width}}"
for det in detectors:
if base_totals[det]["count"] > 0:
rate = base_totals[det]["detected"] / base_totals[det]["count"]
count = base_totals[det]["count"]
detected = base_totals[det]["detected"]
row += f" | {rate:>6.1%} ({detected:>4}/{count:<4})"
else:
row += f" | {'--':^18}"
print(row)
# Overall totals
model_width = max(24, max((len(m) for m in all_models), default=12))
totals_header = f"{'Model':<{model_width}}"
for det in detectors:
totals_header += f" | {det:^{det_width}}"
# Add avg/max columns
totals_header += f" | {'Avg':^6} | {'Max':^6}"
totals_separator = "-" * len(totals_header)
print(f"\n{'=' * len(totals_header)}")
print("OVERALL TOTALS")
print(f"{'=' * len(totals_header)}")
print(totals_header)
print(totals_separator)
# Calculate overall by model
overall_by_model = defaultdict(
lambda: defaultdict(lambda: {"detected": 0, "count": 0})
)
for category in categories:
for model in data[category]:
for det in data[category][model]:
d = data[category][model][det]
overall_by_model[model][det]["detected"] += d["detected"]
overall_by_model[model][det]["count"] += d["count"]
# Track totals separately
non_adv_totals = defaultdict(lambda: {"detected": 0, "count": 0})
adv_totals = defaultdict(lambda: {"detected": 0, "count": 0})
# Print non-adversarial models (base + non-adv)
for model in ["base"] + non_adv_models:
if model not in overall_by_model:
continue
row = f"{model:<{model_width}}"
model_rates = []
for det in detectors:
if (
det in overall_by_model[model]
and overall_by_model[model][det]["count"] > 0
):
d = overall_by_model[model][det]
rate = d["detected"] / d["count"]
count = d["count"]
detected = d["detected"]
row += f" | {rate:>6.1%} ({detected:>4}/{count:<4})"
model_rates.append(rate)
non_adv_totals[det]["detected"] += detected
non_adv_totals[det]["count"] += count
else:
row += f" | {'--':^18}"
# Add avg/max for this model
if model_rates:
avg_rate = sum(model_rates) / len(model_rates)