File size: 1,883 Bytes
226b7bf | 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 51 52 53 | """Author avatars and display names for the dashboard, cached across runs.
cache/authors.json maps an HF user or org name to {"a": avatar url, "n": display name}.
Only names not in the cache are fetched, so a daily run makes a handful of calls.
"""
import json
from concurrent.futures import ThreadPoolExecutor
from . import store
from .hub import api, retry
def path():
return store.LOCAL / "cache" / "authors.json"
AVATAR_HOSTS = ("https://cdn-avatars.huggingface.co/", "https://huggingface.co/")
def _one(name):
"""(name, entry), or (name, None) when the lookup failed for a reason worth retrying."""
missing = 0
# The same name is either a user or an org; the wrong endpoint answers 404.
for fn in (api.get_user_overview, api.get_organization_overview):
try:
o = retry(fn, name)
except Exception as e:
if getattr(getattr(e, "response", None), "status_code", None) == 404:
missing += 1
continue
return name, None
a = o.avatar_url or None
if a and a.startswith("/"):
a = "https://huggingface.co" + a
if a and not a.startswith(AVATAR_HOSTS): # shown on a public page: only HF-hosted images
a = None
return name, {"a": a, "n": o.fullname or name}
return name, ({"a": None, "n": name} if missing == 2 else None)
def update(names, log=print, workers=8):
p = path()
cache = json.loads(p.read_text()) if p.exists() else {}
todo = sorted(set(names) - set(cache))
with ThreadPoolExecutor(workers) as ex:
for name, v in ex.map(_one, todo):
if v is not None:
cache[name] = v
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(cache, ensure_ascii=False))
log(f"authors: {len(todo)} fetched, {len(cache)} cached")
return cache, p
|