"""The hub's FastAPI app - the web UI's only backend. Routes: ARCHITECTURE.md "Hub HTTP API". Every error reaches the browser as {"detail": ""}. """ from __future__ import annotations import asyncio import collections import json import logging import mimetypes import os import secrets import shutil import time from contextlib import asynccontextmanager, contextmanager from dataclasses import dataclass, field from pathlib import Path, PurePosixPath from typing import IO, Any, AsyncIterator, Callable, Iterator from urllib.parse import parse_qsl, urlencode, urlsplit import httpx from fastapi import Body, FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response from fastapi.staticfiles import StaticFiles from starlette.datastructures import UploadFile as FormFile from starlette.exceptions import HTTPException as StarletteHTTPException from . import __version__, config, dialogs, exports, gpu, model_downloads, multiview, paths, promptlib, propfiles from .adapters.base import StageError, ToolAdapter from .adapters.qwen import FLUX3_NEEDS_ENGINE from .install import sdcpp as engine_pin from .installer_bg import IDLE, BackgroundInstall, tail_lines from .jobs import JobError, JobQueue from .procman import INSTALLING, NOT_INSTALLED, READY, UNSUPPORTED, ProcessManager, ToolError, ToolProcess from .projects import (MAX_IMAGE_UPLOADS, MAX_IMPORT_FILES, MAX_MODEL_UPLOAD_BYTES, MAX_PAINT_BYTES, MAX_PAINT_SIZE, MAX_REFERENCES, MAX_THUMB_BYTES, MAX_UPLOAD_BYTES, MAX_VIEWPORT_BYTES, ProjectError, ProjectStore, box_name_from_file, save_model_files, omnitexture_fresh, omnitexture_own, retopo_size_of, too_many_references) from .settings import SettingsError, SettingsStore log = logging.getLogger(__name__) # nvidia-smi takes ~50 ms per call; the header's VRAM meter is informational and the page polls every 2.5 s. GPU_CACHE_SECONDS = 5.0 LOOPBACK_NAMES = {"127.0.0.1", "localhost", "::1"} # Sec-Fetch-Site values of requests the hub's own page (or the address bar) makes. OWN_SITE = {"same-origin", "none"} MEDIA_TYPES = { ".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".obj": "text/plain", ".mtl": "text/plain", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".json": "application/json", ".txt": "text/plain", } INTERNAL_ERROR = "Something went wrong inside Spellcast3D. The details are in code/logs/hub.log." # Multipart framing around the model files of one import (names, boundaries): far below this. UPLOAD_OVERHEAD = 8 * 1024 * 1024 MAX_MASK_BYTES = 32 * 1024 * 1024 # what the artist masked for an Omni-Texture repaint: a PNG of the texture's size OVERRIDE_KEYS = {"role", "flip_green", "invert"} PROJECT_BUSY = ("Spellcast3D is still working on this project (a job, an import or a save is not done yet). " "Wait for it to finish, or cancel the job, then try again.") LOCAL_CLIENTS = ("127.0.0.1", "::1") # The Instant Meshes viewer as the Retopo stage embeds it (instant-meshes-py's /viewer options): its panel # on the right, and an "Accept" button that asks the page (host_origin, added per request) instead of # downloading the mesh. VIEWER_OPTIONS = {"panel": "right", "export_label": "Accept", "export_action": "host"} NO_IMAGE_GENERATOR = f"There is no image generator, because {paths.CONFIG_FILE.name} is not right." FIX_CONFIG = "Fix it, save the file, then close Spellcast3D and start it again." # The Omni-Texture stage paints with Qwen-Image 2.1 alone: refused while the config file picks Forge Neo (or nothing). NO_OMNITEXTURE = (f"Omni-Texture paints with Qwen-Image 2.1, which {paths.CONFIG_FILE.name} does not pick as the " "image generator. To use it, switch on the line backend = qwen there, save the file, then close " "Spellcast3D and start it again.") BEING_BAKED = ("This prop is being baked again, so the painting was not saved: the new bake replaces these textures. " "Paint once the bake is done.") # The painting's raw pixels wait in the prop's folder under this name while the worker reads them. PAINT_TEMP = ".paint-" def config_changed(started: config.Config, now: config.Config) -> str: """What the hub says while the root config file picks something else than it started with: the new choice, and that it applies at the next start (it installs what a new choice needs).""" name = paths.CONFIG_FILE.name if now.backend is None: return f"{name} was changed and has a mistake now: {config.short(now.problems[0]) if now.problems else ''}" \ f" {FIX_CONFIG}".replace(" ", " ") running = config.BACKEND_NAMES[started.backend] if started.backend is not None else "" if now.graphics_card != started.graphics_card and _config_choice(now)[:2] == _config_choice(started)[:2]: return (f"{name} now picks another graphics card (graphics_card = {now.graphics_card}). Close Spellcast3D " f"and start it again to use it: the tools keep the card they started with until then.") if now.backend == started.backend: # Qwen-Image's model size return (f"{name} now picks Qwen-Image 2.1's model size {now.quality}. Close Spellcast3D and start it again to " f"use it (it downloads that size first; {started.quality} runs until then).") return (f"{name} now picks {config.describe(now)}. Close Spellcast3D and start it again to switch (it installs " f"what that needs" + (f"; {running} runs until then)." if running else ").")) def config_status(cfg: config.Config) -> dict[str, Any]: """The root config file (spellcast3d-config.ini, spellcast/config.py) for /api/status: {"image_backend": "qwen" | "forge" | None (the file has a mistake: no image generator is registered), "quality": Qwen-Image's model size, "problems": [what is wrong with the file, in the artist's words: without the sentence that no image generator is installed until it is fixed, which the page says in its own place], "changed": None (the routes add what ConfigWatch says)}.""" return {"image_backend": cfg.backend, "quality": cfg.quality, "problems": [config.short(p) for p in cfg.problems], "changed": None} def _config_choice(cfg: config.Config) -> tuple[str | None, str | None, str]: """What the config file switches: the image generator, Qwen-Image's model size when it is the one, and the graphics card.""" return cfg.backend, cfg.quality if cfg.backend == paths.QWEN else None, cfg.graphics_card class ConfigWatch: """Notices the root config file picking something else while the hub runs. Nothing switches over until the next start (the installer fetches what a new choice needs, the hub registers the image generator it picks), so /api/status settings_warnings then says to start again. Saving it unchanged, or switching back, says nothing.""" def __init__(self, started_with: config.Config): self._started = started_with self._started_with = _config_choice(started_with) def warnings(self) -> list[str]: try: now = config.load() # read again only when the file was saved (one stat call otherwise) except Exception: log.exception("Could not read the config file") return [] return [config_changed(self._started, now)] if _config_choice(now) != self._started_with else [] class _NoStoreStatic(StaticFiles): """The UI must never come from the browser cache after an update.""" def file_response(self, *args: Any, **kwargs: Any) -> Response: response = super().file_response(*args, **kwargs) response.headers["Cache-Control"] = "no-store" return response @dataclass class Hub: """Everything the routes share. procman / jobs / client exist while the app is running.""" adapters: dict[str, ToolAdapter] settings: SettingsStore store: ProjectStore logs_dir: Path gpu_probe: Callable[[], gpu.GpuInfo | None] hub_port: int | None show_in_explorer: Callable[[Path, bool], bool] # exports.show_in_explorer, or a stand-in in tests repaint: exports.Repainter # exports.run_repaint_worker, or a stand-in in tests install: BackgroundInstall | None = None # the rest of the installation, run in the background multiview_download: multiview.BackgroundDownload | None = None # Pixal3D's multi-view models, on request qwen_full_download: model_downloads.BackgroundDownload | None = None # the full Qwen-Image 2.1, on request flux3_download: model_downloads.BackgroundDownload | None = None # FLUX.3 Image Klein, on request hi3d_download: model_downloads.BackgroundDownload | None = None # Hi3D's AI models, on request config: dict[str, Any] = field(default_factory=dict) # config_status() when the hub started config_watch: ConfigWatch | None = None # stage -> the registered tools that run it (paths.STAGE_TOOLS order): the Images stage has the one image # generator the config file picks (none when the file is not valid) stage_tools: dict[str, list[str]] = field(default_factory=dict) fading: set[tuple[str, str]] = field(default_factory=set) # (project, prop): its Omni-Texture being made # again without the image generator # (project, prop) -> hand paintings of its Omni-Texture being saved painting: collections.Counter[tuple[str, str]] = field(default_factory=collections.Counter) procman: ProcessManager = field(init=False) jobs: JobQueue = field(init=False) client: httpx.AsyncClient = field(init=False) exporter: exports.Exporter = field(init=False) gpu_lock: asyncio.Lock = field(init=False) imesh_lock: asyncio.Lock = field(init=False) import_lock: asyncio.Lock = field(init=False) # one model import at a time (RAM, and its cleanup) export_lock: asyncio.Lock = field(init=False) # one save into the export folders at a time (its caches) # project -> model imports or saves in progress: its files must stay where they are importing: collections.Counter[str] = field(default_factory=collections.Counter) _gpu_cache: dict[str, Any] | None = None _gpu_time: float = -GPU_CACHE_SECONDS async def gpu_info(self) -> dict[str, Any] | None: async with self.gpu_lock: if time.monotonic() - self._gpu_time >= GPU_CACHE_SECONDS: try: info = await asyncio.to_thread(self.gpu_probe) except Exception: log.exception("GPU query failed") info = None self._gpu_cache = info.to_dict() if info else None self._gpu_time = time.monotonic() return self._gpu_cache def adapter(self, tool_id: str) -> ToolAdapter: adapter = self.adapters.get(tool_id) if adapter is None: raise ToolError(f'There is no tool called "{tool_id}".', 404) return adapter def running(self, tool_id: str, not_running: str) -> ToolProcess: """The tool's process if it is ready, else a 409 with `not_running` as the message.""" tp = self.procman.get(tool_id) if tp.state != READY or not tp.alive(): raise ToolError(not_running, 409) return tp def busy_projects(self) -> set[str]: """Projects with a job waiting or running, or a model import or a save in progress: their files must stay where they are (no rename, no tidying away).""" return self.jobs.active_projects() | {p for p, n in self.importing.items() if n} def check_omnitexture_idle(self, project: str, prop_id: str) -> None: """409 while the prop's steps may change (check_steps_stay) or a hand painting of it is being saved: before its steps are made again (fade_omnitexture, take_off_omnitexture).""" self.check_steps_stay(project, prop_id) self.check_not_painting(project, [prop_id]) def check_steps_stay(self, project: str, prop_id: str) -> None: """409 while an Omni-Texture job of the prop waits or runs (its result replaces the one shown), or its Omni-Texture is being made again without the image generator (fade_omnitexture, take_off_omnitexture): the steps Ctrl+Z walks, masks and paints on may go.""" if prop_id in self.jobs.active_props(project, "omnitexture"): raise ProjectError("This prop is being OmniTextured. Wait until it is done.", 409) self.check_not_fading(project, [prop_id]) def check_not_fading(self, project: Any, prop_ids: Any) -> None: """409 while the Omni-Texture of one of the props is being made again without the image generator (a repaint's fade, a picture taken off): that and an Omni-Texture job would write the prop's next result folder both.""" if any((project, prop_id) in self.fading for prop_id in prop_ids if isinstance(prop_id, str)): raise ProjectError("This prop's Omni-Texture is being changed (a fade, or a picture taken off). Wait " "until it is done.", 409) def check_not_painting(self, project: Any, prop_ids: Any) -> None: """409 while a hand painting of one of the props' Omni-Texture is being saved: a job, a fade or a picture taken off would read that model before the painting is in it.""" if any(self.painting[(project, prop_id)] for prop_id in prop_ids if isinstance(prop_id, str)): raise ProjectError("This prop's Omni-Texture is being painted on: your painting is being saved. Try " "again in a moment.", 409) async def ready_omnitexture(self, project: str, prop_id: str, glb: Any, every: bool, mask: bool = False) -> dict[str, Any]: """The worker that puts the prop's repaints on again is made ready ahead of a change (adapters/omnitexture.py make_ready: for a click on the newest repaint, on `every` one, or for the slider of the repaint `glb`), or - `mask`: the artist took up the mask marker - ahead of a repaint of the model shown (ready_to_repaint) -> {"ready": whether it was}. Not while any job waits or runs ("busy": true with it): the memory and the processor are the tools' first, and a change then only takes as long as it did without.""" from .adapters import omnitexture self.check_omnitexture_idle(project, prop_id) if self.jobs.active_projects(): return {"ready": False, "busy": True} # (worth asking again once the job is done) block = self.store.get_prop(project, prop_id)["omnitexture"] prop_dir = self.store.prop_dir(project, prop_id) if mask: return {"ready": await asyncio.to_thread(omnitexture.ready_to_repaint, prop_dir, block)} return {"ready": await asyncio.to_thread(omnitexture.make_ready, prop_dir, block, glb, every)} async def fade_omnitexture(self, project: str, prop_id: str, glb: Any, fade: Any) -> dict[str, Any]: """A repaint of the prop's Omni-Texture with its edge faded `fade` times as far (adapters/omnitexture.py refade: the worker alone, no image generator) -> {"prop", "renamed": {step as it was: step as it is}}.""" from .adapters import omnitexture self.check_omnitexture_idle(project, prop_id) if not isinstance(fade, (int, float)) or isinstance(fade, bool) or not 1.0 <= fade <= omnitexture.MAX_FADE: raise ProjectError(f"A repaint's fade is a number from 1 to {omnitexture.MAX_FADE:g}.", 422) self.fading.add((project, prop_id)) try: block = self.store.get_prop(project, prop_id)["omnitexture"] try: patch, renamed = await asyncio.to_thread(omnitexture.refade, self.store.prop_dir(project, prop_id), block, glb, float(fade)) except StageError as e: raise ProjectError(str(e), 409) from e prop = await asyncio.to_thread(self.store.apply_stage_patch, project, prop_id, "omnitexture", patch) return {"prop": prop, "renamed": renamed} finally: self.fading.discard((project, prop_id)) async def hide_in_omnitexture(self, project: str, prop_id: str, glb: Any, repaint: Any, views: bool, hidden: bool) -> dict[str, Any]: """The eye on a picture of the model shown, `glb`: a repaint (`repaint`: the model it made) or the painted views, all at once (`views`), hidden or shown again (adapters/omnitexture.py refade, show_views: the worker alone, no image generator) -> {"prop", "renamed": {step as it was: step as it is}}.""" from .adapters import omnitexture self.check_omnitexture_idle(project, prop_id) self.fading.add((project, prop_id)) try: prop = self.store.get_prop(project, prop_id) if glb != prop["omnitexture"].get("glb"): raise ProjectError("This prop's Omni-Texture changed meanwhile. Reload the page and try again.", 409) prop_dir = self.store.prop_dir(project, prop_id) try: if views: made = await asyncio.to_thread(omnitexture.show_views, prop_dir, prop, hidden) else: made = await asyncio.to_thread(omnitexture.refade, prop_dir, prop["omnitexture"], repaint, None, hidden) except StageError as e: raise ProjectError(str(e), 409) from e if made is None: # (the views are so already) return {"prop": prop, "renamed": {}} patch, renamed = made prop = await asyncio.to_thread(self.store.apply_stage_patch, project, prop_id, "omnitexture", patch) return {"prop": prop, "renamed": renamed} finally: self.fading.discard((project, prop_id)) async def own_omnitexture(self, project: str, prop_id: str) -> dict[str, Any]: """The prop's 3D model becomes the first step of a result of its own texture, so that the artist may paint on it and mask it without an Omni-Texture job (adapters/omnitexture.py begin_own) -> {"prop"}. A prop that has a result keeps it - but for a result of its own texture on a 3D model made again since: that is begun anew, on the model the prop has now.""" from .adapters import omnitexture self.check_omnitexture_idle(project, prop_id) self.fading.add((project, prop_id)) try: prop = self.store.get_prop(project, prop_id) if prop["omnitexture"].get("glb") and (omnitexture_fresh(prop) or not omnitexture_own(prop)): return {"prop": prop} try: patch = await asyncio.to_thread(omnitexture.begin_own, self.store.prop_dir(project, prop_id), prop) except StageError as e: raise ProjectError(str(e), 409) from e return {"prop": await asyncio.to_thread(self.store.apply_stage_patch, project, prop_id, "omnitexture", patch)} finally: self.fading.discard((project, prop_id)) async def take_off_omnitexture(self, project: str, prop_id: str, glb: Any, view: Any, repaint: Any, whole: bool = False) -> dict[str, Any]: """A painted view (`view`: its folder) or a repaint (`repaint`: the model it made) taken off the model shown, `glb` (adapters/omnitexture.py take_off: the worker alone, no image generator) -> {"prop"}: it shows a new step without that picture. `whole`: the result itself is taken off - the step that follows is none of its models, and the prop shows its 3D model.""" from .adapters import omnitexture self.check_omnitexture_idle(project, prop_id) self.fading.add((project, prop_id)) try: prop = self.store.get_prop(project, prop_id) if glb != prop["omnitexture"].get("glb"): raise ProjectError("This prop's Omni-Texture changed meanwhile. Reload the page and try again.", 409) try: patch = await asyncio.to_thread(omnitexture.take_off, self.store.prop_dir(project, prop_id), prop, view, repaint, whole) except StageError as e: raise ProjectError(str(e), 409) from e return {"prop": await asyncio.to_thread(self.store.apply_stage_patch, project, prop_id, "omnitexture", patch)} finally: self.fading.discard((project, prop_id)) async def paint_omnitexture(self, project: str, prop_id: str, glb: str, width: int, height: int, data: bytes) -> dict[str, Any]: """A hand painting of the prop's Omni-Texture step `glb` (`data`: the page's patch, raw RGBA) saved into its model (adapters/omnitexture.py hand_paint: the worker alone, no image generator) -> the prop, whose thumbnail and bake follow it as they follow a repaint (ProjectStore.omnitexture_painted). Meanwhile no job, fade or picture taken off of the prop starts (check_not_painting).""" from .adapters import omnitexture self.painting[(project, prop_id)] += 1 try: # One save at a time (an export never copies a model being written; one prop's .paint-* files never # meet), and the project is not renamed meanwhile. async with self.export_lock: with self.importing_into(project): self.check_steps_stay(project, prop_id) await asyncio.to_thread(self.store.omnitexture_paint_target, project, prop_id, glb, width, height) prop_dir = self.store.prop_dir(project, prop_id) raw = prop_dir / f"{PAINT_TEMP}{secrets.token_hex(6)}.rgba" try: await asyncio.to_thread(_write_paint, prop_dir, raw, data) del data await asyncio.to_thread(omnitexture.hand_paint, prop_dir, glb, raw, width, height) except StageError as e: raise ProjectError(str(e), 409) from e finally: await asyncio.to_thread(raw.unlink, missing_ok=True) return await asyncio.to_thread(self.store.omnitexture_painted, project, prop_id, glb) finally: self.painting[(project, prop_id)] -= 1 def check_paint(self, project: str, prop_id: str) -> None: """409 while a projection job of the prop waits or runs (its bake replaces the textures), or while the program that saves the painting (in the Instant Meshes venv) cannot run.""" if prop_id in self.jobs.active_props(project, "projection"): raise ProjectError(BEING_BAKED, 409) try: self.procman.check_available(paths.IMESH, installing_ok=False) except ToolError as e: raise ProjectError(f"Saving the painting needs the retopology tool. {e}", 409) from e def can_convert(self, fmt: str) -> None: """Raise ProjectError when an FBX or OBJ (or a placed prop's GLB) cannot be made now: its worker runs in the Instant Meshes venv, which may not be installed yet.""" try: self.procman.check_available(paths.IMESH, installing_ok=False) except ToolError as e: raise ProjectError(f"Saving as .{fmt} needs the retopology tool. {e}", 409) from e def explorer(self, request: Request, target: Path, select: bool) -> bool: """Open File Explorer on `target` for a page on this computer (never with SPELLCAST_NO_EXPLORER=1) -> whether it was opened. Never waits for it.""" if request.client is None or request.client.host not in LOCAL_CLIENTS or not exports.explorer_allowed(): return False return self.show_in_explorer(target, select) @contextmanager def importing_into(self, project: str) -> Iterator[None]: self.importing[project] += 1 try: yield finally: self.importing[project] -= 1 def _host_name(value: str) -> str: """'127.0.0.1:7770' -> '127.0.0.1', '[::1]:7770' -> '::1', 'http://localhost:7770' -> 'localhost'.""" value = value.split("://", 1)[-1].split("/", 1)[0].strip().lower() if value.startswith("["): return value[1:value.find("]")] if "]" in value else value return value.rsplit(":", 1)[0] if value.count(":") == 1 else value def _import_overrides(raw: Any) -> dict[str, dict[str, Any]]: """The artist's corrections of an imported model's textures, checked: {texture key: {"role"?: str, "flip_green"?: bool, "invert"?: bool}} (the tool checks the role names).""" if raw is None: return {} problem = ProjectError('"overrides" must map each texture to {"role", "flip_green", "invert"}. ' 'Reload the page and try again.') if not isinstance(raw, dict) or len(raw) > MAX_IMPORT_FILES: raise problem out: dict[str, dict[str, Any]] = {} for key, value in raw.items(): if not isinstance(value, dict) or set(value) - OVERRIDE_KEYS: raise problem role = value.get("role") if role is not None and not (isinstance(role, str) and 0 < len(role) <= 32): raise problem if any(value.get(flag) is not None and not isinstance(value[flag], bool) for flag in ("flip_green", "invert")): raise problem out[key] = {k: v for k, v in value.items() if v is not None} return out def _check_upload_size(request: Request, limit: int, too_big: str) -> None: """413 `too_big` before an upload is read when it says it is bigger than `limit` bytes.""" try: length = int(request.headers.get("content-length") or 0) except ValueError: length = 0 if length > limit: raise ProjectError(too_big, 413) def _check_model_upload_size(request: Request) -> None: """413 before a model upload is read when it says it is too big.""" _check_upload_size(request, MAX_MODEL_UPLOAD_BYTES + UPLOAD_OVERHEAD, f"These files are too big together (the limit is {MAX_MODEL_UPLOAD_BYTES // 1024 ** 3} GB). " f"Leave out what the model does not need, or use smaller textures.") def _model_uploads(form: Any) -> list[tuple[str, IO[bytes]]]: """(name, stream) of the files of a model upload: the form fields "files" or "files[]", repeated.""" uploads = [(item.filename or "", item.file) for key in ("files", "files[]") for item in form.getlist(key) if isinstance(item, FormFile)] if not uploads: raise ProjectError("Choose your 3D model (.fbx, .obj, .glb or .gltf) together with its textures, " "or one .zip that contains them.") return uploads async def _read_body(request: Request, limit: int, too_big: str) -> bytes: """The raw request body, refused (413 `too_big`) as soon as it passes `limit` bytes.""" try: declared = int(request.headers.get("content-length") or 0) except ValueError: declared = 0 if declared > limit: raise ProjectError(too_big, 413) data = bytearray() async for chunk in request.stream(): data += chunk if len(data) > limit: raise ProjectError(too_big, 413) return bytes(data) async def _read_painting(request: Request, width: int, height: int) -> bytes: """A painting's raw RGBA body (PUT .../paint): 413 past MAX_PAINT_BYTES, 422 when it is not width x height x 4 bytes.""" data = await _read_body(request, MAX_PAINT_BYTES, f"The painting is too big. A texture can be {MAX_PAINT_SIZE} x " f"{MAX_PAINT_SIZE} pixels at most.") if len(data) != width * height * 4: raise ProjectError(f"The painting arrived incomplete ({len(data)} of {width * height * 4} bytes), so it was " f"not saved. Save it again.", 422) return data def _write_paint(prop_dir: Path, raw: Path, data: bytes) -> None: """The painting's raw pixels into `raw` in the prop's folder; what an interrupted save left there goes first.""" for old in prop_dir.glob(f"{PAINT_TEMP}*"): old.unlink(missing_ok=True) raw.write_bytes(data) def _page_origin(request: Request, hub_port: int | None, allow_remote: bool) -> str: """The origin of the hub's page that sent `request` ("http://127.0.0.1:7770"), for the viewer's host_origin: the browser's Origin header when it is a plain http(s) origin of this computer (of any host when the hub listens on the network), else the hub's own address.""" origin = request.headers.get("origin") or "" try: parts = urlsplit(origin) port = parts.port except ValueError: parts, port = None, None if parts is not None and parts.scheme in ("http", "https") and parts.hostname and not parts.username \ and parts.path in ("", "/") and not parts.query and not parts.fragment \ and (allow_remote or parts.hostname in LOOPBACK_NAMES): host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname default = 80 if parts.scheme == "http" else 443 return f"{parts.scheme}://{host}" + (f":{port}" if port is not None and port != default else "") port = hub_port or request.url.port return f"http://127.0.0.1:{port}" if port else "http://127.0.0.1" def _viewer_url(base_url: str, viewer_path: str, host_origin: str) -> str: """The launcher's viewer path on `base_url`, with the viewer options of the Retopo stage appended.""" parts = urlsplit(viewer_path) query = [*parse_qsl(parts.query, keep_blank_values=True), *VIEWER_OPTIONS.items(), ("host_origin", host_origin)] return f"{base_url}{parts.path}?{urlencode(query)}" def create_app(adapters: dict[str, ToolAdapter] | None = None, *, settings: SettingsStore | None = None, store: ProjectStore | None = None, static_dir: Path = paths.STATIC, logs_dir: Path = paths.LOGS, hub_port: int | None = None, allow_remote: bool = False, gpu_probe: Callable[[], gpu.GpuInfo | None] = gpu.primary_gpu, installer: BackgroundInstall | None = None, multiview_download: multiview.BackgroundDownload | None = None, qwen_full_download: model_downloads.BackgroundDownload | None = None, flux3_download: model_downloads.BackgroundDownload | None = None, hi3d_download: model_downloads.BackgroundDownload | None = None, show_in_explorer: Callable[[Path, bool], bool] = exports.show_in_explorer, converter: exports.Converter = exports.run_export_worker, repainter: exports.Repainter = exports.run_repaint_worker, prompt_library: Path | None = None) -> FastAPI: """The hub app. Tests pass fake adapters / temp stores; `python -m spellcast` uses the real ones, with the one image generator the root config file picks (spellcast3d-config.ini, read once here: a change applies at the next start, and /api/status says so meanwhile). allow_remote: the server listens on a non-loopback address, so the Host-header check (protection against DNS rebinding) is switched off. installer: installs what is missing or changed in the background while the hub runs (None: nothing is installed, the tools are used as they are). multiview_download: downloads Pixal3D's multi-view models when the page asks for them (default: into the models folder, waiting for `installer` to finish with Pixal3D; tests pass one of their own). qwen_full_download: the same for the full Qwen-Image 2.1 of the size the config file picks (default: into models/qwen-image, waiting for `installer` to finish with Qwen-Image; tests pass one of their own). flux3_download: the same for FLUX.3 Image Klein of that size (default: into models/flux3-klein; tests pass one). show_in_explorer(path, select) opens File Explorer after a save; converter makes the FBX and OBJ files, repainter saves a painting into a bake (exports.py). Tests pass stand-ins. prompt_library: the prompt library's file (paths.PROMPT_LIBRARY). """ library_file = prompt_library or paths.PROMPT_LIBRARY settings = settings or SettingsStore() # What spellcast3d-config.ini picked as the hub started, one snapshot for all: the image generator registered # here, Forge's folder warnings (SettingsStore.config) and the one "start again" warning (ConfigWatch). started_with = settings.config if settings.config is not None else config.load() for problem in started_with.problems: # in hub.log too, not only on the page log.warning("%s", problem) if adapters is None: from .adapters import build_adapters # "" (the file has a mistake) registers no image generator: a typo must not start one the artist did not pick adapters = build_adapters(image_backend=started_with.backend or "") if multiview_download is None: multiview_download = multiview.BackgroundDownload(install=installer, log_file=logs_dir / multiview.LOG_NAME) # The optional models' downloads, in the size and the folders the registered Qwen-Image runs with (as the hub # started: the config file's; FLUX.3 in Qwen-Image's size too, in its own folder, since its launcher serves it) qwen = adapters.get(paths.QWEN) quality = getattr(qwen, "quality", None) quality = quality if quality in config.QUALITIES else started_with.quality def optional_download(model: str, folder_attr: str) -> model_downloads.BackgroundDownload: folder = getattr(qwen, folder_attr, None) return model_downloads.BackgroundDownload(model, quality, folder if isinstance(folder, Path) else None, install=installer, log_file=logs_dir / model_downloads.MODELS[model].log_name) if qwen_full_download is None: qwen_full_download = optional_download("full", "models_dir") if flux3_download is None: flux3_download = optional_download("flux3", "flux3_dir") if hi3d_download is None: # the 3D stage's: into models/hi3d, then Hi3D's convolutions measured hi3d_download = model_downloads.BackgroundDownload( "hi3d", quality, paths.MODELS_HI3D, install=installer, log_file=logs_dir / model_downloads.MODELS["hi3d"].log_name, then=model_downloads.hi3d_calibration) hub = Hub(adapters=adapters, settings=settings, store=store or ProjectStore(), logs_dir=logs_dir, gpu_probe=gpu_probe, hub_port=hub_port, show_in_explorer=show_in_explorer, repaint=repainter, install=installer, multiview_download=multiview_download, qwen_full_download=qwen_full_download, flux3_download=flux3_download, hi3d_download=hi3d_download, config=config_status(started_with), config_watch=ConfigWatch(started_with), stage_tools={stage: [t for t in tools if t in adapters and stage in adapters[t].stages] for stage, tools in paths.STAGE_TOOLS.items()}) # A new prop starts with the retopology method the artist picked last (the page saves it in the settings). hub.store.retopo_default = lambda: (settings.get().get("retopo") or {}).get("default_method") @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: hub.gpu_lock, hub.imesh_lock, hub.import_lock = asyncio.Lock(), asyncio.Lock(), asyncio.Lock() hub.export_lock = asyncio.Lock() if hub.install is not None: hub.install.start() # trust_env=False: every call goes to 127.0.0.1, a system proxy must never see it. hub.client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=10.0), trust_env=False) hub.procman = ProcessManager(hub.adapters, hub.settings, hub.client, hub_port=hub_port, logs_dir=logs_dir, install=hub.install) await hub.procman.startup() hub.jobs = JobQueue(hub.procman, hub.store, hub.settings, hub.adapters, hub.client) hub.jobs.start() if hub.install is not None: # the card is the calibration's alone while the installer measures it hub.install.on_tick = lambda: hub.procman.free_card_for_calibration(hub.jobs.tools_at_work()) hub.exporter = exports.Exporter(hub.store, converter, hub.can_convert) await asyncio.to_thread(hub.store.tidy_untitled) # empty untitled projects of earlier sessions await asyncio.to_thread(hub.store.clear_work_dirs) # what the tools' jobs left in projects/*/temp/ await asyncio.to_thread(hub.store.clear_partial_meshes) # and the 3D models they were writing try: yield finally: log.info("Shutting down: stopping all tools…") await hub.jobs.close() await hub.procman.stop_all() from .adapters import omnitexture await asyncio.to_thread(omnitexture.close_fades) # the edge fade's kept worker if hub.install is not None: await hub.install.close() if hub.multiview_download is not None: await hub.multiview_download.close() for download in (hub.qwen_full_download, hub.flux3_download, hub.hi3d_download): if download is not None: await download.close() await hub.client.aclose() app = FastAPI(title="Spellcast3D", version=__version__, lifespan=lifespan, docs_url=None, redoc_url=None) app.state.hub = hub # ---- errors ---------------------------------------------------------------------------- async def user_error(request: Request, exc: Exception) -> JSONResponse: return JSONResponse({"detail": str(exc)}, status_code=getattr(exc, "status_code", 400)) for error_type in (ProjectError, ToolError, JobError, SettingsError): app.add_exception_handler(error_type, user_error) @app.exception_handler(RequestValidationError) async def bad_request(request: Request, exc: RequestValidationError) -> JSONResponse: errors = exc.errors() first = errors[0] if errors else {} where = ".".join(str(p) for p in first.get("loc", ()) if p != "body") or "request" return JSONResponse({"detail": f"The request was not understood ({where}: {first.get('msg', 'invalid')}). " f"Reload the page and try again."}, status_code=422) @app.exception_handler(Exception) async def internal_error(request: Request, exc: Exception) -> JSONResponse: log.error("Unhandled error in %s %s", request.method, request.url.path, exc_info=exc) return JSONResponse({"detail": INTERNAL_ERROR}, status_code=500) @app.middleware("http") async def local_only(request: Request, call_next: Callable[[Request], Any]) -> Response: """Refuse requests addressed to another host name (DNS rebinding) or sent by other websites. A web page's /