Spaces:
Running
Running
""" | |
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 = {} | |
def _hash(cls, text: str) -> str: | |
return hashlib.sha256(text.encode()).hexdigest() | |
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} | |
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) | |