LPX commited on
Commit
67f3560
·
1 Parent(s): 387e421

♻️ refactor(app): code cleanup

Browse files

- removed unused import: warnings
- added logging configuration
-【docs】modified logging level
-【refactor】renamed old logging config to current logging module
- optimized importance of models by introducing model hook configuration modes
-【docs】map classes of various models
-【feat】move and refactor models into reusable function
- modified logic containment
- reorganized and refactored prediction logic
- moved all augmentation related function to util
- clarified all parameters to be consistent
-【refactor】modified function name consistent
▪️️ feat(app): new model prediction logic with gpu decorator
-【refactor】added model index to output [[model id, model name, class a confidence, class b confidence, label] recommended output]

---·

+ refactor(file management): code cleanup

- remove previous unused paths
- moved function into utils

Files changed (2) hide show
  1. app.py +72 -240
  2. utils/utils.py +25 -0
app.py CHANGED
@@ -5,284 +5,116 @@ from torchvision import transforms
5
  import torch
6
  from PIL import Image
7
  import numpy as np
8
- # from utils.goat import call_inference / announcement soon
9
  import io
10
- import warnings
 
 
 
 
 
 
11
 
12
- # Suppress warnings
13
- warnings.filterwarnings("ignore", category=UserWarning, message="Using a slow image processor as `use_fast` is unset")
14
 
15
  # Ensure using GPU if available
16
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
 
18
- # Load the first model and processor
19
- image_processor_1 = AutoImageProcessor.from_pretrained("haywoodsloan/ai-image-detector-deploy", use_fast=True)
20
- model_1 = Swinv2ForImageClassification.from_pretrained("haywoodsloan/ai-image-detector-deploy")
21
- model_1 = model_1.to(device)
22
- clf_1 = pipeline(model=model_1, task="image-classification", image_processor=image_processor_1, device=device)
23
 
24
- # Load the second model
25
- model_2_path = "Heem2/AI-vs-Real-Image-Detection"
26
- clf_2 = pipeline("image-classification", model=model_2_path, device=device)
 
 
 
 
 
 
27
 
28
- # Load additional models
29
- models = ["Organika/sdxl-detector", "cmckinle/sdxl-flux-detector"]
30
- feature_extractor_3 = AutoFeatureExtractor.from_pretrained(models[0], device=device)
31
- model_3 = AutoModelForImageClassification.from_pretrained(models[0]).to(device)
32
- feature_extractor_4 = AutoFeatureExtractor.from_pretrained(models[1], device=device)
33
- model_4 = AutoModelForImageClassification.from_pretrained(models[1]).to(device)
 
 
34
 
35
- # Load the second model
36
- model_5_path = "prithivMLmods/Deep-Fake-Detector-v2-Model"
37
- clf_5 = pipeline("image-classification", model=model_5_path, device=device)
 
 
 
38
 
39
- model_5b_path = "prithivMLmods/Deepfake-Detection-Exp-02-22"
40
- clf_5b = pipeline("image-classification", model=model_5b_path, device=device)
41
 
42
- # Define class names for all models
43
- class_names_1 = ['artificial', 'real']
44
- class_names_2 = ['AI Image', 'Real Image']
45
- labels_3 = ['AI', 'Real']
46
- labels_4 = ['AI', 'Real']
47
- class_names_5 = ['Realism', 'Deepfake']
48
- class_names_5b = ['Real', 'Deepfake']
49
 
50
- def softmax(vector):
51
- e = np.exp(vector - np.max(vector)) # for numerical stability
52
- return e / e.sum()
53
 
54
- def augment_image(img_pil):
55
- # Example augmentation: horizontal flip
56
- transform_flip = transforms.Compose([
57
- transforms.RandomHorizontalFlip(p=1.0) # Flip the image horizontally with probability 1.0
58
- ])
59
-
60
- # Example augmentation: rotation
61
- transform_rotate = transforms.Compose([
62
- transforms.RandomRotation(degrees=(90, 90)) # Rotate the image by 90 degrees
63
- ])
64
-
65
- augmented_img_flip = transform_flip(img_pil)
66
- augmented_img_rotate = transform_rotate(img_pil)
67
-
68
- return augmented_img_flip, augmented_img_rotate
69
 
70
- # def convert_pil_to_bytes(img_pil):
71
- # img_byte_arr = io.BytesIO()
72
- # img_pil.save(img_byte_arr, format='PNG')
73
- # img_byte_arr = img_byte_arr.getvalue()
74
- # return img_byte_arr
75
 
76
- def convert_pil_to_bytes(image, format='JPEG'):
77
- img_byte_arr = io.BytesIO()
78
- image.save(img_byte_arr, format=format)
79
- img_byte_arr = img_byte_arr.getvalue()
80
- return img_byte_arr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  @spaces.GPU(duration=10)
83
  def predict_image(img, confidence_threshold):
84
- # Ensure the image is a PIL Image
85
  if not isinstance(img, Image.Image):
86
  raise ValueError(f"Expected a PIL Image, but got {type(img)}")
87
-
88
- # Convert the image to RGB if not already
89
  if img.mode != 'RGB':
90
  img_pil = img.convert('RGB')
91
  else:
92
  img_pil = img
93
-
94
- # Resize the image
95
  img_pil = transforms.Resize((256, 256))(img_pil)
96
- # Size 224 for vits models
97
  img_pilvits = transforms.Resize((224, 224))(img_pil)
98
-
99
- # Predict using the first model
100
- try:
101
- prediction_1 = clf_1(img_pil)
102
- result_1 = {pred['label']: pred['score'] for pred in prediction_1}
103
- result_1output = [1, 'SwinV2-base', result_1['real'], result_1['artificial']]
104
- print(result_1output)
105
- # Ensure the result dictionary contains all class names
106
- for class_name in class_names_1:
107
- if class_name not in result_1:
108
- result_1[class_name] = 0.0
109
- # Check if either class meets the confidence threshold
110
- if result_1['artificial'] >= confidence_threshold:
111
- label_1 = f"AI, Confidence: {result_1['artificial']:.4f}"
112
- result_1output += ['AI']
113
- elif result_1['real'] >= confidence_threshold:
114
- label_1 = f"Real, Confidence: {result_1['real']:.4f}"
115
- result_1output += ['REAL']
116
- else:
117
- label_1 = "Uncertain Classification"
118
- result_1output += ['UNCERTAIN']
119
 
120
- except Exception as e:
121
- label_1 = f"Error: {str(e)}"
122
- print(result_1output)
123
- # Predict using the second model
124
- try:
125
- prediction_2 = clf_2(img_pilvits)
126
- result_2 = {pred['label']: pred['score'] for pred in prediction_2}
127
- result_2output = [2, 'ViT-base Classifer', result_2['Real Image'], result_2['AI Image']]
128
- print(result_2output)
129
- # Ensure the result dictionary contains all class names
130
- for class_name in class_names_2:
131
- if class_name not in result_2:
132
- result_2[class_name] = 0.0
133
- # Check if either class meets the confidence threshold
134
- if result_2['AI Image'] >= confidence_threshold:
135
- label_2 = f"AI, Confidence: {result_2['AI Image']:.4f}"
136
- result_2output += ['AI']
137
- elif result_2['Real Image'] >= confidence_threshold:
138
- label_2 = f"Real, Confidence: {result_2['Real Image']:.4f}"
139
- result_2output += ['REAL']
140
- else:
141
- label_2 = "Uncertain Classification"
142
- result_2output += ['UNCERTAIN']
143
- except Exception as e:
144
- label_2 = f"Error: {str(e)}"
145
-
146
- # Predict using the third model with softmax
147
- try:
148
- inputs_3 = feature_extractor_3(img_pil, return_tensors="pt").to(device)
149
- with torch.no_grad():
150
- outputs_3 = model_3(**inputs_3)
151
- logits_3 = outputs_3.logits
152
- probabilities_3 = softmax(logits_3.cpu().numpy()[0])
153
- result_3 = {
154
- labels_3[1]: float(probabilities_3[1]), # Real
155
- labels_3[0]: float(probabilities_3[0]) # AI
156
- }
157
- result_3output = [3, 'SDXL-Trained', float(probabilities_3[1]), float(probabilities_3[0])]
158
- print(result_3output)
159
- # Ensure the result dictionary contains all class names
160
- for class_name in labels_3:
161
- if class_name not in result_3:
162
- result_3[class_name] = 0.0
163
- # Check if either class meets the confidence threshold
164
- if result_3['AI'] >= confidence_threshold:
165
- label_3 = f"AI, Confidence: {result_3['AI']:.4f}"
166
- result_3output += ['AI']
167
- elif result_3['Real'] >= confidence_threshold:
168
- label_3 = f"Real, Confidence: {result_3['Real']:.4f}"
169
- result_3output += ['REAL']
170
- else:
171
- label_3 = "Uncertain Classification"
172
- result_3output += ['UNCERTAIN']
173
- except Exception as e:
174
- label_3 = f"Error: {str(e)}"
175
-
176
- # Predict using the fourth model with softmax
177
- try:
178
- inputs_4 = feature_extractor_4(img_pil, return_tensors="pt").to(device)
179
- with torch.no_grad():
180
- outputs_4 = model_4(**inputs_4)
181
- logits_4 = outputs_4.logits
182
- probabilities_4 = softmax(logits_4.cpu().numpy()[0])
183
- result_4 = {
184
- labels_4[1]: float(probabilities_4[1]), # Real
185
- labels_4[0]: float(probabilities_4[0]) # AI
186
- }
187
- result_4output = [4, 'SDXL + FLUX', float(probabilities_4[1]), float(probabilities_4[0])]
188
- print(result_4)
189
- # Ensure the result dictionary contains all class names
190
- for class_name in labels_4:
191
- if class_name not in result_4:
192
- result_4[class_name] = 0.0
193
- # Check if either class meets the confidence threshold
194
- if result_4['AI'] >= confidence_threshold:
195
- label_4 = f"AI, Confidence: {result_4['AI']:.4f}"
196
- result_4output += ['AI']
197
- elif result_4['Real'] >= confidence_threshold:
198
- label_4 = f"Real, Confidence: {result_4['Real']:.4f}"
199
- result_4output += ['REAL']
200
- else:
201
- label_4 = "Uncertain Classification"
202
- result_4output += ['UNCERTAIN']
203
- except Exception as e:
204
- label_4 = f"Error: {str(e)}"
205
-
206
- try:
207
- prediction_5 = clf_5(img_pilvits)
208
- result_5 = {pred['label']: pred['score'] for pred in prediction_5}
209
- result_5output = [5, 'ViT-base Newcomer', result_5['Realism'], result_5['Deepfake']]
210
-
211
- # Ensure the result dictionary contains all class names
212
- for class_name in class_names_5:
213
- if class_name not in result_5:
214
- result_5[class_name] = 0.0
215
- # Check if either class meets the confidence threshold
216
- if result_5['Deepfake'] >= confidence_threshold:
217
- label_5 = f"AI, Confidence: {result_5['Deepfake']:.4f}"
218
- result_5output += ['AI']
219
- elif result_5['Real Image'] >= confidence_threshold:
220
- label_5 = f"Real, Confidence: {result_5['Realism']:.4f}"
221
- result_5output += ['REAL']
222
- else:
223
- label_5 = "Uncertain Classification"
224
- result_5output += ['UNCERTAIN']
225
- except Exception as e:
226
- label_5 = f"Error: {str(e)}"
227
-
228
- print(result_5output)
229
-
230
- try:
231
- prediction_5b = clf_5b(img_pilvits)
232
- result_5b = {pred['label']: pred['score'] for pred in prediction_5b}
233
- result_5boutput = [6, 'ViT-base Newcomer', result_5b['Real'], result_5b['Deepfake']]
234
-
235
- # Ensure the result dictionary contains all class names
236
- for class_name in class_names_5b:
237
- if class_name not in result_5b:
238
- result_5b[class_name] = 0.0
239
- # Check if either class meets the confidence threshold
240
- if result_5b['Deepfake'] >= confidence_threshold:
241
- label_5b = f"AI, Confidence: {result_5b['Deepfake']:.4f}"
242
- result_5boutput += ['AI']
243
- elif result_5b['Real Image'] >= confidence_threshold:
244
- label_5b = f"Real, Confidence: {result_5b['Real']:.4f}"
245
- result_5boutput += ['REAL']
246
- else:
247
- label_5b = "Uncertain Classification"
248
- result_5boutput += ['UNCERTAIN']
249
- except Exception as e:
250
- label_5b = f"Error: {str(e)}"
251
-
252
- print(result_5boutput)
253
-
254
-
255
- # try:
256
- # result_5output = [5, 'TBA', 0.0, 0.0, 'MAINTENANCE']
257
- # img_bytes = convert_pil_to_bytes(img_pil)
258
- # # print(img)
259
- # # print(img_bytes)
260
- # response5_raw = call_inference(img)
261
- # print(response5_raw)
262
- # response5 = response5_raw
263
- # print(response5)
264
- # label_5 = f"Result: {response5}"
265
-
266
- # except Exception as e:
267
- # label_5 = f"Error: {str(e)}"
268
-
269
 
270
- # Combine results
271
  combined_results = {
272
  "SwinV2/detect": label_1,
273
  "ViT/AI-vs-Real": label_2,
274
  "Swin/SDXL": label_3,
275
  "Swin/SDXL-FLUX": label_4,
276
  "prithivMLmods": label_5,
277
- "prithivMLmods-2-22": label_5b
278
  }
279
- # Generate HTML content
280
-
281
- combined_outputs = [ result_1output, result_2output, result_3output, result_4output, result_5output, result_5boutput ]
282
- # html_content = generate_results_html(combined_outputs)
283
 
 
284
  return img_pil, combined_outputs
285
 
 
286
  # Define a function to generate the HTML content
287
  # Define a function to generate the HTML content
288
  def generate_results_html(results):
 
5
  import torch
6
  from PIL import Image
7
  import numpy as np
 
8
  import io
9
+ import logging
10
+ from utils.utils import softmax, augment_image, convert_pil_to_bytes
11
+
12
+
13
+ # Configure logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
 
 
 
17
 
18
  # Ensure using GPU if available
19
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
20
 
 
 
 
 
 
21
 
22
+ # Model paths and class names
23
+ MODEL_PATHS = {
24
+ "model_1": "haywoodsloan/ai-image-detector-deploy",
25
+ "model_2": "Heem2/AI-vs-Real-Image-Detection",
26
+ "model_3": "Organika/sdxl-detector",
27
+ "model_4": "cmckinle/sdxl-flux-detector",
28
+ "model_5": "prithivMLmods/Deep-Fake-Detector-v2-Model",
29
+ "model_5b": "prithivMLmods/Deepfake-Detection-Exp-02-22"
30
+ }
31
 
32
+ CLASS_NAMES = {
33
+ "model_1": ['artificial', 'real'],
34
+ "model_2": ['AI Image', 'Real Image'],
35
+ "model_3": ['AI', 'Real'],
36
+ "model_4": ['AI', 'Real'],
37
+ "model_5": ['Realism', 'Deepfake'],
38
+ "model_5b": ['Real', 'Deepfake']
39
+ }
40
 
41
+ # Load models and processors
42
+ def load_models():
43
+ image_processor_1 = AutoImageProcessor.from_pretrained(MODEL_PATHS["model_1"], use_fast=True)
44
+ model_1 = Swinv2ForImageClassification.from_pretrained(MODEL_PATHS["model_1"])
45
+ model_1 = model_1.to(device)
46
+ clf_1 = pipeline(model=model_1, task="image-classification", image_processor=image_processor_1, device=device)
47
 
48
+ clf_2 = pipeline("image-classification", model=MODEL_PATHS["model_2"], device=device)
 
49
 
50
+ feature_extractor_3 = AutoFeatureExtractor.from_pretrained(MODEL_PATHS["model_3"], device=device)
51
+ model_3 = AutoModelForImageClassification.from_pretrained(MODEL_PATHS["model_3"]).to(device)
 
 
 
 
 
52
 
53
+ feature_extractor_4 = AutoFeatureExtractor.from_pretrained(MODEL_PATHS["model_4"], device=device)
54
+ model_4 = AutoModelForImageClassification.from_pretrained(MODEL_PATHS["model_4"]).to(device)
 
55
 
56
+ clf_5 = pipeline("image-classification", model=MODEL_PATHS["model_5"], device=device)
57
+ clf_5b = pipeline("image-classification", model=MODEL_PATHS["model_5b"], device=device)
58
+
59
+ return clf_1, clf_2, feature_extractor_3, model_3, feature_extractor_4, model_4, clf_5, clf_5b
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ clf_1, clf_2, feature_extractor_3, model_3, feature_extractor_4, model_4, clf_5, clf_5b = load_models()
 
 
 
 
62
 
63
+ @spaces.GPU(duration=10)
64
+ def predict_with_model(img_pil, clf, class_names, confidence_threshold, model_name, model_id):
65
+ try:
66
+ prediction = clf(img_pil)
67
+ result = {pred['label']: pred['score'] for pred in prediction}
68
+ result_output = [model_id, model_name, result.get(class_names[1], 0.0), result.get(class_names[0], 0.0)]
69
+ logger.info(result_output)
70
+ for class_name in class_names:
71
+ if class_name not in result:
72
+ result[class_name] = 0.0
73
+ if result[class_names[0]] >= confidence_threshold:
74
+ label = f"AI, Confidence: {result[class_names[0]]:.4f}"
75
+ result_output.append('AI')
76
+ elif result[class_names[1]] >= confidence_threshold:
77
+ label = f"Real, Confidence: {result[class_names[1]]:.4f}"
78
+ result_output.append('REAL')
79
+ else:
80
+ label = "Uncertain Classification"
81
+ result_output.append('UNCERTAIN')
82
+ except Exception as e:
83
+ label = f"Error: {str(e)}"
84
+ return label, result_output
85
 
86
  @spaces.GPU(duration=10)
87
  def predict_image(img, confidence_threshold):
 
88
  if not isinstance(img, Image.Image):
89
  raise ValueError(f"Expected a PIL Image, but got {type(img)}")
 
 
90
  if img.mode != 'RGB':
91
  img_pil = img.convert('RGB')
92
  else:
93
  img_pil = img
 
 
94
  img_pil = transforms.Resize((256, 256))(img_pil)
 
95
  img_pilvits = transforms.Resize((224, 224))(img_pil)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ label_1, result_1output = predict_with_model(img_pil, clf_1, CLASS_NAMES["model_1"], confidence_threshold, "SwinV2-base", 1)
98
+ label_2, result_2output = predict_with_model(img_pilvits, clf_2, CLASS_NAMES["model_2"], confidence_threshold, "ViT-base Classifer", 2)
99
+ label_3, result_3output = predict_with_model(img_pil, feature_extractor_3, model_3, CLASS_NAMES["model_3"], confidence_threshold, "SDXL-Trained", 3)
100
+ label_4, result_4output = predict_with_model(img_pil, feature_extractor_4, model_4, CLASS_NAMES["model_4"], confidence_threshold, "SDXL + FLUX", 4)
101
+ label_5, result_5output = predict_with_model(img_pilvits, clf_5, CLASS_NAMES["model_5"], confidence_threshold, "ViT-base Newcomer", 5)
102
+ label_5b, result_5boutput = predict_with_model(img_pilvits, clf_5b, CLASS_NAMES["model_5b"], confidence_threshold, "ViT-base Newcomer", 6)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
 
104
  combined_results = {
105
  "SwinV2/detect": label_1,
106
  "ViT/AI-vs-Real": label_2,
107
  "Swin/SDXL": label_3,
108
  "Swin/SDXL-FLUX": label_4,
109
  "prithivMLmods": label_5,
110
+ "prithivMLmods-2-22": label_5b
111
  }
112
+ print(combined_results)
 
 
 
113
 
114
+ combined_outputs = [result_1output, result_2output, result_3output, result_4output, result_5output, result_5boutput]
115
  return img_pil, combined_outputs
116
 
117
+
118
  # Define a function to generate the HTML content
119
  # Define a function to generate the HTML content
120
  def generate_results_html(results):
utils/utils.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import io
3
+ from PIL import Image
4
+ from torchvision import transforms
5
+
6
+ def softmax(vector):
7
+ e = np.exp(vector - np.max(vector)) # for numerical stability
8
+ return e / e.sum()
9
+
10
+ def augment_image(img_pil):
11
+ transform_flip = transforms.Compose([
12
+ transforms.RandomHorizontalFlip(p=1.0)
13
+ ])
14
+ transform_rotate = transforms.Compose([
15
+ transforms.RandomRotation(degrees=(90, 90))
16
+ ])
17
+ augmented_img_flip = transform_flip(img_pil)
18
+ augmented_img_rotate = transform_rotate(img_pil)
19
+ return augmented_img_flip, augmented_img_rotate
20
+
21
+ def convert_pil_to_bytes(image, format='JPEG'):
22
+ img_byte_arr = io.BytesIO()
23
+ image.save(img_byte_arr, format=format)
24
+ img_byte_arr = img_byte_arr.getvalue()
25
+ return img_byte_arr