syeda-Rija20 commited on
Commit
8714ae5
Β·
verified Β·
1 Parent(s): b2b870e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -61
app.py CHANGED
@@ -2,115 +2,142 @@ import streamlit as st
2
  import numpy as np
3
  import tensorflow as tf
4
  from tensorflow.keras.preprocessing import image
5
- import pickle
6
- import requests
7
- import io
8
 
9
  # ---------------------------
10
  # PAGE CONFIG
11
  # ---------------------------
12
- st.set_page_config(page_title="TruthGuard AI", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
 
 
 
14
  st.title("πŸ›‘οΈ TruthGuard AI")
15
- st.subheader("Multi-Modal Fake News & AI Image Detection")
16
 
17
  # ---------------------------
18
  # LOAD MODELS
19
  # ---------------------------
20
 
21
- # Fake News Model (load from Hugging Face)
22
  @st.cache_resource
23
  def load_text_model():
24
- url = "https://huggingface.co/Maheentouqeer1/truthguard-fake-news-detector/resolve/main/fake_news_model.pkl"
25
- vectorizer_url = "https://huggingface.co/Maheentouqeer1/truthguard-fake-news-detector/resolve/main/tfidf_vectorizer.pkl"
26
-
27
- model_file = requests.get(url).content
28
- vectorizer_file = requests.get(vectorizer_url).content
29
-
30
- model = pickle.loads(model_file)
31
- vectorizer = pickle.loads(vectorizer_file)
32
-
33
- return model, vectorizer
 
 
 
 
34
 
35
- # Image Model
36
  @st.cache_resource
37
  def load_image_model():
38
- url = "https://huggingface.co/syeda-Rija20/image-detector/resolve/main/image_detector_finetuned.h5"
39
- model_file = requests.get(url).content
40
-
41
- with open("temp_model.h5", "wb") as f:
42
- f.write(model_file)
43
 
44
- model = tf.keras.models.load_model("temp_model.h5")
45
- return model
 
46
 
 
 
47
 
48
- text_model, vectorizer = load_text_model()
49
- image_model = load_image_model()
50
-
51
  # ---------------------------
52
- # TEXT CLEANING FUNCTION
53
  # ---------------------------
54
- import re
55
- import string
 
 
 
 
 
 
 
 
 
56
 
57
- def clean_text(text):
58
- text = text.lower()
59
- text = re.sub(r'http\S+', '', text)
60
- text = text.translate(str.maketrans('', '', string.punctuation))
61
- text = re.sub(r'\d+', '', text)
62
- return text
63
 
64
  # ---------------------------
65
- # TABS UI
66
  # ---------------------------
67
  tab1, tab2 = st.tabs(["πŸ“° Fake News Detection", "πŸ–ΌοΈ AI Image Detection"])
68
 
69
  # ===========================
70
- # TAB 1 β†’ FAKE NEWS
71
  # ===========================
72
  with tab1:
73
- st.header("Fake News Detector")
74
 
75
- user_input = st.text_area("Enter news text:")
76
 
77
- if st.button("Analyze News"):
78
  if user_input.strip() == "":
79
  st.warning("Please enter some text")
80
  else:
81
- clean = clean_text(user_input)
82
- vector = vectorizer.transform([clean])
83
-
84
- prediction = text_model.predict(vector)[0]
85
- prob = text_model.predict_proba(vector)[0]
86
-
87
- fake_prob = prob[0] * 100
88
- real_prob = prob[1] * 100
89
 
90
- if prediction == 0:
91
- st.error(f"⚠️ FAKE NEWS ({fake_prob:.2f}%)")
92
  else:
93
- st.success(f"βœ… REAL NEWS ({real_prob:.2f}%)")
94
 
95
- st.write("### Confidence Scores")
96
- st.write(f"Fake: {fake_prob:.2f}%")
97
- st.write(f"Real: {real_prob:.2f}%")
98
 
99
  # ===========================
100
- # TAB 2 β†’ IMAGE DETECTOR
101
  # ===========================
102
  with tab2:
103
- st.header("AI Image Detector")
104
 
105
- uploaded_file = st.file_uploader("Upload Image", type=["jpg", "png"])
106
 
107
  if uploaded_file is not None:
108
  img = image.load_img(uploaded_file, target_size=(224, 224))
 
 
109
  img_array = image.img_to_array(img) / 255.0
110
  img_array = np.expand_dims(img_array, axis=0)
111
 
112
  prediction = image_model.predict(img_array)
113
-
114
  confidence = float(prediction[0][0]) * 100
115
 
116
  if prediction[0][0] > 0.5:
@@ -118,5 +145,10 @@ with tab2:
118
  else:
119
  st.success(f"βœ… REAL IMAGE ({100-confidence:.2f}%)")
120
 
121
- st.write("### Confidence Score")
122
- st.write(f"{confidence:.2f}%")
 
 
 
 
 
 
2
  import numpy as np
3
  import tensorflow as tf
4
  from tensorflow.keras.preprocessing import image
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
+ import torch
 
7
 
8
  # ---------------------------
9
  # PAGE CONFIG
10
  # ---------------------------
11
+ st.set_page_config(
12
+ page_title="TruthGuard AI",
13
+ layout="wide",
14
+ page_icon="πŸ›‘οΈ"
15
+ )
16
+
17
+ # ---------------------------
18
+ # CUSTOM CSS (UI ENHANCEMENT)
19
+ # ---------------------------
20
+ st.markdown("""
21
+ <style>
22
+ .main {
23
+ background-color: #0E1117;
24
+ color: white;
25
+ }
26
+ .stButton>button {
27
+ background-color: #4CAF50;
28
+ color: white;
29
+ border-radius: 10px;
30
+ height: 3em;
31
+ width: 100%;
32
+ }
33
+ </style>
34
+ """, unsafe_allow_html=True)
35
 
36
+ # ---------------------------
37
+ # TITLE
38
+ # ---------------------------
39
  st.title("πŸ›‘οΈ TruthGuard AI")
40
+ st.caption("Multi-Modal Fake News & AI Image Detection System")
41
 
42
  # ---------------------------
43
  # LOAD MODELS
44
  # ---------------------------
45
 
46
+ # TEXT MODEL (DistilBERT)
47
  @st.cache_resource
48
  def load_text_model():
49
+ model_name = "Maheentouqeer1/truthguard-fake-news-detector"
50
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
51
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
52
+ return tokenizer, model
53
+
54
+ # # IMAGE MODEL
55
+ # @st.cache_resource
56
+ # def load_image_model():
57
+ # model = tf.keras.models.load_model("image_detector_finetuned.h5")
58
+ # return model
59
+
60
+ # tokenizer, text_model = load_text_model()
61
+ # image_model = load_image_model()
62
+ import requests
63
 
 
64
  @st.cache_resource
65
  def load_image_model():
66
+
67
+ url = "https://huggingface.co/syeda-Rija20/image-detector/blob/main/image_detector_finetuned.h5"
68
+
69
+ model_path = "image_model.h5"
 
70
 
71
+ # Download model
72
+ with open(model_path, "wb") as f:
73
+ f.write(requests.get(url).content)
74
 
75
+ # Load model
76
+ model = tf.keras.models.load_model(model_path)
77
 
78
+ return model
 
 
79
  # ---------------------------
80
+ # PREDICT TEXT
81
  # ---------------------------
82
+ def predict_news(text):
83
+ inputs = tokenizer(
84
+ text,
85
+ return_tensors="pt",
86
+ truncation=True,
87
+ padding=True,
88
+ max_length=512
89
+ )
90
+
91
+ outputs = text_model(**inputs)
92
+ probs = torch.nn.functional.softmax(outputs.logits, dim=1)
93
 
94
+ prediction = torch.argmax(probs).item()
95
+ confidence = torch.max(probs).item() * 100
96
+
97
+ return prediction, confidence
 
 
98
 
99
  # ---------------------------
100
+ # TABS
101
  # ---------------------------
102
  tab1, tab2 = st.tabs(["πŸ“° Fake News Detection", "πŸ–ΌοΈ AI Image Detection"])
103
 
104
  # ===========================
105
+ # TAB 1 β†’ TEXT
106
  # ===========================
107
  with tab1:
108
+ st.subheader("πŸ“° Fake News Detector")
109
 
110
+ user_input = st.text_area("Paste news article here...")
111
 
112
+ if st.button("πŸ” Analyze News"):
113
  if user_input.strip() == "":
114
  st.warning("Please enter some text")
115
  else:
116
+ pred, conf = predict_news(user_input)
 
 
 
 
 
 
 
117
 
118
+ if pred == 0:
119
+ st.error(f"⚠️ FAKE NEWS ({conf:.2f}%)")
120
  else:
121
+ st.success(f"βœ… REAL NEWS ({conf:.2f}%)")
122
 
123
+ st.progress(int(conf))
 
 
124
 
125
  # ===========================
126
+ # TAB 2 β†’ IMAGE
127
  # ===========================
128
  with tab2:
129
+ st.subheader("πŸ–ΌοΈ AI Image Detector")
130
 
131
+ uploaded_file = st.file_uploader("Upload Image", type=["jpg", "png", "jpeg"])
132
 
133
  if uploaded_file is not None:
134
  img = image.load_img(uploaded_file, target_size=(224, 224))
135
+ st.image(img, caption="Uploaded Image", use_container_width=True)
136
+
137
  img_array = image.img_to_array(img) / 255.0
138
  img_array = np.expand_dims(img_array, axis=0)
139
 
140
  prediction = image_model.predict(img_array)
 
141
  confidence = float(prediction[0][0]) * 100
142
 
143
  if prediction[0][0] > 0.5:
 
145
  else:
146
  st.success(f"βœ… REAL IMAGE ({100-confidence:.2f}%)")
147
 
148
+ st.progress(int(confidence))
149
+
150
+ # ---------------------------
151
+ # FOOTER
152
+ # ---------------------------
153
+ st.markdown("---")
154
+ st.caption("Built with ❀️ using Transformers & Deep Learning")