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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()
|