Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download utils.py from PrismScienceOrg/PLUG-challenge: direct link, hf CLI and curl.
- Browser
- Download file 8.22 kB
-
https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge/resolve/main/utils.py
- Command line
-
hf download hf://spaces/PrismScienceOrg/PLUG-challenge/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge/resolve/main/utils.py
8.22 kB
| """Utilities for the PLUG challenge Space. | |
| Username and link checking, ported from the OpenADMET blind-challenge template | |
| (including its SSRF guard on user-supplied URLs) with the S3 layer removed — | |
| storage lives in ``plug_challenge.store``. | |
| """ | |
| import ipaddress | |
| import re | |
| import socket | |
| import time | |
| from urllib.parse import urljoin, urlparse | |
| import requests | |
| from loguru import logger | |
| _MAX_REDIRECTS = 5 | |
| BANNED_USERNAMES: dict[str, str] = { # normalised (lowercase) username: reason | |
| # Add entries here to block submissions from a Hugging Face account, e.g.: | |
| # "some-username": "Suspected of using multiple HF accounts", | |
| } | |
| def safeify_username(username: str) -> str: | |
| """Sanitise a Hugging Face username for use in repo paths. | |
| Organisation usernames use the form ``org/user``, which would create | |
| unintended path nesting. Lowercased so that casing variants — which all | |
| resolve to the same account — map to the same prefix; otherwise the | |
| submission cooldown could be bypassed by alternating case. | |
| Parameters | |
| ---------- | |
| username : str | |
| The raw username as typed. | |
| Returns | |
| ------- | |
| str | |
| Lowercased, with ``/`` and spaces replaced by underscores. | |
| """ | |
| return str(username).strip().lower().replace("/", "_").replace(" ", "_") | |
| def _is_safe_public_url(url: str) -> bool: | |
| """Reject URLs whose host resolves to a private/loopback/link-local address. | |
| Guards ``check_page_exists`` against SSRF: without this, a user-supplied URL | |
| (the "Method Report Link" field) could point the server at internal | |
| infrastructure and have it report reachability back. | |
| Parameters | |
| ---------- | |
| url : str | |
| The URL to check. | |
| Returns | |
| ------- | |
| bool | |
| True if every address the host resolves to is public. | |
| """ | |
| hostname = urlparse(url).hostname | |
| if not hostname: | |
| return False | |
| try: | |
| infos = socket.getaddrinfo(hostname, None) | |
| except socket.gaierror: | |
| return False | |
| for info in infos: | |
| ip = ipaddress.ip_address(info[4][0]) | |
| if ( | |
| ip.is_private | |
| or ip.is_loopback | |
| or ip.is_link_local | |
| or ip.is_reserved | |
| or ip.is_multicast | |
| or ip.is_unspecified | |
| ): | |
| return False | |
| return True | |
| def check_page_exists( | |
| url: str, | |
| delay: float = 0.2, | |
| max_retries: int = 3, | |
| current_retries: int = 0, | |
| restrict_to_public: bool = True, | |
| ) -> bool: | |
| """Check whether a page exists, retrying on rate limits. | |
| Redirects are followed manually rather than via ``requests``' built-in | |
| ``allow_redirects`` so each hop is checked against ``_is_safe_public_url`` | |
| before it is requested, closing off SSRF via a redirect to an internal | |
| address. | |
| Parameters | |
| ---------- | |
| url : str | |
| The URL to check. | |
| delay : float | |
| Seconds to sleep after every request. | |
| max_retries : int | |
| Maximum retries on HTTP 429. | |
| current_retries : int | |
| Internal retry counter. | |
| restrict_to_public : bool | |
| Reject hosts resolving to private addresses. Only meaningful when the | |
| host is user-controlled; disable for a hardcoded trusted domain, since | |
| some platforms resolve their own domain internally (split-horizon DNS) | |
| and this check would then reject it. | |
| Returns | |
| ------- | |
| bool | |
| True when the URL returns HTTP 200. | |
| """ | |
| safe_url = str(url).strip() | |
| if not safe_url.startswith(("http://", "https://")): | |
| safe_url = f"https://{safe_url}" | |
| try: | |
| response = None | |
| for _ in range(_MAX_REDIRECTS + 1): | |
| if restrict_to_public and not _is_safe_public_url(safe_url): | |
| logger.warning("Refusing to fetch non-public URL: {}", safe_url) | |
| return False | |
| response = requests.get(safe_url, timeout=5, allow_redirects=False) | |
| if ( | |
| response.status_code in (301, 302, 303, 307, 308) | |
| and "Location" in response.headers | |
| ): | |
| safe_url = urljoin(safe_url, response.headers["Location"]) | |
| continue | |
| break | |
| else: | |
| logger.warning("Too many redirects for {}", url) | |
| return False | |
| if response.status_code == 429: | |
| if current_retries < max_retries: | |
| wait = 5 * (2**current_retries) | |
| logger.warning( | |
| "Rate limited on {} (attempt {}/{}), waiting {}s.", | |
| safe_url, | |
| current_retries + 1, | |
| max_retries, | |
| wait, | |
| ) | |
| time.sleep(wait) | |
| return check_page_exists( | |
| safe_url, | |
| delay=delay, | |
| max_retries=max_retries, | |
| current_retries=current_retries + 1, | |
| restrict_to_public=restrict_to_public, | |
| ) | |
| logger.error("Max retries reached for rate limit on {}.", safe_url) | |
| return False | |
| return response.status_code == 200 | |
| except requests.exceptions.RequestException as exc: | |
| logger.error("Error checking URL {}: {}", safe_url, exc) | |
| return False | |
| finally: | |
| time.sleep(delay) | |
| def validate_hf_username(username: str) -> bool: | |
| """Confirm a Hugging Face account exists by fetching its profile page. | |
| This is a typo check, not an identity proof — nothing here verifies that the | |
| submitter owns the account. | |
| Parameters | |
| ---------- | |
| username : str | |
| A username, or a full ``https://huggingface.co/<user>`` URL. | |
| Returns | |
| ------- | |
| bool | |
| True when the profile page loads. | |
| """ | |
| # restrict_to_public=False: the target is always the literal huggingface.co | |
| # domain, never an attacker-supplied host, and HF can resolve its own domain | |
| # to an internal address from inside its infrastructure. | |
| candidate = str(username).strip() | |
| if re.match(r"^https?://huggingface\.co/([^/]+)/?$", candidate): | |
| return check_page_exists( | |
| candidate, delay=1, max_retries=10, restrict_to_public=False | |
| ) | |
| return check_page_exists( | |
| f"https://huggingface.co/{candidate}", | |
| delay=1, | |
| max_retries=10, | |
| restrict_to_public=False, | |
| ) | |
| def validate_model_details(tag: str | None) -> str: | |
| """Validate a method report link. | |
| Parameters | |
| ---------- | |
| tag : str | None | |
| The URL as typed, or empty. | |
| Returns | |
| ------- | |
| str | |
| The URL when it is a reachable ``https://`` page, ``"Not submitted"`` | |
| when blank, or ``"Invalid link"`` otherwise. | |
| """ | |
| if tag is None or str(tag).strip() == "": | |
| return "Not submitted" | |
| safe_tag = str(tag).strip() | |
| if not safe_tag.startswith("https://"): | |
| return "Invalid link" | |
| return safe_tag if check_page_exists(safe_tag, delay=2) else "Invalid link" | |
| def make_user_clickable(name: str) -> str: | |
| """Link a leaderboard username to its Hugging Face profile. | |
| Parameters | |
| ---------- | |
| name : str | |
| Username or alias as displayed. | |
| Returns | |
| ------- | |
| str | |
| An HTML anchor. | |
| """ | |
| link = f"https://huggingface.co/{name}" if not str(name).startswith("https://") else str(name) | |
| return ( | |
| f'<a target="_blank" href="{link}" style="color: var(--link-text-color); ' | |
| f'text-decoration: underline; text-decoration-style: dotted;">{name}</a>' | |
| ) | |
| def make_tag_clickable(tag: str) -> str: | |
| """Render a method report link as a leaderboard cell. | |
| Parameters | |
| ---------- | |
| tag : str | |
| The stored link, possibly empty or a placeholder. | |
| Returns | |
| ------- | |
| str | |
| An HTML anchor, or a plain placeholder string. | |
| """ | |
| text = "" if tag is None else str(tag).strip() | |
| if text in ("", "nan", "Not submitted"): | |
| return "Not submitted" | |
| if not text.startswith(("http://", "https://")): | |
| return "Invalid link" | |
| return ( | |
| f'<a target="_blank" href="{text}" style="color: var(--link-text-color); ' | |
| f'text-decoration: underline; text-decoration-style: dotted;">link</a>' | |
| ) | |