MetaQu commited on
Commit
f924686
·
verified ·
1 Parent(s): 7e3b388

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -110
app.py CHANGED
@@ -1,124 +1,71 @@
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
- # ----------------------------
8
- # MODEL
9
- # ----------------------------
10
- try:
11
- hf_detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
12
- except Exception as e:
13
- hf_detector = None
14
- print("HF AI-detector gagal dimuat:", e)
15
 
16
- try:
17
- general_model = pipeline("image-classification", model="google/vit-base-patch16-224")
18
- except Exception as e:
19
- general_model = None
20
- print("General classifier gagal dimuat:", e)
21
 
22
- # ----------------------------
23
- # ANALISIS LOKAL
24
- # ----------------------------
25
- def calculate_blur(image):
26
- gray = np.array(image.convert("L"))
27
- return cv2.Laplacian(gray, cv2.CV_64F).var()
28
-
29
- def calculate_noise(image):
30
- gray = np.array(image.convert("L"), dtype=np.float32)
31
- noise_std = np.std(gray - np.mean(gray))
32
- return noise_std
33
-
34
- def has_camera_exif(image):
35
  try:
36
- exif = image._getexif()
37
- if exif:
38
- for tag, value in exif.items():
39
- decoded = ExifTags.TAGS.get(tag, tag)
40
- if decoded in ["Make", "Model"]:
41
- return True
42
- except:
43
- return False
44
- return False
45
-
46
- # ----------------------------
47
- # DETEKSI HYBRID DENGAN PERSENTASE
48
- # ----------------------------
49
- def detect_image(image):
50
- hf_score = 0
51
- general_score = 0
52
- local_score = 0
53
-
54
- # -------- HF AI-detector --------
55
- hf_label, hf_conf = "N/A", 0
56
- if hf_detector:
57
- try:
58
- result = hf_detector(image)
59
- hf_label = result[0]['label']
60
- hf_conf = result[0]['score'] * 100
61
- # Jika label mengandung tanda AI → skor AI = confidence
62
- if any(x in hf_label.lower() for x in ["fake", "ai", "artificial"]):
63
- hf_score = hf_conf
64
- except:
65
- hf_score = 0
66
-
67
- # -------- General model --------
68
- general_label, general_conf = "N/A", 0
69
- if general_model:
70
- try:
71
- result2 = general_model(image)
72
- general_label = result2[0]['label']
73
- general_conf = result2[0]['score'] * 100
74
- if any(x in general_label.lower() for x in ["anime","cartoon","illustration","maya","3d"]):
75
- general_score = general_conf * 0.7 # dikurangi bobot karena cadangan
76
- except:
77
- general_score = 0
78
-
79
- # -------- Analisis lokal --------
80
- blur_score = calculate_blur(image)
81
- noise_score = calculate_noise(image)
82
- exif_present = has_camera_exif(image)
83
-
84
- if blur_score < 100 or noise_score < 10:
85
- local_score += 50
86
- if not exif_present:
87
- local_score += 10
88
-
89
- # -------- Weighted Score --------
90
- total_ai_score = hf_score*0.7 + general_score*0.2 + local_score*0.1
91
- total_ai_score = min(max(total_ai_score, 0), 100) # clamp 0–100
92
- total_real_score = 100 - total_ai_score
93
-
94
- # -------- Output --------
95
- if total_ai_score == 100:
96
- final_text = "🤖 Gambar ini hasil AI"
97
- elif total_real_score == 100:
98
- final_text = "✅ Gambar ini asli"
99
- else:
100
- final_text = f"🖼️ {total_ai_score:.2f}% AI / {total_real_score:.2f}% Asli"
101
-
102
- output_lines = [
103
- f"### Hasil Deteksi:\n{final_text}",
104
- f"HF AI-detector: {hf_label} ({hf_conf:.2f}%)",
105
- f"General Model: {general_label} ({general_conf:.2f}%)",
106
- f"Blur Score: {blur_score:.2f}",
107
- f"Noise Score: {noise_score:.2f}",
108
- f"Metadata Kamera: {'Ada' if exif_present else 'Tidak Ada'}"
109
- ]
110
-
111
- return "\n".join(output_lines)
112
 
113
- # ----------------------------
114
- # Gradio Interface
115
- # ----------------------------
116
  iface = gr.Interface(
117
  fn=detect_image,
118
  inputs=gr.Image(type="pil"),
119
  outputs="markdown",
120
- title="Hybrid AI vs Foto Asli Detector (Gratis)",
121
- description="Unggah gambar, sistem akan mendeteksi persentase AI dan persentase asli. Tidak ada kategori tidak pasti."
122
  )
123
 
124
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ from PIL import Image
 
 
4
 
5
+ # Model utama untuk deteksi AI
6
+ detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
 
 
 
 
 
 
7
 
8
+ # Model tambahan general (backup)
9
+ general = pipeline("image-classification", model="google/vit-base-patch16-224")
 
 
 
10
 
11
+ def detect_image(img):
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
+ # Prediksi dengan AI detector
14
+ result1 = detector(img)
15
+ label1 = result1[0]['label'].lower()
16
+ conf1 = result1[0]['score'] * 100
17
+
18
+ # Prediksi dengan model general
19
+ result2 = general(img)
20
+ conf2 = result2[0]['score'] * 100
21
+
22
+ # Kombinasi skor untuk hybrid
23
+ # Logika: AI detector > 50% dianggap AI, <50% dianggap asli
24
+ if "fake" in label1 or "artificial" in label1:
25
+ ai_score = conf1
26
+ real_score = 100 - ai_score
27
+ elif "human" in label1 or "real" in label1:
28
+ real_score = conf1
29
+ ai_score = 100 - real_score
30
+ else:
31
+ # fallback jika label tidak spesifik
32
+ ai_score = conf1 / 2
33
+ real_score = 100 - ai_score
34
+
35
+ # Sensitivitas tambahan: jika AI photorealistic tapi AI score rendah
36
+ # gunakan hasil general model sebagai penyesuaian
37
+ ai_score += conf2 * 0.1
38
+ real_score = 100 - ai_score
39
+
40
+ # Batasi 0-100
41
+ ai_score = max(0, min(100, round(ai_score, 2)))
42
+ real_score = max(0, min(100, round(real_score, 2)))
43
+
44
+ if ai_score == 100:
45
+ final = "🖼️ Gambar ini 100% Hasil AI"
46
+ elif real_score == 100:
47
+ final = "🖼️ Gambar ini 100% Asli"
48
+ else:
49
+ final = f"🖼️ Gambar ini {ai_score}% AI / {real_score}% Asli"
50
+
51
+ output = f"""
52
+ ### Hasil Deteksi:
53
+ {final}
54
+
55
+ **Model AI-detector:** {label1} ({round(conf1,2)}%)
56
+ **Model General (ViT):** {result2[0]['label']} ({round(conf2,2)}%)
57
+ """
58
+ return output
59
+
60
+ except Exception as e:
61
+ return f"Terjadi error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
 
 
63
  iface = gr.Interface(
64
  fn=detect_image,
65
  inputs=gr.Image(type="pil"),
66
  outputs="markdown",
67
+ title="AI vs Real Image Detector Hybrid",
68
+ description="Upload foto untuk mendeteksi persentase kemungkinan AI vs Asli."
69
  )
70
 
71
  if __name__ == "__main__":