code
stringlengths
17
6.64M
def freeze(net: nn.Module, /) -> nn.Module: 'Fix all model parameters and prevent training.' for p in net.parameters(): p.requires_grad = False return net
def unfreeze(net: nn.Module, /) -> nn.Module: 'Make all model parameters trainable.' for p in net.parameters(): p.requires_grad = True return net
def allclose(net1: nn.Module, net2: nn.Module, /) -> bool: 'Check if two networks have the exact same parameters.' for (p1, p2) in zip(net1.parameters(), net2.parameters()): try: if (not p1.allclose(p2)): return False except RuntimeError: return False ...
def num_parameters(net: nn.Module, /, requires_grad: ty.N[bool]=None) -> int: 'Get number of parameters in a network. By default, all parameters are counted.' if (requires_grad is None): key = (lambda p: True) elif requires_grad: key = (lambda p: p.requires_grad) else: key = (l...
@map_container def to_torch(x: ty.Any, /, permute: bool=True, device: ty.N[torch.device]=None) -> ty.Any: 'Convert given input to `torch.Tensors`.\n\n :param x: (ty.Any) Arbitrary structure to convert to tensors (see `map_container`).\n :param permute: (bool) If `True`, permute to PyTorch convention (b, h, ...
@map_container def to_np(x: ty.Any, /, permute: bool=True) -> ty.Any: 'Convert given input to `numpy.ndarrays`.\n\n :param x: (ty.Any) Arbitrary structure to convert to ndarrays (see map_container).\n :param permute: (bool) If `True`, permute from PyTorch convention (b, c, h, w) -> (b, h, w, c).\n :retur...
@map_container def op(_x: ty.Any, /, *args, fn: ty.U[(str, ty.Callable)], **kwargs) -> ty.Any: "Apply a function to an arbitrary input structure. `fn` can be either a function or a method to search on `_x`.\n\n Example:\n >>> out = fn(input, device, op='to') # Apply x.to(device) to each item in `input`...
@opt_args_deco def allow_np(fn: ty.N[ty.Callable], permute: bool=False) -> ty.Callable: "Decorator to allow for `np.ndarray` inputs into a torch function.\n\n Objective is to implement the function using torch ops and apply this decorator to also make it numpy friendly.\n Since `numpy.ndarray` and `torch.Te...
def dilate_mask(mask: ty.T, kernel_size: int=3) -> ty.T: 'Apply morphological dilation to the input binary mask.\n\n If any pixel within the kernel is a valid pixel (`True`), the central point is added to the mask.\n\n :param mask: (Tensor) (b, 1, h, w) Boolean mask indicating valid pixels.\n :param kern...
def erode_mask(mask: ty.T, kernel_size: int=3) -> ty.T: 'Apply morphological erosion to the given binary mask.\n\n If any pixel within the kernel is not a valid pixel (`False`), the central point is removed from the mask.\n Since PyTorch does not provide `min_pool` we simply invert the dilation process.\n\n...
@allow_np(permute=True) def standardize(x: ty.T, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> ty.T: 'Apply standardization. Default uses ImageNet statistics.' shape = (([1] * (x.ndim - 3)) + [3, 1, 1]) mean = x.new_tensor(mean).view(shape) std = x.new_tensor(std).view(shape) x = ((x - mean) / s...
@allow_np(permute=True) def unstandardize(x: ty.T, /, mean: StatsRGB=_mean, std: StatsRGB=_std) -> ty.T: 'Remove standardization. Default uses ImageNet statistics.' shape = (([1] * (x.ndim - 3)) + [3, 1, 1]) mean = x.new_tensor(mean).view(shape) std = x.new_tensor(std).view(shape) x = ((x * std) +...
@allow_np(permute=True) def to_gray(x: ty.T, /, coeffs: StatsRGB=_coeffs, keepdim: bool=False) -> ty.T: 'Convert image to grayscale.' shape = (([1] * (x.ndim - 3)) + [3, 1, 1]) coeffs = x.new_tensor(coeffs).view(shape) x = (x * coeffs).sum(dim=1, keepdim=keepdim) return x
def mean_normalize(x: ty.T, /, dim: ty.U[(int, ty.S[int])]=(2, 3)) -> ty.T: 'Apply mean normalization across the specified dimensions.\n\n :param x: (Tensor) (*) Input tensor to normalize of any shape.\n :param dim: (int | ty.S[int]) Dimension(s) to compute the mean across.\n :return: (Tensor) (*) Mean n...
def eye_like(x: ty.T, /) -> ty.T: 'Create an Identity matrix of the same dtype and size as the input.\n\n NOTE: The input can be of any shape, except the final two dimensions, which must be square.\n\n :param x: (Tensor) (*, n, n) Input reference tensor, where `*` can be any size (including zero).\n :ret...
def interpolate_like(input: ty.T, /, other: ty.T, mode: str='nearest', align_corners: bool=False) -> ty.T: 'Interpolate to match the size of `other` tensor.' if (mode == 'nearest'): align_corners = None return F.interpolate(input, size=other.shape[(- 2):], mode=mode, align_corners=align_corners)
def expand_dim(x: ty.T, /, num: ty.U[(int, ty.S[int])], dim: ty.U[(int, ty.S[int])]=0, insert: bool=False) -> ty.T: 'Expand the specified input tensor dimensions, inserting new ones if required.\n\n >>> expand_dim(torch.rand(1, 1, 1), num=5, dim=1, insert=False) # (1, 1, 1) -> (1, 5, 1)\n >>> ex...
def min(x: ty.T, dim: ty.N[ty.U[(int, ty.S)]]=None, keepdim: bool=False): 'Find the min values of the input tensor along the desired dimension(s).\n Wrapper around `torch.min` that returns only the min value and can be applied to multiple dimensions.\n\n :param x: (Tensor) (*) Input tensor of any shape.\n ...
def max(x: ty.T, dim: ty.N[ty.U[(int, ty.S)]]=None, keepdim: bool=False): 'Find the max values of the input tensor along the desired dimension(s).\n Wrapper around `torch.max` that returns only the max value and can be applied to multiple dimensions.\n\n :param x: (Tensor) (*) Input tensor of any shape.\n ...
def get_cls(cls_dict: dict[(str, ty.Type[T])], /, *args, type: str, **kwargs) -> T: 'Instantiate an arbitrary class from a collection.\n\n Including `type` makes it a keyword-only argument. This has the double benefit of forcing the user to pass it as a\n keyword argument, as well as popping it from the cfg...
def get_net(cfg: dict) -> nn.ModuleDict: "Instantiate the target networks from a cfg dict.\n\n Depth estimation typically consists of multiple networks, commonly `depth` and `pose`.\n We assume that, within a given category, we can use different classes interchangeably.\n For instance, all `depth` networ...
def get_loss(cfg: dict) -> tuple[(nn.ModuleDict, nn.ParameterDict)]: "Instantiate the target losses from a cfg dict.\n\n In addition to the kwargs required to instantiate the loss, we also expect a `weight` kwarg, used to\n balance the various losses when computing the final loss. (Default: 1)\n\n Losses...
def get_ds(cfg: dict, mode: ty.N[str]=None) -> dict[(str, Dataset)]: "Instantiate the target datasets from a cfg dict.\n\n Datasets consist of a default cfg for each class, which can be overriden based on a `mode` sub-dict.\n\n Datasets can be omitted by setting their cfg to `None`. Useful when overriding t...
def get_dl(mode: str, cfg_ds: dict, cfg_dl: dict) -> DataLoader: "Instantiate the target dataloader from a cfg dict.\n\n Dataloaders consist of a default cfg, which can be overriden based on a `mode` sub-dict.\n The datasets are expected to be a subclass of `BaseDataset`, which provides a `collate_fn` metho...
def get_opt(parameters: ty.U[(ty.Iterable, nn.Module)], cfg: dict) -> optim.Optimizer: "Instantiate the target optimizer from a cfg dict. Wrapper for `timm` `create_optimizer_v2`.\n\n Example:\n ```\n cfg = {\n 'type': 'adamw',\n 'lr': 1e-3,\n 'weight_decay': 1e-4,\n 'frozen_b...
def get_sched(opt: optim.Optimizer, cfg: dict[(str, dict)]) -> dict[(str, ty._LRScheduler)]: "Instantiate the target schedulers from a cfg dict. Wrapper for `timm` `create_scheduler_v2`.\n\n Example:\n ```\n cfg = {\n 'steplr': {\n 'step_size': 10,\n 'gamma': 0.1,\n },...
def get_metrics() -> nn.ModuleDict: 'Instantiate the collection of depth metrics to monitor.' return nn.ModuleDict({'MAE': metrics.MAE(), 'RMSE': metrics.RMSE(), 'LogSI': metrics.ScaleInvariant(mode='log'), 'AbsRel': metrics.AbsRel(), 'Acc': metrics.DeltaAcc(delta=1.25)})
def _get_percentile(x: ty.A, p: int) -> float: 'Safe percentile to handle NaNs/Inf.' try: return np.percentile(x, p) except IndexError: return 0.0
@ops.allow_np(permute=True) def rgb_from_disp(disp: ty.T, invert: bool=False, cmap: str='turbo', vmin: float=0, vmax: ty.N[ty.U[(float, ty.S[float])]]=None) -> ty.T: 'Convert a disparity map into an RGB colormap visualization.\n\n :param disp: (Tensor) (*b, *1, h, w) Input disparity/depth map.\n :param inve...
@ops.allow_np(permute=True) def rgb_from_feat(feat: ty.T) -> ty.T: 'Convert dense features into an RGB image via PCA.\n\n NOTE: PCA is computed using all features in the batch, i.e. the representation is batch dependent.\n\n :param feat: (Tensor) (*b, c, h, w) Dense feature representation.\n :return: (Te...
class SuppImageNotFoundError(FileNotFoundError): pass
class Predictor(Protocol): @staticmethod def get_img_shape(data_type: str) -> N[tuple[(int, int)]]: ... def __call__(self, net: nn.Module, dl: DataLoader, use_stereo_blend: bool, device: N[str]) -> NDArray: ... def apply(self, net: nn.Module, dl: DataLoader, func: Callable, use_ster...
class DepthPred(TypedDict, total=False): depth_feats: S[T] disp: dict[(int, T)] disp_stereo: dict[(int, T)] mask: dict[(int, T)] mask_stereo: dict[(int, T)]
class PosePred(TypedDict, total=False): R: T t: T fs: T cs: T
class AutoencoderPred(TypedDict, total=True): autoenc_feats: S[T] autoenc_imgs: dict[(int, T)]
class TQDMProgressBar(plc.TQDMProgressBar): 'Progress bar that removes all `grad norms` from display.' def get_metrics(self, trainer, pl_module) -> dict: m = super().get_metrics(trainer, pl_module) m = {k: v for (k, v) in m.items() if ('grad' not in k)} return m
class RichProgressBar(plc.RichProgressBar): 'Progress bar that removes all `grad norms` from display.' def get_metrics(self, trainer, pl_module) -> dict: m = super().get_metrics(trainer, pl_module) m = {k: v for (k, v) in m.items() if ('grad' not in k)} return m
class DetectAnomaly(plc.Callback): 'Check for NaN/infinite loss at each core step. Replacement for `detect_anomaly=True`.' def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, unused=0) -> None: if (not (loss := outputs['loss']).isfinite()): raise ValueError(f'Detec...
class TrainingManager(plc.Callback): 'Callback to save a dummy file as an indicator when training has started/finished.' def __init__(self, ckpt_dir: Path): super().__init__() self.ckpt_dir = ckpt_dir self.ckpt_dir.mkdir(exist_ok=True, parents=True) self.host = socket.gethostn...
def default_convert(data): "\n Function that converts each NumPy array element into a :class:`torch.Tensor`. If the input is a `Sequence`,\n `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.\n If the input is not an NumPy array, it is left unchang...
def collate(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): "\n General collate function that handles collection type of element within each batch\n and opens function registry to deal with specific element types. `default_collate_fn_map`\n provi...
def collate_tensor_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): elem = batch[0] out = None if (torch.utils.data.get_worker_info() is not None): numel = sum((x.numel() for x in batch)) storage = elem._typed_storage()._new_shared(numel, de...
def collate_numpy_array_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): elem = batch[0] if (np_str_obj_array_pattern.search(elem.dtype.str) is not None): raise TypeError(default_collate_err_msg_format.format(elem.dtype)) return collate([torch.as_te...
def collate_numpy_scalar_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.as_tensor(batch)
def collate_float_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.tensor(batch, dtype=torch.float64)
def collate_int_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.tensor(batch)
def collate_str_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return batch
def default_collate(batch): "\n Function that takes in a batch of data and puts the elements within the batch\n into a tensor with an additional outer dimension - batch size. The exact output type can be\n a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a\n Collection o...
def opt_args_deco(deco: ty.Callable) -> ty.Callable: 'Meta-decorator to make implementing of decorators with optional arguments more intuitive\n\n Recall: Decorators are equivalent to applying functions sequentially\n >>> func = deco(func)\n\n If we want to provide optional arguments, it would be the...
def delegates(to: ty.N[ty.Callable]=None, keep: bool=False): 'From https://www.fast.ai/2019/08/06/delegation/.\n Decorator to replace `**kwargs` in signature with params from `to`.\n\n This can be used to decorate either a class\n ```\n @delegates()\n class Child(Parent): ...\n ```\n ...
def map_container(f: ty.Callable) -> ty.Callable: "Decorator to recursively apply a function to arbitrary nestings of `dict`, `list`, `tuple` & `set`\n\n NOTE: `f` can have an arbitrary signature, but the first arg must be the item we want to apply `f` to.\n\n Example:\n ```\n @map_apply\n ...
def readlines(file: Path, /, encoding: str=None, split: bool=False, sep: ty.N[str]=None) -> ty.U[(list[str], list[list[str]])]: 'Read file as a list of strings.' with open(file, encoding=encoding) as f: lines = f.read().splitlines() if split: lines = splitlines(lines, sep) ...
def splitlines(lines: list[str], sep: ty.N[str]=None) -> list[list[str]]: 'Split each line in a list of lines.' return [l.split(sep) for l in lines]
def mymap(fn: str, iterable: ty.Iterable, type: ty.N[T]=list, **kwargs) -> ty.U[(ty.Generator, T)]: 'Apply instance method `fn` to each item in `iterable`.\n\n :param fn: (str) Function name to search as an attribute of each item.\n :param iterable: (Iterable) Iterable to apply function to.\n :param type...
def _map(fn: ty.Callable, *iterables: ty.Iterable, type: T, star: bool=False) -> T: 'Map `fn` to each iterable item and convert to the specified container `type`.' map_fn = (itertools.starmap if star else map) return type(map_fn(fn, *iterables))
def iterdir(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted contents in path, optionally filtered by the `key`.' key = (key or (lambda f: True)) return sorted(filter(key, path.iterdir()))
def get_dirs(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted directories in a path, optionally filtered by the `key`.' _key = (lambda p: (p.is_dir() and (key(p) if key else True))) return iterdir(path, _key)
def get_files(path: Path, key: ty.N[Key]=None) -> list[Path]: 'Get sorted files in a path, optionally filtered by the `key`.' _key = (lambda p: (p.is_file() and (key(p) if key else True))) return iterdir(path, _key)
def has_contents(path: Path) -> bool: 'Check if directory is not empty.' return (path.is_dir() and bool(iterdir(path)))
def mkdirs(*paths: Path, exist_ok: bool=True, parents: bool=True, **kwargs) -> None: 'Create all input directories with laxer defaults.' for p in paths: p.mkdir(exist_ok=exist_ok, parents=parents, **kwargs)
def pil2np(img: Image, /) -> ty.A: 'Convert PIL image [0, 255] into numpy [0, 1].' return (np.array(img, dtype=np.float32) / 255.0)
def np2pil(arr: ty.A, /) -> Image: 'Convert numpy image [0, 1] into PIL [0, 255].' if (arr.dtype == np.uint8): return Image.fromarray(arr) assert (arr.max() <= 1) return Image.fromarray((arr * 255).astype(np.uint8))
def write_yaml(file: Path, data: dict, mkdir: bool=False, sort_keys: bool=False) -> None: 'Write data to a yaml file.' file = Path(file).with_suffix('.yaml') if mkdir: mkdirs(file.parent) with open(file, 'w') as f: yaml.dump(data, f, sort_keys=sort_keys)
def load_yaml(file: Path, loader: ty.N[yaml.Loader]=yaml.FullLoader) -> dict: 'Load a single yaml file.' with open(file) as f: return yaml.load(f, Loader=loader)
def load_merge_yaml(*files: Path) -> dict: 'Load a list of YAML configs and recursively merge into a single config.\n\n Following dictionary merging rules, the first file is the "base" config, which gets updated by the second file.\n We chain this rule for however many cfg we have, i.e. ((((1 <- 2) <- 3) <-...
def _merge_yaml(old: dict, new: dict) -> dict: 'Recursively merge two YAML cfg.\n Dictionaries are recursively merged. All other types simply update the current value.\n\n NOTE: This means that a "list of dicts" will simply be updated to whatever the new value is,\n not appended to or recursively checked...
class ConcatDataLoader(): "Concatenate multiple DataLoaders in a round-robin manner.\n Example:\n dl1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]\n dl2 = ['a', 'b', 'c']\n dl3 = [0.1, 0.2, 0.3, 0.4. 0.5]\n\n [0, 'a', 0.1, 1, 'b', 0.2, 3, 'c', 0.3, 4, 0.4, 5, 0.5, 6, 7, 8]\n\n :param dls: (Sequ...
class BaseMetric(Metric): 'Base class for depth estimation metrics.' higher_is_better = False full_state_update = False def __init__(self, mode: str='raw', **kwargs): super().__init__(**kwargs) if (mode not in _MODES): raise ValueError(f'Invalid mode! ({mode} vs. {_MODES})...
class MAE(BaseMetric): 'Compute the mean absolute error.' def _compute(self, pred: ty.T, target: ty.T) -> ty.T: return (pred - target).abs().nanmean(dim=1)
class RMSE(BaseMetric): 'Compute the root mean squared error.' def _compute(self, pred: ty.T, target: ty.T) -> ty.T: return (pred - target).pow(2).nanmean(dim=1).sqrt()
class ScaleInvariant(BaseMetric): 'Compute the scale invariant error.' def _compute(self, pred: ty.T, target: ty.T) -> ty.T: err = (pred - target) return (err.pow(2).nanmean(dim=1) - err.nanmean(dim=1).pow(2)).sqrt()
class AbsRel(BaseMetric): 'Compute the absolute relative error.' def __init__(self, **kwargs): super().__init__(**kwargs) self.sf = 100 def _compute(self, pred: ty.T, target: ty.T) -> ty.T: return ((pred - target).abs() / target).nanmean(dim=1)
class SqRel(BaseMetric): 'Compute the absolute relative squared error.' def __init__(self, **kwargs): super().__init__(**kwargs) self.sf = 100 def _compute(self, pred: ty.T, target: ty.T) -> ty.T: return ((pred - target).pow(2) / target.pow(2)).nanmean(dim=1)
class DeltaAcc(BaseMetric): 'Compute the accuracy for a given error threshold.' higher_is_better = True def __init__(self, delta: float, **kwargs): super().__init__(**kwargs) if (self.mode != 'raw'): raise ValueError('DeltaAcc should only be computed using raw depths.') ...
class Timer(): "Context manager for timing a block of code.\n\n Attributes:\n :param name: (str) Timer label when printing.\n :param as_ms: (bool) If `True`, store time as `milliseconds`, otherwise `seconds`.\n :param sync_gpu: (bool) If `True`, ensure that GPU is synced on Timer enter and exit.\n ...
class MultiLevelTimer(): "Context manager Timer capable of being nested across multiple levels.\n\n NOTE: We use the *instance* of this class as a context manager, not the class itself (see examples).\n\n Timers are stored as a dict, mapping labels to (depth, start, end, elapsed).\n In order to allow for...
class EnvWrapper(): def __init__(self, task): self.action_space = self.brain.vector_action_space_size
class CountScore(): def __init__(self): self.total_episode = 100 self.episode_rewards = np.zeros(self.total_episode) self.current_episode = 0 def add_score(self, score): self.episode_rewards[self.current_episode] = score self.current_episode += 1 self.current_...
class UnityTask(): def __init__(self, name): self.brain = None self.brain_name = None self.env = self.create_unity_env() self.action_space = self.brain.vector_action_space_size self.observation_space = self.brain.vector_observation_space_size print(f'Action space {...
class PPOAgent_Unity(): def __init__(self, config): self.config = config self.task = UnityTask('reacher') self.network = PPONetwork(self.config.state_dim, self.config.action_dim, 1000).to('cuda:0') self.opt = torch.optim.Adam(self.network.parameters(), config.lr, amsgrad=True) ...
class UnityEnv(): def __init__(self, env_path, train_mode=True): self.brain = None self.brain_name = None self.train_mode = train_mode self.env = self.create_unity_env(env_path) self.action_space = self.brain.vector_action_space_size self.observation_space = self.b...
class Config(): DEVICE = (torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')) def __init__(self): self.device = ('cuda:0' if torch.cuda.is_available() else 'cpu') self.action_size = 2 self.state_dim = 8 self.action_dim = 2 self.play_only = Tru...
class Env_store(): def __init__(self, dim, state_dim): self.actions = tensor(dim) self.rewards = tensor(dim) self.advantage = tensor(dim) self.states = tensor(state_dim) self.network_output = None self.dones = tensor(dim) def populate(self, states, rewards, do...
class PPONetwork(nn.Module): 'Actor (Policy) Model.' def __init__(self, state_size, action_size, hidden_size): 'Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n ...
class Storage(): def __init__(self, size, keys=None): if (keys is None): keys = [] keys = (keys + ['s', 'a', 'r', 'm', 'v', 'q', 'pi', 'log_pi', 'ent', 'adv', 'ret', 'q_a', 'log_pi_a', 'mean']) self.keys = keys self.size = size self.reset() def add(self, d...
def random_sample(indices, batch_size): indices = np.asarray(np.random.permutation(indices)) batches = indices[:((len(indices) // batch_size) * batch_size)].reshape((- 1), batch_size) for batch in batches: (yield batch) r = (len(indices) % batch_size) if r: (yield indices[(- r):])
def tensor(x): if isinstance(x, torch.Tensor): return x x = torch.tensor(x, device=Config.DEVICE, dtype=torch.float32) return x
def skip_submodules(app, what, name, obj, skip, options): return (name.endswith('__init__') or name.startswith('diart.console') or name.startswith('diart.argdoc'))
def setup(sphinx): sphinx.connect('autoapi-skip-member', skip_submodules)
class AudioLoader(): def __init__(self, sample_rate: int, mono: bool=True): self.sample_rate = sample_rate self.mono = mono def load(self, filepath: FilePath) -> torch.Tensor: 'Load an audio file into a torch.Tensor.\n\n Parameters\n ----------\n filepath : FileP...
class AggregationStrategy(ABC): 'Abstract class representing a strategy to aggregate overlapping buffers\n\n Parameters\n ----------\n cropping_mode: ("strict", "loose", "center"), optional\n Defines the mode to crop buffer chunks as in pyannote.core.\n See https://pyannote.github.io/pyanno...
class HammingWeightedAverageStrategy(AggregationStrategy): 'Compute the average weighted by the corresponding Hamming-window aligned to each buffer' def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray: (num_frames, num_speakers) = buffers[0].data.shape (hamm...
class AverageStrategy(AggregationStrategy): 'Compute a simple average over the focus region' def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray: intersection = np.stack([buffer.crop(focus, mode=self.cropping_mode, fixed=focus.duration) for buffer in buffers]) ...
class FirstOnlyStrategy(AggregationStrategy): 'Instead of aggregating, keep the first focus region in the buffer list' def aggregate(self, buffers: List[SlidingWindowFeature], focus: Segment) -> np.ndarray: return buffers[0].crop(focus, mode=self.cropping_mode, fixed=focus.duration)
class DelayedAggregation(): 'Aggregate aligned overlapping windows of the same duration\n across sliding buffers with a specific step and latency.\n\n Parameters\n ----------\n step: float\n Shift between two consecutive buffers, in seconds.\n latency: float, optional\n Desired latenc...
@dataclass class HyperParameter(): 'Represents a pipeline hyper-parameter that can be tuned by diart' name: Text 'Name of the hyper-parameter (e.g. tau_active)' low: float 'Lowest value that this parameter can take' high: float 'Highest value that this parameter can take' @staticmetho...
class PipelineConfig(ABC): 'Configuration containing the required\n parameters to build and run a pipeline' @property @abstractmethod def duration(self) -> float: 'The duration of an input audio chunk (in seconds)' pass @property @abstractmethod def step(self) -> float...
class Pipeline(ABC): 'Represents a streaming audio pipeline' @staticmethod @abstractmethod def get_config_class() -> type: pass @staticmethod @abstractmethod def suggest_metric() -> BaseMetric: pass @staticmethod @abstractmethod def hyper_parameters() -> Sequ...
class SpeakerDiarizationConfig(base.PipelineConfig): def __init__(self, segmentation: (m.SegmentationModel | None)=None, embedding: (m.EmbeddingModel | None)=None, duration: float=5, step: float=0.5, latency: ((float | Literal[('max', 'min')]) | None)=None, tau_active: float=0.6, rho_update: float=0.3, delta_new...
class SpeakerDiarization(base.Pipeline): def __init__(self, config: (SpeakerDiarizationConfig | None)=None): self._config = (SpeakerDiarizationConfig() if (config is None) else config) msg = f'Latency should be in the range [{self._config.step}, {self._config.duration}]' assert (self._con...