gh-rgupta Claude commited on
Commit
94421ed
·
1 Parent(s): 820a2ea

Add Git LFS configuration and update test files for Mac CPU compatibility

Browse files

- Configure Git LFS to track CSV files
- Update test scripts for CPU-only inference on Mac
- Add latency measurements for model comparison
- Update result CSV files from testing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

demo/app.py CHANGED
@@ -1,6 +1,8 @@
1
  """
2
  Streamlit Demo: AI-Generated Image Detector
3
  Simple web interface for detecting AI-generated images using ARNIQA model.
 
 
4
  """
5
  import streamlit as st
6
  from PIL import Image
 
1
  """
2
  Streamlit Demo: AI-Generated Image Detector
3
  Simple web interface for detecting AI-generated images using ARNIQA model.
4
+
5
+ python3 -m streamlit run app.py --server.port=25000 --server.address=0.0.0.0
6
  """
7
  import streamlit as st
8
  from PIL import Image
functions/run_on_images_fn.py CHANGED
@@ -273,9 +273,8 @@ def run_on_images(feature_extractor, classifier, config, test_real_images_paths,
273
  # Global Variables: (feature_extractor)
274
  global feature_extractor_module
275
  feature_extractor_module = feature_extractor
276
- # Use CPU for Mac compatibility (change to "cuda" if you have NVIDIA GPU)
277
- device = "cpu"
278
- feature_extractor_module.to(device)
279
  feature_extractor_module.eval()
280
  for params in feature_extractor_module.parameters():
281
  params.requires_grad = False
@@ -287,10 +286,17 @@ def run_on_images(feature_extractor, classifier, config, test_real_images_paths,
287
  Model = Model_LightningModule(classifier, config)
288
 
289
  # PyTorch Lightning Trainer
290
- # Override accelerator and devices for Mac compatibility
291
  trainer_config = config["trainer"].copy()
292
- trainer_config["accelerator"] = "cpu" # Use "cuda" for NVIDIA GPU, "mps" for Apple Silicon GPU
293
- trainer_config["devices"] = 1 # CPU uses integer, GPU uses list like [0]
 
 
 
 
 
 
 
294
  trainer = pl.Trainer(
295
  **trainer_config,
296
  callbacks=[best_checkpoint_callback, utils.LitProgressBar()],
 
273
  # Global Variables: (feature_extractor)
274
  global feature_extractor_module
275
  feature_extractor_module = feature_extractor
276
+ # Detect device from feature extractor (it's already on the correct device)
277
+ device = next(feature_extractor_module.parameters()).device
 
278
  feature_extractor_module.eval()
279
  for params in feature_extractor_module.parameters():
280
  params.requires_grad = False
 
286
  Model = Model_LightningModule(classifier, config)
287
 
288
  # PyTorch Lightning Trainer
289
+ # Override accelerator based on detected device
290
  trainer_config = config["trainer"].copy()
291
+ if device.type == "mps":
292
+ trainer_config["accelerator"] = "mps"
293
+ trainer_config["devices"] = 1
294
+ elif device.type == "cuda":
295
+ trainer_config["accelerator"] = "cuda"
296
+ trainer_config["devices"] = [device.index] if device.index is not None else [0]
297
+ else: # cpu
298
+ trainer_config["accelerator"] = "cpu"
299
+ trainer_config["devices"] = 1
300
  trainer = pl.Trainer(
301
  **trainer_config,
302
  callbacks=[best_checkpoint_callback, utils.LitProgressBar()],
new_images_to_test_whatsapp/WhatsApp Image 2025-09-20 at 5.50.50 PM.jpeg ADDED

Git LFS Details

  • SHA256: d5889c608ca25dbd59fa6cd377447654732aa58dcbd2efa29b8517e00e9bc457
  • Pointer size: 131 Bytes
  • Size of remote file: 155 kB
new_images_to_test_whatsapp/WhatsApp Image 2025-09-21 at 11.14.39 PM.jpeg ADDED

Git LFS Details

  • SHA256: 940ded4d20cf778dc3efa95e9307c251e637b22b2331df2a41fa067104871b29
  • Pointer size: 131 Bytes
  • Size of remote file: 164 kB
test_all_models.py CHANGED
@@ -1,169 +1,256 @@
1
  """
2
- Test all available models on the same image
3
  """
4
  import os
5
  import sys
6
-
7
- # Available models - test all 5 IQA-based models
8
- models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
9
-
10
- # Test images directory
11
- test_images_dir = "new_images_to_test"
12
-
13
- # Get all images from the directory
14
- import glob
15
- image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
16
- test_images = []
17
- for ext in image_extensions:
18
- test_images.extend(glob.glob(os.path.join(test_images_dir, ext)))
19
-
20
- if not test_images:
21
- print(f"Error: No images found in {test_images_dir}/")
22
- sys.exit(1)
23
-
24
- print(f"Found {len(test_images)} image(s) in {test_images_dir}/")
25
- print("=" * 80)
26
-
27
- # Import libraries once
28
- sys.path.insert(0, '.')
29
- from yaml import safe_load
30
- from functions.loss_optimizers_metrics import *
31
- from functions.run_on_images_fn import run_on_images
32
- import functions.utils as utils
33
- import functions.networks as networks
34
- import defaults
35
- import warnings
36
- warnings.filterwarnings("ignore")
37
-
38
- all_results = {}
39
-
40
- # Test each model
41
- for model_idx, model_name in enumerate(models, 1):
42
- print(f"\n{'='*80}")
43
- print(f"[{model_idx}/{len(models)}] Testing model: {model_name.upper()}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  print("="*80)
45
 
46
- try:
47
- config_path = f"configs/{model_name}.yaml"
48
- config = safe_load(open(config_path, "r"))
49
-
50
- # Override settings
51
- config["dataset"]["dataset_type"] = "GenImage"
52
- config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
53
- config["checkpoints"]["resume_filename"] = "best_model.ckpt"
54
- config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
55
- config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
56
-
57
- # Training settings (for testing)
58
- config["train_settings"]["train"] = False
59
- config["train_loss_fn"]["name"] = "CrossEntropy"
60
- config["val_loss_fn"]["name"] = "CrossEntropy"
61
-
62
- # Model setup
63
- device = "cpu"
64
- feature_extractor = networks.get_model(model_name=model_name, device=device)
65
-
66
- # Classifier
67
- config["classifier"]["hidden_layers"] = [1024]
68
- classifier = networks.Classifier_Arch2(
69
- input_dim=config["classifier"]["input_dim"],
70
- hidden_layers=config["classifier"]["hidden_layers"]
71
- )
72
-
73
- # Preprocessing settings
74
- preprocess_settings = {
75
- "model_name": model_name,
76
- "selected_transforms_name": "test",
77
- "probability": -1,
78
- "gaussian_blur_range": None,
79
- "jpeg_compression_qfs": None,
80
- "input_image_dimensions": (224, 224),
81
- "resize": None
82
- }
83
-
84
- print(f"✓ {model_name.upper()} model loaded successfully\n")
85
-
86
- results = []
87
-
88
- # Test each image with this model
89
- for idx, test_image in enumerate(test_images, 1):
90
- image_name = os.path.basename(test_image)
91
- print(f" [{idx}/{len(test_images)}] Testing: {image_name}")
92
-
93
- # Test images
94
- test_real_images_paths = [test_image]
95
- test_fake_images_paths = []
96
-
97
- try:
98
- test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
99
- feature_extractor=feature_extractor,
100
- classifier=classifier,
101
- config=config,
102
- test_real_images_paths=test_real_images_paths,
103
- test_fake_images_paths=test_fake_images_paths,
104
- preprocess_settings=preprocess_settings,
105
- best_threshold=0.5,
106
- verbose=False
107
- )
108
-
109
- score = y_pred[0] if len(y_pred) > 0 else None
110
- prediction = "AI-Generated" if score and score > 0.5 else "Real"
111
- confidence = abs(score - 0.5) * 200 if score else 0
112
-
113
- results.append({
114
- 'image': image_name,
115
- 'score': score,
116
- 'prediction': prediction,
117
- 'confidence': confidence
118
- })
119
-
120
- print(f" ✓ Score: {score:.4f} → {prediction} ({confidence:.1f}% confidence)")
121
-
122
- except Exception as e:
123
- print(f" ✗ Error: {e}")
124
- results.append({
125
- 'image': image_name,
126
- 'score': None,
127
- 'prediction': 'Error',
128
- 'confidence': 0
129
- })
130
-
131
- all_results[model_name] = results
132
-
133
- except Exception as e:
134
- print(f"✗ Failed to load {model_name.upper()} model: {e}")
135
- all_results[model_name] = None
136
-
137
- # Final Summary
138
- print("\n" + "="*80)
139
- print("FINAL SUMMARY - ALL MODELS")
140
- print("="*80)
141
-
142
- for model_name, results in all_results.items():
143
- if results is None:
144
- print(f"\n{model_name.upper()}: Failed to load")
145
- continue
146
-
147
- print(f"\n{model_name.upper()}:")
148
- print("-"*80)
149
- print(f"{'Image':<50} {'Score':<10} {'Prediction':<15} {'Confidence':<12}")
150
- print("-"*80)
151
-
152
- for r in results:
153
- score_str = f"{r['score']:.4f}" if r['score'] is not None else "N/A"
154
- conf_str = f"{r['confidence']:.1f}%" if r['score'] is not None else "N/A"
155
- img_name = r['image'][:47] + "..." if len(r['image']) > 50 else r['image']
156
- print(f"{img_name:<50} {score_str:<10} {r['prediction']:<15} {conf_str:<12}")
157
-
158
- # Statistics
159
- valid_predictions = [r for r in results if r['score'] is not None]
160
- if valid_predictions:
161
- avg_score = sum(r['score'] for r in valid_predictions) / len(valid_predictions)
162
- ai_count = sum(1 for r in valid_predictions if r['score'] > 0.5)
163
- real_count = len(valid_predictions) - ai_count
164
- avg_confidence = sum(r['confidence'] for r in valid_predictions) / len(valid_predictions)
165
 
 
 
166
  print("-"*80)
167
- print(f"Average Score: {avg_score:.4f} | AI: {ai_count} | Real: {real_count} | Avg Confidence: {avg_confidence:.1f}%")
168
 
169
- print("\n" + "="*80)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Test all available models on the same image with latency measurements
3
  """
4
  import os
5
  import sys
6
+ import time
7
+
8
+ if __name__ == '__main__':
9
+ # Available models - test all 5 IQA-based models
10
+ models = ['contrique','hyperiqa', 'tres', 'arniqa', 'reiqa']
11
+ models = ['reiqa']
12
+ # models = ['reiqa', 'arniqa']
13
+ # models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
14
+
15
+ """
16
+ ---
17
+ Summary Table - All Models
18
+
19
+ | Model | Image 1 (11.14.39 PM) | Image 2 (5.50.50
20
+ PM) | Verdict |
21
+ |-----------|-----------------------|--------------------
22
+ ---|-----------------------------|
23
+ | CONTRIQUE | 0.7931 (AI - 58.6%) | 0.6332 (AI - 26.6%)
24
+ | Both AI-Generated |
25
+ | HYPERIQA | 0.7602 (AI - 52.0%) | 0.8179 (AI - 63.6%)
26
+ | ✓ Both AI-Generated |
27
+ | TRES | Failed | ❌ Failed
28
+ | Model incompatible with CPU |
29
+ | REIQA | 0.3500 (Real - 30.0%) | 0.2416 (Real -
30
+ 51.7%) | ✗ Both Real |
31
+ | ARNIQA | 0.7133 (AI - 42.7%) | 0.9605 (AI - 92.1%)
32
+ | Both AI-Generated |
33
+
34
+ ---
35
+ """
36
+
37
+ # Test images directory
38
+ test_images_dir = "new_images_to_test"
39
+
40
+ # Get all images from the directory
41
+ import glob
42
+ image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
43
+ test_images = []
44
+ for ext in image_extensions:
45
+ test_images.extend([os.path.abspath(p) for p in glob.glob(os.path.join(test_images_dir, ext))])
46
+
47
+ if not test_images:
48
+ print(f"Error: No images found in {test_images_dir}/")
49
+ sys.exit(1)
50
+
51
+ print(f"Found {len(test_images)} image(s) in {test_images_dir}/")
52
+ print("=" * 80)
53
+
54
+ # Import libraries once
55
+ sys.path.insert(0, '.')
56
+ from yaml import safe_load
57
+ from functions.loss_optimizers_metrics import *
58
+ from functions.run_on_images_fn import run_on_images
59
+ import functions.utils as utils
60
+ import functions.networks as networks
61
+ import defaults
62
+ import warnings
63
+ warnings.filterwarnings("ignore")
64
+
65
+ all_results = {}
66
+ latency_stats = {}
67
+
68
+ # Test each model
69
+ for model_idx, model_name in enumerate(models, 1):
70
+ print(f"\n{'='*80}")
71
+ print(f"[{model_idx}/{len(models)}] Testing model: {model_name.upper()}")
72
+ print("="*80)
73
+
74
+ # Start timing model loading
75
+ model_load_start = time.time()
76
+
77
+ try:
78
+ config_path = f"configs/{model_name}.yaml"
79
+ config = safe_load(open(config_path, "r"))
80
+
81
+ # Override settings
82
+ config["dataset"]["dataset_type"] = "GenImage"
83
+ config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
84
+ config["checkpoints"]["resume_filename"] = "best_model.ckpt"
85
+ config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
86
+ config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
87
+
88
+ # Training settings (for testing)
89
+ config["train_settings"]["train"] = False
90
+ config["train_loss_fn"]["name"] = "CrossEntropy"
91
+ config["val_loss_fn"]["name"] = "CrossEntropy"
92
+
93
+ # Model setup - use CPU (MPS has compatibility issues)
94
+ device = "cpu"
95
+ feature_extractor = networks.get_model(model_name=model_name, device=device)
96
+
97
+ # Classifier
98
+ config["classifier"]["hidden_layers"] = [1024]
99
+ classifier = networks.Classifier_Arch2(
100
+ input_dim=config["classifier"]["input_dim"],
101
+ hidden_layers=config["classifier"]["hidden_layers"]
102
+ )
103
+
104
+ # Preprocessing settings
105
+ preprocess_settings = {
106
+ "model_name": model_name,
107
+ "selected_transforms_name": "test",
108
+ "probability": -1,
109
+ "gaussian_blur_range": None,
110
+ "jpeg_compression_qfs": None,
111
+ "input_image_dimensions": (224, 224),
112
+ "resize": None
113
+ }
114
+
115
+ model_load_time = time.time() - model_load_start
116
+ print(f"✓ {model_name.upper()} model loaded successfully (Load time: {model_load_time:.3f}s)\n")
117
+
118
+ results = []
119
+ inference_times = []
120
+
121
+ # Test each image with this model
122
+ for idx, test_image in enumerate(test_images, 1):
123
+ image_name = os.path.basename(test_image)
124
+ print(f" [{idx}/{len(test_images)}] Testing: {image_name}")
125
+
126
+ # Test images
127
+ test_real_images_paths = [test_image]
128
+ test_fake_images_paths = []
129
+
130
+ try:
131
+ # Start timing inference
132
+ inference_start = time.time()
133
+
134
+ test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
135
+ feature_extractor=feature_extractor,
136
+ classifier=classifier,
137
+ config=config,
138
+ test_real_images_paths=test_real_images_paths,
139
+ test_fake_images_paths=test_fake_images_paths,
140
+ preprocess_settings=preprocess_settings,
141
+ best_threshold=0.5,
142
+ verbose=False
143
+ )
144
+
145
+ inference_time = time.time() - inference_start
146
+ inference_times.append(inference_time)
147
+
148
+ score = y_pred[0] if len(y_pred) > 0 else None
149
+ prediction = "AI-Generated" if score and score > 0.5 else "Real"
150
+ confidence = abs(score - 0.5) * 200 if score else 0
151
+
152
+ results.append({
153
+ 'image': image_name,
154
+ 'score': score,
155
+ 'prediction': prediction,
156
+ 'confidence': confidence,
157
+ 'inference_time': inference_time
158
+ })
159
+
160
+ print(f" ✓ Score: {score:.4f} → {prediction} ({confidence:.1f}% confidence) | Time: {inference_time:.3f}s")
161
+
162
+ except Exception as e:
163
+ print(f" ✗ Error: {e}")
164
+ results.append({
165
+ 'image': image_name,
166
+ 'score': None,
167
+ 'prediction': 'Error',
168
+ 'confidence': 0,
169
+ 'inference_time': None
170
+ })
171
+
172
+ all_results[model_name] = results
173
+
174
+ # Store latency statistics
175
+ if inference_times:
176
+ latency_stats[model_name] = {
177
+ 'model_load_time': model_load_time,
178
+ 'avg_inference_time': sum(inference_times) / len(inference_times),
179
+ 'min_inference_time': min(inference_times),
180
+ 'max_inference_time': max(inference_times),
181
+ 'total_inference_time': sum(inference_times),
182
+ 'num_images': len(inference_times)
183
+ }
184
+
185
+ except Exception as e:
186
+ print(f"✗ Failed to load {model_name.upper()} model: {e}")
187
+ all_results[model_name] = None
188
+
189
+ # Final Summary
190
+ print("\n" + "="*80)
191
+ print("FINAL SUMMARY - ALL MODELS")
192
  print("="*80)
193
 
194
+ for model_name, results in all_results.items():
195
+ if results is None:
196
+ print(f"\n{model_name.upper()}: Failed to load")
197
+ continue
198
+
199
+ print(f"\n{model_name.upper()}:")
200
+ print("-"*80)
201
+ print(f"{'Image':<50} {'Score':<10} {'Prediction':<15} {'Confidence':<12}")
202
+ print("-"*80)
203
+
204
+ for r in results:
205
+ score_str = f"{r['score']:.4f}" if r['score'] is not None else "N/A"
206
+ conf_str = f"{r['confidence']:.1f}%" if r['score'] is not None else "N/A"
207
+ img_name = r['image'][:47] + "..." if len(r['image']) > 50 else r['image']
208
+ print(f"{img_name:<50} {score_str:<10} {r['prediction']:<15} {conf_str:<12}")
209
+
210
+ # Statistics
211
+ valid_predictions = [r for r in results if r['score'] is not None]
212
+ if valid_predictions:
213
+ avg_score = sum(r['score'] for r in valid_predictions) / len(valid_predictions)
214
+ ai_count = sum(1 for r in valid_predictions if r['score'] > 0.5)
215
+ real_count = len(valid_predictions) - ai_count
216
+ avg_confidence = sum(r['confidence'] for r in valid_predictions) / len(valid_predictions)
217
+
218
+ print("-"*80)
219
+ print(f"Average Score: {avg_score:.4f} | AI: {ai_count} | Real: {real_count} | Avg Confidence: {avg_confidence:.1f}%")
220
+
221
+ # Latency Summary
222
+ print("\n" + "="*80)
223
+ print("LATENCY PERFORMANCE COMPARISON")
224
+ print("="*80)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
+ if latency_stats:
227
+ print(f"\n{'Model':<15} {'Load Time':<12} {'Avg Inference':<15} {'Min':<10} {'Max':<10} {'Total':<12}")
228
  print("-"*80)
 
229
 
230
+ for model_name, stats in latency_stats.items():
231
+ print(f"{model_name.upper():<15} "
232
+ f"{stats['model_load_time']:<12.3f} "
233
+ f"{stats['avg_inference_time']:<15.3f} "
234
+ f"{stats['min_inference_time']:<10.3f} "
235
+ f"{stats['max_inference_time']:<10.3f} "
236
+ f"{stats['total_inference_time']:<12.3f}")
237
+
238
+ print("\n" + "-"*80)
239
+ print("Timing units: seconds (s)")
240
+ print("Load Time: Time to load model and classifier")
241
+ print("Avg Inference: Average time per image inference")
242
+ print("Min/Max: Fastest/slowest single image inference")
243
+ print("Total: Total time for all images")
244
+
245
+ # Find fastest model
246
+ fastest_model = min(latency_stats.items(), key=lambda x: x[1]['avg_inference_time'])
247
+ slowest_model = max(latency_stats.items(), key=lambda x: x[1]['avg_inference_time'])
248
+
249
+ print("\n" + "-"*80)
250
+ print(f"⚡ Fastest Model: {fastest_model[0].upper()} ({fastest_model[1]['avg_inference_time']:.3f}s per image)")
251
+ print(f"🐌 Slowest Model: {slowest_model[0].upper()} ({slowest_model[1]['avg_inference_time']:.3f}s per image)")
252
+
253
+ speedup = slowest_model[1]['avg_inference_time'] / fastest_model[1]['avg_inference_time']
254
+ print(f"📊 Speed Difference: {speedup:.2f}x faster")
255
+
256
+ print("\n" + "="*80)
test_all_models.py.bak2 ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test all available models on the same image
3
+ """
4
+ import os
5
+ import sys
6
+
7
+ if __name__ == '__main__':
8
+ # Available models - test all 5 IQA-based models
9
+ models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
10
+
11
+ # Test images directory
12
+ test_images_dir = "new_images_to_test"
13
+
14
+ # Get all images from the directory
15
+ import glob
16
+ image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
17
+ test_images = []
18
+ for ext in image_extensions:
19
+ test_images.extend(glob.glob(os.path.join(test_images_dir, ext)))
20
+
21
+ if not test_images:
22
+ print(f"Error: No images found in {test_images_dir}/")
23
+ sys.exit(1)
24
+
25
+ print(f"Found {len(test_images)} image(s) in {test_images_dir}/")
26
+ print("=" * 80)
27
+
28
+ # Import libraries once
29
+ sys.path.insert(0, '.')
30
+ from yaml import safe_load
31
+ from functions.loss_optimizers_metrics import *
32
+ from functions.run_on_images_fn import run_on_images
33
+ import functions.utils as utils
34
+ import functions.networks as networks
35
+ import defaults
36
+ import warnings
37
+ warnings.filterwarnings("ignore")
38
+
39
+ all_results = {}
40
+
41
+ # Test each model
42
+ for model_idx, model_name in enumerate(models, 1):
43
+ print(f"\n{'='*80}")
44
+ print(f"[{model_idx}/{len(models)}] Testing model: {model_name.upper()}")
45
+ print("="*80)
46
+
47
+ try:
48
+ config_path = f"configs/{model_name}.yaml"
49
+ config = safe_load(open(config_path, "r"))
50
+
51
+ # Override settings
52
+ config["dataset"]["dataset_type"] = "GenImage"
53
+ config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
54
+ config["checkpoints"]["resume_filename"] = "best_model.ckpt"
55
+ config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
56
+ config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
57
+
58
+ # Training settings (for testing)
59
+ config["train_settings"]["train"] = False
60
+ config["train_loss_fn"]["name"] = "CrossEntropy"
61
+ config["val_loss_fn"]["name"] = "CrossEntropy"
62
+
63
+ # Model setup - use CPU (MPS has compatibility issues)
64
+ device = "cpu"
65
+ feature_extractor = networks.get_model(model_name=model_name, device=device)
66
+
67
+ # Classifier
68
+ config["classifier"]["hidden_layers"] = [1024]
69
+ classifier = networks.Classifier_Arch2(
70
+ input_dim=config["classifier"]["input_dim"],
71
+ hidden_layers=config["classifier"]["hidden_layers"]
72
+ )
73
+
74
+ # Preprocessing settings
75
+ preprocess_settings = {
76
+ "model_name": model_name,
77
+ "selected_transforms_name": "test",
78
+ "probability": -1,
79
+ "gaussian_blur_range": None,
80
+ "jpeg_compression_qfs": None,
81
+ "input_image_dimensions": (224, 224),
82
+ "resize": None
83
+ }
84
+
85
+ print(f"✓ {model_name.upper()} model loaded successfully\n")
86
+
87
+ results = []
88
+
89
+ # Test each image with this model
90
+ for idx, test_image in enumerate(test_images, 1):
91
+ image_name = os.path.basename(test_image)
92
+ print(f" [{idx}/{len(test_images)}] Testing: {image_name}")
93
+
94
+ # Test images
95
+ test_real_images_paths = [test_image]
96
+ test_fake_images_paths = []
97
+
98
+ try:
99
+ test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
100
+ feature_extractor=feature_extractor,
101
+ classifier=classifier,
102
+ config=config,
103
+ test_real_images_paths=test_real_images_paths,
104
+ test_fake_images_paths=test_fake_images_paths,
105
+ preprocess_settings=preprocess_settings,
106
+ best_threshold=0.5,
107
+ verbose=False
108
+ )
109
+
110
+ score = y_pred[0] if len(y_pred) > 0 else None
111
+ prediction = "AI-Generated" if score and score > 0.5 else "Real"
112
+ confidence = abs(score - 0.5) * 200 if score else 0
113
+
114
+ results.append({
115
+ 'image': image_name,
116
+ 'score': score,
117
+ 'prediction': prediction,
118
+ 'confidence': confidence
119
+ })
120
+
121
+ print(f" ✓ Score: {score:.4f} → {prediction} ({confidence:.1f}% confidence)")
122
+
123
+ except Exception as e:
124
+ print(f" ✗ Error: {e}")
125
+ results.append({
126
+ 'image': image_name,
127
+ 'score': None,
128
+ 'prediction': 'Error',
129
+ 'confidence': 0
130
+ })
131
+
132
+ all_results[model_name] = results
133
+
134
+ except Exception as e:
135
+ print(f"✗ Failed to load {model_name.upper()} model: {e}")
136
+ all_results[model_name] = None
137
+
138
+ # Final Summary
139
+ print("\n" + "="*80)
140
+ print("FINAL SUMMARY - ALL MODELS")
141
+ print("="*80)
142
+
143
+ for model_name, results in all_results.items():
144
+ if results is None:
145
+ print(f"\n{model_name.upper()}: Failed to load")
146
+ continue
147
+
148
+ print(f"\n{model_name.upper()}:")
149
+ print("-"*80)
150
+ print(f"{'Image':<50} {'Score':<10} {'Prediction':<15} {'Confidence':<12}")
151
+ print("-"*80)
152
+
153
+ for r in results:
154
+ score_str = f"{r['score']:.4f}" if r['score'] is not None else "N/A"
155
+ conf_str = f"{r['confidence']:.1f}%" if r['score'] is not None else "N/A"
156
+ img_name = r['image'][:47] + "..." if len(r['image']) > 50 else r['image']
157
+ print(f"{img_name:<50} {score_str:<10} {r['prediction']:<15} {conf_str:<12}")
158
+
159
+ # Statistics
160
+ valid_predictions = [r for r in results if r['score'] is not None]
161
+ if valid_predictions:
162
+ avg_score = sum(r['score'] for r in valid_predictions) / len(valid_predictions)
163
+ ai_count = sum(1 for r in valid_predictions if r['score'] > 0.5)
164
+ real_count = len(valid_predictions) - ai_count
165
+ avg_confidence = sum(r['confidence'] for r in valid_predictions) / len(valid_predictions)
166
+
167
+ print("-"*80)
168
+ print(f"Average Score: {avg_score:.4f} | AI: {ai_count} | Real: {real_count} | Avg Confidence: {avg_confidence:.1f}%")
169
+
170
+ print("\n" + "="*80)
test_all_models_original.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test all available models on the same image
3
+ """
4
+ import os
5
+ import sys
6
+
7
+ if __name__ == '__main__':
8
+ # Available models - test all 5 IQA-based models
9
+ models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
10
+
11
+ # Test images directory
12
+ test_images_dir = "new_images_to_test"
13
+
14
+ # Get all images from the directory
15
+ import glob
16
+ image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
17
+ test_images = []
18
+ for ext in image_extensions:
19
+ test_images.extend(glob.glob(os.path.join(test_images_dir, ext)))
20
+
21
+ if not test_images:
22
+ print(f"Error: No images found in {test_images_dir}/")
23
+ sys.exit(1)
24
+
25
+ print(f"Found {len(test_images)} image(s) in {test_images_dir}/")
26
+ print("=" * 80)
27
+
28
+ # Import libraries once
29
+ sys.path.insert(0, '.')
30
+ from yaml import safe_load
31
+ from functions.loss_optimizers_metrics import *
32
+ from functions.run_on_images_fn import run_on_images
33
+ import functions.utils as utils
34
+ import functions.networks as networks
35
+ import defaults
36
+ import warnings
37
+ warnings.filterwarnings("ignore")
38
+
39
+ all_results = {}
40
+
41
+ # Test each model
42
+ for model_idx, model_name in enumerate(models, 1):
43
+ print(f"\n{'='*80}")
44
+ print(f"[{model_idx}/{len(models)}] Testing model: {model_name.upper()}")
45
+ print("="*80)
46
+
47
+ try:
48
+ config_path = f"configs/{model_name}.yaml"
49
+ config = safe_load(open(config_path, "r"))
50
+
51
+ # Override settings
52
+ config["dataset"]["dataset_type"] = "GenImage"
53
+ config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
54
+ config["checkpoints"]["resume_filename"] = "best_model.ckpt"
55
+ config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
56
+ config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
57
+
58
+ # Training settings (for testing)
59
+ config["train_settings"]["train"] = False
60
+ config["train_loss_fn"]["name"] = "CrossEntropy"
61
+ config["val_loss_fn"]["name"] = "CrossEntropy"
62
+
63
+ # Model setup - use CPU (MPS has compatibility issues)
64
+ device = "cpu"
65
+ feature_extractor = networks.get_model(model_name=model_name, device=device)
66
+
67
+ # Classifier
68
+ config["classifier"]["hidden_layers"] = [1024]
69
+ classifier = networks.Classifier_Arch2(
70
+ input_dim=config["classifier"]["input_dim"],
71
+ hidden_layers=config["classifier"]["hidden_layers"]
72
+ )
73
+
74
+ # Preprocessing settings
75
+ preprocess_settings = {
76
+ "model_name": model_name,
77
+ "selected_transforms_name": "test",
78
+ "probability": -1,
79
+ "gaussian_blur_range": None,
80
+ "jpeg_compression_qfs": None,
81
+ "input_image_dimensions": (224, 224),
82
+ "resize": None
83
+ }
84
+
85
+ print(f"✓ {model_name.upper()} model loaded successfully\n")
86
+
87
+ results = []
88
+
89
+ # Test each image with this model
90
+ for idx, test_image in enumerate(test_images, 1):
91
+ image_name = os.path.basename(test_image)
92
+ print(f" [{idx}/{len(test_images)}] Testing: {image_name}")
93
+
94
+ # Test images
95
+ test_real_images_paths = [test_image]
96
+ test_fake_images_paths = []
97
+
98
+ try:
99
+ test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
100
+ feature_extractor=feature_extractor,
101
+ classifier=classifier,
102
+ config=config,
103
+ test_real_images_paths=test_real_images_paths,
104
+ test_fake_images_paths=test_fake_images_paths,
105
+ preprocess_settings=preprocess_settings,
106
+ best_threshold=0.5,
107
+ verbose=False
108
+ )
109
+
110
+ score = y_pred[0] if len(y_pred) > 0 else None
111
+ prediction = "AI-Generated" if score and score > 0.5 else "Real"
112
+ confidence = abs(score - 0.5) * 200 if score else 0
113
+
114
+ results.append({
115
+ 'image': image_name,
116
+ 'score': score,
117
+ 'prediction': prediction,
118
+ 'confidence': confidence
119
+ })
120
+
121
+ print(f" ✓ Score: {score:.4f} → {prediction} ({confidence:.1f}% confidence)")
122
+
123
+ except Exception as e:
124
+ print(f" ✗ Error: {e}")
125
+ results.append({
126
+ 'image': image_name,
127
+ 'score': None,
128
+ 'prediction': 'Error',
129
+ 'confidence': 0
130
+ })
131
+
132
+ all_results[model_name] = results
133
+
134
+ except Exception as e:
135
+ print(f"✗ Failed to load {model_name.upper()} model: {e}")
136
+ all_results[model_name] = None
137
+
138
+ # Final Summary
139
+ print("\n" + "="*80)
140
+ print("FINAL SUMMARY - ALL MODELS")
141
+ print("="*80)
142
+
143
+ for model_name, results in all_results.items():
144
+ if results is None:
145
+ print(f"\n{model_name.upper()}: Failed to load")
146
+ continue
147
+
148
+ print(f"\n{model_name.upper()}:")
149
+ print("-"*80)
150
+ print(f"{'Image':<50} {'Score':<10} {'Prediction':<15} {'Confidence':<12}")
151
+ print("-"*80)
152
+
153
+ for r in results:
154
+ score_str = f"{r['score']:.4f}" if r['score'] is not None else "N/A"
155
+ conf_str = f"{r['confidence']:.1f}%" if r['score'] is not None else "N/A"
156
+ img_name = r['image'][:47] + "..." if len(r['image']) > 50 else r['image']
157
+ print(f"{img_name:<50} {score_str:<10} {r['prediction']:<15} {conf_str:<12}")
158
+
159
+ # Statistics
160
+ valid_predictions = [r for r in results if r['score'] is not None]
161
+ if valid_predictions:
162
+ avg_score = sum(r['score'] for r in valid_predictions) / len(valid_predictions)
163
+ ai_count = sum(1 for r in valid_predictions if r['score'] > 0.5)
164
+ real_count = len(valid_predictions) - ai_count
165
+ avg_confidence = sum(r['confidence'] for r in valid_predictions) / len(valid_predictions)
166
+
167
+ print("-"*80)
168
+ print(f"Average Score: {avg_score:.4f} | AI: {ai_count} | Real: {real_count} | Avg Confidence: {avg_confidence:.1f}%")
169
+
170
+ print("\n" + "="*80)
test_mps_compatibility.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test MPS compatibility for each model individually
3
+ """
4
+ import os
5
+ import sys
6
+ import glob
7
+ import torch
8
+ from yaml import safe_load
9
+ import functions.networks as networks
10
+ from functions.run_on_images_fn import run_on_images
11
+ import warnings
12
+ warnings.filterwarnings("ignore")
13
+
14
+ if __name__ == '__main__':
15
+ # Get test images
16
+ test_images_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "new_images_to_test")
17
+ image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
18
+ test_images = []
19
+ for ext in image_extensions:
20
+ test_images.extend([os.path.abspath(p) for p in glob.glob(os.path.join(test_images_dir, ext))])
21
+
22
+ if not test_images:
23
+ print("No test images found!")
24
+ sys.exit(1)
25
+
26
+ # Test one image for each model
27
+ test_image = test_images[0]
28
+ print(f"Testing with image: {os.path.basename(test_image)}\n")
29
+
30
+ # Available models
31
+ models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
32
+
33
+ # Check MPS availability
34
+ if not torch.backends.mps.is_available():
35
+ print("MPS not available on this system!")
36
+ sys.exit(1)
37
+
38
+ print(f"MPS is available. Built: {torch.backends.mps.is_built()}\n")
39
+ print("="*80)
40
+
41
+ results = {}
42
+
43
+ for model_name in models:
44
+ print(f"\nTesting model: {model_name.upper()}")
45
+ print("-"*80)
46
+
47
+ try:
48
+ # Load config
49
+ config_path = f"configs/{model_name}.yaml"
50
+ config = safe_load(open(config_path, "r"))
51
+
52
+ # Override settings
53
+ config["dataset"]["dataset_type"] = "GenImage"
54
+ config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
55
+ config["checkpoints"]["resume_filename"] = "best_model.ckpt"
56
+ config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
57
+ config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
58
+ config["train_settings"]["train"] = False
59
+ config["train_loss_fn"]["name"] = "CrossEntropy"
60
+ config["val_loss_fn"]["name"] = "CrossEntropy"
61
+
62
+ # Try with MPS
63
+ device = "mps"
64
+ print(f" Loading model on {device}...")
65
+ feature_extractor = networks.get_model(model_name=model_name, device=device)
66
+
67
+ # Classifier
68
+ config["classifier"]["hidden_layers"] = [1024]
69
+ classifier = networks.Classifier_Arch2(
70
+ input_dim=config["classifier"]["input_dim"],
71
+ hidden_layers=config["classifier"]["hidden_layers"]
72
+ )
73
+
74
+ # Preprocessing settings
75
+ preprocess_settings = {
76
+ "model_name": model_name,
77
+ "selected_transforms_name": "test",
78
+ "probability": -1,
79
+ "gaussian_blur_range": None,
80
+ "jpeg_compression_qfs": None,
81
+ "input_image_dimensions": (224, 224),
82
+ "resize": None
83
+ }
84
+
85
+ print(f" Running inference...")
86
+
87
+ # Test on single image
88
+ test_real_images_paths = [test_image]
89
+ test_fake_images_paths = []
90
+
91
+ test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
92
+ feature_extractor=feature_extractor,
93
+ classifier=classifier,
94
+ config=config,
95
+ test_real_images_paths=test_real_images_paths,
96
+ test_fake_images_paths=test_fake_images_paths,
97
+ preprocess_settings=preprocess_settings,
98
+ best_threshold=0.5,
99
+ verbose=False
100
+ )
101
+
102
+ score = y_pred[0] if len(y_pred) > 0 else None
103
+ prediction = "AI-Generated" if score and score > 0.5 else "Real"
104
+
105
+ print(f" ✓ SUCCESS - Score: {score:.4f} → {prediction}")
106
+ results[model_name] = {"status": "SUCCESS", "score": score, "prediction": prediction, "error": None}
107
+
108
+ except Exception as e:
109
+ error_msg = str(e)
110
+ print(f" ✗ FAILED - {error_msg[:100]}")
111
+ results[model_name] = {"status": "FAILED", "score": None, "prediction": None, "error": error_msg}
112
+
113
+ # Summary
114
+ print("\n" + "="*80)
115
+ print("MPS COMPATIBILITY SUMMARY")
116
+ print("="*80)
117
+
118
+ successful = []
119
+ failed = []
120
+
121
+ for model_name, result in results.items():
122
+ status_icon = "✓" if result["status"] == "SUCCESS" else "✗"
123
+ print(f"{status_icon} {model_name.upper():<12} - {result['status']}")
124
+ if result["status"] == "SUCCESS":
125
+ successful.append(model_name)
126
+ print(f" Score: {result['score']:.4f} → {result['prediction']}")
127
+ else:
128
+ failed.append(model_name)
129
+ # Print first line of error
130
+ error_line = result['error'].split('\n')[0]
131
+ print(f" Error: {error_line[:70]}")
132
+
133
+ print("\n" + "="*80)
134
+ print(f"Summary: {len(successful)} successful, {len(failed)} failed")
135
+ print(f"MPS-compatible models: {', '.join([m.upper() for m in successful]) if successful else 'None'}")
136
+ print(f"CPU-only models: {', '.join([m.upper() for m in failed]) if failed else 'None'}")
137
+ print("="*80)
test_mps_compatibility.py.bak ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test MPS compatibility for each model individually
3
+ """
4
+ import os
5
+ import sys
6
+ import glob
7
+ import torch
8
+ from yaml import safe_load
9
+ import functions.networks as networks
10
+ from functions.run_on_images_fn import run_on_images
11
+ import warnings
12
+ warnings.filterwarnings("ignore")
13
+
14
+ if __name__ == '__main__':
15
+ # Get test images
16
+ test_images_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "new_images_to_test")
17
+ image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']
18
+ test_images = []
19
+ for ext in image_extensions:
20
+ test_images.extend([os.path.abspath(p) for p in glob.glob(os.path.join(test_images_dir, ext))])
21
+
22
+ if not test_images:
23
+ print("No test images found!")
24
+ sys.exit(1)
25
+
26
+ # Test one image for each model
27
+ test_image = test_images[0]
28
+ print(f"Testing with image: {os.path.basename(test_image)}\n")
29
+
30
+ # Available models
31
+ models = ['contrique', 'hyperiqa', 'tres', 'reiqa', 'arniqa']
32
+
33
+ # Check MPS availability
34
+ if not torch.backends.mps.is_available():
35
+ print("MPS not available on this system!")
36
+ sys.exit(1)
37
+
38
+ print(f"MPS is available. Built: {torch.backends.mps.is_built()}\n")
39
+ print("="*80)
40
+
41
+ results = {}
42
+
43
+ for model_name in models:
44
+ print(f"\nTesting model: {model_name.upper()}")
45
+ print("-"*80)
46
+
47
+ try:
48
+ # Load config
49
+ config_path = f"configs/{model_name}.yaml"
50
+ config = safe_load(open(config_path, "r"))
51
+
52
+ # Override settings
53
+ config["dataset"]["dataset_type"] = "GenImage"
54
+ config["checkpoints"]["resume_dirname"] = "GenImage/extensive/MarginContrastiveLoss_CrossEntropy"
55
+ config["checkpoints"]["resume_filename"] = "best_model.ckpt"
56
+ config["checkpoints"]["checkpoint_dirname"] = "extensive/MarginContrastiveLoss_CrossEntropy"
57
+ config["checkpoints"]["checkpoint_filename"] = "best_model.ckpt"
58
+ config["train_settings"]["train"] = False
59
+ config["train_loss_fn"]["name"] = "CrossEntropy"
60
+ config["val_loss_fn"]["name"] = "CrossEntropy"
61
+
62
+ # Try with MPS
63
+ device = "mps"
64
+ print(f" Loading model on {device}...")
65
+ feature_extractor = networks.get_model(model_name=model_name, device=device)
66
+
67
+ # Classifier
68
+ config["classifier"]["hidden_layers"] = [1024]
69
+ classifier = networks.Classifier_Arch2(
70
+ input_dim=config["classifier"]["input_dim"],
71
+ hidden_layers=config["classifier"]["hidden_layers"]
72
+ )
73
+
74
+ # Preprocessing settings
75
+ preprocess_settings = {
76
+ "model_name": model_name,
77
+ "selected_transforms_name": "test",
78
+ "probability": -1,
79
+ "gaussian_blur_range": None,
80
+ "jpeg_compression_qfs": None,
81
+ "input_image_dimensions": (224, 224),
82
+ "resize": None
83
+ }
84
+
85
+ print(f" Running inference...")
86
+
87
+ # Test on single image
88
+ test_real_images_paths = [test_image]
89
+ test_fake_images_paths = []
90
+
91
+ test_set_metrics, best_threshold, y_pred, y_true = run_on_images(
92
+ feature_extractor=feature_extractor,
93
+ classifier=classifier,
94
+ config=config,
95
+ test_real_images_paths=test_real_images_paths,
96
+ test_fake_images_paths=test_fake_images_paths,
97
+ preprocess_settings=preprocess_settings,
98
+ best_threshold=0.5,
99
+ verbose=False
100
+ )
101
+
102
+ score = y_pred[0] if len(y_pred) > 0 else None
103
+ prediction = "AI-Generated" if score and score > 0.5 else "Real"
104
+
105
+ print(f" ✓ SUCCESS - Score: {score:.4f} → {prediction}")
106
+ results[model_name] = {"status": "SUCCESS", "score": score, "prediction": prediction, "error": None}
107
+
108
+ except Exception as e:
109
+ error_msg = str(e)
110
+ print(f" ✗ FAILED - {error_msg[:100]}")
111
+ results[model_name] = {"status": "FAILED", "score": None, "prediction": None, "error": error_msg}
112
+
113
+ # Summary
114
+ print("\n" + "="*80)
115
+ print("MPS COMPATIBILITY SUMMARY")
116
+ print("="*80)
117
+
118
+ successful = []
119
+ failed = []
120
+
121
+ for model_name, result in results.items():
122
+ status_icon = "✓" if result["status"] == "SUCCESS" else "✗"
123
+ print(f"{status_icon} {model_name.upper():<12} - {result['status']}")
124
+ if result["status"] == "SUCCESS":
125
+ successful.append(model_name)
126
+ print(f" Score: {result['score']:.4f} → {result['prediction']}")
127
+ else:
128
+ failed.append(model_name)
129
+ # Print first line of error
130
+ error_line = result['error'].split('\n')[0]
131
+ print(f" Error: {error_line[:70]}")
132
+
133
+ print("\n" + "="*80)
134
+ print(f"Summary: {len(successful)} successful, {len(failed)} failed")
135
+ print(f"MPS-compatible models: {', '.join([m.upper() for m in successful]) if successful else 'None'}")
136
+ print(f"CPU-only models: {', '.join([m.upper() for m in failed]) if failed else 'None'}")
137
+ print("="*80)
test_on_images.py CHANGED
@@ -132,8 +132,8 @@ if __name__ == '__main__':
132
  f_model_name = config["dataset"]["f_model_name"]
133
 
134
 
135
- # Model - use CPU for Mac (MPS not fully supported by all models)
136
- device = "cpu" # Change to "cuda" if you have NVIDIA GPU
137
  feature_extractor = networks.get_model(model_name=config["dataset"]["model_name"], device=device)
138
 
139
 
 
132
  f_model_name = config["dataset"]["f_model_name"]
133
 
134
 
135
+ # Model - use CPU (MPS has compatibility issues with adaptive pooling)
136
+ device = "cpu" # Use "cuda" for NVIDIA GPU
137
  feature_extractor = networks.get_model(model_name=config["dataset"]["model_name"], device=device)
138
 
139