menikev commited on
Commit
9b28320
·
verified ·
1 Parent(s): 740c82e

Update sentiment_tools.py

Browse files
Files changed (1) hide show
  1. sentiment_tools.py +21 -14
sentiment_tools.py CHANGED
@@ -1,15 +1,22 @@
1
- from langchain.tools import tool
2
- from textblob import TextBlob
3
-
4
- class SentimentTools:
5
- @tool("Analyze Sentiment")
6
- def analyze_sentiment(text):
7
- """Analyzes the sentiment of a given text."""
8
- blob = TextBlob(text)
9
- sentiment = blob.sentiment.polarity
10
- if sentiment > 0:
11
- return "Positive"
12
- elif sentiment < 0:
13
- return "Negative"
14
- else:
 
 
 
 
 
 
 
15
  return "Neutral"
 
1
+ from langchain.tools import tool
2
+ from transformers import pipeline
3
+
4
+ class SentimentTools:
5
+ def __init__(self):
6
+ self.sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
7
+
8
+ @tool("Analyze Sentiment")
9
+ def analyze_sentiment(self, text):
10
+ """Analyzes the sentiment of a given text."""
11
+ # Limit the input text to 512 tokens to ensure faster processing
12
+ truncated_text = ' '.join(text.split()[:512])
13
+ result = self.sentiment_pipeline(truncated_text)[0]
14
+ sentiment = result['label']
15
+ score = result['score']
16
+
17
+ if sentiment == 'POSITIVE':
18
+ return "Positive" if score > 0.6 else "Neutral"
19
+ elif sentiment == 'NEGATIVE':
20
+ return "Negative" if score > 0.6 else "Neutral"
21
+ else:
22
  return "Neutral"