Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,18 +15,17 @@ MODEL_URL = (
|
|
| 15 |
"https://huggingface.co/neuralninja10/deepFakeWithCBAM/"
|
| 16 |
"resolve/main/deepFakeWithCBAM.pt"
|
| 17 |
)
|
| 18 |
-
|
| 19 |
MODEL_PATH = "deepFakeWithCBAM.pt"
|
| 20 |
THRESHOLD = 0.68
|
| 21 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 22 |
|
| 23 |
# ============================================================
|
| 24 |
-
# Page
|
| 25 |
# ============================================================
|
| 26 |
|
| 27 |
st.set_page_config(
|
| 28 |
-
page_title="DeepFake Detection
|
| 29 |
-
page_icon="
|
| 30 |
layout="centered",
|
| 31 |
)
|
| 32 |
|
|
@@ -34,16 +33,16 @@ st.set_page_config(
|
|
| 34 |
# Secure Model Loader
|
| 35 |
# ============================================================
|
| 36 |
|
| 37 |
-
@st.cache_resource
|
| 38 |
def load_model():
|
| 39 |
token = os.environ.get("HF_TOKEN")
|
| 40 |
if token is None:
|
| 41 |
-
raise RuntimeError("HF_TOKEN
|
| 42 |
|
| 43 |
headers = {"Authorization": f"Bearer {token}"}
|
| 44 |
|
| 45 |
if not os.path.exists(MODEL_PATH):
|
| 46 |
-
with st.spinner("Initializing
|
| 47 |
response = requests.get(
|
| 48 |
MODEL_URL,
|
| 49 |
headers=headers,
|
|
@@ -52,7 +51,7 @@ def load_model():
|
|
| 52 |
)
|
| 53 |
response.raise_for_status()
|
| 54 |
with open(MODEL_PATH, "wb") as f:
|
| 55 |
-
for chunk in response.iter_content(
|
| 56 |
f.write(chunk)
|
| 57 |
|
| 58 |
model = torch.jit.load(MODEL_PATH, map_location=DEVICE)
|
|
@@ -60,7 +59,7 @@ def load_model():
|
|
| 60 |
return model
|
| 61 |
|
| 62 |
# ============================================================
|
| 63 |
-
#
|
| 64 |
# ============================================================
|
| 65 |
|
| 66 |
_transform = transforms.Compose([
|
|
@@ -82,21 +81,19 @@ def preprocess_image(image: Image.Image) -> torch.Tensor:
|
|
| 82 |
def run_inference(model, image: Image.Image):
|
| 83 |
tensor = preprocess_image(image).to(DEVICE)
|
| 84 |
|
| 85 |
-
|
| 86 |
with torch.no_grad():
|
| 87 |
logits = model(tensor)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
|
| 91 |
-
is_real =
|
| 92 |
-
confidence =
|
| 93 |
|
| 94 |
return {
|
| 95 |
-
"
|
| 96 |
"confidence": confidence,
|
| 97 |
-
"
|
| 98 |
-
"fake_prob": 1 - prob,
|
| 99 |
-
"latency_ms": latency_ms,
|
| 100 |
}
|
| 101 |
|
| 102 |
# ============================================================
|
|
@@ -104,80 +101,50 @@ def run_inference(model, image: Image.Image):
|
|
| 104 |
# ============================================================
|
| 105 |
|
| 106 |
def main():
|
| 107 |
-
st.title("
|
| 108 |
-
st.
|
| 109 |
-
"""
|
| 110 |
-
Upload a facial image to determine whether it is **Real** or **AI-Generated**.
|
| 111 |
-
This demo runs entirely on **CPU** using a TorchScript model.
|
| 112 |
-
"""
|
| 113 |
-
)
|
| 114 |
|
| 115 |
try:
|
| 116 |
model = load_model()
|
| 117 |
except Exception as e:
|
| 118 |
-
st.error("
|
| 119 |
st.exception(e)
|
| 120 |
return
|
| 121 |
|
| 122 |
uploaded_file = st.file_uploader(
|
| 123 |
-
"Upload
|
| 124 |
type=["jpg", "jpeg", "png"],
|
| 125 |
-
accept_multiple_files=False,
|
| 126 |
)
|
| 127 |
|
| 128 |
if uploaded_file:
|
| 129 |
image = Image.open(uploaded_file).convert("RGB")
|
| 130 |
-
st.image(image, caption="Uploaded Image"
|
| 131 |
|
| 132 |
-
|
| 133 |
-
with st.spinner("Running inference..."):
|
| 134 |
-
result = run_inference(model, image)
|
| 135 |
|
| 136 |
-
|
| 137 |
-
st.
|
|
|
|
| 138 |
|
| 139 |
-
if result["
|
| 140 |
-
st.success("
|
| 141 |
else:
|
| 142 |
-
st.error("
|
| 143 |
|
| 144 |
st.metric(
|
| 145 |
-
label="Confidence
|
| 146 |
value=f"{result['confidence']:.2%}",
|
| 147 |
)
|
| 148 |
|
| 149 |
st.caption(
|
| 150 |
-
f"
|
| 151 |
)
|
| 152 |
|
| 153 |
-
with st.expander("Detailed Probabilities"):
|
| 154 |
-
st.write(f"Real Probability: {result['real_prob']:.4f}")
|
| 155 |
-
st.write(f"Fake Probability: {result['fake_prob']:.4f}")
|
| 156 |
-
|
| 157 |
st.divider()
|
| 158 |
-
|
| 159 |
st.caption(
|
| 160 |
-
""
|
| 161 |
-
|
| 162 |
-
This system is provided for research and demonstration purposes only.
|
| 163 |
-
Predictions may be incorrect and should not be used as the sole basis
|
| 164 |
-
for real-world decisions.
|
| 165 |
-
"""
|
| 166 |
)
|
| 167 |
|
| 168 |
-
with st.expander("Model Information"):
|
| 169 |
-
st.markdown(
|
| 170 |
-
"""
|
| 171 |
-
- **Architecture:** EfficientNet + CBAM
|
| 172 |
-
- **Input Resolution:** 256×256
|
| 173 |
-
- **Runtime:** CPU (TorchScript)
|
| 174 |
-
- **Threshold:** 0.68
|
| 175 |
-
- **Known Limitations:**
|
| 176 |
-
- Heavy compression artifacts
|
| 177 |
-
- Extreme lighting conditions
|
| 178 |
-
- Occluded or profile faces
|
| 179 |
-
"""
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
if __name__ == "__main__":
|
| 183 |
main()
|
|
|
|
| 15 |
"https://huggingface.co/neuralninja10/deepFakeWithCBAM/"
|
| 16 |
"resolve/main/deepFakeWithCBAM.pt"
|
| 17 |
)
|
|
|
|
| 18 |
MODEL_PATH = "deepFakeWithCBAM.pt"
|
| 19 |
THRESHOLD = 0.68
|
| 20 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
|
| 22 |
# ============================================================
|
| 23 |
+
# Page Configuration
|
| 24 |
# ============================================================
|
| 25 |
|
| 26 |
st.set_page_config(
|
| 27 |
+
page_title="DeepFake Detection",
|
| 28 |
+
page_icon="🛡️",
|
| 29 |
layout="centered",
|
| 30 |
)
|
| 31 |
|
|
|
|
| 33 |
# Secure Model Loader
|
| 34 |
# ============================================================
|
| 35 |
|
| 36 |
+
@st.cache_resource
|
| 37 |
def load_model():
|
| 38 |
token = os.environ.get("HF_TOKEN")
|
| 39 |
if token is None:
|
| 40 |
+
raise RuntimeError("HF_TOKEN not found in Space secrets")
|
| 41 |
|
| 42 |
headers = {"Authorization": f"Bearer {token}"}
|
| 43 |
|
| 44 |
if not os.path.exists(MODEL_PATH):
|
| 45 |
+
with st.spinner("Initializing system..."):
|
| 46 |
response = requests.get(
|
| 47 |
MODEL_URL,
|
| 48 |
headers=headers,
|
|
|
|
| 51 |
)
|
| 52 |
response.raise_for_status()
|
| 53 |
with open(MODEL_PATH, "wb") as f:
|
| 54 |
+
for chunk in response.iter_content(8192):
|
| 55 |
f.write(chunk)
|
| 56 |
|
| 57 |
model = torch.jit.load(MODEL_PATH, map_location=DEVICE)
|
|
|
|
| 59 |
return model
|
| 60 |
|
| 61 |
# ============================================================
|
| 62 |
+
# Image Processing
|
| 63 |
# ============================================================
|
| 64 |
|
| 65 |
_transform = transforms.Compose([
|
|
|
|
| 81 |
def run_inference(model, image: Image.Image):
|
| 82 |
tensor = preprocess_image(image).to(DEVICE)
|
| 83 |
|
| 84 |
+
start_time = time.time()
|
| 85 |
with torch.no_grad():
|
| 86 |
logits = model(tensor)
|
| 87 |
+
probability = torch.sigmoid(logits).item()
|
| 88 |
+
latency = (time.time() - start_time) * 1000
|
| 89 |
|
| 90 |
+
is_real = probability > THRESHOLD
|
| 91 |
+
confidence = probability if is_real else (1 - probability)
|
| 92 |
|
| 93 |
return {
|
| 94 |
+
"label": "Real" if is_real else "Fake",
|
| 95 |
"confidence": confidence,
|
| 96 |
+
"latency": latency,
|
|
|
|
|
|
|
| 97 |
}
|
| 98 |
|
| 99 |
# ============================================================
|
|
|
|
| 101 |
# ============================================================
|
| 102 |
|
| 103 |
def main():
|
| 104 |
+
st.title("DeepFake Detection")
|
| 105 |
+
st.caption("Upload an image to verify authenticity.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
try:
|
| 108 |
model = load_model()
|
| 109 |
except Exception as e:
|
| 110 |
+
st.error("System initialization failed.")
|
| 111 |
st.exception(e)
|
| 112 |
return
|
| 113 |
|
| 114 |
uploaded_file = st.file_uploader(
|
| 115 |
+
"Upload Image",
|
| 116 |
type=["jpg", "jpeg", "png"],
|
|
|
|
| 117 |
)
|
| 118 |
|
| 119 |
if uploaded_file:
|
| 120 |
image = Image.open(uploaded_file).convert("RGB")
|
| 121 |
+
st.image(image, caption="Uploaded Image")
|
| 122 |
|
| 123 |
+
st.divider()
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
if st.button("Analyze Image"):
|
| 126 |
+
with st.spinner("Analyzing..."):
|
| 127 |
+
result = run_inference(model, image)
|
| 128 |
|
| 129 |
+
if result["label"] == "Real":
|
| 130 |
+
st.success("✔ Image appears to be authentic")
|
| 131 |
else:
|
| 132 |
+
st.error("✖ Image is likely manipulated")
|
| 133 |
|
| 134 |
st.metric(
|
| 135 |
+
label="Confidence",
|
| 136 |
value=f"{result['confidence']:.2%}",
|
| 137 |
)
|
| 138 |
|
| 139 |
st.caption(
|
| 140 |
+
f"Processing time: {result['latency']:.0f} ms"
|
| 141 |
)
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
st.divider()
|
|
|
|
| 144 |
st.caption(
|
| 145 |
+
"This demo caters all the available generators including Style GAN and Diffusion model variants"
|
| 146 |
+
"For further inquiries please feel free to contact uzair.mughal@unikrew.com"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
)
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
if __name__ == "__main__":
|
| 150 |
main()
|