Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,187 +3,93 @@ import requests
|
|
3 |
from transformers import pipeline
|
4 |
from deepface import DeepFace
|
5 |
from PIL import Image
|
6 |
-
import
|
7 |
-
import
|
8 |
-
import
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
def
|
14 |
-
""
|
15 |
-
|
|
|
|
|
16 |
label = result['label'].lower()
|
17 |
-
score = result['score'] * 100
|
18 |
return ("Fake" if label == "fake" else "Real"), round(score, 2)
|
19 |
|
20 |
-
def analyze_image(image):
|
21 |
-
"""Analyzes image using DeepFace and Google Reverse Image Search."""
|
22 |
-
try:
|
23 |
-
analysis = DeepFace.analyze(image, actions=['emotion'])
|
24 |
-
dominant_emotion = analysis[0]['dominant_emotion']
|
25 |
-
reverse_search_url = reverse_image_search(image)
|
26 |
-
return f"Analysis: {dominant_emotion}", 90.0, reverse_search_url # Dummy Accuracy
|
27 |
-
except Exception as e:
|
28 |
-
return f"Error: {str(e)}", 0.0, None
|
29 |
-
|
30 |
-
def reverse_image_search(image):
|
31 |
-
"""Creates a Google Reverse Image Search link for verification."""
|
32 |
-
buffered = io.BytesIO()
|
33 |
-
image.save(buffered, format="PNG")
|
34 |
-
encoded_img = base64.b64encode(buffered.getvalue()).decode()
|
35 |
-
return f"https://www.google.com/searchbyimage?image_url=data:image/png;base64,{encoded_img}"
|
36 |
-
|
37 |
def verify_news(news_text):
|
38 |
-
"""Searches trusted fact-checking websites for news verification."""
|
39 |
sources = [
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
("Google Search", f"https://www.google.com/search?q={'+'.join(news_text.split())}")
|
47 |
]
|
48 |
-
|
49 |
-
|
50 |
-
def extract_video_id(video_url):
|
51 |
-
"""Extracts the video ID from a YouTube URL."""
|
52 |
-
pattern = r"(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})"
|
53 |
-
match = re.search(pattern, video_url)
|
54 |
-
return match.group(1) if match else None
|
55 |
|
56 |
-
def
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
if
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
# Classify the video metadata text
|
75 |
-
result, accuracy = classify_text(combined_text)
|
76 |
-
verification_links = verify_news(video_title)
|
77 |
-
return result, accuracy, verification_links
|
78 |
-
return "Unknown", 0.0, None
|
79 |
|
80 |
-
# Streamlit UI
|
81 |
st.set_page_config(page_title="Fake News Detector", layout="wide")
|
82 |
st.title("π° Fake News Detector")
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
st.
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
98 |
else:
|
99 |
-
|
100 |
-
verification_links = verify_news(news_text)
|
101 |
-
st.session_state["text_result"] = result
|
102 |
-
st.session_state["text_accuracy"] = accuracy
|
103 |
-
st.session_state["text_verification"] = verification_links
|
104 |
-
|
105 |
-
# πΉ Image Upload Section
|
106 |
-
with col2:
|
107 |
-
st.markdown("### πΌοΈ Image Upload")
|
108 |
-
uploaded_image = st.file_uploader("Upload a news image", type=["jpg", "png", "jpeg"])
|
109 |
-
analyze_image_clicked = st.button("Analyze Image")
|
110 |
-
|
111 |
-
if uploaded_image and analyze_image_clicked:
|
112 |
-
image = Image.open(uploaded_image)
|
113 |
-
result, accuracy, reverse_search_url = analyze_image(image)
|
114 |
-
st.session_state["image_result"] = result
|
115 |
-
st.session_state["image_accuracy"] = accuracy
|
116 |
-
st.session_state["image_search_url"] = reverse_search_url
|
117 |
-
st.session_state["news_image"] = image # Store Image for Display
|
118 |
-
|
119 |
-
# πΉ Video Link Section
|
120 |
-
with col3:
|
121 |
-
st.markdown("### π₯ Video Link")
|
122 |
-
video_url = st.text_input("Enter the video link:")
|
123 |
-
analyze_video_clicked = st.button("Analyze Video")
|
124 |
-
|
125 |
-
if analyze_video_clicked:
|
126 |
-
if not video_url.strip():
|
127 |
-
st.warning("Please enter a valid video link.")
|
128 |
-
else:
|
129 |
-
result, accuracy, verification_links = fetch_video_metadata(video_url)
|
130 |
-
st.session_state["video_result"] = result
|
131 |
-
st.session_state["video_accuracy"] = accuracy
|
132 |
-
st.session_state["video_verification"] = verification_links
|
133 |
-
st.session_state["video_url"] = video_url # Store Video URL for Display
|
134 |
-
|
135 |
-
# πΉ Results Section
|
136 |
-
st.subheader("π Analysis Results")
|
137 |
-
|
138 |
-
# πΉ Text Result
|
139 |
-
if "text_result" in st.session_state:
|
140 |
-
result = st.session_state["text_result"]
|
141 |
-
accuracy = st.session_state["text_accuracy"]
|
142 |
-
|
143 |
-
if result == "Fake":
|
144 |
-
st.error(f"β This news is **Fake**! (Accuracy: {accuracy}%)", icon="β οΈ")
|
145 |
-
else:
|
146 |
-
st.success(f"β
This news is **Real**! (Accuracy: {accuracy}%)", icon="β
")
|
147 |
-
|
148 |
-
st.subheader("π Trusted Fact-Checking Sources")
|
149 |
-
for name, link in st.session_state["text_verification"]:
|
150 |
-
st.markdown(f"[π {name}]({link})")
|
151 |
-
|
152 |
-
# πΉ Image Analysis Result Section
|
153 |
-
if "image_result" in st.session_state:
|
154 |
-
st.image(st.session_state["news_image"], caption="Uploaded Image", use_column_width=True)
|
155 |
-
|
156 |
-
if st.session_state["image_result"] == "Fake":
|
157 |
-
st.error(f"β **This image is likely Fake!** (Accuracy: {st.session_state['image_accuracy']}%)")
|
158 |
-
elif st.session_state["image_result"] == "Real":
|
159 |
-
st.success(f"β
**This image is likely Real!** (Accuracy: {st.session_state['image_accuracy']}%)")
|
160 |
-
else:
|
161 |
-
st.warning("β οΈ Unable to verify the authenticity of this image.")
|
162 |
-
|
163 |
-
# β
Add verification links
|
164 |
-
if st.session_state["image_verification"]:
|
165 |
-
st.subheader("π Trusted Fact-Checking Sources")
|
166 |
-
for name, link in st.session_state["image_verification"]:
|
167 |
-
st.markdown(f"[π {name}]({link})")
|
168 |
-
else:
|
169 |
-
st.warning("No verification sources available for this image.")
|
170 |
-
|
171 |
-
# πΉ Video Result
|
172 |
-
if "video_result" in st.session_state:
|
173 |
-
st.video(st.session_state["video_url"])
|
174 |
-
|
175 |
-
if st.session_state["video_result"] == "Fake":
|
176 |
-
st.error(f"β **This video is Fake!** (Accuracy: {st.session_state['video_accuracy']}%)")
|
177 |
-
elif st.session_state["video_result"] == "Real":
|
178 |
-
st.success(f"β
**This video is Real!** (Accuracy: {st.session_state['video_accuracy']}%)")
|
179 |
-
else:
|
180 |
-
st.warning("β οΈ Unable to verify the authenticity of this video.")
|
181 |
-
|
182 |
-
# β
Check if verification links exist before iterating
|
183 |
-
if st.session_state["video_verification"]:
|
184 |
-
st.subheader("π Trusted Fact-Checking Sources")
|
185 |
-
for name, link in st.session_state["video_verification"]:
|
186 |
-
st.markdown(f"[π {name}]({link})")
|
187 |
-
else:
|
188 |
-
st.warning("No verification sources available for this video.")
|
189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from transformers import pipeline
|
4 |
from deepface import DeepFace
|
5 |
from PIL import Image
|
6 |
+
import cv2
|
7 |
+
import torch
|
8 |
+
import torchvision.transforms as transforms
|
9 |
+
import numpy as np
|
10 |
+
import os
|
11 |
+
import json
|
12 |
+
|
13 |
+
def load_text_model():
|
14 |
+
return pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection")
|
15 |
+
|
16 |
+
def classify_text(news_text, text_model):
|
17 |
+
result = text_model(news_text)[0]
|
18 |
label = result['label'].lower()
|
19 |
+
score = result['score'] * 100
|
20 |
return ("Fake" if label == "fake" else "Real"), round(score, 2)
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
def verify_news(news_text):
|
|
|
23 |
sources = [
|
24 |
+
"https://www.bbc.com/news",
|
25 |
+
"https://www.cnn.com",
|
26 |
+
"https://www.reuters.com",
|
27 |
+
"https://factcheck.org",
|
28 |
+
"https://www.snopes.com",
|
29 |
+
"https://www.politifact.com"
|
|
|
30 |
]
|
31 |
+
search_url = f"https://www.google.com/search?q={'+'.join(news_text.split())}"
|
32 |
+
return sources, search_url
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
+
def analyze_image(image_path):
|
35 |
+
try:
|
36 |
+
result = DeepFace.analyze(image_path, actions=['age', 'gender', 'emotion'])
|
37 |
+
return "Real", 85.0 if result else "Fake", 60.0
|
38 |
+
except:
|
39 |
+
return "Fake", 50.0
|
40 |
+
|
41 |
+
def analyze_video(video_path):
|
42 |
+
cap = cv2.VideoCapture(video_path)
|
43 |
+
frames = []
|
44 |
+
while cap.isOpened():
|
45 |
+
ret, frame = cap.read()
|
46 |
+
if not ret:
|
47 |
+
break
|
48 |
+
frames.append(frame)
|
49 |
+
cap.release()
|
50 |
+
return "Real", 80.0 if len(frames) > 10 else "Fake", 40.0
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
|
|
52 |
st.set_page_config(page_title="Fake News Detector", layout="wide")
|
53 |
st.title("π° Fake News Detector")
|
54 |
|
55 |
+
text_model = load_text_model()
|
56 |
+
|
57 |
+
st.sidebar.title("Select Input Type")
|
58 |
+
option = st.sidebar.radio("Choose an option", ["Text", "Image", "Video"])
|
59 |
+
|
60 |
+
if option == "Text":
|
61 |
+
news_text = st.text_area("Enter the news content:")
|
62 |
+
if st.button("Analyze News"):
|
63 |
+
if news_text.strip():
|
64 |
+
result, accuracy = classify_text(news_text, text_model)
|
65 |
+
sources, verification_link = verify_news(news_text)
|
66 |
+
st.write(f"Result: **{result}** (Accuracy: {accuracy}%)")
|
67 |
+
for link in sources:
|
68 |
+
st.markdown(f"[π {link}]({link})")
|
69 |
+
st.markdown(f"[π Verify on Google]({verification_link})")
|
70 |
else:
|
71 |
+
st.warning("Please enter some text.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
+
elif option == "Image":
|
74 |
+
uploaded_image = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
|
75 |
+
if uploaded_image:
|
76 |
+
img = Image.open(uploaded_image)
|
77 |
+
img_path = "uploaded_image.jpg"
|
78 |
+
img.save(img_path)
|
79 |
+
if st.button("Analyze Image"):
|
80 |
+
result, accuracy = analyze_image(img_path)
|
81 |
+
st.image(img, caption="Uploaded Image", use_column_width=True)
|
82 |
+
st.write(f"Result: **{result}** (Accuracy: {accuracy}%)")
|
83 |
+
os.remove(img_path)
|
84 |
+
|
85 |
+
elif option == "Video":
|
86 |
+
uploaded_video = st.file_uploader("Upload a video", type=["mp4", "avi", "mov"])
|
87 |
+
if uploaded_video:
|
88 |
+
video_path = "uploaded_video.mp4"
|
89 |
+
with open(video_path, "wb") as f:
|
90 |
+
f.write(uploaded_video.read())
|
91 |
+
if st.button("Analyze Video"):
|
92 |
+
result, accuracy = analyze_video(video_path)
|
93 |
+
st.video(video_path)
|
94 |
+
st.write(f"Result: **{result}** (Accuracy: {accuracy}%)")
|
95 |
+
os.remove(video_path)
|