asad231 commited on
Commit
2405a2e
Β·
verified Β·
1 Parent(s): 6a04593

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -95
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
- # ---- 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,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
- 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,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
- 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,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
- 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**")
 
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**")