Spaces:
Sleeping
Sleeping
File size: 2,516 Bytes
36a47ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | """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()
|