Skip to content

[SIGGRAPH Asia 2026] UniMate: One Unified Model to Animate Diverse Skeletons

Python

Fix stale stage-4 caches and metadata, check canonical GLBs and sampled motions against their cond's canonical frame, keep texture sidecars from replacing each other, and reject malformed quaternion patches and over-long caption rewrites

Friedrich-M5febc2d11f78
diff --git a/data_process/feature_extraction/canonical_assets.py b/data_process/feature_extraction/canonical_assets.py
index f097e76..fe18fc3 100644
--- a/data_process/feature_extraction/canonical_assets.py
+++ b/data_process/feature_extraction/canonical_assets.py
@@ -17,7 +17,12 @@ clip of that object type (``<features_dir>/motions/*.npz``: ``local_rotations``
The joint order rides in the GLB as ``canonical_joint_order`` and a digest of
its inputs (the cond entry, its diameter, the source GLB's bytes and
``BAKE_VERSION``) as ``canonical_cond_digest``: an asset whose cond or source
-changed is rebuilt on the next run, the others are skipped. A skeleton whose
+changed is rebuilt on the next run, the others are skipped. The cond's frame
+alone (``asset_files.cond_frame_digest``) rides along as
+``canonical_frame_digest``: an asset whose source GLB is gone (an object type
+of the cond, or a Mixamo character with a canonical GLB but no ``rigs/`` GLB)
+keeps its canonical GLB only while that matches the cond, and one without the
+key cannot be checked and is kept. Mesh driving checks the same key. A skeleton whose
roll about its joint line the fit cannot determine (collinear joints, or nearly
collinear ones for the fit's residual) is refused.
@@ -70,8 +75,9 @@ from Quaternions import Quaternions # noqa: E402
from data_process.mesh_animation.canonical_rig import UndeterminedRoll, bake_canonical_asset # noqa: E402
from data_process.utils.asset_files import ( # noqa: E402
- GLB_ERRORS_DIR, PROCESSED_GLB_DIR, TEXTURE_ISSUES_DIR,
- default_assets_dir, glb_image_digests, glb_node_extra, write_note,
+ FRAME_DIGEST_KEY, GLB_ERRORS_DIR, PROCESSED_GLB_DIR, TEXTURE_ISSUES_DIR,
+ cond_digest, cond_frame_digest, default_assets_dir, glb_image_digests, glb_node_extra,
+ write_note,
)
from data_process.utils.blender_export import ( # noqa: E402
import_gltf, load_scene, prepare_skeleton,
@@ -80,6 +86,8 @@ from data_process.utils.motion_features import process_tpose # noqa: E402
from data_process.utils.skeleton import get_skeleton_diameter, line_ratio # noqa: E402
DIGEST_KEY = 'canonical_cond_digest'
+# Every file a bake can write for an asset (bake_canonical_asset's formats).
+CANONICAL_FORMATS = ('glb', 'fbx')
# Mixamo characters: the clips' rest root in the canonical frame (module docstring).
MOTION_ROOT_KEY = 'canonical_motion_rest_root'
# Part of every digest: bump it when the bake's output changes for the same
@@ -87,17 +95,6 @@ MOTION_ROOT_KEY = 'canonical_motion_rest_root'
BAKE_VERSION = 'v3'
-def cond_digest(entry):
- """sha1 of what the baked asset depends on: joint names, hierarchy and
- the canonical T-pose (rounded to 1e-6)."""
- h = hashlib.sha1()
- h.update(json.dumps([str(n) for n in entry['joint_names']]).encode())
- h.update(np.asarray(entry['parents'], dtype=np.int64).tobytes())
- for key in ('tpos_first_frame', 'tpos_global_rotations'):
- h.update(np.round(np.asarray(entry[key], dtype=np.float64), 6).tobytes())
- return h.hexdigest()
-
-
def cond_diameter(entry):
"""The leaf-to-leaf diameter of the cond's canonical T-pose: stage 4's
``--target_diameter``, recovered from the cond itself (rounded to 1e-4)."""
@@ -207,6 +204,23 @@ def _texture_note(assets_dir, name, source, baked):
logger.warning(f"'{name}': canonical GLB lost image(s) {lost}")
+def _shard(name, num_workers):
+ """The worker (of *num_workers*) that handles asset *name*."""
+ return int(hashlib.sha1(name.encode()).hexdigest(), 16) % num_workers
+
+
+def _remove_asset_files(out_dir, name, partial=None):
+ """Remove ``<name>.<fmt>`` for every format a bake can write (a run asks
+ for fewer than an earlier one may have written), the ``<partial>.<fmt>``
+ files of a broken bake and the asset's texture note."""
+ for fmt in CANONICAL_FORMATS:
+ for path in [os.path.join(out_dir, f'{name}.{fmt}')] + \
+ ([f'{partial}.{fmt}'] if partial else []):
+ if os.path.isfile(path):
+ os.remove(path)
+ write_note(out_dir, TEXTURE_ISSUES_DIR, name, [])
+
+
def bake_canonical_assets(export_dir, features_dir, assets_dir=None, dataset_type=None,
object_types=None, worker_id=0, num_workers=1, overwrite=False,
formats=('glb',)):
@@ -214,8 +228,10 @@ def bake_canonical_assets(export_dir, features_dir, assets_dir=None, dataset_typ
defaults to :func:`default_assets_dir`), plus ``<object_type>.fbx`` when
*formats* holds ``'fbx'`` (the GLB is always written: it carries the digest).
- Returns ``{'baked': n, 'up_to_date': n, 'no_source': n, 'refused': n,
- 'failed': n}`` (refused: collinear skeletons, an expected outcome).
+ Returns ``{'baked': n, 'up_to_date': n, 'no_source': n, 'stale_removed': n,
+ 'refused': n, 'failed': n}`` (refused: collinear skeletons, an expected
+ outcome; stale_removed: the no_source assets whose GLB was baked from
+ another cond frame and was removed with its other formats).
"""
if not 0 <= worker_id < num_workers:
raise ValueError(f"worker_id {worker_id} not in [0, {num_workers})")
@@ -227,21 +243,34 @@ def bake_canonical_assets(export_dir, features_dir, assets_dir=None, dataset_typ
# (asset name, source GLB, object type) per character.
if 'mixamo' not in cond:
raise ValueError(f"{features_dir}/cond.npy has no 'mixamo' entry")
- chars = sorted(f[:-4] for f in os.listdir(src_dir)
- if f.endswith('.glb') and not f.startswith('.')) \
- if os.path.isdir(src_dir) else []
+ # Characters with a canonical GLB but no source are checked too.
+ chars = sorted({f[:-4] for d in (src_dir, out_dir) if os.path.isdir(d)
+ for f in os.listdir(d) if f.endswith('.glb') and not f.startswith('.')})
jobs = [(c, os.path.join(src_dir, f'{c}.glb'), 'mixamo') for c in chars
if object_types is None or c in object_types]
else:
types = sorted(cond) if object_types is None else [t for t in object_types if t in cond]
jobs = [(t, os.path.join(src_dir, f'{t}.glb'), t) for t in types]
- jobs = jobs[worker_id::num_workers]
- counts = {'baked': 0, 'up_to_date': 0, 'no_source': 0, 'refused': 0, 'failed': 0}
+ # A worker's share is fixed by the asset name, not by its position in the
+ # list: a worker that removes a stale Mixamo GLB changes the listing the
+ # workers started after it see.
+ jobs = [job for job in jobs if _shard(job[0], num_workers) == worker_id]
+ counts = {'baked': 0, 'up_to_date': 0, 'no_source': 0, 'stale_removed': 0,
+ 'refused': 0, 'failed': 0}
for name, source, object_type in jobs:
+ final = os.path.join(out_dir, f'{name}.glb')
+ frame = cond_frame_digest(cond[object_type])
if not os.path.isfile(source):
counts['no_source'] += 1
+ stored = glb_node_extra(final, FRAME_DIGEST_KEY)
+ if stored is not None and frame is not None and stored != frame:
+ # Baked from another cond and cannot be rebuilt: it would be
+ # driven as if current.
+ _remove_asset_files(out_dir, name)
+ logger.warning(f"Canonical GLB of '{name}' removed: it was baked from "
+ f"another cond frame and its source {source} is gone")
+ counts['stale_removed'] += 1
continue
- final = os.path.join(out_dir, f'{name}.glb')
extra_files = [(fmt, os.path.join(out_dir, f'{name}.{fmt}'))
for fmt in formats if fmt != 'glb']
# What the GLB is built from: the cond entry (and its diameter, which
@@ -268,7 +297,8 @@ def bake_canonical_assets(export_dir, features_dir, assets_dir=None, dataset_typ
_check_not_collinear(target)
bake_canonical_asset(source, target, partial,
formats=('glb',) + tuple(fmt for fmt, _ in extra_files),
- extra_props={DIGEST_KEY: digest, **extra})
+ extra_props={DIGEST_KEY: digest, FRAME_DIGEST_KEY: frame,
+ **extra})
for fmt, path in extra_files:
os.replace(f'{partial}.{fmt}', path)
os.replace(partial + '.glb', final)
@@ -281,11 +311,7 @@ def bake_canonical_assets(export_dir, features_dir, assets_dir=None, dataset_typ
counts['failed'] += 1
write_note(out_dir, GLB_ERRORS_DIR, name, [f'{type(exc).__name__}: {exc}'])
# A GLB of older inputs would be driven as if current: remove it.
- for stale in [partial + '.glb', final] + [p for _, p in extra_files] \
- + [f'{partial}.{fmt}' for fmt, _ in extra_files]:
- if os.path.isfile(stale):
- os.remove(stale)
- write_note(out_dir, TEXTURE_ISSUES_DIR, name, [])
+ _remove_asset_files(out_dir, name, partial)
continue
write_note(out_dir, GLB_ERRORS_DIR, name, [])
try:
diff --git a/data_process/feature_extraction/extract_features.py b/data_process/feature_extraction/extract_features.py
index 02f6bad..13ec2f7 100644
--- a/data_process/feature_extraction/extract_features.py
+++ b/data_process/feature_extraction/extract_features.py
@@ -209,12 +209,14 @@ def parse_args(argv=None):
help="Path to the body-plan category JSON copied into "
"the feature dir (the training loader reads it for "
"objects_subset). Default 'auto' uses "
- "<data_dir>/category_groups.json if present. Pass "
+ "<data_dir>/category_groups.json if present; "
+ "with none, an earlier run's copy is removed. Pass "
"an empty string to leave it out — the stage-2 "
"classifier may still be running, and a partial "
"file would land in the feature dir as if it were "
- "complete. Copy the finished file in afterwards; "
- "nothing else in this stage reads it.")
+ "complete. Copy the finished file in afterwards "
+ "(a later run with an empty string leaves it in "
+ "place); nothing else in this stage reads it.")
# Execution
parser.add_argument("--num_workers", type=int, default=1,
help="Parallel worker processes (object types are independent)")
@@ -608,8 +610,10 @@ def process_object_task(task):
Failures are contained here: the object is reported as failed (and its
error appended to ``extract_errors.log``) instead of propagating, which
- with ``mp.Pool`` would kill the whole run. No cache entry is written for
- a failed object, so it is retried on the next run.
+ with ``mp.Pool`` would kill the whole run. On a cache miss the old entry
+ is removed before the object's clips are pruned, and no entry is written
+ for a failed object, so it is retried on the next run whatever its
+ settings.
Returns ``(object_type, result_dict, from_cache)``.
"""
@@ -626,12 +630,16 @@ def process_object_task(task):
if cached is not None:
return object_type, cached, True
- removed = _prune_object_clips(task['save_dir'], clip_prefix, task['save_vis'])
- if removed:
- logger.info(f'[{object_type}] removed {removed} clip files from a '
- f'previous run before re-processing')
-
try:
+ # The stale entry goes before the clips it describes: a run that
+ # fails below must not leave an entry that a later run with the old
+ # settings would reuse without its clips.
+ if os.path.isfile(part_path):
+ os.remove(part_path)
+ removed = _prune_object_clips(task['save_dir'], clip_prefix, task['save_vis'])
+ if removed:
+ logger.info(f'[{object_type}] removed {removed} clip files from a '
+ f'previous run before re-processing')
obj_cond, n_clips, n_frames, n_joints, filtered = process_object(
object_type, **task)
except Exception as e: # noqa: BLE001 — keep the batch going
@@ -812,7 +820,8 @@ def main(args):
all_captions = save_outputs(args.save_dir, cond, all_filtered_clips,
category_groups=category_groups,
- extra_captions=extra_captions)
+ extra_captions=extra_captions,
+ keep_category_groups=args.category_groups == '')
stats = build_stats(clips_per_object, joints_per_object, total_frames, max_njoints)
print_summary(stats)
save_metadata_report(args.save_dir, stats, all_filtered_clips,
diff --git a/data_process/feature_extraction/metadata.py b/data_process/feature_extraction/metadata.py
index aceb1cc..d11afd8 100644
--- a/data_process/feature_extraction/metadata.py
+++ b/data_process/feature_extraction/metadata.py
@@ -268,6 +268,14 @@ def collect_captions(cond):
return all_captions
+def _remove_stale(save_dir, name, why):
+ """Remove ``<save_dir>/<name>`` left by an earlier run, if any."""
+ path = pjoin(save_dir, name)
+ if os.path.isfile(path):
+ os.remove(path)
+ print(f'Removed stale {path} ({why} this run)')
+
+
def save_extra_captions(save_dir, all_captions, version, export_captions):
"""Write ``captions_<version>.json`` (keyed like ``captions.json``) from
the export's ``motion_captions_<version>.json`` map, or remove a stale
@@ -281,14 +289,13 @@ def save_extra_captions(save_dir, all_captions, version, export_captions):
missing = sorted(set(all_captions) - set(out))
print(f'Saved {len(out)}/{len(all_captions)} {version} clip captions'
+ (f'; {len(missing)} saved clips have none, e.g. {missing[:3]}' if missing else ''))
- elif os.path.isfile(path):
- os.remove(path)
- print(f'Removed stale {path} (no {version} captions this run)')
+ else:
+ _remove_stale(save_dir, f'captions_{version}.json', f'no {version} captions')
return out
def save_outputs(save_dir, cond, all_filtered_clips, category_groups=None,
- extra_captions=None):
+ extra_captions=None, keep_category_groups=False):
"""Save ``cond.npy``, filtered clips, captions, and category groupings.
Caption files, keyed alike by saved clip (``<clip>-<NNN>``):
@@ -300,7 +307,13 @@ def save_outputs(save_dir, cond, all_filtered_clips, category_groups=None,
never re-processes an object; a version without captions has its stale
``captions_<v>.json`` removed.
- Captions and category groups are only written when present. Every file is
+ Filtered clips, captions and category groups are only written when
+ present; when absent, the file an earlier run wrote is removed (the
+ training loader takes a missing ``captions.json`` as caption-free data
+ and selects category subsets from ``category_groups.json``), except a
+ ``category_groups.json`` the run was told to leave alone
+ (*keep_category_groups*: ``--category_groups ""``, the file is copied in
+ by hand). Every file is
written atomically, so an interrupted run cannot leave a truncated output
behind for the training loader to trip over. Returns the merged captions
dict so callers can pass it to ``save_metadata_report``.
@@ -311,17 +324,23 @@ def save_outputs(save_dir, cond, all_filtered_clips, category_groups=None,
save_json(pjoin(save_dir, 'filtered_clips.json'), all_filtered_clips)
total = sum(len(v) for v in all_filtered_clips.values())
print(f'Saved {total} filtered clips to filtered_clips.json')
+ else:
+ _remove_stale(save_dir, 'filtered_clips.json', 'no filtered clips')
all_captions = collect_captions(cond)
if all_captions:
save_json(pjoin(save_dir, 'captions.json'), all_captions)
print(f'Saved {len(all_captions)} clip captions')
+ else:
+ _remove_stale(save_dir, 'captions.json', 'no captions')
for version in EXTRA_CAPTION_VERSIONS:
save_extra_captions(save_dir, all_captions, version,
(extra_captions or {}).get(version))
if category_groups:
save_json(pjoin(save_dir, 'category_groups.json'), category_groups)
+ elif not keep_category_groups:
+ _remove_stale(save_dir, 'category_groups.json', 'no category groups')
return all_captions
diff --git a/data_process/mesh_animation/sample_manifest.py b/data_process/mesh_animation/sample_manifest.py
index a980b29..ed6ea78 100644
--- a/data_process/mesh_animation/sample_manifest.py
+++ b/data_process/mesh_animation/sample_manifest.py
@@ -7,8 +7,13 @@ turns it into one job per motion for ``animate_motion.py`` and checks, before
any Blender process starts, that the three still belong together:
- the cond file still holds the asset's entry with the recorded joint order
- (a cond rebuilt since sampling can reorder or rename joints);
-- the canonical GLB stores that same joint order (``canonical_joint_order``);
+ (a cond rebuilt since sampling can reorder or rename joints) and, when the
+ motion records it, the frame it was sampled in (``frame_digest``,
+ ``asset_files.cond_frame_digest``: joint names, hierarchy and canonical
+ T-pose; a rest pose patched since sampling keeps the names but moves the
+ frame);
+- the canonical GLB stores that same joint order (``canonical_joint_order``)
+ and, when it records one, the cond's frame (``canonical_frame_digest``);
- the motion has as many joints.
A mismatch is an error rather than a silently scrambled animation.
@@ -35,7 +40,8 @@ import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from data_process.utils.asset_files import ( # noqa: E402
- DEFAULT_MIXAMO_CHARACTER, default_assets_dir, glb_joint_order)
+ DEFAULT_MIXAMO_CHARACTER, FRAME_DIGEST_KEY, cond_frame_digest, default_assets_dir,
+ glb_joint_order, glb_node_extra)
MANIFEST_FILE = 'manifest.json'
FORMAT_PREFIX = 'unimate-samples/'
@@ -84,6 +90,7 @@ def build_jobs(path, include_gt=False, char_path=None, character=None):
jobs, problems = [], []
checked = {}
conds = {}
+ frames = {} # asset -> the cond file entry's frame digest (None: not checkable)
def asset_glb(info):
glb = info.get('canonical_glb')
@@ -110,6 +117,7 @@ def build_jobs(path, include_gt=False, char_path=None, character=None):
return issues
names = [str(n) for n in info.get('joint_names', [])]
cond_path = info.get('cond_path')
+ frames[name] = None
if not cond_path or not os.path.isfile(cond_path):
issues.append(f"{name}: cond file {cond_path!r} not found")
else:
@@ -119,6 +127,8 @@ def build_jobs(path, include_gt=False, char_path=None, character=None):
elif [str(n) for n in entry['joint_names']] != names:
issues.append(f"{name}: {cond_path} changed since sampling (joint order "
f"differs); sample again")
+ else:
+ frames[name] = cond_frame_digest(entry)
if char_path is None:
glb = asset_glb(info)
if not glb or not os.path.isfile(glb):
@@ -132,11 +142,15 @@ def build_jobs(path, include_gt=False, char_path=None, character=None):
issues.append(f"{name}: no canonical GLB ({glb!r}); {hint}")
else:
order = glb_joint_order(glb)
+ baked = glb_node_extra(glb, FRAME_DIGEST_KEY)
if order is None:
issues.append(f"{name}: {glb} carries no canonical joint order")
elif order != names:
issues.append(f"{name}: {glb} was baked from another cond (joint order "
f"differs from the sampled one)")
+ elif baked and frames[name] and baked != frames[name]:
+ issues.append(f"{name}: {glb} was baked from another cond (canonical "
+ f"T-pose differs from {cond_path}'s); rebuild it")
checked[name] = issues
return issues
@@ -153,6 +167,11 @@ def build_jobs(path, include_gt=False, char_path=None, character=None):
n_asset = len(assets[name]['joint_names'])
if n_motion != n_asset:
issues.append(f"{npy}: {n_motion} joints, asset {name!r} has {n_asset}")
+ elif sample.get('frame_digest') and frames.get(name) \
+ and sample['frame_digest'] != frames[name]:
+ issues.append(f"{npy}: sampled in another canonical frame of {name!r} than "
+ f"{assets[name].get('cond_path')} holds now (T-pose or "
+ f"hierarchy changed); sample again")
if issues:
problems.extend(issues)
continue
diff --git a/data_process/tools/patch_annotations.py b/data_process/tools/patch_annotations.py
index 5e22fb6..96f8224 100644
--- a/data_process/tools/patch_annotations.py
+++ b/data_process/tools/patch_annotations.py
@@ -68,6 +68,8 @@ place. Two kinds of fixes:
p -> quat * p + offset in export space (offset optional); the
processed GLB applies the same rotation. Idempotent, undone when the entry
is removed; see apply_rest_orientations)
+ A zero or non-finite quat / offset in either JSON stops the run before any
+ file is written (check_quat_patches; apply_* check their own file too).
<ds>_rig_flags.txt <rig> # <category>: <reason> (objaverse / general: hand-reviewed rig
flags -> export/<ds>/rig_flags.json; only tpose_wrong / not_in_legacy_raw
also go to export/<ds>/filtered_objects.txt, which stage 4 skips)
@@ -597,6 +599,69 @@ def write_activity_keep(ds, root, patch_dir, frames, dry_run, log):
ROOT_OFFSET_KEY = 'root_offset_applied' # the quat currently baked into this NPZ (w, x, y, z)
+def _vector_error(value, size, nonzero=False):
+ """Why *value* is not *size* finite numbers (non-zero ones when
+ *nonzero*), or ''."""
+ try:
+ arr = np.asarray(value, dtype=np.float64)
+ except (TypeError, ValueError):
+ return f'expected {size} numbers, got {value!r}'
+ if arr.shape != (size,):
+ return f'expected {size} numbers, got {value!r}'
+ if not np.all(np.isfinite(arr)):
+ return f'non-finite value in {value!r}'
+ if nonzero and np.linalg.norm(arr) < 1e-6:
+ return f'zero vector {value!r} has no direction'
+ return ''
+
+
+# Quaternion patches: file suffix -> the vector fields of an entry.
+QUAT_PATCHES = {'root_offsets': ('quat',), 'rest_orientation': ('quat', 'offset')}
+
+
+def quat_patch_errors(src, fields):
+ """Every malformed entry of the quaternion patch *src*: no ``quat``, or a
+ *fields* value that is not finite numbers (a zero quat has no rotation and
+ would be written into the export NPZs as NaN)."""
+ errors = []
+ for key, entry in load_overrides(src).items():
+ if not isinstance(entry, dict) or 'quat' not in entry:
+ errors.append(f'{os.path.basename(src)}: {key}: expected {{"quat": [w, x, y, z], ...}}')
+ continue
+ for field in fields:
+ if field in entry:
+ why = _vector_error(entry[field], 4 if field == 'quat' else 3,
+ nonzero=field == 'quat')
+ if why:
+ errors.append(f'{os.path.basename(src)}: {key}: {field}: {why}')
+ return errors
+
+
+def load_quat_patch(src, fields):
+ """The entries of the quaternion patch *src*, or ValueError listing the
+ malformed ones before anything is applied."""
+ errors = quat_patch_errors(src, fields)
+ if errors:
+ raise ValueError('Malformed quaternion patch entries (nothing applied):\n '
+ + '\n '.join(errors))
+ return load_overrides(src)
+
+
+def check_quat_patches(patch_dir, datasets):
+ """Raise SystemExit listing every malformed entry of every dataset's
+ quaternion patches, so a bad entry stops the run before any file of any
+ dataset is written."""
+ errors = []
+ for ds in datasets:
+ for suffix, fields in QUAT_PATCHES.items():
+ src = os.path.join(patch_dir, f'{ds}_{suffix}.json')
+ if os.path.isfile(src):
+ errors.extend(quat_patch_errors(src, fields))
+ if errors:
+ raise SystemExit('Malformed quaternion patch entries (nothing applied):\n '
+ + '\n '.join(errors))
+
+
def _save_npz_atomic(path, data):
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + '.', suffix='.tmp',
dir=os.path.dirname(path) or '.')
@@ -634,7 +699,7 @@ def apply_root_offsets(ds, root, patch_dir, dry_run, log):
src = os.path.join(patch_dir, f'{ds}_root_offsets.json')
if not os.path.isfile(src):
return [] # no patch file: leave earlier fixes in place
- want = load_overrides(src)
+ want = load_quat_patch(src, QUAT_PATCHES['root_offsets'])
mdir = os.path.join(root, 'motions')
changed, n_ok = [], 0
targets = set(want)
@@ -707,7 +772,7 @@ def apply_rest_orientations(ds, root, patch_dir, dry_run, log):
src = os.path.join(patch_dir, f'{ds}_rest_orientation.json')
if not os.path.isfile(src):
return [] # no patch file: leave earlier fixes in place
- want = load_overrides(src)
+ want = load_quat_patch(src, QUAT_PATCHES['rest_orientation'])
mdir = os.path.join(root, 'motions')
by_rig = {}
for f in glob.glob(os.path.join(mdir, '*.npz')):
@@ -1157,6 +1222,7 @@ def main():
'(<patch_dir>/.root_motion_cache.json)')
args = ap.parse_args()
os.makedirs(args.patch_dir, exist_ok=True)
+ check_quat_patches(args.patch_dir, args.datasets)
log = []
for ds in args.datasets:
run_dataset(ds, args, log)
diff --git a/data_process/utils/asset_files.py b/data_process/utils/asset_files.py
index dbbf53b..814642e 100644
--- a/data_process/utils/asset_files.py
+++ b/data_process/utils/asset_files.py
@@ -39,6 +39,9 @@ REPLACED_DIR = 'replaced'
# The canonical rest-pose GLB of a cond entry carries its joint order under
# this glTF extras key (feature_extraction/canonical_assets.py).
CANONICAL_ORDER_KEY = 'canonical_joint_order'
+# ... and the cond_frame_digest of the cond it was baked from (a GLB without
+# it cannot be checked against the cond).
+FRAME_DIGEST_KEY = 'canonical_frame_digest'
def default_assets_dir(features_dir):
@@ -254,6 +257,37 @@ def glb_joint_order(path):
return None if value is None else [str(n) for n in value]
+_FRAME_KEYS = ('joint_names', 'parents', 'tpos_first_frame', 'tpos_global_rotations')
+
+
+def _cond_hash(entry, fold_zero):
+ h = hashlib.sha1()
+ h.update(json.dumps([str(n) for n in entry['joint_names']]).encode())
+ h.update(np.asarray(entry['parents'], dtype=np.int64).tobytes())
+ for key in ('tpos_first_frame', 'tpos_global_rotations'):
+ values = np.round(np.asarray(entry[key], dtype=np.float64), 6)
+ h.update((values + 0.0 if fold_zero else values).tobytes())
+ return h.hexdigest()
+
+
+def cond_digest(entry):
+ """sha1 of a cond entry's joint names, hierarchy and canonical T-pose
+ (rounded to 1e-6): the cond part of a canonical GLB's resume digest."""
+ return _cond_hash(entry, fold_zero=False)
+
+
+def cond_frame_digest(entry):
+ """The canonical frame a cond entry defines, as :func:`cond_digest` but
+ with -0.0 taken as 0.0, so float noise around zero (whose sign can differ
+ between machines) leaves it unchanged; None when the entry lacks one of
+ the T-pose fields. Sampler manifests record it per motion and canonical
+ GLBs per bake (``FRAME_DIGEST_KEY``), and a motion is driven only against
+ a cond and a GLB of the same frame."""
+ if any(key not in entry for key in _FRAME_KEYS):
+ return None
+ return _cond_hash(entry, fold_zero=True)
+
+
def check_glb_textures(glb_path, expected, unresolved):
"""Compare the textures a GLB embeds with the ones the scene used.
diff --git a/data_process/utils/blender_rig.py b/data_process/utils/blender_rig.py
index 6f319c0..67b107f 100644
--- a/data_process/utils/blender_rig.py
+++ b/data_process/utils/blender_rig.py
@@ -137,6 +137,44 @@ def repair_and_pack_textures(source_path):
return broken
+def _file_holds(path, data):
+ """Whether the file at *path* holds exactly the bytes *data*."""
+ if os.path.getsize(path) != len(data):
+ return False
+ with open(path, 'rb') as fh:
+ return fh.read() == bytes(data)
+
+
+def write_sidecar(texture_dir, name, ext, data):
+ """``<texture_dir>/<name><ext>`` holding *data*, or the first free
+ ``<name>_<n><ext>``; the path, or None when nothing could be written.
+
+ A file holding other bytes keeps its name: sanitizing maps ``A B`` and
+ ``A+B`` to one name, and every asset exported into a directory shares its
+ ``textures/``. A name is claimed by creating the file exclusively, so
+ processes exporting into one directory at once never replace each
+ other's files; a file that already holds *data* is reused."""
+ os.makedirs(texture_dir, exist_ok=True)
+ path, n = os.path.join(texture_dir, name + ext), 1
+ while True:
+ try:
+ with open(path, 'xb') as fh:
+ try:
+ fh.write(data)
+ except OSError:
+ os.remove(path)
+ raise
+ return path
+ except FileExistsError:
+ if _file_holds(path, data):
+ return path
+ except OSError as exc:
+ logger.warning(f"Could not write texture sidecar {path}: {exc}")
+ return None
+ path = os.path.join(texture_dir, f'{name}_{n}{ext}')
+ n += 1
+
+
def write_packed_images_to_dir(texture_dir):
"""Write packed images that have no on-disk file out to *texture_dir*.
@@ -145,7 +183,8 @@ def write_packed_images_to_dir(texture_dir):
(typical after a GLB import) are silently skipped, losing textures.
Writing them out right before FBX export makes embedding work.
- Returns the list of file paths written.
+ Returns the sidecar paths the images now point at (written here, or
+ already holding their bytes).
"""
written = []
for idx, img in enumerate(bpy.data.images):
@@ -158,20 +197,17 @@ def write_packed_images_to_dir(texture_dir):
safe_name = re.sub(r'[^A-Za-z0-9_.-]+', '_', img.name).strip('_') or f'image_{idx}'
if not safe_name.lower().endswith(ext):
safe_name += ext
- os.makedirs(texture_dir, exist_ok=True)
- out_path = os.path.join(texture_dir, safe_name)
+ # The packed bytes verbatim (no re-encode), where filepath_raw then
+ # points, so the exporter's embed path finds them. (img.unpack()
+ # writes to the image's *original* path instead.)
+ out_path = write_sidecar(texture_dir, safe_name[:-len(ext)], ext,
+ bytes(img.packed_file.data))
+ if out_path is None:
+ continue
img.filepath_raw = out_path
- try:
- # Dump the packed bytes verbatim (no re-encode) exactly where
- # filepath_raw points, so the exporter's embed path finds them.
- # (img.unpack() writes to the image's *original* path instead.)
- with open(out_path, 'wb') as fh:
- fh.write(img.packed_file.data)
- written.append(out_path)
- except OSError as exc:
- logger.warning(f"Could not write packed image '{img.name}' to disk: {exc}")
+ written.append(out_path)
if written:
- logger.info(f"Wrote {len(written)} packed image(s) to {texture_dir} for FBX embedding")
+ logger.info(f"Put {len(written)} packed image(s) in {texture_dir} for FBX embedding")
return written
diff --git a/data_process/vlm_caption/caption_rewrite_llm.py b/data_process/vlm_caption/caption_rewrite_llm.py
index 36c9cec..02ff060 100644
--- a/data_process/vlm_caption/caption_rewrite_llm.py
+++ b/data_process/vlm_caption/caption_rewrite_llm.py
@@ -56,6 +56,8 @@ PROP_RE = re.compile(
r'grabbing|lifting|raising|throwing|catching|kicking|hitting|striking|drawing|aiming)\s+'
r'(?:%s)s?\b' % (PROP_WORDS, AMBIGUOUS_WORDS), re.IGNORECASE)
SUBJECT_RE = re.compile(r'^(A person|An object|An animal)\b')
+# Word limit the prompt states and validate() enforces.
+MAX_WORDS = 15
SYSTEM_PROMPT = """You edit captions for a motion-capture dataset. Each caption describes a short animation of a rigged body rendered WITHOUT any props, weapons, tools, scenery or other objects: only the body itself is visible.
@@ -63,7 +65,7 @@ Rewrite the caption so that it names NO object at all and describes only the bod
Rules:
- Keep the subject phrase exactly as given ("A person", "An object" or "An animal").
-- One sentence, present tense, at most 15 words, ending with a period.
+- One sentence, present tense, at most %d words, ending with a period.
- Do not add actions that are not implied by the original caption; do not drop actions that are.
- Where a pose clearly implies handling something, you may write "as if holding something", "as if aiming" or "as if carrying something" (at most once). Never say what the thing is.
- Forbidden words: any object noun (rifle, sword, ball, phone, ladder, wall, chair, ...), and also weapon, item, tool, prop, object (except in the subject "An object").
@@ -80,7 +82,7 @@ A person talks on the phone while walking. -> A person walks while holding one h
An object crouches while holding a shield and sword. -> An object crouches with both arms raised as if holding something.
A person reloads a rifle while standing. -> A person stands and moves both hands in front of the chest.
A person leans against a wall. -> A person leans sideways with the shoulder raised.
-A person sits in a chair and crosses their legs. -> A person sits and crosses their legs."""
+A person sits in a chair and crosses their legs. -> A person sits and crosses their legs.""" % MAX_WORDS
def load_json(path):
@@ -106,7 +108,7 @@ def validate(new, old, pattern):
return 'subject changed'
if pattern.search(new):
return 'prop word: ' + pattern.search(new).group(0)
- if len(new.split()) > 18:
+ if len(new.split()) > MAX_WORDS:
return 'too long'
if new.count('.') > 1:
return 'multiple sentences'
@@ -149,7 +151,10 @@ def main():
n_ok = 0
for k, clip in enumerate(clips, 1):
old = captions[clip]
- if clip in result and result[clip].get('ok') and result[clip].get('old') == old:
+ prev = result.get(clip, {})
+ # Kept only while it still passes the current checks (word limit, props).
+ if (prev.get('ok') and prev.get('old') == old
+ and not validate(prev.get('new', ''), old, pattern)):
n_ok += 1
continue
best, best_err, tries = '', 'no answer', 0
diff --git a/unimate/inference/assets.py b/unimate/inference/assets.py
index 5c855eb..44d0b33 100644
--- a/unimate/inference/assets.py
+++ b/unimate/inference/assets.py
@@ -27,7 +27,8 @@ from typing import Dict, Iterable, List, Optional
import numpy as np
-from data_process.utils.asset_files import DEFAULT_MIXAMO_CHARACTER, default_assets_dir
+from data_process.utils.asset_files import (
+ DEFAULT_MIXAMO_CHARACTER, cond_frame_digest, default_assets_dir)
from unimate.utils.logger import get_logger
logger = get_logger(file_name=__file__)
@@ -90,6 +91,7 @@ class Asset:
'canonical_glb': _display_path(self.canonical_glb) if self.canonical_glb else None,
'stats_dataset': self.stats_dataset,
'joint_names': self.joint_names,
+ 'frame_digest': cond_frame_digest(self.cond),
}
diff --git a/unimate/inference/sample.py b/unimate/inference/sample.py
index fc76754..0af50d5 100644
--- a/unimate/inference/sample.py
+++ b/unimate/inference/sample.py
@@ -579,17 +579,20 @@ class SampleManifest:
(``scripts/run_animate_motion.sh <output_dir>``) reads it instead of being
told the dataset, cond and character again.
- A run into a directory that already holds a manifest adds to it: earlier
- motions stay drivable. An earlier asset of the same name that differs
- (another cond, another joint order) loses its motions from the manifest,
- since their files may be overwritten by this run's. Rewritten after every
- chunk.
+ Every motion also records the frame digest of its asset's cond
+ (``frame_digest``), against which mesh driving checks the cond and the
+ canonical GLB. A run into a directory that already holds a manifest adds
+ to it: earlier motions stay drivable. An earlier asset of the same name
+ that differs (another cond, another joint order, another canonical frame)
+ loses its motions from the manifest, since their files may be overwritten
+ by this run's. Rewritten after every chunk.
"""
FILE = 'manifest.json'
FORMAT = 'unimate-samples/1'
- # What makes two manifest assets of one name the same skeleton.
- IDENTITY = ('cond_path', 'cond_key', 'joint_names')
+ # What makes two manifest assets of one name the same skeleton; a key an
+ # earlier manifest does not record is not compared.
+ IDENTITY = ('cond_path', 'cond_key', 'joint_names', 'frame_digest')
def __init__(self, output_dir: str, args: InferenceArgs, model_path: str,
cfg_scale: float, mode: str, assets: Dict[str, Asset]):
@@ -608,7 +611,8 @@ class SampleManifest:
for name, asset in sorted(assets.items()):
entry = asset.manifest_entry()
prev = self.data['assets'].get(name)
- if prev is not None and any(prev.get(k) != entry[k] for k in self.IDENTITY):
+ if prev is not None and any(k in prev and prev[k] != entry[k]
+ for k in self.IDENTITY):
dropped = [k for k, v in self.data['samples'].items() if v.get('asset') == name]
for k in dropped:
del self.data['samples'][k]
@@ -621,8 +625,9 @@ class SampleManifest:
'cfg_scale': cfg_scale, 'seed': args.seed, 'mode': mode})
def add(self, npy_name: str, case_id: str, asset: str, prompt: str, kind: str = 'sample'):
+ frame = self.data['assets'].get(asset, {}).get('frame_digest')
self.data['samples'][npy_name] = {'asset': asset, 'case_id': case_id, 'prompt': prompt,
- 'kind': kind, 'run': self.run}
+ 'kind': kind, 'run': self.run, 'frame_digest': frame}
def save(self):
tmp = f'{self.path}.tmp'