import streamlit as st import requests from transformers import pipeline from deepface import DeepFace from PIL import Image import io import re # Load Fake News Detection Model from Hugging Face fake_news_pipeline = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection") def classify_text(news_text): """Classifies text as Fake or Real with accuracy.""" result = fake_news_pipeline(news_text)[0] label = result['label'].lower() score = result['score'] * 100 # Convert to percentage return ("Fake" if label == "fake" else "Real"), round(score, 2) def analyze_image(image): """Analyzes image using DeepFace and provides a result.""" try: analysis = DeepFace.analyze(image, actions=['emotion']) dominant_emotion = analysis[0]['dominant_emotion'] return f"Analysis Complete - Dominant Emotion: {dominant_emotion}", 90.0 # Dummy Accuracy except Exception as e: return f"Error: {str(e)}", 0.0 def verify_news(news_text): """Generates a Google search link for verification.""" search_url = f"https://www.google.com/search?q={'+'.join(news_text.split())}" return search_url def extract_video_id(video_url): """Extracts the video ID from a YouTube URL.""" pattern = r"(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})" match = re.search(pattern, video_url) return match.group(1) if match else None def fetch_video_metadata(video_url): """Fetches video metadata and runs Fake News detection on it.""" video_id = extract_video_id(video_url) if not video_id: return "Invalid Video URL", 0.0 api_key = "YOUR_YOUTUBE_API_KEY" # Replace with a valid YouTube API Key metadata_url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=snippet&key={api_key}" response = requests.get(metadata_url) if response.status_code == 200: data = response.json() if "items" in data and len(data["items"]) > 0: video_details = data["items"][0]["snippet"] video_title = video_details["title"] video_description = video_details["description"] combined_text = video_title + " " + video_description # Classify the video metadata text result, accuracy = classify_text(combined_text) return result, accuracy return "Unknown", 0.0 # Streamlit UI st.set_page_config(page_title="Fake News Detector", layout="wide") st.title("📰 Fake News Detector") # 🔹 Three Separate Sections for Input st.subheader("🔍 Choose an Input Type") col1, col2, col3 = st.columns(3) # 🔹 Text Input Section with col1: st.markdown("### 📄 Text Input") news_text = st.text_area("Enter the news content to check:", height=150) analyze_text_clicked = st.button("Analyze News") if analyze_text_clicked: if not news_text.strip(): st.warning("Please enter some text.") else: result, accuracy = classify_text(news_text) st.session_state["text_result"] = result st.session_state["text_accuracy"] = accuracy # 🔹 Image Upload Section with col2: st.markdown("### 🖼️ Image Upload") uploaded_image = st.file_uploader("Upload a news image", type=["jpg", "png", "jpeg"]) analyze_image_clicked = st.button("Analyze Image") if uploaded_image and analyze_image_clicked: image = Image.open(uploaded_image) result, accuracy = analyze_image(image) st.session_state["image_result"] = result st.session_state["image_accuracy"] = accuracy st.session_state["news_image"] = image # Store Image for Display # 🔹 Video Link Section with col3: st.markdown("### 🎥 Video Link") video_url = st.text_input("Enter the video link:") analyze_video_clicked = st.button("Analyze Video") if analyze_video_clicked: if not video_url.strip(): st.warning("Please enter a valid video link.") else: result, accuracy = fetch_video_metadata(video_url) st.session_state["video_result"] = result st.session_state["video_accuracy"] = accuracy st.session_state["video_url"] = video_url # Store Video URL for Display # 🔹 Results Section st.subheader("📊 Analysis Results") # 🔹 Text Result if "text_result" in st.session_state: result = st.session_state["text_result"] accuracy = st.session_state["text_accuracy"] if result == "Fake": st.error(f"❌ This news is **Fake**! (Accuracy: {accuracy}%)", icon="⚠️") else: st.success(f"✅ This news is **Real**! (Accuracy: {accuracy}%)", icon="✅") verification_link = verify_news(news_text) st.markdown(f"[🔎 Verify on Google]({verification_link})") # 🔹 Image Result if "image_result" in st.session_state: st.image(st.session_state["news_image"], caption="Uploaded Image", use_column_width=True) st.info(f"🖼️ **Image Analysis Result:** {st.session_state['image_result']} (Accuracy: {st.session_state['image_accuracy']}%)") # 🔹 Video Result if "video_result" in st.session_state: st.video(st.session_state["video_url"]) if st.session_state["video_result"] == "Fake": st.error(f"❌ **This video is Fake!** (Accuracy: {st.session_state['video_accuracy']}%)") elif st.session_state["video_result"] == "Real": st.success(f"✅ **This video is Real!** (Accuracy: {st.session_state['video_accuracy']}%)") else: st.warning("⚠️ Unable to verify the authenticity of this video.")