Skip to content

Utils

closest_power_2(x)

Find the closest power of 2 to a given number.

Parameters:

Name Type Description Default
x float

The number to find the closest power of 2 to.

required

Returns:

Type Description
int

The closest power of 2 to the given number.

Source code in models/tts/styledtts2/diffusion/utils.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def closest_power_2(x: float) -> int:
    r"""Find the closest power of 2 to a given number.

    Args:
        x: The number to find the closest power of 2 to.

    Returns:
        The closest power of 2 to the given number.
    """
    exponent = log2(x)
    distance_fn = lambda z: abs(x - 2 ** z)
    exponent_closest = min((floor(exponent), ceil(exponent)), key=distance_fn)
    return 2 ** int(exponent_closest)

default(val, d)

Return the value if it exists, otherwise return the default value.

Parameters:

Name Type Description Default
val Optional[T]

The value to check.

required
d Union[Callable[..., T], T]

The default value to return if the value does not exist.

required

Returns:

Type Description
T

The value if it exists, otherwise the default value.

Source code in models/tts/styledtts2/diffusion/utils.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def default(val: Optional[T], d: Union[Callable[..., T], T]) -> T:
    r"""Return the value if it exists, otherwise return the default value.

    Args:
        val: The value to check.
        d: The default value to return if the value does not exist.

    Returns:
        The value if it exists, otherwise the default value.
    """
    if exists(val):
        return val
    if callable(d):
        return d()
    else:
        return d

exists(val)

Check if a value is not None.

Parameters:

Name Type Description Default
val Optional[T]

The value to check.

required

Returns:

Type Description
TypeGuard[T]

True if the value is not None, False otherwise.

Source code in models/tts/styledtts2/diffusion/utils.py
11
12
13
14
15
16
17
18
19
20
def exists(val: Optional[T]) -> TypeGuard[T]:
    r"""Check if a value is not None.

    Args:
        val: The value to check.

    Returns:
        True if the value is not None, False otherwise.
    """
    return val is not None

group_dict_by_prefix(prefix, d)

Group a dictionary by keys that start with a given prefix.

Parameters:

Name Type Description Default
prefix str

The prefix to group by.

required
d Dict

The dictionary to group.

required

Returns:

Type Description
Tuple[Dict, Dict]

A tuple of two dictionaries: one with keys that start with the prefix, and one with keys that do not.

Source code in models/tts/styledtts2/diffusion/utils.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def group_dict_by_prefix(prefix: str, d: Dict) -> Tuple[Dict, Dict]:
    r"""Group a dictionary by keys that start with a given prefix.

    Args:
        prefix: The prefix to group by.
        d: The dictionary to group.

    Returns:
        A tuple of two dictionaries: one with keys that start with the prefix, and one with keys that do not.
    """
    return_dicts: Tuple[Dict, Dict] = ({}, {})
    for key in d:
        no_prefix = int(not key.startswith(prefix))
        return_dicts[no_prefix][key] = d[key]
    return return_dicts

groupby(prefix, d, keep_prefix=False)

Group a dictionary by keys that start with a given prefix and optionally remove the prefix from the keys.

Parameters:

Name Type Description Default
prefix str

The prefix to group by.

required
d Dict

The dictionary to group.

required
keep_prefix bool

Whether to keep the prefix in the keys.

False

Returns:

Type Description
Tuple[Dict, Dict]

A tuple of two dictionaries: one with keys that start with the prefix, and one with keys that do not.

Source code in models/tts/styledtts2/diffusion/utils.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def groupby(prefix: str, d: Dict, keep_prefix: bool = False) -> Tuple[Dict, Dict]:
    r"""Group a dictionary by keys that start with a given prefix and optionally remove the prefix from the keys.

    Args:
        prefix: The prefix to group by.
        d: The dictionary to group.
        keep_prefix: Whether to keep the prefix in the keys.

    Returns:
        A tuple of two dictionaries: one with keys that start with the prefix, and one with keys that do not.
    """
    kwargs_with_prefix, kwargs = group_dict_by_prefix(prefix, d)
    if keep_prefix:
        return kwargs_with_prefix, kwargs
    kwargs_no_prefix = {k[len(prefix) :]: v for k, v in kwargs_with_prefix.items()}
    return kwargs_no_prefix, kwargs

iff(condition, value)

Return the value if the condition is True, None otherwise.

Parameters:

Name Type Description Default
condition bool

The condition to check.

required
value T

The value to return if the condition is True.

required

Returns:

Type Description
Optional[T]

The value if the condition is True, None otherwise.

Source code in models/tts/styledtts2/diffusion/utils.py
23
24
25
26
27
28
29
30
31
32
33
def iff(condition: bool, value: T) -> Optional[T]:
    r"""Return the value if the condition is True, None otherwise.

    Args:
        condition: The condition to check.
        value: The value to return if the condition is True.

    Returns:
        The value if the condition is True, None otherwise.
    """
    return value if condition else None

is_sequence(obj)

Check if an object is a list or a tuple.

Parameters:

Name Type Description Default
obj T

The object to check.

required

Returns:

Type Description
TypeGuard[Union[list, tuple]]

True if the object is a list or a tuple, False otherwise.

Source code in models/tts/styledtts2/diffusion/utils.py
36
37
38
39
40
41
42
43
44
45
def is_sequence(obj: T) -> TypeGuard[Union[list, tuple]]:
    r"""Check if an object is a list or a tuple.

    Args:
        obj: The object to check.

    Returns:
        True if the object is a list or a tuple, False otherwise.
    """
    return isinstance(obj, (list, tuple))

prefix_dict(prefix, d)

Add a prefix to all keys in a dictionary.

Parameters:

Name Type Description Default
prefix str

The prefix to add.

required
d Dict

The dictionary to modify.

required

Returns:

Type Description
Dict

The modified dictionary with the prefix added to all keys.

Source code in models/tts/styledtts2/diffusion/utils.py
169
170
171
172
173
174
175
176
177
178
179
def prefix_dict(prefix: str, d: Dict) -> Dict:
    r"""Add a prefix to all keys in a dictionary.

    Args:
        prefix: The prefix to add.
        d: The dictionary to modify.

    Returns:
        The modified dictionary with the prefix added to all keys.
    """
    return {prefix + str(k): v for k, v in d.items()}

prod(vals)

Calculate the product of a sequence of integers.

Parameters:

Name Type Description Default
vals Sequence[int]

The sequence of integers.

required

Returns:

Type Description
int

The product of the sequence of integers.

Source code in models/tts/styledtts2/diffusion/utils.py
84
85
86
87
88
89
90
91
92
93
def prod(vals: Sequence[int]) -> int:
    r"""Calculate the product of a sequence of integers.

    Args:
        vals: The sequence of integers.

    Returns:
        The product of the sequence of integers.
    """
    return reduce(lambda x, y: x * y, vals)

rand_bool(shape, proba)

Generate a tensor of random booleans.

Parameters:

Name Type Description Default
shape Tuple[int, ...]

The shape of the tensor.

required
proba float

The probability of a True value.

required
device

The device to create the tensor on.

required

Returns:

Type Description

A tensor of random booleans.

Source code in models/tts/styledtts2/diffusion/utils.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def rand_bool(shape: Tuple[int, ...], proba: float):
    r"""Generate a tensor of random booleans.

    Args:
        shape: The shape of the tensor.
        proba: The probability of a True value.
        device: The device to create the tensor on.

    Returns:
        A tensor of random booleans.
    """
    if proba == 1:
        return torch.ones(shape, dtype=torch.bool)
    elif proba == 0:
        return torch.zeros(shape, dtype=torch.bool)
    else:
        return torch.bernoulli(torch.full(shape, proba)).to(dtype=torch.bool)

to_list(val)

Convert a value or a sequence of values to a list.

Parameters:

Name Type Description Default
val Union[T, Sequence[T]]

The value or sequence of values to convert.

required

Returns:

Type Description
List[T]

The value or sequence of values as a list.

Source code in models/tts/styledtts2/diffusion/utils.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def to_list(val: Union[T, Sequence[T]]) -> List[T]:
    r"""Convert a value or a sequence of values to a list.

    Args:
        val: The value or sequence of values to convert.

    Returns:
        The value or sequence of values as a list.
    """
    if isinstance(val, tuple):
        return list(val)
    if isinstance(val, list):
        return val
    if isinstance(val, Sequence):
        return list(val)
    return [val]