AyushKunwarAI commited on
Commit
54a9223
·
verified ·
1 Parent(s): 5642eb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -127
app.py CHANGED
@@ -1,145 +1,112 @@
1
  # app.py
 
 
 
 
2
  import io
3
  import os
4
  import numpy as np
5
- from PIL import Image
6
- import gradio as gr
7
- from huggingface_hub import InferenceClient
8
 
9
- # Load API token from HF secrets
10
- HF_API_TOKEN = os.environ.get("HF_API_TOKEN", None)
 
 
11
  client = InferenceClient(token=HF_API_TOKEN)
12
 
13
- # Models
14
- CLASSIFIER_MODEL = "prithivMLmods/deepfake-detector-model-v1"
15
- FORGERY_MODEL = "zhipeixu/fakeshield-v1-22b"
16
-
17
- def run_classification(img):
18
- """ Deepfake / AI image detection model """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
- buf = io.BytesIO()
21
- img.save(buf, format="PNG")
22
- buf.seek(0)
23
-
24
- out = client.image_classification(
25
- model=CLASSIFIER_MODEL,
26
- inputs=buf
27
- )
28
-
29
- if isinstance(out, list) and len(out) > 0:
30
- top = out[0]
31
- label = top.get("label", "")
32
- score = float(top.get("score", 0.0))
33
-
34
- if "fake" in label.lower() or "ai" in label.lower():
35
- return "AI-Generated", round(score * 100, 2)
36
- else:
37
- return "Real Image", round(score * 100, 2)
38
-
39
- return "Unknown", 0.0
40
-
41
- except Exception as e:
42
- return f"Error: {e}", 0.0
43
 
44
- def run_forgery_model(img):
45
- """ Forgery & manipulation detection model """
46
  try:
47
- buf = io.BytesIO()
48
- img.save(buf, format="PNG")
49
- buf.seek(0)
50
-
51
- out = client(
52
- model=FORGERY_MODEL,
53
- inputs=buf
54
- )
55
-
56
- result = {
57
- "explanation": None,
58
- "mask": None,
59
- "raw": out
60
- }
61
-
62
- # Modern HF models return dict
63
- if isinstance(out, dict):
64
- result["explanation"] = out.get("explanation") or out.get("text")
65
- result["mask"] = out.get("mask")
66
- return result
67
-
68
- # If output is a list of tokens
69
- if isinstance(out, list):
70
- explanation = []
71
- for item in out:
72
- if isinstance(item, dict):
73
- explanation.append(item.get("text") or item.get("label", ""))
74
- elif isinstance(item, str):
75
- explanation.append(item)
76
- result["explanation"] = " ".join(explanation)
77
- return result
78
-
79
- return result
80
-
81
- except Exception as e:
82
- return {"explanation": f"Error: {e}", "mask": None}
83
-
84
- def overlay_mask(img, mask_data):
85
- """ Creates a red overlay on manipulated regions """
86
- if mask_data is None:
87
- return None
88
 
 
89
  try:
90
- arr = np.array(mask_data)
91
- if arr.max() <= 1:
92
- arr = (arr * 255).astype("uint8")
93
-
94
- mask = Image.fromarray(arr).resize(img.size).convert("L")
95
- red = Image.new("RGBA", img.size, (255, 0, 0, 120))
96
- overlay = Image.composite(red, Image.new("RGBA", img.size), mask)
97
- final = Image.alpha_composite(img.convert("RGBA"), overlay)
98
- return final
99
-
100
  except:
101
- return None
102
-
103
- def analyze(image):
104
- if not isinstance(image, Image.Image):
105
- image = Image.fromarray(image)
106
-
107
- label, percent = run_classification(image)
108
- forg = run_forgery_model(image)
109
-
110
- explanation = forg.get("explanation") or "No clear manipulation detected."
111
- mask = forg.get("mask")
112
- overlay_image = overlay_mask(image, mask)
113
-
114
- return image, f"{label} ({percent}%)", explanation, overlay_image
115
-
116
-
117
- # ---------------- UI --------------------
118
- title = "AI DeepFake & Manipulation Detector"
119
- description = """
120
- Upload an image to detect if it's AI-generated or manipulated.
121
- Two AI models are used:
122
- - Deepfake classifier (Real vs AI)
123
- - Forgery detector (Manipulated region + explanation)
124
- """
 
125
 
 
 
 
126
  with gr.Blocks() as demo:
127
- gr.Markdown(f"# {title}\n{description}")
128
-
129
  with gr.Row():
130
  inp = gr.Image(type="pil", label="Upload Image")
131
- with gr.Column():
132
- original_out = gr.Image(label="Original Image")
133
- overlay_out = gr.Image(label="Manipulation Overlay")
134
-
135
- label_out = gr.Textbox(label="Classification", interactive=False)
136
- explanation_out = gr.Textbox(label="Manipulation Explanation", interactive=False)
137
-
138
- btn = gr.Button("Analyze")
139
- btn.click(
140
- fn=analyze,
141
- inputs=[inp],
142
- outputs=[original_out, label_out, explanation_out, overlay_out]
143
- )
144
-
145
  demo.launch()
 
1
  # app.py
2
+
3
+ import gradio as gr
4
+ from huggingface_hub import InferenceClient
5
+ from PIL import Image
6
  import io
7
  import os
8
  import numpy as np
 
 
 
9
 
10
+ # -----------------------------
11
+ # Hugging Face API Setup
12
+ # -----------------------------
13
+ HF_API_TOKEN = os.environ.get("HF_API_TOKEN") # Add your token in Hugging Face Secrets
14
  client = InferenceClient(token=HF_API_TOKEN)
15
 
16
+ # -----------------------------
17
+ # Model Names
18
+ # -----------------------------
19
+ MODEL_1 = "prithivMLmods/deepfake-detector-model-v1" # Deepfake detector
20
+ MODEL_2 = "microsoft/dit-base-finetuned-aigc-detection" # AIGC detector
21
+ MODEL_3 = "zhipeixu/fakeshield-v1-22b" # Forgery detector
22
+
23
+ # -----------------------------
24
+ # Helper function: overlay mask on image
25
+ # -----------------------------
26
+ def overlay_mask(image, mask):
27
+ if mask is None:
28
+ return image
29
+ mask = np.array(mask.convert("L")) # Convert mask to grayscale
30
+ mask = (mask > 128).astype(np.uint8) * 255 # Binary mask
31
+ overlay = Image.new("RGBA", image.size, (255,0,0,100)) # Red overlay
32
+ img_rgba = image.convert("RGBA")
33
+ img_rgba.paste(overlay, mask=Image.fromarray(mask))
34
+ return img_rgba
35
+
36
+ # -----------------------------
37
+ # Main function: Analyze image using 3 models
38
+ # -----------------------------
39
+ def analyze_image(image):
40
+ buf = io.BytesIO()
41
+ image.save(buf, format="PNG")
42
+ buf.seek(0)
43
+
44
+ # -------- MODEL 1: Deepfake Detector --------
45
  try:
46
+ out1 = client.image_classification(model=MODEL_1, inputs=buf)
47
+ label1 = out1[0]["label"]
48
+ score1 = round(out1[0]["score"] * 100, 2)
49
+ except:
50
+ label1, score1 = "Error", 0
51
+ buf.seek(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ # -------- MODEL 2: AIGC Detector --------
 
54
  try:
55
+ out2 = client.image_classification(model=MODEL_2, inputs=buf)
56
+ label2 = out2[0]["label"]
57
+ score2 = round(out2[0]["score"] * 100, 2)
58
+ except:
59
+ label2, score2 = "Error", 0
60
+ buf.seek(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # -------- MODEL 3: Forgery / Mask Detector --------
63
  try:
64
+ out3 = client(inputs=buf, model=MODEL_3)
65
+ explanation = out3.get("explanation", "No manipulation detected")
66
+ mask = out3.get("mask", None)
 
 
 
 
 
 
 
67
  except:
68
+ explanation, mask = "Error detecting forgery", None
69
+
70
+ # -------- FINAL DECISION (Fusion) --------
71
+ ai_votes = 0
72
+ if "fake" in label1.lower() or "ai" in label1.lower():
73
+ ai_votes += 1
74
+ if "ai" in label2.lower() or "generated" in label2.lower():
75
+ ai_votes += 1
76
+
77
+ if ai_votes == 2:
78
+ final_label = "AI-GENERATED"
79
+ elif ai_votes == 1:
80
+ final_label = "Possibly AI-GENERATED"
81
+ else:
82
+ final_label = "REAL IMAGE"
83
+
84
+ # Overlay mask if exists
85
+ output_image = overlay_mask(image, mask)
86
+
87
+ # Return outputs
88
+ return (
89
+ output_image,
90
+ f"{final_label}",
91
+ f"Deepfake Model: {label1} ({score1}%)\nAIGC Model: {label2} ({score2}%)\nForgery Detector: {explanation}"
92
+ )
93
 
94
+ # -----------------------------
95
+ # Gradio Interface
96
+ # -----------------------------
97
  with gr.Blocks() as demo:
98
+ gr.Markdown("<h2 style='text-align:center'>AI DeepFake & Manipulation Detector</h2>")
99
+
100
  with gr.Row():
101
  inp = gr.Image(type="pil", label="Upload Image")
102
+ out_img = gr.Image(type="pil", label="Result Image with Mask Overlay")
103
+
104
+ out_text = gr.Textbox(label="Detection Result & Explanation", lines=8)
105
+
106
+ btn = gr.Button("Analyze Image")
107
+ btn.click(fn=analyze_image, inputs=[inp], outputs=[out_img, out_text, out_text])
108
+
109
+ # -----------------------------
110
+ # Launch Gradio App
111
+ # -----------------------------
 
 
 
 
112
  demo.launch()