-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
260 lines (204 loc) · 6.69 KB
/
predict.py
File metadata and controls
260 lines (204 loc) · 6.69 KB
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env python3
"""
Prediction Script for Fake News Detection
Classifies news articles as real or fake.
Usage:
python predict.py "Your news article text here"
python predict.py --file article.txt
python predict.py --interactive
Author: Anik Tahabilder
"""
import argparse
import os
import sys
import re
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from utils import load_model, print_banner
# Paths to saved models
MODEL_DIR = 'models'
VECTORIZER_PATH = os.path.join(MODEL_DIR, 'tfidf_vectorizer.pkl')
MODEL_PATH = os.path.join(MODEL_DIR, 'best_model.pkl')
def preprocess_text(text: str) -> str:
"""Clean and preprocess input text."""
if not text:
return ""
# Convert to lowercase
text = text.lower()
# Remove URLs
text = re.sub(r'http\S+|www\S+|https\S+', '', text)
# Remove email addresses
text = re.sub(r'\S+@\S+', '', text)
# Remove special characters and digits
text = re.sub(r'[^a-zA-Z\s]', '', text)
# Remove extra whitespace
text = re.sub(r'\s+', ' ', text).strip()
return text
class FakeNewsPredictor:
"""
Fake News Prediction Interface.
Loads trained models and provides prediction functionality.
"""
def __init__(self, model_path: str = MODEL_PATH,
vectorizer_path: str = VECTORIZER_PATH):
"""
Initialize the predictor.
Args:
model_path: Path to the trained model
vectorizer_path: Path to the TF-IDF vectorizer
"""
self.model = None
self.vectorizer = None
self._load_models(model_path, vectorizer_path)
def _load_models(self, model_path: str, vectorizer_path: str):
"""Load the model and vectorizer from disk."""
if not os.path.exists(model_path):
raise FileNotFoundError(
f"Model not found at {model_path}. "
"Please run 'python train.py' first."
)
if not os.path.exists(vectorizer_path):
raise FileNotFoundError(
f"Vectorizer not found at {vectorizer_path}. "
"Please run 'python train.py' first."
)
self.model = load_model(model_path)
self.vectorizer = load_model(vectorizer_path)
def predict(self, text: str) -> dict:
"""
Predict if a news article is fake or real.
Args:
text: News article text
Returns:
Dictionary with prediction results
"""
# Preprocess
clean_text = preprocess_text(text)
if len(clean_text) < 20:
return {
'prediction': 'UNKNOWN',
'confidence': 0.0,
'message': 'Text too short for reliable prediction'
}
# Vectorize
text_tfidf = self.vectorizer.transform([clean_text])
# Get prediction
if hasattr(self.model, 'predict'):
# It's a FakeNewsClassifier wrapper
prediction = self.model.predict(text_tfidf)[0]
try:
proba = self.model.predict_proba(text_tfidf)[0]
confidence = max(proba) * 100
except Exception:
confidence = None
else:
# Direct sklearn model
prediction = self.model.predict(text_tfidf)[0]
if hasattr(self.model, 'predict_proba'):
proba = self.model.predict_proba(text_tfidf)[0]
confidence = max(proba) * 100
else:
confidence = None
result = 'FAKE' if prediction == 1 else 'REAL'
return {
'prediction': result,
'confidence': confidence,
'label': int(prediction)
}
def predict_batch(self, texts: list) -> list:
"""
Predict for multiple texts.
Args:
texts: List of news article texts
Returns:
List of prediction dictionaries
"""
return [self.predict(text) for text in texts]
def interactive_mode(predictor: FakeNewsPredictor):
"""Run interactive prediction mode."""
print_banner("INTERACTIVE MODE")
print("\nEnter news articles to classify (type 'quit' to exit):")
print("-" * 50)
while True:
print("\n")
try:
text = input("Enter article text:\n> ").strip()
except (EOFError, KeyboardInterrupt):
print("\n\nExiting...")
break
if text.lower() in ['quit', 'exit', 'q']:
print("Goodbye!")
break
if not text:
print("Please enter some text.")
continue
result = predictor.predict(text)
print(f"\n{'='*40}")
print(f"Prediction: {result['prediction']}")
if result['confidence']:
print(f"Confidence: {result['confidence']:.1f}%")
print(f"{'='*40}")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='Fake News Detection Predictor'
)
parser.add_argument(
'text',
nargs='?',
help='News article text to classify'
)
parser.add_argument(
'--file', '-f',
type=str,
help='Path to file containing news article'
)
parser.add_argument(
'--interactive', '-i',
action='store_true',
help='Run in interactive mode'
)
parser.add_argument(
'--model', '-m',
type=str,
default=MODEL_PATH,
help='Path to model file'
)
args = parser.parse_args()
# Initialize predictor
try:
predictor = FakeNewsPredictor(model_path=args.model)
except FileNotFoundError as e:
print(f"Error: {e}")
print("\nPlease train the model first by running:")
print(" python train.py")
return 1
# Interactive mode
if args.interactive:
interactive_mode(predictor)
return 0
# File mode
if args.file:
if not os.path.exists(args.file):
print(f"Error: File not found: {args.file}")
return 1
with open(args.file, 'r', encoding='utf-8') as f:
text = f.read()
result = predictor.predict(text)
print(f"\nFile: {args.file}")
print(f"Prediction: {result['prediction']}")
if result['confidence']:
print(f"Confidence: {result['confidence']:.1f}%")
return 0
# Direct text mode
if args.text:
result = predictor.predict(args.text)
print(f"\nPrediction: {result['prediction']}")
if result['confidence']:
print(f"Confidence: {result['confidence']:.1f}%")
return 0
# No input provided
parser.print_help()
return 1
if __name__ == '__main__':
sys.exit(main())