Update app.py
Browse files
app.py
CHANGED
|
@@ -103,54 +103,68 @@ st.set_page_config(page_title="Fake & Deepfake Detection", layout="wide")
|
|
| 103 |
st.title("π° Fake News & Deepfake Detection Tool")
|
| 104 |
st.write("π Detect Fake News, Deepfake Images, and Videos using AI")
|
| 105 |
|
| 106 |
-
# Load
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
x =
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
def preprocess_image(image_path):
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
prediction = deepfake_image_model.predict(image)[0][0]
|
| 136 |
-
confidence = round(float(prediction), 2)
|
| 137 |
-
label = "FAKE" if confidence > 0.5 else "REAL"
|
| 138 |
-
return {"label": label, "score": confidence}
|
| 139 |
|
| 140 |
# ---- Fake News Detection Section ----
|
| 141 |
st.subheader("π Fake News Detection")
|
| 142 |
news_input = st.text_area("Enter News Text:", placeholder="Type here...")
|
| 143 |
|
| 144 |
if st.button("Check News"):
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
else:
|
| 153 |
-
st.
|
|
|
|
| 154 |
# ---- Deepfake Image Detection Section ----
|
| 155 |
st.subheader("πΈ Deepfake Image Detection")
|
| 156 |
uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
|
|
@@ -160,16 +174,22 @@ if uploaded_image is not None:
|
|
| 160 |
img = Image.open(uploaded_image).convert("RGB")
|
| 161 |
img.save(temp_file.name, "JPEG")
|
| 162 |
st.image(temp_file.name, caption="πΌοΈ Uploaded Image", use_column_width=True)
|
| 163 |
-
|
| 164 |
if st.button("Analyze Image"):
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
# ---- Deepfake Video Detection Section ----
|
| 175 |
st.subheader("π₯ Deepfake Video Detection")
|
|
@@ -179,18 +199,28 @@ def detect_deepfake_video(video_path):
|
|
| 179 |
cap = cv2.VideoCapture(video_path)
|
| 180 |
frame_scores = []
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
while cap.isOpened():
|
| 183 |
ret, frame = cap.read()
|
| 184 |
if not ret:
|
| 185 |
break
|
| 186 |
-
|
| 187 |
frame_path = "temp_frame.jpg"
|
| 188 |
cv2.imwrite(frame_path, frame)
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
| 191 |
os.remove(frame_path)
|
| 192 |
|
| 193 |
cap.release()
|
|
|
|
|
|
|
|
|
|
| 194 |
avg_score = np.mean(frame_scores)
|
| 195 |
final_label = "FAKE" if avg_score > 0.5 else "REAL"
|
| 196 |
return {"label": final_label, "score": round(float(avg_score), 2)}
|
|
@@ -200,15 +230,19 @@ if uploaded_video is not None:
|
|
| 200 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
|
| 201 |
with open(temp_file.name, "wb") as f:
|
| 202 |
f.write(uploaded_video.read())
|
| 203 |
-
|
| 204 |
if st.button("Analyze Video"):
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
else:
|
| 211 |
-
st.
|
| 212 |
|
| 213 |
st.markdown("πΉ **Developed for Fake News & Deepfake Detection Hackathon**")
|
| 214 |
-
|
|
|
|
| 103 |
st.title("π° Fake News & Deepfake Detection Tool")
|
| 104 |
st.write("π Detect Fake News, Deepfake Images, and Videos using AI")
|
| 105 |
|
| 106 |
+
# ---- Load Fake News Detector ----
|
| 107 |
+
try:
|
| 108 |
+
fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")
|
| 109 |
+
except Exception as e:
|
| 110 |
+
st.error(f"Error loading fake news model: {e}")
|
| 111 |
+
fake_news_detector = None
|
| 112 |
+
|
| 113 |
+
# ---- Load Deepfake Detection Models ----
|
| 114 |
+
try:
|
| 115 |
+
base_model_image = Xception(weights="imagenet", include_top=False)
|
| 116 |
+
base_model_image.trainable = False
|
| 117 |
+
x = GlobalAveragePooling2D()(base_model_image.output)
|
| 118 |
+
x = Dense(1024, activation="relu")(x)
|
| 119 |
+
x = Dense(1, activation="sigmoid")(x)
|
| 120 |
+
deepfake_image_model = Model(inputs=base_model_image.input, outputs=x)
|
| 121 |
+
except Exception as e:
|
| 122 |
+
st.error(f"Error loading image model: {e}")
|
| 123 |
+
deepfake_image_model = None
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
base_model_video = EfficientNetB7(weights="imagenet", include_top=False)
|
| 127 |
+
base_model_video.trainable = False
|
| 128 |
+
x = GlobalAveragePooling2D()(base_model_video.output)
|
| 129 |
+
x = Dense(1024, activation="relu")(x)
|
| 130 |
+
x = Dense(1, activation="sigmoid")(x)
|
| 131 |
+
deepfake_video_model = Model(inputs=base_model_video.input, outputs=x)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
st.error(f"Error loading video model: {e}")
|
| 134 |
+
deepfake_video_model = None
|
| 135 |
+
|
| 136 |
+
# ---- Image Preprocessing Function ----
|
| 137 |
def preprocess_image(image_path):
|
| 138 |
+
try:
|
| 139 |
+
img = load_img(image_path, target_size=(299, 299)) # Xception requires 299x299
|
| 140 |
+
img = img_to_array(img)
|
| 141 |
+
img = np.expand_dims(img, axis=0)
|
| 142 |
+
img /= 255.0 # Normalize
|
| 143 |
+
return img
|
| 144 |
+
except Exception as e:
|
| 145 |
+
st.error(f"Error processing image: {e}")
|
| 146 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
# ---- Fake News Detection Section ----
|
| 149 |
st.subheader("π Fake News Detection")
|
| 150 |
news_input = st.text_area("Enter News Text:", placeholder="Type here...")
|
| 151 |
|
| 152 |
if st.button("Check News"):
|
| 153 |
+
if not news_input.strip():
|
| 154 |
+
st.warning("β οΈ Please enter news text before checking.")
|
| 155 |
+
elif fake_news_detector:
|
| 156 |
+
st.write("π Processing...")
|
| 157 |
+
prediction = fake_news_detector(news_input)
|
| 158 |
+
label = prediction[0]['label']
|
| 159 |
+
confidence = prediction[0]['score']
|
| 160 |
+
|
| 161 |
+
if label.lower() == "fake":
|
| 162 |
+
st.error(f"β οΈ Result: This news is FAKE. (Confidence: {confidence:.2f})")
|
| 163 |
+
else:
|
| 164 |
+
st.success(f"β
Result: This news is REAL. (Confidence: {confidence:.2f})")
|
| 165 |
else:
|
| 166 |
+
st.error("Fake news detection model not loaded.")
|
| 167 |
+
|
| 168 |
# ---- Deepfake Image Detection Section ----
|
| 169 |
st.subheader("πΈ Deepfake Image Detection")
|
| 170 |
uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
|
|
|
|
| 174 |
img = Image.open(uploaded_image).convert("RGB")
|
| 175 |
img.save(temp_file.name, "JPEG")
|
| 176 |
st.image(temp_file.name, caption="πΌοΈ Uploaded Image", use_column_width=True)
|
| 177 |
+
|
| 178 |
if st.button("Analyze Image"):
|
| 179 |
+
if deepfake_image_model:
|
| 180 |
+
st.write("π Processing...")
|
| 181 |
+
image_data = preprocess_image(temp_file.name)
|
| 182 |
+
if image_data is not None:
|
| 183 |
+
prediction = deepfake_image_model.predict(image_data)[0][0]
|
| 184 |
+
confidence = round(float(prediction), 2)
|
| 185 |
+
label = "FAKE" if confidence > 0.5 else "REAL"
|
| 186 |
+
|
| 187 |
+
if label == "REAL":
|
| 188 |
+
st.success(f"β
Result: This image is Real. (Confidence: {1 - confidence:.2f})")
|
| 189 |
+
else:
|
| 190 |
+
st.error(f"β οΈ Result: This image is a Deepfake. (Confidence: {confidence:.2f})")
|
| 191 |
+
else:
|
| 192 |
+
st.error("Deepfake image detection model not loaded.")
|
| 193 |
|
| 194 |
# ---- Deepfake Video Detection Section ----
|
| 195 |
st.subheader("π₯ Deepfake Video Detection")
|
|
|
|
| 199 |
cap = cv2.VideoCapture(video_path)
|
| 200 |
frame_scores = []
|
| 201 |
|
| 202 |
+
if not cap.isOpened():
|
| 203 |
+
st.error("Error: Cannot open video file.")
|
| 204 |
+
return None
|
| 205 |
+
|
| 206 |
while cap.isOpened():
|
| 207 |
ret, frame = cap.read()
|
| 208 |
if not ret:
|
| 209 |
break
|
| 210 |
+
|
| 211 |
frame_path = "temp_frame.jpg"
|
| 212 |
cv2.imwrite(frame_path, frame)
|
| 213 |
+
processed_image = preprocess_image(frame_path)
|
| 214 |
+
|
| 215 |
+
if processed_image is not None:
|
| 216 |
+
prediction = deepfake_image_model.predict(processed_image)[0][0]
|
| 217 |
+
frame_scores.append(prediction)
|
| 218 |
os.remove(frame_path)
|
| 219 |
|
| 220 |
cap.release()
|
| 221 |
+
if not frame_scores:
|
| 222 |
+
return None
|
| 223 |
+
|
| 224 |
avg_score = np.mean(frame_scores)
|
| 225 |
final_label = "FAKE" if avg_score > 0.5 else "REAL"
|
| 226 |
return {"label": final_label, "score": round(float(avg_score), 2)}
|
|
|
|
| 230 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
|
| 231 |
with open(temp_file.name, "wb") as f:
|
| 232 |
f.write(uploaded_video.read())
|
| 233 |
+
|
| 234 |
if st.button("Analyze Video"):
|
| 235 |
+
if deepfake_video_model:
|
| 236 |
+
st.write("π Processing...")
|
| 237 |
+
result = detect_deepfake_video(temp_file.name)
|
| 238 |
+
|
| 239 |
+
if result is None:
|
| 240 |
+
st.error("β οΈ Unable to analyze video.")
|
| 241 |
+
elif result["label"] == "FAKE":
|
| 242 |
+
st.warning(f"β οΈ Result: This video contains Deepfake elements. (Confidence: {result['score']:.2f})")
|
| 243 |
+
else:
|
| 244 |
+
st.success(f"β
Result: This video is Real. (Confidence: {1 - result['score']:.2f})")
|
| 245 |
else:
|
| 246 |
+
st.error("Deepfake video detection model not loaded.")
|
| 247 |
|
| 248 |
st.markdown("πΉ **Developed for Fake News & Deepfake Detection Hackathon**")
|
|
|