Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import pipeline | |
| from PIL import Image | |
| import cv2 | |
| import numpy as np | |
| # ========================= | |
| # Preprocessing function | |
| # ========================= | |
| def preprocess_image(img_path): | |
| img = cv2.imread(img_path) | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| img = cv2.resize(img, (512, 512)) | |
| img = cv2.GaussianBlur(img, (3, 3), 0) # Kurangi noise | |
| return Image.fromarray(img) | |
| # ========================= | |
| # Load models | |
| # ========================= | |
| detector_ai = pipeline("image-classification", model="umm-maybe/AI-image-detector") | |
| detector_resnet = pipeline("image-classification", model="microsoft/resnet-50") | |
| # ========================= | |
| # Detection Function | |
| # ========================= | |
| def detect_image(img): | |
| # Preprocess | |
| img = preprocess_image(img) | |
| # Run AI detector | |
| ai_results = detector_ai(img) | |
| ai_dict = {res['label']: res['score'] for res in ai_results} | |
| human_score = ai_dict.get("human", 0) | |
| artificial_score = ai_dict.get("artificial", 0) | |
| # Run ResNet for natural object cross-check | |
| resnet_results = detector_resnet(img) | |
| top_resnet = resnet_results[0] # ambil label dengan skor tertinggi | |
| # ========================= | |
| # Decision Rule with Threshold | |
| # ========================= | |
| if artificial_score > 0.75: | |
| verdict = "π£ AI-generated" | |
| elif human_score > 0.65: | |
| verdict = "π’ Foto Asli" | |
| else: | |
| verdict = "β οΈ Tidak Pasti" | |
| # Extra check: kalau AI-detector bilang AI tapi ResNet yakin objek nyata | |
| if verdict == "π£ AI-generated" and top_resnet['score'] > 0.70: | |
| verdict = "β οΈ Tidak Pasti (deteksi objek nyata tinggi)" | |
| # ========================= | |
| # Output | |
| # ========================= | |
| summary = f""" | |
| π Ringkasan Deteksi: | |
| πΉ AI Detector: | |
| - Human: {human_score:.2%} | |
| - Artificial: {artificial_score:.2%} | |
| πΉ ResNet50: | |
| - Top Label: {top_resnet['label']} ({top_resnet['score']:.2%}) | |
| === HASIL AKHIR === | |
| {verdict} | |
| """ | |
| return summary | |
| # ========================= | |
| # Gradio App | |
| # ========================= | |
| demo = gr.Interface( | |
| fn=detect_image, | |
| inputs=gr.Image(type="filepath"), | |
| outputs="text", | |
| title="Deteksi AI vs Foto Asli", | |
| description="Upload foto untuk mendeteksi apakah gambar AI-generated atau Foto Asli. Menggunakan threshold + preprocessing." | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |