File size: 946 Bytes
a880c62 | 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 | from transformers import pipeline
class SentimentAnalyzer:
def __init__(self):
self.model_name = "distilbert-base-uncased-finetuned-sst-2-english"
self.analyzer = None
self.load_model()
def load_model(self):
try:
self.analyzer = pipeline("sentiment-analysis", model=self.model_name)
print(f"Model {self.model_name} loaded successfully.")
except Exception as e:
print(f"Error loading model: {e}")
self.analyzer = None
def is_model_loaded(self):
return self.analyzer is not None
def analyze(self, text: str) -> dict:
if not self.analyzer:
raise RuntimeError("Model not loaded")
result = self.analyzer(text)[0]
label = result["label"]
score = result["score"]
sentiment = "Positive" if label == "POSITIVE" else "Negative"
return {"sentiment": sentiment, "confidence": score} |