Classical_Model / fake_news_detector.py
ƤŁΛИ
Upload fake_news_detector.py with huggingface_hub
7f74c27 verified
import joblib, pickle, numpy as np
from huggingface_hub import hf_hub_download
class FakeNewsDetector:
def __init__(self):
print("Loading Fake News Detector from Hugging Face...")
repo = "ghimirewe22/Classical_Model"
self.rf = joblib.load(hf_hub_download(repo, "rf_classifier.joblib"))
self.gb = joblib.load(hf_hub_download(repo, "gb_classifier.joblib"))
self.lr = joblib.load(hf_hub_download(repo, "lr_classifier.joblib"))
self.oc = joblib.load(hf_hub_download(repo, "oneclass_svm.joblib"))
self.vect = joblib.load(hf_hub_download(repo, "tfidf_vectorizer.joblib"))
self.pt = joblib.load(hf_hub_download(repo, "power_transformer.joblib"))
with open(hf_hub_download(repo, "vocab.pkl"), "rb") as f:
self.vocab = pickle.load(f)
print("Model loaded! Ready to detect fake news.")
def predict(self, text):
X = self.vect.transform([text]).toarray()
try:
X = self.pt.transform(X)
except: pass
oc_vote = 0 if self.oc.predict(X)[0] == -1 else 1
votes = [
oc_vote,
int(self.lr.predict(X)[0]),
int(self.gb.predict(X)[0]),
int(self.rf.predict(X)[0])
]
result = "REAL" if sum(votes) >= 2 else "FAKE"
prob = self._fake_prob(text)
return f"{result} ({prob:.1f}% fake)"
def _fake_prob(self, text):
X = self.vect.transform([text]).toarray()
try: X = self.pt.transform(X) except: pass
probs = []
for m in [self.lr, self.gb, self.rf]:
if hasattr(m, "predict_proba"):
probs.append(m.predict_proba(X)[0][0])
return np.mean(probs) * 100 if probs else 50.0