Fixed Desktop App Installer with Auto Rig

This commit is contained in:
Bruno Fargnoli 2026-07-14 12:24:41 +02:00
parent 0ffe63a410
commit 1d7f3dee6d
11 changed files with 777 additions and 272 deletions

View file

@ -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:

View file

@ -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:<PORT>, 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);

View file

@ -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'),
});

304
electron/pysetup.cjs Normal file
View file

@ -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,
};

View file

@ -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 };

171
electron/setup.html Normal file
View file

@ -0,0 +1,171 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
:root {
--bg: #0d0f14; --card: #141821; --text: #e8eaf0; --muted: #8b91a3;
--accent1: #7c5cff; --accent2: #22d3ee; --ok: #4ade80; --err: #f87171;
--line: rgba(255,255,255,0.08);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; background: var(--bg); color: var(--text); overflow: hidden; }
body {
font-family: "Space Grotesk", "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
-webkit-user-select: none; user-select: none;
display: flex; flex-direction: column; padding: 26px 30px; gap: 16px;
}
h1 {
font-size: 20px; font-weight: 700;
background: linear-gradient(90deg, #fff, #c9c2ff 60%, #9be9ff);
-webkit-background-clip: text; background-clip: text; color: transparent;
}
.sub { font-size: 12.5px; color: var(--muted); margin-top: -8px; }
.services { display: flex; flex-direction: column; gap: 10px; }
.svc {
border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px;
background: var(--card); display: flex; flex-direction: column; gap: 8px;
}
.svc__head { display: flex; align-items: center; gap: 10px; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: #3a3f4b; flex: none; transition: background .3s; }
.dot.running { background: var(--accent2); box-shadow: 0 0 10px var(--accent2); animation: pulse 1.2s infinite; }
.dot.done { background: var(--ok); box-shadow: 0 0 8px var(--ok); }
.dot.error { background: var(--err); box-shadow: 0 0 8px var(--err); }
@keyframes pulse { 0%,100%{opacity:.5} 50%{opacity:1} }
.svc__name { font-size: 14px; font-weight: 600; }
.svc__tag { font-size: 11px; color: var(--muted); margin-left: auto; }
.svc__phase { font-size: 12px; color: var(--muted); min-height: 15px; }
.bar { height: 6px; border-radius: 4px; background: rgba(255,255,255,0.06); overflow: hidden; }
.bar > i { display: block; height: 100%; width: 0; border-radius: 4px;
background: linear-gradient(90deg, var(--accent1), var(--accent2)); transition: width .3s; }
label.opt { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--muted); cursor: pointer; }
label.opt input { accent-color: var(--accent1); width: 15px; height: 15px; }
.log {
flex: 1; min-height: 90px; border: 1px solid var(--line); border-radius: 10px;
background: #0a0c11; color: #9aa3b2; font-family: ui-monospace, "Cascadia Code", Consolas, monospace;
font-size: 11px; line-height: 1.45; padding: 10px 12px; overflow-y: auto; white-space: pre-wrap;
display: none;
}
.row { display: flex; align-items: center; gap: 12px; }
.spacer { flex: 1; }
button {
font-family: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
border: 1px solid var(--line); border-radius: 10px; padding: 9px 18px;
background: #1b2130; color: var(--text); transition: filter .2s, opacity .2s;
}
button.primary { border: none; background: linear-gradient(90deg, var(--accent1), var(--accent2)); color: #0b0e14; }
button:hover { filter: brightness(1.12); }
button:disabled { opacity: .45; cursor: default; filter: none; }
.err { color: var(--err); font-size: 12px; min-height: 15px; }
.link { color: var(--accent2); cursor: pointer; font-size: 11.5px; }
</style>
</head>
<body>
<div>
<h1>Set up 3D Gen Studio</h1>
<div class="sub">First launch installs the local Python services. This runs once; later launches are instant.</div>
</div>
<div class="services">
<div class="svc" id="svc-meshtools">
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Mesh Tools</span>
<span class="svc__tag">required · Auto UV / Retopo</span>
</div>
<div class="svc__phase">Waiting to start…</div>
<div class="bar"><i></i></div>
</div>
<div class="svc" id="svc-rigging">
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Rigging (Auto Rig)</span>
<span class="svc__tag">optional · NVIDIA GPU, large download</span>
</div>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB; downloads several GB)</label>
<div class="svc__phase" style="display:none"></div>
<div class="bar" style="display:none"><i></i></div>
</div>
</div>
<div class="err" id="err"></div>
<div class="log" id="log"></div>
<div class="row">
<span class="link" id="toggle-log">Show details</span>
<div class="spacer"></div>
<button id="btn-install" class="primary">Install &amp; continue</button>
<button id="btn-launch" class="primary" style="display:none">Launch 3D Gen Studio</button>
</div>
<script>
const $ = (s) => document.querySelector(s);
const rows = {
meshtools: $('#svc-meshtools'),
rigging: $('#svc-rigging'),
uv: $('#svc-meshtools'), // uv provisioning shows under the first row
};
const logEl = $('#log');
const errEl = $('#err');
function setRow(service, { state, phase, pct }) {
const row = rows[service];
if (!row) return;
const dot = row.querySelector('.dot');
const phaseEl = row.querySelector('.svc__phase');
const bar = row.querySelector('.bar > i');
if (service === 'rigging') { // reveal rigging progress once it starts
row.querySelector('.svc__phase').style.display = '';
row.querySelector('.bar').style.display = '';
}
if (state) { dot.className = 'dot ' + state; }
if (phase != null && phaseEl) phaseEl.textContent = phase;
if (pct != null && bar) bar.style.width = Math.round(pct * 100) + '%';
}
window.genStudioSetup.onProgress((evt) => {
if (evt.kind === 'log') {
logEl.textContent += evt.text;
logEl.scrollTop = logEl.scrollHeight;
return;
}
if (evt.kind === 'phase') {
setRow(evt.service, { state: 'running', phase: evt.phase, pct: evt.pct });
} else if (evt.kind === 'done') {
setRow(evt.service, { state: 'done', phase: 'Done', pct: 1 });
} else if (evt.kind === 'error') {
setRow(evt.service, { state: 'error' });
errEl.textContent = evt.text || 'Setup failed.';
}
});
$('#toggle-log').addEventListener('click', () => {
const show = logEl.style.display === 'none' || !logEl.style.display;
logEl.style.display = show ? 'block' : 'none';
$('#toggle-log').textContent = show ? 'Hide details' : 'Show details';
});
async function runInstall() {
errEl.textContent = '';
const rigging = $('#opt-rigging').checked;
$('#btn-install').disabled = true;
$('#opt-rigging').disabled = true;
setRow('meshtools', { state: 'running', phase: 'Starting…', pct: 0 });
const res = await window.genStudioSetup.run({ rigging });
if (res && res.ok) {
$('#btn-install').style.display = 'none';
$('#btn-launch').style.display = '';
} else {
errEl.textContent = (res && res.error) || 'Setup failed. See details.';
$('#btn-install').disabled = false;
$('#opt-rigging').disabled = false;
$('#btn-install').textContent = 'Retry';
}
}
$('#btn-install').addEventListener('click', runInstall);
$('#btn-launch').addEventListener('click', () => window.genStudioSetup.finish());
</script>
</body>
</html>

View file

@ -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' });

View file

@ -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 (
<p className="settings-helper-text" style={{ display: 'flex', alignItems: 'center', gap: '0.4em', color: '#4caf50' }}>
<span className="material-symbols-outlined" style={{ fontSize: '1.1em' }}>check_circle</span>
Rigging service is installed and ready.
</p>
)
}
return (
<div style={{ marginTop: '8px' }}>
<button
type="button"
onClick={handleInstall}
disabled={running}
style={{
fontFamily: 'inherit', fontSize: '13px', fontWeight: 600,
cursor: running ? 'default' : 'pointer', opacity: running ? 0.6 : 1,
border: 'none', borderRadius: '8px', padding: '9px 16px', color: '#0b0e14',
background: 'linear-gradient(90deg, #7c5cff, #22d3ee)',
}}
>
{running ? `Installing… ${Math.round(pct * 100)}%` : 'Install rigging service'}
</button>
{running && (
<>
<div style={{ height: '6px', borderRadius: '4px', background: 'rgba(255,255,255,0.08)', marginTop: '8px', overflow: 'hidden' }}>
<div style={{ height: '100%', width: `${Math.round(pct * 100)}%`, background: 'linear-gradient(90deg, #7c5cff, #22d3ee)', transition: 'width .3s' }} />
</div>
<p className="settings-helper-text" style={{ marginTop: '4px' }}>{phase}</p>
</>
)}
{error && <p className="settings-helper-text" style={{ color: '#f87171' }}>{error}</p>}
<p className="settings-helper-text">One-time install; downloads several GB and needs an NVIDIA GPU (≥14 GB).</p>
</div>
)
}
export default function SettingsModal({ onClose }) {
const { settings, updateSettings, addCustomApi } = useSettings()
const [localSettings, setLocalSettings] = useState(settings)
@ -539,9 +617,10 @@ export default function SettingsModal({ onClose }) {
</div>
<p className="settings-helper-text">
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.
</p>
<RiggingInstaller />
</div>
</section>
)}

View file

@ -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)

View file

@ -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,
)

View file

@ -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