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
 
 
5242e79
bd1ee8d
 
 
 
 
2405a2e
5242e79
 
 
c51b4df
5242e79
 
 
 
bd1ee8d
 
5242e79
 
 
 
bd1ee8d
5242e79
bd1ee8d
5242e79
 
bd1ee8d
4578e0e
db588d5
 
 
 
 
 
 
 
 
 
 
 
 
 
4578e0e
 
 
 
 
 
 
 
 
 
 
 
 
db588d5
 
 
8eb6c20
 
 
 
 
 
 
 
4578e0e
8eb6c20
4578e0e
 
 
 
 
 
8eb6c20
9eb2d43
 
 
 
 
 
 
 
 
 
 
 
 
 
c51b4df
2405a2e
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# 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 requests
from pytube import YouTube
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 Models
fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")

@st.cache_resource
def load_fake_news_model():
    return pipeline("text-classification", model="microsoft/deberta-v3-base")

@st.cache_resource
def load_deepfake_models():
    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)

    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)

    return deepfake_image_model, deepfake_video_model

# Load models once in cache
fake_news_detector = load_fake_news_model()
deepfake_image_model, deepfake_video_model = load_deepfake_models()


# Load Deepfake Detection Models
base_model_image = Xception(weights="imagenet", include_top=False)
base_model_image.trainable = False  # Freeze base layers
x = GlobalAveragePooling2D()(base_model_image.output)
x = Dense(1024, activation="relu")(x)
x = Dense(1, activation="sigmoid")(x)  # Sigmoid for probability output
deepfake_image_model = Model(inputs=base_model_image.input, outputs=x)

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)

# Function to Preprocess Image
def preprocess_image(image_path):
    img = load_img(image_path, target_size=(100, 100))  # Xception expects 299x299
    img = img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img /= 255.0  # Normalize pixel values
    return img

# Function to Detect Deepfake Image
def detect_deepfake_image(image_path):
    image = preprocess_image(image_path)
    prediction = deepfake_image_model.predict(image)[0][0]
    confidence = round(float(prediction), 2)
    label = "FAKE" if confidence > 0.5 else "REAL"
    return {"label": label, "score": confidence}

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

# Manually verified facts database (you can expand this)
fact_check_db = {
    "elon musk was born in 1932": "FAKE",
    "earth revolves around the sun": "REAL",
    "the moon is made of cheese": "FAKE",
    "water boils at 100 degrees celsius": "REAL",
    "the great wall of china is visible from space": "FAKE",
    "human beings need oxygen to survive": "REAL",
    "vaccines cause autism": "FAKE",
    "the sun rises in the west": "FAKE",
    "chocolate is toxic to dogs": "REAL",
    "microsoft was founded by bill gates": "REAL",
    "dinosaurs and humans lived together": "FAKE",
    "the eiffel tower is in italy": "FAKE",
    "the speed of light is faster than sound": "REAL",
    "5g technology spreads covid-19": "FAKE",
    "honey never spoils": "REAL",
    "napoleon was extremely short": "FAKE",
    "goldfish have a three-second memory": "FAKE",
    "einstein failed math in school": "FAKE",
    "birds are descendants of dinosaurs": "REAL",
    "water is composed of hydrogen and oxygen": "REAL",
    "humans only use 10 percent of their brain": "FAKE",
    "the human body has 206 bones": "REAL",
    "the great pyramid of giza was built by aliens": "FAKE",
    "the internet was invented in 1983": "REAL",
    "earth is flat": "FAKE",
    "bananas grow on trees": "FAKE",
    "polar bears are left-handed": "FAKE",
    "the amazon rainforest produces 20 percent of the world's oxygen": "REAL",
    "dogs can see only black and white": "FAKE",
    "lightning never strikes the same place twice": "FAKE",
    "the shortest war lasted only 38 minutes": "REAL",
    "there is no gravity in space": "FAKE",
    "sharks do not get cancer": "FAKE",
    "the human heart beats about 100,000 times a day": "REAL",
    "albert einstein was a high school dropout": "FAKE",
    "diamonds are formed from coal": "FAKE",
    "the human tongue has different taste zones": "FAKE",
    "tomatoes are a fruit": "REAL",
    "a year on venus is shorter than a day": "REAL",
    "vikings wore horned helmets": "FAKE",
    "the moon has its own gravity": "REAL",
    "sugar causes hyperactivity in children": "FAKE",
    "human blood is blue inside the body": "FAKE",
    "gold is edible": "REAL",
    "ostriches bury their heads in the sand": "FAKE",
    "earth is the only planet with water": "FAKE",
    "black holes can evaporate": "REAL",
    "a penny dropped from the empire state building can kill a person": "FAKE",
    "octopuses have three hearts": "REAL",
    "mars is red because of iron oxide": "REAL",
    "eating carrots improves eyesight": "FAKE",
    "the human nose and ears keep growing with age": "REAL",
    "the leaning tower of pisa has always leaned": "REAL",
    "bats are blind": "FAKE",
    "you swallow eight spiders a year in your sleep": "FAKE",
    "the statue of liberty was a gift from france": "REAL",
    "light bulbs were invented by thomas edison": "REAL",
    "chameleons change color to match their surroundings": "FAKE",
    "dogs have unique nose prints": "REAL",
    "some frogs can survive being frozen": "REAL",
    "birds die if they eat rice": "FAKE",
    "a group of crows is called a murder": "REAL",
    "human dna is 60% similar to bananas": "REAL",
    "snakes can dislocate their jaws": "REAL",
    "the longest english word has 189,819 letters": "REAL",
    "there are more trees on earth than stars in the milky way": "REAL",
    "bananas are berries": "REAL",
    "peanuts are nuts": "FAKE",
    "avocados are poisonous to birds": "REAL",
    "a day on mercury is longer than its year": "REAL",
    "sharks existed before trees": "REAL",
    "the olympics were originally held in greece": "REAL",
    "human fingers have no muscles": "REAL",
    "cows have best friends": "REAL",
    "the inventor of the frisbee was turned into a frisbee after he died": "REAL",
    "watermelon is 92% water": "REAL",
    "new york was once called new amsterdam": "REAL",
    "the heart of a blue whale is the size of a small car": "REAL",
    "giraffes have the same number of neck bones as humans": "REAL",
    "venus is the hottest planet in the solar system": "REAL",
    "your hair and nails continue to grow after death": "FAKE",
    "the sun is a star": "REAL",
    "the human body glows in the dark but is invisible to the naked eye": "REAL",
    "barbie’s full name is barbara millicent roberts": "REAL",
    "ants can carry 50 times their own body weight": "REAL",
    "rabbits can’t vomit": "REAL",
    "the speed of sound is faster in water than in air": "REAL",
    "every planet in our solar system could fit between earth and the moon": "REAL",
    "a single lightning bolt is five times hotter than the sun’s surface": "REAL",
    "mosquitoes are the deadliest animals on earth": "REAL",
    "sea otters hold hands while sleeping": "REAL",
    "the empire state building can be seen from space": "FAKE",
    "your stomach gets a new lining every 3 to 4 days": "REAL",
    "hummingbirds can fly backward": "REAL",
    "a shrimp’s heart is in its head": "REAL",
    "the eiffel tower grows in the summer": "REAL",
    "neptune was the first planet discovered using math": "REAL"
}
def check_manual_facts(text):
    text_lower = text.lower().strip()
    return fact_check_db.get(text_lower, None)

if st.button("Check News"):
    # st.write("🔍 Processing...")
    loading_placeholder = st.empty()
    with loading_placeholder:
        st.markdown("<div style='text-align: center;'>🔍 Processing...</div>", unsafe_allow_html=True)

    # Check if the news is in the fact-check database
    manual_result = check_manual_facts(news_input)
    if manual_result:
        if manual_result == "FAKE":
            st.error(f"⚠️ Result: This news is **FAKE** (Verified by Database).")
        else:
            st.success(f"✅ Result: This news is **REAL** (Verified by Database).")
    else:
        # Use AI model if fact is not in the database
        prediction = fake_news_detector(news_input)
        label = prediction[0]['label'].lower()
        confidence = prediction[0]['score']

        if "fake" in label or confidence < 0.5:
            st.error(f"⚠️ Result: This news is **FAKE**. (Confidence: {confidence:.2f})")
        else:
            st.success(f"✅ Result: This news is **REAL**. (Confidence: {confidence:.2f})")

# ---- 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"):
        st.write("🔍 Processing...")
        result = detect_deepfake_image(temp_file.name)
        
        if result["label"] == "REAL":
          st.success(f"✅ Result: This image is Real. (Confidence: {1 - result['score']:.2f})")
        else: 
            
            st.error(f"⚠️ Result: This image is a Deepfake. (Confidence: {result['score']:.2f})")

# # ---- 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 = []
#     frame_count = 0
    
#     while cap.isOpened():
#         ret, frame = cap.read()
#         if not ret:
#             break
        
#         if frame_count % 10 == 0:  # ہر 10ویں فریم کا تجزیہ کریں
#             frame_path = "temp_frame.jpg"
#             cv2.imwrite(frame_path, frame)
#             result = detect_deepfake_image(frame_path)
#             frame_scores.append(result["score"])
#             os.remove(frame_path)
        
#         frame_count += 1
    
#     cap.release()
    
#     if not frame_scores:
#         return {"label": "UNKNOWN", "score": 0.0}  # اگر کوئی فریم پراسیس نہ ہو سکے
    
#     avg_score = np.mean(frame_scores)
#     confidence = round(float(avg_score), 2)
#     final_label = "FAKE" if avg_score > 0.5 else "REAL"
    
#     return {"label": final_label, "score": confidence}

# 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"):
#         st.write("🔍 Processing... Please wait.")
#         result = detect_deepfake_video(temp_file.name)
        
#         if result["label"] == "FAKE":
#             st.error(f"⚠️ Deepfake Detected! This video appears to be FAKE. (Confidence: {result['score']:.2f})")
#         elif result["label"] == "REAL":
#             st.success(f"✅ This video appears to be REAL. (Confidence: {1 - result['score']:.2f})")
#         else:
#             st.warning("⚠️ Unable to analyze the video. Please try a different file.")
# ---- Deepfake Video Detection Section ----
st.subheader("🎥 Deepfake Video Detection")

# Upload video file
uploaded_video = st.file_uploader("Upload a Video", type=["mp4", "avi", "mov"])

# URL Input for Video (MP4 Direct Link or YouTube URL)
video_url = st.text_input("Enter Video URL (YouTube or MP4 Link)")

# Function to detect deepfake in video
def detect_deepfake_video(video_path):
    cap = cv2.VideoCapture(video_path)
    frame_scores = []
    frame_count = 0
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        
        if frame_count % 10 == 0:  # ہر 10ویں فریم کا تجزیہ کریں
            frame_path = "temp_frame.jpg"
            cv2.imwrite(frame_path, frame)
            result = detect_deepfake_image(frame_path)  # Deepfake detection function
            frame_scores.append(result["score"])
            os.remove(frame_path)
        
        frame_count += 1
    
    cap.release()
    
    if not frame_scores:
        return {"label": "UNKNOWN", "score": 0.0}  # اگر کوئی فریم پراسیس نہ ہو سکے
    
    avg_score = np.mean(frame_scores)
    confidence = round(float(avg_score), 2)
    final_label = "FAKE" if avg_score > 0.5 else "REAL"
    
    return {"label": final_label, "score": confidence}

# Download video from direct MP4 URL
def download_video(url):
    try:
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(temp_file.name, "wb") as f:
                for chunk in response.iter_content(chunk_size=1024):
                    f.write(chunk)
            return temp_file.name
        else:
            return None
    except Exception as e:
        return None

# Download YouTube video
def download_youtube_video(youtube_url):
    try:
        yt = YouTube(youtube_url)
        video_stream = yt.streams.filter(file_extension="mp4", res="360p").first()
        if not video_stream:
            video_stream = yt.streams.get_lowest_resolution()
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
        video_stream.download(filename=temp_file.name)
        return temp_file.name
    except Exception as e:
        return None

# Select Video Source
video_path = None

# Process Uploaded Video
if uploaded_video is not None:
    st.video(uploaded_video)  # Show uploaded video
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    with open(temp_file.name, "wb") as f:
        f.write(uploaded_video.read())
    video_path = temp_file.name  # Set video path for detection

# Process Video from URL (Check if YouTube or Direct Link)
elif video_url:
    if "youtube.com" in video_url or "youtu.be" in video_url:
        st.video(video_url)  # Show YouTube video
        video_path = download_youtube_video(video_url)  # Download YouTube video
    else:
        st.video(video_url)  # Show direct MP4 video
        video_path = download_video(video_url)  # Download direct MP4 video

# Ensure video_path is valid before analysis
if video_path and os.path.exists(video_path):
    if st.button("Analyze Video"):
        st.write("🔍 Processing... Please wait.")
        result = detect_deepfake_video(video_path)
        
        if result["label"] == "FAKE":
            st.error(f"⚠️ Deepfake Detected! This video appears to be FAKE. (Confidence: {result['score']:.2f})")
        elif result["label"] == "REAL":
            st.success(f"✅ This video appears to be REAL. (Confidence: {1 - result['score']:.2f})")
        else:
            st.warning("⚠️ Unable to analyze the video. Please try a different file.")
else:
    st.warning("⚠️ Please upload a video or enter a valid URL.")
            
st.markdown("🔹 **Developed for Fake News & Deepfake Detection Hackathon**")