File size: 1,700 Bytes
fb17746
061fd19
fb17746
f611cc3
 
 
 
061fd19
f611cc3
061fd19
 
 
 
f611cc3
061fd19
f611cc3
 
 
 
 
 
 
 
 
 
 
061fd19
 
 
 
 
 
 
 
 
 
 
f611cc3
 
 
061fd19
f611cc3
 
 
 
061fd19
 
f611cc3
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
Sentiment analysis module using Hugging Face Inference API to avoid local model downloads.
"""
import os
import hashlib
import logging
from functools import lru_cache
import httpx

# Environment variables (set HF_API_TOKEN in your Space's Settings)
HF_API_TOKEN = os.getenv("HF_API_TOKEN", "")
API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}

# In-memory cache for latest sentiment
class SentimentCache:
    latest_id: int = 0
    latest_result: dict = {}

    @classmethod
    def _hash(cls, text: str) -> str:
        return hashlib.sha256(text.encode()).hexdigest()

    @classmethod
    @lru_cache(maxsize=128)
    def _analyze(cls, text: str):
        try:
            response = httpx.post(API_URL, headers=HEADERS, json={"inputs": text}, timeout=20)
            response.raise_for_status()
            data = response.json()
            # Expecting list of {label, score}
            if isinstance(data, list) and data:
                return data[0]
            raise ValueError("Unexpected response format: %s" % data)
        except Exception as e:
            logging.error("❌ Sentiment API error: %s", e)
            return {"label": "ERROR", "score": 0.0}

    @classmethod
    def compute(cls, text: str):
        """Trigger sentiment inference via API and update latest result."""
        res = cls._analyze(text)
        cls.latest_id += 1
        cls.latest_result = {
            "text": text,
            "label": res.get("label"),
            "score": round(res.get("score", 0.0), 4)
        }
        logging.info("βœ… Sentiment computed: %s", cls.latest_result)