mgbam commited on
Commit
ae4946d
Β·
verified Β·
1 Parent(s): cb01390

Update app/sentiment.py

Browse files
Files changed (1) hide show
  1. app/sentiment.py +9 -6
app/sentiment.py CHANGED
@@ -1,22 +1,24 @@
1
  """
2
- Safe lazy-loading sentiment pipeline that works in Hugging Face Spaces (no /.cache error).
3
  """
4
-
5
  import os
6
  import hashlib
7
  import logging
8
  from functools import lru_cache
9
 
10
- # Redirect the HF model cache to a writable directory
 
 
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 # Lazy init
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["label"],
48
- "score": round(res["score"], 4)
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)