diff --git a/.gitignore b/.gitignore index 75e1c49..2e5e203 100644 --- a/.gitignore +++ b/.gitignore @@ -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. diff --git a/thirdparty/skintokens/download_wheel.py b/thirdparty/skintokens/download_wheel.py index 2fbd923..bf37792 100644 --- a/thirdparty/skintokens/download_wheel.py +++ b/thirdparty/skintokens/download_wheel.py @@ -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 diff --git a/thirdparty/skintokens/src/data/augment.py b/thirdparty/skintokens/src/data/augment.py new file mode 100644 index 0000000..0909d5d --- /dev/null +++ b/thirdparty/skintokens/src/data/augment.py @@ -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 \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/datapath.py b/thirdparty/skintokens/src/data/datapath.py new file mode 100644 index 0000000..268123a --- /dev/null +++ b/thirdparty/skintokens/src/data/datapath.py @@ -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) \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/dataset.py b/thirdparty/skintokens/src/data/dataset.py new file mode 100644 index 0000000..6d8de18 --- /dev/null +++ b/thirdparty/skintokens/src/data/dataset.py @@ -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) \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/order.py b/thirdparty/skintokens/src/data/order.py new file mode 100644 index 0000000..2bde391 --- /dev/null +++ b/thirdparty/skintokens/src/data/order.py @@ -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 \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/sampler.py b/thirdparty/skintokens/src/data/sampler.py new file mode 100644 index 0000000..ef7bc0d --- /dev/null +++ b/thirdparty/skintokens/src/data/sampler.py @@ -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 \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/spec.py b/thirdparty/skintokens/src/data/spec.py new file mode 100644 index 0000000..3719d80 --- /dev/null +++ b/thirdparty/skintokens/src/data/spec.py @@ -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() \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/transform.py b/thirdparty/skintokens/src/data/transform.py new file mode 100644 index 0000000..3601d75 --- /dev/null +++ b/thirdparty/skintokens/src/data/transform.py @@ -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 \ No newline at end of file diff --git a/thirdparty/skintokens/src/data/vertex_group.py b/thirdparty/skintokens/src/data/vertex_group.py new file mode 100644 index 0000000..04c0c17 --- /dev/null +++ b/thirdparty/skintokens/src/data/vertex_group.py @@ -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 \ No newline at end of file