text
stringlengths
0
1.47k
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]
# 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
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
# scales a Mixamo character), the source asset, the bake version and,
# for a Mixamo character, the clips' rest root it stores.
extra = {}
if mixamo:
extra[MOTION_ROOT_KEY] = json.dumps(
[float(v) for v in np.asarray(cond[object_type]['tpos_first_frame'])[0]])
digest = hashlib.sha1((cond_digest(cond[object_type])
+ str(cond_diameter(cond[object_type]))
+ file_digest(source) + ''.join(extra.values())
+ BAKE_VERSION).encode()).hexdigest()
if (not overwrite and os.path.isfile(final) and glb_digest(final) == digest
and all(os.path.isfile(path) for _, path in extra_files)):
write_note(out_dir, GLB_ERRORS_DIR, name, [])
counts['up_to_date'] += 1
continue
partial = os.path.join(out_dir, f'.{name}.partial')
try:
os.makedirs(out_dir, exist_ok=True)
target = mixamo_character_cond(source, cond[object_type]) if mixamo \
else cond[object_type]
_check_not_collinear(target)
bake_canonical_asset(source, target, partial,
formats=('glb',) + tuple(fmt for fmt, _ in extra_files),
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)
# Another format of the asset that this run did not write was
# baked from the older inputs (the GLB is always written).
for fmt in CANONICAL_FORMATS:
stale = os.path.join(out_dir, f'{name}.{fmt}')
if fmt != 'glb' and fmt not in formats and os.path.isfile(stale):
os.remove(stale)
except Exception as exc: # noqa: BLE001 — keep the batch going
if isinstance(exc, UndeterminedRoll): # incl. CollinearSkeleton
logger.info(f"Canonical GLB of '{name}' refused: {exc}")
counts['refused'] += 1
else:
logger.exception(f"Canonical GLB of '{name}' failed")
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.
_remove_asset_files(out_dir, name, partial)
continue
write_note(out_dir, GLB_ERRORS_DIR, name, [])
try:
_texture_note(out_dir, name, source, final)
except Exception as exc: # noqa: BLE001 — the GLB is written; keep it
logger.warning(f"'{name}': texture comparison failed: {exc}")
counts['baked'] += 1
logger.info(f"Canonical GLBs in {out_dir}: {counts} "
f"({len(jobs)} asset(s){' on this worker' if num_workers > 1 else ''}; "
f"'no_source' = no {export_dir}/{PROCESSED_GLB_DIR}/<asset>.glb)")
return counts
def parse_args():
ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
ap.add_argument('--export_dir', required=True,
help='Stage-1 export directory (its rigs/ holds the rest-pose GLBs).')
ap.add_argument('--features_dir', required=True,
help='Stage-4 feature directory (its cond.npy).')
ap.add_argument('--assets_dir', default=None,
help='Output directory (default: canonical_assets/<dataset> beside the '
'features root, e.g. dataset/canonical_assets/truebones).')
ap.add_argument('--dataset_type', default=None,
help="'mixamo' (also detected from a cond with the single key 'mixamo'): "
"one GLB per character in the export's rigs/; else per object type.")
ap.add_argument('--object_types', nargs='+', default=None,