Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
import tempfile
|
5 |
+
import os
|
6 |
+
from PIL import Image
|
7 |
+
import tensorflow as tf
|
8 |
+
from transformers import pipeline
|
9 |
+
from tensorflow.keras.applications import Xception, EfficientNetB7
|
10 |
+
from tensorflow.keras.models import Model
|
11 |
+
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
|
12 |
+
from tensorflow.keras.preprocessing.image import load_img, img_to_array
|
13 |
+
|
14 |
+
# ---- Page Configuration ----
|
15 |
+
st.set_page_config(page_title="Fake & Deepfake Detection", layout="wide")
|
16 |
+
|
17 |
+
st.title("📰 Fake News & Deepfake Detection Tool")
|
18 |
+
st.write("🚀 Detect Fake News, Deepfake Images, and Videos using AI")
|
19 |
+
|
20 |
+
# Load Models
|
21 |
+
fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")
|
22 |
+
|
23 |
+
# Load Deepfake Detection Models
|
24 |
+
base_model_image = Xception(weights="imagenet", include_top=False)
|
25 |
+
base_model_image.trainable = False # Freeze base layers
|
26 |
+
x = GlobalAveragePooling2D()(base_model_image.output)
|
27 |
+
x = Dense(1024, activation="relu")(x)
|
28 |
+
x = Dense(1, activation="sigmoid")(x) # Sigmoid for probability output
|
29 |
+
deepfake_image_model = Model(inputs=base_model_image.input, outputs=x)
|
30 |
+
|
31 |
+
base_model_video = EfficientNetB7(weights="imagenet", include_top=False)
|
32 |
+
base_model_video.trainable = False
|
33 |
+
x = GlobalAveragePooling2D()(base_model_video.output)
|
34 |
+
x = Dense(1024, activation="relu")(x)
|
35 |
+
x = Dense(1, activation="sigmoid")(x)
|
36 |
+
deepfake_video_model = Model(inputs=base_model_video.input, outputs=x)
|
37 |
+
|
38 |
+
# Function to Preprocess Image
|
39 |
+
def preprocess_image(image_path):
|
40 |
+
img = load_img(image_path, target_size=(100, 100)) # Xception expects 299x299
|
41 |
+
img = img_to_array(img)
|
42 |
+
img = np.expand_dims(img, axis=0)
|
43 |
+
img /= 255.0 # Normalize pixel values
|
44 |
+
return img
|
45 |
+
|
46 |
+
# Function to Detect Deepfake Image
|
47 |
+
def detect_deepfake_image(image_path):
|
48 |
+
image = preprocess_image(image_path)
|
49 |
+
prediction = deepfake_image_model.predict(image)[0][0]
|
50 |
+
confidence = round(float(prediction), 2)
|
51 |
+
label = "FAKE" if confidence > 0.5 else "REAL"
|
52 |
+
return {"label": label, "score": confidence}
|
53 |
+
|
54 |
+
# ---- Fake News Detection Section ----
|
55 |
+
st.subheader("📝 Fake News Detection")
|
56 |
+
news_input = st.text_area("Enter News Text:", placeholder="Type here...")
|
57 |
+
|
58 |
+
if st.button("Check News"):
|
59 |
+
st.write("🔍 Processing...")
|
60 |
+
prediction = fake_news_detector(news_input)
|
61 |
+
label = prediction[0]['label']
|
62 |
+
confidence = prediction[0]['score']
|
63 |
+
|
64 |
+
if label == "FAKE":
|
65 |
+
st.error(f"⚠ Result: This news is FAKE. (Confidence: {confidence:.2f})")
|
66 |
+
else:
|
67 |
+
st.success(f"✅ Result: This news is REAL. (Confidence: {confidence:.2f})")
|
68 |
+
# ---- Deepfake Image Detection Section ----
|
69 |
+
st.subheader("📸 Deepfake Image Detection")
|
70 |
+
uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
|
71 |
+
|
72 |
+
if uploaded_image is not None:
|
73 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
|
74 |
+
img = Image.open(uploaded_image).convert("RGB")
|
75 |
+
img.save(temp_file.name, "JPEG")
|
76 |
+
st.image(temp_file.name, caption="🖼 Uploaded Image", use_column_width=True)
|
77 |
+
|
78 |
+
if st.button("Analyze Image"):
|
79 |
+
st.write("🔍 Processing...")
|
80 |
+
result = detect_deepfake_image(temp_file.name)
|
81 |
+
|
82 |
+
if result["label"] == "REAL":
|
83 |
+
st.success(f"✅ Result: This image is Real. (Confidence: {1 - result['score']:.2f})")
|
84 |
+
else:
|
85 |
+
|
86 |
+
st.error(f"⚠ Result: This image is a Deepfake. (Confidence: {result['score']:.2f})")
|
87 |
+
|
88 |
+
# ---- Deepfake Video Detection Section ----
|
89 |
+
st.subheader("🎥 Deepfake Video Detection")
|
90 |
+
uploaded_video = st.file_uploader("Upload a Video", type=["mp4", "avi", "mov"])
|
91 |
+
|
92 |
+
def detect_deepfake_video(video_path):
|
93 |
+
cap = cv2.VideoCapture(video_path)
|
94 |
+
frame_scores = []
|
95 |
+
|
96 |
+
while cap.isOpened():
|
97 |
+
ret, frame = cap.read()
|
98 |
+
if not ret:
|
99 |
+
break
|
100 |
+
|
101 |
+
frame_path = "temp_frame.jpg"
|
102 |
+
cv2.imwrite(frame_path, frame)
|
103 |
+
result = detect_deepfake_image(frame_path)
|
104 |
+
frame_scores.append(result["score"])
|
105 |
+
os.remove(frame_path)
|
106 |
+
|
107 |
+
cap.release()
|
108 |
+
avg_score = np.mean(frame_scores)
|
109 |
+
final_label = "FAKE" if avg_score > 0.5 else "REAL"
|
110 |
+
return {"label": final_label, "score": round(float(avg_score), 2)}
|
111 |
+
|
112 |
+
if uploaded_video is not None:
|
113 |
+
st.video(uploaded_video)
|
114 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
|
115 |
+
with open(temp_file.name, "wb") as f:
|
116 |
+
f.write(uploaded_video.read())
|
117 |
+
|
118 |
+
if st.button("Analyze Video"):
|
119 |
+
st.write("🔍 Processing...")
|
120 |
+
result = detect_deepfake_video(temp_file.name)
|
121 |
+
|
122 |
+
if result["label"] == "FAKE":
|
123 |
+
st.warning(f"⚠ Result: This video contains Deepfake elements. (Confidence: {result['score']:.2f})")
|
124 |
+
else:
|
125 |
+
st.success(f"✅ Result: This video is Real. (Confidence: {1 - result['score']:.2f})")
|
126 |
+
|
127 |
+
st.markdown("🔹 *Developed for Fake News & Deepfake Detection Hackathon*")
|