File size: 4,562 Bytes
d28cb94
81b378a
 
 
87bb8c7
81b378a
 
87bb8c7
 
 
96f0952
 
50c46a8
313a6c1
b6079f4
313a6c1
b6079f4
 
 
807ba41
313a6c1
 
 
 
 
87bb8c7
313a6c1
b6079f4
313a6c1
 
81b378a
313a6c1
81b378a
87bb8c7
313a6c1
 
 
 
 
 
 
b6079f4
313a6c1
 
 
 
 
96f0952
 
81b378a
87bb8c7
313a6c1
 
 
87bb8c7
 
f508f88
87bb8c7
 
 
313a6c1
 
 
87bb8c7
 
 
 
 
 
 
81b378a
87bb8c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6079f4
87bb8c7
 
 
 
 
 
313a6c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d386029
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import os
import sys
import zipfile
import requests
import pickle
import torch
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
import cv2
from timm import create_model
import gradio as gr

# -------------------------------
# تحميل كود StyleGAN2
# -------------------------------
if not os.path.exists("stylegan2-ada-pytorch"):
    os.system("git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git")
sys.path.append("stylegan2-ada-pytorch")

# -------------------------------
# تحميل ملفات النماذج المضغوطة
# -------------------------------
stylegan2_url = "https://huggingface.co/lam107/stylegan2-models/resolve/main/stylegan2-ffhq-512x512.zip"
swin_url = "https://huggingface.co/lam107/swin_classifier/resolve/main/best_model_final.pth.zip"

if not os.path.exists("stylegan2-ffhq-512x512.pkl"):
    print("Downloading StyleGAN2 model...")
    r = requests.get(stylegan2_url)
    with open("stylegan2.zip", "wb") as f:
        f.write(r.content)
    with zipfile.ZipFile("stylegan2.zip", 'r') as zip_ref:
        zip_ref.extractall(".")

if not os.path.exists("best_model_final.pth"):
    print("Downloading Swin model...")
    r = requests.get(swin_url)
    with open("swin.zip", "wb") as f:
        f.write(r.content)
    with zipfile.ZipFile("swin.zip", 'r') as zip_ref:
        zip_ref.extractall(".")

# -------------------------------
# تحميل StyleGAN2 Discriminator
# -------------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
with open("stylegan2-ffhq-512x512.pkl", "rb") as f:
    data = pickle.load(f)
    D = data['D'].to(device)
D.eval()

# -------------------------------
# تحميل Swin Transformer
# -------------------------------
class_names = ["real", "fake"]
model = create_model('swin_large_patch4_window12_384', pretrained=False, num_classes=len(class_names))
model.load_state_dict(torch.load("best_model_final.pth", map_location=device))
model = model.to(device)
model.eval()

# -------------------------------
# التدرجات + التصنيف
# -------------------------------
def compute_gradients(model, pil_image):
    transform = transforms.Compose([
        transforms.Resize((512, 512)),
        transforms.ToTensor(),
        transforms.Normalize([0.5], [0.5])
    ])
    image = transform(pil_image.convert("RGB")).unsqueeze(0).to(device).requires_grad_(True)
    c = torch.zeros([image.shape[0], model.c_dim], device=device) if hasattr(model, "c_dim") and model.c_dim > 0 else None
    output = model(image, c)
    loss = -output.mean()
    loss.backward()
    gradients = image.grad.detach().cpu().numpy()
    gradients = np.abs(gradients).mean(axis=1)[0]
    gradients = (gradients - gradients.min()) / (gradients.max() - gradients.min() + 1e-8)
    gradients = (gradients * 255).astype(np.uint8)
    grad_color = cv2.applyColorMap(gradients, cv2.COLORMAP_JET)
    grad_rgb = cv2.cvtColor(grad_color, cv2.COLOR_BGR2RGB)
    return Image.fromarray(grad_rgb)

def swin_classifier(pil_image):
    transform = transforms.Compose([
        transforms.Resize((384, 384)),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406],
                             [0.229, 0.224, 0.225])
    ])
    image = transform(pil_image).unsqueeze(0).to(device)
    with torch.no_grad():
        output = model(image)
        probabilities = torch.softmax(output, dim=1).squeeze().cpu().numpy()
        return {"Real": float(probabilities[0]), "Fake": float(probabilities[1])}

def process_image(pil_img):
    grad_pil = compute_gradients(D, pil_img).resize((384, 384))
    prediction = swin_classifier(grad_pil)
    return grad_pil, prediction

# -------------------------------
# Gradio واجهة
# -------------------------------
with gr.Blocks() as demo:
    gr.Markdown("**💜 Mukhbir: AI Generated Image Detection**")
    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="pil", label="Upload Image")
            clear_button = gr.Button("Clear")
            submit_button = gr.Button("Submit", variant="primary")
        with gr.Column():
            output_image = gr.Image(label="Gradient Image", type="pil")
            output_label = gr.Label(label="Prediction")

    submit_button.click(fn=process_image, inputs=image_input, outputs=[output_image, output_label])
    clear_button.click(fn=lambda: (None, None, None), inputs=None, outputs=[image_input, output_image, output_label])

demo.launch(server_name="0.0.0.0", server_port=7860,ssr_mode=False)