Can start/stop the python servers from the Settings
This commit is contained in:
parent
f7b331834e
commit
22d41aca82
9 changed files with 328 additions and 42 deletions
1
body.json
Normal file
1
body.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"property_id":"8FFB834C-3B0A-4815-925E-51E97A6BD5D7","username":"bfargnoli@nikelle.co"}
|
||||
|
|
@ -49,12 +49,19 @@ const RIG_VENV = path.join(DATA_ROOT, 'rig-venv');
|
|||
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;
|
||||
|
||||
// The two Python services are started ON DEMAND (not at boot) and can be
|
||||
// stopped from Settings — stopping the rigging service fully releases its GPU
|
||||
// memory (the CUDA context an in-process unload can't free). `handles[name]`
|
||||
// holds a running service's { stop() }; `starting[name]` dedupes concurrent
|
||||
// ensure() calls. The registry is populated after the launchers are defined.
|
||||
const handles = { meshtools: null, rigging: null };
|
||||
const starting = { meshtools: null, rigging: null };
|
||||
let SERVICES = null;
|
||||
|
||||
function log(line) {
|
||||
const stamped = `[main] ${line}`;
|
||||
console.log(stamped);
|
||||
|
|
@ -114,27 +121,116 @@ 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({
|
||||
// --- On-demand Python service management ------------------------------------
|
||||
function serviceRegistry() {
|
||||
return {
|
||||
meshtools: {
|
||||
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT,
|
||||
start: () => 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({
|
||||
}),
|
||||
},
|
||||
rigging: {
|
||||
label: 'Rigging', venv: RIG_VENV, port: RIG_PORT,
|
||||
start: () => 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}`); }
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// One /health probe → boolean.
|
||||
function isHealthy(port) {
|
||||
return new Promise((resolve) => {
|
||||
const req = http.get({ host: '127.0.0.1', port, path: '/health', timeout: 2000 }, (res) => {
|
||||
res.resume();
|
||||
resolve(res.statusCode === 200);
|
||||
});
|
||||
req.on('error', () => resolve(false));
|
||||
req.on('timeout', () => { req.destroy(); resolve(false); });
|
||||
});
|
||||
}
|
||||
|
||||
// Poll /health until healthy or timeout. Rigging can take a while (heavy imports
|
||||
// + model), hence the generous default.
|
||||
function waitForHealth(port, timeoutMs = 180000, intervalMs = 600) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
return new Promise((resolve, reject) => {
|
||||
const tick = async () => {
|
||||
if (await isHealthy(port)) return resolve();
|
||||
if (Date.now() > deadline) return reject(new Error('service did not become ready in time'));
|
||||
setTimeout(tick, intervalMs);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
}
|
||||
|
||||
function stopService(name) {
|
||||
const h = handles[name];
|
||||
handles[name] = null;
|
||||
starting[name] = null;
|
||||
if (h && typeof h.stop === 'function') {
|
||||
log(`Stopping ${name} service`);
|
||||
try { h.stop(); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
// Start the service if needed and wait until it answers /health. Concurrent
|
||||
// callers share one in-flight start. Recovers a crashed service (handle present
|
||||
// but not answering) by restarting it.
|
||||
function ensureService(name) {
|
||||
const svc = SERVICES[name];
|
||||
if (!svc) return Promise.reject(new Error(`Unknown service: ${name}`));
|
||||
if (!isReady(svc.venv)) {
|
||||
return Promise.reject(new Error(`${svc.label} is not installed yet. Install it in Settings.`));
|
||||
}
|
||||
if (starting[name]) return starting[name];
|
||||
|
||||
const p = (async () => {
|
||||
if (handles[name]) {
|
||||
if (await isHealthy(svc.port)) return;
|
||||
stopService(name); // crashed → restart
|
||||
}
|
||||
log(`Starting ${name} service on demand`);
|
||||
handles[name] = svc.start();
|
||||
await waitForHealth(svc.port);
|
||||
})();
|
||||
starting[name] = p;
|
||||
p.catch(() => {}).finally(() => { if (starting[name] === p) starting[name] = null; });
|
||||
return p;
|
||||
}
|
||||
|
||||
function serviceStatus() {
|
||||
const out = {};
|
||||
for (const [name, svc] of Object.entries(SERVICES)) {
|
||||
out[name] = {
|
||||
label: svc.label,
|
||||
installed: isReady(svc.venv),
|
||||
running: !!handles[name],
|
||||
starting: !!starting[name],
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function registerServicesIpc() {
|
||||
ipcMain.handle('services:status', () => serviceStatus());
|
||||
ipcMain.handle('services:ensure', async (_e, { name } = {}) => {
|
||||
try { await ensureService(name); return { ok: true, status: serviceStatus() }; }
|
||||
catch (err) { return { ok: false, error: err.message, status: serviceStatus() }; }
|
||||
});
|
||||
ipcMain.handle('services:start', async (_e, { name } = {}) => {
|
||||
try { await ensureService(name); return { ok: true, status: serviceStatus() }; }
|
||||
catch (err) { return { ok: false, error: err.message, status: serviceStatus() }; }
|
||||
});
|
||||
ipcMain.handle('services:stop', (_e, { name } = {}) => {
|
||||
stopService(name);
|
||||
return { ok: true, status: serviceStatus() };
|
||||
});
|
||||
}
|
||||
|
||||
// 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).
|
||||
|
|
@ -173,7 +269,8 @@ function registerSetupIpc() {
|
|||
const send = (evt) => { try { event.sender.send('setup:progress', evt); } catch { /* window gone */ } };
|
||||
try {
|
||||
await doSetup(!!opts.rigging, send);
|
||||
syncServices();
|
||||
// Provisioned only — services are started on demand (or from Settings),
|
||||
// not here, so installing doesn't spin up a process the user isn't using.
|
||||
log('Setup run complete.');
|
||||
return { ok: true, status: { meshtools: isReady(PY_VENV), rigging: isReady(RIG_VENV) } };
|
||||
} catch (err) {
|
||||
|
|
@ -235,7 +332,9 @@ function loadingWindow() {
|
|||
|
||||
async function boot() {
|
||||
fs.mkdirSync(DATA_ROOT, { recursive: true });
|
||||
SERVICES = serviceRegistry();
|
||||
registerSetupIpc();
|
||||
registerServicesIpc();
|
||||
backendProc = startBackend();
|
||||
|
||||
// First run OR a broken/absent Mesh Tools venv → guided setup window with
|
||||
|
|
@ -248,7 +347,8 @@ async function boot() {
|
|||
splash = loadingWindow();
|
||||
}
|
||||
|
||||
syncServices();
|
||||
// Python services are NOT started here — they start on demand when the user
|
||||
// runs Auto UV/Retopo (Mesh Tools) or Auto Rig (Rigging), or from Settings.
|
||||
|
||||
try {
|
||||
await waitForBackend();
|
||||
|
|
@ -273,10 +373,10 @@ function shutdown() {
|
|||
if (didShutdown) return;
|
||||
didShutdown = true;
|
||||
shuttingDown = true;
|
||||
// Kill each service's whole process tree (the rigging service spawns a
|
||||
// bpy_server child that a plain kill would orphan — leaving a python.exe
|
||||
// running that holds the rig venv).
|
||||
for (const h of [pythonHandle, rigHandle]) {
|
||||
// Kill each running service's whole process tree (the rigging service spawns
|
||||
// a bpy_server child + cold worker that a plain kill would orphan).
|
||||
for (const name of Object.keys(handles)) {
|
||||
const h = handles[name];
|
||||
if (h && typeof h.stop === 'function') { try { h.stop(); } catch { /* ignore */ } }
|
||||
}
|
||||
// Backend is a lone Node process (no long-lived children) → a plain kill is fine.
|
||||
|
|
|
|||
|
|
@ -11,6 +11,19 @@ contextBridge.exposeInMainWorld('genStudioDesktop', {
|
|||
version: process.env.npm_package_version || null,
|
||||
});
|
||||
|
||||
// Start/stop the on-demand Python services (Mesh Tools, Rigging). Used by the
|
||||
// mesh-editor tool handlers (ensure the right service is up before a request)
|
||||
// and by Settings (manual Start/Stop). No-op semantics outside the desktop app,
|
||||
// where the services are launched externally.
|
||||
contextBridge.exposeInMainWorld('genStudioServices', {
|
||||
isDesktop: true,
|
||||
// Ensure a service is running + healthy before use. name: 'meshtools' | 'rigging'.
|
||||
ensure: (name) => ipcRenderer.invoke('services:ensure', { name }),
|
||||
start: (name) => ipcRenderer.invoke('services:start', { name }),
|
||||
stop: (name) => ipcRenderer.invoke('services:stop', { name }),
|
||||
status: () => ipcRenderer.invoke('services:status'),
|
||||
});
|
||||
|
||||
contextBridge.exposeInMainWorld('genStudioSetup', {
|
||||
// Kick off provisioning. opts: { rigging: boolean }. Resolves to { ok, error }.
|
||||
run: (opts) => ipcRenderer.invoke('setup:run', opts),
|
||||
|
|
|
|||
|
|
@ -14,6 +14,78 @@ function getCustomApiTypeLabel(type) {
|
|||
return CUSTOM_API_TYPE_OPTIONS.find(option => option.value === type)?.label || 'Image Generation'
|
||||
}
|
||||
|
||||
// Desktop-only: start/stop a Python service on demand and show its status. The
|
||||
// services aren't started at app launch — they spin up when a tool needs them,
|
||||
// and can be stopped here (stopping Rigging frees its GPU memory). Renders
|
||||
// nothing outside the desktop app.
|
||||
function ServiceControl({ name }) {
|
||||
const bridge = typeof window !== 'undefined' ? window.genStudioServices : null
|
||||
const isDesktop = !!bridge?.isDesktop
|
||||
const [st, setSt] = useState(null)
|
||||
const [busy, setBusy] = useState('') // '' | 'start' | 'stop'
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktop) return undefined
|
||||
let alive = true
|
||||
const refresh = async () => {
|
||||
try { const s = await bridge.status(); if (alive) setSt(s?.[name] || null) } catch { /* ignore */ }
|
||||
}
|
||||
refresh()
|
||||
const id = setInterval(refresh, 3000) // reflect starting → running transitions
|
||||
return () => { alive = false; clearInterval(id) }
|
||||
}, [isDesktop, bridge, name])
|
||||
|
||||
if (!isDesktop || !st) return null
|
||||
if (!st.installed) return null // not installed yet (Rigging install is handled above)
|
||||
|
||||
const stopping = busy === 'stop'
|
||||
const starting = !stopping && (st.starting || busy === 'start')
|
||||
const running = st.running && !starting && !stopping
|
||||
|
||||
const applyResult = (r) => {
|
||||
if (r?.status?.[name]) setSt(r.status[name])
|
||||
if (r && r.ok === false) setError(r.error || 'Operation failed.')
|
||||
}
|
||||
const doStart = async () => {
|
||||
setError(''); setBusy('start')
|
||||
try { applyResult(await bridge.start(name)) }
|
||||
catch (e) { setError(e?.message || 'Failed to start.') }
|
||||
finally { setBusy('') }
|
||||
}
|
||||
const doStop = async () => {
|
||||
setError(''); setBusy('stop')
|
||||
try { applyResult(await bridge.stop(name)) }
|
||||
catch (e) { setError(e?.message || 'Failed to stop.') }
|
||||
finally { setBusy('') }
|
||||
}
|
||||
|
||||
const dotColor = running ? '#4caf50' : (starting || stopping) ? '#e0a030' : '#6b7280'
|
||||
const btn = {
|
||||
fontFamily: 'inherit', fontSize: '12px', fontWeight: 600, cursor: busy ? 'default' : 'pointer',
|
||||
borderRadius: '8px', padding: '6px 14px', border: '1px solid rgba(255,255,255,0.12)',
|
||||
background: '#1b2130', color: '#e8eaf0', opacity: busy ? 0.6 : 1,
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6em' }}>
|
||||
<span style={{ width: 9, height: 9, borderRadius: '50%', background: dotColor, boxShadow: running ? '0 0 6px #4caf50' : 'none', flex: 'none' }} />
|
||||
<span className="settings-helper-text" style={{ margin: 0 }}>
|
||||
{stopping ? 'Stopping…' : starting ? 'Starting…' : running ? 'Running' : 'Stopped'}
|
||||
</span>
|
||||
<div style={{ flex: 1 }} />
|
||||
{running ? (
|
||||
<button type="button" style={btn} onClick={doStop} disabled={!!busy}>Stop</button>
|
||||
) : (
|
||||
<button type="button" style={btn} onClick={doStart} disabled={!!busy}>{starting ? 'Starting…' : 'Start'}</button>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="settings-helper-text" style={{ color: '#f87171' }}>{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -562,9 +634,11 @@ export default function SettingsModal({ onClose }) {
|
|||
</div>
|
||||
|
||||
<p className="settings-helper-text">
|
||||
The Python mesh-processing service (Auto UV, Auto Retopo). Start it from
|
||||
python-server/run.bat. Can run on another machine or port.
|
||||
The Python mesh-processing service (Auto UV, Auto Retopo). In the desktop
|
||||
app it starts automatically when you use those tools; you can also start or
|
||||
stop it here. Outside the desktop app, start it from python-server/run.
|
||||
</p>
|
||||
<ServiceControl name="meshtools" />
|
||||
</div>
|
||||
|
||||
<h3 className="settings-section-title font-label">Rigging (Python) Connection</h3>
|
||||
|
|
@ -618,9 +692,11 @@ export default function SettingsModal({ onClose }) {
|
|||
|
||||
<p className="settings-helper-text">
|
||||
The SkinTokens/TokenRig rigging service (Auto Rig). Needs an NVIDIA GPU (≥14 GB).
|
||||
In the desktop app it starts on demand; Stop it here to free GPU memory.
|
||||
Outside the desktop app, start it from thirdparty/skintokens/run_server.
|
||||
</p>
|
||||
<RiggingInstaller />
|
||||
<ServiceControl name="rigging" />
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -153,7 +153,7 @@ import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel'
|
|||
import AutoRigToolsPanel from '../components/meshEditor/AutoRigToolsPanel'
|
||||
import SkeletonOverlay from '../components/meshEditor/SkeletonOverlay'
|
||||
import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel'
|
||||
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService } from '../utils/meshTools'
|
||||
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService, ensureDesktopService } from '../utils/meshTools'
|
||||
|
||||
// Default option sets for the Python mesh-tools panels. These mirror the
|
||||
// defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see
|
||||
|
|
@ -3871,7 +3871,7 @@ export default function MeshEditorPage() {
|
|||
// pre-op mesh onto the modeling undo stack, so "Revert" is just an undo.
|
||||
// After applying, the texturable-mesh state is rebuilt so the new UVs (Auto
|
||||
// UV) immediately enable painting/texturing/projection.
|
||||
const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label, preserveTexture = false }) => {
|
||||
const runMeshTool = useCallback(async (service, options, { setRunning, setResult, setProgress, buildRows, label, preserveTexture = false, requiresService = null }) => {
|
||||
if (!geometry || autoUvRunning || autoRetopoRunning || optimizeRunning || repairRunning) {
|
||||
return
|
||||
}
|
||||
|
|
@ -3881,6 +3881,11 @@ export default function MeshEditorPage() {
|
|||
setError('')
|
||||
setFeedback(`${label}…`)
|
||||
try {
|
||||
// Desktop: start the required Python service on demand (no-op elsewhere).
|
||||
if (requiresService) {
|
||||
setProgress({ stage: 'service', frac: 0, message: 'Starting service…' })
|
||||
await ensureDesktopService(requiresService)
|
||||
}
|
||||
const glbBuffer = await exportGeometryToGlb(geometry)
|
||||
const meshBlob = new Blob([glbBuffer], { type: 'model/gltf-binary' })
|
||||
const { blob, stats, previewUrl } = await service(meshBlob, {
|
||||
|
|
@ -3940,6 +3945,7 @@ export default function MeshEditorPage() {
|
|||
setResult: setAutoUvResult,
|
||||
setProgress: setAutoUvProgress,
|
||||
label: 'Auto UV',
|
||||
requiresService: 'meshtools',
|
||||
buildRows: stats => {
|
||||
const t = stats?.tool || {}
|
||||
const rows = []
|
||||
|
|
@ -3958,6 +3964,7 @@ export default function MeshEditorPage() {
|
|||
setResult: setAutoRetopoResult,
|
||||
setProgress: setAutoRetopoProgress,
|
||||
label: 'Auto Retopo',
|
||||
requiresService: 'meshtools',
|
||||
buildRows: stats => {
|
||||
const m = stats?.tool?.metrics || {}
|
||||
const rows = [
|
||||
|
|
@ -4017,6 +4024,9 @@ export default function MeshEditorPage() {
|
|||
setError('')
|
||||
setFeedback('Auto Rig…')
|
||||
try {
|
||||
// Desktop: start the rigging service on demand (no-op elsewhere).
|
||||
setAutoRigProgress({ stage: 'service', frac: 0, message: 'Starting rigging service…' })
|
||||
await ensureDesktopService('rigging')
|
||||
const canExportTextured = !!(
|
||||
texturableMesh?.root
|
||||
&& texturableMesh?.textureCanvas
|
||||
|
|
@ -4140,6 +4150,7 @@ export default function MeshEditorPage() {
|
|||
setResult: setRepairResult,
|
||||
setProgress: setRepairProgress,
|
||||
label: 'Repair',
|
||||
requiresService: 'meshtools',
|
||||
buildRows: stats => {
|
||||
const t = stats?.tool || {}
|
||||
const before = t.before || {}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,19 @@
|
|||
// this helper decodes it into { blob, stats, previewUrl }.
|
||||
import { API_BASE } from '../config'
|
||||
|
||||
// In the desktop app the Python services (Mesh Tools, Rigging) are started on
|
||||
// demand. Call this before a request that needs one — it starts the service and
|
||||
// waits until it's healthy. Outside the desktop app it's a no-op (the services
|
||||
// are launched externally). name: 'meshtools' | 'rigging'.
|
||||
export async function ensureDesktopService(name) {
|
||||
const svc = typeof window !== 'undefined' ? window.genStudioServices : null
|
||||
if (!svc?.isDesktop) return
|
||||
const res = await svc.ensure(name)
|
||||
if (!res?.ok) {
|
||||
throw new Error(res?.error || `Could not start the ${name === 'rigging' ? 'Rigging' : 'Mesh Tools'} service.`)
|
||||
}
|
||||
}
|
||||
|
||||
// Decode a base64 string into a Blob of the given MIME type.
|
||||
function base64ToBlob(base64, type) {
|
||||
const binary = atob(base64)
|
||||
|
|
|
|||
15
thirdparty/skintokens/rig.py
vendored
15
thirdparty/skintokens/rig.py
vendored
|
|
@ -521,8 +521,22 @@ def main() -> None:
|
|||
raise RuntimeError(f"No valid 3D files found under: {input_path}")
|
||||
outputs = _resolve_outputs(files, input_path, output_path)
|
||||
|
||||
# When driven as a subprocess (e.g. the rig service's "cold" path), stream
|
||||
# progress as JSON lines on stdout so the parent can forward them; otherwise
|
||||
# progress is just the tqdm bar. Enabled via RIG_PROGRESS_JSON=1.
|
||||
progress = None
|
||||
if os.environ.get("RIG_PROGRESS_JSON"):
|
||||
import json as _json
|
||||
|
||||
def progress(stage, frac, message=""): # noqa: E306
|
||||
print(f"@@RP@@{_json.dumps({'stage': stage, 'frac': frac, 'message': message})}", flush=True)
|
||||
|
||||
pipeline = RigPipeline(model_ckpt=args.model_ckpt, hf_path=args.hf_path)
|
||||
if progress:
|
||||
progress("init", 0.01, "Starting Blender worker…")
|
||||
with BpyServer():
|
||||
if progress:
|
||||
progress("model", 0.03, "Loading rig model…")
|
||||
pipeline.load()
|
||||
pipeline._run(
|
||||
files,
|
||||
|
|
@ -536,6 +550,7 @@ def main() -> None:
|
|||
temperature=args.temperature,
|
||||
repetition_penalty=args.repetition_penalty,
|
||||
num_beams=args.num_beams,
|
||||
progress=progress,
|
||||
)
|
||||
|
||||
print(f"[rig] done. {len(outputs)} mesh(es) rigged.")
|
||||
|
|
|
|||
85
thirdparty/skintokens/rig_server.py
vendored
85
thirdparty/skintokens/rig_server.py
vendored
|
|
@ -36,6 +36,8 @@ import os
|
|||
import queue
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
|
@ -72,6 +74,9 @@ HOST = os.environ.get("RIGTOOLS_HOST", "0.0.0.0")
|
|||
PORT = int(os.environ.get("RIGTOOLS_PORT", "8300") or "8300")
|
||||
MODEL_CKPT = os.environ.get("RIGTOOLS_MODEL_CKPT", DEFAULT_MODEL_CKPT)
|
||||
HF_PATH = os.environ.get("RIGTOOLS_HF_PATH") or None
|
||||
# bpy port for the short-lived "cold" (keep_loaded=False) worker — distinct from
|
||||
# the default 59876 a warm in-process bpy_server uses, so the two never collide.
|
||||
COLD_BPY_PORT = os.environ.get("RIGTOOLS_COLD_BPY_PORT", "59900")
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("RIGTOOLS_MAX_UPLOAD_BYTES", str(512 * 1024 * 1024)))
|
||||
ALLOWED_ORIGINS = [
|
||||
o.strip()
|
||||
|
|
@ -117,6 +122,54 @@ def _ensure_ready(report) -> RigPipeline:
|
|||
return _pipeline
|
||||
|
||||
|
||||
def _run_cold_rig(in_path: Path, out_path: Path, opts: dict, report) -> None:
|
||||
"""Run one rig in a short-lived subprocess (rig.py CLI) that EXITS afterward.
|
||||
|
||||
Used for keep_loaded=False: exiting the process returns ALL of its GPU memory
|
||||
to the OS — including the CUDA context + cuDNN/cuBLAS/flash-attn workspaces
|
||||
that an in-process unload() cannot free. Progress is streamed back via the
|
||||
subprocess's `@@RP@@{json}` stdout lines (RIG_PROGRESS_JSON). The worker runs
|
||||
its own bpy_server on COLD_BPY_PORT so it never collides with a warm one.
|
||||
"""
|
||||
args = [
|
||||
sys.executable, str(_HERE / "rig.py"),
|
||||
"--input", str(in_path), "--output", str(out_path),
|
||||
"--rename_bones", opts["rename_bones"],
|
||||
"--top_k", str(opts["top_k"]), "--top_p", str(opts["top_p"]),
|
||||
"--temperature", str(opts["temperature"]),
|
||||
"--repetition_penalty", str(opts["repetition_penalty"]),
|
||||
"--num_beams", str(opts["num_beams"]),
|
||||
"--use_transfer" if opts["use_transfer"] else "--no_transfer",
|
||||
]
|
||||
if opts["use_postprocess"]:
|
||||
args.append("--use_postprocess")
|
||||
if opts["use_skeleton"]:
|
||||
args.append("--use_skeleton")
|
||||
|
||||
env = {**os.environ, "RIG_PROGRESS_JSON": "1", "BPY_PORT": str(COLD_BPY_PORT)}
|
||||
# cwd = the writable data dir so the worker's relative weight/config lookups
|
||||
# resolve exactly like the in-process path (same run-root).
|
||||
proc = subprocess.Popen(
|
||||
args, cwd=str(_DATA_DIR), env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, bufsize=1,
|
||||
)
|
||||
try:
|
||||
for line in proc.stdout:
|
||||
if line.startswith("@@RP@@"):
|
||||
try:
|
||||
evt = json.loads(line[len("@@RP@@"):])
|
||||
report(evt.get("stage", ""), float(evt.get("frac", 0.0)), evt.get("message", ""))
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
print(line, end="") # forward the worker's other output to the log
|
||||
finally:
|
||||
code = proc.wait()
|
||||
if code != 0:
|
||||
raise RuntimeError(f"cold rig worker exited with code {code} (see log above).")
|
||||
|
||||
|
||||
def _glb_bone_count(path: Path) -> int | None:
|
||||
"""Best-effort count of skeleton joints in a GLB (parses the JSON chunk only)."""
|
||||
try:
|
||||
|
|
@ -217,23 +270,25 @@ async def rig(
|
|||
out_path = tmpdir / "rigged.glb"
|
||||
try:
|
||||
in_path.write_bytes(data)
|
||||
# Only one rig at a time — the model + bpy_server are shared singletons.
|
||||
# Only one rig at a time (GPU-bound). The lock also guards the warm
|
||||
# singletons and keeps a cold worker from overlapping a warm rig.
|
||||
with _lock:
|
||||
pipeline = _ensure_ready(emit)
|
||||
pipeline.rig(
|
||||
in_path,
|
||||
out_path,
|
||||
progress=emit,
|
||||
**opts,
|
||||
)
|
||||
# Free the model unless the user asked to keep it warm. Done under
|
||||
# the lock so no other request sees a half-unloaded pipeline; the
|
||||
# next rig reloads it via _ensure_ready.
|
||||
if not keep_loaded:
|
||||
if keep_loaded:
|
||||
# Warm path: load once, reuse across rigs, stay resident.
|
||||
pipeline = _ensure_ready(emit)
|
||||
pipeline.rig(in_path, out_path, progress=emit, **opts)
|
||||
else:
|
||||
# Cold path: run in a subprocess that EXITS afterward so ALL
|
||||
# its GPU memory (model + CUDA context) is returned to the OS.
|
||||
# An in-process unload() can't free the CUDA context.
|
||||
global _pipeline
|
||||
emit("unload", 0.99, "Unloading model from memory…")
|
||||
pipeline.unload()
|
||||
_pipeline = None
|
||||
if _pipeline is not None:
|
||||
# Free a model left resident by an earlier keep_loaded=True
|
||||
# rig — the user asked not to keep the model in memory.
|
||||
emit("unload", 0.02, "Freeing the resident model…")
|
||||
_pipeline.unload()
|
||||
_pipeline = None
|
||||
_run_cold_rig(in_path, out_path, opts, emit)
|
||||
payload = out_path.read_bytes()
|
||||
holder["payload"] = {
|
||||
"format": "glb",
|
||||
|
|
|
|||
4
thirdparty/skintokens/src/server/spec.py
vendored
4
thirdparty/skintokens/src/server/spec.py
vendored
|
|
@ -13,7 +13,9 @@ PORT = 59875
|
|||
SERVER = f"http://localhost:{PORT}"
|
||||
TMP_CKPT_DIR = "./tmp_ckpt"
|
||||
|
||||
BPY_PORT = 59876
|
||||
# Overridable so a short-lived "cold" rig worker can run its own bpy_server on a
|
||||
# different port without colliding with a warm in-process one (see rig_server.py).
|
||||
BPY_PORT = int(os.environ.get("BPY_PORT", "59876"))
|
||||
BPY_SERVER = f"http://localhost:{BPY_PORT}"
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue