File size: 1,294 Bytes
9f76cac | 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 | """Validate the HF token in .env.txt without ever printing the secret."""
import os
import re
import sys
from pathlib import Path
BASE = Path(__file__).resolve().parents[1]
ENV = BASE / ".env.txt"
def load_token() -> str:
raw = ENV.read_text(encoding="utf-8", errors="replace").strip()
# Accept "HF_TOKEN hf_xxx", "HF_TOKEN=hf_xxx", or a bare "hf_xxx".
m = re.search(r"(hf_[A-Za-z0-9]+)", raw)
if not m:
print("TOKEN_PARSE_FAIL: no hf_ token found in .env.txt")
sys.exit(2)
return m.group(1)
def main() -> None:
from huggingface_hub import HfApi
token = load_token()
api = HfApi(token=token)
try:
info = api.whoami()
except Exception as e: # noqa: BLE001
print(f"AUTH_FAIL: {type(e).__name__}: {str(e)[:160]}")
sys.exit(3)
name = info.get("name")
# Permission detection across hub versions.
perm = None
auth = info.get("auth") or {}
at = auth.get("accessToken") or {}
perm = at.get("role") or at.get("fineGrained") or info.get("type")
print(f"HF_USER: {name}")
print(f"TOKEN_ROLE: {perm}")
# Namespaces the token can write to.
orgs = [o.get("name") for o in info.get("orgs", [])]
print(f"ORGS: {orgs}")
print("AUTH_OK")
if __name__ == "__main__":
main()
|