thrimurthi2025 commited on
Commit
cc95494
·
verified ·
1 Parent(s): b8e54d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -83
app.py CHANGED
@@ -3,95 +3,112 @@ from transformers import pipeline
3
  from PIL import Image
4
  import traceback
5
 
6
- # Correct model names
7
- MODELS = {
8
- "umm-maybe": "umm-maybe/AI-image-detector",
9
- "dima806": "dima806/ai_vs_human_generated_image_detection",
10
- "ateeqq": "Ateeqq/ai-vs-human-image-detector"
11
- }
12
-
13
- # Equal weights
14
- WEIGHTS = {
15
- "umm-maybe": 1,
16
- "dima806": 1,
17
- "ateeqq": 1
18
- }
19
-
20
- # Load pipelines
21
- pipes = {}
22
- for key, model_id in MODELS.items():
23
  try:
24
- pipes[key] = pipeline("image-classification", model=model_id)
25
- print(f"✅ Loaded {model_id}")
26
  except Exception as e:
27
- print(f"⚠️ Failed to load {model_id}: {e}")
28
 
29
  def predict_image(image: Image.Image):
30
  try:
31
- scores = {}
32
  results = []
33
-
34
- for key, pipe in pipes.items():
35
- outputs = pipe(image)
36
- ai_score = None
37
-
38
- for o in outputs:
39
- label = o['label'].lower()
40
- score = o['score']
41
-
42
- if 'ai' in label or 'artificial' in label or 'fake' in label:
43
- ai_score = score
44
- break
45
- elif 'human' in label or 'real' in label:
46
- ai_score = 1 - score
47
- break
48
-
49
- if ai_score is None:
50
- ai_score = 0.5
51
-
52
- scores[key] = ai_score
53
- results.append({
54
- "model": MODELS[key],
55
- "ai_score": round(ai_score, 3)
56
- })
57
-
58
- # Weighted average
59
- total_weight = sum(WEIGHTS.values())
60
- final_score = sum(scores[k] * WEIGHTS[k] for k in scores) / total_weight
61
- final_score = max(0, min(1, final_score))
62
- final_percent = round(final_score * 100, 2)
63
-
64
- verdict = "🧠 AI-Generated" if final_score > 0.55 else "🧍 Human"
65
- color = "#ff4b4b" if final_score > 0.55 else "#4caf50"
66
-
67
- # HTML output with bars
68
- text = "## 🔍 Model Results\n"
69
- for res in results:
70
- percent = round(res["ai_score"] * 100, 2)
71
- bar_color = "#ff4b4b" if percent > 50 else "#4caf50"
72
- text += (
73
- f"**{res['model']}** → {percent}% AI\n"
74
- f"<div style='height:10px;background-color:{bar_color};width:{percent}%;border-radius:5px;margin-bottom:6px;'></div>\n"
75
- )
76
-
77
- text += f"\n## 🧾 Final Verdict\n"
78
- text += f"<div style='font-size:18px;font-weight:bold;color:{color};'>{verdict} ({final_percent}%)</div>"
79
-
80
- return text
81
 
82
  except Exception as e:
83
  traceback.print_exc()
84
- return f" Error: {str(e)}"
85
-
86
-
87
- # Gradio app
88
- demo = gr.Interface(
89
- fn=predict_image,
90
- inputs=gr.Image(type="pil", label="Upload Image"),
91
- outputs=gr.HTML(label="Results"),
92
- title="🧩 Unreal Eye – AI Image Detector",
93
- description="Detects AI-generated images using 3 equal-weight expert models (umm-maybe, dima806, ateeqq)."
94
- )
95
-
96
- if __name__ == "__main__":
97
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from PIL import Image
4
  import traceback
5
 
6
+ # Define model priorities
7
+ models = [
8
+ ("Ateeqq/ai-vs-human-image-detector", "ateeq"),
9
+ ("umm-maybe/AI-image-detector", "umm_maybe"),
10
+ ("dima806/ai_vs_human_generated_image_detection", "dimma"),
11
+ ]
12
+
13
+ pipes = []
14
+ for model_id, _ in models:
 
 
 
 
 
 
 
 
15
  try:
16
+ pipes.append((model_id, pipeline("image-classification", model=model_id)))
 
17
  except Exception as e:
18
+ print(f"Error loading {model_id}: {e}")
19
 
20
  def predict_image(image: Image.Image):
21
  try:
 
22
  results = []
23
+ for _, pipe in pipes:
24
+ res = pipe(image)[0]
25
+ results.append(res)
26
+
27
+ final_result = results[0] # Highest priority model result
28
+ label = final_result["label"].lower()
29
+ score = final_result["score"] * 100
30
+
31
+ if "ai" in label or "fake" in label:
32
+ verdict = f"🧠 AI-Generated ({score:.1f}% confidence)"
33
+ color = "#007BFF"
34
+ else:
35
+ verdict = f"🧍 Human-Made ({score:.1f}% confidence)"
36
+ color = "#4CAF50"
37
+
38
+ html = f"""
39
+ <div class='result-box' style="
40
+ background: linear-gradient(135deg, {color}33, #1a1a1a);
41
+ border: 2px solid {color};
42
+ border-radius: 15px;
43
+ padding: 25px;
44
+ text-align: center;
45
+ color: white;
46
+ font-size: 20px;
47
+ font-weight: 600;
48
+ box-shadow: 0 0 20px {color}55;
49
+ animation: fadeIn 0.6s ease-in-out;
50
+ ">
51
+ {verdict}
52
+ </div>
53
+ """
54
+ return html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  except Exception as e:
57
  traceback.print_exc()
58
+ return f"<div style='color:red;'>Error analyzing image: {str(e)}</div>"
59
+
60
+ # Custom CSS
61
+ css = """
62
+ .gr-button-primary {
63
+ background-color: #007BFF !important;
64
+ border-color: #007BFF !important;
65
+ color: white !important;
66
+ font-weight: 600;
67
+ }
68
+ .gr-button-secondary {
69
+ background-color: #dc3545 !important;
70
+ color: white !important;
71
+ font-weight: 600;
72
+ }
73
+ #loading-text {
74
+ text-align: center;
75
+ font-size: 18px;
76
+ color: #007BFF;
77
+ animation: blink 1.2s infinite;
78
+ }
79
+ @keyframes blink {
80
+ 50% { opacity: 0.5; }
81
+ }
82
+ @keyframes fadeIn {
83
+ from { opacity: 0; transform: scale(0.95); }
84
+ to { opacity: 1; transform: scale(1); }
85
+ }
86
+ """
87
+
88
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
89
+ gr.Markdown("<h1 style='text-align:center; color:#007BFF;'>🔍 AI Image Detector</h1>")
90
+
91
+ with gr.Row():
92
+ with gr.Column(scale=1):
93
+ image_input = gr.Image(type="pil", label="Upload an image")
94
+ analyze_button = gr.Button("Analyze", variant="primary")
95
+ clear_button = gr.Button("Clear", variant="secondary")
96
+ loading_text = gr.Markdown("", elem_id="loading-text")
97
+ with gr.Column(scale=1):
98
+ output = gr.HTML(label="Result")
99
+
100
+ def analyze_with_animation(img):
101
+ loading_text.value = "⏳ Analyzing image..."
102
+ result = predict_image(img)
103
+ loading_text.value = ""
104
+ return result
105
+
106
+ analyze_button.click(
107
+ analyze_with_animation,
108
+ inputs=image_input,
109
+ outputs=output,
110
+ )
111
+
112
+ clear_button.click(lambda: (None, ""), outputs=[image_input, output])
113
+
114
+ demo.launch()