Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import zipfile
|
| 4 |
+
import requests
|
| 5 |
+
import pickle
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torchvision.transforms as transforms
|
| 10 |
+
import cv2
|
| 11 |
+
from timm import create_model
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
# ุชุญู
ูู ููุฏ StyleGAN2
|
| 15 |
+
if not os.path.exists("stylegan2-ada-pytorch"):
|
| 16 |
+
os.system("git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git")
|
| 17 |
+
sys.path.append("stylegan2-ada-pytorch")
|
| 18 |
+
|
| 19 |
+
# ุชุญู
ูู ู
ูู zip ู
ู HF model repo
|
| 20 |
+
ZIP_URL = "https://huggingface.co/lam107/stylegan2-models/resolve/main/stylegan2-ffhq-512x512.zip"
|
| 21 |
+
ZIP_PATH = "stylegan2-ffhq-512x512.zip"
|
| 22 |
+
PKL_PATH = "stylegan2-ffhq-512x512.pkl"
|
| 23 |
+
|
| 24 |
+
if not os.path.exists(PKL_PATH):
|
| 25 |
+
print("Downloading StyleGAN2 model...")
|
| 26 |
+
r = requests.get(ZIP_URL)
|
| 27 |
+
with open(ZIP_PATH, "wb") as f:
|
| 28 |
+
f.write(r.content)
|
| 29 |
+
print("Extracting...")
|
| 30 |
+
with zipfile.ZipFile(ZIP_PATH, 'r') as zip_ref:
|
| 31 |
+
zip_ref.extractall(".")
|
| 32 |
+
|
| 33 |
+
# ุชุฌููุฒ ุงูุฌูุงุฒ
|
| 34 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 35 |
+
|
| 36 |
+
# ุชุญู
ูู Discriminator
|
| 37 |
+
with open(PKL_PATH, "rb") as f:
|
| 38 |
+
data = pickle.load(f)
|
| 39 |
+
D = data['D'].to(device)
|
| 40 |
+
D.eval()
|
| 41 |
+
|
| 42 |
+
# ุชุญู
ูู Swin model
|
| 43 |
+
class_names = ["real", "fake"]
|
| 44 |
+
model = create_model('swin_large_patch4_window12_384', pretrained=False, num_classes=len(class_names))
|
| 45 |
+
model.load_state_dict(torch.load("best_model_final.pth", map_location=device))
|
| 46 |
+
model = model.to(device)
|
| 47 |
+
model.eval()
|
| 48 |
+
|
| 49 |
+
def compute_gradients(model, pil_image):
|
| 50 |
+
transform = transforms.Compose([
|
| 51 |
+
transforms.Resize((512, 512)),
|
| 52 |
+
transforms.ToTensor(),
|
| 53 |
+
transforms.Normalize([0.5], [0.5])
|
| 54 |
+
])
|
| 55 |
+
image = transform(pil_image.convert("RGB")).unsqueeze(0).to(device).requires_grad_(True)
|
| 56 |
+
|
| 57 |
+
c = torch.zeros([image.shape[0], model.c_dim], device=device) if hasattr(model, "c_dim") and model.c_dim > 0 else None
|
| 58 |
+
output = model(image, c)
|
| 59 |
+
|
| 60 |
+
loss = -output.mean()
|
| 61 |
+
loss.backward()
|
| 62 |
+
|
| 63 |
+
gradients = image.grad.detach().cpu().numpy()
|
| 64 |
+
gradients = np.abs(gradients).mean(axis=1)[0]
|
| 65 |
+
gradients = (gradients - gradients.min()) / (gradients.max() - gradients.min() + 1e-8)
|
| 66 |
+
gradients = (gradients * 255).astype(np.uint8)
|
| 67 |
+
|
| 68 |
+
grad_color = cv2.applyColorMap(gradients, cv2.COLORMAP_JET)
|
| 69 |
+
grad_rgb = cv2.cvtColor(grad_color, cv2.COLOR_BGR2RGB)
|
| 70 |
+
|
| 71 |
+
return Image.fromarray(grad_rgb)
|
| 72 |
+
|
| 73 |
+
def swin_classifier(pil_image):
|
| 74 |
+
transform = transforms.Compose([
|
| 75 |
+
transforms.Resize((384, 384)),
|
| 76 |
+
transforms.ToTensor(),
|
| 77 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 78 |
+
[0.229, 0.224, 0.225])
|
| 79 |
+
])
|
| 80 |
+
image = transform(pil_image).unsqueeze(0).to(device)
|
| 81 |
+
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
output = model(image)
|
| 84 |
+
probabilities = torch.softmax(output, dim=1).squeeze().cpu().numpy()
|
| 85 |
+
return {"Real": float(probabilities[0]), "Fake": float(probabilities[1])}
|
| 86 |
+
|
| 87 |
+
def process_image(pil_img):
|
| 88 |
+
grad_pil = compute_gradients(D, pil_img).resize((384, 384))
|
| 89 |
+
prediction = swin_classifier(grad_pil)
|
| 90 |
+
return grad_pil, prediction
|
| 91 |
+
|
| 92 |
+
# ูุงุฌูุฉ Gradio
|
| 93 |
+
def main():
|
| 94 |
+
with gr.Blocks() as demo:
|
| 95 |
+
gr.Markdown("**๐ Mukhbir: AI Generated Image Detection**")
|
| 96 |
+
with gr.Row():
|
| 97 |
+
with gr.Column():
|
| 98 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
| 99 |
+
clear_button = gr.Button("Clear")
|
| 100 |
+
submit_button = gr.Button("Submit", variant="primary")
|
| 101 |
+
with gr.Column():
|
| 102 |
+
output_image = gr.Image(label="Gradient Image", type="pil")
|
| 103 |
+
output_label = gr.Label(label="Prediction")
|
| 104 |
+
|
| 105 |
+
submit_button.click(fn=process_image, inputs=image_input, outputs=[output_image, output_label])
|
| 106 |
+
clear_button.click(fn=lambda: (None, None, None), inputs=None, outputs=[image_input, output_image, output_label])
|
| 107 |
+
|
| 108 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
main()
|