MetaQu commited on
Commit
bb086d0
·
verified ·
1 Parent(s): 5dd3ca7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -62
app.py CHANGED
@@ -1,91 +1,93 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image
4
- from PIL.ExifTags import TAGS
5
  import numpy as np
 
6
 
7
- # Model utama deteksi AI
8
  detector = pipeline("image-classification", model="umm-maybe/AI-image-detector")
9
- # Model general classifier (backup)
10
  general = pipeline("image-classification", model="google/vit-base-patch16-224")
11
 
12
- def get_exif_metadata(img):
13
- """Cek metadata kamera untuk membantu deteksi foto asli"""
14
- try:
15
- exif_data = img._getexif()
16
- if exif_data is None:
17
- return False
18
- for tag_id, value in exif_data.items():
19
- tag = TAGS.get(tag_id, tag_id)
20
- if tag in ["Make", "Model", "Software"]:
21
- return True
22
- return False
23
- except:
24
- return False
25
 
26
  def detect_image(img):
27
  try:
28
- # Prediksi dengan AI-detector
29
- result1 = detector(img)
30
- label1 = result1[0]['label']
31
- conf1 = result1[0]['score'] * 100
32
-
33
- # Prediksi dengan model general
34
- result2 = general(img)
35
- label2 = result2[0]['label']
36
- conf2 = result2[0]['score'] * 100
37
-
38
- # Cek metadata kamera
39
- has_metadata = get_exif_metadata(img)
40
-
41
- # Weighted hybrid scoring
42
- # Skema: AI-detector 50%, Metadata 30%, general model 20%
43
- ai_score = conf1 if "artificial" in label1.lower() or "fake" in label1.lower() else 0
44
- human_score = conf1 if "human" in label1.lower() or "real" in label1.lower() else 0
45
-
46
- if has_metadata:
47
- human_score += 30 # boost jika metadata ada
48
- ai_score = min(ai_score, 100)
49
- human_score = min(human_score, 100)
50
-
51
- # Normalisasi agar total = 100%
52
- total = ai_score + human_score
53
- if total == 0:
54
- ai_percent = 50
55
- human_percent = 50
56
- else:
57
- ai_percent = round((ai_score / total) * 100, 2)
58
- human_percent = round((human_score / total) * 100, 2)
59
-
60
- # Tentukan hasil akhir
61
- if ai_percent == 100:
62
- final_text = "🖼️ Gambar ini 100% AI"
63
- elif human_percent == 100:
64
- final_text = "🖼️ Gambar ini asli 100%"
65
  else:
66
- final_text = f"🖼️ Gambar ini {ai_percent}% AI / {human_percent}% Asli"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- # Tambahkan info model
69
  output = f"""
70
  ### Hasil Deteksi:
71
- {final_text}
72
 
73
- **Model AI-detector:** {label1} ({conf1:.2f}%)
74
- **Model General (ViT):** {label2} ({conf2:.2f}%)
75
- **Metadata Kamera Ada:** {"Ya" if has_metadata else "Tidak"}
 
 
76
  """
77
  return output
78
 
79
  except Exception as e:
80
  return f"Terjadi error: {str(e)}"
81
 
82
- # UI Gradio
83
  iface = gr.Interface(
84
  fn=detect_image,
85
  inputs=gr.Image(type="pil"),
86
  outputs="markdown",
87
- title="Hybrid AI vs Real Image Detector",
88
- description="Upload gambar, sistem akan mendeteksi persentase AI vs foto asli, sensitif untuk AI photorealistic tapi tetap akurat untuk foto asli."
89
  )
90
 
91
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image
 
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
+ # Model tambahan general classifier
10
  general = pipeline("image-classification", model="google/vit-base-patch16-224")
11
 
12
+ def variance_of_laplacian(image):
13
+ # Menghitung blur menggunakan Laplacian
14
+ return cv2.Laplacian(image, cv2.CV_64F).var()
15
+
16
+ def estimate_noise(image):
17
+ # Menghitung noise sederhana
18
+ img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
19
+ m = np.mean(img_gray)
20
+ noise = np.mean((img_gray - m)**2)
21
+ return noise
 
 
 
22
 
23
  def detect_image(img):
24
  try:
25
+ # Convert PIL ke OpenCV format
26
+ img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
27
+
28
+ # Blur dan Noise
29
+ blur_score = variance_of_laplacian(img_cv)
30
+ noise_score = estimate_noise(img_cv)
31
+
32
+ # Metadata kamera
33
+ metadata_camera = img.info.get("exif") is not None
34
+
35
+ # Prediksi AI
36
+ result_ai = detector(img)
37
+ label_ai = result_ai[0]['label'].lower()
38
+ conf_ai = result_ai[0]['score'] * 100
39
+
40
+ # Prediksi general
41
+ result_gen = general(img)
42
+ label_gen = result_gen[0]['label']
43
+ conf_gen = result_gen[0]['score'] * 100
44
+
45
+ # Hybrid scoring
46
+ if "artificial" in label_ai or "fake" in label_ai:
47
+ ai_score = max(conf_ai, 70)
48
+ elif "human" in label_ai:
49
+ ai_score = 100 - conf_ai * 0.7
 
 
 
 
 
 
 
 
 
 
 
 
50
  else:
51
+ ai_score = 50
52
+
53
+ # Tambah bobot metadata kamera
54
+ if metadata_camera:
55
+ ai_score -= 10
56
+
57
+ # Penalti blur rendah untuk AI photorealistic
58
+ if blur_score < 100:
59
+ ai_score += 10 # foto asli biasanya lebih tajam
60
+ # Penalti noise sangat rendah (AI sering terlalu bersih)
61
+ if noise_score < 30:
62
+ ai_score += 5
63
+
64
+ # Clamp nilai
65
+ ai_score = max(0, min(100, ai_score))
66
+ real_score = 100 - ai_score
67
 
68
+ # Output
69
  output = f"""
70
  ### Hasil Deteksi:
71
+ 🖼️ Gambar ini {round(ai_score,2)}% AI / {round(real_score,2)}% Asli
72
 
73
+ **Model AI-detector:** {result_ai[0]['label']} ({round(conf_ai,2)}%)
74
+ **Model General (ViT):** {label_gen} ({round(conf_gen,2)}%)
75
+ Blur Score: {round(blur_score,2)}
76
+ Noise Score: {round(noise_score,2)}
77
+ Metadata Kamera: {'Ada' if metadata_camera else 'Tidak'}
78
  """
79
  return output
80
 
81
  except Exception as e:
82
  return f"Terjadi error: {str(e)}"
83
 
84
+ # Gradio interface
85
  iface = gr.Interface(
86
  fn=detect_image,
87
  inputs=gr.Image(type="pil"),
88
  outputs="markdown",
89
+ title="AI vs Real Image Detector (Advanced Hybrid)",
90
+ description="Gratis, mendeteksi AI photorealistic dengan blur & noise analisis, semua persentase."
91
  )
92
 
93
  if __name__ == "__main__":