Download geomgnn/access.py from shanto268/PlanarCapacitanceModel: direct link, hf CLI and curl.
- Browser
- Download file 6.67 kB
-
https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/geomgnn/access.py
- Command line
-
hf download hf://spaces/shanto268/PlanarCapacitanceModel/geomgnn/access.py
-
curl -L -o access.py https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/geomgnn/access.py
6.67 kB
| """Sign-in, daily limits and the layout-size limit of the public demo (handoff/squadds_integration/PLAN_PUBLIC_SPACE.md, amendment | |
| 2026-11-14). Served requests only: in-process calls (request None: tests, preload) are not limited. | |
| - Anonymous visitors run the bundled examples only (matched by the file's sha256). Their own GDS needs Hugging Face sign-in. | |
| - Signed in = a browser session through Hugging Face OAuth, or an API call with Client(..., oauth_token=<HF token>). | |
| - Each signed-in user gets TLSQ_DAILY_PREDICTIONS (10) predictions of their own layouts per UTC day. A repeat answered from the | |
| response cache and the bundled examples do not count. | |
| - Safety limit per client address: TLSQ_IP_DAILY (50) computed predictions per UTC day, examples included. | |
| - Layouts with MAX_NETS (70) or more conductors, ground included, are refused before any solve. | |
| Usernames and addresses are held only as keyed hashes (usage.keyed), in memory, and the counters are cleared at the end of the UTC day. | |
| """ | |
| from __future__ import annotations | |
| import datetime as dt | |
| import hashlib | |
| import html | |
| import os | |
| import threading | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from tlsq_infer.layout import LayoutError | |
| from .usage import keyed, today | |
| LOCAL_GUIDE = os.environ.get("TLSQ_LOCAL_GUIDE", "https://lfl-lab.github.io/SQuADDS/source/ml_local.html") | |
| DAILY = int(os.environ.get("TLSQ_DAILY_PREDICTIONS", 10)) | |
| IP_DAILY = int(os.environ.get("TLSQ_IP_DAILY", 50)) | |
| MAX_NETS = 70 | |
| HEADS = {"auth": "Sign in to use your own layout", "quota": "Daily limit reached", "ip": "Daily limit reached", | |
| "size": "Layout too large for the demo"} | |
| class LimitReached(LayoutError): | |
| """A limit of the demo (reason: auth, quota, ip, size). str() carries the guide's URL for API users; limit_html links it.""" | |
| def __init__(self, reason: str, text: str): | |
| self.reason, self.text, self.head = reason, text, HEADS[reason] | |
| super().__init__(f"{text} On your own computer there are no limits: {LOCAL_GUIDE}") | |
| def limit_html(self) -> str: | |
| return (f"{html.escape(self.text)} <a href='{LOCAL_GUIDE}' target='_blank' rel='noopener'>Run the models on your own " | |
| "computer</a> to avoid these limits.") | |
| class Who: | |
| user: str | None = None # keyed hash of the Hugging Face username | |
| ip: str | None = None # keyed hash of the client address | |
| served: bool = False # False for in-process calls | |
| _TOKENS: dict = {} | |
| _LOCK = threading.Lock() | |
| def _token_user(token: str) -> str | None: | |
| """A gradio_client call with Client(..., oauth_token=HF token) (Gradio injects it as gr.OAuthToken): whoami, cached ten minutes | |
| by the token's sha256.""" | |
| k = hashlib.sha256(token.encode()).hexdigest() | |
| with _LOCK: | |
| hit = _TOKENS.get(k) | |
| if hit and time.monotonic() - hit[1] < 600: | |
| return hit[0] | |
| try: | |
| from huggingface_hub import whoami | |
| user = keyed("user", whoami(token=token)["name"]) | |
| except Exception: # noqa: BLE001 | |
| user = None | |
| with _LOCK: | |
| if len(_TOKENS) > 10_000: | |
| _TOKENS.clear() | |
| _TOKENS[k] = (user, time.monotonic()) | |
| return user | |
| def who(profile=None, request=None, token=None) -> Who: | |
| """profile: gr.OAuthProfile of a signed-in browser session; token: gr.OAuthToken (an API call's oauth_token); request: gr.Request.""" | |
| if request is None: | |
| return Who() | |
| h = getattr(request, "headers", None) or {} | |
| fwd = h.get("x-forwarded-for") or "" | |
| ip = fwd.split(",")[0].strip() or getattr(getattr(request, "client", None), "host", None) or "?" | |
| user = keyed("user", profile.username) if profile is not None and getattr(profile, "username", None) else None | |
| if user is None and getattr(token, "token", None): | |
| user = _token_user(token.token) | |
| return Who(user=user, ip=keyed("ip", ip), served=True) | |
| _EXAMPLES: set = set() | |
| def register_examples(paths) -> None: | |
| _EXAMPLES.update(hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths) | |
| def is_example(path) -> bool: | |
| try: | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() in _EXAMPLES | |
| except OSError: | |
| return False | |
| def _reset_in() -> str: | |
| now = dt.datetime.now(dt.timezone.utc) | |
| s = int((dt.datetime.combine(now.date() + dt.timedelta(days=1), dt.time(), dt.timezone.utc) - now).total_seconds()) | |
| return f"{s // 3600} h {s % 3600 // 60} min" | |
| def check_file(path, w: Who) -> bool: | |
| """True when the file is the user's own layout (not a bundled example); anonymous served calls get examples only.""" | |
| own = not is_example(path) | |
| if w.served and own and w.user is None: | |
| raise LimitReached("auth", "To run your own layout, sign in with Hugging Face using the button at the top. The examples " | |
| "run without sign-in.") | |
| return own | |
| def check_size(n_conductors: int) -> None: | |
| n = int(n_conductors) + 1 | |
| if n >= MAX_NETS: | |
| raise LimitReached("size", f"This layout has {n} conductors, ground included. The demo takes layouts with fewer than " | |
| f"{MAX_NETS}.") | |
| class Quota: | |
| def __init__(self): | |
| self.lock, self.day, self.users, self.ips = threading.Lock(), None, {}, {} | |
| def _roll(self) -> None: | |
| d = today() | |
| if d != self.day: | |
| self.day, self.users, self.ips = d, {}, {} | |
| def check(self, w: Who, own: bool) -> None: | |
| if not w.served: | |
| return | |
| with self.lock: | |
| self._roll() | |
| if own and self.users.get(w.user, 0) >= DAILY: | |
| raise LimitReached("quota", f"You have used all {DAILY} of today's predictions for your own layouts. The count " | |
| f"resets at 00:00 UTC, in {_reset_in()}. The examples, and repeats of a result you " | |
| "already have, do not count.") | |
| if self.ips.get(w.ip, 0) >= IP_DAILY: | |
| raise LimitReached("ip", f"Your network has made {IP_DAILY} predictions today, the most we allow. The count " | |
| f"resets at 00:00 UTC, in {_reset_in()}.") | |
| def charge(self, w: Who, own: bool) -> None: | |
| if not w.served: | |
| return | |
| with self.lock: | |
| self._roll() | |
| if own and w.user: | |
| self.users[w.user] = self.users.get(w.user, 0) + 1 | |
| self.ips[w.ip] = self.ips.get(w.ip, 0) + 1 | |
| def used(self, w: Who) -> int: | |
| with self.lock: | |
| self._roll() | |
| return self.users.get(w.user, 0) | |
| QUOTA = Quota() | |