MetaQu commited on
Commit
13ae792
·
verified ·
1 Parent(s): b5ea682

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -32
app.py CHANGED
@@ -1,49 +1,119 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- from PIL import Image
 
 
4
 
5
- # Model utama untuk deteksi real vs AI
6
- detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
 
 
 
 
 
 
7
 
8
- # Model tambahan general classifier (backup)
9
- general = pipeline("image-classification", model="google/vit-base-patch16-224")
 
 
 
10
 
11
- def detect_image(img):
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
- result1 = detector(img)
14
- label1 = result1[0]['label']
15
- conf1 = round(result1[0]['score'] * 100, 2)
16
-
17
- result2 = general(img)
18
- label2 = result2[0]['label']
19
- conf2 = round(result2[0]['score'] * 100, 2)
20
-
21
- # Logika baru tanpa cek manual
22
- if "fake" in label1.lower() or "artificial" in label1.lower():
23
- final = f"⚠️ Gambar ini kemungkinan besar dihasilkan AI ({conf1}%)"
24
- elif "human" in label1.lower() and conf1 < 95:
25
- final = f"⚠️ Gambar ini kemungkinan besar dihasilkan AI ({100-conf1:.2f}%)"
26
- else:
27
- final = f"✅ Gambar ini kemungkinan besar asli ({conf1}%)"
28
-
29
- output = f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  ### Hasil Deteksi:
31
- {final}
32
 
33
- **Model AI-detector:** {label1} ({conf1}%)
34
- **Model General (ViT):** {label2} ({conf2}%)
 
 
 
35
  """
36
- return output
37
- except Exception as e:
38
- return f"Terjadi error: {str(e)}"
39
 
40
- # UI Gradio
 
 
41
  iface = gr.Interface(
42
  fn=detect_image,
43
  inputs=gr.Image(type="pil"),
44
  outputs="markdown",
45
- title="AI vs Real Image Detector",
46
- description="Upload foto untuk mendeteksi apakah gambar kemungkinan besar asli atau hasil AI."
47
  )
48
 
49
  if __name__ == "__main__":
 
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
48
+ # ----------------------------
49
+ def detect_image(image):
50
+ hf_score = 0
51
+ if hf_detector:
52
+ try:
53
+ result = hf_detector(image)
54
+ label = result[0]['label']
55
+ conf = result[0]['score'] * 100
56
+ if "fake" in label.lower() or "artificial" in label.lower():
57
+ hf_score = conf
58
+ elif "human" in label.lower():
59
+ hf_score = 100 - conf # human confidence rendah → kemungkinan AI
60
+ except:
61
+ hf_score = 0
62
+
63
+ general_score = 0
64
+ if general_model:
65
+ try:
66
+ result2 = general_model(image)
67
+ label2 = result2[0]['label']
68
+ conf2 = result2[0]['score'] * 100
69
+ if any(x in label2.lower() for x in ["anime","cartoon","illustration","3d","maya"]):
70
+ general_score = conf2
71
+ except:
72
+ general_score = 0
73
+
74
+ # Analisis lokal
75
+ blur_score = calculate_blur(image)
76
+ noise_score = calculate_noise(image)
77
+ exif_present = has_camera_exif(image)
78
+ local_score = 0
79
+ if blur_score < 100 or noise_score < 10:
80
+ local_score += 50
81
+ if not exif_present:
82
+ local_score += 10
83
+
84
+ # Weighted score
85
+ weighted_score = hf_score*0.6 + general_score*0.2 + local_score*0.2
86
+ weighted_score = min(max(weighted_score, 0), 100) # clamp 0-100
87
+
88
+ # Output final
89
+ if weighted_score >= 95:
90
+ final_result = f"⚠️ Gambar ini hasil AI ({weighted_score:.2f}%)"
91
+ elif weighted_score <= 5:
92
+ final_result = f"✅ Gambar ini asli ({100-weighted_score:.2f}%)"
93
+ else:
94
+ final_result = f"AI: {weighted_score:.2f}%, Asli: {100-weighted_score:.2f}%"
95
+
96
+ output = f"""
97
  ### Hasil Deteksi:
98
+ {final_result}
99
 
100
+ HF AI-detector: {label if hf_detector else 'N/A'} ({conf if hf_detector else 0:.2f}%)
101
+ General Model: {label2 if general_model else 'N/A'} ({conf2 if general_model else 0:.2f}%)
102
+ Blur Score: {blur_score:.2f}
103
+ Noise Score: {noise_score:.2f}
104
+ Metadata Kamera: {'Ada' if exif_present else 'Tidak Ada'}
105
  """
106
+ return output
 
 
107
 
108
+ # ----------------------------
109
+ # Gradio Interface
110
+ # ----------------------------
111
  iface = gr.Interface(
112
  fn=detect_image,
113
  inputs=gr.Image(type="pil"),
114
  outputs="markdown",
115
+ title="AI vs Foto Asli Detector (Hybrid)",
116
+ description="Unggah gambar, sistem akan mendeteksi apakah gambar kemungkinan besar asli atau dihasilkan AI."
117
  )
118
 
119
  if __name__ == "__main__":