MetaQu's picture
Update app.py
cc2b650 verified
raw
history blame
2.45 kB
import gradio as gr
from transformers import pipeline
from PIL import Image, ExifTags
import numpy as np
import cv2
import io
# 1. Load model AI detector dari HuggingFace
detector = pipeline("image-classification", model="microsoft/resnet-50")
# Fungsi hitung noise (variansi Laplacian)
def estimate_noise(img):
gray = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
return cv2.Laplacian(gray, cv2.CV_64F).var()
# Fungsi cek metadata kamera
def has_camera_metadata(img):
try:
exif = img._getexif()
if exif is not None:
for tag, value in exif.items():
tag_name = ExifTags.TAGS.get(tag, tag)
if "Model" in tag_name or "Make" in tag_name:
return True
except:
pass
return False
# Fungsi utama deteksi hybrid
def detect_image(img):
# Resize ke 224x224 untuk model
img_resized = img.resize((224,224))
# Prediksi AI-detector HuggingFace
preds = detector(img_resized)
ai_score = 0
for p in preds:
if "artificial" in p['label'].lower() or "fake" in p['label'].lower():
ai_score += p['score'] * 100
elif "human" in p['label'].lower() or "real" in p['label'].lower():
ai_score += (1 - p['score']) * 100
ai_score = max(0, min(100, ai_score)) # jaga range
real_score = 100 - ai_score
# Hybrid Adjustment
# 1. Metadata kamera โ†’ tambah bobot real
if has_camera_metadata(img):
real_score += 30
ai_score -= 30
# 2. Noise โ†’ kalau noise tinggi berarti asli
noise = estimate_noise(img)
if noise > 500: # ambang noise
real_score += 20
ai_score -= 20
# Normalisasi agar tetap 0-100
real_score = max(0, min(100, real_score))
ai_score = 100 - real_score
# Final Output
if real_score == 100:
label = "๐Ÿ–ผ๏ธ Gambar ini ASLI 100%"
elif ai_score == 100:
label = "๐Ÿ–ผ๏ธ Gambar ini HASIL AI 100%"
else:
label = f"๐Ÿ–ผ๏ธ Gambar ini {ai_score:.2f}% AI / {real_score:.2f}% Asli"
return label, f"Noise Score: {noise:.2f} | Metadata Kamera: {'Ada' if has_camera_metadata(img) else 'Tidak'}"
# Gradio UI
demo = gr.Interface(
fn=detect_image,
inputs=gr.Image(type="pil"),
outputs=[gr.Textbox(label="Hasil Deteksi"), gr.Textbox(label="Analisis Teknis")],
title="Hybrid AI vs Real Image Detector"
)
if __name__ == "__main__":
demo.launch()