CyberNative AI LLC
Publish SO-arm task clock dataset and reproduction scripts
04782c0
Raw History Blame Contribute Delete
2.64 kB
"""Bounded HTTPS GET for public Hugging Face metadata. Python standard library only.
Every request and every redirect must go to https on huggingface.co or a subdomain of huggingface.co or hf.co
(Hugging Face's file storage). Anything else raises OffOrigin before a connection is made to it. Redirects are
followed here, not by urllib: at most MAX_HOPS, and each redirect response is closed without reading its body. A final
body larger than the caller's limit raises TooLarge; at most limit + 1 bytes are read, before any parsing."""
import re, urllib.error, urllib.parse, urllib.request
UA = {"User-Agent": "so-arm-task-clock/0.2"}
REPO_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}")
class OffOrigin(Exception):
pass
class TooLarge(Exception):
pass
def allowed(url):
u = urllib.parse.urlsplit(url)
h = (u.hostname or "").lower()
return (u.scheme == "https" and u.port in (None, 443) and u.username is None and u.password is None
and (h == "huggingface.co" or h.endswith(".huggingface.co") or h.endswith(".hf.co")))
def valid_repo_id(i):
return bool(REPO_ID.fullmatch(i)) and ".." not in i
MAX_HOPS = 5
REDIRECT = (301, 302, 303, 307, 308)
class TooManyRedirects(Exception):
pass
class _NoFollow(urllib.request.HTTPRedirectHandler):
"""Hand every 30x back to get() as an HTTPError, before urllib reads the redirect body."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
_opener = urllib.request.build_opener(_NoFollow)
def get(url, limit, timeout=40):
"""Return (body bytes, response headers). Raises OffOrigin, TooLarge, TooManyRedirects or urllib.error.HTTPError."""
for _ in range(MAX_HOPS + 1):
if not allowed(url):
raise OffOrigin(url)
try:
r = _opener.open(urllib.request.Request(url, headers=UA), timeout=timeout)
except urllib.error.HTTPError as e:
if e.code not in REDIRECT:
raise
loc = e.headers.get("Location")
e.close() # the redirect body is never read
if not loc:
raise
url = urllib.parse.urljoin(url, loc)
continue
with r:
n = r.headers.get("Content-Length")
if n is not None and n.strip().isdigit() and int(n) > limit:
raise TooLarge(f"{url}: Content-Length {n} > {limit}")
b = r.read(limit + 1)
if len(b) > limit:
raise TooLarge(f"{url}: body > {limit} bytes")
return b, r.headers
raise TooManyRedirects(url)