asad231's picture
Update app.py
6702b7b verified
raw
history blame
10.3 kB
# 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 Models
# fake_news_detector = pipeline("text-classification", model="microsoft/deberta-v3-base")
# # 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=(299, 299)) # 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...")
# if st.button("Check News"):
# st.write("🔍 Processing...")
# prediction = fake_news_detector(news_input)
# label = prediction[0]['label']
# confidence = prediction[0]['score']
# if label == "FAKE":
# 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"] == "FAKE":
# st.error(f"⚠️ Result: This image is a Deepfake. (Confidence: {result['score']:.2f})")
# else:
# st.success(f"✅ Result: This image is Real. (Confidence: {1 - 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 = []
# while cap.isOpened():
# ret, frame = cap.read()
# if not ret:
# break
# 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)
# cap.release()
# 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"):
# st.write("🔍 Processing...")
# result = detect_deepfake_video(temp_file.name)
# if 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})")
# st.markdown("🔹 **Developed for Fake News & Deepfake Detection Hackathon**")
import streamlit as st
import numpy as np
from transformers import pipeline
import requests
# ---- Page Configuration ----
st.set_page_config(page_title="Fake News & Deepfake Detection", layout="wide")
st.title("📰 Fake News & Deepfake Detection Tool")
st.write("🚀 Detect Fake News, Deepfake Images, and Videos using AI")
# Load Improved Fake News Detection Model
fake_news_detector = pipeline("text-classification", model="roberta-base-openai-detector")
# Fact-Checking API Function
def fact_check_google(news_text):
api_url = f'https://factchecktools.googleapis.com/v1alpha1/claims:search?query={news_text}&key=YOUR_GOOGLE_FACTCHECK_API_KEY'
response = requests.get(api_url)
if response.status_code == 200:
data = response.json()
if "claims" in data:
return data["claims"]
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"):
st.write("🔍 Processing...")
# Step 1: AI-Based Classification
prediction = fake_news_detector(news_input)
label = prediction[0]['label']
confidence = prediction[0]['score']
# Step 2: Fact Checking via API
fact_check_result = fact_check_google(news_input)
if label == "FAKE":
st.error(f"⚠️ Result: This news is FAKE. (Confidence: {confidence:.2f})")
else:
st.success(f"✅ Result: This news is REAL. (Confidence: {confidence:.2f})")
# Display Fact Check Results
if fact_check_result:
st.write("📜 Fact Check Results:")
for claim in fact_check_result:
st.write(f"🔹 {claim['text']} - *{claim['claimReview'][0]['textualRating']}*")
else:
st.warning("⚠️ No Fact-Check Data Available.")
st.markdown("🔹 **Developed for Fake News & Deepfake Detection Hackathon**")