MetaQu commited on
Commit
6394c51
·
verified ·
1 Parent(s): 419f944

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -82
app.py CHANGED
@@ -1,99 +1,48 @@
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
- # ===== 1. Load 3 Public Models =====
8
  model_ids = [
9
- "umm-maybe/AI-image-detector", # Detektor umum
10
- "vikhyatk/moondream2", # Model multimodal
11
- "microsoft/resnet-50" # Baseline visual classifier
12
  ]
13
 
14
- detectors = [pipeline("image-classification", model=m) for m in model_ids]
 
15
 
16
- # ===== 2. Fungsi Forensik Manual =====
17
- def forensic_analysis(img: Image.Image):
18
- img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
19
-
20
- # Blur (Laplacian variance)
21
- blur_var = cv2.Laplacian(img_cv, cv2.CV_64F).var()
22
-
23
- # Noise (High-pass filter std)
24
- gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
25
- noise = cv2.Laplacian(gray, cv2.CV_64F).std()
26
-
27
- # High-frequency ratio (FFT)
28
- f = np.fft.fft2(gray)
29
- fshift = np.fft.fftshift(f)
30
- magnitude_spectrum = np.abs(fshift)
31
- high_freq_ratio = np.sum(magnitude_spectrum > 50) / magnitude_spectrum.size
32
-
33
- # Metadata kamera
34
- exif_data = img.getexif()
35
- has_exif = len(exif_data) > 0
36
-
37
- forensic_score = 0
38
- if blur_var > 500: forensic_score += 20
39
- if noise > 10: forensic_score += 20
40
- if high_freq_ratio > 0.3: forensic_score += 20
41
- if has_exif: forensic_score += 40
42
-
43
- return {
44
- "blur": round(blur_var, 2),
45
- "noise": round(noise, 2),
46
- "high_freq_ratio": round(high_freq_ratio, 3),
47
- "has_exif": has_exif,
48
- "forensic_score": forensic_score
49
- }
50
-
51
- # ===== 3. Fungsi Prediksi Gabungan =====
52
- def detect_ai(image):
53
- votes = []
54
  scores = []
55
-
56
- # Jalankan semua model
57
  for det in detectors:
58
- preds = det(image)
59
- label = preds[0]['label'].lower()
60
- score = preds[0]['score']
61
-
62
- if "ai" in label or "fake" in label or "artificial" in label:
63
- votes.append("AI")
64
- else:
65
- votes.append("Real")
66
- scores.append(score)
67
-
68
- # Analisis forensik
69
- forensic = forensic_analysis(image)
70
-
71
- # Voting
72
- ai_votes = votes.count("AI")
73
- real_votes = votes.count("Real")
74
-
75
- if ai_votes > real_votes:
76
- final = "AI"
77
- elif real_votes > ai_votes:
78
- final = "Real"
79
  else:
80
- # Gunakan forensic sebagai tie-breaker
81
- final = "Real" if forensic["forensic_score"] > 50 else "AI"
82
-
83
- return {
84
- "Hasil Deteksi": final,
85
- "Voting Model": votes,
86
- "Confidence Scores": scores,
87
- "Forensik": forensic
88
- }
89
 
90
- # ===== 4. Gradio UI =====
91
  demo = gr.Interface(
92
- fn=detect_ai,
93
  inputs=gr.Image(type="pil"),
94
- outputs="json",
95
- title="AI vs Real Image Detector (Ensemble + Forensic)",
96
- description="Menggunakan 3 model publik + analisis forensik (blur, noise, frekuensi, metadata)."
97
  )
98
 
99
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ from PIL import Image
 
4
  import numpy as np
5
 
6
+ # ====== MODEL LIST ======
7
  model_ids = [
8
+ "vikhyatk/moondream2", # butuh trust_remote_code=True
9
+ "umm-maybe/synthetic-image-detector",
10
+ "falconsai/nsfw_image_detection"
11
  ]
12
 
13
+ # Load semua model dengan trust_remote_code
14
+ detectors = [pipeline("image-classification", model=m, trust_remote_code=True) for m in model_ids]
15
 
16
+ def detect_image(img: Image.Image):
17
+ results = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  scores = []
19
+
 
20
  for det in detectors:
21
+ try:
22
+ out = det(img)
23
+ # Ambil label & skor tertinggi
24
+ top = max(out, key=lambda x: x["score"])
25
+ results.append(f"{det.model.config.name_or_path}: {top['label']} ({top['score']:.2f})")
26
+ scores.append(top["score"] if "ai" in top["label"].lower() or "fake" in top["label"].lower() or "artificial" in top["label"].lower() else 1 - top["score"])
27
+ except Exception as e:
28
+ results.append(f"Error {det.model.config.name_or_path}: {str(e)}")
29
+
30
+ if scores:
31
+ avg_score = np.mean(scores) * 100
 
 
 
 
 
 
 
 
 
 
32
  else:
33
+ avg_score = 0
34
+
35
+ verdict = "AI" if avg_score > 50 else "Asli"
36
+
37
+ return f"🔎 Hasil Deteksi: {verdict}\nPersentase AI: {avg_score:.2f}%\n\nDetail:\n" + "\n".join(results)
 
 
 
 
38
 
39
+ # ====== GRADIO UI ======
40
  demo = gr.Interface(
41
+ fn=detect_image,
42
  inputs=gr.Image(type="pil"),
43
+ outputs="text",
44
+ title="AI vs Real Image Detector",
45
+ description="Upload foto untuk mendeteksi apakah itu AI-generated atau asli. Menggunakan 3 model publik dengan trust_remote_code=True."
46
  )
47
 
48
  if __name__ == "__main__":