oss-ecosystem-data / code /hfeco /authors.py
saladday1's picture
code: sync from git
226b7bf verified
Raw History Blame Contribute Delete
1.88 kB
"""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