Nokia123543 commited on
Commit
c0a30a3
·
verified ·
1 Parent(s): ec9679a

PLUS: штатный сервер MuScriptor с нашими весами и ссылкой

Browse files
Files changed (1) hide show
  1. plus/serve_muscriptor.py +234 -0
plus/serve_muscriptor.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MuScriptor-сервер и публичная ссылка, одной командой.
2
+
3
+ python3 plus/serve_muscriptor.py # наши веса с HF, порт 8222
4
+ python3 plus/serve_muscriptor.py --device cuda # на T4
5
+ python3 plus/serve_muscriptor.py --no-tunnel # только локально
6
+
7
+ Поднимает ШТАТНЫЙ сервер MuScriptor (python -m muscriptor serve), тот самый,
8
+ что отдаёт веб-приложение «MuScriptor: Music to MIDI and Sheet Music», и
9
+ открывает туннель, печатая ссылку. Своего интерфейса здесь нет.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import collections
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ import time
23
+ import urllib.request
24
+
25
+ LINKS_FILE = "muscriptor_links.txt"
26
+ DEFAULT_MODEL = "hf://Nokia123543/muscriptor-large-fork/model.safetensors"
27
+ PACKAGE = "muscriptor"
28
+ TUNNEL_ORDER = ("localhostrun", "serveo", "cloudflared")
29
+
30
+
31
+ def say(text: str) -> None:
32
+ print(text, flush=True)
33
+
34
+
35
+ def ensure_package() -> None:
36
+ import importlib.util
37
+
38
+ if importlib.util.find_spec(PACKAGE) is not None:
39
+ return
40
+ say("ставлю пакет %s" % PACKAGE)
41
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", PACKAGE], check=False)
42
+
43
+
44
+ def healthy(port: int, timeout: float = 3.0) -> bool:
45
+ try:
46
+ with urllib.request.urlopen("http://127.0.0.1:%d/health" % port, timeout=timeout) as answer:
47
+ return answer.status == 200
48
+ except Exception:
49
+ return False
50
+
51
+
52
+ def start_server(port: int, model: str, device: str, dtype: str | None) -> subprocess.Popen:
53
+ command = [sys.executable, "-m", "muscriptor", "serve",
54
+ "--model", model, "--device", device, "--host", "0.0.0.0", "--port", str(port)]
55
+ if dtype:
56
+ command += ["--dtype", dtype]
57
+ log = open("muscriptor_server.log", "a")
58
+ say("запускаю: " + " ".join(command[1:]))
59
+ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT,
60
+ stdin=open(os.devnull, "rb"))
61
+ deadline = time.time() + 600
62
+ started = time.time()
63
+ while time.time() < deadline:
64
+ if process.poll() is not None:
65
+ raise SystemExit("сервер умер при старте, смотри muscriptor_server.log")
66
+ if healthy(port):
67
+ return process
68
+ waited = int(time.time() - started)
69
+ if waited and waited % 15 == 0:
70
+ say(" жду загрузки модели, %d с (первый раз качаются веса)"
71
+ % waited)
72
+ time.sleep(1)
73
+ time.sleep(2)
74
+ raise SystemExit("сервер не ответил за 10 минут, смотри muscriptor_server.log")
75
+
76
+
77
+ class Tunnel:
78
+ def __init__(self, name: str, argv: list[str], pattern: str):
79
+ self.name, self.pattern = name, re.compile(pattern)
80
+ self.url: str | None = None
81
+ self.tail: collections.deque[str] = collections.deque(maxlen=40)
82
+ self.proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
83
+ stdin=open(os.devnull, "rb"), text=True, bufsize=1)
84
+ threading.Thread(target=self._drain, daemon=True).start()
85
+
86
+ def _drain(self) -> None:
87
+ assert self.proc.stdout is not None
88
+ for line in self.proc.stdout:
89
+ self.tail.append(line.rstrip())
90
+ if self.url is None:
91
+ found = self.pattern.search(line)
92
+ if found:
93
+ self.url = found.group(0)
94
+
95
+ def alive(self) -> bool:
96
+ return self.proc.poll() is None
97
+
98
+ def kill(self) -> None:
99
+ try:
100
+ self.proc.kill()
101
+ except Exception:
102
+ pass
103
+
104
+
105
+ SSH_OPTS = ["-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null",
106
+ "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3",
107
+ "-o", "TCPKeepAlive=yes", "-o", "ExitOnForwardFailure=yes"]
108
+
109
+
110
+ def specs(port: int) -> list[tuple[str, list[str], str]]:
111
+ return [
112
+ ("localhostrun",
113
+ ["ssh", "-T", *SSH_OPTS, "-R", "80:127.0.0.1:%d" % port, "nokey@localhost.run"],
114
+ r"https://[a-z0-9]+\.lhr\.life"),
115
+ ("serveo",
116
+ ["ssh", "-T", *SSH_OPTS, "-R", "80:127.0.0.1:%d" % port, "serveo.net"],
117
+ r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)*\."
118
+ r"(?:serveousercontent|serveo)\.[a-z]+"),
119
+ ("cloudflared",
120
+ ["cloudflared", "tunnel", "--url", "http://127.0.0.1:%d" % port, "--no-autoupdate"],
121
+ r"https://[a-z0-9-]+\.trycloudflare\.com"),
122
+ ]
123
+
124
+
125
+ def reachable(url: str, attempts: int = 4) -> bool:
126
+ for _ in range(attempts):
127
+ try:
128
+ with urllib.request.urlopen(url + "/health", timeout=8) as answer:
129
+ if answer.status == 200:
130
+ return True
131
+ except Exception:
132
+ pass
133
+ time.sleep(3)
134
+ return False
135
+
136
+
137
+ def open_tunnel(port: int, order: tuple[str, ...]) -> Tunnel:
138
+ table = {name: (argv, pattern) for name, argv, pattern in specs(port)}
139
+ fails = []
140
+ for name in order:
141
+ if name not in table:
142
+ continue
143
+ argv, pattern = table[name]
144
+ if not shutil.which(argv[0]):
145
+ say(" [%s] нет команды %s, пропускаю" % (name, argv[0]))
146
+ continue
147
+ say(" [%s] открываю" % name)
148
+ tunnel = Tunnel(name, argv, pattern)
149
+ deadline, started = time.time() + 60, time.time()
150
+ while time.time() < deadline and tunnel.url is None and tunnel.alive():
151
+ time.sleep(1)
152
+ waited = int(time.time() - started)
153
+ if waited and waited % 10 == 0:
154
+ say(" [%s] ждём адрес, %d с" % (name, waited))
155
+ if tunnel.url and reachable(tunnel.url):
156
+ say(" [%s] работает: %s" % (name, tunnel.url))
157
+ return tunnel
158
+ fails.append((name, tunnel.url, list(tunnel.tail)[-2:]))
159
+ tunnel.kill()
160
+ for name, url, tail in fails:
161
+ say(" [%s] не вышло: %s | %s" % (name, url or "нет адреса", " / ".join(tail)))
162
+ raise SystemExit("ни один туннель не поднялся")
163
+
164
+
165
+ def write_link(url: str, port: int) -> None:
166
+ lines = ["MuScriptor " + time.strftime("%H:%M:%S"), "ссылка: " + url,
167
+ "локально: http://127.0.0.1:%d" % port]
168
+ with open(LINKS_FILE, "w", encoding="utf-8") as handle:
169
+ handle.write("\n".join(lines) + "\n")
170
+ say("\n" + "\n".join(lines))
171
+
172
+
173
+ def main(argv: list[str] | None = None) -> int:
174
+ parser = argparse.ArgumentParser(description="MuScriptor: сервер и ссылка")
175
+ parser.add_argument("--port", type=int, default=8222)
176
+ parser.add_argument("--model", default=DEFAULT_MODEL,
177
+ help="путь к safetensors, имя размера или hf://org/repo/file")
178
+ parser.add_argument("--device", default="auto", help="auto | cpu | cuda | cuda:0")
179
+ parser.add_argument("--dtype", default=None, help="float32 | float16 | bfloat16")
180
+ parser.add_argument("--tunnel", default=None, help="только этот туннель")
181
+ parser.add_argument("--no-tunnel", action="store_true", help="без публичной ссылки")
182
+ parser.add_argument("--keep", type=int, default=0, help="держать N секунд и выйти")
183
+ args = parser.parse_args(argv)
184
+
185
+ ensure_package()
186
+ server = start_server(args.port, args.model, args.device, args.dtype)
187
+ say("[1/2] сервер отвечает: http://127.0.0.1:%d" % args.port)
188
+
189
+ if args.no_tunnel:
190
+ write_link("нет (локальный режим)", args.port)
191
+ say(">>> LOCAL LINK: http://127.0.0.1:%d" % args.port)
192
+ tunnel, order = None, ()
193
+ else:
194
+ say("[2/2] публичная ссылка")
195
+ order = (args.tunnel,) + tuple(n for n in TUNNEL_ORDER if n != args.tunnel) \
196
+ if args.tunnel else TUNNEL_ORDER
197
+ tunnel = open_tunnel(args.port, order)
198
+ write_link(tunnel.url or "", args.port)
199
+ say(">>> OPEN THIS LINK: " + str(tunnel.url))
200
+
201
+ started, beat = time.time(), time.time()
202
+ try:
203
+ while True:
204
+ time.sleep(10)
205
+ if time.time() - beat > 60:
206
+ beat = time.time()
207
+ say(" жив: %.1f мин | сервер %s | ссылка %s"
208
+ % ((time.time() - started) / 60,
209
+ "ок" if server.poll() is None else "упал",
210
+ tunnel.url if tunnel else "локально"))
211
+ if args.keep and time.time() - started > args.keep:
212
+ break
213
+ if server.poll() is not None:
214
+ say("сервер упал, поднимаю заново")
215
+ server = start_server(args.port, args.model, args.device, args.dtype)
216
+ if tunnel is not None and not tunnel.alive():
217
+ say("туннель умер, открываю новый")
218
+ tunnel.kill()
219
+ tunnel = open_tunnel(args.port, order)
220
+ write_link(tunnel.url or "", args.port)
221
+ if tunnel.url:
222
+ say(">>> OPEN THIS LINK: " + tunnel.url)
223
+ except KeyboardInterrupt:
224
+ pass
225
+ if tunnel is not None:
226
+ tunnel.kill()
227
+ if server.poll() is None:
228
+ server.terminate()
229
+ say("остановлено")
230
+ return 0
231
+
232
+
233
+ if __name__ == "__main__":
234
+ sys.exit(main())