karthikeya1212 commited on
Commit
1150a03
Β·
verified Β·
1 Parent(s): c2fa6a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -112
app.py CHANGED
@@ -5,149 +5,86 @@ import torch
5
  import torch.nn.functional as F
6
 
7
  print("\n" + "="*80)
8
- print("πŸ† SSP-AI-GENERATED-IMAGE DETECTOR - 2025 STATE-OF-THE-ART")
9
  print("="*80)
10
- print("\nBased on SSP 2025 Benchmark")
11
- print("βœ“ High precision on latest AI generators (Midjourney v6+, DALL-E 3, Stable Diffusion)")
12
- print("βœ“ Trained on massive datasets with real + AI images")
13
  print("="*80 + "\n")
14
 
15
- # NEW MODEL CONFIG
16
- MODELS_CONFIG = [
17
- {
18
- "name": "bcmi/SSP-AI-Generated-Image-Detection",
19
- "weight": 1.0,
20
- "type": "SSP-AI Detection",
21
- "proven_accuracy": "SOTA (claimed >90% on modern generators)",
22
- "best_for": "Midjourney v6+, DALL-E 3, Stable Diffusion, GANs, and Hybrid generators"
23
- },
24
- ]
25
 
26
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
  print(f"πŸ–₯️ Device: {str(device).upper()}\n")
28
 
29
- models_list = []
30
- processors_list = []
31
- model_metadata = []
32
- loaded_count = 0
33
-
34
- # Load models
35
- for i, config in enumerate(MODELS_CONFIG):
36
- model_name = config["name"]
37
- try:
38
- print(f"[{i+1}/{len(MODELS_CONFIG)}] {model_name}")
39
- print(f" β€’ Type: {config['type']}")
40
- print(f" β€’ Weight: {int(config['weight']*100)}%")
41
- print(f" β€’ Accuracy: {config['proven_accuracy']}")
42
- print(f" β€’ Best for: {config['best_for']}\n")
43
-
44
- processor = AutoImageProcessor.from_pretrained(model_name)
45
- model = AutoModelForImageClassification.from_pretrained(model_name).to(device)
46
- model.eval()
47
-
48
- models_list.append(model)
49
- processors_list.append(processor)
50
- model_metadata.append(config)
51
- loaded_count += 1
52
-
53
- except Exception as e:
54
- print(f" ⚠️ Warning: Failed to load - {str(e)[:50]}\n")
55
-
56
- if loaded_count == 0:
57
- raise RuntimeError("❌ Failed to load SSP-AI model. Check Hugging Face access and model name.")
58
-
59
- print("="*80)
60
- print(f"βœ… Successfully loaded {loaded_count} model(s)")
61
- print("="*80 + "\n")
62
-
63
 
64
  def predict(image):
65
  if image is None:
66
  return "❌ No image uploaded", 0.0, "Upload an image to analyze"
67
-
68
  try:
69
  if image.mode != 'RGB':
70
  image = image.convert('RGB')
71
-
72
- all_scores = []
73
- model_results = []
74
-
75
- # Run models
76
- for idx, (processor, model) in enumerate(zip(processors_list, models_list)):
77
- inputs = processor(images=image, return_tensors="pt").to(device)
78
- with torch.no_grad():
79
- outputs = model(**inputs)
80
- logits = outputs.logits
81
- probs = F.softmax(logits, dim=1)[0].cpu().numpy()
82
-
83
- real_prob = float(probs[0])
84
- ai_prob = float(probs[1])
85
- all_scores.append(ai_prob)
86
-
87
- pred = "πŸ€– AI-Generated" if ai_prob > real_prob else "βœ“ Real Photo"
88
- conf = max(ai_prob, real_prob)
89
- meta = model_metadata[idx]
90
-
91
- model_results.append({
92
- 'name': meta["name"].split('/')[-1],
93
- 'type': meta['type'],
94
- 'weight': meta['weight'],
95
- 'prediction': pred,
96
- 'ai_score': ai_prob,
97
- 'real_score': real_prob,
98
- 'confidence': conf,
99
- 'accuracy': meta['proven_accuracy']
100
- })
101
-
102
- # Weighted score
103
- weights = [m['weight'] for m in model_metadata[:len(all_scores)]]
104
- total_weight = sum(weights)
105
- normalized_weights = [w/total_weight for w in weights]
106
- weighted_ai_score = sum(s * w for s, w in zip(all_scores, normalized_weights))
107
-
108
  threshold = 0.50
109
  is_ai = weighted_ai_score > threshold
110
  final_pred = "🚨 AI-GENERATED" if is_ai else "βœ… REAL PHOTO"
111
  confidence = max(weighted_ai_score, 1 - weighted_ai_score)
112
-
113
- # Individual votes
114
- ai_votes = sum(1 for r in model_results if "AI" in r['prediction'])
115
- total_votes = len(model_results)
116
-
117
  # Build report
118
  report = f"""
119
  ╔════════════════════════════════════════════════════════════════════════╗
120
- β•‘ πŸ† SSP-AI-Generated-Image Detection Report β•‘
121
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
122
 
123
  🎯 PREDICTION: {final_pred}
124
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
125
  Weighted AI Probability: {weighted_ai_score:.4f}
126
  Detection Confidence: {confidence:.4f}
127
- Ensemble Consensus: {ai_votes}/{total_votes} models vote AI-Generated
128
-
129
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
130
- πŸ“Š INDIVIDUAL MODEL ANALYSIS:
131
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  """
133
-
134
- for i, result in enumerate(model_results, 1):
135
- weight_pct = int(result['weight'] * 100)
136
- report += f"""
137
- Model {i}: {result['name']} ({result['type']})
138
- β”œβ”€ Ensemble Weight: {weight_pct}%
139
- β”œβ”€ Vote: {result['prediction']}
140
- β”œβ”€ AI Score: {result['ai_score']:.4f} | Real Score: {result['real_score']:.4f}
141
- β”œβ”€ Model Confidence: {result['confidence']:.4f}
142
- └─ Accuracy: {result['accuracy']}
143
- """
144
-
145
  return final_pred, round(weighted_ai_score, 4), report
146
-
147
  except Exception as e:
148
  return f"❌ Error: {str(e)}", 0.0, f"Processing failed: {str(e)}"
149
 
150
-
151
  # Gradio Interface
152
  demo = gr.Interface(
153
  fn=predict,
@@ -155,10 +92,10 @@ demo = gr.Interface(
155
  outputs=[
156
  gr.Textbox(label="🎯 Detection Result"),
157
  gr.Number(label="πŸ“Š AI Score (0.0-1.0)"),
158
- gr.Textbox(label="πŸ“‹ SSP-AI Analysis", lines=30)
159
  ],
160
- title="πŸ† SSP-AI-Generated-Image Detector 2025",
161
- description="High-precision AI image detector for latest generators (Midjourney v6+, DALL-E 3, Stable Diffusion, GANs)."
162
  )
163
 
164
  if __name__ == "__main__":
 
5
  import torch.nn.functional as F
6
 
7
  print("\n" + "="*80)
8
+ print("πŸ” BEST FREE AI IMAGE DETECTOR 2025 - ATEEQQ MODEL ONLY")
9
  print("="*80)
10
+ print("\nBased on Ateeqq 2025 benchmarks:")
11
+ print("βœ“ Diffusion detection (Midjourney, DALL-E, Stable Diffusion): 88-94% accuracy")
12
+ print("βœ“ CNN + Semantic Analysis approach")
13
  print("="*80 + "\n")
14
 
15
+ # Use only Ateeqq model
16
+ MODEL_NAME = "Ateeqq/ai-vs-human-image-detector"
17
+ MODEL_WEIGHT = 1.0 # 100% weight
 
 
 
 
 
 
 
18
 
19
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
  print(f"πŸ–₯️ Device: {str(device).upper()}\n")
21
 
22
+ # Load Ateeqq model
23
+ try:
24
+ processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
25
+ model = AutoModelForImageClassification.from_pretrained(MODEL_NAME).to(device)
26
+ model.eval()
27
+ print(f"βœ… Successfully loaded model: {MODEL_NAME}")
28
+ except Exception as e:
29
+ raise RuntimeError(f"❌ Failed to load model {MODEL_NAME}. Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  def predict(image):
32
  if image is None:
33
  return "❌ No image uploaded", 0.0, "Upload an image to analyze"
34
+
35
  try:
36
  if image.mode != 'RGB':
37
  image = image.convert('RGB')
38
+
39
+ inputs = processor(images=image, return_tensors="pt").to(device)
40
+ with torch.no_grad():
41
+ outputs = model(**inputs)
42
+ logits = outputs.logits
43
+ probs = F.softmax(logits, dim=1)[0].cpu().numpy()
44
+
45
+ real_prob = float(probs[0])
46
+ ai_prob = float(probs[1])
47
+
48
+ weighted_ai_score = ai_prob * MODEL_WEIGHT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  threshold = 0.50
50
  is_ai = weighted_ai_score > threshold
51
  final_pred = "🚨 AI-GENERATED" if is_ai else "βœ… REAL PHOTO"
52
  confidence = max(weighted_ai_score, 1 - weighted_ai_score)
53
+
 
 
 
 
54
  # Build report
55
  report = f"""
56
  ╔════════════════════════════════════════════════════════════════════════╗
57
+ β•‘ πŸ”¬ AI IMAGE DETECTION ANALYSIS - ATEEQQ MODEL ONLY β•‘
58
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
59
 
60
  🎯 PREDICTION: {final_pred}
61
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
62
  Weighted AI Probability: {weighted_ai_score:.4f}
63
  Detection Confidence: {confidence:.4f}
 
 
64
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
65
+ πŸ“Š MODEL ANALYSIS:
66
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
67
+ Model: Ateeqq/ai-vs-human-image-detector
68
+ β”œβ”€ Detection Type: SigLIP + Semantic Analysis
69
+ β”œβ”€ Vote: {"πŸ€– AI-Generated" if ai_prob > real_prob else "βœ“ Real Photo"}
70
+ β”œβ”€ AI Score: {ai_prob:.4f} | Real Score: {real_prob:.4f}
71
+ β”œβ”€ Confidence: {confidence:.4f}
72
+ β”œβ”€ Proven Accuracy: 88-94% on diffusion models
73
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
74
+ βœ… WHAT IT DETECTS:
75
+ βœ“ DALL-E 3, Midjourney v6+, Stable Diffusion
76
+ βœ“ Flux, GANs, Hybrid AI generators
77
+ βœ“ Post-processed AI images
78
+ ⚠️ LIMITATIONS:
79
+ βœ— May struggle with heavily edited/compressed images
80
+ βœ— Hybrid real+AI images are challenging
81
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
82
  """
 
 
 
 
 
 
 
 
 
 
 
 
83
  return final_pred, round(weighted_ai_score, 4), report
84
+
85
  except Exception as e:
86
  return f"❌ Error: {str(e)}", 0.0, f"Processing failed: {str(e)}"
87
 
 
88
  # Gradio Interface
89
  demo = gr.Interface(
90
  fn=predict,
 
92
  outputs=[
93
  gr.Textbox(label="🎯 Detection Result"),
94
  gr.Number(label="πŸ“Š AI Score (0.0-1.0)"),
95
+ gr.Textbox(label="πŸ“‹ Research-Based Analysis", lines=25)
96
  ],
97
+ title="πŸ” Advanced AI Image Detector 2025 - Ateeqq Only",
98
+ description="Detection using the proven Ateeqq model (88-94% accuracy on modern AI generators)."
99
  )
100
 
101
  if __name__ == "__main__":