Sattfaceee123 commited on
Commit
0ca3bc2
·
verified ·
1 Parent(s): 7845218

Delete app_final.py

Browse files
Files changed (1) hide show
  1. app_final.py +0 -86
app_final.py DELETED
@@ -1,86 +0,0 @@
1
- import gradio as gr
2
- import torch, torch.nn as nn, warnings
3
- from torchvision import transforms
4
- from transformers import EfficientNetModel
5
- from PIL import Image
6
- import numpy as np
7
- import os
8
- warnings.filterwarnings("ignore")
9
-
10
- class FFTBranch(nn.Module):
11
- def __init__(self, out_dim=512):
12
- super().__init__()
13
- self.cnn = nn.Sequential(
14
- nn.Conv2d(1,32,3,padding=1),nn.BatchNorm2d(32),nn.GELU(),nn.MaxPool2d(2),
15
- nn.Conv2d(32,64,3,padding=1),nn.BatchNorm2d(64),nn.GELU(),nn.MaxPool2d(2),
16
- nn.Conv2d(64,128,3,padding=1),nn.BatchNorm2d(128),nn.GELU(),
17
- nn.AdaptiveAvgPool2d((4,4)),
18
- )
19
- self.proj = nn.Sequential(nn.Linear(128*4*4,out_dim),nn.GELU(),nn.Dropout(0.3))
20
- def forward(self, x):
21
- g=x.mean(dim=1,keepdim=True)
22
- fft=torch.fft.fftshift(torch.fft.fft2(g))
23
- mag=torch.log(torch.abs(fft)+1e-8)
24
- mn=mag.flatten(2).min(2)[0].unsqueeze(-1).unsqueeze(-1)
25
- mx=mag.flatten(2).max(2)[0].unsqueeze(-1).unsqueeze(-1)
26
- mag=(mag-mn)/(mx-mn+1e-8)
27
- return self.proj(self.cnn(mag).flatten(1))
28
-
29
- class CNNFFTDetector(nn.Module):
30
- def __init__(self):
31
- super().__init__()
32
- self.cnn=EfficientNetModel.from_pretrained("google/efficientnet-b0")
33
- params=list(self.cnn.parameters())
34
- for i,p in enumerate(params):
35
- p.requires_grad=(i>=int(len(params)*0.6))
36
- self.cnn_proj=nn.Sequential(nn.Linear(1280,512),nn.GELU(),nn.Dropout(0.3))
37
- self.fft=FFTBranch(out_dim=512)
38
- self.classifier=nn.Sequential(
39
- nn.Linear(1024,256),nn.GELU(),nn.Dropout(0.4),
40
- nn.Linear(256,64),nn.GELU(),nn.Linear(64,1))
41
- def forward(self, x):
42
- c=self.cnn_proj(self.cnn(x).pooler_output)
43
- f=self.fft(x)
44
- return self.classifier(torch.cat([c,f],dim=1))
45
-
46
- print("Loading model...")
47
- device = torch.device("cpu")
48
- model = CNNFFTDetector().to(device)
49
- ckpt = torch.load("best.pth", map_location="cpu")
50
- model.load_state_dict(ckpt["model_state"])
51
- model.eval()
52
- print(f"Model ready — {ckpt[\'best_val_acc\']*100:.2f}%")
53
-
54
- tf = transforms.Compose([
55
- transforms.Resize((224,224)),
56
- transforms.ToTensor(),
57
- transforms.Normalize([0.5]*3,[0.5]*3),
58
- ])
59
-
60
- def predict(image):
61
- if image is None:
62
- return {"AI Generated": 0.0, "Real": 1.0}, "Please upload an image"
63
- if isinstance(image, np.ndarray):
64
- image = Image.fromarray(image)
65
- tensor = tf(image).unsqueeze(0).to(device)
66
- with torch.no_grad():
67
- score = torch.sigmoid(model(tensor)).item()
68
- fake_pct = round(score * 100, 1)
69
- real_pct = round((1 - score) * 100, 1)
70
- verdict = f"{\'🔴\' if score >= 0.5 else \'🟢\'} {\'AI Generated\' if score >= 0.5 else \'Real Image\'} | AI: {fake_pct}% | Real: {real_pct}%"
71
- return {"AI Generated": float(score), "Real": float(1-score)}, verdict
72
-
73
- with gr.Blocks(theme=gr.themes.Soft(), title="LunaNet") as demo:
74
- gr.Markdown("# 🌙 LunaNet — AI Image & Deepfake Detector\n**CNN (EfficientNetB0) + FFT** · 91.47% accuracy")
75
- with gr.Row():
76
- with gr.Column():
77
- img_input = gr.Image(type="pil", label="Upload Image")
78
- btn = gr.Button("✦ Analyse", variant="primary", size="lg")
79
- with gr.Column():
80
- label_out = gr.Label(num_top_classes=2, label="Detection Result")
81
- md_out = gr.Markdown()
82
- btn.click(fn=predict, inputs=img_input, outputs=[label_out, md_out])
83
- img_input.upload(fn=predict, inputs=img_input, outputs=[label_out, md_out])
84
- gr.Markdown("---\n**Training data:** CIFAKE · 140k Faces · OpenForensics · Celeb-DF v2 · 46,010 images")
85
-
86
- demo.launch()