Inam65 commited on
Commit
07b113f
Β·
verified Β·
1 Parent(s): 7882e41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -59
app.py CHANGED
@@ -1,90 +1,97 @@
1
  import gradio as gr
2
- import torch
3
- import torchvision.transforms as T
4
- from PIL import Image
5
  import numpy as np
 
 
6
 
7
  # -----------------------------
8
- # NOTE FOR USER:
9
- # This is a PROTOTYPE detector.
10
- # It uses simple CNN-based feature heuristics + frequency analysis.
11
- # It is NOT a forensic-grade deepfake detector.
 
 
12
  # -----------------------------
13
 
14
- # Image preprocessing
15
- transform = T.Compose([
16
- T.Resize((224, 224)),
17
- T.ToTensor(),
18
- T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
19
- ])
20
-
21
- # Simple frequency analysis (FFT-based heuristic)
22
- def frequency_artifacts(image: Image.Image):
23
- gray = image.convert("L")
24
- arr = np.array(gray)
25
- fft = np.fft.fft2(arr)
26
- fft_shift = np.fft.fftshift(fft)
27
- magnitude = np.log(np.abs(fft_shift) + 1)
28
- score = np.mean(magnitude)
29
- return score
30
-
31
- # Main prediction function
32
- def detect_authenticity(image):
 
33
  if image is None:
34
- return "No image provided", 0.0
35
 
36
- pil_image = Image.fromarray(image)
37
- freq_score = frequency_artifacts(pil_image)
38
 
39
- # Heuristic thresholds (tunable)
40
- if freq_score > 5.2:
41
- label = "⚠️ Likely Manipulated / Deepfake"
42
- confidence = min((freq_score - 5) * 20, 95)
 
 
 
 
43
  else:
44
- label = "βœ… Likely Authentic"
45
- confidence = min((6 - freq_score) * 20, 95)
 
 
 
 
 
 
46
 
47
- return label, round(confidence, 2)
48
 
49
- # Gradio UI
 
 
50
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
51
  gr.Markdown("""
52
- # πŸ•΅οΈ Deepfake & Image Authenticity Detector
53
- Upload an image to analyze whether it appears **authentic or manipulated**.
54
 
55
- **Use cases:**
56
- - Media verification
57
- - Social media fact-checking
58
- - Educational demos
59
- - Digital forensics awareness
60
 
61
- ⚠️ *This tool uses heuristic signals and is for educational purposes.*
62
  """)
63
 
64
  with gr.Row():
65
  with gr.Column():
66
- image_input = gr.Image(label="Upload Image", type="numpy")
67
  analyze_btn = gr.Button("Analyze Image πŸ”")
68
  with gr.Column():
69
- result_label = gr.Textbox(label="Prediction")
70
- confidence = gr.Slider(0, 100, label="Confidence (%)")
71
 
72
  analyze_btn.click(
73
- fn=detect_authenticity,
74
  inputs=image_input,
75
- outputs=[result_label, confidence]
76
  )
77
 
78
  gr.Markdown("""
79
- ### ℹ️ How it works (Simplified)
80
- - Analyzes **frequency artifacts** commonly introduced by GANs & image manipulation
81
- - Detects unnatural pixel distributions
82
-
83
- πŸ”§ *Future upgrades you can add:*
84
- - XceptionNet / EfficientNet deepfake models
85
- - Face-only region detection
86
- - Video deepfake detection
87
- - Explainable heatmaps
88
  """)
89
 
90
  # Launch
 
1
  import gradio as gr
 
 
 
2
  import numpy as np
3
+ from PIL import Image
4
+ import cv2
5
 
6
  # -----------------------------
7
+ # STEP 1: FACE DETECTION + ROUTING (VERSION 2 - FOUNDATION)
8
+ # -----------------------------
9
+ # This version does NOT yet classify deepfakes.
10
+ # It ONLY decides:
11
+ # 1) Does the image contain a human face?
12
+ # 2) Route it to the correct analysis pipeline
13
  # -----------------------------
14
 
15
+ # Load OpenCV Haar Cascade (lightweight & HF-friendly)
16
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
17
+
18
+
19
+ def detect_faces(image_np):
20
+ """
21
+ Detect faces using OpenCV Haar Cascade
22
+ Returns number of faces detected
23
+ """
24
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
25
+ faces = face_cascade.detectMultiScale(
26
+ gray,
27
+ scaleFactor=1.1,
28
+ minNeighbors=5,
29
+ minSize=(60, 60)
30
+ )
31
+ return faces
32
+
33
+
34
+ def route_image(image):
35
  if image is None:
36
+ return "No image provided", "N/A"
37
 
38
+ image_np = np.array(image)
39
+ faces = detect_faces(image_np)
40
 
41
+ # ROUTING LOGIC
42
+ if len(faces) > 0:
43
+ route = "πŸ§‘ Face Detected"
44
+ explanation = (
45
+ "This image contains one or more human faces.\n"
46
+ "β†’ It will be analyzed using **deepfake face-detection models**\n"
47
+ "(XceptionNet / EfficientNet in next step)."
48
+ )
49
  else:
50
+ route = "πŸ–ΌοΈ No Face Detected"
51
+ explanation = (
52
+ "No human face detected in this image.\n"
53
+ "β†’ It will be analyzed using **generic AI-image detection models**\n"
54
+ "(GAN / diffusion detection)."
55
+ )
56
+
57
+ return route, explanation
58
 
 
59
 
60
+ # -----------------------------
61
+ # GRADIO UI
62
+ # -----------------------------
63
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
64
  gr.Markdown("""
65
+ # 🧭 Image Analysis Router (Version 2 – Step 1)
 
66
 
67
+ This step determines **how the image should be analyzed**:
68
+ - πŸ‘€ Face present β†’ Deepfake detection pipeline
69
+ - πŸ–ΌοΈ No face β†’ Generic AI-image detection pipeline
 
 
70
 
71
+ *(No deepfake classification is performed yet.)*
72
  """)
73
 
74
  with gr.Row():
75
  with gr.Column():
76
+ image_input = gr.Image(type="pil", label="Upload Any Image")
77
  analyze_btn = gr.Button("Analyze Image πŸ”")
78
  with gr.Column():
79
+ route_output = gr.Textbox(label="Routing Decision")
80
+ explanation_output = gr.Textbox(label="Explanation", lines=5)
81
 
82
  analyze_btn.click(
83
+ fn=route_image,
84
  inputs=image_input,
85
+ outputs=[route_output, explanation_output]
86
  )
87
 
88
  gr.Markdown("""
89
+ ### βœ… Why this step matters
90
+ - Prevents misuse of face-only deepfake models
91
+ - Reduces false positives
92
+ - Makes the system work for **ANY image**
93
+
94
+ πŸ”œ **Next step:** Integrate XceptionNet / EfficientNet classifiers.
 
 
 
95
  """)
96
 
97
  # Launch