Nimzi commited on
Commit
71c7fc8
Β·
verified Β·
1 Parent(s): 1e2b9dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -70
app.py CHANGED
@@ -1,95 +1,150 @@
1
  import streamlit as st
2
  import requests
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import requests
3
  from transformers import pipeline
 
4
  from PIL import Image
 
5
  import torch
6
  import torchvision.transforms as transforms
7
+ import cv2
8
  import numpy as np
9
+ from deepface import DeepFace
10
+ from bs4 import BeautifulSoup
11
 
12
+ # Load Fake News Detection Model (Text)
13
+ fake_news_pipeline = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection")
14
 
15
+ # Function to classify text as Fake or Real
16
+ def classify_text(news_text):
17
+ result = fake_news_pipeline(news_text)[0]
18
  label = result['label'].lower()
19
+ score = result['score'] * 100 # Convert to percentage
20
  return ("Fake" if label == "fake" else "Real"), round(score, 2)
21
 
22
+ # Function to analyze image authenticity
23
+ def analyze_image(image):
24
+ try:
25
+ image_array = np.array(image)
26
+ result = DeepFace.analyze(image_array, actions=["age", "gender", "race"], enforce_detection=False)
27
+ return "Real" if result else "Fake", 90 # Placeholder accuracy
28
+ except Exception as e:
29
+ return "Error", str(e)
30
+
31
+ # Function to verify news from open sources
32
  def verify_news(news_text):
 
 
 
 
 
 
 
 
33
  search_url = f"https://www.google.com/search?q={'+'.join(news_text.split())}"
34
+ response = requests.get(search_url)
35
+ soup = BeautifulSoup(response.text, "html.parser")
36
+
37
+ results = []
38
+ for link in soup.find_all("a", href=True):
39
+ if "http" in link["href"] and "google" not in link["href"]:
40
+ results.append((link.text.strip(), link["href"]))
41
+ if len(results) >= 3: # Limit to 3 sources
 
 
 
 
 
 
 
42
  break
43
+ return results
 
 
44
 
45
+ # Streamlit UI Configuration
46
  st.set_page_config(page_title="Fake News Detector", layout="wide")
47
  st.title("πŸ“° Fake News Detector")
48
 
49
+ # Sidebar Input Selection
 
50
  st.sidebar.title("Select Input Type")
51
+ option = st.sidebar.radio("Choose an option", ["Text", "Image", "Video Link"])
52
+
53
+ # Session Variables
54
+ if "result_text" not in st.session_state:
55
+ st.session_state["result_text"] = None
56
+ if "accuracy_text" not in st.session_state:
57
+ st.session_state["accuracy_text"] = None
58
+ if "result_image" not in st.session_state:
59
+ st.session_state["result_image"] = None
60
+ if "accuracy_image" not in st.session_state:
61
+ st.session_state["accuracy_image"] = None
62
+ if "video_result" not in st.session_state:
63
+ st.session_state["video_result"] = None
64
 
65
+ # Input Section
66
  if option == "Text":
67
+ news_text = st.text_area("Enter the news content to check:", height=200)
68
+ analyze_text_clicked = st.button("Analyze News")
69
+
70
+ if analyze_text_clicked:
71
+ if not news_text.strip():
 
 
 
 
 
72
  st.warning("Please enter some text.")
73
+ else:
74
+ result, accuracy = classify_text(news_text)
75
+ st.session_state["result_text"] = result
76
+ st.session_state["accuracy_text"] = accuracy
77
+ verification_links = verify_news(news_text)
78
+ st.session_state["verification_text"] = verification_links
79
 
80
  elif option == "Image":
81
+ uploaded_image = st.file_uploader("Upload a news image", type=["jpg", "png", "jpeg"])
82
+ analyze_image_clicked = st.button("Analyze Image")
83
+
84
+ if uploaded_image and analyze_image_clicked:
85
+ image = Image.open(uploaded_image)
86
+ result, accuracy = analyze_image(image)
87
+ st.session_state["result_image"] = result
88
+ st.session_state["accuracy_image"] = accuracy
89
+
90
+ elif option == "Video Link":
91
+ video_url = st.text_input("Enter the video link:")
92
+ analyze_video_clicked = st.button("Analyze Video")
93
+
94
+ if analyze_video_clicked:
95
+ if not video_url.strip():
96
+ st.warning("Please enter a valid video link.")
97
+ else:
98
+ st.session_state["video_result"] = "Real" # Placeholder (Video verification requires advanced models)
99
+
100
+ # Results Section
101
+ st.subheader("πŸ“Š Analysis Results")
102
+
103
+ # Text Results
104
+ if st.session_state.get("result_text"):
105
+ result = st.session_state["result_text"]
106
+ accuracy = st.session_state["accuracy_text"]
107
+ st.subheader("πŸ“ Text Analysis")
108
+
109
+ if result == "Fake":
110
+ st.error(f"❌ This news is likely **Fake**! (Accuracy: {accuracy}%)", icon="⚠️")
111
+ else:
112
+ st.success(f"βœ… This news is likely **Real**! (Accuracy: {accuracy}%)", icon="βœ…")
113
+
114
+ st.subheader("πŸ” Verification & Trusted Sources")
115
+ sources = [
116
+ "https://www.bbc.com/news",
117
+ "https://www.cnn.com",
118
+ "https://www.reuters.com",
119
+ "https://factcheck.org",
120
+ "https://www.snopes.com",
121
+ "https://www.politifact.com"
122
+ ]
123
+ for link in sources:
124
+ st.markdown(f"[πŸ”— {link}]({link})")
125
+
126
+ if "verification_text" in st.session_state:
127
+ for name, link in st.session_state["verification_text"]:
128
+ st.markdown(f"[πŸ” {name}]({link})")
129
+
130
+ # Image Results
131
+ if st.session_state.get("result_image"):
132
+ result = st.session_state["result_image"]
133
+ accuracy = st.session_state["accuracy_image"]
134
+ st.subheader("πŸ–ΌοΈ Image Analysis")
135
+
136
+ if result == "Fake":
137
+ st.error(f"❌ This image is likely **Fake**! (Accuracy: {accuracy}%)", icon="⚠️")
138
+ else:
139
+ st.success(f"βœ… This image is likely **Real**! (Accuracy: {accuracy}%)", icon="βœ…")
140
+
141
+ # Video Results
142
+ if st.session_state.get("video_result"):
143
+ result = st.session_state["video_result"]
144
+ st.subheader("πŸ“Ή Video Analysis")
145
+
146
+ if result == "Fake":
147
+ st.error("❌ This video is likely **Fake**!", icon="⚠️")
148
+ else:
149
+ st.success("βœ… This video is likely **Real**!", icon="βœ…")
150
+