File size: 9,376 Bytes
1028a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39abc8d
56e3c29
bd1ee8d
 
 
 
 
3a45cce
bd1ee8d
 
 
 
51b55ad
97e3cb7
bd1ee8d
51b55ad
3a45cce
 
51b55ad
6a04593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd1ee8d
6a04593
 
 
 
 
 
 
 
 
1028a4f
97e3cb7
3a45cce
2bb11c3
51b55ad
97e3cb7
6a04593
 
 
 
 
 
 
 
 
 
 
 
272e331
6a04593
 
bd1ee8d
3a45cce
bd1ee8d
 
 
 
 
 
3a45cce
6a04593
bd1ee8d
6a04593
 
 
 
 
 
 
 
 
 
 
 
 
 
bd1ee8d
 
3a45cce
bd1ee8d
 
 
 
 
 
6a04593
 
 
 
bd1ee8d
 
 
 
6a04593
bd1ee8d
 
6a04593
 
 
 
 
bd1ee8d
 
 
6a04593
 
 
bd1ee8d
 
 
 
 
 
 
 
 
6a04593
bd1ee8d
6a04593
 
 
 
 
 
 
 
 
 
bd1ee8d
6a04593
39abc8d
e61c7d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# import streamlit as st
# import numpy as np
# import cv2
# import tempfile
# import os
# from PIL import Image

# # ---- Page Configuration ----
# st.set_page_config(page_title="Fake & Deepfake Detection", layout="wide")

# st.title("📰 Fake News & Deepfake Detection Tool")
# st.write("🚀 Detect Fake News, Deepfake Images, and Videos using AI")

# # ---- Fake News Detection Section ----
# st.subheader("📝 Fake News Detection")
# news_input = st.text_area("Enter News Text:", "Type here...")

# if st.button("Check News"):
#     st.write("🔍 Processing...")
#     st.success("✅ Result: This news is FAKE.")  # Replace with ML Model

# # ---- Deepfake Image Detection Section ----
# st.subheader("📸 Deepfake Image Detection")
# uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])

# def compress_image(image, quality=90, max_size=(300, 300)):  # ✅ High clarity image
#     img = Image.open(image).convert("RGB")
#     img.thumbnail(max_size)  
#     temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
#     img.save(temp_file.name, "JPEG", quality=quality)
#     return temp_file.name

# if uploaded_image is not None:
#     compressed_image_path = compress_image(uploaded_image)
#     st.image(compressed_image_path, caption="🖼️ Compressed & Clear Image", use_column_width=True)
#     if st.button("Analyze Image"):
#         st.write("🔍 Processing...")
#         st.error("⚠️ Result: This image is a Deepfake.")  # Replace with model

# # ---- Deepfake Video Detection Section ----
# st.subheader("🎥 Deepfake Video Detection")
# uploaded_video = st.file_uploader("Upload a Video", type=["mp4", "avi", "mov"])

# def compress_video(video):
#     temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")

#     with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
#         temp_video.write(video.read())
#         video_path = temp_video.name

#     cap = cv2.VideoCapture(video_path)
    
#     if not cap.isOpened():
#         st.error("❌ Error: Unable to read video!")
#         return None

#     fourcc = cv2.VideoWriter_fourcc(*'mp4v')

#     # ✅ New Resolution (100x80) & 15 FPS
#     frame_width = 50  
#     frame_height = 80  
#     out = cv2.VideoWriter(temp_file.name, fourcc, 15.0, (frame_width, frame_height))  

#     while cap.isOpened():
#         ret, frame = cap.read()
#         if not ret:
#             break
#         frame = cv2.resize(frame, (frame_width, frame_height))
#         out.write(frame)

#     cap.release()
#     out.release()
    
#     return temp_file.name

# if uploaded_video is not None:
#     st.video(uploaded_video)  # ✅ فوراً ویڈیو اپ لوڈ ہونے کے بعد دکھائیں
#     compressed_video_path = compress_video(uploaded_video)
#     if compressed_video_path:
#         st.video(compressed_video_path)  # ✅ کمپریسڈ ویڈیو بھی دکھائیں
#         if st.button("Analyze Video"):
#             st.write("🔍 Processing...")
#             st.warning("⚠️ Result: This video contains Deepfake elements.")  # Replace with model

# st.markdown("🔹 **Developed for Fake News & Deepfake Detection Hackathon**")

import streamlit as st
import numpy as np
import cv2
import tempfile
import os
from PIL import Image
import tensorflow as tf
from transformers import pipeline
from tensorflow.keras.applications import Xception, EfficientNetB7
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.preprocessing.image import load_img, img_to_array

# ---- Page Configuration ----
st.set_page_config(page_title="Fake & Deepfake Detection", layout="wide")

st.title("📰 Fake News & Deepfake Detection Tool")
st.write("🚀 Detect Fake News, Deepfake Images, and Videos using AI")

# ---- Load Fake News Detector ----
try:
    fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")
except Exception as e:
    st.error(f"Error loading fake news model: {e}")
    fake_news_detector = None

# ---- Load Deepfake Detection Models ----
try:
    base_model_image = Xception(weights="imagenet", include_top=False)
    base_model_image.trainable = False
    x = GlobalAveragePooling2D()(base_model_image.output)
    x = Dense(1024, activation="relu")(x)
    x = Dense(1, activation="sigmoid")(x)
    deepfake_image_model = Model(inputs=base_model_image.input, outputs=x)
except Exception as e:
    st.error(f"Error loading image model: {e}")
    deepfake_image_model = None

try:
    base_model_video = EfficientNetB7(weights="imagenet", include_top=False)
    base_model_video.trainable = False
    x = GlobalAveragePooling2D()(base_model_video.output)
    x = Dense(1024, activation="relu")(x)
    x = Dense(1, activation="sigmoid")(x)
    deepfake_video_model = Model(inputs=base_model_video.input, outputs=x)
except Exception as e:
    st.error(f"Error loading video model: {e}")
    deepfake_video_model = None

# ---- Image Preprocessing Function ----
def preprocess_image(image_path):
    try:
        img = load_img(image_path, target_size=(299, 299))  # Xception requires 299x299
        img = img_to_array(img)
        img = np.expand_dims(img, axis=0)
        img /= 255.0  # Normalize
        return img
    except Exception as e:
        st.error(f"Error processing image: {e}")
        return None

# ---- Fake News Detection Section ----
st.subheader("📝 Fake News Detection")
news_input = st.text_area("Enter News Text:", placeholder="Type here...")

if st.button("Check News"):
    if not news_input.strip():
        st.warning("⚠️ Please enter news text before checking.")
    elif fake_news_detector:
        st.write("🔍 Processing...")
        prediction = fake_news_detector(news_input)
        label = prediction[0]['label']
        confidence = prediction[0]['score']

        if label.lower() == "fake":
            st.error(f"⚠️ Result: This news is FAKE. (Confidence: {confidence:.2f})")
        else:
            st.success(f"✅ Result: This news is REAL. (Confidence: {confidence:.2f})")
    else:
        st.error("Fake news detection model not loaded.")

# ---- Deepfake Image Detection Section ----
st.subheader("📸 Deepfake Image Detection")
uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])

if uploaded_image is not None:
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
    img = Image.open(uploaded_image).convert("RGB")
    img.save(temp_file.name, "JPEG")
    st.image(temp_file.name, caption="🖼️ Uploaded Image", use_column_width=True)

    if st.button("Analyze Image"):
        if deepfake_image_model:
            st.write("🔍 Processing...")
            image_data = preprocess_image(temp_file.name)
            if image_data is not None:
                prediction = deepfake_image_model.predict(image_data)[0][0]
                confidence = round(float(prediction), 2)
                label = "FAKE" if confidence > 0.5 else "REAL"

                if label == "REAL":
                    st.success(f"✅ Result: This image is Real. (Confidence: {1 - confidence:.2f})")
                else:
                    st.error(f"⚠️ Result: This image is a Deepfake. (Confidence: {confidence:.2f})")
        else:
            st.error("Deepfake image detection model not loaded.")

# ---- Deepfake Video Detection Section ----
st.subheader("🎥 Deepfake Video Detection")
uploaded_video = st.file_uploader("Upload a Video", type=["mp4", "avi", "mov"])

def detect_deepfake_video(video_path):
    cap = cv2.VideoCapture(video_path)
    frame_scores = []
    
    if not cap.isOpened():
        st.error("Error: Cannot open video file.")
        return None

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        frame_path = "temp_frame.jpg"
        cv2.imwrite(frame_path, frame)
        processed_image = preprocess_image(frame_path)
        
        if processed_image is not None:
            prediction = deepfake_image_model.predict(processed_image)[0][0]
            frame_scores.append(prediction)
        os.remove(frame_path)
    
    cap.release()
    if not frame_scores:
        return None

    avg_score = np.mean(frame_scores)
    final_label = "FAKE" if avg_score > 0.5 else "REAL"
    return {"label": final_label, "score": round(float(avg_score), 2)}

if uploaded_video is not None:
    st.video(uploaded_video)
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    with open(temp_file.name, "wb") as f:
        f.write(uploaded_video.read())

    if st.button("Analyze Video"):
        if deepfake_video_model:
            st.write("🔍 Processing...")
            result = detect_deepfake_video(temp_file.name)

            if result is None:
                st.error("⚠️ Unable to analyze video.")
            elif result["label"] == "FAKE":
                st.warning(f"⚠️ Result: This video contains Deepfake elements. (Confidence: {result['score']:.2f})")
            else:
                st.success(f"✅ Result: This video is Real. (Confidence: {1 - result['score']:.2f})")
        else:
            st.error("Deepfake video detection model not loaded.")

st.markdown("🔹 **Developed for Fake News & Deepfake Detection Hackathon**")