Spaces:
Sleeping
Sleeping
Download utils/augmentations.py from AfanR/Bisindo-Sign-Detection: direct link, hf CLI and curl.
- Browser
- Download file 5.71 kB
-
https://huggingface.co/spaces/AfanR/Bisindo-Sign-Detection/resolve/main/utils/augmentations.py
- Command line
-
hf download hf://spaces/AfanR/Bisindo-Sign-Detection/utils/augmentations.py
-
curl -L -o augmentations.py https://huggingface.co/spaces/AfanR/Bisindo-Sign-Detection/resolve/main/utils/augmentations.py
5.71 kB
| import numpy as np | |
| import warnings | |
| from scipy.ndimage import gaussian_filter1d | |
| class Augmentations: | |
| def __init__(self, mode:str, strength:float=0.7, seed:int=42): | |
| self.mode = mode | |
| self.strength = np.clip(strength, 0.0, 1.0) | |
| self.seed = seed | |
| np.random.seed(self.seed) | |
| self.feature_idx = { | |
| 'left_hand': list(range(0, 63)), | |
| 'right_hand': list(range(63, 126)), | |
| 'flags': list(range(126, 128)), | |
| 'confidence': list(range(128, 130)) | |
| } | |
| self._setup_parameters() | |
| def _setup_parameters(self): | |
| if self.mode !='train': | |
| self.enabled_augmentations =[] | |
| return | |
| self.enabled_augmentations = ['temporal_crop', | |
| 'spatial_jitter', | |
| 'temporal_warp', | |
| 'feature_dropout', | |
| 'gaussian_noise' | |
| ] | |
| self.params = { | |
| 'min_crop_ratio': max(0.7, 0.9-0.2*self.strength), | |
| 'jitter_std': 0.02*self.strength, | |
| 'speed_range': [0.85,1.15], | |
| 'feature_dropout_rate': 0.1*self.strength, | |
| 'gaussian_noise_std': 0.01*self.strength, | |
| 'frame_dropout_prob': 0.05*self.strength | |
| } | |
| self.probs = { | |
| 'temporal_crop': 0.8, | |
| 'spatial_jitter': 0.9, | |
| 'temporal_warp': 0.6, | |
| 'feature_dropout': 0.5, | |
| 'gaussian_noise': 0.7 | |
| } | |
| def temporal_crop(self, sequence): | |
| T = sequence.shape[0] | |
| min_length = int(T * self.params['min_crop_ratio']) | |
| if min_length >= T: | |
| return sequence | |
| strategy = np.random.choice(['start', 'end', 'middle'], p=[0.4, 0.4, 0.2]) | |
| if strategy == 'start': | |
| crop_length = np.random.randint(min_length,T) | |
| cropped = sequence[T - crop_length:] | |
| elif strategy == 'end': | |
| crop_length = np.random.randint(min_length,T) | |
| cropped = sequence[:crop_length] | |
| else: | |
| crop_length = np.random.randint(min_length,T) | |
| start = np.random.randint(0, T - crop_length) | |
| cropped = sequence[start:start + crop_length] | |
| if len(cropped) != T: | |
| cropped = self._fast_resample(cropped,T) | |
| return cropped | |
| def spatial_jitter(self, sequence): | |
| jittered = sequence.copy() | |
| T = sequence.shape[0] | |
| hand_features = slice(0,126) | |
| noise = np.random.normal(0, self.params['jitter_std'], size=(T,126)) | |
| jittered[:, hand_features] += noise | |
| return jittered | |
| def temporal_warp(self, sequence): | |
| T = sequence.shape[0] | |
| speed = np.random.uniform(*self.params['speed_range']) | |
| # original_timeline = np.arange(T) | |
| new_timeline = np.linspace(0, T-1, num=int(T*speed)) | |
| if len(new_timeline) > T: | |
| new_timeline = new_timeline[:T] | |
| warped = np.zeros_like(sequence) | |
| for i in range(sequence.shape[1]): | |
| warped[:,i] = np.interp(np.arange(T), new_timeline, sequence[:len(new_timeline), i]) | |
| return warped | |
| def feature_dropout(self, sequence): | |
| if self.params['feature_dropout_rate'] <= 0: | |
| return sequence | |
| T, F = sequence.shape | |
| masked = sequence.copy() | |
| dropout_rate = self.params['feature_dropout_rate'] | |
| num_features = F | |
| features_drop = np.random.rand(num_features) < dropout_rate | |
| features_drop[self.feature_idx['flags']] = False | |
| features_drop[self.feature_idx['confidence']] = False | |
| if features_drop.any(): | |
| for i in np.where(features_drop)[0]: | |
| masked[:, i] = 0.0 | |
| return masked | |
| def gaussian_noise(self, sequence): | |
| T, F = sequence.shape | |
| noise = np.random.normal(0, self.params['gaussian_noise_std'], size=(T,F)) | |
| return sequence + noise | |
| def _fast_resample(self, sequence, target_length): | |
| if len(sequence) == target_length: | |
| return sequence | |
| T_original = len(sequence) | |
| T_target = target_length | |
| x_original = np.linspace(0, 1, T_original) | |
| x_target = np.linspace(0, 1, T_target) | |
| resampled = np.zeros((T_target, sequence.shape[1])) | |
| for i in range(sequence.shape[1]): | |
| resampled[:,i] = np.interp(x_target, x_original, sequence[:,i]) | |
| return resampled | |
| def __call__(self, sequence): | |
| if self.mode != 'train' or not self.enabled_augmentations: | |
| return sequence | |
| augmented = sequence.copy() | |
| methods = { | |
| 'temporal_crop': self.temporal_crop, | |
| 'spatial_jitter': self.spatial_jitter, | |
| 'temporal_warp': self.temporal_warp, | |
| 'feature_dropout': self.feature_dropout, | |
| 'gaussian_noise': self.gaussian_noise, | |
| 'linear_interpolation': self.linear_interpolation | |
| } | |
| for aug in self.enabled_augmentations: | |
| if aug in methods and np.random.rand() < self.probs.get(aug, 0.5): | |
| try: | |
| augmented = methods[aug](augmented) | |
| except Exception as e: | |
| warnings.warn(f"Augmentation {aug} failed: {e}") | |
| continue | |
| return augmented | |
| def augment_batch(self, batch): | |
| if self.mode != 'train': | |
| return batch | |
| B = batch.shape[0] | |
| augmented = np.zeros_like(batch) | |
| for i in range(B): | |
| augmented[i] = self(batch[i]) | |
| return augmented | |