noranisa commited on
Commit
c5dde9d
·
verified ·
1 Parent(s): c17e451

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -0
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+ import tarfile
7
+ import urllib.request
8
+ from pathlib import Path
9
+
10
+ import gradio as gr
11
+ import spaces
12
+
13
+ # ============================================================
14
+ # ZeroGPU requirement: at least one module-level @spaces.GPU
15
+ # function, or the Space fails startup with
16
+ # "No @spaces.GPU function detected during startup".
17
+ # Never called; the app serving port 7860 is the bansos daemon.
18
+ # ============================================================
19
+
20
+ @spaces.GPU
21
+ def _zerogpu_startup_stub():
22
+ return None
23
+
24
+
25
+ # A launched Gradio server is what triggers the ZeroGPU startup report
26
+ # (spaces hooks gr.Blocks.launch). It serves only this stub page on 7861;
27
+ # bansos-router itself serves port 7860.
28
+ demo = gr.Blocks()
29
+ with demo:
30
+ gr.Markdown(
31
+ "bansos-router runs on this Space's port 7860. "
32
+ "Open the root URL once the Space is Running."
33
+ )
34
+
35
+
36
+ def launch_gradio_stub():
37
+ demo.queue().launch(
38
+ server_name="0.0.0.0",
39
+ server_port=7861,
40
+ prevent_thread_lock=True,
41
+ show_error=True,
42
+ )
43
+
44
+
45
+ # ============================================================
46
+ # bansos-router launcher (npm package, prebuilt — no build)
47
+ # ============================================================
48
+
49
+ NODE_ROOT = Path("/tmp/node22")
50
+ PORT = "7860"
51
+
52
+
53
+ def log(message):
54
+ print(f"\n[bansos HF] {message}", flush=True)
55
+
56
+
57
+ def run(cmd, cwd=None, env=None):
58
+ log("+ " + " ".join(str(x) for x in cmd))
59
+ subprocess.run(cmd, cwd=str(cwd) if cwd else None, env=env, check=True)
60
+
61
+
62
+ def node_arch():
63
+ arch = platform.machine().lower()
64
+ if arch in ("x86_64", "amd64"):
65
+ return "x64"
66
+ if arch in ("aarch64", "arm64"):
67
+ return "arm64"
68
+ raise RuntimeError(f"Unsupported architecture: {arch}")
69
+
70
+
71
+ def install_node22():
72
+ node_bin = NODE_ROOT / "bin" / "node"
73
+ npm_bin = NODE_ROOT / "bin" / "npm"
74
+ if node_bin.exists() and npm_bin.exists():
75
+ log("Node.js already available.")
76
+ return node_bin, npm_bin
77
+
78
+ log("Finding latest Node.js 22...")
79
+ arch = node_arch()
80
+ with urllib.request.urlopen(
81
+ "https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt", timeout=60
82
+ ) as response:
83
+ shasums = response.read().decode("utf-8")
84
+ match = re.search(rf"([a-f0-9]{{64}})\s+(node-v[\d.]+-linux-{arch}\.tar\.xz)", shasums)
85
+ if not match:
86
+ raise RuntimeError("Node.js 22 binary was not found.")
87
+ expected_hash, filename = match.group(1), match.group(2)
88
+ archive = Path("/tmp") / filename
89
+ log(f"Downloading {filename}...")
90
+ urllib.request.urlretrieve(f"https://nodejs.org/dist/latest-v22.x/{filename}", archive)
91
+
92
+ import hashlib
93
+ digest = hashlib.sha256()
94
+ with open(archive, "rb") as f:
95
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
96
+ digest.update(chunk)
97
+ if digest.hexdigest() != expected_hash:
98
+ raise RuntimeError("Node.js SHA256 verification failed.")
99
+
100
+ extract_root = Path("/tmp/node22-extract")
101
+ shutil.rmtree(extract_root, ignore_errors=True)
102
+ extract_root.mkdir(parents=True, exist_ok=True)
103
+ log("Extracting Node.js...")
104
+ with tarfile.open(archive, "r:xz") as tar:
105
+ tar.extractall(extract_root)
106
+ extracted = next(p for p in extract_root.iterdir() if p.is_dir())
107
+ shutil.rmtree(NODE_ROOT, ignore_errors=True)
108
+ shutil.move(str(extracted), str(NODE_ROOT))
109
+ log("Node.js 22 installed.")
110
+ return node_bin, npm_bin
111
+
112
+
113
+ def main():
114
+ node_bin, npm_bin = install_node22()
115
+
116
+ env = os.environ.copy()
117
+ env["PATH"] = str(NODE_ROOT / "bin") + os.pathsep + env.get("PATH", "")
118
+ # State dir (~/.bansos). Free-tier containers reset on restart.
119
+ env["HOME"] = "/tmp"
120
+ env["PORT"] = PORT
121
+
122
+ run([str(node_bin), "--version"], env=env)
123
+
124
+ bansos_bin = NODE_ROOT / "bin" / "bansos"
125
+ if not bansos_bin.exists():
126
+ log("Installing bansos-router (prebuilt, npm)...")
127
+ run([str(npm_bin), "install", "--global", "--no-audit", "--no-fund", "bansos-router"], env=env)
128
+ else:
129
+ log("bansos-router already installed.")
130
+
131
+ run([str(bansos_bin), "--version"], env=env)
132
+
133
+ log("Launching Gradio stub on 7861 (ZeroGPU startup report)...")
134
+ launch_gradio_stub()
135
+
136
+ log(f"Starting bansos daemon on 0.0.0.0:{PORT}")
137
+ # Foreground (no --bg): this process IS the Space. HF proxies
138
+ # https://<space>.hf.space -> :7860, so allow non-loopback clients.
139
+ os.execvpe(
140
+ str(bansos_bin),
141
+ [str(bansos_bin), "start",
142
+ "--bind", "0.0.0.0", "--port", PORT,
143
+ "--unsafe-allow-non-loopback"],
144
+ env,
145
+ )
146
+
147
+
148
+ if __name__ == "__main__":
149
+ print("\n========================================\n bansos-router - Hugging Face Space\n========================================\n", flush=True)
150
+ main()