ABasiit/DCGAN2
0
1# # gradio_app.py2# import gradio as gr3# from PIL import Image4# import torch5# import torch.nn as nn6# import torchvision.transforms as transforms7# import io8 9# # === Define your trained model architecture ===10# class DCGANDiscriminator(nn.Module):11# def __init__(self):12# super(DCGANDiscriminator, self).__init__()13# self.model = nn.Sequential(14# nn.Conv2d(3, 64, 4, 2, 1),15# nn.LeakyReLU(0.2, inplace=True),16 17# nn.Conv2d(64, 128, 4, 2, 1),18# nn.BatchNorm2d(128),19# nn.LeakyReLU(0.2, inplace=True),20 21# nn.Conv2d(128, 256, 4, 2, 1),22# nn.BatchNorm2d(256),23# nn.LeakyReLU(0.2, inplace=True),24 25# nn.Conv2d(256, 512, 4, 2, 1),26# nn.BatchNorm2d(512),27# nn.LeakyReLU(0.2, inplace=True),28 29# nn.Conv2d(512, 1, 8),30# nn.Sigmoid()31# )32 33# def forward(self, x):34# return self.model(x).view(-1, 1)35 36# # === Load model ===37# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")38# model = DCGANDiscriminator().to(device)39# model.load_state_dict(torch.load("dcgan_discriminator.pth", map_location=device))40# model.eval()41 42# # === Define transform ===43# transform = transforms.Compose([44# transforms.Resize(128),45# transforms.CenterCrop(128),46# transforms.ToTensor(),47# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))48# ])49 50# # === Define prediction function ===51# def predict(image):52# image = image.convert("RGB")53# input_tensor = transform(image).unsqueeze(0).to(device)54# with torch.no_grad():55# output = model(input_tensor)56# confidence = output.item()57# label = "REAL" if confidence > 0.5 else "FAKE"58# return f"Prediction: {label}\nConfidence: {confidence:.4f}"59 60# # === Gradio UI ===61# interface = gr.Interface(62# fn=predict,63# inputs=gr.Image(type="pil"),64# outputs="text",65# title="Deepfake Detector",66# description="Upload a face image and the model will predict whether it's REAL or FAKE."67# )68 69# interface.launch()70# gradio_app.py71# gradio_app.py72# gradio_app.py73# gradio_app.py74# gradio_app.py75# import gradio as gr76# from PIL import Image77# import torch78# import torch.nn as nn79# import torchvision.transforms as transforms80# import io81# import os82# import random83 84# # === Define your trained model architecture ===85# class DCGANDiscriminator(nn.Module):86# def __init__(self):87# super(DCGANDiscriminator, self).__init__()88# self.model = nn.Sequential(89# nn.Conv2d(3, 64, 4, 2, 1),90# nn.LeakyReLU(0.2, inplace=True),91 92# nn.Conv2d(64, 128, 4, 2, 1),93# nn.BatchNorm2d(128),94# nn.LeakyReLU(0.2, inplace=True),95 96# nn.Conv2d(128, 256, 4, 2, 1),97# nn.BatchNorm2d(256),98# nn.LeakyReLU(0.2, inplace=True),99 100# nn.Conv2d(256, 512, 4, 2, 1),101# nn.BatchNorm2d(512),102# nn.LeakyReLU(0.2, inplace=True),103 104# nn.Conv2d(512, 1, 8),105# nn.Sigmoid()106# )107 108# def forward(self, x):109# return self.model(x).view(-1, 1)110 111# # === Load model ===112# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")113# model = DCGANDiscriminator().to(device)114# model.load_state_dict(torch.load("dcgan_discriminator.pth", map_location=device))115# model.eval()116 117# # === Define transform ===118# transform = transforms.Compose([119# transforms.Resize(128),120# transforms.CenterCrop(128),121# transforms.ToTensor(),122# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))123# ])124 125# # === Load a random default image from available ===126# def load_random_image():127# folder = "default_images"128# if os.path.exists(folder):129# images = [f for f in os.listdir(folder) if f.lower().endswith(('jpg', 'jpeg', 'png'))]130# if images:131# selected = random.choice(images)132# return Image.open(os.path.join(folder, selected)).convert("RGB")133# return None134 135# # === Define prediction function ===136# def predict(image):137# image = image.convert("RGB")138# input_tensor = transform(image).unsqueeze(0).to(device)139# with torch.no_grad():140# output = model(input_tensor)141# confidence = output.item()142# label = "REAL" if confidence > 0.5 else "FAKE"143# return f"Prediction: {label}\nConfidence: {confidence:.4f}"144 145# # === Gradio UI ===146# with gr.Blocks() as demo:147# gr.Markdown("# Deepfake Detector")148# gr.Markdown("Upload an image or use a randomly loaded one to detect if it's real or fake.")149 150# image_input = gr.Image(type="pil", label="Input Image")151# output = gr.Textbox(label="Prediction")152# submit = gr.Button("Submit")153# clear = gr.Button("Clear")154 155# demo.load(fn=load_random_image, inputs=None, outputs=image_input)156# submit.click(fn=predict, inputs=image_input, outputs=output)157# clear.click(fn=lambda: (load_random_image(), ""), inputs=None, outputs=[image_input, output])158 159# gr.Markdown("Each refresh loads a random image from the `default_images/` folder.")160 161# demo.launch(share=True)162 163# gradio_app.py164# gradio_app.py165import gradio as gr166from PIL import Image167import torch168import torch.nn as nn169import torchvision.transforms as transforms170import io171import os172import random173 174# === Define your trained model architecture ===175class DCGANDiscriminator(nn.Module):176 def __init__(self):177 super(DCGANDiscriminator, self).__init__()178 self.model = nn.Sequential(179 nn.Conv2d(3, 64, 4, 2, 1),180 nn.LeakyReLU(0.2, inplace=True),181 182 nn.Conv2d(64, 128, 4, 2, 1),183 nn.BatchNorm2d(128),184 nn.LeakyReLU(0.2, inplace=True),185 186 nn.Conv2d(128, 256, 4, 2, 1),187 nn.BatchNorm2d(256),188 nn.LeakyReLU(0.2, inplace=True),189 190 nn.Conv2d(256, 512, 4, 2, 1),191 nn.BatchNorm2d(512),192 nn.LeakyReLU(0.2, inplace=True),193 194 nn.Conv2d(512, 1, 8),195 nn.Sigmoid()196 )197 198 def forward(self, x):199 return self.model(x).view(-1, 1)200 201# === Load model ===202device = torch.device("cuda" if torch.cuda.is_available() else "cpu")203model = DCGANDiscriminator().to(device)204model.load_state_dict(torch.load("dcgan_discriminator.pth", map_location=device))205model.eval()206 207# === Define transform ===208transform = transforms.Compose([209 transforms.Resize(128),210 transforms.CenterCrop(128),211 transforms.ToTensor(),212 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))213])214 215# === Load a random default image from available ===216def load_random_image():217 folder = "default_images"218 if os.path.exists(folder):219 images = [f for f in os.listdir(folder) if f.lower().endswith(('jpg', 'jpeg', 'png'))]220 if images:221 selected = random.choice(images)222 return Image.open(os.path.join(folder, selected)).convert("RGB")223 return None224 225# === Define prediction function ===226def predict(image):227 image = image.convert("RGB")228 input_tensor = transform(image).unsqueeze(0).to(device)229 with torch.no_grad():230 output = model(input_tensor)231 confidence = output.item()232 label = "REAL" if confidence > 0.5 else "FAKE"233 return f"Prediction: {label}\nConfidence: {confidence:.4f}"234 235# === Gradio UI ===236with gr.Blocks() as demo:237 gr.Markdown("# Deepfake Detector")238 gr.Markdown("Upload an image or use a randomly loaded one to detect if it's real or fake.")239 240 image_state = gr.State()241 image_input = gr.Image(type="pil", label="Input Image")242 output = gr.Textbox(label="Prediction")243 submit = gr.Button("Submit")244 clear = gr.Button("Clear")245 246 def assign_random_image():247 return load_random_image()248 249 def set_image_and_clear_output(image):250 return image, ""251 252 demo.load(fn=assign_random_image, inputs=None, outputs=image_state)253 image_state.change(fn=set_image_and_clear_output, inputs=image_state, outputs=[image_input, output])254 submit.click(fn=predict, inputs=image_input, outputs=output)255 clear.click(fn=lambda: (load_random_image(), ""), inputs=None, outputs=[image_input, output])256 257 gr.Markdown("Each refresh loads a random image from the `default_images/` folder.")258 259demo.launch(share=True)260 261 