-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappCodeBackup.txt
More file actions
359 lines (272 loc) · 12.1 KB
/
appCodeBackup.txt
File metadata and controls
359 lines (272 loc) · 12.1 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# CODE TO DETECT WETHER THE UPLOADED IMAGE IS FAKE OR REAL
# from flask import Flask, request, jsonify, render_template
# import torch
# import torchvision.transforms as transforms
# from PIL import Image
# import io
# import torch.nn as nn
# app = Flask(__name__) # Removed template_folder override
# # Define the Discriminator model
# class Discriminator(nn.Module):
# def __init__(self):
# super(Discriminator, self).__init__()
# self.main = nn.Sequential(
# nn.Conv2d(3, 64, 4, 2, 1, bias=False),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(64, 128, 4, 2, 1, bias=False),
# nn.BatchNorm2d(128),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(128, 256, 4, 2, 1, bias=False),
# nn.BatchNorm2d(256),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(256, 512, 4, 2, 1, bias=False),
# nn.BatchNorm2d(512),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(512, 1, 4, 1, 0, bias=False),
# nn.Sigmoid()
# )
# def forward(self, x):
# return self.main(x)
# # Load the model
# model = Discriminator()
# model.load_state_dict(torch.load("discriminator_model_flask.pth", map_location=torch.device("cpu")))
# model.eval()
# ##################################################################
# # Add at the beginning
# optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)
# criterion = nn.BCELoss() # Binary cross-entropy loss
# @app.route("/feedback", methods=["POST"])
# def feedback():
# data = request.json
# image_id = data.get("image_id")
# true_label = data.get("true_label") # "Real" or "Fake" from user feedback
# # Retrieve the image and prediction from storage (you'd need to implement this)
# stored_image = retrieve_image(image_id)
# input_tensor = preprocess_image(stored_image)
# # Set to training mode
# model.train()
# # Forward pass
# output = model(input_tensor)
# # Convert label to tensor (1 for Fake, 0 for Real)
# target = torch.tensor([[1.0]]) if true_label == "Fake" else torch.tensor([[0.0]])
# # Compute loss
# loss = criterion(output.mean(), target)
# # Backpropagation
# optimizer.zero_grad()
# loss.backward()
# optimizer.step()
# # Save updated model periodically
# torch.save(model.state_dict(), "discriminator_model_flask.pth")
# # Set back to evaluation mode for future predictions
# model.eval()
# return jsonify({"status": "Model updated", "loss": float(loss.item())})
# ###################################################################################################################
# # Define image preprocessing function
# transform = transforms.Compose([
# transforms.Resize((224, 224)),
# transforms.ToTensor(),
# transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # Adjusted for RGB images
# ])
# def preprocess_image(image_bytes):
# image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# return transform(image).unsqueeze(0)
# @app.route("/")
# def home():
# return render_template("index.html") # Make sure this file exists in templates folder
# @app.route("/predict", methods=["POST"])
# def predict():
# if "file" not in request.files:
# return jsonify({"error": "No file uploaded"}), 400
# file = request.files["file"]
# image_bytes = file.read()
# input_tensor = preprocess_image(image_bytes)
# with torch.no_grad():
# # This outputs a 1xCxHxW tensor where C=1 for your model
# output_tensor = model(input_tensor)
# # Get the average prediction value (properly handling the tensor dimensions)
# confidence = output_tensor.mean().item()
# # Since your Discriminator outputs a probability, classify it
# prediction = "Fake" if confidence > 0.5 else "Real"
# return jsonify({"prediction": prediction, "confidence": float(confidence)})
# if __name__ == "__main__":
# app.run(debug=True)
# -------------------------------------------------------------------------------------------------------------------
# FORGED AREA DETECTION CODE
# from flask import Flask, request, jsonify, render_template
# import torch
# import torchvision.transforms as transforms
# from PIL import Image
# import io
# import torch.nn as nn
# import numpy as np
# import cv2
# import base64
# from scipy.spatial.distance import cdist
# app = Flask(__name__)
# class Discriminator(nn.Module):
# def __init__(self):
# super(Discriminator, self).__init__()
# self.main = nn.Sequential(
# nn.Conv2d(3, 64, 4, 2, 1, bias=False),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(64, 128, 4, 2, 1, bias=False),
# nn.BatchNorm2d(128),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(128, 256, 4, 2, 1, bias=False),
# nn.BatchNorm2d(256),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(256, 512, 4, 2, 1, bias=False),
# nn.BatchNorm2d(512),
# nn.LeakyReLU(0.2, inplace=True),
# nn.Conv2d(512, 1, 4, 1, 0, bias=False),
# nn.Sigmoid()
# )
# def forward(self, x):
# features = []
# for i, layer in enumerate(self.main):
# x = layer(x)
# if isinstance(layer, nn.Conv2d):
# features.append(x)
# return x, features
# class CopyMoveDetector:
# def __init__(self, model):
# self.model = model
# self.gradients = []
# self.features = None
# def save_gradient(self, grad):
# self.gradients.append(grad)
# def detect_copied_regions(self, feature_maps, threshold=0.85):
# """
# Detect similar regions in feature maps that might indicate copy-move forgery
# """
# B, C, H, W = feature_maps.shape
# features_reshaped = feature_maps.view(C, H * W).t()
# # Compute similarity matrix
# similarity = torch.mm(features_reshaped, features_reshaped.t())
# similarity = similarity / torch.norm(features_reshaped, dim=1).unsqueeze(0)
# similarity = similarity / torch.norm(features_reshaped, dim=1).unsqueeze(1)
# # Create mask for similar regions
# mask = (similarity > threshold).float()
# mask = mask.view(H, W, H, W)
# # Convert to heatmap
# heatmap = torch.sum(mask, dim=(2, 3))
# heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min() + 1e-8)
# return heatmap.detach().cpu().numpy()
# def generate_forgery_map(self, input_tensor):
# self.gradients = []
# self.features = None
# # Forward pass
# output, features = self.model(input_tensor)
# # Get features from the last convolutional layer
# feature_maps = features[-2] # Using the second-to-last conv layer
# # Detect copy-move regions
# copy_move_map = self.detect_copied_regions(feature_maps)
# # Generate activation map
# feature_maps.requires_grad_(True)
# feature_maps.register_hook(self.save_gradient)
# self.features = feature_maps
# # Get model prediction
# pred = output.mean()
# # Backward pass
# self.model.zero_grad()
# pred.backward()
# if len(self.gradients) > 0:
# gradients = self.gradients[0]
# pooled_gradients = torch.mean(gradients, dim=[0, 2, 3])
# # Weight the channels
# for i in range(self.features.shape[1]):
# self.features[:, i, :, :] *= pooled_gradients[i]
# # Create activation heatmap
# activation_map = torch.mean(self.features, dim=1).squeeze()
# activation_map = torch.relu(activation_map)
# if torch.max(activation_map) > 0:
# activation_map = activation_map / torch.max(activation_map)
# # Combine copy-move map and activation map
# combined_map = 0.7 * copy_move_map + 0.3 * activation_map.detach().cpu().numpy()
# combined_map = (combined_map - combined_map.min()) / (combined_map.max() - combined_map.min() + 1e-8)
# return combined_map
# return copy_move_map
# def apply_forgery_heatmap(image_bytes, heatmap):
# # Read original image
# image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
# image = image.resize((224, 224))
# img_array = np.array(image)
# # Resize heatmap
# heatmap_resized = cv2.resize(heatmap, (224, 224))
# # Create color heatmap
# heatmap_color = cv2.applyColorMap(np.uint8(255 * heatmap_resized), cv2.COLORMAP_JET)
# heatmap_color = cv2.cvtColor(heatmap_color, cv2.COLOR_BGR2RGB)
# # Create binary mask for potentially copied regions
# threshold = 0.5
# binary_mask = (heatmap_resized > threshold).astype(np.uint8)
# # Find connected components
# num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8, cv2.CV_32S)
# # Create visualization
# overlay = img_array.copy()
# alpha = 0.4
# for i in range(1, num_labels): # Skip background (0)
# if stats[i, cv2.CC_STAT_AREA] > 50: # Filter small regions
# mask = (labels == i).astype(np.float32)
# mask = np.expand_dims(mask, axis=-1)
# region_color = heatmap_color * mask
# overlay = (1 - alpha * mask) * overlay + alpha * region_color
# overlay = np.clip(overlay, 0, 255).astype(np.uint8)
# # Draw contours around potential copied regions
# contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(overlay, contours, -1, (255, 255, 255), 1)
# return Image.fromarray(overlay)
# # Load model
# model = Discriminator()
# try:
# model.load_state_dict(torch.load("discriminator_model_flask.pth", map_location=torch.device("cpu")))
# except Exception as e:
# print(f"Error loading model: {e}")
# model.eval()
# # Initialize detector
# detector = CopyMoveDetector(model)
# # Image preprocessing
# transform = transforms.Compose([
# transforms.Resize((224, 224)),
# transforms.ToTensor(),
# transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
# ])
# def preprocess_image(image_bytes):
# image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# return transform(image).unsqueeze(0)
# @app.route("/")
# def home():
# return render_template("index.html")
# @app.route("/detect_forge", methods=["POST"])
# def detect_forge():
# if "file" not in request.files:
# return jsonify({"error": "No file uploaded"}), 400
# file = request.files["file"]
# image_bytes = file.read()
# # Preprocess image
# input_tensor = preprocess_image(image_bytes)
# # Generate forgery map
# forgery_map = detector.generate_forgery_map(input_tensor)
# # Apply visualization
# visualization = apply_forgery_heatmap(image_bytes, forgery_map)
# # Convert to base64
# buffered = io.BytesIO()
# visualization.save(buffered, format="PNG")
# visualization_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
# # Get prediction
# with torch.no_grad():
# output, _ = model(input_tensor)
# confidence = output.mean().item()
# # Calculate metrics
# affected_area = float(np.mean(forgery_map > 0.5) * 100)
# num_regions = len(np.unique(forgery_map > 0.5)) - 1 # Subtract 1 for background
# return jsonify({
# "prediction": "Fake" if confidence > 0.5 else "Real",
# "confidence": float(confidence),
# "heatmap": visualization_base64,
# "affected_area_percentage": affected_area,
# "num_copied_regions": int(num_regions),
# "timestamp": "2025-04-14 19:09:40",
# "analyzed_by": "SahilB2k"
# })
# if __name__ == "__main__":
# app.run(debug=True)