MetaQu's picture
Update app.py
f0ff41c verified
raw
history blame
2.4 kB
import gradio as gr
from transformers import pipeline
from PIL import Image, ExifTags
import cv2
import numpy as np
# Model Hugging Face untuk AI vs Human
detector = pipeline("image-classification", model="microsoft/resnet-50")
def analyze_image(image):
# Convert ke format OpenCV
img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
# ---- 1. Prediksi dengan model HF ----
preds = detector(image)
ai_score = 0.0
human_score = 0.0
for p in preds:
if "artificial" in p["label"].lower() or "ai" in p["label"].lower():
ai_score += p["score"]
else:
human_score += p["score"]
# Normalisasi biar total 1
total = ai_score + human_score
if total > 0:
ai_score /= total
human_score /= total
# ---- 2. Analisis blur/noise ----
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
blur_score = cv2.Laplacian(gray, cv2.CV_64F).var()
noise_score = np.std(gray)
# Semakin kecil blur/noise β†’ semakin cenderung AI
blur_factor = 1.0 if blur_score < 100 else 0.0
noise_factor = 1.0 if noise_score < 20 else 0.0
# ---- 3. Cek metadata kamera ----
has_metadata = False
try:
exif = image._getexif()
if exif is not None:
for tag, value in exif.items():
decoded = ExifTags.TAGS.get(tag, tag)
if decoded in ["Make", "Model"]:
has_metadata = True
except:
pass
metadata_factor = 0.0 if has_metadata else 1.0
# ---- 4. Ensemble skor ----
final_score = (
0.6 * ai_score +
0.2 * blur_factor +
0.1 * noise_factor +
0.1 * metadata_factor
)
result = "AI Generated" if final_score > 0.5 else "Foto Asli"
# ---- 5. Hasil detail ----
details = f"""
πŸ” Hasil Deteksi:
{result}
Skor Model AI-detector: {ai_score:.2f}
Skor Human: {human_score:.2f}
Blur Score: {blur_score:.2f}
Noise Score: {noise_score:.2f}
Metadata Kamera: {"Ada" if has_metadata else "Tidak Ada"}
Final Score: {final_score:.2f}
"""
return details
# Gradio UI
demo = gr.Interface(
fn=analyze_image,
inputs=gr.Image(type="pil"),
outputs="text",
title="AI vs Real Image Detector",
description="Upload foto untuk mendeteksi apakah gambar asli atau hasil AI."
)
if __name__ == "__main__":
demo.launch()