File size: 7,872 Bytes
62c311b
a7f66d4
81a136d
28d0426
c8d1c47
 
a1b2fed
2ee8dae
62c311b
c8d1c47
 
107dbe8
a7f66d4
c8d1c47
5bc427c
 
 
 
a7f66d4
c8d1c47
2ee8dae
c8d1c47
 
 
2ee8dae
 
c8d1c47
2ee8dae
 
 
 
 
 
 
 
c8d1c47
ea6e24c
2ee8dae
 
 
 
 
 
 
 
 
 
 
ea6e24c
a1b2fed
 
 
 
 
 
 
 
 
 
2ee8dae
a1b2fed
 
 
c8d1c47
a1b2fed
c8d1c47
 
a1b2fed
 
 
 
 
 
 
 
2ee8dae
 
 
a7f66d4
62c311b
7e55fba
 
 
a346939
 
ea6e24c
a346939
5ff1805
c8d1c47
a346939
 
 
 
 
 
f1dc8a7
 
 
 
2ee8dae
a346939
 
2ee8dae
ea6e24c
c8d1c47
a346939
 
f1dc8a7
a346939
 
 
f1dc8a7
2ee8dae
a346939
 
2ee8dae
a346939
a7c9258
c8d1c47
a346939
 
f1dc8a7
a346939
 
 
f1dc8a7
 
 
2ee8dae
a346939
 
2ee8dae
a346939
c8d1c47
 
 
a346939
 
 
 
 
c8d1c47
 
a346939
c8d1c47
a346939
 
2ee8dae
 
 
a346939
a5b7aa4
a346939
c8d1c47
a5b7aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8d1c47
a346939
 
c8d1c47
a5b7aa4
a1b2fed
 
 
 
 
 
a5b7aa4
 
 
 
 
 
 
 
 
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
import streamlit as st
import requests
from transformers import pipeline
from deepface import DeepFace
from PIL import Image
import io
import re
import base64

# 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 Google Reverse Image Search."""
    try:
        analysis = DeepFace.analyze(image, actions=['emotion'])
        dominant_emotion = analysis[0]['dominant_emotion']
        reverse_search_url = reverse_image_search(image)
        return f"Analysis: {dominant_emotion}", 90.0, reverse_search_url  # Dummy Accuracy
    except Exception as e:
        return f"Error: {str(e)}", 0.0, None

def reverse_image_search(image):
    """Creates a Google Reverse Image Search link for verification."""
    buffered = io.BytesIO()
    image.save(buffered, format="PNG")
    encoded_img = base64.b64encode(buffered.getvalue()).decode()
    return f"https://www.google.com/searchbyimage?image_url=data:image/png;base64,{encoded_img}"

def verify_news(news_text):
    """Searches trusted fact-checking websites for news verification."""
    sources = [
        ("BBC News", "https://www.bbc.com/news"),
        ("CNN", "https://www.cnn.com"),
        ("Reuters", "https://www.reuters.com"),
        ("FactCheck.org", "https://www.factcheck.org"),
        ("Snopes", "https://www.snopes.com"),
        ("PolitiFact", "https://www.politifact.com"),
        ("Google Search", f"https://www.google.com/search?q={'+'.join(news_text.split())}")
    ]
    return sources

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, None

    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)
            verification_links = verify_news(video_title)
            return result, accuracy, verification_links
    return "Unknown", 0.0, None

# 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)
            verification_links = verify_news(news_text)
            st.session_state["text_result"] = result
            st.session_state["text_accuracy"] = accuracy
            st.session_state["text_verification"] = verification_links

# πŸ”Ή 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, reverse_search_url = analyze_image(image)
        st.session_state["image_result"] = result
        st.session_state["image_accuracy"] = accuracy
        st.session_state["image_search_url"] = reverse_search_url
        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, verification_links = fetch_video_metadata(video_url)
            st.session_state["video_result"] = result
            st.session_state["video_accuracy"] = accuracy
            st.session_state["video_verification"] = verification_links
            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="βœ…")
    
    st.subheader("πŸ”Ž Trusted Fact-Checking Sources")
    for name, link in st.session_state["text_verification"]:
        st.markdown(f"[πŸ”— {name}]({link})")

# πŸ”Ή Image Analysis Result Section
if "image_result" in st.session_state:
    st.image(st.session_state["news_image"], caption="Uploaded Image", use_column_width=True)

    if st.session_state["image_result"] == "Fake":
        st.error(f"❌ **This image is likely Fake!** (Accuracy: {st.session_state['image_accuracy']}%)")
    elif st.session_state["image_result"] == "Real":
        st.success(f"βœ… **This image is likely Real!** (Accuracy: {st.session_state['image_accuracy']}%)")
    else:
        st.warning("⚠️ Unable to verify the authenticity of this image.")

    # βœ… Add verification links
    if st.session_state["image_verification"]:
        st.subheader("πŸ”Ž Trusted Fact-Checking Sources")
        for name, link in st.session_state["image_verification"]:
            st.markdown(f"[πŸ”— {name}]({link})")
    else:
        st.warning("No verification sources available for this image.")

# πŸ”Ή 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.")

    # βœ… Check if verification links exist before iterating
    if st.session_state["video_verification"]:
        st.subheader("πŸ”Ž Trusted Fact-Checking Sources")
        for name, link in st.session_state["video_verification"]:
            st.markdown(f"[πŸ”— {name}]({link})")
    else:
        st.warning("No verification sources available for this video.")