"""Start the Space's server with the engines its image may not hold. Anyone can pull a public Space's image, so the image holds no engine code. At start this fetches the engine tarball from the private model repo with the Space secret HF_TOKEN, installs it with engines.py, which stops unless the tarball comes from the commit engines.lock pins, and then runs the given command without HF_TOKEN in its environment. python boot.py tini -- uvicorn app.main:create_app --factory """ import os import shutil import subprocess import sys import tempfile import urllib.error import urllib.request from pathlib import Path from urllib.parse import urljoin ENGINES_URL = "https://huggingface.co/MrTechie/audit-automation-engines/resolve/main/engines.tar" HERE = Path(__file__).resolve().parent REDIRECTS = {301, 302, 303, 307, 308} class _KeepRedirect(urllib.request.HTTPRedirectHandler): # The tarball redirects to a signed storage URL, which must not receive the token. def redirect_request(self, *args: object, **kwargs: object) -> None: return None def fetch(token: str, out: Path) -> None: request = urllib.request.Request(ENGINES_URL, headers={"Authorization": f"Bearer {token}"}) try: response = urllib.request.build_opener(_KeepRedirect).open(request, timeout=60) except urllib.error.HTTPError as error: if error.code not in REDIRECTS: sys.exit(f"the engine download answered HTTP {error.code}") location = urljoin(ENGINES_URL, error.headers["Location"]) response = urllib.request.urlopen(location, timeout=120) # noqa: S310 an https URL from the Hub. with response, out.open("wb") as tarball: shutil.copyfileobj(response, tarball) def main() -> None: env = dict(os.environ) token = env.pop("HF_TOKEN", "") if not token: sys.exit("the Space secret HF_TOKEN is not set") with tempfile.TemporaryDirectory() as folder: tarball = Path(folder) / "engines.tar" fetch(token, tarball) install = [sys.executable, str(HERE / "engines.py"), "install", str(tarball)] subprocess.run( # noqa: S603 the installer that ships beside this file. [*install, "--pin", "engines.lock", "--into", env["AA_ENGINE_ROOT"]], check=True, env=env, ) print(f"engines installed in {env['AA_ENGINE_ROOT']}", flush=True) os.execvpe(sys.argv[1], sys.argv[1:], env) # noqa: S606 the image's own CMD. if __name__ == "__main__": main()