Spaces:
Running
Running
Update app/sentiment.py
Browse files- app/sentiment.py +9 -6
app/sentiment.py
CHANGED
@@ -1,22 +1,24 @@
|
|
1 |
"""
|
2 |
-
Safe lazy-loading sentiment pipeline
|
3 |
"""
|
4 |
-
|
5 |
import os
|
6 |
import hashlib
|
7 |
import logging
|
8 |
from functools import lru_cache
|
9 |
|
10 |
-
#
|
|
|
|
|
11 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface"
|
12 |
os.makedirs("/tmp/huggingface", exist_ok=True)
|
13 |
|
14 |
from transformers import pipeline
|
15 |
|
16 |
class SentimentCache:
|
|
|
17 |
latest_id: int = 0
|
18 |
latest_result: dict = {}
|
19 |
-
_pipeline = None #
|
20 |
|
21 |
@classmethod
|
22 |
def _get_pipeline(cls):
|
@@ -40,11 +42,12 @@ class SentimentCache:
|
|
40 |
|
41 |
@classmethod
|
42 |
def compute(cls, text: str):
|
|
|
43 |
res = cls._analyze(text)
|
44 |
cls.latest_id += 1
|
45 |
cls.latest_result = {
|
46 |
"text": text,
|
47 |
-
"label": res
|
48 |
-
"score": round(res
|
49 |
}
|
50 |
logging.info("β
Sentiment computed: %s", cls.latest_result)
|
|
|
1 |
"""
|
2 |
+
Safe, lazy-loading sentiment pipeline for HF Spaces with proper cache redirection.
|
3 |
"""
|
|
|
4 |
import os
|
5 |
import hashlib
|
6 |
import logging
|
7 |
from functools import lru_cache
|
8 |
|
9 |
+
# βββ Ensure all HF caching uses a writable directory βββββββββββββββββββββββββ
|
10 |
+
# Set HF_HOME for huggingface_hub and TRANSFORMERS_CACHE for transformers
|
11 |
+
os.environ["HF_HOME"] = "/tmp/huggingface"
|
12 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface"
|
13 |
os.makedirs("/tmp/huggingface", exist_ok=True)
|
14 |
|
15 |
from transformers import pipeline
|
16 |
|
17 |
class SentimentCache:
|
18 |
+
"""Handles in-memory caching and streaming of sentiment results."""
|
19 |
latest_id: int = 0
|
20 |
latest_result: dict = {}
|
21 |
+
_pipeline = None # Will hold the loaded pipeline
|
22 |
|
23 |
@classmethod
|
24 |
def _get_pipeline(cls):
|
|
|
42 |
|
43 |
@classmethod
|
44 |
def compute(cls, text: str):
|
45 |
+
"""Trigger inference and update latest result."""
|
46 |
res = cls._analyze(text)
|
47 |
cls.latest_id += 1
|
48 |
cls.latest_result = {
|
49 |
"text": text,
|
50 |
+
"label": res.get("label"),
|
51 |
+
"score": round(res.get("score", 0.0), 4)
|
52 |
}
|
53 |
logging.info("β
Sentiment computed: %s", cls.latest_result)
|