Compare commits
8 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9786988690 | |||
|
|
52862252f2 | ||
|
|
e66c0c3fcd | ||
|
|
4558969b6c | ||
|
|
49f799058a | ||
|
|
e4715aa0c1 | ||
|
|
64ed97fd3a | ||
|
|
4d7ee2eff6 |
41 changed files with 2668 additions and 89 deletions
8
.gitignore
vendored
8
.gitignore
vendored
|
|
@ -7,8 +7,12 @@ dist/
|
|||
# Electron packaged installers
|
||||
release/
|
||||
|
||||
# Local database and assets (Portable Data)
|
||||
data/
|
||||
# Local database and assets (Portable Data).
|
||||
# Leading slash ANCHORS this to the repo root. Unanchored, `data/` matches a
|
||||
# directory named "data" at ANY depth — which silently excluded the whole
|
||||
# thirdparty/skintokens/src/data package from the repo, so a fresh clone could
|
||||
# not import rig.py at all ("No module named 'src.data'").
|
||||
/data/
|
||||
|
||||
# Wiki author mode — presence of this file unlocks editing the Wiki.
|
||||
# Kept local (never synced) so the published docs are read-only for end users.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@
|
|||
|
||||
| Date | Description |
|
||||
| --- | --- |
|
||||
| **2026-07-28** | Fixed Desktop App on Linux<br>ComfyUI: Added Enums<br>Wireframe mode in Mesh Previewer |
|
||||
| **2026-07-27** | ComfyUI: Custom models folder<br>Mesh Export: Save last output folder<br>DB: Fixed assets linked to a project<br>Kanban: Can add more meshes and images from any column<br>Desktop App: Fixed Graph page slowness |
|
||||
| **2026-07-23** | Added Brainstorming Boards |
|
||||
| **2026-07-20** | MCP Server<br>Graph Page: Added Reorganize button<br>Graph Page: Save the last position and zoom level<br>Graph Page: Simplified Image Node Actions<br>Desktop App: Fixed Wiki<br>Desktop App: Auto-start python services in Settings<br>3D Mesh: Thumbnail is now generated by mesh-tools (python) |
|
||||
|
|
|
|||
|
|
@ -41,6 +41,9 @@ files:
|
|||
- package.json
|
||||
- dist/**/*
|
||||
- electron/**/*
|
||||
# App icon shown on the splash/setup windows (electron/splash.html loads it
|
||||
# from disk, so it must ship even though dist/ has its own copy).
|
||||
- public/favicon.png
|
||||
- comfyui_workflows/**/*
|
||||
- setup/**/*
|
||||
- tools/**/*
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@
|
|||
// - 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).
|
||||
// (select_flash_attn.py / download_wheel.py / download.py). Windows and Linux
|
||||
// only — flash-attn comes from a prebuilt wheel curated PER PLATFORM
|
||||
// (flash_attention_windows.txt / flash_attention_linux.txt) because building
|
||||
// it from source takes ~an hour either way. macOS has no CUDA and is refused.
|
||||
//
|
||||
// Everything is async and streams output to an onProgress callback; nothing
|
||||
// blocks the Electron main-process event loop.
|
||||
|
|
@ -21,6 +24,7 @@ const os = require('node:os');
|
|||
const { spawn, spawnSync } = require('node:child_process');
|
||||
|
||||
const IS_WIN = process.platform === 'win32';
|
||||
const IS_MAC = process.platform === 'darwin';
|
||||
const PYVER = '3.13';
|
||||
const UV_EXE = IS_WIN ? 'uv.exe' : 'uv';
|
||||
|
||||
|
|
@ -192,6 +196,11 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
|
|||
// 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 }) {
|
||||
// Rigging needs an NVIDIA GPU. Say so up front rather than failing several GB
|
||||
// into a torch install that has no macOS CUDA build to find.
|
||||
if (IS_MAC) {
|
||||
throw new Error('Rigging (Auto Rig) needs an NVIDIA GPU (CUDA), which macOS does not provide. The rest of the app works normally.');
|
||||
}
|
||||
const vp = venvPython(venvDir);
|
||||
const env = process.env;
|
||||
const modelDir = dataDir || serviceDir;
|
||||
|
|
@ -214,6 +223,9 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
|
|||
], (e) => onProgress(scaled(e, 0, 0.4)));
|
||||
|
||||
// Select the flash-attn wheel + matching torch for this machine's CUDA.
|
||||
// select_flash_attn.py picks the table for THIS platform (win_amd64 wheels from
|
||||
// flash_attention_windows.txt, linux_x86_64 from flash_attention_linux.txt) —
|
||||
// a wheel from the wrong table is rejected outright by uv at install time.
|
||||
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;
|
||||
|
|
@ -222,29 +234,39 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
|
|||
else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim();
|
||||
}
|
||||
|
||||
// Install torch (curated per-wheel command, or a sane default).
|
||||
// No match -> no rigging. Bail BEFORE the torch download: flash-attn is a hard
|
||||
// requirement (src/model/tokenrig.py imports it unguarded, so the service cannot
|
||||
// even load without it), and building it from source takes ~an hour on every
|
||||
// platform. Pulling multi-GB of torch on the way to a certain failure is waste.
|
||||
if (!wheel || !torchArgs) {
|
||||
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA (see details). Rigging is unavailable on this machine.');
|
||||
}
|
||||
|
||||
// Install torch with the curated per-wheel command, ABI-matched to the wheel.
|
||||
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 }) });
|
||||
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchArgs.split(/\s+/)], { 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 });
|
||||
// flash-attn — download the prebuilt wheel first (Hugging Face Xet URLs 403 for
|
||||
// pip and need the HF client; GitHub release assets are plain URLs), install it,
|
||||
// then PROVE it loads: a wheel built against a different torch ABI installs
|
||||
// cleanly and only dies at `import flash_attn` with `undefined symbol: _ZN3c10…`.
|
||||
// Catching that here beats surfacing it after the multi-GB checkpoint download.
|
||||
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.6 });
|
||||
{
|
||||
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.');
|
||||
if (dl.code !== 0 || !localWheel) throw new Error('flash-attn download failed. Rigging cannot start without it.');
|
||||
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.');
|
||||
}
|
||||
onProgress({ kind: 'phase', phase: 'Verifying flash-attn', pct: 0.72 });
|
||||
{
|
||||
const probe = 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)';
|
||||
const r = await runStream(vp, ['-c', probe], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
|
||||
if (r.code !== 0) throw new Error('flash-attn installed but will not import — most likely a torch ABI mismatch with the selected wheel (see details). Rigging cannot start.');
|
||||
}
|
||||
|
||||
// Model checkpoints (large; downloaded into the WRITABLE data dir).
|
||||
|
|
|
|||
|
|
@ -83,7 +83,7 @@
|
|||
<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>
|
||||
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB with a recent driver — CUDA 12.8+; downloads several GB)</label>
|
||||
<div class="svc__phase" style="display:none"></div>
|
||||
<div class="bar" style="display:none"><i></i></div>
|
||||
</div>
|
||||
|
|
@ -109,6 +109,13 @@
|
|||
const logEl = $('#log');
|
||||
const errEl = $('#err');
|
||||
|
||||
// Rigging needs CUDA, so it exists on Windows and Linux only. Hide the option on
|
||||
// macOS rather than offering an install that cannot succeed. (An unchecked box
|
||||
// reads as false in runInstall, so nothing else needs to know.)
|
||||
if ((window.genStudioDesktop && window.genStudioDesktop.platform) === 'darwin') {
|
||||
$('#svc-rigging').style.display = 'none';
|
||||
}
|
||||
|
||||
function setRow(service, { state, phase, pct }) {
|
||||
const row = rows[service];
|
||||
if (!row) return;
|
||||
|
|
|
|||
|
|
@ -52,6 +52,13 @@
|
|||
box-shadow: 0 0 22px rgba(124,92,255,0.55);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 22px;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* App icon fills the orb; if the file is missing the emoji underneath shows. */
|
||||
.orb img {
|
||||
position: absolute; inset: 0; width: 100%; height: 100%;
|
||||
object-fit: cover; border-radius: 50%;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
.title {
|
||||
font-size: 26px; font-weight: 700; letter-spacing: .3px;
|
||||
|
|
@ -68,7 +75,7 @@
|
|||
<div class="glow"></div>
|
||||
<div class="mark">
|
||||
<div class="ring"></div>
|
||||
<div class="orb">🌌</div>
|
||||
<div class="orb">🌌<img src="../public/favicon.png" alt="" onerror="this.remove()" /></div>
|
||||
</div>
|
||||
<div class="title">3D Gen Studio</div>
|
||||
<div class="status">Starting local services<span class="dots"></span></div>
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ async function resolveWorkflowJson({ workflowJson, filePath }) {
|
|||
export function registerWorkflowTools(server, { api, notifyMutation }) {
|
||||
server.registerTool('list_workflows', {
|
||||
title: 'List ComfyUI workflows',
|
||||
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue) and output nodes.',
|
||||
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue, plus enums when the parameter only accepts a fixed list of values) and output nodes.',
|
||||
annotations: { readOnlyHint: true }
|
||||
}, toolHandler(async () => {
|
||||
const workflows = await api.apiJson('GET', '/library/comfy-workflows');
|
||||
|
|
@ -58,7 +58,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
|
|||
|
||||
server.registerTool('import_workflow', {
|
||||
title: 'Import ComfyUI workflow',
|
||||
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
|
||||
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean, enums?: allowed values for a string/number parameter}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
|
||||
inputSchema: {
|
||||
name: z.string().min(1).describe('Workflow name in the library'),
|
||||
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
|
||||
|
|
@ -66,7 +66,9 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
|
|||
parameters: z.array(z.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional(),
|
||||
valueType: z.string().optional()
|
||||
valueType: z.string().optional(),
|
||||
enums: z.array(z.union([z.string(), z.number()])).optional()
|
||||
.describe('Allowed values for a string/number parameter — the app renders it as a dropdown limited to this list. Ignored for other value types.')
|
||||
})).optional().describe('Inputs to expose as parameters (ids from inspect_workflow)'),
|
||||
outputs: z.array(z.object({
|
||||
nodeId: z.string(),
|
||||
|
|
|
|||
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "app",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "app",
|
||||
"private": true,
|
||||
"version": "2.1.1",
|
||||
"version": "2.1.2",
|
||||
"type": "module",
|
||||
"main": "electron/main.cjs",
|
||||
"description": "AI-powered 3D mesh production studio — image generation, mesh generation, UV unwrapping, and texturing pipelines.",
|
||||
|
|
|
|||
51
server.js
51
server.js
|
|
@ -374,10 +374,13 @@ app.post('/api/library/comfy-workflows', async (req, res) => {
|
|||
throw new Error(`Unknown workflow parameter: ${parameter.id}`);
|
||||
}
|
||||
|
||||
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
|
||||
|
||||
return {
|
||||
...sourceParameter,
|
||||
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
|
||||
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter))
|
||||
valueType,
|
||||
enums: normalizeComfyEnums(parameter.enums, valueType)
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -455,10 +458,20 @@ app.put('/api/library/comfy-workflows/:id', async (req, res) => {
|
|||
defaultValue = cloneSerializable(sourceParameter.defaultValue);
|
||||
}
|
||||
|
||||
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
|
||||
|
||||
// Same rule as defaultValue: an incoming list wins (including an empty one,
|
||||
// which clears the enums), otherwise keep whatever was stored — callers such
|
||||
// as "Set as default" send a minimal parameter list and must not wipe it.
|
||||
const enums = Object.prototype.hasOwnProperty.call(parameter, 'enums')
|
||||
? normalizeComfyEnums(parameter.enums, valueType)
|
||||
: normalizeComfyEnums(storedParameter?.enums, valueType);
|
||||
|
||||
return {
|
||||
...sourceParameter,
|
||||
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
|
||||
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter)),
|
||||
valueType,
|
||||
enums,
|
||||
defaultValue
|
||||
};
|
||||
});
|
||||
|
|
@ -865,6 +878,33 @@ function normalizeComfyValueType(value, fallback = 'string') {
|
|||
return ['string', 'number', 'boolean', 'image', 'video', 'mesh'].includes(value) ? value : fallback;
|
||||
}
|
||||
|
||||
// Enums restrict a String / Number parameter to a fixed list of allowed values,
|
||||
// which the UI renders as a dropdown. Entries are coerced to the parameter's value
|
||||
// type and de-duplicated; a non-String/Number parameter never keeps a list.
|
||||
// Returns undefined when there is nothing to store (JSON.stringify drops the key).
|
||||
function normalizeComfyEnums(rawEnums, valueType) {
|
||||
if (!Array.isArray(rawEnums) || !['string', 'number'].includes(valueType)) return undefined;
|
||||
|
||||
const values = [];
|
||||
|
||||
for (const entry of rawEnums) {
|
||||
if (entry === null || entry === undefined || typeof entry === 'boolean' || typeof entry === 'object') continue;
|
||||
|
||||
if (valueType === 'number') {
|
||||
const numericValue = Number(entry);
|
||||
if (!Number.isFinite(numericValue) || values.includes(numericValue)) continue;
|
||||
values.push(numericValue);
|
||||
continue;
|
||||
}
|
||||
|
||||
const textValue = String(entry).trim();
|
||||
if (!textValue || values.includes(textValue)) continue;
|
||||
values.push(textValue);
|
||||
}
|
||||
|
||||
return values.length > 0 ? values : undefined;
|
||||
}
|
||||
|
||||
function getComfyNodeLabel(nodeId, node = {}) {
|
||||
return sanitizeDisplayName(node._meta?.title || node.title || node.class_type || `Node ${nodeId}`, `Node ${nodeId}`);
|
||||
}
|
||||
|
|
@ -1441,7 +1481,7 @@ async function sleep(ms) {
|
|||
|
||||
async function queueComfyPrompt(baseUrl, workflowJson, identifiers = {}) {
|
||||
const clientId = String(identifiers?.clientId || '').trim() || randomUUID();
|
||||
const promptId = String(identifiers?.promptId || '').trim() || randomUUID();
|
||||
const promptId = randomUUID(); // patched 2026-07-30: ComfyUI now enforces UUID prompt_id, client-supplied ids can be non-UUID and get rejected
|
||||
const response = await fetch(`${baseUrl}/prompt`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
|
@ -7863,10 +7903,13 @@ async function installSetupWorkflow(workflowConfig, diffusionModelFileName = '')
|
|||
if (!sourceParameter) {
|
||||
throw new Error(`Workflow "${workflowConfig.Name}": input ${parameterId} not found`);
|
||||
}
|
||||
const valueType = normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter));
|
||||
parameters.push({
|
||||
...sourceParameter,
|
||||
name: sanitizeDisplayName(inputCfg.Name || sourceParameter.name, sourceParameter.name),
|
||||
valueType: normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter))
|
||||
valueType,
|
||||
// Optional "Enums": [...] in setup.json turns the field into a dropdown.
|
||||
enums: normalizeComfyEnums(inputCfg.Enums, valueType)
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -559,7 +559,7 @@
|
|||
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
|
||||
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
|
||||
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
|
||||
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" }
|
||||
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] }
|
||||
],
|
||||
"Outputs": [
|
||||
{ "Node": "232", "Name": "Save Mesh", "Type": "Mesh" }
|
||||
|
|
@ -572,7 +572,7 @@
|
|||
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
|
||||
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
|
||||
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
|
||||
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" },
|
||||
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] },
|
||||
{ "Node": "261", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" }
|
||||
],
|
||||
"Outputs": [
|
||||
|
|
@ -585,7 +585,7 @@
|
|||
"Inputs": [
|
||||
{ "Node": "1", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
|
||||
{ "Node": "3", "Input": "target_face_num", "Name": "Target Face Number", "Type": "Number" },
|
||||
{ "Node": "3", "Input": "method", "Name": "Method (Cumesh or Meshlib)", "Type": "String" }
|
||||
{ "Node": "3", "Input": "method", "Name": "Method", "Type": "String", "Enums":["Cumesh","Meshlib"] }
|
||||
],
|
||||
"Outputs": [
|
||||
{ "Node": "5", "Name": "Save Mesh", "Type": "Mesh" }
|
||||
|
|
@ -598,7 +598,7 @@
|
|||
{ "Node": "1", "Input": "image", "Name": "Source Image", "Type": "Image" },
|
||||
{ "Node": "8", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
|
||||
{ "Node": "3", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" },
|
||||
{ "Node": "3", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
|
||||
{ "Node": "3", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
|
||||
],
|
||||
"Outputs": [
|
||||
{ "Node": "12", "Name": "Output Mesh", "Type": "Mesh" }
|
||||
|
|
@ -625,7 +625,7 @@
|
|||
{ "Node": "2", "Input": "image", "Name": "Source Image", "Type": "Image" },
|
||||
{ "Node": "28", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
|
||||
{ "Node": "4", "Input": "seed", "Name": "Seed", "Type": "Number" },
|
||||
{ "Node": "4", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
|
||||
{ "Node": "4", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
|
||||
],
|
||||
"Outputs": [
|
||||
{ "Node": "7", "Name": "Save Mesh", "Type": "Mesh" }
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
|
|||
const [showGrid, setShowGrid] = useState(true)
|
||||
const [showShadows, setShowShadows] = useState(false)
|
||||
const [showAlbedo, setShowAlbedo] = useState(false)
|
||||
const [showWireframe, setShowWireframe] = useState(false)
|
||||
const [showLightSlider, setShowLightSlider] = useState(false)
|
||||
const [lightIntensity, setLightIntensity] = useState(2.2)
|
||||
const [showExport, setShowExport] = useState(false)
|
||||
|
|
@ -46,6 +47,15 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
|
|||
>
|
||||
A
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`mesh-preview-dialog__tool ${showWireframe ? 'mesh-preview-dialog__tool--active' : ''}`}
|
||||
onClick={() => setShowWireframe(current => !current)}
|
||||
aria-pressed={showWireframe}
|
||||
title="Toggle wireframe"
|
||||
>
|
||||
W
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`mesh-preview-dialog__tool ${showGrid ? 'mesh-preview-dialog__tool--active' : ''}`}
|
||||
|
|
@ -93,6 +103,7 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
|
|||
showGrid={showGrid}
|
||||
showShadows={showShadows}
|
||||
showAlbedo={showAlbedo}
|
||||
showWireframe={showWireframe}
|
||||
lightIntensity={lightIntensity}
|
||||
fitMode="center"
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -184,6 +184,36 @@ function applyDisplayMaterial(object, showNormals, showShadows, showAlbedo) {
|
|||
})
|
||||
}
|
||||
|
||||
function applyWireframeOverlay(object, showWireframe) {
|
||||
if (!showWireframe || !object) {
|
||||
return
|
||||
}
|
||||
|
||||
const meshes = []
|
||||
object.traverse(child => {
|
||||
if (child.isMesh && child.geometry) {
|
||||
meshes.push(child)
|
||||
}
|
||||
})
|
||||
|
||||
meshes.forEach(mesh => {
|
||||
const overlay = new THREE.Mesh(
|
||||
mesh.geometry,
|
||||
new THREE.MeshBasicMaterial({
|
||||
color: '#ffffff',
|
||||
wireframe: true,
|
||||
transparent: true,
|
||||
opacity: 0.36,
|
||||
depthWrite: false
|
||||
})
|
||||
)
|
||||
overlay.castShadow = false
|
||||
overlay.receiveShadow = false
|
||||
overlay.userData.isWireframeOverlay = true
|
||||
mesh.add(overlay)
|
||||
})
|
||||
}
|
||||
|
||||
async function loadModelFromUrl(url, fitMode = 'ground') {
|
||||
const extension = getExtensionFromUrl(url)
|
||||
|
||||
|
|
@ -249,6 +279,7 @@ export default function Viewer({
|
|||
showGrid = true,
|
||||
showShadows = true,
|
||||
showAlbedo = false,
|
||||
showWireframe = false,
|
||||
lightIntensity = 2.2,
|
||||
fitMode = 'ground'
|
||||
}) {
|
||||
|
|
@ -294,8 +325,9 @@ export default function Viewer({
|
|||
|
||||
const modelClone = modelState.object.clone(true)
|
||||
applyDisplayMaterial(modelClone, showNormals, showShadows, showAlbedo)
|
||||
applyWireframeOverlay(modelClone, showWireframe)
|
||||
return modelClone
|
||||
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo])
|
||||
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo, showWireframe])
|
||||
|
||||
const cameraTarget = modelState?.modelUrl === modelUrl ? modelState.target : new THREE.Vector3(0, 0.75, 0)
|
||||
const cameraPosition = modelState?.modelUrl === modelUrl ? modelState.cameraPosition : new THREE.Vector3(3, 3, 5)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
createComfyExecutionId
|
||||
} from '../../utils/graphHelpers'
|
||||
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import AssetSelectorModal from '../AssetSelectorModal'
|
||||
|
||||
// An image/file input value chosen from the Assets library (vs an uploaded File).
|
||||
|
|
@ -279,6 +280,24 @@ export default function BoardAiPanel({ projectId, projectName, boardId, onImageG
|
|||
)
|
||||
}
|
||||
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, value)
|
||||
if (enumOptions) {
|
||||
return (
|
||||
<div className="board-ai-panel__field" key={parameter.id}>
|
||||
<span className="board-ai-panel__label">{label}</span>
|
||||
<select
|
||||
className="board-ai-panel__select"
|
||||
value={value == null ? '' : String(value)}
|
||||
onChange={(e) => setInputValue(parameter.id, resolveWorkflowEnumValue(parameter, e.target.value))}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (valueType === 'number') {
|
||||
return (
|
||||
<div className="board-ai-panel__field" key={parameter.id}>
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
createComfyExecutionId
|
||||
} from '../../utils/graphHelpers'
|
||||
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import { buildAssetUrl } from '../../utils/meshTexturing'
|
||||
import './ComfyTextGenModal.css'
|
||||
|
||||
|
|
@ -324,6 +325,24 @@ export default function ComfyTextGenModal({ open, onClose, onResult }) {
|
|||
)
|
||||
}
|
||||
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, value)
|
||||
if (enumOptions) {
|
||||
return (
|
||||
<div key={parameter.id} className="comfy-tg-field">
|
||||
<label className="comfy-tg-label">{parameter.name} • {valueType.toUpperCase()}</label>
|
||||
<select
|
||||
className="comfy-tg-input"
|
||||
value={value == null ? '' : String(value)}
|
||||
onChange={event => handleInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (valueType === 'number') {
|
||||
return (
|
||||
<div key={parameter.id} className="comfy-tg-field">
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ import {
|
|||
resolveImageSourceOption,
|
||||
resolveSelectedInputSource
|
||||
} from '../../utils/graphHelpers'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import ComfyTextButton from '../comfy/ComfyTextButton'
|
||||
import LastActionInfo from './LastActionInfo'
|
||||
|
||||
|
|
@ -178,6 +179,21 @@ const GraphAssetNode = memo(function GraphAssetNode({ data }) {
|
|||
)
|
||||
}
|
||||
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
|
||||
if (enumOptions) {
|
||||
return (
|
||||
<select
|
||||
className="params-card__select nodrag"
|
||||
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
|
||||
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
if (valueType === 'string' || parameter.type === 'json') {
|
||||
return (
|
||||
<div className="comfy-textfield-wrap nodrag">
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
isFileWorkflowValueType,
|
||||
resolveSelectedInputSource
|
||||
} from '../../utils/graphHelpers'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import ComfyTextButton from '../comfy/ComfyTextButton'
|
||||
import LastActionInfo from './LastActionInfo'
|
||||
|
||||
|
|
@ -77,6 +78,21 @@ const GraphValueNode = memo(function GraphValueNode({ data }) {
|
|||
)
|
||||
}
|
||||
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
|
||||
if (enumOptions) {
|
||||
return (
|
||||
<select
|
||||
className="params-card__select nodrag"
|
||||
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
|
||||
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
if (valueType === 'string' || parameter.type === 'json') {
|
||||
return (
|
||||
<div className="comfy-textfield-wrap nodrag">
|
||||
|
|
|
|||
|
|
@ -1,10 +1,29 @@
|
|||
// Renders a single non-image ComfyUI workflow parameter (boolean checkbox or
|
||||
// text/number input). Shared by the AI control panels. Presentational.
|
||||
import { getValueType } from '../../../utils/imageEditorCanvas'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../../utils/workflowEnums'
|
||||
import ComfyTextButton from '../../comfy/ComfyTextButton'
|
||||
|
||||
export default function WorkflowParameterField({ parameter, value, onChange }) {
|
||||
const valueType = getValueType(parameter)
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, value)
|
||||
|
||||
if (enumOptions) {
|
||||
return (
|
||||
<label className="image-editor-label">
|
||||
{parameter.name}
|
||||
<select
|
||||
className="image-editor-input"
|
||||
value={value == null ? '' : String(value)}
|
||||
onChange={event => onChange(parameter.id, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
if (valueType === 'boolean') {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
isTencentMeshGenerationApi,
|
||||
isTripoMeshGenerationApi
|
||||
} from '../../utils/kanbanHelpers'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
|
||||
// A single Kanban board card (image / image-edit / mesh-gen / mesh-edit / texturing).
|
||||
// Presentational: all board state, derived selectors, and handlers are passed in
|
||||
|
|
@ -603,6 +604,12 @@ export default function KanbanImageCard({
|
|||
}
|
||||
|
||||
const sourceOptions = getAttributeOptionsForCard(card.id, valueType === 'number' ? 'Number' : 'Text')
|
||||
// An attribute-bound value is shown read-only, so the dropdown
|
||||
// reflects whichever value is actually in play.
|
||||
const enumSelectValue = binding.source === 'custom'
|
||||
? (binding.customValue == null ? '' : String(binding.customValue))
|
||||
: String(resolvedValue ?? '')
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, enumSelectValue)
|
||||
|
||||
return (
|
||||
<div key={parameter.id} className="params-card__field">
|
||||
|
|
@ -616,7 +623,18 @@ export default function KanbanImageCard({
|
|||
<option key={option.id} value={option.id}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
{valueType === 'string' ? (
|
||||
{enumOptions ? (
|
||||
<select
|
||||
className="image-card__attribute-select"
|
||||
value={enumSelectValue}
|
||||
onChange={event => handleImageEditParameterValueChange(card, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
disabled={binding.source !== 'custom'}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : valueType === 'string' ? (
|
||||
<div className="comfy-textfield-wrap">
|
||||
<textarea
|
||||
className="gen-prompt-input image-card__param-textarea"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { getWorkflowValueType } from '../../utils/meshTexturing'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import ComfyTextButton from '../comfy/ComfyTextButton'
|
||||
|
||||
// Projection-mode left panel (projection setup, AI workflow + image-input
|
||||
|
|
@ -189,11 +190,26 @@ export default function ProjectionToolsPanel({
|
|||
{projectionWorkflowParameters.map(parameter => {
|
||||
const valueType = getWorkflowValueType(parameter)
|
||||
const currentValue = projectionWorkflowInputs?.[parameter.id]
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
|
||||
|
||||
return (
|
||||
<label key={parameter.id} className="mesh-editor-workflow-field">
|
||||
<span>{parameter.name}</span>
|
||||
{valueType === 'boolean' ? (
|
||||
{enumOptions ? (
|
||||
<select
|
||||
className="mesh-editor-panel__input"
|
||||
value={currentValue == null ? '' : String(currentValue)}
|
||||
onChange={event => setProjectionWorkflowInputs(current => ({
|
||||
...current,
|
||||
[parameter.id]: resolveWorkflowEnumValue(parameter, event.target.value)
|
||||
}))}
|
||||
disabled={!!texturingUnavailableReason || projecting || projectionRebuilding}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : valueType === 'boolean' ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { getWorkflowValueType } from '../../utils/meshTexturing'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
|
||||
import ComfyTextButton from '../comfy/ComfyTextButton'
|
||||
|
||||
// Texturing-mode left panel (brush/crop/feather, AI workflow + image-input
|
||||
|
|
@ -162,11 +163,23 @@ export default function TexturingToolsPanel({
|
|||
{textureWorkflowParameters.map(parameter => {
|
||||
const valueType = getWorkflowValueType(parameter)
|
||||
const currentValue = textureWorkflowInputs?.[parameter.id]
|
||||
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
|
||||
|
||||
return (
|
||||
<label key={parameter.id} className="mesh-editor-workflow-field">
|
||||
<span>{parameter.name}</span>
|
||||
{valueType === 'boolean' ? (
|
||||
{enumOptions ? (
|
||||
<select
|
||||
className="mesh-editor-panel__input"
|
||||
value={currentValue == null ? '' : String(currentValue)}
|
||||
onChange={event => handleTextureWorkflowInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
|
||||
disabled={!!texturingUnavailableReason || !!pendingPatch}
|
||||
>
|
||||
{enumOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : valueType === 'boolean' ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}
|
||||
|
|
|
|||
|
|
@ -519,6 +519,23 @@
|
|||
color: var(--on-surface);
|
||||
}
|
||||
|
||||
.library-textarea {
|
||||
resize: vertical;
|
||||
min-height: 4.5rem;
|
||||
font-family: inherit;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* Enum editor: label + textarea + hint sit tighter than a top-level form field. */
|
||||
.library-selected-item .library-field {
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.library-hint {
|
||||
font-size: 0.72rem;
|
||||
color: var(--on-surface-variant);
|
||||
}
|
||||
|
||||
.library-config-fields,
|
||||
.library-config-actions,
|
||||
.library-workflow-card__actions,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,11 @@ import { useProjects } from '../context/ProjectContext'
|
|||
import { createMeshThumbnailFile, isMeshFile } from '../utils/meshThumbnail'
|
||||
import { parseAbrFile } from '../utils/brushAbr'
|
||||
import { downloadShareableWorkflow, isShareableWorkflow } from '../utils/workflowShare'
|
||||
import {
|
||||
formatWorkflowEnumsInput,
|
||||
isEnumWorkflowValueType,
|
||||
parseWorkflowEnumsInput
|
||||
} from '../utils/workflowEnums'
|
||||
import './AssetsPage.css'
|
||||
|
||||
const ASSETS_PER_PAGE = 20
|
||||
|
|
@ -74,7 +79,8 @@ function createSelectionMap(items, getLabel, isOutput = false, selected = false)
|
|||
{
|
||||
selected,
|
||||
name: getLabel(item),
|
||||
valueType: getDefaultValueType(item, isOutput)
|
||||
valueType: getDefaultValueType(item, isOutput),
|
||||
enumsText: formatWorkflowEnumsInput(item?.enums)
|
||||
}
|
||||
])
|
||||
)
|
||||
|
|
@ -92,7 +98,8 @@ function hydrateWorkflowSelection(workflow) {
|
|||
{
|
||||
selected: Boolean(selectedParameter),
|
||||
name: selectedParameter?.name || input.name,
|
||||
valueType: getDefaultValueType(selectedParameter || input)
|
||||
valueType: getDefaultValueType(selectedParameter || input),
|
||||
enumsText: formatWorkflowEnumsInput(selectedParameter?.enums)
|
||||
}
|
||||
]
|
||||
})
|
||||
|
|
@ -127,7 +134,8 @@ function selectWorkflowItem(setter, key, name, valueType) {
|
|||
[key]: {
|
||||
selected: true,
|
||||
name: prev[key]?.name || name,
|
||||
valueType: prev[key]?.valueType || valueType
|
||||
valueType: prev[key]?.valueType || valueType,
|
||||
enumsText: prev[key]?.enumsText || ''
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
|
@ -1104,11 +1112,17 @@ export default function AssetsPage() {
|
|||
const buildWorkflowPayload = () => {
|
||||
const parameters = (inspectedWorkflow?.inputs || [])
|
||||
.filter(input => selectedInputs[input.id]?.selected)
|
||||
.map(input => ({
|
||||
id: input.id,
|
||||
name: selectedInputs[input.id]?.name || input.name,
|
||||
valueType: selectedInputs[input.id]?.valueType || getDefaultValueType(input)
|
||||
}))
|
||||
.map(input => {
|
||||
const valueType = selectedInputs[input.id]?.valueType || getDefaultValueType(input)
|
||||
|
||||
return {
|
||||
id: input.id,
|
||||
name: selectedInputs[input.id]?.name || input.name,
|
||||
valueType,
|
||||
// Always sent so emptying the field clears a previously saved list.
|
||||
enums: parseWorkflowEnumsInput(selectedInputs[input.id]?.enumsText, valueType)
|
||||
}
|
||||
})
|
||||
|
||||
const outputs = (inspectedWorkflow?.outputs || [])
|
||||
.filter(output => selectedOutputs[output.nodeId]?.selected)
|
||||
|
|
@ -1671,6 +1685,30 @@ export default function AssetsPage() {
|
|||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* JSON inputs resolve to the String value type but are parsed as
|
||||
JSON at run time, so they never get an allowed-value list. */}
|
||||
{input.type !== 'json' && isEnumWorkflowValueType(selectedInputs[input.id]?.valueType || getDefaultValueType(input)) && (
|
||||
<div className="library-field">
|
||||
<label className="library-label">Allowed Values (optional)</label>
|
||||
<textarea
|
||||
className="library-input library-textarea"
|
||||
rows={3}
|
||||
value={selectedInputs[input.id]?.enumsText || ''}
|
||||
onChange={event => setSelectedInputs(prev => ({
|
||||
...prev,
|
||||
[input.id]: {
|
||||
...prev[input.id],
|
||||
enumsText: event.target.value
|
||||
}
|
||||
}))}
|
||||
placeholder={'1024\n1536'}
|
||||
/>
|
||||
<span className="library-hint">
|
||||
One value per line. Leave empty for a free-form field; two or more values turn it into a dropdown everywhere the workflow is used.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ import {
|
|||
normalizeCustomApiType
|
||||
} from '../utils/kanbanHelpers'
|
||||
import { saveWorkflowDefaults } from '../utils/workflowDefaults'
|
||||
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../utils/workflowEnums'
|
||||
|
||||
// Database id of the "Mesh Gen" kanban column (see IMAGE_CARD_COLUMNS).
|
||||
const MESH_GEN_COLUMN_ID = 3
|
||||
|
|
@ -3218,6 +3219,16 @@ export default function KanbanPage() {
|
|||
</div>
|
||||
<span>{parameter.label || 'Toggle value'}</span>
|
||||
</label>
|
||||
) : getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]) ? (
|
||||
<select
|
||||
className="params-card__select"
|
||||
value={imageDraft.inputs?.[parameter.id] == null ? '' : String(imageDraft.inputs[parameter.id])}
|
||||
onChange={e => handleComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
|
||||
>
|
||||
{getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]).map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : getWorkflowParameterValueType(parameter) === 'string' ? (
|
||||
<div className="comfy-textfield-wrap">
|
||||
<textarea
|
||||
|
|
@ -3452,6 +3463,16 @@ export default function KanbanPage() {
|
|||
</div>
|
||||
<span>{parameter.label || 'Toggle value'}</span>
|
||||
</label>
|
||||
) : getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]) ? (
|
||||
<select
|
||||
className="params-card__select"
|
||||
value={meshDraft.inputs?.[parameter.id] == null ? '' : String(meshDraft.inputs[parameter.id])}
|
||||
onChange={e => handleMeshComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
|
||||
>
|
||||
{getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]).map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : getWorkflowParameterValueType(parameter) === 'string' ? (
|
||||
<textarea
|
||||
className="gen-prompt-input image-card__param-textarea"
|
||||
|
|
|
|||
|
|
@ -23,6 +23,15 @@ const PRESETS = [
|
|||
]
|
||||
|
||||
const CHANGE_LOG_ENTRIES = [
|
||||
{
|
||||
version: 'v2.1.2',
|
||||
date: '2026-07-28',
|
||||
items: [
|
||||
'Fixed Desktop App on Linux',
|
||||
'ComfyUI: Added Enums',
|
||||
'Wireframe mode in Mesh Previewer'
|
||||
],
|
||||
},
|
||||
{
|
||||
version: 'v2.1.1',
|
||||
date: '2026-07-27',
|
||||
|
|
|
|||
|
|
@ -21,7 +21,11 @@ export function buildWorkflowDefaultsPayload(workflow, values = {}) {
|
|||
const base = {
|
||||
id: parameter.id,
|
||||
name: parameter.name,
|
||||
valueType
|
||||
valueType,
|
||||
// Echo the allowed-value list back so saving defaults never drops it.
|
||||
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
|
||||
? { enums: [...parameter.enums] }
|
||||
: {})
|
||||
}
|
||||
|
||||
// Only String / Number / Boolean fields are saved as defaults. File-type params
|
||||
|
|
|
|||
75
src/utils/workflowEnums.js
Normal file
75
src/utils/workflowEnums.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// Enum support for ComfyUI workflow parameters.
|
||||
//
|
||||
// A String or Number parameter can carry an `enums` array that restricts it to a
|
||||
// fixed list of allowed values. Every AI panel renders such a parameter as a
|
||||
// dropdown instead of a free-form field, so the value can only ever be one the
|
||||
// workflow actually accepts.
|
||||
//
|
||||
// Values keep their real type in storage (numbers stay numbers) while <select>
|
||||
// values are always strings — hence resolveWorkflowEnumValue, which maps a picked
|
||||
// option back to its typed entry.
|
||||
|
||||
const ENUM_VALUE_TYPES = ['string', 'number']
|
||||
|
||||
// The allowed values of a parameter, or null when it isn't an enum parameter.
|
||||
export function getWorkflowParameterEnums(parameter) {
|
||||
if (!Array.isArray(parameter?.enums)) return null
|
||||
|
||||
const values = parameter.enums.filter(value => typeof value === 'string' || typeof value === 'number')
|
||||
return values.length > 0 ? values : null
|
||||
}
|
||||
|
||||
export function isEnumWorkflowValueType(valueType) {
|
||||
return ENUM_VALUE_TYPES.includes(valueType)
|
||||
}
|
||||
|
||||
// Options for a <select>, or null when the parameter has no enums. A current
|
||||
// value outside the list is kept as an extra option so an older saved value is
|
||||
// never silently rewritten.
|
||||
export function getWorkflowEnumOptions(parameter, currentValue) {
|
||||
const enums = getWorkflowParameterEnums(parameter)
|
||||
if (!enums) return null
|
||||
|
||||
const options = enums.map(value => ({ value: String(value), label: String(value) }))
|
||||
|
||||
if (currentValue !== undefined && currentValue !== null && currentValue !== ''
|
||||
&& !options.some(option => option.value === String(currentValue))) {
|
||||
options.unshift({ value: String(currentValue), label: `${currentValue} (custom)` })
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// Map a <select> value (always a string) back to the typed enum entry.
|
||||
export function resolveWorkflowEnumValue(parameter, rawValue) {
|
||||
const enums = getWorkflowParameterEnums(parameter)
|
||||
const match = enums?.find(value => String(value) === String(rawValue))
|
||||
return match === undefined ? rawValue : match
|
||||
}
|
||||
|
||||
// Parse the workflow editor's enum field (one value per line) into stored values.
|
||||
export function parseWorkflowEnumsInput(text, valueType) {
|
||||
if (!isEnumWorkflowValueType(valueType)) return []
|
||||
|
||||
const values = []
|
||||
for (const line of String(text || '').split('\n')) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) continue
|
||||
|
||||
if (valueType === 'number') {
|
||||
const numeric = Number(trimmed)
|
||||
if (!Number.isFinite(numeric) || values.includes(numeric)) continue
|
||||
values.push(numeric)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!values.includes(trimmed)) values.push(trimmed)
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
// Render stored enums back into the editor field (one value per line).
|
||||
export function formatWorkflowEnumsInput(enums) {
|
||||
return Array.isArray(enums) ? enums.join('\n') : ''
|
||||
}
|
||||
|
|
@ -26,7 +26,12 @@ export function buildShareableWorkflow(workflow) {
|
|||
parameters: (workflow?.parameters || []).map(parameter => ({
|
||||
id: parameter.id,
|
||||
name: parameter.name,
|
||||
valueType: parameter.valueType
|
||||
valueType: parameter.valueType,
|
||||
// Only String/Number parameters carry an allowed-value list; omit the key
|
||||
// entirely for the rest so bundles stay as small as they were.
|
||||
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
|
||||
? { enums: [...parameter.enums] }
|
||||
: {})
|
||||
})),
|
||||
outputs: (workflow?.outputs || []).map(output => ({
|
||||
nodeId: output.nodeId,
|
||||
|
|
|
|||
20
thirdparty/skintokens/download_wheel.py
vendored
20
thirdparty/skintokens/download_wheel.py
vendored
|
|
@ -14,7 +14,9 @@ exits non-zero on failure so the caller can skip the install.
|
|||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
|
|
@ -40,13 +42,21 @@ def download(url: str) -> str:
|
|||
return hf_hub_download(repo_id=repo_id, filename=filename)
|
||||
|
||||
# Plain HTTP(S) download (e.g. GitHub release assets).
|
||||
fd, path = tempfile.mkstemp(suffix=".whl", prefix="flash_attn_")
|
||||
import os
|
||||
|
||||
os.close(fd)
|
||||
#
|
||||
# The original basename MUST be preserved. pip/uv read the distribution name,
|
||||
# version and compatibility tags out of the wheel FILENAME, so a mkstemp name
|
||||
# like "flash_attn_t5eu90p9.whl" is rejected before the file is even opened:
|
||||
# error: The wheel filename "flash_attn_t5eu90p9.whl" is invalid: Must have a version
|
||||
# So download into a temp DIRECTORY and keep the name the server gave us.
|
||||
name = os.path.basename(urllib.parse.unquote(urllib.parse.urlparse(url).path))
|
||||
if not name.endswith(".whl"):
|
||||
raise ValueError(f"URL does not name a .whl file: {url}")
|
||||
path = os.path.join(tempfile.mkdtemp(prefix="flash_attn_"), name)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
# copyfileobj streams: these wheels are a few hundred MB and don't need to be
|
||||
# held in memory in one piece.
|
||||
with urllib.request.urlopen(req) as resp, open(path, "wb") as out:
|
||||
out.write(resp.read())
|
||||
shutil.copyfileobj(resp, out)
|
||||
return path
|
||||
|
||||
|
||||
|
|
|
|||
3
thirdparty/skintokens/flash_attention_linux.txt
vendored
Normal file
3
thirdparty/skintokens/flash_attention_linux.txt
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
Torch;Cuda;Link;PyTorchLink
|
||||
2.13.0;12.6.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu126torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision --index-url https://download.pytorch.org/whl/cu126
|
||||
2.13.0;13.0.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision
|
||||
76
thirdparty/skintokens/run_server.sh
vendored
76
thirdparty/skintokens/run_server.sh
vendored
|
|
@ -6,12 +6,18 @@
|
|||
#
|
||||
# On first run it uses `uv` to provision a pinned standalone Python (see
|
||||
# .python-version -> 3.13) and installs the SkinTokens requirements, torch, a
|
||||
# flash-attn wheel, and the model checkpoints. Unlike Windows (which needs the
|
||||
# curated flash_attention_windows.txt wheels), Linux gets flash-attn straight
|
||||
# from pip, which resolves a prebuilt wheel for the installed torch/CUDA/Python
|
||||
# (or builds it — needs the CUDA toolkit + ninja). uv is auto-installed if absent.
|
||||
# flash-attn wheel, and the model checkpoints. Like Windows, Linux installs
|
||||
# flash-attn from a curated prebuilt wheel (flash_attention_linux.txt) rather than
|
||||
# `pip install flash-attn`, which compiles from source and takes about an hour.
|
||||
# uv is auto-installed if absent.
|
||||
#
|
||||
# Env overrides: RIGTOOLS_PORT/HOST, RIGTOOLS_SKIP_FLASH=1, RIGTOOLS_SKIP_MODEL=1.
|
||||
# Env overrides:
|
||||
# RIGTOOLS_PORT / RIGTOOLS_HOST bind address
|
||||
# RIGTOOLS_CUDA=12.6 force the CUDA build to target (skip nvidia-smi)
|
||||
# RIGTOOLS_SKIP_FLASH=1 don't install flash-attn
|
||||
# RIGTOOLS_BUILD_FLASH=1 if no curated wheel matches, build from source
|
||||
# instead of giving up (~1 hour, needs nvcc+ninja)
|
||||
# RIGTOOLS_SKIP_MODEL=1 don't download the model checkpoints
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
PYVER=3.13
|
||||
|
|
@ -42,22 +48,70 @@ if [ ! -x ".venv/bin/python" ]; then
|
|||
# shellcheck disable=SC1091
|
||||
source .venv/bin/activate
|
||||
|
||||
# --- Pick a prebuilt flash-attn wheel + its matching torch install ----------
|
||||
# select_flash_attn.py picks the table for this platform (flash_attention_linux.txt
|
||||
# here) and, on a CUDA match, prints:
|
||||
# WHEEL=<flash-attn wheel url>
|
||||
# TORCHARGS=<torch~=.. torchvision .. [--index-url ..]>
|
||||
# Prints nothing on no match. Python is pinned to 3.13 by uv, so the wheels (all
|
||||
# cp313) always fit; only CUDA has to be matched.
|
||||
echo
|
||||
echo "Detecting CUDA to select a flash-attn wheel..."
|
||||
WHEEL=""
|
||||
TORCHARGS=""
|
||||
while IFS= read -r line; do
|
||||
case "$line" in
|
||||
WHEEL=*) WHEEL="${line#WHEEL=}" ;;
|
||||
TORCHARGS=*) TORCHARGS="${line#TORCHARGS=}" ;;
|
||||
esac
|
||||
done < <(python select_flash_attn.py)
|
||||
|
||||
echo
|
||||
echo "Installing SkinTokens requirements..."
|
||||
"$UV" pip install -r requirements.txt
|
||||
|
||||
# torch AFTER requirements so it overrides the torch `lightning` pulls in. On
|
||||
# Linux the default PyPI torch wheels bundle CUDA, so no custom index is needed.
|
||||
# torch AFTER requirements so it overrides the torch `lightning` pulls in. The
|
||||
# curated TORCHARGS pins torch to the version the flash-attn wheel was built
|
||||
# against, so the ABI matches. On Linux the PyPI torch wheels bundle CUDA, so a
|
||||
# row may legitimately carry no --index-url.
|
||||
echo
|
||||
echo "Installing torch (CUDA build)..."
|
||||
"$UV" pip install torch torchvision torchaudio
|
||||
if [ -n "$TORCHARGS" ]; then
|
||||
echo "Installing torch: $TORCHARGS"
|
||||
# shellcheck disable=SC2086 -- curated arg list; word-splitting is intended
|
||||
"$UV" pip install $TORCHARGS
|
||||
else
|
||||
echo "No matching prebuilt flash-attn wheel -- installing default torch (CUDA build from PyPI)..."
|
||||
"$UV" pip install torch torchvision
|
||||
fi
|
||||
|
||||
# --- flash-attn -------------------------------------------------------------
|
||||
echo
|
||||
if [ -n "${RIGTOOLS_SKIP_FLASH:-}" ]; then
|
||||
echo "RIGTOOLS_SKIP_FLASH set -- skipping flash-attn."
|
||||
elif [ -n "$WHEEL" ]; then
|
||||
echo "Downloading + installing prebuilt flash-attn wheel..."
|
||||
# Fetch to a local path first: `pip install <hf-url>` 403s on Hugging Face
|
||||
# Xet-backed files. GitHub release assets go over plain urllib.
|
||||
if FA_WHEEL="$(python download_wheel.py "$WHEEL" | tail -n 1)" && [ -n "$FA_WHEEL" ]; then
|
||||
"$UV" pip install "$FA_WHEEL" || echo "[warn] flash-attn install failed; continuing without it."
|
||||
else
|
||||
echo "[warn] flash-attn download failed; continuing without it."
|
||||
fi
|
||||
elif [ -n "${RIGTOOLS_BUILD_FLASH:-}" ]; then
|
||||
echo "No curated wheel matched -- building flash-attn from source (this takes ~an hour)..."
|
||||
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn build failed; continuing without it."
|
||||
else
|
||||
echo "Installing flash-attn (prebuilt wheel if available, else builds from source)..."
|
||||
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn install failed; continuing without it."
|
||||
echo "[warn] No prebuilt flash-attn wheel matched this CUDA; flash-attn was NOT installed."
|
||||
echo " rig_server.py cannot import without it. Either add a row for your"
|
||||
echo " CUDA/torch to flash_attention_linux.txt, or build from source with:"
|
||||
echo " RIGTOOLS_BUILD_FLASH=1 ./run_server.sh # ~1 hour, needs nvcc + ninja"
|
||||
fi
|
||||
|
||||
# A wheel built against a different torch ABI installs cleanly and only fails at
|
||||
# import ("undefined symbol: _ZN3c10..."), so check now rather than mid-rig.
|
||||
if [ -z "${RIGTOOLS_SKIP_FLASH:-}" ]; then
|
||||
python -c 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)' \
|
||||
|| echo "[warn] flash-attn does not import -- likely a torch ABI mismatch with the selected wheel."
|
||||
fi
|
||||
|
||||
echo
|
||||
|
|
|
|||
86
thirdparty/skintokens/select_flash_attn.py
vendored
86
thirdparty/skintokens/select_flash_attn.py
vendored
|
|
@ -1,50 +1,63 @@
|
|||
"""Pick the prebuilt flash-attn wheel + matching torch install for this machine.
|
||||
|
||||
Building flash-attn from source on Windows takes ages, so we prefer a
|
||||
precompiled wheel. ``flash_attention_windows.txt`` lists, per row:
|
||||
Building flash-attn from source takes ~an hour on BOTH Windows and Linux, so we
|
||||
always prefer a precompiled wheel. There is one curated table per platform —
|
||||
``flash_attention_windows.txt`` (win_amd64 wheels) and
|
||||
``flash_attention_linux.txt`` (linux_x86_64 wheels) — and this script picks the
|
||||
table matching the host. Each lists, per row:
|
||||
|
||||
Torch;Cuda;Link;PyTorchLink
|
||||
│ │ │ └ the exact `pip install torch... --index-url ...` command
|
||||
│ │ │ └ the exact `pip install torch... [--index-url ...]` command
|
||||
│ │ │ that pairs with this flash-attn wheel (ABI-matched)
|
||||
│ │ └ flash-attn wheel URL
|
||||
│ └ CUDA build the wheel targets (match key against the driver)
|
||||
│ └ CUDA build the wheel targets (match key against the driver;
|
||||
│ "13.0" and "13.0.0" both work — only major.minor is compared)
|
||||
└ torch version (informational; also encoded in the wheel + PyTorchLink)
|
||||
|
||||
Python is pinned to 3.13 by uv (see .python-version) so it is no longer a match
|
||||
key — every wheel here is cp313. We just pick the newest CUDA build the driver
|
||||
can run and hand the caller both pieces to install.
|
||||
key — every wheel in both tables is cp313. We just pick the newest CUDA build
|
||||
the driver can run and hand the caller both pieces to install.
|
||||
|
||||
On a match it prints two `KEY=value` lines to stdout:
|
||||
|
||||
WHEEL=https://.../flash_attn-...cp313-win_amd64.whl
|
||||
TORCHARGS=torch==2.12.0 torchvision==0.27.0 --index-url https://download.pytorch.org/whl/cu130
|
||||
|
||||
(``TORCHARGS`` is column 4 with the leading ``pip install`` stripped, so the
|
||||
caller can run it with ``uv pip install``.) On no match it prints nothing.
|
||||
(``TORCHARGS`` is column 4 with the leading ``pip install`` / ``pip3 install``
|
||||
stripped, so the caller can run it with ``uv pip install``.) On no match — no
|
||||
NVIDIA driver, an unsupported platform/arch, or a driver older than every listed
|
||||
CUDA build — it prints nothing and exits 0; the caller decides what that means.
|
||||
Diagnostics go to stderr. Standard library + nvidia-smi only.
|
||||
|
||||
macOS has no CUDA, so rigging is unavailable there and this prints nothing.
|
||||
|
||||
Override CUDA detection with RIGTOOLS_CUDA (e.g. "12.8").
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
WHEELS_FILE = Path(__file__).resolve().parent / "flash_attention_windows.txt"
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# Wheels are platform-tagged: a win_amd64 wheel is rejected outright by pip/uv on
|
||||
# Linux ("wheel is compatible with Windows, but you're on Linux"), so the table
|
||||
# MUST follow the host rather than being a single shared list.
|
||||
WHEELS_FILE = _HERE / ("flash_attention_windows.txt" if sys.platform == "win32"
|
||||
else "flash_attention_linux.txt")
|
||||
|
||||
|
||||
def driver_cuda() -> float | None:
|
||||
"""Max CUDA version the NVIDIA driver supports (from nvidia-smi), or None."""
|
||||
override = os.environ.get("RIGTOOLS_CUDA")
|
||||
if override:
|
||||
try:
|
||||
return float(override)
|
||||
except ValueError:
|
||||
pass
|
||||
forced = cuda_key(override)
|
||||
if forced is not None:
|
||||
return forced
|
||||
exe = shutil.which("nvidia-smi")
|
||||
if not exe:
|
||||
return None
|
||||
|
|
@ -56,6 +69,17 @@ def driver_cuda() -> float | None:
|
|||
return float(f"{m.group(1)}.{m.group(2)}") if m else None
|
||||
|
||||
|
||||
def cuda_key(text: str) -> float | None:
|
||||
"""Normalise a CUDA column to a comparable major.minor float.
|
||||
|
||||
Accepts "13", "13.0" and "13.0.0" — the Linux table quotes three-part CUDA
|
||||
versions, and a bare float() on those raises, which would silently drop the
|
||||
row and look identical to "no GPU".
|
||||
"""
|
||||
m = re.match(r"\s*(\d+)(?:\.(\d+))?", text)
|
||||
return float(f"{m.group(1)}.{m.group(2) or 0}") if m else None
|
||||
|
||||
|
||||
def parse_rows():
|
||||
"""Yield (torch_ver, cuda: float, wheel_url, torch_args) from the wheels file."""
|
||||
rows = []
|
||||
|
|
@ -67,19 +91,37 @@ def parse_rows():
|
|||
if len(parts) < 4:
|
||||
continue
|
||||
torch_ver, cuda, link, pytorch_cmd = parts[0], parts[1], parts[2], parts[3]
|
||||
try:
|
||||
cuda_f = float(cuda)
|
||||
except ValueError:
|
||||
cuda_f = cuda_key(cuda)
|
||||
if cuda_f is None:
|
||||
continue
|
||||
# Strip the leading "pip install" (or "uv pip install") so the caller can
|
||||
# run it via `uv pip install <args>`.
|
||||
args = re.sub(r"^\s*(uv\s+)?pip\s+install\s+", "", pytorch_cmd).strip()
|
||||
# Strip the leading "pip install" / "pip3 install" (or the "uv "-prefixed
|
||||
# forms) so the caller can run it via `uv pip install <args>`.
|
||||
args = re.sub(r"^\s*(uv\s+)?pip3?\s+install\s+", "", pytorch_cmd).strip()
|
||||
rows.append((torch_ver, cuda_f, link, args))
|
||||
return rows
|
||||
|
||||
|
||||
def main() -> None:
|
||||
py = f"{sys.version_info.major}.{sys.version_info.minor}"
|
||||
|
||||
# Platform/arch gates first: both tables ship x86_64 wheels for a CUDA GPU, so
|
||||
# anywhere else there is nothing to pick and saying so beats letting the caller
|
||||
# download multi-GB of torch on the way to an unavoidable failure.
|
||||
if sys.platform == "darwin":
|
||||
print("[flash-attn] macOS has no CUDA; rigging is unavailable here.", file=sys.stderr)
|
||||
return
|
||||
if sys.platform not in ("win32", "linux"):
|
||||
print(f"[flash-attn] Unsupported platform {sys.platform!r}; no prebuilt wheels listed.", file=sys.stderr)
|
||||
return
|
||||
arch = platform.machine().lower()
|
||||
if arch not in ("x86_64", "amd64"):
|
||||
print(f"[flash-attn] Unsupported CPU architecture {arch!r} — the listed wheels are "
|
||||
f"x86_64 only.", file=sys.stderr)
|
||||
return
|
||||
if not WHEELS_FILE.exists():
|
||||
print(f"[flash-attn] Missing wheel table {WHEELS_FILE.name}.", file=sys.stderr)
|
||||
return
|
||||
|
||||
cuda = driver_cuda()
|
||||
if cuda is None:
|
||||
print("[flash-attn] No NVIDIA GPU / CUDA detected; skipping prebuilt wheel.", file=sys.stderr)
|
||||
|
|
@ -87,7 +129,7 @@ def main() -> None:
|
|||
|
||||
rows = parse_rows()
|
||||
if not rows:
|
||||
print("[flash-attn] No usable rows in flash_attention_windows.txt.", file=sys.stderr)
|
||||
print(f"[flash-attn] No usable rows in {WHEELS_FILE.name}.", file=sys.stderr)
|
||||
return
|
||||
|
||||
# Rows whose CUDA build the driver can run (wheel_cuda <= driver_cuda),
|
||||
|
|
@ -103,8 +145,8 @@ def main() -> None:
|
|||
if py != "3.13":
|
||||
print(f"[flash-attn] WARNING: running Python {py}, but the wheels are cp313. "
|
||||
f"Expect an install failure unless the venv is Python 3.13.", file=sys.stderr)
|
||||
print(f"[flash-attn] driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, torch {torch_ver}.",
|
||||
file=sys.stderr)
|
||||
print(f"[flash-attn] {WHEELS_FILE.name}: driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, "
|
||||
f"torch {torch_ver}.", file=sys.stderr)
|
||||
print(f"WHEEL={link}")
|
||||
print(f"TORCHARGS={torch_args}")
|
||||
|
||||
|
|
|
|||
706
thirdparty/skintokens/src/data/augment.py
vendored
Normal file
706
thirdparty/skintokens/src/data/augment.py
vendored
Normal file
|
|
@ -0,0 +1,706 @@
|
|||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from typing import Tuple, Union, List, Optional, Dict
|
||||
from numpy import ndarray
|
||||
from abc import ABC, abstractmethod
|
||||
from scipy.spatial.transform import Rotation as R
|
||||
|
||||
import numpy as np
|
||||
import random
|
||||
|
||||
from .spec import ConfigSpec
|
||||
|
||||
from ..rig_package.utils import axis_angle_to_matrix
|
||||
from ..rig_package.info.asset import Asset
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Augment(ConfigSpec):
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def parse(cls, **kwags) -> 'Augment':
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
pass
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentTrim(Augment):
|
||||
"""randomly delete joints and vertices"""
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentTrim':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentTrim()
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
asset.trim_skeleton()
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentDelete(Augment):
|
||||
"""randomly delete joints and vertices"""
|
||||
|
||||
# probability
|
||||
p: float
|
||||
|
||||
# how much to keep
|
||||
rate: float
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentDelete':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentDelete(
|
||||
p=kwargs.get('p', 0.),
|
||||
rate=kwargs.get('rate', 0.5),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
if asset.skin is None:
|
||||
raise ValueError("do not have skin")
|
||||
if asset.parents is None:
|
||||
raise ValueError("do not have parents")
|
||||
asset.normalize_skin()
|
||||
def select_k(arr: List, k: int):
|
||||
if len(arr) <= k:
|
||||
return arr
|
||||
else:
|
||||
rest_indices = list(range(1, len(arr)))
|
||||
selected_indices = sorted(random.sample(rest_indices, k))
|
||||
return [arr[i] for i in selected_indices]
|
||||
if np.random.rand() >= self.p:
|
||||
return
|
||||
ids = select_k([i for i in range(asset.J)], max(int(asset.J * (1 - np.random.rand() * self.rate)), 1))
|
||||
if len(ids) == 0:
|
||||
return
|
||||
# keep bones with no skin
|
||||
keep = {}
|
||||
for id in ids:
|
||||
keep[id] = True
|
||||
for id in range(asset.J):
|
||||
if np.all(asset.skin[:, id] < 0.1):
|
||||
keep[id] = True
|
||||
keep[asset.root] = True
|
||||
|
||||
vertices_to_delete = np.zeros(asset.N, dtype=bool)
|
||||
for id in range(asset.J):
|
||||
if id not in keep:
|
||||
dominant = asset.skin.argmax(axis=1) == id
|
||||
x = (asset.skin[:, id] > 0.1) & dominant
|
||||
if np.all(~x) or x.sum() * asset.J < asset.N: # avoid collapsing
|
||||
keep[id] = 1
|
||||
continue
|
||||
vertices_to_delete[x] = True
|
||||
if np.all(vertices_to_delete):
|
||||
return
|
||||
if asset.faces is not None:
|
||||
indices = np.where(~vertices_to_delete)[0]
|
||||
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
|
||||
if np.all(~face_mask):
|
||||
return
|
||||
|
||||
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
|
||||
asset.delete_joints(joints_to_delete)
|
||||
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentDropPart(Augment):
|
||||
"""randomly drop subtrees and their vertices"""
|
||||
|
||||
# probability
|
||||
p: float
|
||||
|
||||
# drop rate
|
||||
rate: float
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentDropPart':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentDropPart(
|
||||
p=kwargs.get('p', 0.),
|
||||
rate=kwargs.get('rate', 0.5),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
if np.random.rand() >= self.p:
|
||||
return
|
||||
if asset.parents is None:
|
||||
raise ValueError("do not have parents")
|
||||
if asset.skin is None:
|
||||
raise ValueError("do not have skin")
|
||||
keep = []
|
||||
for id in range(asset.J):
|
||||
if np.random.rand() < self.rate:
|
||||
keep.append(id)
|
||||
if len(keep) == 0:
|
||||
return
|
||||
for id in reversed(asset.dfs_order):
|
||||
p = asset.parents[id]
|
||||
if p == -1:
|
||||
continue
|
||||
if id in keep and p not in keep:
|
||||
keep.append(p)
|
||||
|
||||
mask = np.zeros(asset.N, dtype=bool)
|
||||
for id in keep:
|
||||
mask[asset.skin[:, id] > 1e-5] = True
|
||||
vertices_to_delete = ~mask
|
||||
if np.all(vertices_to_delete):
|
||||
return
|
||||
if asset.faces is not None:
|
||||
indices = np.where(~vertices_to_delete)[0]
|
||||
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
|
||||
if np.all(~face_mask):
|
||||
return
|
||||
|
||||
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
|
||||
asset.delete_joints(joints_to_delete)
|
||||
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
|
||||
|
||||
def inverse(self, asset: Asset):
|
||||
pass
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentCollapse(Augment):
|
||||
"""randomly merge joints"""
|
||||
|
||||
# collapse the skeleton with probability p
|
||||
p: float
|
||||
|
||||
# probability to merge the bone
|
||||
rate: float
|
||||
|
||||
# max bones
|
||||
max_bones: int
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentCollapse':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentCollapse(
|
||||
p=kwargs.get('p', 0.),
|
||||
rate=kwargs.get('rate', 0.),
|
||||
max_bones=kwargs.get('max_bones', 2147483647),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
def select_k(arr: List, k: int):
|
||||
if len(arr) <= k:
|
||||
return arr
|
||||
else:
|
||||
rest_indices = list(range(1, len(arr)))
|
||||
selected_indices = sorted(random.sample(rest_indices, k))
|
||||
return [arr[i] for i in selected_indices]
|
||||
|
||||
root = asset.root
|
||||
if np.random.rand() < self.p:
|
||||
ids = []
|
||||
for id in range(asset.J):
|
||||
if np.random.rand() >= self.rate:
|
||||
ids.append(id)
|
||||
if root not in ids:
|
||||
ids.append(root)
|
||||
keep: List[int|str] = select_k([i for i in range(asset.J) if i in ids], self.max_bones)
|
||||
if root not in keep:
|
||||
keep[0] = root
|
||||
asset.set_order(new_orders=keep)
|
||||
elif asset.J > self.max_bones:
|
||||
ids = select_k([i for i in range(asset.J)], k=self.max_bones)
|
||||
if root not in ids:
|
||||
ids[0] = root
|
||||
keep: List[int|str] = [i for i in range(asset.J) if i in ids]
|
||||
asset.set_order(new_orders=keep)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentJointDiscrete(Augment):
|
||||
# perturb the skeleton with probability p
|
||||
p: float
|
||||
|
||||
# num of discretized coord
|
||||
discrete: int
|
||||
|
||||
# continuous range
|
||||
continuous_range: Tuple[float, float]
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentJointDiscrete':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentJointDiscrete(
|
||||
p=kwargs.get('p', 0.),
|
||||
discrete=kwargs.get('discrete', 256),
|
||||
continuous_range=kwargs.get('continuous_range', [-1., 1.]),
|
||||
)
|
||||
|
||||
def _discretize(
|
||||
self,
|
||||
t: ndarray,
|
||||
continuous_range: Tuple[float, float],
|
||||
num_discrete: int,
|
||||
) -> ndarray:
|
||||
lo, hi = continuous_range
|
||||
assert hi >= lo
|
||||
t = (t - lo) / (hi - lo)
|
||||
t *= num_discrete
|
||||
return np.clip(t.round(), 0, num_discrete - 1).astype(np.int64)
|
||||
|
||||
def _undiscretize(
|
||||
self,
|
||||
t: ndarray,
|
||||
continuous_range: Tuple[float, float],
|
||||
num_discrete: int,
|
||||
) -> ndarray:
|
||||
lo, hi = continuous_range
|
||||
assert hi >= lo
|
||||
t = t.astype(np.float32) + 0.5
|
||||
t /= num_discrete
|
||||
return t * (hi - lo) + lo
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
if np.random.rand() < self.p:
|
||||
joints = asset.joints
|
||||
if joints is not None and asset.matrix_local is not None:
|
||||
joints = self._undiscretize(self._discretize(
|
||||
joints,
|
||||
self.continuous_range,
|
||||
self.discrete,
|
||||
),
|
||||
self.continuous_range,
|
||||
self.discrete,
|
||||
)
|
||||
asset.matrix_local[:, :3, 3] = joints
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentJointPerturb(Augment):
|
||||
# perturb the skeleton with probability p
|
||||
p: float
|
||||
|
||||
# jitter sigma on joints
|
||||
sigma: float
|
||||
|
||||
# jitter clip on joints
|
||||
clip: float
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentJointPerturb':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentJointPerturb(
|
||||
p=kwargs.get('p', 0.),
|
||||
sigma=kwargs.get('sigma', 0.),
|
||||
clip=kwargs.get('clip', 0.),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
if np.random.rand() < self.p and asset.matrix_local is not None:
|
||||
asset.matrix_local[:, :3] += np.clip(
|
||||
np.random.normal(0, self.sigma, (asset.J, 3)),
|
||||
-self.clip,
|
||||
self.clip,
|
||||
)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentLBS(Augment):
|
||||
# apply a random pose with probability p
|
||||
random_pose_p: float
|
||||
|
||||
# random pose angle range
|
||||
random_pose_angle: float
|
||||
|
||||
# random scale
|
||||
random_scale_range: Tuple[float, float]
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentLBS':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentLBS(
|
||||
random_pose_p=kwargs.get('random_pose_p', 0.),
|
||||
random_pose_angle=kwargs.get('random_pose_angle', 0.),
|
||||
random_scale_range=kwargs.get('random_scale_range', (1., 1.)),
|
||||
)
|
||||
|
||||
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
|
||||
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
def get_matrix_basis(angle: float):
|
||||
matrix = axis_angle_to_matrix((np.random.rand(asset.J, 3) - 0.5) * angle / 180 * np.pi * 2).astype(np.float32)
|
||||
return matrix
|
||||
|
||||
if np.random.rand() < self.random_pose_p and asset.joints is not None:
|
||||
matrix_basis = get_matrix_basis(self.random_pose_angle)
|
||||
max_offset = (asset.joints.max(axis=0) - asset.joints.min(axis=0)).max()
|
||||
matrix_basis[:, :3, :3] *= np.tile(np.random.uniform(low=self.random_scale_range[0], high=self.random_scale_range[1], size=(asset.J, 1, 1)), (1, 3, 3))
|
||||
asset.vertices_with_pose(matrix_basis=matrix_basis, inplace=True)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentLinear(Augment):
|
||||
# apply random rotation with probability p
|
||||
random_rotate_p: float
|
||||
|
||||
# random rotation angle(degree)
|
||||
random_rotate_angle: float
|
||||
|
||||
# swap x with probability p
|
||||
random_flip_x_p: float
|
||||
|
||||
# swap y with probability p
|
||||
random_flip_y_p: float
|
||||
|
||||
# swap z with probability p
|
||||
random_flip_z_p: float
|
||||
|
||||
# probability to pick an angle in static_rotate_x
|
||||
static_rotate_x_p: float
|
||||
|
||||
# rotate around x axis among given angles(degrees)
|
||||
static_rotate_x: List[float]
|
||||
|
||||
# probability to pick an angle in static_rotate_y
|
||||
static_rotate_y_p: float
|
||||
|
||||
# rotate around y axis among given angles(degrees)
|
||||
static_rotate_y: List[float]
|
||||
|
||||
# probability to pick an angle in static_rotate_z
|
||||
static_rotate_z_p: float
|
||||
|
||||
# rotate around z axis among given angles(degrees)
|
||||
static_rotate_z: List[float]
|
||||
|
||||
# apply random scaling with probability p
|
||||
random_scale_p: float
|
||||
|
||||
# random scaling xyz axis
|
||||
random_scale: Tuple[float, float]
|
||||
|
||||
# randomly change xyz orientation
|
||||
random_transpose: float
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentLinear':
|
||||
if kwargs.get('random_flip_x_p', 0) > 0 or kwargs.get('random_flip_y_p', 0) > 0 or kwargs.get('random_flip_z_p', 0) > 0:
|
||||
print("\033[31mWARNING: random flip is enabled and is very likely to confuse ar model !\033[0m")
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentLinear(
|
||||
random_rotate_p=kwargs.get('random_rotate_p', 0.),
|
||||
random_rotate_angle=kwargs.get('random_rotate_angle', 0.),
|
||||
random_flip_x_p=kwargs.get('random_flip_x_p', 0.),
|
||||
random_flip_y_p=kwargs.get('random_flip_y_p', 0.),
|
||||
random_flip_z_p=kwargs.get('random_flip_z_p', 0.),
|
||||
static_rotate_x_p=kwargs.get('static_rotate_x_p', 0.),
|
||||
static_rotate_x=kwargs.get('static_rotate_x', []),
|
||||
static_rotate_y_p=kwargs.get('static_rotate_y_p', 0.),
|
||||
static_rotate_y=kwargs.get('static_rotate_y', []),
|
||||
static_rotate_z_p=kwargs.get('static_rotate_z_p', 0.),
|
||||
static_rotate_z=kwargs.get('static_rotate_z', []),
|
||||
random_scale_p=kwargs.get('random_scale_p', 0.),
|
||||
random_scale=kwargs.get('random_scale', [1.0, 1.0]),
|
||||
random_transpose=kwargs.get('random_transpose', 0.),
|
||||
)
|
||||
|
||||
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
|
||||
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
trans_vertex = np.eye(4, dtype=np.float32)
|
||||
r = np.eye(4, dtype=np.float32)
|
||||
if np.random.rand() < self.random_rotate_p:
|
||||
angle = self.random_rotate_angle
|
||||
axis_angle = (np.random.rand(3) - 0.5) * angle / 180 * np.pi * 2
|
||||
r = R.from_rotvec(axis_angle).as_matrix()
|
||||
r = np.pad(r, ((0, 1), (0, 1)), 'constant', constant_values=0.)
|
||||
r[3, 3] = 1.
|
||||
|
||||
if np.random.uniform(0, 1) < self.random_flip_x_p:
|
||||
r @= np.array([
|
||||
[-1.0, 0.0, 0.0, 0.0],
|
||||
[ 0.0, 1.0, 0.0, 0.0],
|
||||
[ 0.0, 0.0, 1.0, 0.0],
|
||||
[ 0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.random_flip_y_p:
|
||||
r @= np.array([
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, -1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.random_flip_z_p:
|
||||
r @= np.array([
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, -1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.static_rotate_x_p:
|
||||
assert len(self.static_rotate_x) > 0, "static rotation of x is enabled, but static_rotate_x is empty"
|
||||
angle = np.random.choice(self.static_rotate_x) / 180 * np.pi
|
||||
c = np.cos(angle)
|
||||
s = np.sin(angle)
|
||||
r @= np.array([
|
||||
[ 1.0, 0.0, 0.0, 0.0],
|
||||
[ 0.0, c, s, 0.0],
|
||||
[ 0.0, -s, c, 0.0],
|
||||
[ 0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.static_rotate_y_p:
|
||||
assert len(self.static_rotate_y) > 0, "static rotation of y is enabled, but static_rotate_y is empty"
|
||||
angle = np.random.choice(self.static_rotate_y) / 180 * np.pi
|
||||
c = np.cos(angle)
|
||||
s = np.sin(angle)
|
||||
r @= np.array([
|
||||
[ c, 0.0, -s, 0.0],
|
||||
[ 0.0, 1.0, 0.0, 0.0],
|
||||
[ s, 0.0, c, 0.0],
|
||||
[ 0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.static_rotate_z_p:
|
||||
assert len(self.static_rotate_z) > 0, "static rotation of z is enabled, but static_rotate_z is empty"
|
||||
angle = np.random.choice(self.static_rotate_z) / 180 * np.pi
|
||||
c = np.cos(angle)
|
||||
s = np.sin(angle)
|
||||
r @= np.array([
|
||||
[ c, s, 0.0, 0.0],
|
||||
[ -s, c, 0.0, 0.0],
|
||||
[ 0.0, 0.0, 1.0, 0.0],
|
||||
[ 0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.random_scale_p:
|
||||
scale_x = np.random.uniform(self.random_scale[0], self.random_scale[1])
|
||||
scale_y = np.random.uniform(self.random_scale[0], self.random_scale[1])
|
||||
scale_z = np.random.uniform(self.random_scale[0], self.random_scale[1])
|
||||
r @= np.array([
|
||||
[scale_x, 0.0, 0.0, 0.0],
|
||||
[0.0, scale_y, 0.0, 0.0],
|
||||
[0.0, 0.0, scale_z, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
])
|
||||
|
||||
if np.random.uniform(0, 1) < self.random_transpose:
|
||||
permutations = [
|
||||
(0, 1, 2), # x, y, z
|
||||
(0, 2, 1), # x, z, y
|
||||
(1, 0, 2), # y, x, z
|
||||
(1, 2, 0), # y, z, x
|
||||
(2, 0, 1), # z, x, y
|
||||
(2, 1, 0), # z, y, x
|
||||
]
|
||||
direction_signs = [
|
||||
(1, 1, 1),
|
||||
(1, 1, -1),
|
||||
(1, -1, 1),
|
||||
(1, -1, -1),
|
||||
(-1, 1, 1),
|
||||
(-1, 1, -1),
|
||||
(-1, -1, 1),
|
||||
(-1, -1, -1),
|
||||
]
|
||||
perm = permutations[np.random.randint(0, 6)]
|
||||
sign = direction_signs[np.random.randint(0, 8)]
|
||||
m = np.zeros((4, 4))
|
||||
for i in range(3):
|
||||
m[i, perm[i]] = sign[i]
|
||||
m[3, 3] = 1.0
|
||||
r = m @ r
|
||||
|
||||
trans_vertex = r @ trans_vertex
|
||||
|
||||
# apply transform here
|
||||
asset.transform(trans=trans_vertex)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentAffine(Augment):
|
||||
# final normalization cube
|
||||
normalize_into: Tuple[float, float]
|
||||
|
||||
# randomly scale coordinates with probability p
|
||||
random_scale_p: float
|
||||
|
||||
# scale range (lower, upper)
|
||||
random_scale: Tuple[float, float]
|
||||
|
||||
# randomly shift coordinates with probability p
|
||||
random_shift_p: float
|
||||
|
||||
# shift range (lower, upper)
|
||||
random_shift: Tuple[float, float]
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentAffine':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentAffine(
|
||||
normalize_into=kwargs.get('normalize_into', [-1.0, 1.0]),
|
||||
random_scale_p=kwargs.get('random_scale_p', 0.),
|
||||
random_scale=kwargs.get('random_scale', [1., 1.]),
|
||||
random_shift_p=kwargs.get('random_shift_p', 0.),
|
||||
random_shift=kwargs.get('random_shift', [0., 0.]),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
if asset.vertices is None:
|
||||
raise ValueError("do not have vertices")
|
||||
bound_min = asset.vertices.min(axis=0)
|
||||
bound_max = asset.vertices.max(axis=0)
|
||||
if asset.joints is not None:
|
||||
joints_bound_min = asset.joints.min(axis=0)
|
||||
joints_bound_max = asset.joints.max(axis=0)
|
||||
bound_min = np.minimum(bound_min, joints_bound_min)
|
||||
bound_max = np.maximum(bound_max, joints_bound_max)
|
||||
|
||||
trans_vertex = np.eye(4, dtype=np.float32)
|
||||
|
||||
trans_vertex = _trans_to_m(-(bound_max + bound_min)/2) @ trans_vertex
|
||||
|
||||
if self.normalize_into is not None:
|
||||
# scale into the cube
|
||||
normalize_into = self.normalize_into
|
||||
scale = np.max((bound_max - bound_min) / (normalize_into[1] - normalize_into[0]))
|
||||
trans_vertex = _scale_to_m(1. / scale) @ trans_vertex
|
||||
|
||||
bias = (normalize_into[0] + normalize_into[1]) / 2
|
||||
trans_vertex = _trans_to_m(np.array([bias, bias, bias], dtype=np.float32)) @ trans_vertex
|
||||
|
||||
if np.random.rand() < self.random_scale_p:
|
||||
scale = _scale_to_m(np.random.uniform(self.random_scale[0], self.random_scale[1]))
|
||||
trans_vertex = scale @ trans_vertex
|
||||
|
||||
if np.random.rand() < self.random_shift_p:
|
||||
l, r = self.random_shift
|
||||
shift_vals = np.array([
|
||||
np.random.uniform(l, r),
|
||||
np.random.uniform(l, r),
|
||||
np.random.uniform(l, r),
|
||||
], dtype=np.float32)
|
||||
if self.normalize_into is not None:
|
||||
def _apply(v: ndarray, trans: ndarray) -> ndarray:
|
||||
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
|
||||
lo, hi = self.normalize_into
|
||||
pts_min = _apply(bound_min[None, :], trans_vertex)[0]
|
||||
pts_max = _apply(bound_max[None, :], trans_vertex)[0]
|
||||
low_allowed = lo - pts_min
|
||||
high_allowed = hi - pts_max
|
||||
shift_vals = np.array([
|
||||
np.random.uniform(low_allowed[0], high_allowed[0]),
|
||||
np.random.uniform(low_allowed[1], high_allowed[1]),
|
||||
np.random.uniform(low_allowed[2], high_allowed[2]),
|
||||
], dtype=np.float32)
|
||||
shift = _trans_to_m(shift_vals.astype(np.float32))
|
||||
trans_vertex = shift @ trans_vertex
|
||||
asset.transform(trans=trans_vertex)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentJitter(Augment):
|
||||
# probability
|
||||
p: float
|
||||
|
||||
# jitter sigma on vertices
|
||||
vertex_sigma: float
|
||||
|
||||
# jitter clip on vertices
|
||||
vertex_clip: float
|
||||
|
||||
# jitter sigma on normals
|
||||
normal_sigma: float
|
||||
|
||||
# jitter clip on normals
|
||||
normal_clip: float
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentJitter':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentJitter(
|
||||
p=kwargs.get('p', 0.5),
|
||||
vertex_sigma=kwargs.get('vertex_sigma', 0.),
|
||||
vertex_clip=kwargs.get('vertex_clip', 0.),
|
||||
normal_sigma=kwargs.get('normal_sigma', 0.),
|
||||
normal_clip=kwargs.get('normal_clip', 0.),
|
||||
)
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
vertex_sigma = self.vertex_sigma
|
||||
vertex_clip = self.vertex_clip
|
||||
normal_sigma = self.normal_sigma
|
||||
normal_clip = self.normal_clip
|
||||
|
||||
if np.random.rand() < self.p:
|
||||
scale = np.random.rand() + 1e-6
|
||||
vertex_sigma *= scale
|
||||
vertex_clip *= scale
|
||||
scale = np.random.rand() + 1e-6
|
||||
normal_sigma *= scale
|
||||
normal_clip *= scale
|
||||
if vertex_sigma > 0 and asset.vertices is not None:
|
||||
noise = np.clip(np.random.randn(*asset.vertices.shape) * vertex_sigma, -vertex_clip, vertex_clip).astype(np.float32)
|
||||
asset.vertices += noise
|
||||
|
||||
if normal_sigma > 0:
|
||||
if asset.vertex_normals is not None:
|
||||
noise = np.clip(np.random.randn(*asset.vertex_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
|
||||
asset.vertex_normals += noise
|
||||
|
||||
if asset.face_normals is not None:
|
||||
noise = np.clip(np.random.randn(*asset.face_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
|
||||
asset.face_normals += noise
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AugmentNormalize(Augment):
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'AugmentNormalize':
|
||||
cls.check_keys(kwargs)
|
||||
return AugmentNormalize()
|
||||
|
||||
def transform(self, asset: Asset, **kwargs):
|
||||
epsilon = 1e-10
|
||||
if asset.vertex_normals is not None:
|
||||
vertex_norms = np.linalg.norm(asset.vertex_normals, axis=1, keepdims=True)
|
||||
vertex_norms = np.maximum(vertex_norms, epsilon)
|
||||
asset.vertex_normals = asset.vertex_normals / vertex_norms
|
||||
asset.vertex_normals = np.nan_to_num(asset.vertex_normals, nan=0., posinf=0., neginf=0.) # type: ignore
|
||||
|
||||
if asset.face_normals is not None:
|
||||
face_norms = np.linalg.norm(asset.face_normals, axis=1, keepdims=True)
|
||||
face_norms = np.maximum(face_norms, epsilon)
|
||||
asset.face_normals = asset.face_normals / face_norms
|
||||
asset.face_normals = np.nan_to_num(asset.face_normals, nan=0., posinf=0., neginf=0.) # type: ignore
|
||||
|
||||
def _trans_to_m(v: ndarray):
|
||||
m = np.eye(4, dtype=np.float32)
|
||||
m[0:3, 3] = v
|
||||
return m
|
||||
|
||||
def _scale_to_m(r: ndarray|float):
|
||||
m = np.zeros((4, 4), dtype=np.float32)
|
||||
m[0, 0] = r
|
||||
m[1, 1] = r
|
||||
m[2, 2] = r
|
||||
m[3, 3] = 1.
|
||||
return m
|
||||
|
||||
def get_augments(*args) -> List[Augment]:
|
||||
MAP = {
|
||||
'trim': AugmentTrim,
|
||||
'delete': AugmentDelete,
|
||||
'drop_part': AugmentDropPart,
|
||||
'collapse': AugmentCollapse,
|
||||
'lbs': AugmentLBS,
|
||||
'linear': AugmentLinear,
|
||||
'affine': AugmentAffine,
|
||||
'jitter': AugmentJitter,
|
||||
'joint_perturb': AugmentJointPerturb,
|
||||
'joint_discrete': AugmentJointDiscrete,
|
||||
'normalize': AugmentNormalize,
|
||||
}
|
||||
MAP: Dict[str, type[Augment]]
|
||||
augments = []
|
||||
for (i, config) in enumerate(args):
|
||||
__target__ = config.get('__target__')
|
||||
assert __target__ is not None, f"do not find `__target__` in augment of position {i}"
|
||||
c = deepcopy(config)
|
||||
del c['__target__']
|
||||
augments.append(MAP[__target__].parse(**c))
|
||||
return augments
|
||||
344
thirdparty/skintokens/src/data/datapath.py
vendored
Normal file
344
thirdparty/skintokens/src/data/datapath.py
vendored
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
from abc import abstractmethod, ABC
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from numpy import ndarray
|
||||
from random import shuffle
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import numpy as np
|
||||
import requests
|
||||
import os
|
||||
|
||||
from ..rig_package.info.asset import Asset
|
||||
from ..server.spec import BPY_SERVER, bytes_to_object, object_to_bytes
|
||||
from .spec import ConfigSpec
|
||||
|
||||
@dataclass
|
||||
class LazyAsset(ABC):
|
||||
"""store datapath and load upon requiring"""
|
||||
path: str
|
||||
|
||||
cls: Optional[str]=None
|
||||
|
||||
@abstractmethod
|
||||
def load(self) -> 'Asset':
|
||||
raise NotImplementedError()
|
||||
|
||||
@dataclass
|
||||
class BpyLazyAsset(LazyAsset):
|
||||
|
||||
def load(self) -> 'Asset':
|
||||
from ..rig_package.parser.bpy import BpyParser
|
||||
asset = BpyParser.load(filepath=self.path)
|
||||
asset.cls = self.cls
|
||||
asset.path = self.path
|
||||
return asset
|
||||
|
||||
@dataclass
|
||||
class BpyServerLazyAsset(LazyAsset):
|
||||
"""workaround while bpy is working in multiple threads"""
|
||||
def load(self) -> 'Asset':
|
||||
try:
|
||||
asset = bytes_to_object(requests.get(f"{BPY_SERVER}/load", data=object_to_bytes(self.path)).content)
|
||||
if isinstance(asset, str):
|
||||
raise RuntimeError(f"bpy server failed: {asset}")
|
||||
assert isinstance(asset, Asset)
|
||||
asset.cls = self.cls
|
||||
asset.path = self.path
|
||||
return asset
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"bpy server failed: {str(e)}")
|
||||
|
||||
@dataclass
|
||||
class NpzLazyAsset(LazyAsset):
|
||||
|
||||
def load(self) -> 'Asset':
|
||||
d = np.load(self.path, allow_pickle=True)
|
||||
asset = Asset(
|
||||
vertices=d['vertices'],
|
||||
faces=d['faces'],
|
||||
mesh_names=d.get('mesh_names', None),
|
||||
joint_names=d.get('joint_names', None),
|
||||
parents=d.get('parents', None),
|
||||
lengths=d.get('lengths', None),
|
||||
matrix_world=d.get('matrix_world', None),
|
||||
matrix_local=d.get('matrix_local', None),
|
||||
armature_name=d.get('armature_name', None),
|
||||
skin=d.get('skin', None),
|
||||
cls=self.cls,
|
||||
path=self.path
|
||||
)
|
||||
asset.cls = self.cls
|
||||
asset.path = self.path
|
||||
return asset
|
||||
|
||||
@dataclass
|
||||
class UniRigLazyAsset(LazyAsset):
|
||||
"""map unirig's data correctly"""
|
||||
|
||||
def load(self) -> 'Asset':
|
||||
def bn(x):
|
||||
if isinstance(x, ndarray) and x.ndim==0:
|
||||
return x.item()
|
||||
return x
|
||||
|
||||
d = np.load(self.path, allow_pickle=True)
|
||||
parents = bn(d.get('parents', None))
|
||||
if parents is not None:
|
||||
parents = [-1 if x is None else x for x in parents]
|
||||
parents = np.array(parents)
|
||||
matrix_local = bn(d.get('matrix_local', None))
|
||||
joints = bn(d.get('joints', None))
|
||||
if matrix_local is not None and matrix_local.ndim != 3 and joints is not None:
|
||||
matrix_local = np.zeros((joints.shape[0], 4, 4))
|
||||
matrix_local[...] = np.eye(4)
|
||||
matrix_local[:, :3, 3] = joints
|
||||
asset = Asset(
|
||||
vertices=d['vertices'],
|
||||
faces=d['faces'],
|
||||
joint_names=bn(d.get('names', None)),
|
||||
parents=parents, # type: ignore
|
||||
lengths=bn(d.get('lengths', None)),
|
||||
matrix_world=bn(d.get('matrix_world', None)),
|
||||
matrix_local=matrix_local,
|
||||
armature_name=bn(d.get('armature_name', None)),
|
||||
skin=bn(d.get('skin', None)),
|
||||
cls=self.cls,
|
||||
path=self.path
|
||||
).change_dtype(float_dtype=np.float32, int_dtype=np.int32)
|
||||
asset.cls = self.cls
|
||||
asset.path = self.path
|
||||
return asset
|
||||
|
||||
@dataclass
|
||||
class Datapath(ConfigSpec):
|
||||
"""handle input data paths"""
|
||||
|
||||
# all filepaths
|
||||
filepaths: List[str]
|
||||
|
||||
# root to add to prefix
|
||||
input_dataset_dir: str=''
|
||||
|
||||
# name of class
|
||||
cls_name: Optional[List[str]]=None
|
||||
|
||||
# bias in a single class
|
||||
cls_bias: Optional[List[int]]=None
|
||||
|
||||
# num of files in a single class
|
||||
cls_length: Optional[List[int]]=None
|
||||
|
||||
# how many files to return when using data sampling
|
||||
num_files: Optional[int]=None
|
||||
|
||||
# use proportion data sampling
|
||||
use_prob: bool=False
|
||||
|
||||
# weight
|
||||
cls_weight: Optional[List[float]]=None
|
||||
|
||||
# use bpy loader
|
||||
loader: type[LazyAsset]=BpyLazyAsset
|
||||
|
||||
# data name
|
||||
data_name: Optional[str]=None
|
||||
|
||||
# check if path exists
|
||||
ignore_check: bool=False
|
||||
|
||||
#################################################################
|
||||
# other vertex groups
|
||||
vertex_groups: Dict[str, ndarray]=field(default_factory=dict)
|
||||
|
||||
# sampled vertices
|
||||
sampled_vertices: Optional[ndarray]=None
|
||||
|
||||
# sampled normals
|
||||
sampled_normals: Optional[ndarray]=None
|
||||
|
||||
# sampled vertex groups
|
||||
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'Datapath':
|
||||
MAP = {
|
||||
None: BpyLazyAsset,
|
||||
'bpy': BpyLazyAsset,
|
||||
'bpy_server': BpyServerLazyAsset,
|
||||
'npz': NpzLazyAsset,
|
||||
'unirig': UniRigLazyAsset,
|
||||
}
|
||||
input_dataset_dir = kwargs.get('input_dataset_dir', '')
|
||||
num_files = kwargs.get('num_files', None)
|
||||
use_prob = kwargs.get('use_prob', False)
|
||||
data_name = kwargs.get('data_name', 'raw_data.npz')
|
||||
data_path = kwargs.get('data_path', None)
|
||||
loader_cls = MAP[kwargs.get('loader', None)]
|
||||
ignore_check = kwargs.get('ignore_check', False)
|
||||
|
||||
if data_path is not None:
|
||||
filepaths = []
|
||||
if isinstance(data_path, dict):
|
||||
cls_name = []
|
||||
cls_bias = []
|
||||
cls_length = []
|
||||
cls_weight = []
|
||||
for name, v in data_path.items():
|
||||
assert isinstance(v, list), "items in the dict must be a list of data list paths"
|
||||
for item in v:
|
||||
if isinstance(item, str):
|
||||
datalist_path = item
|
||||
weight = 1.0
|
||||
else:
|
||||
datalist_path = item[0]
|
||||
weight = item[1]
|
||||
cls_name.append(name)
|
||||
lines = [x.strip() for x in open(datalist_path, "r").readlines()]
|
||||
ok_lines = []
|
||||
missing = 0
|
||||
for line in lines:
|
||||
if ignore_check:
|
||||
ok_lines.append(line)
|
||||
elif os.path.exists(os.path.join(input_dataset_dir, line, data_name)):
|
||||
ok_lines.append(line)
|
||||
else:
|
||||
missing += 1
|
||||
if missing != 0:
|
||||
print(f"\033[31m{datalist_path}: {missing} missing files\033[0m")
|
||||
cls_bias.append(len(filepaths))
|
||||
cls_length.append(len(ok_lines))
|
||||
cls_weight.append(weight)
|
||||
filepaths.extend(ok_lines)
|
||||
else:
|
||||
raise NotImplementedError()
|
||||
else:
|
||||
_filepaths = kwargs['filepaths']
|
||||
if isinstance(_filepaths, list):
|
||||
filepaths = _filepaths
|
||||
cls_name = None
|
||||
cls_bias = None
|
||||
cls_length = None
|
||||
cls_weight = None
|
||||
elif isinstance(_filepaths, dict):
|
||||
filepaths = []
|
||||
cls_name = []
|
||||
cls_bias = []
|
||||
cls_length = []
|
||||
cls_weight = []
|
||||
for k, v in _filepaths.items():
|
||||
assert isinstance(v, list), "items in the dict must be a list of paths"
|
||||
cls_name.append(k)
|
||||
cls_bias.append(len(filepaths))
|
||||
cls_length.append(len(v))
|
||||
cls_weight.append(1.0)
|
||||
filepaths.extend(v)
|
||||
else:
|
||||
raise NotImplementedError()
|
||||
if cls_weight is not None:
|
||||
total = sum(cls_weight)
|
||||
cls_weight = [x/total for x in cls_weight]
|
||||
return Datapath(
|
||||
filepaths=filepaths,
|
||||
input_dataset_dir=input_dataset_dir,
|
||||
cls_name=cls_name,
|
||||
cls_bias=cls_bias,
|
||||
cls_length=cls_length,
|
||||
num_files=num_files,
|
||||
use_prob=use_prob,
|
||||
cls_weight=cls_weight,
|
||||
loader=loader_cls,
|
||||
data_name=data_name,
|
||||
ignore_check=ignore_check,
|
||||
)
|
||||
|
||||
def make(self, path: str, cls: str|None) -> LazyAsset:
|
||||
return self.loader(path=path, cls=cls)
|
||||
|
||||
def __getitem__(self, index: int) -> LazyAsset:
|
||||
if self.use_prob and self.cls_weight is not None:
|
||||
if self.cls_bias is None:
|
||||
raise ValueError("do not have cls_bias")
|
||||
if self.cls_length is None:
|
||||
raise ValueError("do not have cls_length")
|
||||
if not hasattr(self, "perms"):
|
||||
self.perms = []
|
||||
self.current_bias = []
|
||||
for i in range(len(self.cls_weight)):
|
||||
self.perms.append([x for x in range(self.cls_length[i])])
|
||||
self.current_bias.append(0)
|
||||
idx = np.random.choice(len(self.cls_weight), p=self.cls_weight)
|
||||
i = self.perms[idx][self.current_bias[idx]]
|
||||
self.current_bias[idx] += 1
|
||||
if self.current_bias[idx] >= self.cls_length[idx]:
|
||||
shuffle(self.perms[idx])
|
||||
self.current_bias[idx] = 0
|
||||
if self.cls_name is None:
|
||||
name = None
|
||||
else:
|
||||
name = self.cls_name[idx]
|
||||
path = os.path.join(self.input_dataset_dir, self.filepaths[i+self.cls_bias[idx]])
|
||||
if self.data_name is not None:
|
||||
path = os.path.join(path, self.data_name)
|
||||
return self.make(path=path, cls=name)
|
||||
else:
|
||||
if self.cls_name is None or self.cls_bias is None or self.cls_length is None:
|
||||
name = None
|
||||
else:
|
||||
name = None
|
||||
for i in range(len(self.cls_bias)):
|
||||
start = self.cls_bias[i]
|
||||
end = start + self.cls_length[i]
|
||||
if start <= index < end:
|
||||
name = self.cls_name[i]
|
||||
break
|
||||
path = os.path.join(self.input_dataset_dir, self.filepaths[index])
|
||||
if self.data_name is not None:
|
||||
path = os.path.join(path, self.data_name)
|
||||
return self.make(path=path, cls=name)
|
||||
|
||||
def get_data(self) -> List[LazyAsset]:
|
||||
return [self[i] for i in range(len(self))]
|
||||
|
||||
def split_by_cls(self) -> Dict[str|None, 'Datapath']:
|
||||
res: Dict[str|None, Datapath] = {}
|
||||
if self.cls_name is None:
|
||||
res[None] = self
|
||||
return res
|
||||
if self.cls_bias is None:
|
||||
raise ValueError("do not have cls_bias")
|
||||
if self.cls_length is None:
|
||||
raise ValueError("do not have cls_length")
|
||||
d_filepaths = defaultdict(list)
|
||||
d_length = defaultdict(int)
|
||||
d_weight = defaultdict(list)
|
||||
for (i, cls) in enumerate(self.cls_name):
|
||||
s = slice(self.cls_bias[i], self.cls_bias[i]+self.cls_length[i])
|
||||
d_filepaths[cls].extend(self.filepaths[s].copy())
|
||||
d_length[cls] += self.cls_length[i]
|
||||
if self.cls_weight is not None:
|
||||
d_weight[cls].append(self.cls_weight[i])
|
||||
for cls in d_filepaths:
|
||||
cls_weight = None if self.cls_weight is None else d_weight[cls]
|
||||
if cls_weight is not None:
|
||||
total = sum(cls_weight)
|
||||
cls_weight = [x/total for x in cls_weight]
|
||||
res[cls] = Datapath(
|
||||
filepaths=d_filepaths[cls],
|
||||
input_dataset_dir=self.input_dataset_dir,
|
||||
cls_name=[cls],
|
||||
cls_bias=[0],
|
||||
cls_length=[len(d_filepaths[cls])],
|
||||
num_files=self.num_files,
|
||||
use_prob=self.use_prob,
|
||||
cls_weight=cls_weight,
|
||||
loader=self.loader,
|
||||
data_name=self.data_name,
|
||||
)
|
||||
return res
|
||||
|
||||
def __len__(self):
|
||||
if self.use_prob:
|
||||
assert self.num_files is not None, 'num_files is not specified'
|
||||
return self.num_files
|
||||
return len(self.filepaths)
|
||||
319
thirdparty/skintokens/src/data/dataset.py
vendored
Normal file
319
thirdparty/skintokens/src/data/dataset.py
vendored
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS
|
||||
from numpy import ndarray
|
||||
from torch import Tensor
|
||||
from torch.utils import data
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from typing import Dict, List, Tuple, Callable, Optional
|
||||
|
||||
import os
|
||||
import lightning.pytorch as pl
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from .datapath import Datapath, LazyAsset
|
||||
from .spec import ConfigSpec
|
||||
from .transform import Transform
|
||||
|
||||
from ..model.spec import ModelInput
|
||||
from ..rig_package.info.asset import Asset
|
||||
from ..tokenizer.spec import Tokenizer, TokenizeInput
|
||||
|
||||
@dataclass
|
||||
class DatasetConfig(ConfigSpec):
|
||||
shuffle: bool
|
||||
batch_size: int
|
||||
num_workers: int
|
||||
datapath: Datapath
|
||||
pin_memory: bool=True
|
||||
persistent_workers: bool=True
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'DatasetConfig':
|
||||
cls.check_keys(kwargs)
|
||||
return DatasetConfig(
|
||||
shuffle=kwargs.get('shuffle', False),
|
||||
batch_size=kwargs.get('batch_size', 1),
|
||||
num_workers=kwargs.get('num_workers', 1),
|
||||
pin_memory=kwargs.get('pin_memory', True),
|
||||
persistent_workers=kwargs.get('persistent_workers', True),
|
||||
datapath=Datapath.parse(**kwargs.get('datapath')),
|
||||
)
|
||||
|
||||
def split_by_cls(self) -> Dict[str|None, 'DatasetConfig']:
|
||||
res: Dict[str|None, DatasetConfig] = {}
|
||||
datapath_dict = self.datapath.split_by_cls()
|
||||
for cls, v in datapath_dict.items():
|
||||
res[cls] = DatasetConfig(
|
||||
shuffle=self.shuffle,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
datapath=v,
|
||||
pin_memory=self.pin_memory,
|
||||
persistent_workers=self.persistent_workers,
|
||||
)
|
||||
return res
|
||||
|
||||
class RigDatasetModule(pl.LightningDataModule):
|
||||
def __init__(
|
||||
self,
|
||||
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
|
||||
train_dataset_config: Optional[DatasetConfig]=None,
|
||||
validate_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
|
||||
predict_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
|
||||
train_transform: Optional[Transform]=None,
|
||||
validate_transform: Optional[Transform]=None,
|
||||
predict_transform: Optional[Transform]=None,
|
||||
tokenizer: Optional[Tokenizer]=None,
|
||||
debug: bool=False,
|
||||
):
|
||||
super().__init__()
|
||||
self.process_fn = process_fn
|
||||
self.train_dataset_config = train_dataset_config
|
||||
self.validate_dataset_config = validate_dataset_config
|
||||
self.predict_dataset_config = predict_dataset_config
|
||||
self.train_transform = train_transform
|
||||
self.validate_transform = validate_transform
|
||||
self.predict_transform = predict_transform
|
||||
self.tokenizer = tokenizer
|
||||
self.debug = debug
|
||||
|
||||
if debug:
|
||||
print("\033[31mWARNING: debug mode, dataloader will be extremely slow !!!\033[0m")
|
||||
|
||||
# build train datapath
|
||||
if self.train_dataset_config is not None:
|
||||
self.train_datapath = self.train_dataset_config.datapath
|
||||
else:
|
||||
self.train_datapath = None
|
||||
|
||||
# build validate datapath
|
||||
if self.validate_dataset_config is not None:
|
||||
self.validate_datapath = {
|
||||
cls: self.validate_dataset_config[cls].datapath
|
||||
for cls in self.validate_dataset_config
|
||||
}
|
||||
else:
|
||||
self.validate_datapath = None
|
||||
|
||||
# build predict datapath
|
||||
if self.predict_dataset_config is not None:
|
||||
self.predict_datapath = {
|
||||
cls: self.predict_dataset_config[cls].datapath
|
||||
for cls in self.predict_dataset_config
|
||||
}
|
||||
else:
|
||||
self.predict_datapath = None
|
||||
|
||||
self.tokenizer = tokenizer
|
||||
|
||||
def prepare_data(self):
|
||||
pass
|
||||
|
||||
def train_dataloader(self) -> TRAIN_DATALOADERS:
|
||||
if self.train_dataset_config is None:
|
||||
raise ValueError("do not have train_dataset_config")
|
||||
if self.train_transform is None:
|
||||
raise ValueError("do not have train_transform")
|
||||
if self.train_datapath is not None:
|
||||
self._train_ds = RigDataset(
|
||||
process_fn=self.process_fn,
|
||||
data=self.train_datapath.get_data(),
|
||||
name="train",
|
||||
tokenizer=self.tokenizer,
|
||||
transform=self.train_transform,
|
||||
debug=self.debug,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
return self._create_dataloader(
|
||||
dataset=self._train_ds,
|
||||
config=self.train_dataset_config,
|
||||
is_train=True,
|
||||
drop_last=False,
|
||||
)
|
||||
|
||||
def val_dataloader(self) -> EVAL_DATALOADERS:
|
||||
if self.validate_dataset_config is None:
|
||||
raise ValueError("do not have validate_dataset_config")
|
||||
if self.validate_transform is None:
|
||||
raise ValueError("do not have validate_transform")
|
||||
if self.validate_datapath is not None:
|
||||
self._validation_ds = {}
|
||||
for cls in self.validate_datapath:
|
||||
self._validation_ds[cls] = RigDataset(
|
||||
process_fn=self.process_fn,
|
||||
data=self.validate_datapath[cls].get_data(),
|
||||
name=f"validate-{cls}",
|
||||
tokenizer=self.tokenizer,
|
||||
transform=self.validate_transform,
|
||||
debug=self.debug,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
return self._create_dataloader(
|
||||
dataset=self._validation_ds,
|
||||
config=self.validate_dataset_config,
|
||||
is_train=False,
|
||||
drop_last=False,
|
||||
)
|
||||
|
||||
def predict_dataloader(self):
|
||||
if self.predict_dataset_config is None:
|
||||
raise ValueError("do not have predict_dataset_config")
|
||||
if self.predict_transform is None:
|
||||
raise ValueError("do not have predict_transform")
|
||||
if self.predict_datapath is not None:
|
||||
self._predict_ds = {}
|
||||
for cls in self.predict_datapath:
|
||||
self._predict_ds[cls] = RigDataset(
|
||||
process_fn=self.process_fn,
|
||||
data=self.predict_datapath[cls].get_data(),
|
||||
name=f"predict-{cls}",
|
||||
tokenizer=self.tokenizer,
|
||||
transform=self.predict_transform,
|
||||
debug=self.debug,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
return self._create_dataloader(
|
||||
dataset=self._predict_ds,
|
||||
config=self.predict_dataset_config,
|
||||
is_train=False,
|
||||
drop_last=False,
|
||||
)
|
||||
|
||||
def _create_dataloader(
|
||||
self,
|
||||
dataset: Dataset|Dict[str, Dataset],
|
||||
config: DatasetConfig|Dict[str|None, DatasetConfig],
|
||||
is_train: bool,
|
||||
**kwargs,
|
||||
) -> DataLoader|Dict[str, DataLoader]:
|
||||
def create_single_dataloader(dataset, config: DatasetConfig, **kwargs):
|
||||
return DataLoader(
|
||||
dataset,
|
||||
batch_size=config.batch_size,
|
||||
shuffle=config.shuffle,
|
||||
num_workers=config.num_workers,
|
||||
pin_memory=config.pin_memory,
|
||||
persistent_workers=config.persistent_workers,
|
||||
collate_fn=dataset.collate_fn,
|
||||
**kwargs,
|
||||
)
|
||||
if isinstance(dataset, Dict):
|
||||
assert isinstance(config, dict)
|
||||
return {k: create_single_dataloader(v, config[k], **kwargs) for k, v in dataset.items()}
|
||||
else:
|
||||
assert isinstance(config, DatasetConfig)
|
||||
return create_single_dataloader(dataset, config, **kwargs)
|
||||
|
||||
class RigDataset(Dataset):
|
||||
def __init__(
|
||||
self,
|
||||
data: List[LazyAsset],
|
||||
transform: Transform,
|
||||
name: Optional[str]=None,
|
||||
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
|
||||
tokenizer: Optional[Tokenizer]=None,
|
||||
debug: bool=False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.data = data
|
||||
self.name = name
|
||||
self.process_fn = process_fn
|
||||
self.tokenizer = tokenizer
|
||||
self.transform = transform
|
||||
self.debug = debug
|
||||
|
||||
if not debug:
|
||||
assert self.process_fn is not None, 'missing data processing function'
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.data)
|
||||
|
||||
def __getitem__(self, idx) -> ModelInput:
|
||||
lazy_asset = self.data[idx]
|
||||
asset = lazy_asset.load()
|
||||
self.transform.apply(asset=asset)
|
||||
if self.tokenizer is not None and asset.parents is not None:
|
||||
x = TokenizeInput(
|
||||
joints=asset.joints,
|
||||
parents=asset.parents,
|
||||
cls=asset.cls,
|
||||
joint_names=asset.joint_names,
|
||||
)
|
||||
tokens = self.tokenizer.tokenize(input=x)
|
||||
else:
|
||||
tokens = None
|
||||
return ModelInput(asset=asset, tokens=tokens)
|
||||
|
||||
def _collate_fn_debug(self, batch):
|
||||
return batch
|
||||
|
||||
def _collate_fn(self, batch):
|
||||
processed_batch = self.process_fn(batch) # type: ignore
|
||||
processed_batch: List[Dict]
|
||||
|
||||
tensors_stack = {}
|
||||
tensors_cat = {}
|
||||
non_tensors = {}
|
||||
vis = {}
|
||||
def check(x):
|
||||
assert x not in vis, f"multiple keys found: {x}"
|
||||
vis[x] = True
|
||||
|
||||
for k, v in processed_batch[0].items():
|
||||
if k == "cat":
|
||||
assert isinstance(v, dict)
|
||||
for k1 in v.keys():
|
||||
check(k1)
|
||||
tensors_cat[k1] = []
|
||||
for i in range(len(processed_batch)):
|
||||
v1 = processed_batch[i]['cat'][k1]
|
||||
if isinstance(v1, ndarray):
|
||||
v1 = torch.from_numpy(v1)
|
||||
elif isinstance(v1, Tensor):
|
||||
v1 = v1
|
||||
else:
|
||||
raise ValueError(f"cannot concatenate non-tensor type of key {k1}, type: {type(v1)}")
|
||||
tensors_cat[k1].append(v1)
|
||||
elif k == "non":
|
||||
assert isinstance(v, dict)
|
||||
for k1 in v.keys():
|
||||
check(k1)
|
||||
non_tensors[k1] = []
|
||||
for i in range(len(processed_batch)):
|
||||
v1 = processed_batch[i]['non'][k1]
|
||||
if isinstance(v1, ndarray):
|
||||
v1 = torch.from_numpy(v1)
|
||||
non_tensors[k1].append(v1)
|
||||
else:
|
||||
check(k)
|
||||
tensors_stack[k] = []
|
||||
for i in range(len(processed_batch)):
|
||||
v1 = processed_batch[i][k]
|
||||
if isinstance(v1, ndarray):
|
||||
v1 = torch.from_numpy(v1)
|
||||
elif isinstance(v1, Tensor):
|
||||
v1 = v1
|
||||
else:
|
||||
raise ValueError(f"cannot stack type of key {k}, type: {type(v1)}")
|
||||
tensors_stack[k].append(v1)
|
||||
|
||||
collated_stack = {k: torch.stack(v) for k, v in tensors_stack.items()}
|
||||
collated_cat = {k: torch.concat(v, dim=1) for k, v in tensors_cat.items()}
|
||||
|
||||
collated_batch = {
|
||||
**collated_stack,
|
||||
**collated_cat,
|
||||
**non_tensors,
|
||||
}
|
||||
return collated_batch
|
||||
|
||||
def collate_fn(self, batch):
|
||||
if self.debug:
|
||||
return self._collate_fn_debug(batch)
|
||||
return self._collate_fn(batch)
|
||||
132
thirdparty/skintokens/src/data/order.py
vendored
Normal file
132
thirdparty/skintokens/src/data/order.py
vendored
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from numpy import ndarray
|
||||
from omegaconf import OmegaConf
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
|
||||
from .spec import ConfigSpec
|
||||
|
||||
@dataclass
|
||||
class Order(ConfigSpec):
|
||||
|
||||
# {part_name: [bone_name_1, bone_name_2, ...]}
|
||||
parts: Dict[str, Dict[str, List[str]]]
|
||||
|
||||
# parts of bones to be arranged in [part_name_1, part_name_2, ...]
|
||||
parts_order: Dict[str, List[str]]
|
||||
|
||||
# {skeleton_name: path}
|
||||
skeleton_path: Optional[Dict[str, str]]=None
|
||||
|
||||
sort_by_xyz: bool=False
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'Order':
|
||||
cls.check_keys(kwargs)
|
||||
skeleton_path = kwargs.get('skeleton_path', None)
|
||||
if skeleton_path is not None:
|
||||
parts = {}
|
||||
parts_order = {}
|
||||
for (cls, path) in skeleton_path.items():
|
||||
assert cls not in parts, 'cls conflicts'
|
||||
d = OmegaConf.load(path)
|
||||
parts[cls] = d.parts
|
||||
parts_order[cls] = d.parts_order
|
||||
else:
|
||||
parts = kwargs.get('parts')
|
||||
parts_order = kwargs.get('parts_order')
|
||||
assert parts is not None
|
||||
assert parts_order is not None
|
||||
return Order(
|
||||
skeleton_path=skeleton_path,
|
||||
parts=parts,
|
||||
parts_order=parts_order,
|
||||
sort_by_xyz=kwargs.get('sort_by_xyz', False),
|
||||
)
|
||||
|
||||
def part_exists(self, cls: str, part: str, names: List[str]) -> bool:
|
||||
'''
|
||||
Check if part exists.
|
||||
'''
|
||||
if part not in self.parts[cls]:
|
||||
return False
|
||||
for name in self.parts[cls][part]:
|
||||
if name not in names:
|
||||
return False
|
||||
return True
|
||||
|
||||
def make_names(self, cls: str|None, parts: List[str|None], num_bones: int) -> List[str]:
|
||||
'''
|
||||
Get names for specified cls.
|
||||
'''
|
||||
names = []
|
||||
for part in parts:
|
||||
if part is None: # spring
|
||||
continue
|
||||
if cls in self.parts and part in self.parts[cls]:
|
||||
names.extend(self.parts[cls][part])
|
||||
assert len(names) <= num_bones, "number of bones in required skeleton is more than existing bones"
|
||||
for i in range(len(names), num_bones):
|
||||
names.append(f"bone_{i}")
|
||||
return names
|
||||
|
||||
def arrange_names(self, cls: str|None, names: List[str], parents: List[int], joints: Optional[ndarray]=None) -> Tuple[List[str], Dict[int, str|None]]:
|
||||
'''
|
||||
Arrange names according to required parts order.
|
||||
'''
|
||||
def sort_by_xyz(joints):
|
||||
return sorted(joints, key=lambda joint: (joint[1][2], joint[1][0], joint[1][1]))
|
||||
|
||||
if self.sort_by_xyz:
|
||||
assert joints is not None
|
||||
new_names = []
|
||||
root = -1
|
||||
son = defaultdict(list)
|
||||
not_root = {}
|
||||
for (i, p) in enumerate(parents):
|
||||
if p != -1:
|
||||
son[p].append(i)
|
||||
not_root[i] = True
|
||||
for i in range(len(parents)):
|
||||
if not_root.get(i, False) == False:
|
||||
root = i
|
||||
break
|
||||
Q = [root]
|
||||
while Q:
|
||||
u = Q.pop(0)
|
||||
new_names.append(names[u])
|
||||
wait = []
|
||||
for v in son[u]:
|
||||
wait.append((v, joints[v]))
|
||||
wait_sorted = sort_by_xyz(wait)
|
||||
new_wait = [v for v, _ in wait_sorted]
|
||||
Q = new_wait + Q
|
||||
return new_names, {}
|
||||
if cls not in self.parts_order:
|
||||
return names, {0: None} # add a spring token
|
||||
vis = defaultdict(bool)
|
||||
name_to_id = {name: i for (i, name) in enumerate(names)}
|
||||
new_names = []
|
||||
parts_bias = {}
|
||||
for part in self.parts_order[cls]:
|
||||
if self.part_exists(cls=cls, part=part, names=names):
|
||||
for name in self.parts[cls][part]:
|
||||
vis[name] = True
|
||||
flag = False
|
||||
for name in self.parts[cls][part]:
|
||||
pid = parents[name_to_id[name]]
|
||||
if pid==-1:
|
||||
continue
|
||||
if not vis[names[pid]]:
|
||||
flag = True
|
||||
break
|
||||
if flag: # incorrect parts order and should immediately add a spring token
|
||||
break
|
||||
parts_bias[len(new_names)] = part
|
||||
new_names.extend(self.parts[cls][part])
|
||||
parts_bias[len(new_names)] = None # add a spring token
|
||||
for name in names:
|
||||
if name not in new_names:
|
||||
new_names.append(name)
|
||||
return new_names, parts_bias
|
||||
189
thirdparty/skintokens/src/data/sampler.py
vendored
Normal file
189
thirdparty/skintokens/src/data/sampler.py
vendored
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
from dataclasses import dataclass
|
||||
from abc import ABC, abstractmethod
|
||||
from numpy import ndarray
|
||||
from scipy.spatial import cKDTree # type: ignore
|
||||
from typing import Dict, Optional
|
||||
|
||||
import numpy as np
|
||||
import random
|
||||
|
||||
from ..rig_package.info.asset import Asset
|
||||
from ..rig_package.utils import sample_vertex_groups
|
||||
from .spec import ConfigSpec
|
||||
|
||||
@dataclass
|
||||
class SamplerResult():
|
||||
sampled_vertices: Optional[ndarray]=None
|
||||
sampled_normals: Optional[ndarray]=None
|
||||
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
|
||||
|
||||
# number of sampled skin
|
||||
skin_samples: Optional[int]=None
|
||||
|
||||
class Sampler(ABC):
|
||||
@abstractmethod
|
||||
def sample(
|
||||
self,
|
||||
asset: Asset,
|
||||
) -> SamplerResult:
|
||||
'''
|
||||
Return sampled vertices, sampled normals and vertex groups.
|
||||
'''
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def parse(cls, **kwargs) -> 'Sampler':
|
||||
pass
|
||||
|
||||
@dataclass
|
||||
class SamplerMix(Sampler, ConfigSpec):
|
||||
num_samples: int
|
||||
num_vertex_samples: int
|
||||
num_skin_samples: Optional[int]=None
|
||||
replace: bool=True
|
||||
all_skeleton: Optional[bool]=None
|
||||
max_distance: float=0.1
|
||||
rate_distance: float=0.1
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'SamplerMix':
|
||||
cls.check_keys(kwargs)
|
||||
return SamplerMix(
|
||||
num_samples=kwargs.get('num_samples', 0),
|
||||
num_vertex_samples=kwargs.get('num_vertex_samples', 0),
|
||||
num_skin_samples=kwargs.get('num_skin_samples', None),
|
||||
replace=kwargs.get('replace', True),
|
||||
all_skeleton=kwargs.get('all_skeleton', None),
|
||||
max_distance=kwargs.get('max_distance', 0.1),
|
||||
rate_distance=kwargs.get('rate_distance', 0.1),
|
||||
)
|
||||
|
||||
def sample_on_skin(
|
||||
self,
|
||||
skin: ndarray,
|
||||
vertices: ndarray,
|
||||
faces: ndarray,
|
||||
):
|
||||
face_has_skin = np.any(skin[faces] > 0, axis=-1)
|
||||
if face_has_skin.sum() == 0:
|
||||
face_has_skin = np.ones_like(face_has_skin)
|
||||
elif self.max_distance < 1e-5:
|
||||
return face_has_skin
|
||||
else:
|
||||
# sample near points
|
||||
p = np.unique(faces[face_has_skin].reshape(-1))
|
||||
tree = cKDTree(vertices[p])
|
||||
dis, _ = tree.query(vertices, k=1)
|
||||
dis_skin = np.sqrt(((np.max(vertices[p], axis=0) - np.min(vertices[p], axis=0))**2).sum())
|
||||
mask_face_near = np.any(dis[faces] < min(self.max_distance, dis_skin * self.rate_distance), axis=-1)
|
||||
face_has_skin |= mask_face_near
|
||||
return face_has_skin
|
||||
|
||||
def sample(
|
||||
self,
|
||||
asset: Asset,
|
||||
) -> SamplerResult:
|
||||
if asset.vertices is None:
|
||||
raise ValueError("do not have vertices")
|
||||
if asset.faces is None:
|
||||
raise ValueError("do not have faces")
|
||||
vertex_groups = []
|
||||
mapping = {}
|
||||
tot = 0
|
||||
for k, v in asset.vertex_groups.items():
|
||||
if v.ndim == 1:
|
||||
v = v[:, None]
|
||||
elif v.ndim != 2:
|
||||
raise ValueError(f"ndim of key {k} is {v.ndim}")
|
||||
s = tot
|
||||
e = tot + v.shape[1]
|
||||
mapping[k] = slice(s,e)
|
||||
vertex_groups.append(v)
|
||||
if len(vertex_groups) > 0:
|
||||
vertex_groups = np.concatenate(vertex_groups, axis=1)
|
||||
else:
|
||||
vertex_groups = None
|
||||
final_sampled_vertices, final_sampled_normals, sampled_vertex_groups = sample_vertex_groups(
|
||||
vertices=asset.vertices,
|
||||
faces=asset.faces,
|
||||
num_samples=self.num_samples,
|
||||
vertex_normals=asset.vertex_normals,
|
||||
face_normals=asset.face_normals,
|
||||
vertex_groups=vertex_groups,
|
||||
face_mask=None,
|
||||
shuffle=True,
|
||||
same=True,
|
||||
)
|
||||
if vertex_groups is not None:
|
||||
final_sampled_vertices = final_sampled_vertices[:, 0]
|
||||
if final_sampled_normals is not None:
|
||||
final_sampled_normals = final_sampled_normals[:, 0]
|
||||
final_sampled_vertex_groups = {}
|
||||
if sampled_vertex_groups is not None:
|
||||
for k, s in mapping.items():
|
||||
final_sampled_vertex_groups[k] = sampled_vertex_groups[:, s] # (N, k)
|
||||
if vertex_groups is not None and self.num_skin_samples is not None:
|
||||
dense_vertices = []
|
||||
dense_normals = []
|
||||
dense_skin = []
|
||||
if 'skin' not in mapping:
|
||||
raise ValueError("do not have skin")
|
||||
if self.all_skeleton:
|
||||
dense_indices = [i for i in range(asset.J)]
|
||||
else:
|
||||
dense_indices = [random.randint(0, asset.J-1)]
|
||||
for indice in dense_indices:
|
||||
_s = asset.vertex_groups['skin'][:, indice]
|
||||
face_has_skin = self.sample_on_skin(
|
||||
skin=_s,
|
||||
vertices=asset.vertices,
|
||||
faces=asset.faces,
|
||||
)
|
||||
sampled_vertices, sampled_normals, sampled_skin = sample_vertex_groups(
|
||||
vertices=asset.vertices,
|
||||
faces=asset.faces,
|
||||
vertex_normals=asset.vertex_normals,
|
||||
face_normals=asset.face_normals,
|
||||
vertex_groups=_s,
|
||||
num_samples=self.num_skin_samples,
|
||||
num_vertex_samples=self.num_vertex_samples,
|
||||
face_mask=face_has_skin,
|
||||
shuffle=True,
|
||||
same=True,
|
||||
)
|
||||
assert sampled_skin is not None
|
||||
assert sampled_skin.ndim == 2
|
||||
dense_vertices.append(sampled_vertices[:, 0])
|
||||
if sampled_normals is not None:
|
||||
dense_normals.append(sampled_normals[:, 0])
|
||||
dense_skin.append(sampled_skin[:, 0])
|
||||
dense_vertices = np.stack(dense_vertices, axis=0) # (J, m, 3)
|
||||
if len(dense_normals) > 0:
|
||||
dense_normals = np.stack(dense_normals, axis=0) # (J, m, 3)
|
||||
else:
|
||||
dense_normals = None
|
||||
dense_skin = np.stack(dense_skin, axis=0) # (J, m, 1)
|
||||
final_sampled_vertex_groups['skin'] = final_sampled_vertex_groups['skin'][:, dense_indices]
|
||||
if asset.meta is None:
|
||||
asset.meta = {}
|
||||
asset.meta['dense_vertices'] = dense_vertices
|
||||
asset.meta['dense_normals'] = dense_normals
|
||||
asset.meta['dense_skin'] = dense_skin
|
||||
asset.meta['dense_indices'] = dense_indices
|
||||
return SamplerResult(
|
||||
sampled_vertices=final_sampled_vertices,
|
||||
sampled_normals=final_sampled_normals if final_sampled_normals is not None else None,
|
||||
sampled_vertex_groups=final_sampled_vertex_groups,
|
||||
skin_samples=self.num_skin_samples,
|
||||
)
|
||||
|
||||
def get_sampler(**kwargs) -> Sampler:
|
||||
__target__ = kwargs.get('__target__')
|
||||
assert __target__ is not None
|
||||
del kwargs['__target__']
|
||||
if __target__ == 'mix':
|
||||
sampler = SamplerMix.parse(**kwargs)
|
||||
else:
|
||||
raise ValueError(f"sampler method {__target__} not supported")
|
||||
return sampler
|
||||
16
thirdparty/skintokens/src/data/spec.py
vendored
Normal file
16
thirdparty/skintokens/src/data/spec.py
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from dataclasses import fields
|
||||
|
||||
class ConfigSpec(ABC):
|
||||
@classmethod
|
||||
def check_keys(cls, config, expect=None):
|
||||
if expect is None:
|
||||
expect = [field.name for field in fields(cls)] # type: ignore
|
||||
for key in config.keys():
|
||||
if key not in expect:
|
||||
raise ValueError(f"expect names {expect} in {cls.__name__}, found {key}")
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def parse(cls, **kwargs) -> 'ConfigSpec':
|
||||
raise NotImplementedError()
|
||||
70
thirdparty/skintokens/src/data/transform.py
vendored
Normal file
70
thirdparty/skintokens/src/data/transform.py
vendored
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
from ..rig_package.info.asset import Asset
|
||||
from .augment import Augment, get_augments
|
||||
from .order import Order
|
||||
from .sampler import Sampler, get_sampler
|
||||
from .spec import ConfigSpec
|
||||
from .vertex_group import VertexGroup, get_vertex_groups
|
||||
|
||||
@dataclass
|
||||
class Transform(ConfigSpec):
|
||||
|
||||
order: Optional[Order]=None
|
||||
|
||||
vertex_groups: Optional[List[VertexGroup]]=None
|
||||
|
||||
augments: Optional[List[Augment]]=None
|
||||
|
||||
sampler: Optional[Sampler]=None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'Transform':
|
||||
cls.check_keys(kwargs)
|
||||
order_config = kwargs.get('order')
|
||||
vertex_groups_config = kwargs.get('vertex_groups')
|
||||
augments_config = kwargs.get('augments')
|
||||
sampler_config = kwargs.get('sampler')
|
||||
|
||||
d = {}
|
||||
if order_config is not None:
|
||||
d['order'] = Order.parse(**order_config)
|
||||
if vertex_groups_config is not None:
|
||||
d['vertex_groups'] = get_vertex_groups(*vertex_groups_config)
|
||||
if augments_config is not None:
|
||||
d['augments'] = get_augments(*augments_config)
|
||||
if sampler_config is not None:
|
||||
d['sampler'] = get_sampler(**sampler_config)
|
||||
return Transform(**d)
|
||||
|
||||
def apply(self, asset: Asset, **kwargs):
|
||||
|
||||
# 1. arrange bones
|
||||
if self.order is not None:
|
||||
if asset.joint_names is not None and asset.parents is not None:
|
||||
new_names, _ = self.order.arrange_names(cls=asset.cls, names=asset.joint_names, parents=asset.parents.tolist())
|
||||
asset.set_order(new_orders=new_names) # type: ignore
|
||||
|
||||
# 2. collapse must perform first
|
||||
if self.augments is not None:
|
||||
kwargs = {}
|
||||
for augment in self.augments:
|
||||
augment.transform(asset=asset, **kwargs)
|
||||
|
||||
# 3. get vertex groups
|
||||
if self.vertex_groups is not None:
|
||||
d = {}
|
||||
for v in self.vertex_groups:
|
||||
d.update(v.get_vertex_group(asset=asset))
|
||||
asset.vertex_groups = d
|
||||
else:
|
||||
asset.vertex_groups = {}
|
||||
|
||||
# 4. sample
|
||||
if self.sampler is not None:
|
||||
res = self.sampler.sample(asset=asset)
|
||||
asset.sampled_vertices = res.sampled_vertices
|
||||
asset.sampled_normals = res.sampled_normals
|
||||
asset.sampled_vertex_groups = res.sampled_vertex_groups
|
||||
asset.skin_samples = res.skin_samples
|
||||
257
thirdparty/skintokens/src/data/vertex_group.py
vendored
Normal file
257
thirdparty/skintokens/src/data/vertex_group.py
vendored
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from collections import defaultdict
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from numpy import ndarray
|
||||
from scipy.spatial import cKDTree # type: ignore
|
||||
from scipy.sparse import csr_matrix
|
||||
from scipy.sparse.csgraph import shortest_path, connected_components
|
||||
from typing import Dict, List, Optional, Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..rig_package.info.asset import Asset
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VertexGroup(ABC):
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def parse(cls, **kwargs) -> 'VertexGroup':
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
|
||||
pass
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VertexGroupSkin(VertexGroup):
|
||||
"""capture skin"""
|
||||
|
||||
normalize: bool=True
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'VertexGroupSkin':
|
||||
return VertexGroupSkin(normalize=kwargs.get('normalize', True))
|
||||
|
||||
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
|
||||
if asset.skin is None:
|
||||
raise ValueError("do not have skin")
|
||||
if self.normalize:
|
||||
asset.normalize_skin()
|
||||
return {'skin': asset.skin.copy()}
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VertexGroupVoxelSkin(VertexGroup):
|
||||
"""capture voxel skin"""
|
||||
|
||||
grid: int
|
||||
alpha: float
|
||||
link_dis: float
|
||||
grid_query: int
|
||||
vertex_query: int
|
||||
grid_weight: float
|
||||
mode: Literal['square', 'exp']
|
||||
|
||||
@classmethod
|
||||
def parse(cls, **kwargs) -> 'VertexGroupVoxelSkin':
|
||||
return VertexGroupVoxelSkin(
|
||||
grid=kwargs.get('grid', 64),
|
||||
alpha=kwargs.get('alpha', 0.5),
|
||||
link_dis=kwargs.get('link_dis', 0.00001),
|
||||
grid_query=kwargs.get('grid_query', 27),
|
||||
vertex_query=kwargs.get('vertex_query', 27),
|
||||
grid_weight=kwargs.get('grid_weight', 3.0),
|
||||
mode=kwargs.get('mode', 'square'),
|
||||
)
|
||||
|
||||
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
|
||||
if asset.vertices is None:
|
||||
raise ValueError("do not have vertices")
|
||||
if asset.faces is None:
|
||||
raise ValueError("do not have faces")
|
||||
if asset.joints is None:
|
||||
raise ValueError("do not have joints")
|
||||
# normalize into [-1, 1] first
|
||||
min_vals = np.min(asset.vertices, axis=0)
|
||||
max_vals = np.max(asset.vertices, axis=0)
|
||||
|
||||
center = (min_vals + max_vals) / 2
|
||||
|
||||
scale = np.max(max_vals - min_vals) / 2
|
||||
|
||||
normalized_vertices = (asset.vertices - center) / scale
|
||||
normalized_joints = (asset.joints - center) / scale
|
||||
|
||||
grid_coords = asset.voxel().coords
|
||||
skin = voxel_skin(
|
||||
grid=self.grid,
|
||||
grid_coords=grid_coords,
|
||||
joints=normalized_joints,
|
||||
vertices=normalized_vertices,
|
||||
faces=asset.faces,
|
||||
alpha=self.alpha,
|
||||
link_dis=self.link_dis,
|
||||
grid_query=self.grid_query,
|
||||
vertex_query=self.vertex_query,
|
||||
grid_weight=self.grid_weight,
|
||||
mode=self.mode,
|
||||
)
|
||||
skin = np.nan_to_num(skin, nan=0., posinf=0., neginf=0.)
|
||||
return {'voxel_skin': skin,}
|
||||
|
||||
def voxel_skin(
|
||||
grid: int,
|
||||
grid_coords: ndarray, # (M, 3)
|
||||
joints: ndarray, # (J, 3)
|
||||
vertices: ndarray, # (N, 3)
|
||||
faces: ndarray, # (F, 3)
|
||||
alpha: float=0.5,
|
||||
link_dis: float=0.00001,
|
||||
grid_query: int=27,
|
||||
vertex_query: int=27,
|
||||
grid_weight: float=3.0,
|
||||
voxel_size: Optional[float]=None,
|
||||
mode: str='square',
|
||||
parents: Optional[ndarray]=None,
|
||||
):
|
||||
# modified from https://dl.acm.org/doi/pdf/10.1145/2485895.2485919
|
||||
assert mode in ['square', 'exp']
|
||||
J = joints.shape[0]
|
||||
M = grid_coords.shape[0]
|
||||
N = vertices.shape[0]
|
||||
|
||||
if voxel_size is None:
|
||||
_range = 2/grid*1.74
|
||||
else:
|
||||
_range = voxel_size*1.74
|
||||
|
||||
grid_tree = cKDTree(grid_coords)
|
||||
vertex_tree = cKDTree(vertices)
|
||||
if parents is not None:
|
||||
son = defaultdict(list)
|
||||
for i, p in enumerate(parents):
|
||||
if i == -1:
|
||||
continue
|
||||
son[p].append(i)
|
||||
divide_joints = []
|
||||
joints_map = []
|
||||
for u in range(len(parents)):
|
||||
if len(son[u]) != 1:
|
||||
divide_joints.append(joints[u])
|
||||
joints_map.append(u)
|
||||
else:
|
||||
pu = joints[u]
|
||||
pv = joints[son[u][0]]
|
||||
seg = 10
|
||||
for i in range(seg+1):
|
||||
p = (pu*i + pv*(seg-i)) / seg
|
||||
divide_joints.append(p)
|
||||
joints_map.append(u)
|
||||
divide_joints = np.stack(divide_joints)
|
||||
joints_map = np.array(joints_map)
|
||||
else:
|
||||
divide_joints = joints
|
||||
joints_map = np.arange(joints.shape[0])
|
||||
joint_tree = cKDTree(divide_joints)
|
||||
|
||||
# make combined vertices
|
||||
# 0 ~ N-1: mesh vertices
|
||||
# N ~ N+M-1: grid vertices
|
||||
combined_vertices = np.concatenate([vertices, grid_coords], axis=0)
|
||||
|
||||
# link adjacent grids
|
||||
dist, idx = grid_tree.query(grid_coords, grid_query) # 3*3*3
|
||||
dist = dist[:, 1:]
|
||||
idx = idx[:, 1:]
|
||||
mask = (0 < dist) & (dist < _range)
|
||||
source_grid2grid = np.repeat(np.arange(M), grid_query-1)[mask.ravel()] + N
|
||||
to_grid2grid = idx[mask] + N
|
||||
weight_grid2grid = dist[mask] * grid_weight
|
||||
|
||||
# link very close vertices
|
||||
dist, idx = vertex_tree.query(vertices, 4)
|
||||
dist = dist[:, 1:]
|
||||
idx = idx[:, 1:]
|
||||
mask = (0 < dist) & (dist < link_dis)
|
||||
source_close = np.repeat(np.arange(N), 3)[mask.ravel()]
|
||||
to_close = idx[mask]
|
||||
weight_close = dist[mask]
|
||||
|
||||
# link grids to mesh vertices
|
||||
dist, idx = vertex_tree.query(grid_coords, vertex_query)
|
||||
mask = (0 < dist) & (dist < _range) # sqrt(3)
|
||||
source_grid2vertex = np.repeat(np.arange(M), vertex_query)[mask.ravel()] + N
|
||||
to_grid2vertex = idx[mask]
|
||||
weight_grid2vertex = dist[mask]
|
||||
|
||||
# build combined vertices tree
|
||||
combined_tree = cKDTree(combined_vertices)
|
||||
# link bones to the neartest vertices
|
||||
_, joint_indices = combined_tree.query(divide_joints)
|
||||
|
||||
# build graph
|
||||
source_vertex2vertex = np.concatenate([faces[:, 0], faces[:, 1], faces[:, 2]], axis=0)
|
||||
to_vertex2vertex = np.concatenate([faces[:, 1], faces[:, 2], faces[:, 0]], axis=0)
|
||||
weight_vertex2vertex = np.sqrt(((vertices[source_vertex2vertex] - vertices[to_vertex2vertex])**2).sum(axis=-1))
|
||||
graph = csr_matrix(
|
||||
(np.concatenate([weight_close, weight_vertex2vertex, weight_grid2grid, weight_grid2vertex]),
|
||||
(
|
||||
np.concatenate([source_close, source_vertex2vertex, source_grid2grid, source_grid2vertex], axis=0),
|
||||
np.concatenate([to_close, to_vertex2vertex, to_grid2grid, to_grid2vertex], axis=0)),
|
||||
),
|
||||
shape=(N+M, N+M),
|
||||
)
|
||||
|
||||
# get shortest path (J, N+M)
|
||||
dist_matrix = shortest_path(graph, method='D', directed=False, indices=joint_indices)
|
||||
|
||||
# (sum_J, N)
|
||||
dis_vertex2bone = dist_matrix[:, :N]
|
||||
unreachable = np.isinf(dis_vertex2bone).all(axis=0)
|
||||
k = min(J, 3)
|
||||
dist, idx = joint_tree.query(vertices[unreachable], k)
|
||||
|
||||
# make sure at least one value in dis is not inf
|
||||
unreachable_indices = np.where(unreachable)[0]
|
||||
row_indices = idx
|
||||
col_indices = np.repeat(unreachable_indices, k).reshape(-1, k)
|
||||
dis_vertex2bone[row_indices, col_indices] = dist
|
||||
|
||||
finite_vals = dis_vertex2bone[np.isfinite(dis_vertex2bone)]
|
||||
max_dis = np.max(finite_vals)
|
||||
dis_vertex2bone = np.nan_to_num(dis_vertex2bone, nan=max_dis, posinf=max_dis, neginf=max_dis)
|
||||
dis_vertex2bone = np.maximum(dis_vertex2bone, 1e-6)
|
||||
|
||||
# turn dis2bone to dis2vertex
|
||||
dis_vertex2joint = np.full((joints.shape[0], vertices.shape[0]), max_dis)
|
||||
for i in range(len(dis_vertex2bone)):
|
||||
dis_vertex2joint[joints_map[i]] = np.minimum(dis_vertex2bone[i], dis_vertex2joint[joints_map[i]])
|
||||
|
||||
# (J, N)
|
||||
if mode == 'exp':
|
||||
skin = np.exp(-dis_vertex2joint / max_dis * 20.0)
|
||||
elif mode == 'square':
|
||||
skin = (1./((1-alpha)*dis_vertex2joint + alpha*dis_vertex2joint**2))**2
|
||||
else:
|
||||
assert False, f'invalid mode: {mode}'
|
||||
skin = skin / skin.sum(axis=0)
|
||||
# (N, J)
|
||||
skin = skin.transpose()
|
||||
return skin
|
||||
|
||||
def get_vertex_groups(*args) -> List[VertexGroup]:
|
||||
vertex_groups = []
|
||||
MAP = {
|
||||
'skin': VertexGroupSkin,
|
||||
'voxel_skin': VertexGroupVoxelSkin,
|
||||
}
|
||||
MAP: Dict[str, type[VertexGroup]]
|
||||
for (i, c) in enumerate(args):
|
||||
__target__ = c.get('__target__')
|
||||
assert __target__ is not None, f"do not find `__target__` in config of vertex_groups of position {i}"
|
||||
assert __target__ in MAP, f"expect: [{','.join(MAP.keys())}], found: {__target__}"
|
||||
c = deepcopy(c)
|
||||
del c['__target__']
|
||||
vertex_groups.append(MAP[__target__].parse(**c))
|
||||
return vertex_groups
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
{
|
||||
"version": "2.1.1",
|
||||
"message": "ComfyUI custom models folder, Kanban: Can add more meshes/images from any column"
|
||||
"version": "2.1.2",
|
||||
"message": "Fixed Desktop App on Linux - ComfyUI: Added Enums - Wireframe in Mesh Previewer"
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue