MetaQu commited on
Commit
39141aa
ยท
verified ยท
1 Parent(s): af7913c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -42
app.py CHANGED
@@ -1,62 +1,95 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- from PIL import Image
4
  import numpy as np
5
 
6
- # Model utama
7
  detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
8
  general = pipeline("image-classification", model="google/vit-base-patch16-224")
9
 
10
- # Estimasi blur & noise tanpa OpenCV
 
11
  def estimate_blur(img):
12
  gray = img.convert("L")
13
  arr = np.array(gray)
14
  gx, gy = np.gradient(arr)
15
- laplacian_var = np.var(gx + gy)
16
- return laplacian_var
17
 
18
  def estimate_noise(img):
19
  gray = img.convert("L")
20
  arr = np.array(gray)
21
- m = np.mean(arr)
22
- noise = np.mean((arr - m) ** 2)
23
- return noise
24
-
25
- # Pengecekan pola photorealistic AI
26
- def photorealistic_ai_adjustment(img, ai_score):
27
- # Cek metadata, blur, dan noise
28
- has_metadata = bool(img.info)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  blur = estimate_blur(img)
30
  noise = estimate_noise(img)
 
 
 
31
 
32
- # Logika sensitif:
33
- # Foto asli biasanya ada metadata kamera, blur & noise tertentu
34
- # Jika metadata kosong, blur sangat rendah, dan noise aneh => kemungkinan AI lebih tinggi
35
  adjustment = 0
36
- if not has_metadata:
 
 
 
 
 
 
 
 
 
 
37
  adjustment += 10
38
- if blur < 100: # sangat tajam
 
 
39
  adjustment += 10
40
- if noise < 50: # terlalu bersih
 
 
41
  adjustment += 10
42
 
43
- ai_score += adjustment
44
- ai_score = min(ai_score, 100) # maksimal 100%
45
- return ai_score
46
 
 
47
  def detect_image(img):
48
  try:
49
- # Prediksi AI detector
50
  result1 = detector(img)
51
  label1 = result1[0]['label'].lower()
52
  conf1 = round(result1[0]['score'] * 100, 2)
53
 
54
- # Prediksi model general
55
  result2 = general(img)
56
  label2 = result2[0]['label']
57
  conf2 = round(result2[0]['score'] * 100, 2)
58
 
59
- # Hitung AI % awal
60
  if "artificial" in label1 or "fake" in label1:
61
  ai_percent = conf1
62
  elif "human" in label1:
@@ -64,37 +97,36 @@ def detect_image(img):
64
  else:
65
  ai_percent = conf1
66
 
67
- # Adjust untuk photorealistic AI
68
- ai_percent = photorealistic_ai_adjustment(img, ai_percent)
69
- ai_percent = round(ai_percent, 2)
70
  real_percent = round(100 - ai_percent, 2)
71
 
72
- # Blur & Noise untuk info
73
- blur_score = round(estimate_blur(img), 2)
74
- noise_score = round(estimate_noise(img), 2)
75
- has_metadata = "Ada" if img.info else "Tidak"
76
 
77
- output = f"""
78
- ### Hasil Deteksi:
79
- ๐Ÿ–ผ๏ธ Gambar ini {ai_percent}% AI / {real_percent}% Asli
80
 
81
  **Model AI-detector:** {label1} ({conf1}%)
82
  **Model General (ViT):** {label2} ({conf2}%)
83
- **Blur Score:** {blur_score}
84
- **Noise Score:** {noise_score}
85
- **Metadata Kamera:** {has_metadata}
 
 
 
 
86
  """
87
- return output
88
  except Exception as e:
89
- return f"Terjadi error: {str(e)}"
90
 
91
  # UI Gradio
92
  iface = gr.Interface(
93
  fn=detect_image,
94
  inputs=gr.Image(type="pil"),
95
  outputs="markdown",
96
- title="Hybrid AI vs Real Image Detector (Sensitif Photorealistic)",
97
- description="Upload foto untuk mendeteksi kemungkinan besar gambar asli atau hasil AI. Lebih sensitif terhadap AI photorealistic. 100% gratis."
98
  )
99
 
100
  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
 
6
+ # Model HuggingFace
7
  detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
8
  general = pipeline("image-classification", model="google/vit-base-patch16-224")
9
 
10
+ # --- Analisis tambahan ---
11
+
12
  def estimate_blur(img):
13
  gray = img.convert("L")
14
  arr = np.array(gray)
15
  gx, gy = np.gradient(arr)
16
+ return np.var(gx + gy)
 
17
 
18
  def estimate_noise(img):
19
  gray = img.convert("L")
20
  arr = np.array(gray)
21
+ return np.var(arr - np.mean(arr))
22
+
23
+ def jpeg_artifacts(img):
24
+ # konversi ke numpy
25
+ arr = np.array(img.convert("L"))
26
+ # ambil perbedaan antar piksel
27
+ diff = np.abs(arr[:, 1:] - arr[:, :-1])
28
+ return np.mean(diff)
29
+
30
+ def edge_inconsistency(img):
31
+ gray = img.convert("L")
32
+ arr = np.array(gray)
33
+ gx, gy = np.gradient(arr)
34
+ edges = np.sqrt(gx**2 + gy**2)
35
+ return np.std(edges)
36
+
37
+ def has_exif(img):
38
+ try:
39
+ exif_data = img._getexif()
40
+ if exif_data:
41
+ return True, {ExifTags.TAGS.get(k, k): v for k, v in exif_data.items()}
42
+ return False, {}
43
+ except:
44
+ return False, {}
45
+
46
+ # --- Penyesuaian AI score ---
47
+ def adjust_ai_score(img, ai_score):
48
  blur = estimate_blur(img)
49
  noise = estimate_noise(img)
50
+ jpeg = jpeg_artifacts(img)
51
+ edge_std = edge_inconsistency(img)
52
+ has_meta, meta = has_exif(img)
53
 
 
 
 
54
  adjustment = 0
55
+
56
+ # Metadata kamera sangat penting
57
+ if not has_meta:
58
+ adjustment += 15
59
+
60
+ # Blur terlalu kecil โ†’ terlalu tajam โ†’ AI photorealistic
61
+ if blur < 80:
62
+ adjustment += 10
63
+
64
+ # Noise terlalu rendah โ†’ gambar terlalu bersih โ†’ AI
65
+ if noise < 50:
66
  adjustment += 10
67
+
68
+ # JPEG artifact rendah โ†’ AI cenderung hasil render
69
+ if jpeg < 5:
70
  adjustment += 10
71
+
72
+ # Edge terlalu konsisten โ†’ AI
73
+ if edge_std < 20:
74
  adjustment += 10
75
 
76
+ ai_score = min(ai_score + adjustment, 100)
77
+ return ai_score, blur, noise, jpeg, edge_std, has_meta
 
78
 
79
+ # --- Deteksi utama ---
80
  def detect_image(img):
81
  try:
82
+ # Prediksi AI
83
  result1 = detector(img)
84
  label1 = result1[0]['label'].lower()
85
  conf1 = round(result1[0]['score'] * 100, 2)
86
 
87
+ # Prediksi general
88
  result2 = general(img)
89
  label2 = result2[0]['label']
90
  conf2 = round(result2[0]['score'] * 100, 2)
91
 
92
+ # Hitung AI %
93
  if "artificial" in label1 or "fake" in label1:
94
  ai_percent = conf1
95
  elif "human" in label1:
 
97
  else:
98
  ai_percent = conf1
99
 
100
+ # Penyesuaian tambahan
101
+ ai_percent, blur, noise, jpeg, edge_std, has_meta = adjust_ai_score(img, ai_percent)
 
102
  real_percent = round(100 - ai_percent, 2)
103
 
104
+ meta_status = "Ada" if has_meta else "Tidak"
 
 
 
105
 
106
+ return f"""
107
+ ### ๐Ÿ” Hasil Deteksi:
108
+ ๐Ÿ–ผ๏ธ Gambar ini {ai_percent:.2f}% AI / {real_percent:.2f}% Asli
109
 
110
  **Model AI-detector:** {label1} ({conf1}%)
111
  **Model General (ViT):** {label2} ({conf2}%)
112
+
113
+ **Analisis Kamera & Teknis:**
114
+ - Blur Score: {blur:.2f}
115
+ - Noise Score: {noise:.2f}
116
+ - JPEG Artifact Level: {jpeg:.2f}
117
+ - Edge Consistency (STD): {edge_std:.2f}
118
+ - Metadata Kamera: {meta_status}
119
  """
 
120
  except Exception as e:
121
+ return f"โš ๏ธ Error: {str(e)}"
122
 
123
  # UI Gradio
124
  iface = gr.Interface(
125
  fn=detect_image,
126
  inputs=gr.Image(type="pil"),
127
  outputs="markdown",
128
+ title="Ultimate AI vs Real Detector",
129
+ description="Detektor gratis untuk membedakan foto asli vs AI photorealistic. Memakai model HuggingFace + analisis metadata kamera, blur, noise, artefak JPEG, dan pola tepi."
130
  )
131
 
132
  if __name__ == "__main__":