-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsentiment.py
More file actions
32 lines (27 loc) · 1.04 KB
/
sentiment.py
File metadata and controls
32 lines (27 loc) · 1.04 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
# sentiment.py
from transformers import pipeline
# Create (singleton) sentiment pipeline
def get_sentiment_pipeline():
# uses distilbert fine-tuned on SST-2 by default
return pipeline("sentiment-analysis", return_all_scores=False)
def detect_sentiment(text, nlp=None):
"""
Returns a simplified sentiment: 'positive', 'negative', or 'neutral' (if uncertain).
Also returns the raw pipeline output.
"""
if nlp is None:
nlp = get_sentiment_pipeline()
result = nlp(text)[0] # {'label': 'POSITIVE', 'score': 0.99}
label = result.get("label", "").lower()
score = float(result.get("score", 0.0))
# Map labels -> simplified categories
if label.startswith("pos"):
sentiment = "positive"
elif label.startswith("neg"):
sentiment = "negative"
else:
sentiment = "neutral"
# If the model is unsure, label as neutral (adjust threshold if needed)
if score < 0.6:
sentiment = "neutral"
return {"sentiment": sentiment, "label": result.get("label"), "score": score}