Spaces:
Runtime error
Runtime error
Create sentiment_analysis.py
Browse files
modules/sentiment_analysis.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modules/sentiment_analysis.py
|
| 2 |
+
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
|
| 5 |
+
# Load sentiment pipeline (you can change model to "distilbert-base-uncased-finetuned-sst-2-english")
|
| 6 |
+
sentiment_pipeline = pipeline("sentiment-analysis")
|
| 7 |
+
|
| 8 |
+
def analyze_sentiment(texts: list) -> list:
|
| 9 |
+
"""
|
| 10 |
+
Perform sentiment analysis on a list of texts.
|
| 11 |
+
Returns a list of dictionaries with label and score.
|
| 12 |
+
"""
|
| 13 |
+
results = []
|
| 14 |
+
for t in texts:
|
| 15 |
+
if t.strip():
|
| 16 |
+
try:
|
| 17 |
+
result = sentiment_pipeline(t)[0]
|
| 18 |
+
results.append({
|
| 19 |
+
"text": t,
|
| 20 |
+
"label": result["label"],
|
| 21 |
+
"score": float(result["score"])
|
| 22 |
+
})
|
| 23 |
+
except Exception as e:
|
| 24 |
+
results.append({
|
| 25 |
+
"text": t,
|
| 26 |
+
"label": "ERROR",
|
| 27 |
+
"score": 0.0,
|
| 28 |
+
"error": str(e)
|
| 29 |
+
})
|
| 30 |
+
return results
|