shanto268's picture
SQuADDS ML API 2: squadds 53ec2b11, registry 1dbf099a
55ce00a verified
Raw History Blame Contribute Delete
1.28 kB
"""Gate for gated models: a Hugging Face token of a member of the organization (whoami, cached for ten minutes)."""
from __future__ import annotations
import hashlib
import threading
import time
def bearer(headers) -> str | None:
h = headers.get("authorization", "")
return h[7:].strip() or None if h.lower().startswith("bearer ") else None
class Gate:
def __init__(self, org: str = "SQuADDS", ttl_s: float = 600):
self.org, self.ttl_s = org, ttl_s
self._memo: dict = {}
self._lock = threading.Lock()
def is_member(self, token: str) -> bool:
from huggingface_hub import whoami
from huggingface_hub.errors import HfHubHTTPError
k = hashlib.sha256(token.encode()).hexdigest()
with self._lock:
hit = self._memo.get(k)
if hit and time.monotonic() - hit[1] < self.ttl_s:
return hit[0]
try:
info = whoami(token=token)
ok = any(o.get("name") == self.org for o in info.get("orgs", []))
except HfHubHTTPError as exc:
if getattr(exc.response, "status_code", None) not in (401, 403):
raise
ok = False
with self._lock:
self._memo[k] = (ok, time.monotonic())
return ok