Download app.py from lam107/test: direct link, hf CLI and curl.
- Browser
- Download file 4.56 kB
-
https://huggingface.co/spaces/lam107/test/resolve/main/app.py
- Command line
-
hf download hf://spaces/lam107/test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/lam107/test/resolve/main/app.py
4.56 kB
| 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) | |