Spaces:
Sleeping
Sleeping
Create app/sentiment.py
Browse files- app/sentiment.py +28 -0
app/sentiment.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tiny wrapper around HF transformers sentiment pipeline with in‑memory cache.
|
| 3 |
+
"""
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
import hashlib, logging
|
| 7 |
+
|
| 8 |
+
_sentiment = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 9 |
+
|
| 10 |
+
class SentimentCache:
|
| 11 |
+
latest_id: int = 0
|
| 12 |
+
latest_result: dict = {}
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def _hash(cls, text: str) -> str:
|
| 16 |
+
return hashlib.sha256(text.encode()).hexdigest()
|
| 17 |
+
|
| 18 |
+
@classmethod
|
| 19 |
+
@lru_cache(maxsize=128)
|
| 20 |
+
def _analyze(cls, text: str):
|
| 21 |
+
return _sentiment(text)[0]
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def compute(cls, text: str):
|
| 25 |
+
res = cls._analyze(text)
|
| 26 |
+
cls.latest_id += 1
|
| 27 |
+
cls.latest_result = {"text": text, **res}
|
| 28 |
+
logging.info("🧠 sentiment computed")
|