{t['title']}
{t['running']}
{t['what']}
"""ScolioSim helper: runs TotalSegmentator on this computer for the ScolioSim web app. ScolioSim runs in the browser, and a browser cannot install or start programs. This small server, installed once, does that part: it listens only on this computer (127.0.0.1), answers only the ScolioSim site, and installs, runs and removes TotalSegmentator when the page asks. The CT goes from the browser to this program inside the same computer and nowhere else. Standard library only: it runs on its own small Python, apart from TotalSegmentator's. """ from __future__ import annotations import ctypes import json import os import re import shutil import signal import subprocess import sys import threading import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path VERSION = "1.4" PORT = 41789 IDLE_MINUTES = 30 WINDOWS = sys.platform == "win32" MAC = sys.platform == "darwin" NO_WINDOW = 0x08000000 if WINDOWS else 0 # CREATE_NO_WINDOW def package_family() -> str | None: """The package this program runs from when installed from the Microsoft Store, or None.""" if not WINDOWS: return None try: length = ctypes.c_uint32(0) get = ctypes.windll.kernel32.GetCurrentPackageFamilyName if get(ctypes.byref(length), None) != 122: # ERROR_INSUFFICIENT_BUFFER; 15700 = no package return None name = ctypes.create_unicode_buffer(length.value) return name.value if get(ctypes.byref(length), name) == 0 else None except (AttributeError, OSError): return None PACKAGE = package_family() if PACKAGE: # From the Store: the program is a package, read-only, its Python in python\ (this file in python\Lib). # What it makes goes to a real folder of its own, beside the installer's: the package does not let Windows # keep its AppData writes aside (manifest), because the DLLs of a program kept there do not load, and the # package's own folder is so deep that TotalSegmentator's paths would pass the 260 characters a Windows # path may have. Windows does not remove this folder with the package: Uninstall empties it first. CODE = Path(sys.executable).resolve().parent.parent APP = Path(os.environ["LOCALAPPDATA"]) / "ScolioSim" / "Store" APP.mkdir(parents=True, exist_ok=True) else: CODE = APP = Path(__file__).resolve().parent ENGINE = APP / "engine" # TotalSegmentator's own Python WEIGHTS = APP / "totalseg" # its model weights and settings WORK = APP / "work" # a CT while it is segmented, removed afterwards # On macOS and Linux the install script (helper-install.sh) puts uv beside this file, and leaves # uninstall.sh there, which unregisters scoliosim-helper:// and deletes this folder UV = CODE / ("uv.exe" if WINDOWS else "uv") WORKER = CODE / "worker.py" LOG = APP / "helper.log" ORIGINS = { "https://scoliosim.com", "https://www.scoliosim.com", "https://scoliosim.web.app", "https://scoliosim.firebaseapp.com", } DEV_ORIGIN = re.compile(r"^http://(localhost|127\.0\.0\.1):\d+$") # What TotalSegmentator brings: the program, PyTorch, readers for compressed DICOM PACKAGES = ["TotalSegmentator", "pylibjpeg", "pylibjpeg-libjpeg", "pylibjpeg-openjpeg", "pylibjpeg-rle"] def log(text: str) -> None: try: with LOG.open("a", encoding="utf-8") as f: f.write(time.strftime("%Y-%m-%d %H:%M:%S ") + text + "\n") except OSError: pass # ---------------------------------------------------------------- this computer def sysctl(name: str) -> str: """A value of the Mac's sysctl, or an empty text.""" try: return subprocess.run(["/usr/sbin/sysctl", "-n", name], capture_output=True, text=True, timeout=5).stdout.strip() except (OSError, subprocess.SubprocessError): return "" def memory_gib() -> float | None: if MAC: try: return int(sysctl("hw.memsize")) / 2**30 except ValueError: return None if not WINDOWS: try: return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 2**30 except (ValueError, OSError, AttributeError): return None class Status(ctypes.Structure): _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong), ("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("pagefile", ctypes.c_ulonglong), ("freepage", ctypes.c_ulonglong), ("virtual", ctypes.c_ulonglong), ("freevirtual", ctypes.c_ulonglong), ("extended", ctypes.c_ulonglong)] s = Status() s.length = ctypes.sizeof(Status) return s.total / 2**30 if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(s)) else None def graphics() -> dict | None: """The NVIDIA card, if there is one: the only kind TotalSegmentator uses on Windows and Linux.""" smi = shutil.which("nvidia-smi") if not smi: return None try: out = subprocess.run([smi, "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=10, creationflags=NO_WINDOW).stdout name, mib = [x.strip() for x in out.strip().splitlines()[0].split(",")] return {"name": name, "memoryGib": round(int(mib) / 1024, 1)} except (OSError, ValueError, IndexError, subprocess.SubprocessError): return None def apple_silicon() -> dict | None: """A Mac with Apple silicon (M1 and later), whose graphics PyTorch uses through Metal (mps), or None. Asked of the Mac itself, not of this Python, which could be an Intel one running under Rosetta.""" if not MAC or sysctl("hw.optional.arm64") != "1": return None return {"name": sysctl("machdep.cpu.brand_string") or "Apple silicon"} MACHINE = {"memoryGib": None, "graphics": None, "apple": None} def machine() -> dict: disk = shutil.disk_usage(APP) return {**MACHINE, "freeDiskGib": round(disk.free / 2**30, 1), "platform": sys.platform} def engine() -> dict | None: """TotalSegmentator as installed here, or None.""" try: return json.loads((ENGINE / "ready.json").read_text(encoding="utf-8")) except (OSError, ValueError): return None def engine_python() -> Path: return ENGINE / ("Scripts/python.exe" if WINDOWS else "bin/python") def folder_size(path: Path) -> int: total = 0 for root, _, files in os.walk(path): for name in files: try: total += (Path(root) / name).stat().st_size except OSError: pass return total # ---------------------------------------------------------------- the one job at a time class Job: def __init__(self, kind: str, stages: list[str]): self.id = uuid.uuid4().hex[:12] self.kind = kind self.stages = stages self.stage = 0 self.lines: list[str] = [] self.started = time.time() self.finished: float | None = None self.error: str | None = None self.process: subprocess.Popen | None = None self.cancelled = False self.received = 0 self.expected = 0 self.fast = False self.bodies = False self.last_file = time.time() def say(self, text: str) -> None: text = text.rstrip() if not text: return # A progress bar redraws its line: keep only the latest if self.lines and ("%|" in text or text.startswith("\r")) and "%|" in self.lines[-1]: self.lines[-1] = text.strip() else: self.lines.append(text.strip()) del self.lines[:-40] def view(self) -> dict: return { "id": self.id, "kind": self.kind, "stages": self.stages, "stage": self.stage, "lines": self.lines[-12:], "seconds": round((self.finished or time.time()) - self.started), "done": self.finished is not None, "error": self.error, "cancelled": self.cancelled, "received": self.received, "expected": self.expected, } JOB: Job | None = None LOCK = threading.Lock() LAST_SEEN = time.time() def busy() -> bool: return JOB is not None and JOB.finished is None def run(job: Job, command: list[str], env: dict | None = None) -> int: """Runs a step of a job, its output read line by line into the job.""" # On macOS and Linux in a process group of its own, so that Cancel stops the programs it starts too job.process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, creationflags=NO_WINDOW, bufsize=1, text=True, encoding="utf-8", errors="replace", start_new_session=not WINDOWS) assert job.process.stdout for line in job.process.stdout: for part in line.split("\r"): if part.startswith("STAGE "): try: job.stage = int(part.split()[1]) except (IndexError, ValueError): pass else: job.say(part) return job.process.wait() def uv_env() -> dict: env = dict(os.environ) env["UV_PYTHON_INSTALL_DIR"] = str(APP / "python") env["UV_CACHE_DIR"] = str(APP / "cache") env["UV_NO_PROGRESS"] = "1" if PACKAGE: # No Python downloaded: TotalSegmentator's is made from a copy of the package's (see install) env["UV_PYTHON_DOWNLOADS"] = "never" env["TOTALSEG_HOME_DIR"] = str(WEIGHTS) if MAC: # What the Apple graphics cannot do, PyTorch does on the processor instead of stopping env["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" env["PYTHONIOENCODING"] = "utf-8" env["PYTHONUNBUFFERED"] = "1" return env def install(job: Job) -> None: env = uv_env() try: job.stage = 0 job.say("Creating TotalSegmentator's own Python 3.12...") if PACKAGE: # From the Store, a copy of the package's own Python, kept in this folder: nothing downloaded, and # not the package's folder itself, which changes name with every update base = APP / "python-base" if not (base / "python.exe").exists(): shutil.copytree(Path(sys.base_prefix), base, dirs_exist_ok=True) python = ["--python", str(base / "python.exe")] else: # Always uv's own Python, in this folder: never one the computer already has (uv finds them in the registry) python = ["--python", "3.12", "--managed-python"] if run(job, [str(UV), "venv", *python, "--allow-existing", str(ENGINE)], env) != 0: raise RuntimeError("Could not create the Python environment.") if job.cancelled: return job.stage = 1 nvidia = MACHINE["graphics"] is not None packages = list(PACKAGES) if MAC: # PyTorch for the Mac is the standard one, from PyPI: with Apple silicon it brings the graphics (mps). # For Intel Macs PyTorch stopped at 2.2, built against NumPy 1 if not MACHINE["apple"]: packages.append("numpy<2") job.say("Installing TotalSegmentator and PyTorch" + (" for the Apple graphics" if MACHINE["apple"] else " for the processor") + " (a few GB)...") else: # CUDA only with an NVIDIA card; with any other card, the processor build env["UV_TORCH_BACKEND"] = "auto" if nvidia else "cpu" job.say("Installing TotalSegmentator and PyTorch" + (" for the NVIDIA card" if nvidia else " for the processor") + " (a few GB)...") if run(job, [str(UV), "pip", "install", "--python", str(engine_python()), "--upgrade", *packages], env) != 0: raise RuntimeError("Could not install TotalSegmentator. Is the computer connected to the internet?") if job.cancelled: return job.stage = 2 job.say("Downloading the model weights (about 1.3 GB)...") if run(job, [str(engine_python()), "-I", str(WORKER), "weights"], env) != 0: raise RuntimeError("Could not download the model weights.") if job.cancelled: return job.stage = 3 check = subprocess.run([str(engine_python()), "-I", str(WORKER), "check"], capture_output=True, text=True, env=env, creationflags=NO_WINDOW, timeout=300) info = json.loads(check.stdout.strip().splitlines()[-1]) info["installed"] = time.strftime("%Y-%m-%d") shutil.rmtree(APP / "cache", ignore_errors=True) # Measured once: walking its thousands of files takes seconds info["sizeGib"] = round((folder_size(ENGINE) + folder_size(WEIGHTS)) / 2**30, 1) (ENGINE / "ready.json").write_text(json.dumps(info), encoding="utf-8") if info.get("cuda"): job.say(f"Ready. Graphics card in use: {info['device']}.") elif info.get("mps"): job.say("Ready. The graphics of Apple silicon will do the work.") else: job.say("Ready. The processor will do the work.") job.stage = 4 except Exception as e: # noqa: BLE001 - every failure is shown on the page job.error = str(e) or e.__class__.__name__ log(f"install failed: {job.error}") finally: job.finished = time.time() def segment(job: Job, folder: Path) -> None: env = uv_env() try: command = [str(engine_python()), "-I", str(WORKER), "segment", str(folder / "dicom"), str(folder / "vertebrae.nii.gz")] if job.fast: command.append("--fast") if job.bodies: command.append("--bodies") code = run(job, command, env) if job.cancelled: return if code != 0 or not (folder / "vertebrae.nii.gz").exists(): last = next((line for line in reversed(job.lines) if line.startswith("ERROR")), None) raise RuntimeError(last[6:].strip() if last else "TotalSegmentator stopped without finishing.") shutil.rmtree(folder / "dicom", ignore_errors=True) except Exception as e: # noqa: BLE001 job.error = str(e) or e.__class__.__name__ log(f"segment failed: {job.error}") finally: job.finished = time.time() def remove_engine(job: Job) -> None: try: for path in (ENGINE, WEIGHTS, APP / "cache", WORK): job.say(f"Removing {path.name}...") shutil.rmtree(path, ignore_errors=True) job.stage = 1 finally: job.finished = time.time() def stop_process(job: Job) -> None: p = job.process if p and p.poll() is None: if WINDOWS: subprocess.run(["taskkill", "/T", "/F", "/PID", str(p.pid)], capture_output=True, creationflags=NO_WINDOW) else: try: os.killpg(p.pid, signal.SIGKILL) # its whole group: TotalSegmentator's worker processes too except OSError: p.kill() def uninstall_everything() -> None: """The uninstaller removes this folder once this program has stopped.""" if not WINDOWS: # macOS and Linux: uninstall.sh, left by the install script, waits for this program to stop, unregisters # scoliosim-helper:// and deletes this folder, TotalSegmentator, its weights and its Python included script = APP / "uninstall.sh" if script.exists(): subprocess.Popen(["/bin/sh", str(script)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True) threading.Timer(0.5, lambda: os._exit(0)).start() return if PACKAGE: # A package is removed by Windows, which does not touch this folder: emptied here first (TotalSegmentator, # its weights, its Python), then the package's page in Settings, with the Uninstall button def empty_and_go() -> None: shutil.rmtree(APP, ignore_errors=True) try: APP.parent.rmdir() # ScolioSim, if the installer's helper is not there too except OSError: pass os.startfile(f"ms-settings:appsfeatures-app?{PACKAGE}") os._exit(0) threading.Timer(0.5, empty_and_go).start() return uninstaller = next(iter(sorted(APP.glob("unins*.exe"))), None) if uninstaller: subprocess.Popen(f'cmd /c ping -n 3 127.0.0.1 >nul & "{uninstaller}" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART', creationflags=NO_WINDOW | 0x00000008, close_fds=True) # DETACHED_PROCESS threading.Timer(0.5, lambda: os._exit(0)).start() # ---------------------------------------------------------------- the page of this program TEXTS = { "en": { "lang": "en", "title": "ScolioSim Helper", "running": "The helper is running on this computer.", "what": "It segments a patient's CT with TotalSegmentator for the ScolioSim web app, here on this computer: " "the CT goes from the browser to this program and nowhere else. It is used from ScolioSim itself " "(X-rays, The patient's own vertebrae, Segment the CT on this computer); this page only shows how it is.", "version": "Version", "engine": "TotalSegmentator", "notYet": "not installed yet: ScolioSim installs it when you ask (a few GB)", "installed": "installed ({gib} GB)", "card": "Graphics card", "noCard": "none that TotalSegmentator can use: the processor does the work", "job": "Now", "idle": "waiting", "open": "Open ScolioSim", "stop": "Stop the helper", "stopped": "The helper has stopped. ScolioSim starts it again when it needs it.", "privacy": "Privacy", "store": "To remove it, use Uninstall the helper in ScolioSim: it first deletes TotalSegmentator and its weights (several GB), which Windows would leave behind, and then opens Windows Settings.", }, "es": { "lang": "es", "title": "Asistente de ScolioSim", "running": "El asistente está en marcha en este ordenador.", "what": "Segmenta el TAC de un paciente con TotalSegmentator para la aplicación web ScolioSim, aquí, en este ordenador: " "el TAC va del navegador a este programa y a ningún otro sitio. Se usa desde la propia ScolioSim " "(Radiografías, Las vértebras del propio paciente, Segmentar el TAC en este ordenador); esta página solo muestra cómo está.", "version": "Versión", "engine": "TotalSegmentator", "notYet": "aún sin instalar: ScolioSim lo instala cuando usted lo pida (unos GB)", "installed": "instalado ({gib} GB)", "card": "Tarjeta gráfica", "noCard": "ninguna que TotalSegmentator pueda usar: trabaja el procesador", "job": "Ahora", "idle": "a la espera", "open": "Abrir ScolioSim", "stop": "Detener el asistente", "stopped": "El asistente se ha detenido. ScolioSim lo vuelve a poner en marcha cuando lo necesita.", "privacy": "Privacidad", "store": "Para quitarlo, use Desinstalar el asistente en ScolioSim: primero borra TotalSegmentator y sus pesos (varios GB), que Windows dejaría, y después abre Configuración de Windows.", }, } def status_page(languages: str) -> str: t = TEXTS["es" if languages.lower().startswith("es") else "en"] eng = engine() card = MACHINE["graphics"] apple = MACHINE["apple"] rows = [ (t["version"], VERSION), (t["engine"], t["installed"].format(gib=eng.get("sizeGib", "?")) if eng else t["notYet"]), (t["card"], f"{card['name']} ({card['memoryGib']} GB)" if card else f"{apple['name']} (Apple silicon)" if apple else t["noCard"]), (t["job"], f"{JOB.kind}{' …' if busy() else ''}" if JOB else t["idle"]), ] table = "".join(f"
{t['running']}
{t['what']}