MetaQu commited on
Commit
f0ff41c
·
verified ·
1 Parent(s): a152fb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -100
app.py CHANGED
@@ -1,120 +1,87 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image, ExifTags
4
- import numpy as np
5
  import cv2
 
 
 
 
6
 
7
- # Model utama AI-detector
8
- detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
 
9
 
10
- # Model backup (general classifier)
11
- general = pipeline("image-classification", model="google/vit-base-patch16-224")
 
 
 
 
 
 
 
12
 
13
- def analyze_image(img_pil):
14
- img = np.array(img_pil)
 
 
 
15
 
16
- # Blur detection (variance of Laplacian)
17
- gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
18
  blur_score = cv2.Laplacian(gray, cv2.CV_64F).var()
19
-
20
- # Noise estimation (std deviation)
21
  noise_score = np.std(gray)
22
 
23
- # Edge consistency
24
- edges = cv2.Canny(gray, 100, 200)
25
- edge_score = np.std(edges)
26
-
27
- # JPEG artifacts (kasar: std dev dari DCT block)
28
- dct = cv2.dct(np.float32(gray) / 255.0)
29
- jpeg_artifact = np.std(dct)
30
 
31
- # Metadata kamera
32
- metadata = "Tidak Ada"
33
  try:
34
- exif_data = img_pil._getexif()
35
- if exif_data:
36
- metadata = "Ada"
 
 
 
37
  except:
38
  pass
39
 
40
- return blur_score, noise_score, edge_score, jpeg_artifact, metadata
41
-
42
- def detect_image(img):
43
- try:
44
- # Prediksi AI-detector
45
- result1 = detector(img)
46
- label1 = result1[0]['label']
47
- conf1 = round(result1[0]['score'] * 100, 2)
48
-
49
- # Prediksi model general
50
- result2 = general(img)
51
- label2 = result2[0]['label']
52
- conf2 = round(result2[0]['score'] * 100, 2)
53
-
54
- # Analisis teknis
55
- blur, noise, edge, jpeg_art, metadata = analyze_image(img)
56
-
57
- # --- Voting System ---
58
- ai_score = 0
59
- real_score = 0
60
-
61
- # Dari model AI-detector
62
- if "fake" in label1.lower() or "artificial" in label1.lower():
63
- ai_score += conf1
64
- elif "real" in label1.lower() or "human" in label1.lower():
65
- real_score += conf1
66
-
67
- # Dari metadata
68
- if metadata == "Ada":
69
- real_score += 30 # bobot ekstra untuk foto asli
70
- else:
71
- ai_score += 20
72
-
73
- # Dari noise & blur
74
- if noise > 20 and blur > 50:
75
- real_score += 20
76
- else:
77
- ai_score += 10
78
-
79
- # Hasil akhir
80
- total = ai_score + real_score + 1e-6
81
- ai_pct = round((ai_score / total) * 100, 2)
82
- real_pct = round((real_score / total) * 100, 2)
83
-
84
- if ai_pct > real_pct:
85
- final = f"⚠️ Kemungkinan Besar AI Generated ({ai_pct}%)"
86
- else:
87
- final = f"✅ Kemungkinan Besar Foto Asli ({real_pct}%)"
88
-
89
- output = f"""
90
- ### Hasil Deteksi:
91
- {final}
92
-
93
- **Persentase AI:** {ai_pct}%
94
- **Persentase Asli:** {real_pct}%
95
-
96
- **Model AI-detector:** {label1} ({conf1}%)
97
- **Model General (ViT):** {label2} ({conf2}%)
98
-
99
- **Analisis Kamera & Teknis:**
100
- - Blur Score: {round(blur,2)}
101
- - Noise Score: {round(noise,2)}
102
- - Edge Consistency (STD): {round(edge,2)}
103
- - JPEG Artifact Level: {round(jpeg_art,2)}
104
- - Metadata Kamera: {metadata}
105
- """
106
- return output
107
- except Exception as e:
108
- return f"Terjadi error: {str(e)}"
109
-
110
- # UI Gradio
111
- iface = gr.Interface(
112
- fn=detect_image,
113
  inputs=gr.Image(type="pil"),
114
- outputs="markdown",
115
- title="AI vs Real Image Detector (Hybrid)",
116
- description="Deteksi AI vs Foto Asli dengan kombinasi model + analisis teknis (blur, noise, edge, metadata)."
117
  )
118
 
119
  if __name__ == "__main__":
120
- iface.launch()
 
1
  import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image, ExifTags
 
4
  import cv2
5
+ import numpy as np
6
+
7
+ # Model Hugging Face untuk AI vs Human
8
+ detector = pipeline("image-classification", model="microsoft/resnet-50")
9
 
10
+ def analyze_image(image):
11
+ # Convert ke format OpenCV
12
+ img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
13
 
14
+ # ---- 1. Prediksi dengan model HF ----
15
+ preds = detector(image)
16
+ ai_score = 0.0
17
+ human_score = 0.0
18
+ for p in preds:
19
+ if "artificial" in p["label"].lower() or "ai" in p["label"].lower():
20
+ ai_score += p["score"]
21
+ else:
22
+ human_score += p["score"]
23
 
24
+ # Normalisasi biar total 1
25
+ total = ai_score + human_score
26
+ if total > 0:
27
+ ai_score /= total
28
+ human_score /= total
29
 
30
+ # ---- 2. Analisis blur/noise ----
31
+ gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
32
  blur_score = cv2.Laplacian(gray, cv2.CV_64F).var()
 
 
33
  noise_score = np.std(gray)
34
 
35
+ # Semakin kecil blur/noise → semakin cenderung AI
36
+ blur_factor = 1.0 if blur_score < 100 else 0.0
37
+ noise_factor = 1.0 if noise_score < 20 else 0.0
 
 
 
 
38
 
39
+ # ---- 3. Cek metadata kamera ----
40
+ has_metadata = False
41
  try:
42
+ exif = image._getexif()
43
+ if exif is not None:
44
+ for tag, value in exif.items():
45
+ decoded = ExifTags.TAGS.get(tag, tag)
46
+ if decoded in ["Make", "Model"]:
47
+ has_metadata = True
48
  except:
49
  pass
50
 
51
+ metadata_factor = 0.0 if has_metadata else 1.0
52
+
53
+ # ---- 4. Ensemble skor ----
54
+ final_score = (
55
+ 0.6 * ai_score +
56
+ 0.2 * blur_factor +
57
+ 0.1 * noise_factor +
58
+ 0.1 * metadata_factor
59
+ )
60
+
61
+ result = "AI Generated" if final_score > 0.5 else "Foto Asli"
62
+
63
+ # ---- 5. Hasil detail ----
64
+ details = f"""
65
+ 🔍 Hasil Deteksi:
66
+ {result}
67
+
68
+ Skor Model AI-detector: {ai_score:.2f}
69
+ Skor Human: {human_score:.2f}
70
+ Blur Score: {blur_score:.2f}
71
+ Noise Score: {noise_score:.2f}
72
+ Metadata Kamera: {"Ada" if has_metadata else "Tidak Ada"}
73
+ Final Score: {final_score:.2f}
74
+ """
75
+ return details
76
+
77
+ # Gradio UI
78
+ demo = gr.Interface(
79
+ fn=analyze_image,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  inputs=gr.Image(type="pil"),
81
+ outputs="text",
82
+ title="AI vs Real Image Detector",
83
+ description="Upload foto untuk mendeteksi apakah gambar asli atau hasil AI."
84
  )
85
 
86
  if __name__ == "__main__":
87
+ demo.launch()