From 1d7f3dee6dbc0cd28fdec2a70dfda5dbfc4e2405 Mon Sep 17 00:00:00 2001 From: Bruno Fargnoli Date: Tue, 14 Jul 2026 12:24:41 +0200 Subject: [PATCH] Fixed Desktop App Installer with Auto Rig --- electron-builder.yml | 10 + electron/main.cjs | 231 +++++++++++++-------- electron/preload.cjs | 27 ++- electron/pysetup.cjs | 304 ++++++++++++++++++++++++++++ electron/python.cjs | 168 --------------- electron/setup.html | 171 ++++++++++++++++ server.js | 7 +- src/components/SettingsModal.jsx | 83 +++++++- thirdparty/skintokens/download.py | 16 +- thirdparty/skintokens/rig.py | 10 +- thirdparty/skintokens/rig_server.py | 22 +- 11 files changed, 777 insertions(+), 272 deletions(-) create mode 100644 electron/pysetup.cjs delete mode 100644 electron/python.cjs create mode 100644 electron/setup.html diff --git a/electron-builder.yml b/electron-builder.yml index 249cb1a..4ddcc9e 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -47,6 +47,16 @@ files: - "!python-server/.venv/**" - "!python-server/**/__pycache__/**" - "!python-server/*.log" + # Rigging service (opt-in). Ship the source; the venv + multi-GB model + # checkpoints are provisioned into the per-user data dir on opt-in, never shipped. + - thirdparty/skintokens/**/* + - "!thirdparty/skintokens/.venv/**" + - "!thirdparty/skintokens/**/__pycache__/**" + - "!thirdparty/skintokens/experiments/**" + - "!thirdparty/skintokens/models/**" + - "!thirdparty/skintokens/tmp_ckpt/**" + - "!thirdparty/skintokens/tmp_gradio/**" + - "!thirdparty/skintokens/*.log" - "!**/*.map" win: diff --git a/electron/main.cjs b/electron/main.cjs index 5ce118d..288d84b 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -4,47 +4,55 @@ // 1. Resolve the app root + a writable data directory. // 2. Spawn the Node/Express backend (server.js) using Electron's own Node // runtime (ELECTRON_RUN_AS_NODE) so users don't need Node installed. -// 3. Spawn the Python mesh-tools service (optional; Auto UV / Auto Retopo). -// On first launch it creates a venv and installs requirements — this is -// the "require Python on the machine" model (fastest to ship). -// 4. Wait for the backend to answer, then open the window pointing at it. -// 5. Kill both child processes on quit. -// -// The window loads http://localhost:, where the backend serves the Vite -// production build (dist/) and the API from the same origin — see server.js. +// 3. FIRST RUN: show a setup window that provisions the Python services with +// uv (Mesh Tools always; Rigging opt-in) and streams live progress. Later +// runs skip straight to the splash — the venvs already exist. +// 4. Launch the Python services (Mesh Tools always; Rigging if it was set up). +// 5. Wait for the backend to answer, then open the app window. +// 6. Kill child processes on quit. -const { app, BrowserWindow, shell, dialog } = require('electron'); +const { app, BrowserWindow, shell, dialog, ipcMain } = require('electron'); const path = require('node:path'); const http = require('node:http'); const fs = require('node:fs'); const { spawn } = require('node:child_process'); -const { startPythonService } = require('./python.cjs'); +const { + isReady, + ensureUv, + setupPythonServer, + setupSkintokens, + startPythonServer, + startSkintokens, +} = require('./pysetup.cjs'); -// Force a stable, brandable name BEFORE any getPath('userData') call so the -// per-user data folder is ".../3DGenStudio" instead of ".../app" (which came -// from package.json "name"). Applies to both dev and packaged builds. +// Force a stable, brandable name BEFORE any getPath('userData') call. app.setName('3DGenStudio'); const BACKEND_PORT = Number(process.env.PORT) || 3001; const BACKEND_ORIGIN = `http://localhost:${BACKEND_PORT}`; const PYTHON_PORT = Number(process.env.MESHTOOLS_PORT) || 8200; +const RIG_PORT = Number(process.env.RIGTOOLS_PORT) || 8300; -// app.getAppPath() is the project root in dev and resources/app in a packaged -// build (we ship unpacked — asar:false — so relative requires + dist/ resolve -// normally and the backend can serve static files without asar path shims). const APP_ROOT = app.getAppPath(); const SERVER_JS = path.join(APP_ROOT, 'server.js'); const PYTHON_DIR = path.join(APP_ROOT, 'python-server'); +const SKINTOKENS_DIR = path.join(APP_ROOT, 'thirdparty', 'skintokens'); -// The backend keys its data/ folder off process.cwd() (see storage.js), so we -// point it at a per-user writable location. The installed app directory is -// read-only on macOS/Linux, so we must not write there. +// Backend keys data/ off process.cwd() (storage.js); point it at a per-user +// writable dir. The venvs also live here — the installed app dir is read-only. const DATA_ROOT = process.env.GENSTUDIO_DATA_ROOT || app.getPath('userData'); const LOG_DIR = path.join(DATA_ROOT, 'logs'); +const PY_VENV = path.join(DATA_ROOT, 'python-venv'); +const RIG_VENV = path.join(DATA_ROOT, 'rig-venv'); +// Rigging model weights (experiments/, models/) — the installed app dir is +// read-only, so download them here and point rig_server.py at it. +const RIG_DATA = path.join(DATA_ROOT, 'rig-data'); let backendProc = null; let pythonHandle = null; +let rigHandle = null; let mainWindow = null; +let setupWindow = null; let shuttingDown = false; function log(line) { @@ -53,9 +61,7 @@ function log(line) { try { fs.mkdirSync(LOG_DIR, { recursive: true }); fs.appendFileSync(path.join(LOG_DIR, 'desktop.log'), stamped + '\n'); - } catch { - /* logging must never crash startup */ - } + } catch { /* logging must never crash startup */ } } function openLogStream(name) { @@ -72,7 +78,7 @@ function startBackend() { cwd: DATA_ROOT, env: { ...process.env, - ELECTRON_RUN_AS_NODE: '1', // run server.js as plain Node, not an Electron window + ELECTRON_RUN_AS_NODE: '1', PORT: String(BACKEND_PORT), NODE_ENV: 'production', }, @@ -93,15 +99,11 @@ function startBackend() { return proc; } -// Poll the backend until it answers or we time out. function waitForBackend(timeoutMs = 60000, intervalMs = 400) { const deadline = Date.now() + timeoutMs; return new Promise((resolve, reject) => { const tick = () => { - const req = http.get(`${BACKEND_ORIGIN}/`, (res) => { - res.resume(); - resolve(); - }); + const req = http.get(`${BACKEND_ORIGIN}/`, (res) => { res.resume(); resolve(); }); req.on('error', () => { if (Date.now() > deadline) reject(new Error('Backend did not start in time')); else setTimeout(tick, intervalMs); @@ -112,74 +114,142 @@ function waitForBackend(timeoutMs = 60000, intervalMs = 400) { }); } +// Ensure each provisioned service is running (and don't double-start). Safe to +// call repeatedly — after boot and after an in-app "install rigging" action. +function syncServices() { + if (!pythonHandle && isReady(PY_VENV)) { + try { + pythonHandle = startPythonServer({ + serviceDir: PYTHON_DIR, venvDir: PY_VENV, port: PYTHON_PORT, + logStream: openLogStream('python.log'), log, + }); + } catch (err) { log(`Mesh Tools service failed to start (non-fatal): ${err.message}`); } + } + if (!rigHandle && isReady(RIG_VENV)) { + try { + rigHandle = startSkintokens({ + serviceDir: SKINTOKENS_DIR, venvDir: RIG_VENV, dataDir: RIG_DATA, port: RIG_PORT, + logStream: openLogStream('rig.log'), log, + }); + } catch (err) { log(`Rigging service failed to start (non-fatal): ${err.message}`); } + } +} + +// Provision the Python services with uv, forwarding progress to `send`. Skips a +// service that is already set up (so the in-app "install rigging" path doesn't +// needlessly reinstall Mesh Tools). +async function doSetup(rigging, send) { + const uv = await ensureUv({ appRoot: APP_ROOT, onLine: (t) => send({ service: 'meshtools', kind: 'log', text: t }) }); + if (!uv) throw new Error('Could not find or install uv (the Python toolchain manager).'); + + if (!isReady(PY_VENV)) { + await setupPythonServer({ + uv, serviceDir: PYTHON_DIR, venvDir: PY_VENV, + onProgress: (e) => send({ service: 'meshtools', ...e }), + }); + } else { + send({ service: 'meshtools', kind: 'done' }); + } + + if (rigging && !isReady(RIG_VENV)) { + await setupSkintokens({ + uv, serviceDir: SKINTOKENS_DIR, venvDir: RIG_VENV, dataDir: RIG_DATA, + onProgress: (e) => send({ service: 'rigging', ...e }), + }); + } +} + +// Global setup IPC — used by BOTH the first-run window and the running app +// (Settings → Rigging "install" action). Progress streams back to whichever +// window invoked it; on success the newly-provisioned services are launched. +function registerSetupIpc() { + ipcMain.handle('setup:status', () => ({ + desktop: true, + meshtools: isReady(PY_VENV), + rigging: isReady(RIG_VENV), + })); + + ipcMain.handle('setup:run', async (event, opts = {}) => { + const send = (evt) => { try { event.sender.send('setup:progress', evt); } catch { /* window gone */ } }; + try { + await doSetup(!!opts.rigging, send); + syncServices(); + log('Setup run complete.'); + return { ok: true, status: { meshtools: isReady(PY_VENV), rigging: isReady(RIG_VENV) } }; + } catch (err) { + log(`Setup run failed: ${err.message}`); + send({ kind: 'error', text: err.message }); + return { ok: false, error: err.message }; + } + }); +} + +// First-run setup window. Resolves when the user launches (or closes) it. +function runFirstRunSetup() { + return new Promise((resolve) => { + const win = new BrowserWindow({ + width: 640, height: 560, resizable: false, backgroundColor: '#0d0f14', + title: '3D Gen Studio — Setup', show: true, center: true, + webPreferences: { + preload: path.join(__dirname, 'preload.cjs'), + contextIsolation: true, nodeIntegration: false, + }, + }); + setupWindow = win; + win.setMenuBarVisibility(false); + win.loadFile(path.join(__dirname, 'setup.html')); + + let resolved = false; + const done = () => { if (!resolved) { resolved = true; resolve(); } }; + ipcMain.once('setup:finish', done); + win.on('closed', done); + }); +} + function createWindow() { mainWindow = new BrowserWindow({ - width: 1600, - height: 1000, - minWidth: 1024, - minHeight: 700, - backgroundColor: '#111318', - show: false, - title: '3D Gen Studio', + width: 1600, height: 1000, minWidth: 1024, minHeight: 700, + backgroundColor: '#111318', show: false, title: '3D Gen Studio', webPreferences: { preload: path.join(__dirname, 'preload.cjs'), - contextIsolation: true, - nodeIntegration: false, + contextIsolation: true, nodeIntegration: false, }, }); - mainWindow.once('ready-to-show', () => mainWindow.show()); mainWindow.loadURL(BACKEND_ORIGIN); - - // Open external links (docs, Discord, cloud API dashboards) in the OS browser. mainWindow.webContents.setWindowOpenHandler(({ url }) => { - if (!url.startsWith(BACKEND_ORIGIN)) { - shell.openExternal(url); - return { action: 'deny' }; - } + if (!url.startsWith(BACKEND_ORIGIN)) { shell.openExternal(url); return { action: 'deny' }; } return { action: 'allow' }; }); - - mainWindow.on('closed', () => { - mainWindow = null; - }); + mainWindow.on('closed', () => { mainWindow = null; }); } function loadingWindow() { const win = new BrowserWindow({ - width: 520, - height: 320, - frame: false, - resizable: false, - transparent: true, - backgroundColor: '#00000000', - show: true, - center: true, - title: '3D Gen Studio', - // Edit electron/splash.html to change the splash design. + width: 520, height: 320, frame: false, resizable: false, transparent: true, + backgroundColor: '#00000000', show: true, center: true, title: '3D Gen Studio', }); win.loadFile(path.join(__dirname, 'splash.html')); return win; } async function boot() { - const splash = loadingWindow(); - + fs.mkdirSync(DATA_ROOT, { recursive: true }); + registerSetupIpc(); backendProc = startBackend(); - // Python is optional — Auto UV/Retopo only. Never block or fail the app on it. - try { - pythonHandle = startPythonService({ - pythonDir: PYTHON_DIR, - dataRoot: DATA_ROOT, - port: PYTHON_PORT, - logStream: openLogStream('python.log'), - log, - }); - } catch (err) { - log(`Python service failed to start (non-fatal): ${err.message}`); + // First run OR a broken/absent Mesh Tools venv → guided setup window with + // progress (isReady probes the venv, so a legacy venv whose system Python was + // removed is detected and rebuilt). Otherwise → fast path (splash). + let splash = null; + if (!isReady(PY_VENV)) { + await runFirstRunSetup(); + } else { + splash = loadingWindow(); } + syncServices(); + try { await waitForBackend(); log('Backend is up.'); @@ -194,29 +264,24 @@ async function boot() { } createWindow(); - if (!splash.isDestroyed()) splash.close(); + if (splash && !splash.isDestroyed()) splash.close(); + if (setupWindow && !setupWindow.isDestroyed()) setupWindow.close(); } function shutdown() { shuttingDown = true; - if (pythonHandle && typeof pythonHandle.stop === 'function') { - try { pythonHandle.stop(); } catch { /* ignore */ } - } - if (backendProc && !backendProc.killed) { - try { backendProc.kill(); } catch { /* ignore */ } + for (const h of [pythonHandle, rigHandle]) { + if (h && typeof h.stop === 'function') { try { h.stop(); } catch { /* ignore */ } } } + if (backendProc && !backendProc.killed) { try { backendProc.kill(); } catch { /* ignore */ } } } -// Single-instance: focus the existing window instead of launching a 2nd copy -// (which would fight over ports 3001/8200). if (!app.requestSingleInstanceLock()) { app.quit(); } else { app.on('second-instance', () => { - if (mainWindow) { - if (mainWindow.isMinimized()) mainWindow.restore(); - mainWindow.focus(); - } + const win = mainWindow || setupWindow; + if (win) { if (win.isMinimized()) win.restore(); win.focus(); } }); app.whenReady().then(boot); diff --git a/electron/preload.cjs b/electron/preload.cjs index 6ad9788..5f83ee3 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -1,11 +1,28 @@ -// Minimal preload. The UI is a normal same-origin web app served by the -// backend, so it needs no privileged bridge today. We expose only a tiny, -// read-only marker so the frontend can detect it's running inside the desktop -// shell (e.g. to hide "open in browser" hints) without granting Node access. -const { contextBridge } = require('electron'); +// Preload bridges. +// - genStudioDesktop: read-only marker so the web UI can tell it runs in the +// desktop shell. +// - genStudioSetup: used ONLY by the first-run setup window (setup.html) to +// drive the Python provisioning and stream progress. Harmless elsewhere. +const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('genStudioDesktop', { isDesktop: true, platform: process.platform, version: process.env.npm_package_version || null, }); + +contextBridge.exposeInMainWorld('genStudioSetup', { + // Kick off provisioning. opts: { rigging: boolean }. Resolves to { ok, error }. + run: (opts) => ipcRenderer.invoke('setup:run', opts), + // Which services are provisioned: { desktop, meshtools, rigging }. + status: () => ipcRenderer.invoke('setup:status'), + // Subscribe to progress events: { service, kind, phase, pct, text }. + // Returns an unsubscribe function. + onProgress: (cb) => { + const handler = (_e, evt) => cb(evt); + ipcRenderer.on('setup:progress', handler); + return () => ipcRenderer.removeListener('setup:progress', handler); + }, + // Tell the main process the user is done and the app can launch (first-run window). + finish: () => ipcRenderer.send('setup:finish'), +}); diff --git a/electron/pysetup.cjs b/electron/pysetup.cjs new file mode 100644 index 0000000..7928f05 --- /dev/null +++ b/electron/pysetup.cjs @@ -0,0 +1,304 @@ +// uv-based provisioning + launch for the bundled Python services, with progress +// callbacks so the first-run setup window can show live status. Supersedes the +// older python.cjs (system-Python model). +// +// Model: uv provisions a pinned standalone Python (3.13 — see each service's +// .python-version) and a venv in a WRITABLE per-user dir (the installed app +// folder is read-only on macOS/Linux). This mirrors the CLI run.bat/run.sh and +// makes the flash-attn wheel selection for rigging deterministic. +// +// - Mesh Tools (python-server): always provisioned. CPU only. +// - Rigging (skintokens): opt-in. Heavy (torch + flash-attn + model) and needs +// an NVIDIA GPU; the setup reuses the service's own Python helpers +// (select_flash_attn.py / download_wheel.py / download.py). +// +// Everything is async and streams output to an onProgress callback; nothing +// blocks the Electron main-process event loop. + +const path = require('node:path'); +const fs = require('node:fs'); +const os = require('node:os'); +const { spawn, spawnSync } = require('node:child_process'); + +const IS_WIN = process.platform === 'win32'; +const PYVER = '3.13'; +const UV_EXE = IS_WIN ? 'uv.exe' : 'uv'; + +function venvPython(venvDir) { + return IS_WIN + ? path.join(venvDir, 'Scripts', 'python.exe') + : path.join(venvDir, 'bin', 'python'); +} + +// Written only after a service's deps fully install, so an interrupted first run +// is detected and re-completed next time instead of launching a broken service. +function depsMarker(venvDir) { + return path.join(venvDir, '.deps-installed'); +} + +// A venv's python.exe existing on disk is NOT enough: a venv made by +// `python -m venv` depends on its base interpreter, so if that system Python was +// uninstalled/moved the venv python fails to launch ("did not find executable at +// C:\PythonXXX\python.exe", exit 103). Actually PROBE it so a broken venv is +// detected and rebuilt (uv venvs are self-contained and don't have this issue). +function venvUsable(venvDir) { + const vp = venvPython(venvDir); + if (!fs.existsSync(vp)) return false; + try { + const r = spawnSync(vp, ['-c', 'import sys'], { timeout: 20000, stdio: 'ignore' }); + return r.status === 0; + } catch { + return false; + } +} + +function isReady(venvDir) { + return fs.existsSync(depsMarker(venvDir)) && venvUsable(venvDir); +} + +// Create the venv with uv, rebuilding from scratch if the existing one is broken +// (e.g. a legacy python -m venv whose base interpreter is gone). A healthy venv +// is left untouched. Returns an exit code (0 = ok). +async function ensureVenv({ uv, serviceDir, venvDir, onLine }) { + if (venvUsable(venvDir)) return 0; + if (fs.existsSync(venvDir)) { + if (onLine) onLine(`Existing virtual environment is unusable — rebuilding it.\n`); + try { fs.rmSync(venvDir, { recursive: true, force: true }); } catch { /* ignore */ } + } + const r = await runStream(uv, ['venv', venvDir, '--python', PYVER], { cwd: serviceDir, env: process.env, onLine }); + return r.code; +} + +// Spawn a command, stream stdout+stderr line-ish chunks to onLine, resolve the +// exit code. Never rejects. `capture` also accumulates stdout for the caller. +function runStream(cmd, args, { cwd, env, onLine } = {}) { + return new Promise((resolve) => { + const emit = (s) => { if (onLine) try { onLine(s); } catch { /* ignore */ } }; + emit(`$ ${path.basename(cmd)} ${args.join(' ')}\n`); + let p; + try { + p = spawn(cmd, args, { cwd, env: env || process.env }); + } catch (err) { + emit(`spawn error: ${err.message}\n`); + return resolve({ code: -1, stdout: '' }); + } + let stdout = ''; + p.stdout.on('data', (d) => { const s = d.toString(); stdout += s; emit(s); }); + p.stderr.on('data', (d) => emit(d.toString())); + p.on('error', (err) => { emit(`error: ${err.message}\n`); resolve({ code: -1, stdout }); }); + p.on('exit', (code) => resolve({ code: code ?? -1, stdout })); + }); +} + +// Locate uv, or install it. Order: env override -> bundled resource -> +// PATH -> ~/.local/bin -> official installer (into ~/.local/bin). Returns the +// uv path, or null on failure. +async function ensureUv({ appRoot, onLine }) { + const emit = (s) => { if (onLine) try { onLine(s); } catch { /* ignore */ } }; + + const candidates = [ + process.env.GENSTUDIO_UV, + // Bundled via electron-builder extraResources (resources/uv/uv[.exe]). + appRoot && path.join(appRoot, 'resources', 'uv', UV_EXE), + path.join(os.homedir(), '.local', 'bin', UV_EXE), + ].filter(Boolean); + for (const c of candidates) { + if (fs.existsSync(c)) return c; + } + // On PATH? + try { + const probe = spawnSync('uv', ['--version'], { encoding: 'utf8' }); + if (probe.status === 0) return 'uv'; + } catch { /* not on PATH */ } + + emit('Installing uv (Python toolchain manager)…\n'); + if (IS_WIN) { + await runStream('powershell', [ + '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', + 'irm https://astral.sh/uv/install.ps1 | iex', + ], { onLine }); + } else { + await runStream('sh', ['-c', 'curl -LsSf https://astral.sh/uv/install.sh | sh'], { onLine }); + } + const installed = path.join(os.homedir(), '.local', 'bin', UV_EXE); + if (fs.existsSync(installed)) return installed; + try { + const probe = spawnSync('uv', ['--version'], { encoding: 'utf8' }); + if (probe.status === 0) return 'uv'; + } catch { /* still not found */ } + return null; +} + +// Run a weighted list of steps, mapping progress to 0..1 and forwarding phase + +// log events via onProgress({ kind, phase, pct, text }). A step returns an exit +// code (0 = ok); a non-zero code from a `required` step aborts with an error. +async function runSteps(steps, onProgress) { + const total = steps.reduce((s, st) => s + (st.weight || 1), 0); + let done = 0; + const emitLog = (text) => onProgress({ kind: 'log', text }); + for (const step of steps) { + onProgress({ kind: 'phase', phase: step.label, pct: done / total }); + const code = await step.run(emitLog); + if (code !== 0 && step.required !== false) { + throw new Error(`${step.label} failed (exit ${code}).`); + } + done += step.weight || 1; + onProgress({ kind: 'phase', phase: step.label, pct: done / total }); + } +} + +// ---- Mesh Tools (python-server) ------------------------------------------- +async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) { + const vp = venvPython(venvDir); + const env = process.env; + await runSteps([ + { + label: 'Provisioning Python', weight: 2, + run: (log) => runStream(uv, ['python', 'install', PYVER], { cwd: serviceDir, env, onLine: log }).then((r) => r.code), + }, + { + label: 'Creating virtual environment', weight: 1, + run: (log) => ensureVenv({ uv, serviceDir, venvDir, onLine: log }), + }, + { + label: 'Installing mesh-tools dependencies', weight: 6, + run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code), + }, + ], onProgress); + fs.writeFileSync(depsMarker(venvDir), new Date().toISOString()); + onProgress({ kind: 'done' }); +} + +// ---- Rigging (skintokens) -------------------------------------------------- +// `dataDir` is a WRITABLE folder for the downloaded weights (experiments/, +// models/). The packaged app's code dir is read-only, so the model MUST NOT be +// downloaded there; rig_server.py chdirs to this same dir at launch (via +// RIGTOOLS_DATA_DIR) so its relative weight lookups resolve here. +async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) { + const vp = venvPython(venvDir); + const env = process.env; + const modelDir = dataDir || serviceDir; + try { fs.mkdirSync(modelDir, { recursive: true }); } catch { /* ignore */ } + + // Provision + base deps first. + await runSteps([ + { + label: 'Provisioning Python', weight: 2, + run: (log) => runStream(uv, ['python', 'install', PYVER], { cwd: serviceDir, env, onLine: log }).then((r) => r.code), + }, + { + label: 'Creating virtual environment', weight: 1, + run: (log) => ensureVenv({ uv, serviceDir, venvDir, onLine: log }), + }, + { + label: 'Installing rigging dependencies', weight: 5, + run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code), + }, + ], (e) => onProgress(scaled(e, 0, 0.4))); + + // Select the flash-attn wheel + matching torch for this machine's CUDA. + onProgress({ kind: 'phase', phase: 'Selecting CUDA build', pct: 0.4 }); + const sel = await runStream(vp, ['select_flash_attn.py'], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + let wheel = null, torchArgs = null; + for (const line of sel.stdout.split(/\r?\n/)) { + if (line.startsWith('WHEEL=')) wheel = line.slice(6).trim(); + else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim(); + } + + // Install torch (curated per-wheel command, or a sane default). + onProgress({ kind: 'phase', phase: 'Installing PyTorch', pct: 0.45 }); + const torchInstall = torchArgs + ? torchArgs.split(/\s+/) + : ['torch==2.7.0', 'torchvision==0.22.0', 'torchaudio==2.7.0', '--index-url', 'https://download.pytorch.org/whl/cu128']; + { + const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchInstall], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + if (r.code !== 0) throw new Error(`PyTorch install failed (exit ${r.code}).`); + } + + // flash-attn — download the prebuilt wheel via the HF client, then install it. + if (wheel) { + onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.65 }); + const dl = await runStream(vp, ['download_wheel.py', wheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + const localWheel = dl.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop(); + if (dl.code === 0 && localWheel) { + const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.'); + } else { + throw new Error('flash-attn download failed. Rigging cannot start without it.'); + } + } else { + throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA. Rigging is unavailable.'); + } + + // Model checkpoints (large; downloaded into the WRITABLE data dir). + onProgress({ kind: 'phase', phase: 'Downloading model checkpoints', pct: 0.8 }); + { + const r = await runStream(vp, ['download.py', '--model', '--dir', modelDir], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + if (r.code !== 0) throw new Error(`Model download failed (exit ${r.code}).`); + } + + fs.writeFileSync(depsMarker(venvDir), new Date().toISOString()); + onProgress({ kind: 'phase', phase: 'Rigging ready', pct: 1 }); + onProgress({ kind: 'done' }); +} + +// Remap a child onProgress event's pct into a [lo, hi] slice of the parent bar. +function scaled(evt, lo, hi) { + if (evt.kind === 'phase' && typeof evt.pct === 'number') { + return { ...evt, pct: lo + (hi - lo) * evt.pct }; + } + return evt; +} + +// ---- Launchers ------------------------------------------------------------- +function startPythonServer({ serviceDir, venvDir, port, logStream, log }) { + return startService({ + name: 'mesh-tools', serviceDir, venvDir, script: 'main.py', logStream, log, + env: { MESHTOOLS_HOST: '127.0.0.1', MESHTOOLS_PORT: String(port) }, + }); +} + +function startSkintokens({ serviceDir, venvDir, dataDir, port, logStream, log }) { + // RIGTOOLS_DATA_DIR makes rig_server.py chdir to the same writable folder the + // weights were downloaded into, so its relative model lookups resolve. + const env = { RIGTOOLS_HOST: '127.0.0.1', RIGTOOLS_PORT: String(port) }; + if (dataDir) env.RIGTOOLS_DATA_DIR = dataDir; + return startService({ name: 'rigging', serviceDir, venvDir, script: 'rig_server.py', logStream, log, env }); +} + +function startService({ name, serviceDir, venvDir, script, env, logStream, log }) { + const write = (s) => { try { logStream && logStream.write(s); } catch { /* ignore */ } }; + const vp = venvPython(venvDir); + if (!isReady(venvDir)) { + log && log(`${name} not set up yet — skipping launch.`); + return { stop() {} }; + } + let proc = null; + try { + log && log(`Starting ${name} service…`); + proc = spawn(vp, [script], { + cwd: serviceDir, + env: { ...process.env, ...env }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + proc.stdout.on('data', (d) => write(d.toString())); + proc.stderr.on('data', (d) => write(d.toString())); + proc.on('exit', (code, signal) => { log && log(`${name} service exited (code=${code} signal=${signal})`); }); + } catch (err) { + log && log(`${name} service failed to start: ${err.message}`); + } + return { + stop() { if (proc && !proc.killed) { try { proc.kill(); } catch { /* ignore */ } } }, + }; +} + +module.exports = { + PYVER, + venvPython, + isReady, + ensureUv, + setupPythonServer, + setupSkintokens, + startPythonServer, + startSkintokens, +}; diff --git a/electron/python.cjs b/electron/python.cjs deleted file mode 100644 index 33ad421..0000000 --- a/electron/python.cjs +++ /dev/null @@ -1,168 +0,0 @@ -// Cross-platform launcher for the Python mesh-tools service (Auto UV / Auto -// Retopo). This is the Node/Electron equivalent of python-server/run.bat, made -// to work on Windows, macOS and Linux. -// -// Model: "require Python on the machine" (fastest to ship). On first launch we -// 1. locate a system Python interpreter, -// 2. create a virtualenv in a WRITABLE location (the per-user data dir — the -// installed app folder is read-only on macOS/Linux), -// 3. install requirements.txt (CPU-only base install), -// then run main.py against that venv. Subsequent launches reuse the venv. -// -// IMPORTANT: every step here is ASYNCHRONOUS. venv creation + pip install take -// minutes on first run; doing them synchronously (spawnSync) would block -// Electron's main-process event loop and starve the backend health-poll, -// causing a bogus "backend did not start" error on first launch. -// -// GPU acceleration (CuPy/Warp) is intentionally NOT installed here to keep the -// first-run install portable and fast; it can be layered in later per the -// python-server README (requirements-nvidia.txt + detect_cuda.py). - -const path = require('node:path'); -const fs = require('node:fs'); -const { spawn, spawnSync } = require('node:child_process'); - -const IS_WIN = process.platform === 'win32'; - -function venvPython(venvDir) { - return IS_WIN - ? path.join(venvDir, 'Scripts', 'python.exe') - : path.join(venvDir, 'bin', 'python'); -} - -// Written only after requirements install fully succeeds. Gating on this (not -// just python.exe's existence) means a venv left half-built by a crashed or -// interrupted first run is detected and completed on the next launch, instead -// of launching a broken service that fails on missing imports. -function depsMarker(venvDir) { - return path.join(venvDir, '.deps-installed'); -} - -// Find a usable system Python (3.x). A one-shot `--version` probe is instant, -// so spawnSync is fine here (it does not block for any meaningful time). -function findSystemPython() { - const candidates = IS_WIN ? ['python', 'python3', 'py'] : ['python3', 'python']; - for (const c of candidates) { - try { - const r = spawnSync(c, ['--version'], { encoding: 'utf8' }); - if (r.status === 0 && /Python 3\./.test((r.stdout || '') + (r.stderr || ''))) { - return c; - } - } catch { - /* try next */ - } - } - return null; -} - -// Public entry point. Fully non-blocking: kicks off setup + launch and returns -// immediately with a handle exposing stop(). -function startPythonService({ pythonDir, dataRoot, port, logStream, log }) { - const venvDir = path.join(dataRoot, 'python-venv'); - let proc = null; - let stopped = false; - - const write = (s) => { try { logStream.write(s); } catch { /* ignore */ } }; - - // Run a command asynchronously, streaming output to the log. Resolves to the - // exit code (0 = success). Never rejects. - const run = (cmd, args) => - new Promise((resolve) => { - write(`\n$ ${cmd} ${args.join(' ')}\n`); - let p; - try { - p = spawn(cmd, args, { cwd: pythonDir }); - } catch (err) { - write(`spawn error: ${err.message}\n`); - return resolve(-1); - } - // {end:false} so a finished child doesn't close the shared log stream. - p.stdout.on('data', (d) => write(d.toString())); - p.stderr.on('data', (d) => write(d.toString())); - p.on('error', (err) => { write(`error: ${err.message}\n`); resolve(-1); }); - p.on('exit', (code) => resolve(code)); - }); - - async function ensureVenv() { - // Fully set up already (venv + deps marker) → nothing to do. - if (fs.existsSync(venvPython(venvDir)) && fs.existsSync(depsMarker(venvDir))) { - return true; - } - - const py = venvPython(venvDir); - - // Create the venv only if it isn't there yet. If a previous run created it - // but crashed before finishing pip install, reuse it and just (re)install. - if (!fs.existsSync(py)) { - const sysPython = findSystemPython(); - if (!sysPython) { - log( - 'Python 3 not found on PATH — the mesh-tools service (Auto UV/Retopo) ' + - 'will be unavailable. Install Python 3.10+ and restart to enable it.' - ); - return false; - } - log(`First run: creating Python venv with "${sysPython}" (this can take a few minutes)…`); - fs.mkdirSync(path.dirname(venvDir), { recursive: true }); - if ((await run(sysPython, ['-m', 'venv', venvDir])) !== 0) { - log('Failed to create Python venv — see python.log.'); - return false; - } - } else { - log('Completing Python setup (installing dependencies)…'); - } - - await run(py, ['-m', 'pip', 'install', '--upgrade', 'pip']); - - const reqs = path.join(pythonDir, 'requirements.txt'); - if ((await run(py, ['-m', 'pip', 'install', '-r', reqs])) !== 0) { - log('Failed to install Python requirements — see python.log.'); - return false; - } - - try { fs.writeFileSync(depsMarker(venvDir), new Date().toISOString()); } catch { /* ignore */ } - log('Python environment ready.'); - return true; - } - - async function launch() { - try { - if (stopped) return; - const ok = await ensureVenv(); - if (stopped || !ok) return; - - const py = venvPython(venvDir); - log(`Starting Python mesh-tools service on port ${port}…`); - proc = spawn(py, ['main.py'], { - cwd: pythonDir, - env: { - ...process.env, - MESHTOOLS_HOST: '127.0.0.1', - MESHTOOLS_PORT: String(port), - }, - stdio: ['ignore', 'pipe', 'pipe'], - }); - proc.stdout.on('data', (d) => write(d.toString())); - proc.stderr.on('data', (d) => write(d.toString())); - proc.on('exit', (code, signal) => { - log(`Python service exited (code=${code} signal=${signal})`); - }); - } catch (err) { - log(`Python service failed: ${err.message}`); - } - } - - // Fire and forget — runs on the microtask queue, never blocks the caller. - launch(); - - return { - stop() { - stopped = true; - if (proc && !proc.killed) { - try { proc.kill(); } catch { /* ignore */ } - } - }, - }; -} - -module.exports = { startPythonService }; diff --git a/electron/setup.html b/electron/setup.html new file mode 100644 index 0000000..64a09be --- /dev/null +++ b/electron/setup.html @@ -0,0 +1,171 @@ + + + + + + + +
+

Set up 3D Gen Studio

+
First launch installs the local Python services. This runs once; later launches are instant.
+
+ +
+
+
+ + Mesh Tools + required · Auto UV / Retopo +
+
Waiting to start…
+
+
+ +
+
+ + Rigging (Auto Rig) + optional · NVIDIA GPU, large download +
+ + + +
+
+ +
+
+ +
+ Show details +
+ + +
+ + + + diff --git a/server.js b/server.js index b883bc0..b6c1336 100644 --- a/server.js +++ b/server.js @@ -5754,7 +5754,7 @@ const meshToolsUpload = multer({ limits: { fileSize: 512 * 1024 * 1024 }, }); -async function proxyMeshTool(operationPath, req, res, { baseUrlBuilder = buildMeshToolsBaseUrl } = {}) { +async function proxyMeshTool(operationPath, req, res, { baseUrlBuilder = buildMeshToolsBaseUrl, serviceLabel = 'Mesh Tools' } = {}) { const meshFile = req.file; if (!meshFile?.buffer?.length) { return res.status(400).json({ error: 'meshFile is required' }); @@ -5782,7 +5782,8 @@ async function proxyMeshTool(operationPath, req, res, { baseUrlBuilder = buildMe } catch (err) { console.error(`Mesh tool proxy (${operationPath}) could not reach the Python service:`, err); return res.status(502).json({ - error: `Could not reach the Mesh Tools (Python) service at ${baseUrl}. Is it running?`, + error: `Could not reach the ${serviceLabel} (Python) service at ${baseUrl}. ` + + `Is it running? (The rigging service can take a while to start on first launch while the model loads.)`, }); } @@ -5862,7 +5863,7 @@ app.post('/api/meshes/repair', meshToolsUpload.single('meshFile'), async (req, r // Same SSE contract as the mesh-tools routes above. app.post('/api/meshes/rig', meshToolsUpload.single('meshFile'), async (req, res) => { try { - await proxyMeshTool('/meshes/rig', req, res, { baseUrlBuilder: buildRigToolsBaseUrl }); + await proxyMeshTool('/meshes/rig', req, res, { baseUrlBuilder: buildRigToolsBaseUrl, serviceLabel: 'Rigging' }); } catch (err) { console.error('Auto Rig proxy failed:', err); if (!res.headersSent) res.status(500).json({ error: err.message || 'Auto Rig failed' }); diff --git a/src/components/SettingsModal.jsx b/src/components/SettingsModal.jsx index fb6444e..380b749 100644 --- a/src/components/SettingsModal.jsx +++ b/src/components/SettingsModal.jsx @@ -14,6 +14,84 @@ function getCustomApiTypeLabel(type) { return CUSTOM_API_TYPE_OPTIONS.find(option => option.value === type)?.label || 'Image Generation' } +// Desktop-only: install the (opt-in) rigging service after first run — for users +// who upgraded, skipped it on the setup screen, or later added a GPU. Drives the +// same uv provisioning as the first-run window via the genStudioSetup bridge and +// shows live progress. Renders nothing outside the desktop app. +function RiggingInstaller() { + const bridge = typeof window !== 'undefined' ? window.genStudioSetup : null + const isDesktop = typeof window !== 'undefined' && window.genStudioDesktop?.isDesktop && bridge + const [status, setStatus] = useState(null) + const [running, setRunning] = useState(false) + const [phase, setPhase] = useState('') + const [pct, setPct] = useState(0) + const [error, setError] = useState('') + + useEffect(() => { + if (!isDesktop) return undefined + let alive = true + bridge.status().then(s => { if (alive) setStatus(s) }).catch(() => {}) + const off = bridge.onProgress(evt => { + if (!alive) return + if (evt.kind === 'phase') { setPhase(evt.phase || ''); if (typeof evt.pct === 'number') setPct(evt.pct) } + else if (evt.kind === 'error') setError(evt.text || 'Setup failed.') + }) + return () => { alive = false; if (typeof off === 'function') off() } + }, [isDesktop, bridge]) + + if (!isDesktop) return null + + const handleInstall = async () => { + setError(''); setRunning(true); setPhase('Starting…'); setPct(0) + try { + const res = await bridge.run({ rigging: true }) + if (res?.ok) setStatus(await bridge.status()) + else setError(res?.error || 'Installation failed. See details in the setup logs.') + } catch (e) { + setError(e?.message || 'Installation failed.') + } finally { + setRunning(false) + } + } + + if (status?.rigging) { + return ( +

+ check_circle + Rigging service is installed and ready. +

+ ) + } + + return ( +
+ + {running && ( + <> +
+
+
+

{phase}

+ + )} + {error &&

{error}

} +

One-time install; downloads several GB and needs an NVIDIA GPU (≥14 GB).

+
+ ) +} + export default function SettingsModal({ onClose }) { const { settings, updateSettings, addCustomApi } = useSettings() const [localSettings, setLocalSettings] = useState(settings) @@ -539,9 +617,10 @@ export default function SettingsModal({ onClose }) {

- The SkinTokens/TokenRig rigging service (Auto Rig). Start it from - thirdparty/skintokens/run_server.bat. Needs an NVIDIA GPU (≥14 GB). + The SkinTokens/TokenRig rigging service (Auto Rig). Needs an NVIDIA GPU (≥14 GB). + Outside the desktop app, start it from thirdparty/skintokens/run_server.

+ )} diff --git a/thirdparty/skintokens/download.py b/thirdparty/skintokens/download.py index 8091bc3..b55a4ee 100644 --- a/thirdparty/skintokens/download.py +++ b/thirdparty/skintokens/download.py @@ -1,6 +1,7 @@ from huggingface_hub import hf_hub_download, snapshot_download import argparse +import os REPO_ID = "VAST-AI/SkinTokens" @@ -18,19 +19,19 @@ LLM_REPO = "Qwen/Qwen3-0.6B" LLM_LOCAL_DIR = "models/Qwen3-0.6B" -def download_model(name: str): +def download_model(name: str, out_dir: str = "."): local_path = hf_hub_download( repo_id=REPO_ID, filename=name, - local_dir=".", + local_dir=out_dir, ) print(f"[MODEL] {name} downloaded to: {local_path}") -def download_llm(): +def download_llm(out_dir: str = "."): local_path = snapshot_download( repo_id=LLM_REPO, - local_dir=LLM_LOCAL_DIR, + local_dir=os.path.join(out_dir, LLM_LOCAL_DIR), ignore_patterns=["*.bin", "*.safetensors"], ) print(f"[LLM] Config downloaded to: {local_path}") @@ -55,14 +56,17 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("--model", action="store_true", help="Download model checkpoints") parser.add_argument("--data", action="store_true", help="Download datasets") + parser.add_argument("--dir", default=".", + help="Destination directory for the downloads (default: current dir). " + "Use a writable path when the code dir is read-only.") args = parser.parse_args() if not args.model and not args.data: print("Please specify --model or --data") return if args.model: for model in MODELS: - download_model(model) - download_llm() + download_model(model, args.dir) + download_llm(args.dir) if args.data: for data in DATASETS: download_data(data) diff --git a/thirdparty/skintokens/rig.py b/thirdparty/skintokens/rig.py index ae9c764..e5d8ef0 100644 --- a/thirdparty/skintokens/rig.py +++ b/thirdparty/skintokens/rig.py @@ -79,8 +79,16 @@ class BpyServer: if self._proc is not None: return self + # Launch bpy_server.py by ABSOLUTE path with cwd pinned to this code dir. + # The main process may run with a different cwd (e.g. the packaged app + # points it at a writable model-data dir), so relying on a relative + # "bpy_server.py" / the inherited cwd would break. Its `from src...` + # imports resolve via sys.path (the script's own dir), and it only writes + # to explicit temp paths, so a read-only code dir as cwd is fine. + here = Path(__file__).resolve().parent popen_kwargs = dict( - args=[sys.executable, "bpy_server.py"], + args=[sys.executable, str(here / "bpy_server.py")], + cwd=str(here), stdout=None, stderr=None, ) diff --git a/thirdparty/skintokens/rig_server.py b/thirdparty/skintokens/rig_server.py index aa173d6..e89e48b 100644 --- a/thirdparty/skintokens/rig_server.py +++ b/thirdparty/skintokens/rig_server.py @@ -34,6 +34,7 @@ import base64 import json import os import queue +import shutil import struct import tempfile import threading @@ -41,11 +42,24 @@ from pathlib import Path os.environ.setdefault("XFORMERS_IGNORE_FLASH_VERSION_CHECK", "1") -# The bpy_server.py subprocess and the checkpoint paths are resolved relative to -# the current working directory, so anchor it to this file's location regardless -# of where the service was launched from. +# The rig resolves several resources by paths RELATIVE TO THE WORKING DIRECTORY: +# downloaded weights (experiments/…, models/…) AND static configs the model +# checkpoint references (configs/skeleton/*.yaml). By default the working dir is +# this code dir (matches the CLI). In the packaged desktop app the code dir is +# READ-ONLY, so the app sets RIGTOOLS_DATA_DIR to a writable per-user folder and +# we chdir there — but that folder must be a COMPLETE run-root. The weights are +# downloaded into it; here we also mirror the code dir's configs/ into it so the +# checkpoint's relative config lookups (e.g. configs/skeleton/vroid.yaml) resolve. +# The bpy_server.py subprocess is launched by absolute path (see BpyServer in +# rig.py) and `from src…` imports resolve via sys.path, so both are unaffected. _HERE = Path(__file__).resolve().parent -os.chdir(_HERE) +_DATA_DIR = Path(os.environ.get("RIGTOOLS_DATA_DIR") or _HERE).resolve() +_DATA_DIR.mkdir(parents=True, exist_ok=True) +if _DATA_DIR != _HERE: + _src_configs = _HERE / "configs" + if _src_configs.is_dir(): + shutil.copytree(_src_configs, _DATA_DIR / "configs", dirs_exist_ok=True) +os.chdir(_DATA_DIR) import uvicorn from fastapi import FastAPI, File, Form, HTTPException, UploadFile