Spaces:
Running
Running
Update app/sentiment.py
Browse files- app/sentiment.py +26 -5
app/sentiment.py
CHANGED
@@ -1,28 +1,49 @@
|
|
1 |
"""
|
2 |
-
|
|
|
|
|
3 |
"""
|
|
|
4 |
from transformers import pipeline
|
5 |
from functools import lru_cache
|
6 |
-
import hashlib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
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 = {
|
28 |
-
|
|
|
|
|
|
|
|
1 |
"""
|
2 |
+
CryptoSentinel AI
|
3 |
+
Hugging Face Transformers-based sentiment analysis
|
4 |
+
✅ Fixed for Hugging Face Spaces: avoids /.cache write errors
|
5 |
"""
|
6 |
+
|
7 |
from transformers import pipeline
|
8 |
from functools import lru_cache
|
9 |
+
import hashlib
|
10 |
+
import logging
|
11 |
+
import os
|
12 |
+
|
13 |
+
# 🚨 Hugging Face Spaces cache workaround
|
14 |
+
# Set model cache path to a writable directory
|
15 |
+
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface"
|
16 |
+
os.makedirs("/tmp/huggingface", exist_ok=True)
|
17 |
|
18 |
+
# Load sentiment analysis pipeline
|
19 |
+
_sentiment = pipeline(
|
20 |
+
"sentiment-analysis",
|
21 |
+
model="distilbert-base-uncased-finetuned-sst-2-english"
|
22 |
+
)
|
23 |
|
24 |
class SentimentCache:
|
25 |
+
"""Stores and deduplicates sentiment results in memory."""
|
26 |
latest_id: int = 0
|
27 |
latest_result: dict = {}
|
28 |
|
29 |
@classmethod
|
30 |
def _hash(cls, text: str) -> str:
|
31 |
+
"""Hash text to deduplicate analysis."""
|
32 |
return hashlib.sha256(text.encode()).hexdigest()
|
33 |
|
34 |
@classmethod
|
35 |
@lru_cache(maxsize=128)
|
36 |
def _analyze(cls, text: str):
|
37 |
+
"""Analyze and cache sentiment."""
|
38 |
return _sentiment(text)[0]
|
39 |
|
40 |
@classmethod
|
41 |
def compute(cls, text: str):
|
42 |
+
"""Run analysis and update latest result."""
|
43 |
res = cls._analyze(text)
|
44 |
cls.latest_id += 1
|
45 |
+
cls.latest_result = {
|
46 |
+
"text": text,
|
47 |
+
**res
|
48 |
+
}
|
49 |
+
logging.info("🧠 Sentiment computed: %s", res)
|