Duncan222 commited on
Commit
5632cc9
·
verified ·
1 Parent(s): e43c848

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ !pip install gradio
2
+ import gradio as gr
3
+ from transformers import AutoImageProcessor, SiglipForImageClassification
4
+ from torch.optim import AdamW
5
+ from PIL import Image
6
+ import torch
7
+ from torch.utils.data import Dataset, DataLoader
8
+ import os
9
+
10
+ # Load model and processor
11
+ model_name = "prithivMLmods/deepfake-detector-model-v1"
12
+ processor = AutoImageProcessor.from_pretrained(model_name)
13
+ model = SiglipForImageClassification.from_pretrained(model_name)
14
+ model.train()
15
+
16
+ # Device setup
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+ model.to(device)
19
+
20
+ # Labels mapping
21
+ id2label = {0: "FAKE", 1: "REAL"}
22
+ label2id = {"FAKE": 0, "REAL": 1}
23
+
24
+ # Optimizer for fine-tuning
25
+ optimizer = AdamW(model.parameters(), lr=5e-6)
26
+
27
+ # Dataset class for single example fine-tuning
28
+ class SingleImageDataset(Dataset):
29
+ def __init__(self, image, label):
30
+ self.image = image
31
+ self.label = label
32
+
33
+ def __len__(self):
34
+ return 1
35
+
36
+ def __getitem__(self, idx):
37
+ inputs = processor(images=self.image, return_tensors="pt")
38
+ inputs = {k: v.squeeze(0) for k,v in inputs.items()}
39
+ inputs['labels'] = torch.tensor(self.label)
40
+ return inputs
41
+
42
+ def fine_tune(image, correct_label):
43
+ dataset = SingleImageDataset(image, correct_label)
44
+ dataloader = DataLoader(dataset, batch_size=1)
45
+
46
+ model.train()
47
+ for epoch in range(1): # just 1 epoch for fast feedback
48
+ for batch in dataloader:
49
+ batch = {k: v.to(device) for k,v in batch.items()}
50
+ outputs = model(**batch)
51
+ loss = outputs.loss
52
+ optimizer.zero_grad()
53
+ loss.backward()
54
+ optimizer.step()
55
+ # Save the updated model locally
56
+ save_path = "./fine_tuned_model"
57
+ os.makedirs(save_path, exist_ok=True)
58
+ model.save_pretrained(save_path)
59
+ processor.save_pretrained(save_path)
60
+ return
61
+
62
+ def predict(image):
63
+ model.eval()
64
+ inputs = processor(images=image, return_tensors="pt").to(device)
65
+ with torch.no_grad():
66
+ outputs = model(**inputs)
67
+ logits = outputs.logits
68
+ pred_class = logits.argmax(-1).item()
69
+ return id2label[pred_class]
70
+
71
+ def inference(image, feedback, correct_label_text):
72
+ if image is None:
73
+ return "Please upload an image.", None
74
+
75
+ prediction = predict(image)
76
+ message = f"Prediction: {prediction}"
77
+
78
+ if feedback == "Wrong":
79
+ if correct_label_text.upper() in label2id:
80
+ correct_label = label2id[correct_label_text.upper()]
81
+ fine_tune(image, correct_label)
82
+ message += f" | Model fine-tuned with correct label: {correct_label_text.upper()}"
83
+ else:
84
+ message += " | Please enter a valid correct label (REAL or FAKE)."
85
+
86
+ return message, image
87
+
88
+ # Gradio UI setup
89
+ title = "Deepfake Detector with Interactive Feedback and Fine-tuning"
90
+
91
+ iface = gr.Interface(
92
+ fn=inference,
93
+ inputs=[
94
+ gr.Image(type="pil", label="Upload Image"),
95
+ gr.Radio(["Correct", "Wrong"], label="Is the prediction correct?", value="Correct"),
96
+ gr.Textbox(label="If Wrong, enter correct label (REAL or FAKE)", lines=1, placeholder="REAL or FAKE")
97
+ ],
98
+ outputs=[
99
+ gr.Textbox(label="Output"),
100
+ gr.Image(type="pil", label="Uploaded Image")
101
+ ],
102
+ title=title,
103
+ live=False,
104
+ allow_flagging="never"
105
+ )
106
+
107
+ iface.launch()