ƤŁΛИ commited on
Upload fake_news_detector.py with huggingface_hub
Browse files- fake_news_detector.py +43 -0
fake_news_detector.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import joblib, pickle, numpy as np
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
|
| 5 |
+
class FakeNewsDetector:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
print("Loading Fake News Detector from Hugging Face...")
|
| 8 |
+
repo = "ghimirewe22/Classical_Model"
|
| 9 |
+
self.rf = joblib.load(hf_hub_download(repo, "rf_classifier.joblib"))
|
| 10 |
+
self.gb = joblib.load(hf_hub_download(repo, "gb_classifier.joblib"))
|
| 11 |
+
self.lr = joblib.load(hf_hub_download(repo, "lr_classifier.joblib"))
|
| 12 |
+
self.oc = joblib.load(hf_hub_download(repo, "oneclass_svm.joblib"))
|
| 13 |
+
self.vect = joblib.load(hf_hub_download(repo, "tfidf_vectorizer.joblib"))
|
| 14 |
+
self.pt = joblib.load(hf_hub_download(repo, "power_transformer.joblib"))
|
| 15 |
+
with open(hf_hub_download(repo, "vocab.pkl"), "rb") as f:
|
| 16 |
+
self.vocab = pickle.load(f)
|
| 17 |
+
print("Model loaded! Ready to detect fake news.")
|
| 18 |
+
|
| 19 |
+
def predict(self, text):
|
| 20 |
+
X = self.vect.transform([text]).toarray()
|
| 21 |
+
try:
|
| 22 |
+
X = self.pt.transform(X)
|
| 23 |
+
except: pass
|
| 24 |
+
|
| 25 |
+
oc_vote = 0 if self.oc.predict(X)[0] == -1 else 1
|
| 26 |
+
votes = [
|
| 27 |
+
oc_vote,
|
| 28 |
+
int(self.lr.predict(X)[0]),
|
| 29 |
+
int(self.gb.predict(X)[0]),
|
| 30 |
+
int(self.rf.predict(X)[0])
|
| 31 |
+
]
|
| 32 |
+
result = "REAL" if sum(votes) >= 2 else "FAKE"
|
| 33 |
+
prob = self._fake_prob(text)
|
| 34 |
+
return f"{result} ({prob:.1f}% fake)"
|
| 35 |
+
|
| 36 |
+
def _fake_prob(self, text):
|
| 37 |
+
X = self.vect.transform([text]).toarray()
|
| 38 |
+
try: X = self.pt.transform(X) except: pass
|
| 39 |
+
probs = []
|
| 40 |
+
for m in [self.lr, self.gb, self.rf]:
|
| 41 |
+
if hasattr(m, "predict_proba"):
|
| 42 |
+
probs.append(m.predict_proba(X)[0][0])
|
| 43 |
+
return np.mean(probs) * 100 if probs else 50.0
|