TKM03 commited on
Commit
ff41b45
·
verified ·
1 Parent(s): 1dc035a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -8
app.py CHANGED
@@ -2,12 +2,17 @@ import gradio as gr
2
  from transformers import ViTForImageClassification, ViTImageProcessor
3
  from PIL import Image
4
  import torch
 
 
 
 
 
5
 
6
  # Load the model and processor from Hugging Face
7
  model = ViTForImageClassification.from_pretrained("dima806/deepfake_vs_real_image_detection")
8
  processor = ViTImageProcessor.from_pretrained("dima806/deepfake_vs_real_image_detection")
9
 
10
- def detect(image):
11
  """Detect deepfake content in an image using dima806/deepfake_vs_real_image_detection"""
12
  if image is None:
13
  raise gr.Error("Please upload an image to analyze")
@@ -16,6 +21,9 @@ def detect(image):
16
  # Convert Gradio image (filepath) to PIL Image
17
  pil_image = Image.open(image).convert("RGB")
18
 
 
 
 
19
  # Preprocess the image
20
  inputs = processor(images=pil_image, return_tensors="pt")
21
 
@@ -23,27 +31,31 @@ def detect(image):
23
  with torch.no_grad():
24
  outputs = model(**inputs)
25
  logits = outputs.logits
26
- predicted_class = torch.argmax(logits, dim=1).item()
27
 
28
  # Get confidence scores
29
- probabilities = torch.softmax(logits, dim=1)[0]
30
  confidence_real = probabilities[0].item() * 100
31
  confidence_fake = probabilities[1].item() * 100
32
 
33
- # Map class index to label
34
- label = model.config.id2label[predicted_class]
 
 
 
 
35
 
36
  # Prepare output
37
- overall = f"{max(confidence_real, confidence_fake):.1f}% Confidence"
38
  aigen = f"{confidence_fake:.1f}% (AI-Generated Content Likelihood)"
39
  deepfake = f"{confidence_fake:.1f}% (Face Manipulation Likelihood)"
40
 
41
  return overall, aigen, deepfake
42
 
43
  except Exception as e:
 
44
  raise gr.Error(f"Analysis error: {str(e)}")
45
 
46
- # Custom CSS (unchanged from your original)
47
  custom_css = """
48
  .container {
49
  max-width: 1200px;
@@ -85,7 +97,8 @@ MARKDOWN0 = """
85
  <div class="header">
86
  <h1>DeepFake Detection System</h1>
87
  <p>Advanced AI-powered analysis for identifying manipulated media<br>
88
- Powered by dima806/deepfake_vs_real_image_detection model</p>
 
89
  </div>
90
  """
91
 
 
2
  from transformers import ViTForImageClassification, ViTImageProcessor
3
  from PIL import Image
4
  import torch
5
+ import logging
6
+
7
+ # Set up logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
 
11
  # Load the model and processor from Hugging Face
12
  model = ViTForImageClassification.from_pretrained("dima806/deepfake_vs_real_image_detection")
13
  processor = ViTImageProcessor.from_pretrained("dima806/deepfake_vs_real_image_detection")
14
 
15
+ def detect(image, confidence_threshold=0.7):
16
  """Detect deepfake content in an image using dima806/deepfake_vs_real_image_detection"""
17
  if image is None:
18
  raise gr.Error("Please upload an image to analyze")
 
21
  # Convert Gradio image (filepath) to PIL Image
22
  pil_image = Image.open(image).convert("RGB")
23
 
24
+ # Ensure image meets ViT's expected size (224x224)
25
+ pil_image = pil_image.resize((224, 224), Image.Resampling.LANCZOS)
26
+
27
  # Preprocess the image
28
  inputs = processor(images=pil_image, return_tensors="pt")
29
 
 
31
  with torch.no_grad():
32
  outputs = model(**inputs)
33
  logits = outputs.logits
34
+ probabilities = torch.softmax(logits, dim=1)[0]
35
 
36
  # Get confidence scores
 
37
  confidence_real = probabilities[0].item() * 100
38
  confidence_fake = probabilities[1].item() * 100
39
 
40
+ # Determine prediction based on threshold
41
+ predicted_label = "Fake" if confidence_fake / 100 >= confidence_threshold else "Real"
42
+ confidence_score = max(confidence_real, confidence_fake)
43
+
44
+ # Log the prediction
45
+ logger.info(f"Real: {confidence_real:.1f}%, Fake: {confidence_fake:.1f}%, Predicted: {predicted_label}")
46
 
47
  # Prepare output
48
+ overall = f"{confidence_score:.1f}% Confidence ({predicted_label})"
49
  aigen = f"{confidence_fake:.1f}% (AI-Generated Content Likelihood)"
50
  deepfake = f"{confidence_fake:.1f}% (Face Manipulation Likelihood)"
51
 
52
  return overall, aigen, deepfake
53
 
54
  except Exception as e:
55
+ logger.error(f"Error during analysis: {str(e)}")
56
  raise gr.Error(f"Analysis error: {str(e)}")
57
 
58
+ # Custom CSS (unchanged)
59
  custom_css = """
60
  .container {
61
  max-width: 1200px;
 
97
  <div class="header">
98
  <h1>DeepFake Detection System</h1>
99
  <p>Advanced AI-powered analysis for identifying manipulated media<br>
100
+ Powered by dima806/deepfake_vs_real_image_detection model<br>
101
+ Note: Accuracy may vary with recent deepfakes due to training data age</p>
102
  </div>
103
  """
104