Update app.py
Browse files
app.py
CHANGED
@@ -103,68 +103,54 @@ 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 |
-
#
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
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 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
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 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
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.
|
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,22 +160,16 @@ if uploaded_image is not None:
|
|
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 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
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,28 +179,18 @@ def detect_deepfake_video(video_path):
|
|
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 |
-
|
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,19 +200,14 @@ if uploaded_video is not None:
|
|
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 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
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.
|
247 |
|
248 |
-
st.markdown("πΉ **Developed for Fake News & Deepfake Detection Hackathon**")
|
|
|
103 |
st.title("π° Fake News & Deepfake Detection Tool")
|
104 |
st.write("π Detect Fake News, Deepfake Images, and Videos using AI")
|
105 |
|
106 |
+
# Load Models
|
107 |
+
fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")
|
108 |
+
|
109 |
+
# Load Deepfake Detection Models
|
110 |
+
base_model_image = Xception(weights="imagenet", include_top=False)
|
111 |
+
base_model_image.trainable = False # Freeze base layers
|
112 |
+
x = GlobalAveragePooling2D()(base_model_image.output)
|
113 |
+
x = Dense(1024, activation="relu")(x)
|
114 |
+
x = Dense(1, activation="sigmoid")(x) # Sigmoid for probability output
|
115 |
+
deepfake_image_model = Model(inputs=base_model_image.input, outputs=x)
|
116 |
+
|
117 |
+
base_model_video = EfficientNetB7(weights="imagenet", include_top=False)
|
118 |
+
base_model_video.trainable = False
|
119 |
+
x = GlobalAveragePooling2D()(base_model_video.output)
|
120 |
+
x = Dense(1024, activation="relu")(x)
|
121 |
+
x = Dense(1, activation="sigmoid")(x)
|
122 |
+
deepfake_video_model = Model(inputs=base_model_video.input, outputs=x)
|
123 |
+
|
124 |
+
# Function to Preprocess Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
def preprocess_image(image_path):
|
126 |
+
img = load_img(image_path, target_size=(100, 100)) # Xception expects 299x299
|
127 |
+
img = img_to_array(img)
|
128 |
+
img = np.expand_dims(img, axis=0)
|
129 |
+
img /= 255.0 # Normalize pixel values
|
130 |
+
return img
|
131 |
+
|
132 |
+
# Function to Detect Deepfake Image
|
133 |
+
def detect_deepfake_image(image_path):
|
134 |
+
image = preprocess_image(image_path)
|
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 |
+
st.write("π Processing...")
|
146 |
+
prediction = fake_news_detector(news_input)
|
147 |
+
label = prediction[0]['label']
|
148 |
+
confidence = prediction[0]['score']
|
149 |
+
|
150 |
+
if label == "FAKE":
|
151 |
+
st.error(f"β οΈ Result: This news is FAKE. (Confidence: {confidence:.2f})")
|
|
|
|
|
|
|
|
|
|
|
152 |
else:
|
153 |
+
st.success(f"β
Result: This news is REAL. (Confidence: {confidence:.2f})")
|
|
|
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 |
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 |
+
st.write("π Processing...")
|
166 |
+
result = detect_deepfake_image(temp_file.name)
|
167 |
+
|
168 |
+
if result["label"] == "REAL":
|
169 |
+
st.success(f"β
Result: This image is Real. (Confidence: {1 - result['score']:.2f})")
|
170 |
+
else:
|
171 |
+
|
172 |
+
st.error(f"β οΈ Result: This image is a Deepfake. (Confidence: {result['score']:.2f})")
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
|
174 |
# ---- Deepfake Video Detection Section ----
|
175 |
st.subheader("π₯ Deepfake Video Detection")
|
|
|
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 |
+
result = detect_deepfake_image(frame_path)
|
190 |
+
frame_scores.append(result["score"])
|
|
|
|
|
|
|
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 |
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 |
+
st.write("π Processing...")
|
206 |
+
result = detect_deepfake_video(temp_file.name)
|
207 |
+
|
208 |
+
if result["label"] == "FAKE":
|
209 |
+
st.warning(f"β οΈ Result: This video contains Deepfake elements. (Confidence: {result['score']:.2f})")
|
|
|
|
|
|
|
|
|
|
|
210 |
else:
|
211 |
+
st.success(f"β
Result: This video is Real. (Confidence: {1 - result['score']:.2f})")
|
212 |
|
213 |
+
st.markdown("πΉ **Developed for Fake News & Deepfake Detection Hackathon**")
|