Spaces:
Running on Zero
Running on Zero
Add 14 files (batch 3)
Browse filesFiles changed (14)
- third_party/Matcha-TTS/matcha/models/components/decoder.pyAdded+443
- third_party/Matcha-TTS/matcha/models/components/text_encoder.pyAdded+410
- third_party/Matcha-TTS/matcha/models/components/transformer.pyAdded+316
- third_party/Matcha-TTS/matcha/models/matcha_tts.pyAdded+245
- whisper/assets/gpt2.tiktokenAdded
- whisper/assets/multilingual.tiktokenAdded
- whisper/decoding.pyAdded+826
- whisper/model.pyAdded+314
- whisper/normalizers/english.jsonAdded+1741
- whisper/normalizers/english.pyAdded+550
- whisper/timing.pyAdded+385
- whisper/tokenizer.pyAdded+395
- whisper/transcribe.pyAdded+486
- whisper/utils.pyAdded+302
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443import math
from typing import Optional
import torch
import torch.nn as nn # pylint: disable=consider-using-from-import
import torch.nn.functional as F
from conformer import ConformerBlock
from diffusers.models.activations import get_activation
from einops import pack, rearrange, repeat
from matcha.models.components.transformer import BasicTransformerBlock
class SinusoidalPosEmb(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
assert self.dim % 2 == 0, "SinusoidalPosEmb requires dim to be even"
def forward(self, x, scale=1000):
if x.ndim < 1:
x = x.unsqueeze(0)
device = x.device
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
return emb
class Block1D(torch.nn.Module):
def __init__(self, dim, dim_out, groups=8):
super().__init__()
self.block = torch.nn.Sequential(
torch.nn.Conv1d(dim, dim_out, 3, padding=1),
torch.nn.GroupNorm(groups, dim_out),
nn.Mish(),
)
def forward(self, x, mask):
output = self.block(x * mask)
return output * mask
class ResnetBlock1D(torch.nn.Module):
def __init__(self, dim, dim_out, time_emb_dim, groups=8):
super().__init__()
self.mlp = torch.nn.Sequential(nn.Mish(), torch.nn.Linear(time_emb_dim, dim_out))
self.block1 = Block1D(dim, dim_out, groups=groups)
self.block2 = Block1D(dim_out, dim_out, groups=groups)
self.res_conv = torch.nn.Conv1d(dim, dim_out, 1)
def forward(self, x, mask, time_emb):
h = self.block1(x, mask)
h += self.mlp(time_emb).unsqueeze(-1)
h = self.block2(h, mask)
output = h + self.res_conv(x * mask)
return output
class Downsample1D(nn.Module):
def __init__(self, dim):
super().__init__()
self.conv = torch.nn.Conv1d(dim, dim, 3, 2, 1)
def forward(self, x):
return self.conv(x)
class TimestepEmbedding(nn.Module):
def __init__(
self,
in_channels: int,
time_embed_dim: int,
act_fn: str = "silu",
out_dim: int = None,
post_act_fn: Optional[str] = None,
cond_proj_dim=None,
):
super().__init__()
self.linear_1 = nn.Linear(in_channels, time_embed_dim)
if cond_proj_dim is not None:
self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
else:
self.cond_proj = None
self.act = get_activation(act_fn)
if out_dim is not None:
time_embed_dim_out = out_dim
else:
time_embed_dim_out = time_embed_dim
self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out)
if post_act_fn is None:
self.post_act = None
else:
self.post_act = get_activation(post_act_fn)
def forward(self, sample, condition=None):
if condition is not None:
sample = sample + self.cond_proj(condition)
sample = self.linear_1(sample)
if self.act is not None:
sample = self.act(sample)
sample = self.linear_2(sample)
if self.post_act is not None:
sample = self.post_act(sample)
return sample
class Upsample1D(nn.Module):
"""A 1D upsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
use_conv_transpose (`bool`, default `False`):
option to use a convolution transpose.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
"""
def __init__(self, channels, use_conv=False, use_conv_transpose=True, out_channels=None, name="conv"):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.use_conv_transpose = use_conv_transpose
self.name = name
self.conv = None
if use_conv_transpose:
self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
elif use_conv:
self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
def forward(self, inputs):
assert inputs.shape[1] == self.channels
if self.use_conv_transpose:
return self.conv(inputs)
outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
if self.use_conv:
outputs = self.conv(outputs)
return outputs
class ConformerWrapper(ConformerBlock):
def __init__( # pylint: disable=useless-super-delegation
self,
*,
dim,
dim_head=64,
heads=8,
ff_mult=4,
conv_expansion_factor=2,
conv_kernel_size=31,
attn_dropout=0,
ff_dropout=0,
conv_dropout=0,
conv_causal=False,
):
super().__init__(
dim=dim,
dim_head=dim_head,
heads=heads,
ff_mult=ff_mult,
conv_expansion_factor=conv_expansion_factor,
conv_kernel_size=conv_kernel_size,
attn_dropout=attn_dropout,
ff_dropout=ff_dropout,
conv_dropout=conv_dropout,
conv_causal=conv_causal,
)
def forward(
self,
hidden_states,
attention_mask,
encoder_hidden_states=None,
encoder_attention_mask=None,
timestep=None,
):
return super().forward(x=hidden_states, mask=attention_mask.bool())
class Decoder(nn.Module):
def __init__(
self,
in_channels,
out_channels,
channels=(256, 256),
dropout=0.05,
attention_head_dim=64,
n_blocks=1,
num_mid_blocks=2,
num_heads=4,
act_fn="snake",
down_block_type="transformer",
mid_block_type="transformer",
up_block_type="transformer",
):
super().__init__()
channels = tuple(channels)
self.in_channels = in_channels
self.out_channels = out_channels
self.time_embeddings = SinusoidalPosEmb(in_channels)
time_embed_dim = channels[0] * 4
self.time_mlp = TimestepEmbedding(
in_channels=in_channels,
time_embed_dim=time_embed_dim,
act_fn="silu",
)
self.down_blocks = nn.ModuleList([])
self.mid_blocks = nn.ModuleList([])
self.up_blocks = nn.ModuleList([])
output_channel = in_channels
for i in range(len(channels)): # pylint: disable=consider-using-enumerate
input_channel = output_channel
output_channel = channels[i]
is_last = i == len(channels) - 1
resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
transformer_blocks = nn.ModuleList(
[
self.get_block(
down_block_type,
output_channel,
attention_head_dim,
num_heads,
dropout,
act_fn,
)
for _ in range(n_blocks)
]
)
downsample = (
Downsample1D(output_channel) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1)
)
self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
for i in range(num_mid_blocks):
input_channel = channels[-1]
out_channels = channels[-1]
resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
transformer_blocks = nn.ModuleList(
[
self.get_block(
mid_block_type,
output_channel,
attention_head_dim,
num_heads,
dropout,
act_fn,
)
for _ in range(n_blocks)
]
)
self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
channels = channels[::-1] + (channels[0],)
for i in range(len(channels) - 1):
input_channel = channels[i]
output_channel = channels[i + 1]
is_last = i == len(channels) - 2
resnet = ResnetBlock1D(
dim=2 * input_channel,
dim_out=output_channel,
time_emb_dim=time_embed_dim,
)
transformer_blocks = nn.ModuleList(
[
self.get_block(
up_block_type,
output_channel,
attention_head_dim,
num_heads,
dropout,
act_fn,
)
for _ in range(n_blocks)
]
)
upsample = (
Upsample1D(output_channel, use_conv_transpose=True)
if not is_last
else nn.Conv1d(output_channel, output_channel, 3, padding=1)
)
self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
self.final_block = Block1D(channels[-1], channels[-1])
self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
self.initialize_weights()
# nn.init.normal_(self.final_proj.weight)
@staticmethod
def get_block(block_type, dim, attention_head_dim, num_heads, dropout, act_fn):
if block_type == "conformer":
block = ConformerWrapper(
dim=dim,
dim_head=attention_head_dim,
heads=num_heads,
ff_mult=1,
conv_expansion_factor=2,
ff_dropout=dropout,
attn_dropout=dropout,
conv_dropout=dropout,
conv_kernel_size=31,
)
elif block_type == "transformer":
block = BasicTransformerBlock(
dim=dim,
num_attention_heads=num_heads,
attention_head_dim=attention_head_dim,
dropout=dropout,
activation_fn=act_fn,
)
else:
raise ValueError(f"Unknown block type {block_type}")
return block
def initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv1d):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.GroupNorm):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x, mask, mu, t, spks=None, cond=None):
"""Forward pass of the UNet1DConditional model.
Args:
x (torch.Tensor): shape (batch_size, in_channels, time)
mask (_type_): shape (batch_size, 1, time)
t (_type_): shape (batch_size)
spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
cond (_type_, optional): placeholder for future use. Defaults to None.
Raises:
ValueError: _description_
ValueError: _description_
Returns:
_type_: _description_
"""
t = self.time_embeddings(t)
t = self.time_mlp(t)
x = pack([x, mu], "b * t")[0]
if spks is not None:
spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
x = pack([x, spks], "b * t")[0]
hiddens = []
masks = [mask]
for resnet, transformer_blocks, downsample in self.down_blocks:
mask_down = masks[-1]
x = resnet(x, mask_down, t)
x = rearrange(x, "b c t -> b t c")
mask_down = rearrange(mask_down, "b 1 t -> b t")
for transformer_block in transformer_blocks:
x = transformer_block(
hidden_states=x,
attention_mask=mask_down,
timestep=t,
)
x = rearrange(x, "b t c -> b c t")
mask_down = rearrange(mask_down, "b t -> b 1 t")
hiddens.append(x) # Save hidden states for skip connections
x = downsample(x * mask_down)
masks.append(mask_down[:, :, ::2])
masks = masks[:-1]
mask_mid = masks[-1]
for resnet, transformer_blocks in self.mid_blocks:
x = resnet(x, mask_mid, t)
x = rearrange(x, "b c t -> b t c")
mask_mid = rearrange(mask_mid, "b 1 t -> b t")
for transformer_block in transformer_blocks:
x = transformer_block(
hidden_states=x,
attention_mask=mask_mid,
timestep=t,
)
x = rearrange(x, "b t c -> b c t")
mask_mid = rearrange(mask_mid, "b t -> b 1 t")
for resnet, transformer_blocks, upsample in self.up_blocks:
mask_up = masks.pop()
x = resnet(pack([x, hiddens.pop()], "b * t")[0], mask_up, t)
x = rearrange(x, "b c t -> b t c")
mask_up = rearrange(mask_up, "b 1 t -> b t")
for transformer_block in transformer_blocks:
x = transformer_block(
hidden_states=x,
attention_mask=mask_up,
timestep=t,
)
x = rearrange(x, "b t c -> b c t")
mask_up = rearrange(mask_up, "b t -> b 1 t")
x = upsample(x * mask_up)
x = self.final_block(x, mask_up)
output = self.final_proj(x * mask_up)
return output * mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410""" from https://github.com/jaywalnut310/glow-tts """
import math
import torch
import torch.nn as nn # pylint: disable=consider-using-from-import
from einops import rearrange
import matcha.utils as utils # pylint: disable=consider-using-from-import
from matcha.utils.model import sequence_mask
log = utils.get_pylogger(__name__)
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-4):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = torch.nn.Parameter(torch.ones(channels))
self.beta = torch.nn.Parameter(torch.zeros(channels))
def forward(self, x):
n_dims = len(x.shape)
mean = torch.mean(x, 1, keepdim=True)
variance = torch.mean((x - mean) ** 2, 1, keepdim=True)
x = (x - mean) * torch.rsqrt(variance + self.eps)
shape = [1, -1] + [1] * (n_dims - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
class ConvReluNorm(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.conv_layers = torch.nn.ModuleList()
self.norm_layers = torch.nn.ModuleList()
self.conv_layers.append(torch.nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size // 2))
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = torch.nn.Sequential(torch.nn.ReLU(), torch.nn.Dropout(p_dropout))
for _ in range(n_layers - 1):
self.conv_layers.append(
torch.nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size // 2)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = torch.nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.p_dropout = p_dropout
self.drop = torch.nn.Dropout(p_dropout)
self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.norm_1 = LayerNorm(filter_channels)
self.conv_2 = torch.nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.norm_2 = LayerNorm(filter_channels)
self.proj = torch.nn.Conv1d(filter_channels, 1, 1)
def forward(self, x, x_mask):
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.norm_1(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
x = torch.relu(x)
x = self.norm_2(x)
x = self.drop(x)
x = self.proj(x * x_mask)
return x * x_mask
class RotaryPositionalEmbeddings(nn.Module):
"""
## RoPE module
Rotary encoding transforms pairs of features by rotating in the 2D plane.
That is, it organizes the $d$ features as $\frac{d}{2}$ pairs.
Each pair can be considered a coordinate in a 2D plane, and the encoding will rotate it
by an angle depending on the position of the token.
"""
def __init__(self, d: int, base: int = 10_000):
r"""
* `d` is the number of features $d$
* `base` is the constant used for calculating $\Theta$
"""
super().__init__()
self.base = base
self.d = int(d)
self.cos_cached = None
self.sin_cached = None
def _build_cache(self, x: torch.Tensor):
r"""
Cache $\cos$ and $\sin$ values
"""
# Return if cache is already built
if self.cos_cached is not None and x.shape[0] <= self.cos_cached.shape[0]:
return
# Get sequence length
seq_len = x.shape[0]
# $\Theta = {\theta_i = 10000^{-\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
theta = 1.0 / (self.base ** (torch.arange(0, self.d, 2).float() / self.d)).to(x.device)
# Create position indexes `[0, 1, ..., seq_len - 1]`
seq_idx = torch.arange(seq_len, device=x.device).float().to(x.device)
# Calculate the product of position index and $\theta_i$
idx_theta = torch.einsum("n,d->nd", seq_idx, theta)
# Concatenate so that for row $m$ we have
# $[m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}, m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}]$
idx_theta2 = torch.cat([idx_theta, idx_theta], dim=1)
# Cache them
self.cos_cached = idx_theta2.cos()[:, None, None, :]
self.sin_cached = idx_theta2.sin()[:, None, None, :]
def _neg_half(self, x: torch.Tensor):
# $\frac{d}{2}$
d_2 = self.d // 2
# Calculate $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
return torch.cat([-x[:, :, :, d_2:], x[:, :, :, :d_2]], dim=-1)
def forward(self, x: torch.Tensor):
"""
* `x` is the Tensor at the head of a key or a query with shape `[seq_len, batch_size, n_heads, d]`
"""
# Cache $\cos$ and $\sin$ values
x = rearrange(x, "b h t d -> t b h d")
self._build_cache(x)
# Split the features, we can choose to apply rotary embeddings only to a partial set of features.
x_rope, x_pass = x[..., : self.d], x[..., self.d :]
# Calculate
# $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
neg_half_x = self._neg_half(x_rope)
x_rope = (x_rope * self.cos_cached[: x.shape[0]]) + (neg_half_x * self.sin_cached[: x.shape[0]])
return rearrange(torch.cat((x_rope, x_pass), dim=-1), "t b h d -> b h t d")
class MultiHeadAttention(nn.Module):
def __init__(
self,
channels,
out_channels,
n_heads,
heads_share=True,
p_dropout=0.0,
proximal_bias=False,
proximal_init=False,
):
super().__init__()
assert channels % n_heads == 0
self.channels = channels
self.out_channels = out_channels
self.n_heads = n_heads
self.heads_share = heads_share
self.proximal_bias = proximal_bias
self.p_dropout = p_dropout
self.attn = None
self.k_channels = channels // n_heads
self.conv_q = torch.nn.Conv1d(channels, channels, 1)
self.conv_k = torch.nn.Conv1d(channels, channels, 1)
self.conv_v = torch.nn.Conv1d(channels, channels, 1)
# from https://nn.labml.ai/transformers/rope/index.html
self.query_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
self.key_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
self.conv_o = torch.nn.Conv1d(channels, out_channels, 1)
self.drop = torch.nn.Dropout(p_dropout)
torch.nn.init.xavier_uniform_(self.conv_q.weight)
torch.nn.init.xavier_uniform_(self.conv_k.weight)
if proximal_init:
self.conv_k.weight.data.copy_(self.conv_q.weight.data)
self.conv_k.bias.data.copy_(self.conv_q.bias.data)
torch.nn.init.xavier_uniform_(self.conv_v.weight)
def forward(self, x, c, attn_mask=None):
q = self.conv_q(x)
k = self.conv_k(c)
v = self.conv_v(c)
x, self.attn = self.attention(q, k, v, mask=attn_mask)
x = self.conv_o(x)
return x
def attention(self, query, key, value, mask=None):
b, d, t_s, t_t = (*key.size(), query.size(2))
query = rearrange(query, "b (h c) t-> b h t c", h=self.n_heads)
key = rearrange(key, "b (h c) t-> b h t c", h=self.n_heads)
value = rearrange(value, "b (h c) t-> b h t c", h=self.n_heads)
query = self.query_rotary_pe(query)
key = self.key_rotary_pe(key)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels)
if self.proximal_bias:
assert t_s == t_t, "Proximal bias is only available for self-attention."
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e4)
p_attn = torch.nn.functional.softmax(scores, dim=-1)
p_attn = self.drop(p_attn)
output = torch.matmul(p_attn, value)
output = output.transpose(2, 3).contiguous().view(b, d, t_t)
return output, p_attn
@staticmethod
def _attention_bias_proximal(length):
r = torch.arange(length, dtype=torch.float32)
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
class FFN(nn.Module):
def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.conv_2 = torch.nn.Conv1d(filter_channels, out_channels, kernel_size, padding=kernel_size // 2)
self.drop = torch.nn.Dropout(p_dropout)
def forward(self, x, x_mask):
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
return x * x_mask
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
**kwargs,
):
super().__init__()
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.drop = torch.nn.Dropout(p_dropout)
self.attn_layers = torch.nn.ModuleList()
self.norm_layers_1 = torch.nn.ModuleList()
self.ffn_layers = torch.nn.ModuleList()
self.norm_layers_2 = torch.nn.ModuleList()
for _ in range(self.n_layers):
self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask):
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
for i in range(self.n_layers):
x = x * x_mask
y = self.attn_layers[i](x, x, attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class TextEncoder(nn.Module):
def __init__(
self,
encoder_type,
encoder_params,
duration_predictor_params,
n_vocab,
n_spks=1,
spk_emb_dim=128,
):
super().__init__()
self.encoder_type = encoder_type
self.n_vocab = n_vocab
self.n_feats = encoder_params.n_feats
self.n_channels = encoder_params.n_channels
self.spk_emb_dim = spk_emb_dim
self.n_spks = n_spks
self.emb = torch.nn.Embedding(n_vocab, self.n_channels)
torch.nn.init.normal_(self.emb.weight, 0.0, self.n_channels**-0.5)
if encoder_params.prenet:
self.prenet = ConvReluNorm(
self.n_channels,
self.n_channels,
self.n_channels,
kernel_size=5,
n_layers=3,
p_dropout=0.5,
)
else:
self.prenet = lambda x, x_mask: x
self.encoder = Encoder(
encoder_params.n_channels + (spk_emb_dim if n_spks > 1 else 0),
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
self.proj_m = torch.nn.Conv1d(self.n_channels + (spk_emb_dim if n_spks > 1 else 0), self.n_feats, 1)
self.proj_w = DurationPredictor(
self.n_channels + (spk_emb_dim if n_spks > 1 else 0),
duration_predictor_params.filter_channels_dp,
duration_predictor_params.kernel_size,
duration_predictor_params.p_dropout,
)
def forward(self, x, x_lengths, spks=None):
"""Run forward pass to the transformer based encoder and duration predictor
Args:
x (torch.Tensor): text input
shape: (batch_size, max_text_length)
x_lengths (torch.Tensor): text input lengths
shape: (batch_size,)
spks (torch.Tensor, optional): speaker ids. Defaults to None.
shape: (batch_size,)
Returns:
mu (torch.Tensor): average output of the encoder
shape: (batch_size, n_feats, max_text_length)
logw (torch.Tensor): log duration predicted by the duration predictor
shape: (batch_size, 1, max_text_length)
x_mask (torch.Tensor): mask for the text input
shape: (batch_size, 1, max_text_length)
"""
x = self.emb(x) * math.sqrt(self.n_channels)
x = torch.transpose(x, 1, -1)
x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
x = self.prenet(x, x_mask)
if self.n_spks > 1:
x = torch.cat([x, spks.unsqueeze(-1).repeat(1, 1, x.shape[-1])], dim=1)
x = self.encoder(x, x_mask)
mu = self.proj_m(x) * x_mask
x_dp = torch.detach(x)
logw = self.proj_w(x_dp, x_mask)
return mu, logw, x_mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316from typing import Any, Dict, Optional
import torch
import torch.nn as nn # pylint: disable=consider-using-from-import
from diffusers.models.attention import (
GEGLU,
GELU,
AdaLayerNorm,
AdaLayerNormZero,
ApproximateGELU,
)
from diffusers.models.attention_processor import Attention
from diffusers.models.lora import LoRACompatibleLinear
from diffusers.utils.torch_utils import maybe_allow_in_graph
class SnakeBeta(nn.Module):
"""
A modified Snake function which uses separate parameters for the magnitude of the periodic components
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter that controls frequency
- beta - trainable parameter that controls magnitude
References:
- This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
https://arxiv.org/abs/2006.08195
Examples:
>>> a1 = snakebeta(256)
>>> x = torch.randn(256)
>>> x = a1(x)
"""
def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
"""
Initialization.
INPUT:
- in_features: shape of the input
- alpha - trainable parameter that controls frequency
- beta - trainable parameter that controls magnitude
alpha is initialized to 1 by default, higher values = higher-frequency.
beta is initialized to 1 by default, higher values = higher-magnitude.
alpha will be trained along with the rest of your model.
"""
super().__init__()
self.in_features = out_features if isinstance(out_features, list) else [out_features]
self.proj = LoRACompatibleLinear(in_features, out_features)
# initialize alpha
self.alpha_logscale = alpha_logscale
if self.alpha_logscale: # log scale alphas initialized to zeros
self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
else: # linear scale alphas initialized to ones
self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
self.alpha.requires_grad = alpha_trainable
self.beta.requires_grad = alpha_trainable
self.no_div_by_zero = 0.000000001
def forward(self, x):
"""
Forward pass of the function.
Applies the function to the input elementwise.
SnakeBeta ∶= x + 1/b * sin^2 (xa)
"""
x = self.proj(x)
if self.alpha_logscale:
alpha = torch.exp(self.alpha)
beta = torch.exp(self.beta)
else:
alpha = self.alpha
beta = self.beta
x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
return x
class FeedForward(nn.Module):
r"""
A feed-forward layer.
Parameters:
dim (`int`): The number of channels in the input.
dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
"""
def __init__(
self,
dim: int,
dim_out: Optional[int] = None,
mult: int = 4,
dropout: float = 0.0,
activation_fn: str = "geglu",
final_dropout: bool = False,
):
super().__init__()
inner_dim = int(dim * mult)
dim_out = dim_out if dim_out is not None else dim
if activation_fn == "gelu":
act_fn = GELU(dim, inner_dim)
if activation_fn == "gelu-approximate":
act_fn = GELU(dim, inner_dim, approximate="tanh")
elif activation_fn == "geglu":
act_fn = GEGLU(dim, inner_dim)
elif activation_fn == "geglu-approximate":
act_fn = ApproximateGELU(dim, inner_dim)
elif activation_fn == "snakebeta":
act_fn = SnakeBeta(dim, inner_dim)
self.net = nn.ModuleList([])
# project in
self.net.append(act_fn)
# project dropout
self.net.append(nn.Dropout(dropout))
# project out
self.net.append(LoRACompatibleLinear(inner_dim, dim_out))
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
if final_dropout:
self.net.append(nn.Dropout(dropout))
def forward(self, hidden_states):
for module in self.net:
hidden_states = module(hidden_states)
return hidden_states
@maybe_allow_in_graph
class BasicTransformerBlock(nn.Module):
r"""
A basic Transformer block.
Parameters:
dim (`int`): The number of channels in the input and output.
num_attention_heads (`int`): The number of heads to use for multi-head attention.
attention_head_dim (`int`): The number of channels in each head.
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
only_cross_attention (`bool`, *optional*):
Whether to use only cross-attention layers. In this case two cross attention layers are used.
double_self_attention (`bool`, *optional*):
Whether to use two self-attention layers. In this case no cross attention layers are used.
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
num_embeds_ada_norm (:
obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
attention_bias (:
obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
"""
def __init__(
self,
dim: int,
num_attention_heads: int,
attention_head_dim: int,
dropout=0.0,
cross_attention_dim: Optional[int] = None,
activation_fn: str = "geglu",
num_embeds_ada_norm: Optional[int] = None,
attention_bias: bool = False,
only_cross_attention: bool = False,
double_self_attention: bool = False,
upcast_attention: bool = False,
norm_elementwise_affine: bool = True,
norm_type: str = "layer_norm",
final_dropout: bool = False,
):
super().__init__()
self.only_cross_attention = only_cross_attention
self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
raise ValueError(
f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
)
# Define 3 blocks. Each block has its own normalization layer.
# 1. Self-Attn
if self.use_ada_layer_norm:
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
elif self.use_ada_layer_norm_zero:
self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
else:
self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
self.attn1 = Attention(
query_dim=dim,
heads=num_attention_heads,
dim_head=attention_head_dim,
dropout=dropout,
bias=attention_bias,
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
upcast_attention=upcast_attention,
)
# 2. Cross-Attn
if cross_attention_dim is not None or double_self_attention:
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
# the second cross attention block.
self.norm2 = (
AdaLayerNorm(dim, num_embeds_ada_norm)
if self.use_ada_layer_norm
else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
)
self.attn2 = Attention(
query_dim=dim,
cross_attention_dim=cross_attention_dim if not double_self_attention else None,
heads=num_attention_heads,
dim_head=attention_head_dim,
dropout=dropout,
bias=attention_bias,
upcast_attention=upcast_attention,
# scale_qk=False, # uncomment this to not to use flash attention
) # is self-attn if encoder_hidden_states is none
else:
self.norm2 = None
self.attn2 = None
# 3. Feed-forward
self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
# let chunk size default to None
self._chunk_size = None
self._chunk_dim = 0
def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
# Sets chunk feed-forward
self._chunk_size = chunk_size
self._chunk_dim = dim
def forward(
self,
hidden_states: torch.FloatTensor,
attention_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
timestep: Optional[torch.LongTensor] = None,
cross_attention_kwargs: Dict[str, Any] = None,
class_labels: Optional[torch.LongTensor] = None,
):
# Notice that normalization is always applied before the real computation in the following blocks.
# 1. Self-Attention
if self.use_ada_layer_norm:
norm_hidden_states = self.norm1(hidden_states, timestep)
elif self.use_ada_layer_norm_zero:
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
)
else:
norm_hidden_states = self.norm1(hidden_states)
cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
attn_output = self.attn1(
norm_hidden_states,
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
**cross_attention_kwargs,
)
if self.use_ada_layer_norm_zero:
attn_output = gate_msa.unsqueeze(1) * attn_output
hidden_states = attn_output + hidden_states
# 2. Cross-Attention
if self.attn2 is not None:
norm_hidden_states = (
self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
)
attn_output = self.attn2(
norm_hidden_states,
encoder_hidden_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
**cross_attention_kwargs,
)
hidden_states = attn_output + hidden_states
# 3. Feed-forward
norm_hidden_states = self.norm3(hidden_states)
if self.use_ada_layer_norm_zero:
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
if self._chunk_size is not None:
# "feed_forward_chunk_size" can be used to save memory
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
raise ValueError(
f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
)
num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
ff_output = torch.cat(
[self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
dim=self._chunk_dim,
)
else:
ff_output = self.ff(norm_hidden_states)
if self.use_ada_layer_norm_zero:
ff_output = gate_mlp.unsqueeze(1) * ff_output
hidden_states = ff_output + hidden_states
return hidden_states123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import datetime as dt
import math
import random
import torch
import matcha.utils.monotonic_align as monotonic_align # pylint: disable=consider-using-from-import
from matcha import utils
from matcha.models.baselightningmodule import BaseLightningClass
from matcha.models.components.flow_matching import CFM
from matcha.models.components.text_encoder import TextEncoder
from matcha.utils.model import (
denormalize,
duration_loss,
fix_len_compatibility,
generate_path,
sequence_mask,
)
log = utils.get_pylogger(__name__)
class MatchaTTS(BaseLightningClass): # 🍵
def __init__(
self,
n_vocab,
n_spks,
spk_emb_dim,
n_feats,
encoder,
decoder,
cfm,
data_statistics,
out_size,
optimizer=None,
scheduler=None,
prior_loss=True,
use_precomputed_durations=False,
):
super().__init__()
self.save_hyperparameters(logger=False)
self.n_vocab = n_vocab
self.n_spks = n_spks
self.spk_emb_dim = spk_emb_dim
self.n_feats = n_feats
self.out_size = out_size
self.prior_loss = prior_loss
self.use_precomputed_durations = use_precomputed_durations
if n_spks > 1:
self.spk_emb = torch.nn.Embedding(n_spks, spk_emb_dim)
self.encoder = TextEncoder(
encoder.encoder_type,
encoder.encoder_params,
encoder.duration_predictor_params,
n_vocab,
n_spks,
spk_emb_dim,
)
self.decoder = CFM(
in_channels=2 * encoder.encoder_params.n_feats,
out_channel=encoder.encoder_params.n_feats,
cfm_params=cfm,
decoder_params=decoder,
n_spks=n_spks,
spk_emb_dim=spk_emb_dim,
)
self.update_data_statistics(data_statistics)
@torch.inference_mode()
def synthesise(self, x, x_lengths, n_timesteps, temperature=1.0, spks=None, length_scale=1.0):
"""
Generates mel-spectrogram from text. Returns:
1. encoder outputs
2. decoder outputs
3. generated alignment
Args:
x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
shape: (batch_size, max_text_length)
x_lengths (torch.Tensor): lengths of texts in batch.
shape: (batch_size,)
n_timesteps (int): number of steps to use for reverse diffusion in decoder.
temperature (float, optional): controls variance of terminal distribution.
spks (bool, optional): speaker ids.
shape: (batch_size,)
length_scale (float, optional): controls speech pace.
Increase value to slow down generated speech and vice versa.
Returns:
dict: {
"encoder_outputs": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
# Average mel spectrogram generated by the encoder
"decoder_outputs": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
# Refined mel spectrogram improved by the CFM
"attn": torch.Tensor, shape: (batch_size, max_text_length, max_mel_length),
# Alignment map between text and mel spectrogram
"mel": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
# Denormalized mel spectrogram
"mel_lengths": torch.Tensor, shape: (batch_size,),
# Lengths of mel spectrograms
"rtf": float,
# Real-time factor
}
"""
# For RTF computation
t = dt.datetime.now()
if self.n_spks > 1:
# Get speaker embedding
spks = self.spk_emb(spks.long())
# Get encoder_outputs `mu_x` and log-scaled token durations `logw`
mu_x, logw, x_mask = self.encoder(x, x_lengths, spks)
w = torch.exp(logw) * x_mask
w_ceil = torch.ceil(w) * length_scale
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
y_max_length = y_lengths.max()
y_max_length_ = fix_len_compatibility(y_max_length)
# Using obtained durations `w` construct alignment map `attn`
y_mask = sequence_mask(y_lengths, y_max_length_).unsqueeze(1).to(x_mask.dtype)
attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
attn = generate_path(w_ceil.squeeze(1), attn_mask.squeeze(1)).unsqueeze(1)
# Align encoded text and get mu_y
mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
mu_y = mu_y.transpose(1, 2)
encoder_outputs = mu_y[:, :, :y_max_length]
# Generate sample tracing the probability flow
decoder_outputs = self.decoder(mu_y, y_mask, n_timesteps, temperature, spks)
decoder_outputs = decoder_outputs[:, :, :y_max_length]
t = (dt.datetime.now() - t).total_seconds()
rtf = t * 22050 / (decoder_outputs.shape[-1] * 256)
return {
"encoder_outputs": encoder_outputs,
"decoder_outputs": decoder_outputs,
"attn": attn[:, :, :y_max_length],
"mel": denormalize(decoder_outputs, self.mel_mean, self.mel_std),
"mel_lengths": y_lengths,
"rtf": rtf,
}
def forward(self, x, x_lengths, y, y_lengths, spks=None, out_size=None, cond=None, durations=None):
"""
Computes 3 losses:
1. duration loss: loss between predicted token durations and those extracted by Monotonic Alignment Search (MAS).
2. prior loss: loss between mel-spectrogram and encoder outputs.
3. flow matching loss: loss between mel-spectrogram and decoder outputs.
Args:
x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
shape: (batch_size, max_text_length)
x_lengths (torch.Tensor): lengths of texts in batch.
shape: (batch_size,)
y (torch.Tensor): batch of corresponding mel-spectrograms.
shape: (batch_size, n_feats, max_mel_length)
y_lengths (torch.Tensor): lengths of mel-spectrograms in batch.
shape: (batch_size,)
out_size (int, optional): length (in mel's sampling rate) of segment to cut, on which decoder will be trained.
Should be divisible by 2^{num of UNet downsamplings}. Needed to increase batch size.
spks (torch.Tensor, optional): speaker ids.
shape: (batch_size,)
"""
if self.n_spks > 1:
# Get speaker embedding
spks = self.spk_emb(spks)
# Get encoder_outputs `mu_x` and log-scaled token durations `logw`
mu_x, logw, x_mask = self.encoder(x, x_lengths, spks)
y_max_length = y.shape[-1]
y_mask = sequence_mask(y_lengths, y_max_length).unsqueeze(1).to(x_mask)
attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
if self.use_precomputed_durations:
attn = generate_path(durations.squeeze(1), attn_mask.squeeze(1))
else:
# Use MAS to find most likely alignment `attn` between text and mel-spectrogram
with torch.no_grad():
const = -0.5 * math.log(2 * math.pi) * self.n_feats
factor = -0.5 * torch.ones(mu_x.shape, dtype=mu_x.dtype, device=mu_x.device)
y_square = torch.matmul(factor.transpose(1, 2), y**2)
y_mu_double = torch.matmul(2.0 * (factor * mu_x).transpose(1, 2), y)
mu_square = torch.sum(factor * (mu_x**2), 1).unsqueeze(-1)
log_prior = y_square - y_mu_double + mu_square + const
attn = monotonic_align.maximum_path(log_prior, attn_mask.squeeze(1))
attn = attn.detach() # b, t_text, T_mel
# Compute loss between predicted log-scaled durations and those obtained from MAS
# refered to as prior loss in the paper
logw_ = torch.log(1e-8 + torch.sum(attn.unsqueeze(1), -1)) * x_mask
dur_loss = duration_loss(logw, logw_, x_lengths)
# Cut a small segment of mel-spectrogram in order to increase batch size
# - "Hack" taken from Grad-TTS, in case of Grad-TTS, we cannot train batch size 32 on a 24GB GPU without it
# - Do not need this hack for Matcha-TTS, but it works with it as well
if not isinstance(out_size, type(None)):
max_offset = (y_lengths - out_size).clamp(0)
offset_ranges = list(zip([0] * max_offset.shape[0], max_offset.cpu().numpy()))
out_offset = torch.LongTensor(
[torch.tensor(random.choice(range(start, end)) if end > start else 0) for start, end in offset_ranges]
).to(y_lengths)
attn_cut = torch.zeros(attn.shape[0], attn.shape[1], out_size, dtype=attn.dtype, device=attn.device)
y_cut = torch.zeros(y.shape[0], self.n_feats, out_size, dtype=y.dtype, device=y.device)
y_cut_lengths = []
for i, (y_, out_offset_) in enumerate(zip(y, out_offset)):
y_cut_length = out_size + (y_lengths[i] - out_size).clamp(None, 0)
y_cut_lengths.append(y_cut_length)
cut_lower, cut_upper = out_offset_, out_offset_ + y_cut_length
y_cut[i, :, :y_cut_length] = y_[:, cut_lower:cut_upper]
attn_cut[i, :, :y_cut_length] = attn[i, :, cut_lower:cut_upper]
y_cut_lengths = torch.LongTensor(y_cut_lengths)
y_cut_mask = sequence_mask(y_cut_lengths).unsqueeze(1).to(y_mask)
attn = attn_cut
y = y_cut
y_mask = y_cut_mask
# Align encoded text with mel-spectrogram and get mu_y segment
mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
mu_y = mu_y.transpose(1, 2)
# Compute loss of the decoder
diff_loss, _ = self.decoder.compute_loss(x1=y, mask=y_mask, mu=mu_y, spks=spks, cond=cond)
if self.prior_loss:
prior_loss = torch.sum(0.5 * ((y - mu_y) ** 2 + math.log(2 * math.pi)) * y_mask)
prior_loss = prior_loss / (torch.sum(y_mask) * self.n_feats)
else:
prior_loss = 0
return dur_loss, prior_loss, diff_loss, attn123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826from dataclasses import dataclass, field, replacefrom typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as npimport torchimport torch.nn.functional as Ffrom torch import Tensorfrom torch.distributions import Categorical
from .audio import CHUNK_LENGTHfrom .tokenizer import Tokenizer, get_tokenizerfrom .utils import compression_ratio
if TYPE_CHECKING: from .model import Whisper
@torch.no_grad()def detect_language( model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None) -> Tuple[Tensor, List[dict]]: """ Detect the spoken language in the audio, and return them as list of strings, along with the ids of the most probable language tokens and the probability distribution over all language tokens. This is performed outside the main decode loop in order to not interfere with kv-caching.
Returns ------- language_tokens : Tensor, shape = (n_audio,) ids of the most probable language tokens, which appears after the startoftranscript token. language_probs : List[Dict[str, float]], length = n_audio list of dictionaries containing the probability distribution over all languages. """ if tokenizer is None: tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages ) if ( tokenizer.language is None or tokenizer.language_token not in tokenizer.sot_sequence ): raise ValueError( "This model doesn't have language tokens so it can't perform lang id" )
single = mel.ndim == 2 if single: mel = mel.unsqueeze(0)
# skip encoder forward pass if already-encoded audio features were given if mel.shape[-2:] != (model.dims.n_audio_ctx, model.dims.n_audio_state): mel = model.encoder(mel)
# forward pass using a single token, startoftranscript n_audio = mel.shape[0] x = torch.tensor([[tokenizer.sot]] * n_audio).to(mel.device) # [n_audio, 1] logits = model.logits(x, mel)[:, 0]
# collect detected languages; suppress all non-language tokens mask = torch.ones(logits.shape[-1], dtype=torch.bool) mask[list(tokenizer.all_language_tokens)] = False logits[:, mask] = -np.inf language_tokens = logits.argmax(dim=-1) language_token_probs = logits.softmax(dim=-1).cpu() language_probs = [ { c: language_token_probs[i, j].item() for j, c in zip(tokenizer.all_language_tokens, tokenizer.all_language_codes) } for i in range(n_audio) ]
if single: language_tokens = language_tokens[0] language_probs = language_probs[0]
return language_tokens, language_probs
@dataclass(frozen=True)class DecodingOptions: # whether to perform X->X "transcribe" or X->English "translate" task: str = "transcribe"
# language that the audio is in; uses detected language if None language: Optional[str] = None
# sampling-related options temperature: float = 0.0 sample_len: Optional[int] = None # maximum number of tokens to sample best_of: Optional[int] = None # number of independent sample trajectories, if t > 0 beam_size: Optional[int] = None # number of beams in beam search, if t == 0 patience: Optional[float] = None # patience in beam search (arxiv:2204.05424)
# "alpha" in Google NMT, or None for length norm, when ranking generations # to select which to return among the beams or best-of-N samples length_penalty: Optional[float] = None
# text or tokens to feed as the prompt or the prefix; for more info: # https://github.com/openai/whisper/discussions/117#discussioncomment-3727051 prompt: Optional[Union[str, List[int]]] = None # for the previous context prefix: Optional[Union[str, List[int]]] = None # to prefix the current context
# list of tokens ids (or comma-separated token ids) to suppress # "-1" will suppress a set of symbols as defined in `tokenizer.non_speech_tokens()` suppress_tokens: Optional[Union[str, Iterable[int]]] = "-1" suppress_blank: bool = True # this will suppress blank outputs
# timestamp sampling options without_timestamps: bool = False # use <|notimestamps|> to sample text tokens only max_initial_timestamp: Optional[float] = 1.0
# implementation details fp16: bool = True # use fp16 for most of the calculation
@dataclass(frozen=True)class DecodingResult: audio_features: Tensor language: str language_probs: Optional[Dict[str, float]] = None tokens: List[int] = field(default_factory=list) text: str = "" avg_logprob: float = np.nan no_speech_prob: float = np.nan temperature: float = np.nan compression_ratio: float = np.nan
class Inference: def logits(self, tokens: Tensor, audio_features: Tensor) -> Tensor: """Perform a forward pass on the decoder and return per-token logits""" raise NotImplementedError
def rearrange_kv_cache(self, source_indices) -> None: """Update the key-value cache according to the updated beams""" raise NotImplementedError
def cleanup_caching(self) -> None: """Clean up any resources or hooks after decoding is finished""" pass
class PyTorchInference(Inference): def __init__(self, model: "Whisper", initial_token_length: int): self.model: "Whisper" = model self.initial_token_length = initial_token_length self.kv_cache = {} self.hooks = []
key_modules = [block.attn.key for block in self.model.decoder.blocks] value_modules = [block.attn.value for block in self.model.decoder.blocks] self.kv_modules = key_modules + value_modules
def logits(self, tokens: Tensor, audio_features: Tensor) -> Tensor: if not self.kv_cache: self.kv_cache, self.hooks = self.model.install_kv_cache_hooks()
if tokens.shape[-1] > self.initial_token_length: # only need to use the last token except in the first forward pass tokens = tokens[:, -1:]
return self.model.decoder(tokens, audio_features, kv_cache=self.kv_cache)
def cleanup_caching(self): for hook in self.hooks: hook.remove()
self.kv_cache = {} self.hooks = []
def rearrange_kv_cache(self, source_indices): if source_indices != list(range(len(source_indices))): for module in self.kv_modules: # update the key/value cache to contain the selected sequences self.kv_cache[module] = self.kv_cache[module][source_indices].detach()
class SequenceRanker: def rank( self, tokens: List[List[Tensor]], sum_logprobs: List[List[float]] ) -> List[int]: """ Given a list of groups of samples and their cumulative log probabilities, return the indices of the samples in each group to select as the final result """ raise NotImplementedError
class MaximumLikelihoodRanker(SequenceRanker): """ Select the sample with the highest log probabilities, penalized using either a simple length normalization or Google NMT paper's length penalty """
def __init__(self, length_penalty: Optional[float]): self.length_penalty = length_penalty
def rank(self, tokens: List[List[Tensor]], sum_logprobs: List[List[float]]): def scores(logprobs, lengths): result = [] for logprob, length in zip(logprobs, lengths): if self.length_penalty is None: penalty = length else: # from the Google NMT paper penalty = ((5 + length) / 6) ** self.length_penalty result.append(logprob / penalty) return result
# get the sequence with the highest score lengths = [[len(t) for t in s] for s in tokens] return [np.argmax(scores(p, l)) for p, l in zip(sum_logprobs, lengths)]
class TokenDecoder: def reset(self): """Initialize any stateful variables for decoding a new sequence"""
def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: """Specify how to select the next token, based on the current trace and logits
Parameters ---------- tokens : Tensor, shape = (n_batch, current_sequence_length) all tokens in the context so far, including the prefix and sot_sequence tokens
logits : Tensor, shape = (n_batch, vocab_size) per-token logits of the probability distribution at the current step
sum_logprobs : Tensor, shape = (n_batch) cumulative log probabilities for each sequence
Returns ------- tokens : Tensor, shape = (n_batch, current_sequence_length + 1) the tokens, appended with the selected next token
completed : bool True if all sequences has reached the end of text
""" raise NotImplementedError
def finalize( self, tokens: Tensor, sum_logprobs: Tensor ) -> Tuple[Sequence[Sequence[Tensor]], List[List[float]]]: """Finalize search and return the final candidate sequences
Parameters ---------- tokens : Tensor, shape = (n_audio, n_group, current_sequence_length) all tokens in the context so far, including the prefix and sot_sequence
sum_logprobs : Tensor, shape = (n_audio, n_group) cumulative log probabilities for each sequence
Returns ------- tokens : Sequence[Sequence[Tensor]], length = n_audio sequence of Tensors containing candidate token sequences, for each audio input
sum_logprobs : List[List[float]], length = n_audio sequence of cumulative log probabilities corresponding to the above
""" raise NotImplementedError
class GreedyDecoder(TokenDecoder): def __init__(self, temperature: float, eot: int): self.temperature = temperature self.eot = eot
def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: if self.temperature == 0: next_tokens = logits.argmax(dim=-1) else: next_tokens = Categorical(logits=logits / self.temperature).sample()
logprobs = F.log_softmax(logits.float(), dim=-1) current_logprobs = logprobs[torch.arange(logprobs.shape[0]), next_tokens] sum_logprobs += current_logprobs * (tokens[:, -1] != self.eot)
next_tokens[tokens[:, -1] == self.eot] = self.eot tokens = torch.cat([tokens, next_tokens[:, None]], dim=-1)
completed = (tokens[:, -1] == self.eot).all() return tokens, completed
def finalize(self, tokens: Tensor, sum_logprobs: Tensor): # make sure each sequence has at least one EOT token at the end tokens = F.pad(tokens, (0, 1), value=self.eot) return tokens, sum_logprobs.tolist()
class BeamSearchDecoder(TokenDecoder): def __init__( self, beam_size: int, eot: int, inference: Inference, patience: Optional[float] = None, ): self.beam_size = beam_size self.eot = eot self.inference = inference self.patience = patience or 1.0 self.max_candidates: int = round(beam_size * self.patience) self.finished_sequences = None
assert ( self.max_candidates > 0 ), f"Invalid beam size ({beam_size}) or patience ({patience})"
def reset(self): self.finished_sequences = None
def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: if tokens.shape[0] % self.beam_size != 0: raise ValueError(f"{tokens.shape}[0] % {self.beam_size} != 0")
n_audio = tokens.shape[0] // self.beam_size if self.finished_sequences is None: # for the first update self.finished_sequences = [{} for _ in range(n_audio)]
logprobs = F.log_softmax(logits.float(), dim=-1) next_tokens, source_indices, finished_sequences = [], [], [] for i in range(n_audio): scores, sources, finished = {}, {}, {}
# STEP 1: calculate the cumulative log probabilities for possible candidates for j in range(self.beam_size): idx = i * self.beam_size + j prefix = tokens[idx].tolist() for logprob, token in zip(*logprobs[idx].topk(self.beam_size + 1)): new_logprob = (sum_logprobs[idx] + logprob).item() sequence = tuple(prefix + [token.item()]) scores[sequence] = new_logprob sources[sequence] = idx
# STEP 2: rank the candidates and keep the top beam_size sequences for each audio saved = 0 for sequence in sorted(scores, key=scores.get, reverse=True): if sequence[-1] == self.eot: finished[sequence] = scores[sequence] else: sum_logprobs[len(next_tokens)] = scores[sequence] next_tokens.append(sequence) source_indices.append(sources[sequence])
saved += 1 if saved == self.beam_size: break
finished_sequences.append(finished)
tokens = torch.tensor(next_tokens, device=tokens.device) self.inference.rearrange_kv_cache(source_indices)
# add newly finished sequences to self.finished_sequences assert len(self.finished_sequences) == len(finished_sequences) for previously_finished, newly_finished in zip( self.finished_sequences, finished_sequences ): for seq in sorted(newly_finished, key=newly_finished.get, reverse=True): if len(previously_finished) >= self.max_candidates: break # the candidate list is full previously_finished[seq] = newly_finished[seq]
# mark as completed if all audio has enough number of samples completed = all( len(sequences) >= self.max_candidates for sequences in self.finished_sequences ) return tokens, completed
def finalize(self, preceding_tokens: Tensor, sum_logprobs: Tensor): # collect all finished sequences, including patience, and add unfinished ones if not enough sum_logprobs = sum_logprobs.cpu() for i, sequences in enumerate(self.finished_sequences): if ( len(sequences) < self.beam_size ): # when not enough sequences are finished for j in list(np.argsort(sum_logprobs[i]))[::-1]: sequence = preceding_tokens[i, j].tolist() + [self.eot] sequences[tuple(sequence)] = sum_logprobs[i][j].item() if len(sequences) >= self.beam_size: break
tokens: List[List[Tensor]] = [ [torch.tensor(seq) for seq in sequences.keys()] for sequences in self.finished_sequences ] sum_logprobs: List[List[float]] = [ list(sequences.values()) for sequences in self.finished_sequences ] return tokens, sum_logprobs
class LogitFilter: def apply(self, logits: Tensor, tokens: Tensor) -> None: """Apply any filtering or masking to logits in-place
Parameters ---------- logits : Tensor, shape = (n_batch, vocab_size) per-token logits of the probability distribution at the current step
tokens : Tensor, shape = (n_batch, current_sequence_length) all tokens in the context so far, including the prefix and sot_sequence tokens
""" raise NotImplementedError
class SuppressBlank(LogitFilter): def __init__(self, tokenizer: Tokenizer, sample_begin: int): self.tokenizer = tokenizer self.sample_begin = sample_begin
def apply(self, logits: Tensor, tokens: Tensor): if tokens.shape[1] == self.sample_begin: logits[:, self.tokenizer.encode(" ") + [self.tokenizer.eot]] = -np.inf
class SuppressTokens(LogitFilter): def __init__(self, suppress_tokens: Sequence[int]): self.suppress_tokens = list(suppress_tokens)
def apply(self, logits: Tensor, tokens: Tensor): logits[:, self.suppress_tokens] = -np.inf
class ApplyTimestampRules(LogitFilter): def __init__( self, tokenizer: Tokenizer, sample_begin: int, max_initial_timestamp_index: Optional[int], ): self.tokenizer = tokenizer self.sample_begin = sample_begin self.max_initial_timestamp_index = max_initial_timestamp_index
def apply(self, logits: Tensor, tokens: Tensor): # suppress <|notimestamps|> which is handled by without_timestamps if self.tokenizer.no_timestamps is not None: logits[:, self.tokenizer.no_timestamps] = -np.inf
# timestamps have to appear in pairs, except directly before EOT; mask logits accordingly for k in range(tokens.shape[0]): sampled_tokens = tokens[k, self.sample_begin :] seq = [t for t in sampled_tokens.tolist()] last_was_timestamp = ( len(seq) >= 1 and seq[-1] >= self.tokenizer.timestamp_begin ) penultimate_was_timestamp = ( len(seq) < 2 or seq[-2] >= self.tokenizer.timestamp_begin )
if last_was_timestamp: if penultimate_was_timestamp: # has to be non-timestamp logits[k, self.tokenizer.timestamp_begin :] = -np.inf else: # cannot be normal text tokens logits[k, : self.tokenizer.eot] = -np.inf
timestamps = sampled_tokens[ sampled_tokens.ge(self.tokenizer.timestamp_begin) ] if timestamps.numel() > 0: # timestamps shouldn't decrease; forbid timestamp tokens smaller than the last # also force each segment to have a nonzero length, to prevent infinite looping if last_was_timestamp and not penultimate_was_timestamp: timestamp_last = timestamps[-1] else: timestamp_last = timestamps[-1] + 1 logits[k, self.tokenizer.timestamp_begin : timestamp_last] = -np.inf
if tokens.shape[1] == self.sample_begin: # suppress generating non-timestamp tokens at the beginning logits[:, : self.tokenizer.timestamp_begin] = -np.inf
# apply the `max_initial_timestamp` option if self.max_initial_timestamp_index is not None: last_allowed = ( self.tokenizer.timestamp_begin + self.max_initial_timestamp_index ) logits[:, last_allowed + 1 :] = -np.inf
# if sum of probability over timestamps is above any other token, sample timestamp logprobs = F.log_softmax(logits.float(), dim=-1) for k in range(tokens.shape[0]): timestamp_logprob = logprobs[k, self.tokenizer.timestamp_begin :].logsumexp( dim=-1 ) max_text_token_logprob = logprobs[k, : self.tokenizer.timestamp_begin].max() if timestamp_logprob > max_text_token_logprob: logits[k, : self.tokenizer.timestamp_begin] = -np.inf
class DecodingTask: inference: Inference sequence_ranker: SequenceRanker decoder: TokenDecoder logit_filters: List[LogitFilter]
def __init__(self, model: "Whisper", options: DecodingOptions): self.model = model
language = options.language or "en" tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages, language=language, task=options.task, ) self.tokenizer: Tokenizer = tokenizer self.options: DecodingOptions = self._verify_options(options)
self.n_group: int = options.beam_size or options.best_of or 1 self.n_ctx: int = model.dims.n_text_ctx self.sample_len: int = options.sample_len or model.dims.n_text_ctx // 2
self.sot_sequence: Tuple[int] = tokenizer.sot_sequence if self.options.without_timestamps: self.sot_sequence = tokenizer.sot_sequence_including_notimestamps
self.initial_tokens: Tuple[int] = self._get_initial_tokens() self.sample_begin: int = len(self.initial_tokens) self.sot_index: int = self.initial_tokens.index(tokenizer.sot)
# inference: implements the forward pass through the decoder, including kv caching self.inference = PyTorchInference(model, len(self.initial_tokens))
# sequence ranker: implements how to rank a group of sampled sequences self.sequence_ranker = MaximumLikelihoodRanker(options.length_penalty)
# decoder: implements how to select the next tokens, given the autoregressive distribution if options.beam_size is not None: self.decoder = BeamSearchDecoder( options.beam_size, tokenizer.eot, self.inference, options.patience ) else: self.decoder = GreedyDecoder(options.temperature, tokenizer.eot)
# logit filters: applies various rules to suppress or penalize certain tokens self.logit_filters = [] if self.options.suppress_blank: self.logit_filters.append(SuppressBlank(self.tokenizer, self.sample_begin)) if self.options.suppress_tokens: self.logit_filters.append(SuppressTokens(self._get_suppress_tokens())) if not options.without_timestamps: precision = CHUNK_LENGTH / model.dims.n_audio_ctx # usually 0.02 seconds max_initial_timestamp_index = None if options.max_initial_timestamp: max_initial_timestamp_index = round( self.options.max_initial_timestamp / precision ) self.logit_filters.append( ApplyTimestampRules( tokenizer, self.sample_begin, max_initial_timestamp_index ) )
def _verify_options(self, options: DecodingOptions) -> DecodingOptions: if options.beam_size is not None and options.best_of is not None: raise ValueError("beam_size and best_of can't be given together") if options.temperature == 0: if options.best_of is not None: raise ValueError("best_of with greedy sampling (T=0) is not compatible") if options.patience is not None and options.beam_size is None: raise ValueError("patience requires beam_size to be given") if options.length_penalty is not None and not ( 0 <= options.length_penalty <= 1 ): raise ValueError("length_penalty (alpha) should be a value between 0 and 1")
return options
def _get_initial_tokens(self) -> Tuple[int]: tokens = list(self.sot_sequence)
if prefix := self.options.prefix: prefix_tokens = ( self.tokenizer.encode(" " + prefix.strip()) if isinstance(prefix, str) else prefix ) if self.sample_len is not None: max_prefix_len = self.n_ctx // 2 - self.sample_len prefix_tokens = prefix_tokens[-max_prefix_len:] tokens = tokens + prefix_tokens
if prompt := self.options.prompt: prompt_tokens = ( self.tokenizer.encode(" " + prompt.strip()) if isinstance(prompt, str) else prompt ) tokens = ( [self.tokenizer.sot_prev] + prompt_tokens[-(self.n_ctx // 2 - 1) :] + tokens )
return tuple(tokens)
def _get_suppress_tokens(self) -> Tuple[int]: suppress_tokens = self.options.suppress_tokens
if isinstance(suppress_tokens, str): suppress_tokens = [int(t) for t in suppress_tokens.split(",")]
if -1 in suppress_tokens: suppress_tokens = [t for t in suppress_tokens if t >= 0] suppress_tokens.extend(self.tokenizer.non_speech_tokens) elif suppress_tokens is None or len(suppress_tokens) == 0: suppress_tokens = [] # interpret empty string as an empty list else: assert isinstance(suppress_tokens, list), "suppress_tokens must be a list"
suppress_tokens.extend( [ self.tokenizer.transcribe, self.tokenizer.translate, self.tokenizer.sot, self.tokenizer.sot_prev, self.tokenizer.sot_lm, ] ) if self.tokenizer.no_speech is not None: # no-speech probability is collected separately suppress_tokens.append(self.tokenizer.no_speech)
return tuple(sorted(set(suppress_tokens)))
def _get_audio_features(self, mel: Tensor): if self.options.fp16: mel = mel.half()
if mel.shape[-2:] == ( self.model.dims.n_audio_ctx, self.model.dims.n_audio_state, ): # encoded audio features are given; skip audio encoding audio_features = mel else: audio_features = self.model.encoder(mel)
if audio_features.dtype != ( torch.float16 if self.options.fp16 else torch.float32 ): return TypeError( f"audio_features has an incorrect dtype: {audio_features.dtype}" )
return audio_features
def _detect_language(self, audio_features: Tensor, tokens: Tensor): languages = [self.options.language] * audio_features.shape[0] lang_probs = None
if self.options.language is None or self.options.task == "lang_id": lang_tokens, lang_probs = self.model.detect_language( audio_features, self.tokenizer ) languages = [max(probs, key=probs.get) for probs in lang_probs] if self.options.language is None: tokens[:, self.sot_index + 1] = lang_tokens # write language tokens
return languages, lang_probs
def _main_loop(self, audio_features: Tensor, tokens: Tensor): n_batch = tokens.shape[0] sum_logprobs: Tensor = torch.zeros(n_batch, device=audio_features.device) no_speech_probs = [np.nan] * n_batch
try: for i in range(self.sample_len): logits = self.inference.logits(tokens, audio_features)
if ( i == 0 and self.tokenizer.no_speech is not None ): # save no_speech_probs probs_at_sot = logits[:, self.sot_index].float().softmax(dim=-1) no_speech_probs = probs_at_sot[:, self.tokenizer.no_speech].tolist()
# now we need to consider the logits at the last token only logits = logits[:, -1]
# apply the logit filters, e.g. for suppressing or applying penalty to for logit_filter in self.logit_filters: logit_filter.apply(logits, tokens)
# expand the tokens tensor with the selected next tokens tokens, completed = self.decoder.update(tokens, logits, sum_logprobs)
if completed or tokens.shape[-1] > self.n_ctx: break finally: self.inference.cleanup_caching()
return tokens, sum_logprobs, no_speech_probs
@torch.no_grad() def run(self, mel: Tensor) -> List[DecodingResult]: self.decoder.reset() tokenizer: Tokenizer = self.tokenizer n_audio: int = mel.shape[0]
audio_features: Tensor = self._get_audio_features(mel) # encoder forward pass tokens: Tensor = torch.tensor([self.initial_tokens]).repeat(n_audio, 1)
# detect language if requested, overwriting the language token languages, language_probs = self._detect_language(audio_features, tokens) if self.options.task == "lang_id": return [ DecodingResult( audio_features=features, language=language, language_probs=probs ) for features, language, probs in zip( audio_features, languages, language_probs ) ]
# repeat text tensors by the group size, for beam search or best-of-n sampling tokens = tokens.repeat_interleave(self.n_group, dim=0).to(audio_features.device)
# call the main sampling loop tokens, sum_logprobs, no_speech_probs = self._main_loop(audio_features, tokens)
# reshape the tensors to have (n_audio, n_group) as the first two dimensions audio_features = audio_features[:: self.n_group] no_speech_probs = no_speech_probs[:: self.n_group] assert audio_features.shape[0] == len(no_speech_probs) == n_audio
tokens = tokens.reshape(n_audio, self.n_group, -1) sum_logprobs = sum_logprobs.reshape(n_audio, self.n_group)
# get the final candidates for each group, and slice between the first sampled token and EOT tokens, sum_logprobs = self.decoder.finalize(tokens, sum_logprobs) tokens: List[List[Tensor]] = [ [t[self.sample_begin : (t == tokenizer.eot).nonzero()[0, 0]] for t in s] for s in tokens ]
# select the top-ranked sample in each group selected = self.sequence_ranker.rank(tokens, sum_logprobs) tokens: List[List[int]] = [t[i].tolist() for i, t in zip(selected, tokens)] texts: List[str] = [tokenizer.decode(t).strip() for t in tokens]
sum_logprobs: List[float] = [lp[i] for i, lp in zip(selected, sum_logprobs)] avg_logprobs: List[float] = [ lp / (len(t) + 1) for t, lp in zip(tokens, sum_logprobs) ]
fields = ( texts, languages, tokens, audio_features, avg_logprobs, no_speech_probs, ) if len(set(map(len, fields))) != 1: raise RuntimeError(f"inconsistent result lengths: {list(map(len, fields))}")
return [ DecodingResult( audio_features=features, language=language, tokens=tokens, text=text, avg_logprob=avg_logprob, no_speech_prob=no_speech_prob, temperature=self.options.temperature, compression_ratio=compression_ratio(text), ) for text, language, tokens, features, avg_logprob, no_speech_prob in zip( *fields ) ]
@torch.no_grad()def decode( model: "Whisper", mel: Tensor, options: DecodingOptions = DecodingOptions(), **kwargs,) -> Union[DecodingResult, List[DecodingResult]]: """ Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s).
Parameters ---------- model: Whisper the Whisper model instance
mel: torch.Tensor, shape = (80, 3000) or (*, 80, 3000) A tensor containing the Mel spectrogram(s)
options: DecodingOptions A dataclass that contains all necessary options for decoding 30-second segments
Returns ------- result: Union[DecodingResult, List[DecodingResult]] The result(s) of decoding contained in `DecodingResult` dataclass instance(s) """ if single := mel.ndim == 2: mel = mel.unsqueeze(0)
if kwargs: options = replace(options, **kwargs)
result = DecodingTask(model, options).run(mel)
return result[0] if single else result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314import base64import gzipfrom dataclasses import dataclassfrom typing import Dict, Iterable, Optional
import numpy as npimport torchimport torch.nn.functional as Ffrom torch import Tensor, nn
from .decoding import decode as decode_functionfrom .decoding import detect_language as detect_language_functionfrom .transcribe import transcribe as transcribe_function
@dataclassclass ModelDimensions: n_mels: int n_audio_ctx: int n_audio_state: int n_audio_head: int n_audio_layer: int n_vocab: int n_text_ctx: int n_text_state: int n_text_head: int n_text_layer: int
class LayerNorm(nn.LayerNorm): def forward(self, x: Tensor) -> Tensor: return super().forward(x.float()).type(x.dtype)
class Linear(nn.Linear): def forward(self, x: Tensor) -> Tensor: return F.linear( x, self.weight.to(x.dtype), None if self.bias is None else self.bias.to(x.dtype), )
class Conv1d(nn.Conv1d): def _conv_forward( self, x: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return super()._conv_forward( x, weight.to(x.dtype), None if bias is None else bias.to(x.dtype) )
def sinusoids(length, channels, max_timescale=10000): """Returns sinusoids for positional embedding""" assert channels % 2 == 0 log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2)) scaled_time = torch.arange(length)[:, np.newaxis] * inv_timescales[np.newaxis, :] return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
class MultiHeadAttention(nn.Module): def __init__(self, n_state: int, n_head: int): super().__init__() self.n_head = n_head self.query = Linear(n_state, n_state) self.key = Linear(n_state, n_state, bias=False) self.value = Linear(n_state, n_state) self.out = Linear(n_state, n_state)
def forward( self, x: Tensor, xa: Optional[Tensor] = None, mask: Optional[Tensor] = None, kv_cache: Optional[dict] = None, ): q = self.query(x)
if kv_cache is None or xa is None or self.key not in kv_cache: # hooks, if installed (i.e. kv_cache is not None), will prepend the cached kv tensors; # otherwise, perform key/value projections for self- or cross-attention as usual. k = self.key(x if xa is None else xa) v = self.value(x if xa is None else xa) else: # for cross-attention, calculate keys and values once and reuse in subsequent calls. k = kv_cache[self.key] v = kv_cache[self.value]
wv, qk = self.qkv_attention(q, k, v, mask) return self.out(wv), qk
def qkv_attention( self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None ): n_batch, n_ctx, n_state = q.shape scale = (n_state // self.n_head) ** -0.25 q = q.view(*q.shape[:2], self.n_head, -1).permute(0, 2, 1, 3) * scale k = k.view(*k.shape[:2], self.n_head, -1).permute(0, 2, 3, 1) * scale v = v.view(*v.shape[:2], self.n_head, -1).permute(0, 2, 1, 3)
qk = q @ k if mask is not None: qk = qk + mask[:n_ctx, :n_ctx] qk = qk.float()
w = F.softmax(qk, dim=-1).to(q.dtype) return (w @ v).permute(0, 2, 1, 3).flatten(start_dim=2), qk.detach()
class ResidualAttentionBlock(nn.Module): def __init__(self, n_state: int, n_head: int, cross_attention: bool = False): super().__init__()
self.attn = MultiHeadAttention(n_state, n_head) self.attn_ln = LayerNorm(n_state)
self.cross_attn = ( MultiHeadAttention(n_state, n_head) if cross_attention else None ) self.cross_attn_ln = LayerNorm(n_state) if cross_attention else None
n_mlp = n_state * 4 self.mlp = nn.Sequential( Linear(n_state, n_mlp), nn.GELU(), Linear(n_mlp, n_state) ) self.mlp_ln = LayerNorm(n_state)
def forward( self, x: Tensor, xa: Optional[Tensor] = None, mask: Optional[Tensor] = None, kv_cache: Optional[dict] = None, ): x = x + self.attn(self.attn_ln(x), mask=mask, kv_cache=kv_cache)[0] if self.cross_attn: x = x + self.cross_attn(self.cross_attn_ln(x), xa, kv_cache=kv_cache)[0] x = x + self.mlp(self.mlp_ln(x)) return x
class AudioEncoder(nn.Module): def __init__( self, n_mels: int, n_ctx: int, n_state: int, n_head: int, n_layer: int ): super().__init__() self.conv1 = Conv1d(n_mels, n_state, kernel_size=3, padding=1) self.conv2 = Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1) self.register_buffer("positional_embedding", sinusoids(n_ctx, n_state))
self.blocks: Iterable[ResidualAttentionBlock] = nn.ModuleList( [ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)] ) self.ln_post = LayerNorm(n_state)
def forward(self, x: Tensor): """ x : torch.Tensor, shape = (batch_size, n_mels, n_ctx) the mel spectrogram of the audio """ x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1)
assert x.shape[1:] == self.positional_embedding.shape, "incorrect audio shape" x = (x + self.positional_embedding).to(x.dtype)
for block in self.blocks: x = block(x)
x = self.ln_post(x) return x
class TextDecoder(nn.Module): def __init__( self, n_vocab: int, n_ctx: int, n_state: int, n_head: int, n_layer: int ): super().__init__()
self.token_embedding = nn.Embedding(n_vocab, n_state) self.positional_embedding = nn.Parameter(torch.empty(n_ctx, n_state))
self.blocks: Iterable[ResidualAttentionBlock] = nn.ModuleList( [ ResidualAttentionBlock(n_state, n_head, cross_attention=True) for _ in range(n_layer) ] ) self.ln = LayerNorm(n_state)
mask = torch.empty(n_ctx, n_ctx).fill_(-np.inf).triu_(1) self.register_buffer("mask", mask, persistent=False)
def forward(self, x: Tensor, xa: Tensor, kv_cache: Optional[dict] = None): """ x : torch.LongTensor, shape = (batch_size, <= n_ctx) the text tokens xa : torch.Tensor, shape = (batch_size, n_audio_ctx, n_audio_state) the encoded audio features to be attended on """ offset = next(iter(kv_cache.values())).shape[1] if kv_cache else 0 x = ( self.token_embedding(x) + self.positional_embedding[offset : offset + x.shape[-1]] ) x = x.to(xa.dtype)
for block in self.blocks: x = block(x, xa, mask=self.mask, kv_cache=kv_cache)
x = self.ln(x) logits = ( x @ torch.transpose(self.token_embedding.weight.to(x.dtype), 0, 1) ).float()
return logits
class Whisper(nn.Module): def __init__(self, dims: ModelDimensions): super().__init__() self.dims = dims self.encoder = AudioEncoder( self.dims.n_mels, self.dims.n_audio_ctx, self.dims.n_audio_state, self.dims.n_audio_head, self.dims.n_audio_layer, ) self.decoder = TextDecoder( self.dims.n_vocab, self.dims.n_text_ctx, self.dims.n_text_state, self.dims.n_text_head, self.dims.n_text_layer, ) # use the last half among the decoder layers for time alignment by default; # to use a specific set of heads, see `set_alignment_heads()` below. all_heads = torch.zeros( self.dims.n_text_layer, self.dims.n_text_head, dtype=torch.bool ) all_heads[self.dims.n_text_layer // 2 :] = True self.register_buffer("alignment_heads", all_heads.to_sparse(), persistent=False)
def set_alignment_heads(self, dump: bytes): array = np.frombuffer( gzip.decompress(base64.b85decode(dump)), dtype=bool ).copy() mask = torch.from_numpy(array).reshape( self.dims.n_text_layer, self.dims.n_text_head ) self.register_buffer("alignment_heads", mask.to_sparse(), persistent=False)
def embed_audio(self, mel: torch.Tensor): return self.encoder(mel)
def logits(self, tokens: torch.Tensor, audio_features: torch.Tensor): return self.decoder(tokens, audio_features)
def forward( self, mel: torch.Tensor, tokens: torch.Tensor ) -> Dict[str, torch.Tensor]: return self.decoder(tokens, self.encoder(mel))
@property def device(self): return next(self.parameters()).device
@property def is_multilingual(self): return self.dims.n_vocab >= 51865
@property def num_languages(self): return self.dims.n_vocab - 51765 - int(self.is_multilingual)
def install_kv_cache_hooks(self, cache: Optional[dict] = None): """ The `MultiHeadAttention` module optionally accepts `kv_cache` which stores the key and value tensors calculated for the previous positions. This method returns a dictionary that stores all caches, and the necessary hooks for the key and value projection modules that save the intermediate tensors to be reused during later calculations.
Returns ------- cache : Dict[nn.Module, torch.Tensor] A dictionary object mapping the key/value projection modules to its cache hooks : List[RemovableHandle] List of PyTorch RemovableHandle objects to stop the hooks to be called """ cache = {**cache} if cache is not None else {} hooks = []
def save_to_cache(module, _, output): if module not in cache or output.shape[1] > self.dims.n_text_ctx: # save as-is, for the first token or cross attention cache[module] = output else: cache[module] = torch.cat([cache[module], output], dim=1).detach() return cache[module]
def install_hooks(layer: nn.Module): if isinstance(layer, MultiHeadAttention): hooks.append(layer.key.register_forward_hook(save_to_cache)) hooks.append(layer.value.register_forward_hook(save_to_cache))
self.decoder.apply(install_hooks) return cache, hooks
detect_language = detect_language_function transcribe = transcribe_function decode = decode_function1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741{ "accessorise": "accessorize", "accessorised": "accessorized", "accessorises": "accessorizes", "accessorising": "accessorizing", "acclimatisation": "acclimatization", "acclimatise": "acclimatize", "acclimatised": "acclimatized", "acclimatises": "acclimatizes", "acclimatising": "acclimatizing", "accoutrements": "accouterments", "aeon": "eon", "aeons": "eons", "aerogramme": "aerogram", "aerogrammes": "aerograms", "aeroplane": "airplane", "aeroplanes": "airplanes", "aesthete": "esthete", "aesthetes": "esthetes", "aesthetic": "esthetic", "aesthetically": "esthetically", "aesthetics": "esthetics", "aetiology": "etiology", "ageing": "aging", "aggrandisement": "aggrandizement", "agonise": "agonize", "agonised": "agonized", "agonises": "agonizes", "agonising": "agonizing", "agonisingly": "agonizingly", "almanack": "almanac", "almanacks": "almanacs", "aluminium": "aluminum", "amortisable": "amortizable", "amortisation": "amortization", "amortisations": "amortizations", "amortise": "amortize", "amortised": "amortized", "amortises": "amortizes", "amortising": "amortizing", "amphitheatre": "amphitheater", "amphitheatres": "amphitheaters", "anaemia": "anemia", "anaemic": "anemic", "anaesthesia": "anesthesia", "anaesthetic": "anesthetic", "anaesthetics": "anesthetics", "anaesthetise": "anesthetize", "anaesthetised": "anesthetized", "anaesthetises": "anesthetizes", "anaesthetising": "anesthetizing", "anaesthetist": "anesthetist", "anaesthetists": "anesthetists", "anaesthetize": "anesthetize", "anaesthetized": "anesthetized", "anaesthetizes": "anesthetizes", "anaesthetizing": "anesthetizing", "analogue": "analog", "analogues": "analogs", "analyse": "analyze", "analysed": "analyzed", "analyses": "analyzes", "analysing": "analyzing", "anglicise": "anglicize", "anglicised": "anglicized", "anglicises": "anglicizes", "anglicising": "anglicizing", "annualised": "annualized", "antagonise": "antagonize", "antagonised": "antagonized", "antagonises": "antagonizes", "antagonising": "antagonizing", "apologise": "apologize", "apologised": "apologized", "apologises": "apologizes", "apologising": "apologizing", "appal": "appall", "appals": "appalls", "appetiser": "appetizer", "appetisers": "appetizers", "appetising": "appetizing", "appetisingly": "appetizingly", "arbour": "arbor", "arbours": "arbors", "archeological": "archaeological", "archaeologically": "archeologically", "archaeologist": "archeologist", "archaeologists": "archeologists", "archaeology": "archeology</span>", "ardour": "ardor", "armour": "armor", "armoured": "armored", "armourer": "armorer", "armourers": "armorers", "armouries": "armories", "armoury": "armory", "artefact": "artifact", "artefacts": "artifacts", "authorise": "authorize", "authorised": "authorized", "authorises": "authorizes", "authorising": "authorizing", "axe": "ax", "backpedalled": "backpedaled", "backpedalling": "backpedaling", "bannister": "banister", "bannisters": "banisters", "baptise": "baptize", "baptised": "baptized", "baptises": "baptizes", "baptising": "baptizing", "bastardise": "bastardize", "bastardised": "bastardized", "bastardises": "bastardizes", "bastardising": "bastardizing", "battleax": "battleaxe", "baulk": "balk", "baulked": "balked", "baulking": "balking", "baulks": "balks", "bedevilled": "bedeviled", "bedevilling": "bedeviling", "behaviour": "behavior", "behavioural": "behavioral", "behaviourism": "behaviorism", "behaviourist": "behaviorist", "behaviourists": "behaviorists", "behaviours": "behaviors", "behove": "behoove", "behoved": "behooved", "behoves": "behooves", "bejewelled": "bejeweled", "belabour": "belabor", "belaboured": "belabored", "belabouring": "belaboring", "belabours": "belabors", "bevelled": "beveled", "bevvies": "bevies", "bevvy": "bevy", "biassed": "biased", "biassing": "biasing", "bingeing": "binging", "bougainvillaea": "bougainvillea", "bougainvillaeas": "bougainvilleas", "bowdlerise": "bowdlerize", "bowdlerised": "bowdlerized", "bowdlerises": "bowdlerizes", "bowdlerising": "bowdlerizing", "breathalyse": "breathalyze", "breathalysed": "breathalyzed", "breathalyser": "breathalyzer", "breathalysers": "breathalyzers", "breathalyses": "breathalyzes", "breathalysing": "breathalyzing", "brutalise": "brutalize", "brutalised": "brutalized", "brutalises": "brutalizes", "brutalising": "brutalizing", "busses": "buses", "bussing": "busing", "caesarean": "cesarean", "caesareans": "cesareans", "calibre": "caliber", "calibres": "calibers", "calliper": "caliper", "callipers": "calipers", "callisthenics": "calisthenics", "canalise": "canalize", "canalised": "canalized", "canalises": "canalizes", "canalising": "canalizing", "cancelation": "cancellation", "cancelations": "cancellations", "cancelled": "canceled", "cancelling": "canceling", "candour": "candor", "cannibalise": "cannibalize", "cannibalised": "cannibalized", "cannibalises": "cannibalizes", "cannibalising": "cannibalizing", "canonise": "canonize", "canonised": "canonized", "canonises": "canonizes", "canonising": "canonizing", "capitalise": "capitalize", "capitalised": "capitalized", "capitalises": "capitalizes", "capitalising": "capitalizing", "caramelise": "caramelize", "caramelised": "caramelized", "caramelises": "caramelizes", "caramelising": "caramelizing", "carbonise": "carbonize", "carbonised": "carbonized", "carbonises": "carbonizes", "carbonising": "carbonizing", "carolled": "caroled", "carolling": "caroling", "catalogue": "catalog", "catalogued": "cataloged", "catalogues": "catalogs", "cataloguing": "cataloging", "catalyse": "catalyze", "catalysed": "catalyzed", "catalyses": "catalyzes", "catalysing": "catalyzing", "categorise": "categorize", "categorised": "categorized", "categorises": "categorizes", "categorising": "categorizing", "cauterise": "cauterize", "cauterised": "cauterized", "cauterises": "cauterizes", "cauterising": "cauterizing", "cavilled": "caviled", "cavilling": "caviling", "centigramme": "centigram", "centigrammes": "centigrams", "centilitre": "centiliter", "centilitres": "centiliters", "centimetre": "centimeter", "centimetres": "centimeters", "centralise": "centralize", "centralised": "centralized", "centralises": "centralizes", "centralising": "centralizing", "centre": "center", "centred": "centered", "centrefold": "centerfold", "centrefolds": "centerfolds", "centrepiece": "centerpiece", "centrepieces": "centerpieces", "centres": "centers", "channelled": "channeled", "channelling": "channeling", "characterise": "characterize", "characterised": "characterized", "characterises": "characterizes", "characterising": "characterizing", "cheque": "check", "chequebook": "checkbook", "chequebooks": "checkbooks", "chequered": "checkered", "cheques": "checks", "chilli": "chili", "chimaera": "chimera", "chimaeras": "chimeras", "chiselled": "chiseled", "chiselling": "chiseling", "circularise": "circularize", "circularised": "circularized", "circularises": "circularizes", "circularising": "circularizing", "civilise": "civilize", "civilised": "civilized", "civilises": "civilizes", "civilising": "civilizing", "clamour": "clamor", "clamoured": "clamored", "clamouring": "clamoring", "clamours": "clamors", "clangour": "clangor", "clarinettist": "clarinetist", "clarinettists": "clarinetists", "collectivise": "collectivize", "collectivised": "collectivized", "collectivises": "collectivizes", "collectivising": "collectivizing", "colonisation": "colonization", "colonise": "colonize", "colonised": "colonized", "coloniser": "colonizer", "colonisers": "colonizers", "colonises": "colonizes", "colonising": "colonizing", "colour": "color", "colourant": "colorant", "colourants": "colorants", "coloured": "colored", "coloureds": "coloreds", "colourful": "colorful", "colourfully": "colorfully", "colouring": "coloring", "colourize": "colorize", "colourized": "colorized", "colourizes": "colorizes", "colourizing": "colorizing", "colourless": "colorless", "colours": "colors", "commercialise": "commercialize", "commercialised": "commercialized", "commercialises": "commercializes", "commercialising": "commercializing", "compartmentalise": "compartmentalize", "compartmentalised": "compartmentalized", "compartmentalises": "compartmentalizes", "compartmentalising": "compartmentalizing", "computerise": "computerize", "computerised": "computerized", "computerises": "computerizes", "computerising": "computerizing", "conceptualise": "conceptualize", "conceptualised": "conceptualized", "conceptualises": "conceptualizes", "conceptualising": "conceptualizing", "connexion": "connection", "connexions": "connections", "contextualise": "contextualize", "contextualised": "contextualized", "contextualises": "contextualizes", "contextualising": "contextualizing", "cosier": "cozier", "cosies": "cozies", "cosiest": "coziest", "cosily": "cozily", "cosiness": "coziness", "cosy": "cozy", "councillor": "councilor", "councillors": "councilors", "counselled": "counseled", "counselling": "counseling", "counsellor": "counselor", "counsellors": "counselors", "crenelated": "crenellated", "criminalise": "criminalize", "criminalised": "criminalized", "criminalises": "criminalizes", "criminalising": "criminalizing", "criticise": "criticize", "criticised": "criticized", "criticises": "criticizes", "criticising": "criticizing", "crueller": "crueler", "cruellest": "cruelest", "crystallisation": "crystallization", "crystallise": "crystallize", "crystallised": "crystallized", "crystallises": "crystallizes", "crystallising": "crystallizing", "cudgelled": "cudgeled", "cudgelling": "cudgeling", "customise": "customize", "customised": "customized", "customises": "customizes", "customising": "customizing", "cypher": "cipher", "cyphers": "ciphers", "decentralisation": "decentralization", "decentralise": "decentralize", "decentralised": "decentralized", "decentralises": "decentralizes", "decentralising": "decentralizing", "decriminalisation": "decriminalization", "decriminalise": "decriminalize", "decriminalised": "decriminalized", "decriminalises": "decriminalizes", "decriminalising": "decriminalizing", "defence": "defense", "defenceless": "defenseless", "defences": "defenses", "dehumanisation": "dehumanization", "dehumanise": "dehumanize", "dehumanised": "dehumanized", "dehumanises": "dehumanizes", "dehumanising": "dehumanizing", "demeanour": "demeanor", "demilitarisation": "demilitarization", "demilitarise": "demilitarize", "demilitarised": "demilitarized", "demilitarises": "demilitarizes", "demilitarising": "demilitarizing", "demobilisation": "demobilization", "demobilise": "demobilize", "demobilised": "demobilized", "demobilises": "demobilizes", "demobilising": "demobilizing", "democratisation": "democratization", "democratise": "democratize", "democratised": "democratized", "democratises": "democratizes", "democratising": "democratizing", "demonise": "demonize", "demonised": "demonized", "demonises": "demonizes", "demonising": "demonizing", "demoralisation": "demoralization", "demoralise": "demoralize", "demoralised": "demoralized", "demoralises": "demoralizes", "demoralising": "demoralizing", "denationalisation": "denationalization", "denationalise": "denationalize", "denationalised": "denationalized", "denationalises": "denationalizes", "denationalising": "denationalizing", "deodorise": "deodorize", "deodorised": "deodorized", "deodorises": "deodorizes", "deodorising": "deodorizing", "depersonalise": "depersonalize", "depersonalised": "depersonalized", "depersonalises": "depersonalizes", "depersonalising": "depersonalizing", "deputise": "deputize", "deputised": "deputized", "deputises": "deputizes", "deputising": "deputizing", "desensitisation": "desensitization", "desensitise": "desensitize", "desensitised": "desensitized", "desensitises": "desensitizes", "desensitising": "desensitizing", "destabilisation": "destabilization", "destabilise": "destabilize", "destabilised": "destabilized", "destabilises": "destabilizes", "destabilising": "destabilizing", "dialled": "dialed", "dialling": "dialing", "dialogue": "dialog", "dialogues": "dialogs", "diarrhoea": "diarrhea", "digitise": "digitize", "digitised": "digitized", "digitises": "digitizes", "digitising": "digitizing", "disc": "disk", "discolour": "discolor", "discoloured": "discolored", "discolouring": "discoloring", "discolours": "discolors", "discs": "disks", "disembowelled": "disemboweled", "disembowelling": "disemboweling", "disfavour": "disfavor", "dishevelled": "disheveled", "dishonour": "dishonor", "dishonourable": "dishonorable", "dishonourably": "dishonorably", "dishonoured": "dishonored", "dishonouring": "dishonoring", "dishonours": "dishonors", "disorganisation": "disorganization", "disorganised": "disorganized", "distil": "distill", "distils": "distills", "dramatisation": "dramatization", "dramatisations": "dramatizations", "dramatise": "dramatize", "dramatised": "dramatized", "dramatises": "dramatizes", "dramatising": "dramatizing", "draught": "draft", "draughtboard": "draftboard", "draughtboards": "draftboards", "draughtier": "draftier", "draughtiest": "draftiest", "draughts": "drafts", "draughtsman": "draftsman", "draughtsmanship": "draftsmanship", "draughtsmen": "draftsmen", "draughtswoman": "draftswoman", "draughtswomen": "draftswomen", "draughty": "drafty", "drivelled": "driveled", "drivelling": "driveling", "duelled": "dueled", "duelling": "dueling", "economise": "economize", "economised": "economized", "economises": "economizes", "economising": "economizing", "edoema": "edema", "editorialise": "editorialize", "editorialised": "editorialized", "editorialises": "editorializes", "editorialising": "editorializing", "empathise": "empathize", "empathised": "empathized", "empathises": "empathizes", "empathising": "empathizing", "emphasise": "emphasize", "emphasised": "emphasized", "emphasises": "emphasizes", "emphasising": "emphasizing", "enamelled": "enameled", "enamelling": "enameling", "enamoured": "enamored", "encyclopaedia": "encyclopedia", "encyclopaedias": "encyclopedias", "encyclopaedic": "encyclopedic", "endeavour": "endeavor", "endeavoured": "endeavored", "endeavouring": "endeavoring", "endeavours": "endeavors", "energise": "energize", "energised": "energized", "energises": "energizes", "energising": "energizing", "enrol": "enroll", "enrols": "enrolls", "enthral": "enthrall", "enthrals": "enthralls", "epaulette": "epaulet", "epaulettes": "epaulets", "epicentre": "epicenter", "epicentres": "epicenters", "epilogue": "epilog", "epilogues": "epilogs", "epitomise": "epitomize", "epitomised": "epitomized", "epitomises": "epitomizes", "epitomising": "epitomizing", "equalisation": "equalization", "equalise": "equalize", "equalised": "equalized", "equaliser": "equalizer", "equalisers": "equalizers", "equalises": "equalizes", "equalising": "equalizing", "eulogise": "eulogize", "eulogised": "eulogized", "eulogises": "eulogizes", "eulogising": "eulogizing", "evangelise": "evangelize", "evangelised": "evangelized", "evangelises": "evangelizes", "evangelising": "evangelizing", "exorcise": "exorcize", "exorcised": "exorcized", "exorcises": "exorcizes", "exorcising": "exorcizing", "extemporisation": "extemporization", "extemporise": "extemporize", "extemporised": "extemporized", "extemporises": "extemporizes", "extemporising": "extemporizing", "externalisation": "externalization", "externalisations": "externalizations", "externalise": "externalize", "externalised": "externalized", "externalises": "externalizes", "externalising": "externalizing", "factorise": "factorize", "factorised": "factorized", "factorises": "factorizes", "factorising": "factorizing", "faecal": "fecal", "faeces": "feces", "familiarisation": "familiarization", "familiarise": "familiarize", "familiarised": "familiarized", "familiarises": "familiarizes", "familiarising": "familiarizing", "fantasise": "fantasize", "fantasised": "fantasized", "fantasises": "fantasizes", "fantasising": "fantasizing", "favour": "favor", "favourable": "favorable", "favourably": "favorably", "favoured": "favored", "favouring": "favoring", "favourite": "favorite", "favourites": "favorites", "favouritism": "favoritism", "favours": "favors", "feminise": "feminize", "feminised": "feminized", "feminises": "feminizes", "feminising": "feminizing", "fertilisation": "fertilization", "fertilise": "fertilize", "fertilised": "fertilized", "fertiliser": "fertilizer", "fertilisers": "fertilizers", "fertilises": "fertilizes", "fertilising": "fertilizing", "fervour": "fervor", "fibre": "fiber", "fibreglass": "fiberglass", "fibres": "fibers", "fictionalisation": "fictionalization", "fictionalisations": "fictionalizations", "fictionalise": "fictionalize", "fictionalised": "fictionalized", "fictionalises": "fictionalizes", "fictionalising": "fictionalizing", "fillet": "filet", "filleted": "fileted", "filleting": "fileting", "fillets": "filets", "finalisation": "finalization", "finalise": "finalize", "finalised": "finalized", "finalises": "finalizes", "finalising": "finalizing", "flautist": "flutist", "flautists": "flutists", "flavour": "flavor", "flavoured": "flavored", "flavouring": "flavoring", "flavourings": "flavorings", "flavourless": "flavorless", "flavours": "flavors", "flavoursome": "flavorsome", "flyer / flier": "flier / flyer", "foetal": "fetal", "foetid": "fetid", "foetus": "fetus", "foetuses": "fetuses", "formalisation": "formalization", "formalise": "formalize", "formalised": "formalized", "formalises": "formalizes", "formalising": "formalizing", "fossilisation": "fossilization", "fossilise": "fossilize", "fossilised": "fossilized", "fossilises": "fossilizes", "fossilising": "fossilizing", "fraternisation": "fraternization", "fraternise": "fraternize", "fraternised": "fraternized", "fraternises": "fraternizes", "fraternising": "fraternizing", "fulfil": "fulfill", "fulfilment": "fulfillment", "fulfils": "fulfills", "funnelled": "funneled", "funnelling": "funneling", "galvanise": "galvanize", "galvanised": "galvanized", "galvanises": "galvanizes", "galvanising": "galvanizing", "gambolled": "gamboled", "gambolling": "gamboling", "gaol": "jail", "gaolbird": "jailbird", "gaolbirds": "jailbirds", "gaolbreak": "jailbreak", "gaolbreaks": "jailbreaks", "gaoled": "jailed", "gaoler": "jailer", "gaolers": "jailers", "gaoling": "jailing", "gaols": "jails", "gasses": "gases", "gage": "gauge", "gaged": "gauged", "gages": "gauges", "gaging": "gauging", "generalisation": "generalization", "generalisations": "generalizations", "generalise": "generalize", "generalised": "generalized", "generalises": "generalizes", "generalising": "generalizing", "ghettoise": "ghettoize", "ghettoised": "ghettoized", "ghettoises": "ghettoizes", "ghettoising": "ghettoizing", "gipsies": "gypsies", "glamorise": "glamorize", "glamorised": "glamorized", "glamorises": "glamorizes", "glamorising": "glamorizing", "glamor": "glamour", "globalisation": "globalization", "globalise": "globalize", "globalised": "globalized", "globalises": "globalizes", "globalising": "globalizing", "glueing": "gluing", "goitre": "goiter", "goitres": "goiters", "gonorrhoea": "gonorrhea", "gramme": "gram", "grammes": "grams", "gravelled": "graveled", "grey": "gray", "greyed": "grayed", "greying": "graying", "greyish": "grayish", "greyness": "grayness", "greys": "grays", "grovelled": "groveled", "grovelling": "groveling", "groyne": "groin", "groynes": "groins", "gruelling": "grueling", "gruellingly": "gruelingly", "gryphon": "griffin", "gryphons": "griffins", "gynaecological": "gynecological", "gynaecologist": "gynecologist", "gynaecologists": "gynecologists", "gynaecology": "gynecology", "haematological": "hematological", "haematologist": "hematologist", "haematologists": "hematologists", "haematology": "hematology", "haemoglobin": "hemoglobin", "haemophilia": "hemophilia", "haemophiliac": "hemophiliac", "haemophiliacs": "hemophiliacs", "haemorrhage": "hemorrhage", "haemorrhaged": "hemorrhaged", "haemorrhages": "hemorrhages", "haemorrhaging": "hemorrhaging", "haemorrhoids": "hemorrhoids", "harbour": "harbor", "harboured": "harbored", "harbouring": "harboring", "harbours": "harbors", "harmonisation": "harmonization", "harmonise": "harmonize", "harmonised": "harmonized", "harmonises": "harmonizes", "harmonising": "harmonizing", "homoeopath": "homeopath", "homoeopathic": "homeopathic", "homoeopaths": "homeopaths", "homoeopathy": "homeopathy", "homogenise": "homogenize", "homogenised": "homogenized", "homogenises": "homogenizes", "homogenising": "homogenizing", "honour": "honor", "honourable": "honorable", "honourably": "honorably", "honoured": "honored", "honouring": "honoring", "honours": "honors", "hospitalisation": "hospitalization", "hospitalise": "hospitalize", "hospitalised": "hospitalized", "hospitalises": "hospitalizes", "hospitalising": "hospitalizing", "humanise": "humanize", "humanised": "humanized", "humanises": "humanizes", "humanising": "humanizing", "humour": "humor", "humoured": "humored", "humouring": "humoring", "humourless": "humorless", "humours": "humors", "hybridise": "hybridize", "hybridised": "hybridized", "hybridises": "hybridizes", "hybridising": "hybridizing", "hypnotise": "hypnotize", "hypnotised": "hypnotized", "hypnotises": "hypnotizes", "hypnotising": "hypnotizing", "hypothesise": "hypothesize", "hypothesised": "hypothesized", "hypothesises": "hypothesizes", "hypothesising": "hypothesizing", "idealisation": "idealization", "idealise": "idealize", "idealised": "idealized", "idealises": "idealizes", "idealising": "idealizing", "idolise": "idolize", "idolised": "idolized", "idolises": "idolizes", "idolising": "idolizing", "immobilisation": "immobilization", "immobilise": "immobilize", "immobilised": "immobilized", "immobiliser": "immobilizer", "immobilisers": "immobilizers", "immobilises": "immobilizes", "immobilising": "immobilizing", "immortalise": "immortalize", "immortalised": "immortalized", "immortalises": "immortalizes", "immortalising": "immortalizing", "immunisation": "immunization", "immunise": "immunize", "immunised": "immunized", "immunises": "immunizes", "immunising": "immunizing", "impanelled": "impaneled", "impanelling": "impaneling", "imperilled": "imperiled", "imperilling": "imperiling", "individualise": "individualize", "individualised": "individualized", "individualises": "individualizes", "individualising": "individualizing", "industrialise": "industrialize", "industrialised": "industrialized", "industrialises": "industrializes", "industrialising": "industrializing", "inflexion": "inflection", "inflexions": "inflections", "initialise": "initialize", "initialised": "initialized", "initialises": "initializes", "initialising": "initializing", "initialled": "initialed", "initialling": "initialing", "instal": "install", "instalment": "installment", "instalments": "installments", "instals": "installs", "instil": "instill", "instils": "instills", "institutionalisation": "institutionalization", "institutionalise": "institutionalize", "institutionalised": "institutionalized", "institutionalises": "institutionalizes", "institutionalising": "institutionalizing", "intellectualise": "intellectualize", "intellectualised": "intellectualized", "intellectualises": "intellectualizes", "intellectualising": "intellectualizing", "internalisation": "internalization", "internalise": "internalize", "internalised": "internalized", "internalises": "internalizes", "internalising": "internalizing", "internationalisation": "internationalization", "internationalise": "internationalize", "internationalised": "internationalized", "internationalises": "internationalizes", "internationalising": "internationalizing", "ionisation": "ionization", "ionise": "ionize", "ionised": "ionized", "ioniser": "ionizer", "ionisers": "ionizers", "ionises": "ionizes", "ionising": "ionizing", "italicise": "italicize", "italicised": "italicized", "italicises": "italicizes", "italicising": "italicizing", "itemise": "itemize", "itemised": "itemized", "itemises": "itemizes", "itemising": "itemizing", "jeopardise": "jeopardize", "jeopardised": "jeopardized", "jeopardises": "jeopardizes", "jeopardising": "jeopardizing", "jewelled": "jeweled", "jeweller": "jeweler", "jewellers": "jewelers", "jewellery": "jewelry", "judgement": "judgment", "kilogramme": "kilogram", "kilogrammes": "kilograms", "kilometre": "kilometer", "kilometres": "kilometers", "labelled": "labeled", "labelling": "labeling", "labour": "labor", "laboured": "labored", "labourer": "laborer", "labourers": "laborers", "labouring": "laboring", "labours": "labors", "lacklustre": "lackluster", "legalisation": "legalization", "legalise": "legalize", "legalised": "legalized", "legalises": "legalizes", "legalising": "legalizing", "legitimise": "legitimize", "legitimised": "legitimized", "legitimises": "legitimizes", "legitimising": "legitimizing", "leukaemia": "leukemia", "levelled": "leveled", "leveller": "leveler", "levellers": "levelers", "levelling": "leveling", "libelled": "libeled", "libelling": "libeling", "libellous": "libelous", "liberalisation": "liberalization", "liberalise": "liberalize", "liberalised": "liberalized", "liberalises": "liberalizes", "liberalising": "liberalizing", "licence": "license", "licenced": "licensed", "licences": "licenses", "licencing": "licensing", "likeable": "likable", "lionisation": "lionization", "lionise": "lionize", "lionised": "lionized", "lionises": "lionizes", "lionising": "lionizing", "liquidise": "liquidize", "liquidised": "liquidized", "liquidiser": "liquidizer", "liquidisers": "liquidizers", "liquidises": "liquidizes", "liquidising": "liquidizing", "litre": "liter", "litres": "liters", "localise": "localize", "localised": "localized", "localises": "localizes", "localising": "localizing", "louvre": "louver", "louvred": "louvered", "louvres": "louvers", "lustre": "luster", "magnetise": "magnetize", "magnetised": "magnetized", "magnetises": "magnetizes", "magnetising": "magnetizing", "manoeuvrability": "maneuverability", "manoeuvrable": "maneuverable", "manoeuvre": "maneuver", "manoeuvred": "maneuvered", "manoeuvres": "maneuvers", "manoeuvring": "maneuvering", "manoeuvrings": "maneuverings", "marginalisation": "marginalization", "marginalise": "marginalize", "marginalised": "marginalized", "marginalises": "marginalizes", "marginalising": "marginalizing", "marshalled": "marshaled", "marshalling": "marshaling", "marvelled": "marveled", "marvelling": "marveling", "marvellous": "marvelous", "marvellously": "marvelously", "materialisation": "materialization", "materialise": "materialize", "materialised": "materialized", "materialises": "materializes", "materialising": "materializing", "maximisation": "maximization", "maximise": "maximize", "maximised": "maximized", "maximises": "maximizes", "maximising": "maximizing", "meagre": "meager", "mechanisation": "mechanization", "mechanise": "mechanize", "mechanised": "mechanized", "mechanises": "mechanizes", "mechanising": "mechanizing", "mediaeval": "medieval", "memorialise": "memorialize", "memorialised": "memorialized", "memorialises": "memorializes", "memorialising": "memorializing", "memorise": "memorize", "memorised": "memorized", "memorises": "memorizes", "memorising": "memorizing", "mesmerise": "mesmerize", "mesmerised": "mesmerized", "mesmerises": "mesmerizes", "mesmerising": "mesmerizing", "metabolise": "metabolize", "metabolised": "metabolized", "metabolises": "metabolizes", "metabolising": "metabolizing", "metre": "meter", "metres": "meters", "micrometre": "micrometer", "micrometres": "micrometers", "militarise": "militarize", "militarised": "militarized", "militarises": "militarizes", "militarising": "militarizing", "milligramme": "milligram", "milligrammes": "milligrams", "millilitre": "milliliter", "millilitres": "milliliters", "millimetre": "millimeter", "millimetres": "millimeters", "miniaturisation": "miniaturization", "miniaturise": "miniaturize", "miniaturised": "miniaturized", "miniaturises": "miniaturizes", "miniaturising": "miniaturizing", "minibusses": "minibuses", "minimise": "minimize", "minimised": "minimized", "minimises": "minimizes", "minimising": "minimizing", "misbehaviour": "misbehavior", "misdemeanour": "misdemeanor", "misdemeanours": "misdemeanors", "misspelt": "misspelled", "mitre": "miter", "mitres": "miters", "mobilisation": "mobilization", "mobilise": "mobilize", "mobilised": "mobilized", "mobilises": "mobilizes", "mobilising": "mobilizing", "modelled": "modeled", "modeller": "modeler", "modellers": "modelers", "modelling": "modeling", "modernise": "modernize", "modernised": "modernized", "modernises": "modernizes", "modernising": "modernizing", "moisturise": "moisturize", "moisturised": "moisturized", "moisturiser": "moisturizer", "moisturisers": "moisturizers", "moisturises": "moisturizes", "moisturising": "moisturizing", "monologue": "monolog", "monologues": "monologs", "monopolisation": "monopolization", "monopolise": "monopolize", "monopolised": "monopolized", "monopolises": "monopolizes", "monopolising": "monopolizing", "moralise": "moralize", "moralised": "moralized", "moralises": "moralizes", "moralising": "moralizing", "motorised": "motorized", "mould": "mold", "moulded": "molded", "moulder": "molder", "mouldered": "moldered", "mouldering": "moldering", "moulders": "molders", "mouldier": "moldier", "mouldiest": "moldiest", "moulding": "molding", "mouldings": "moldings", "moulds": "molds", "mouldy": "moldy", "moult": "molt", "moulted": "molted", "moulting": "molting", "moults": "molts", "moustache": "mustache", "moustached": "mustached", "moustaches": "mustaches", "moustachioed": "mustachioed", "multicoloured": "multicolored", "nationalisation": "nationalization", "nationalisations": "nationalizations", "nationalise": "nationalize", "nationalised": "nationalized", "nationalises": "nationalizes", "nationalising": "nationalizing", "naturalisation": "naturalization", "naturalise": "naturalize", "naturalised": "naturalized", "naturalises": "naturalizes", "naturalising": "naturalizing", "neighbour": "neighbor", "neighbourhood": "neighborhood", "neighbourhoods": "neighborhoods", "neighbouring": "neighboring", "neighbourliness": "neighborliness", "neighbourly": "neighborly", "neighbours": "neighbors", "neutralisation": "neutralization", "neutralise": "neutralize", "neutralised": "neutralized", "neutralises": "neutralizes", "neutralising": "neutralizing", "normalisation": "normalization", "normalise": "normalize", "normalised": "normalized", "normalises": "normalizes", "normalising": "normalizing", "odour": "odor", "odourless": "odorless", "odours": "odors", "oesophagus": "esophagus", "oesophaguses": "esophaguses", "oestrogen": "estrogen", "offence": "offense", "offences": "offenses", "omelette": "omelet", "omelettes": "omelets", "optimise": "optimize", "optimised": "optimized", "optimises": "optimizes", "optimising": "optimizing", "organisation": "organization", "organisational": "organizational", "organisations": "organizations", "organise": "organize", "organised": "organized", "organiser": "organizer", "organisers": "organizers", "organises": "organizes", "organising": "organizing", "orthopaedic": "orthopedic", "orthopaedics": "orthopedics", "ostracise": "ostracize", "ostracised": "ostracized", "ostracises": "ostracizes", "ostracising": "ostracizing", "outmanoeuvre": "outmaneuver", "outmanoeuvred": "outmaneuvered", "outmanoeuvres": "outmaneuvers", "outmanoeuvring": "outmaneuvering", "overemphasise": "overemphasize", "overemphasised": "overemphasized", "overemphasises": "overemphasizes", "overemphasising": "overemphasizing", "oxidisation": "oxidization", "oxidise": "oxidize", "oxidised": "oxidized", "oxidises": "oxidizes", "oxidising": "oxidizing", "paederast": "pederast", "paederasts": "pederasts", "paediatric": "pediatric", "paediatrician": "pediatrician", "paediatricians": "pediatricians", "paediatrics": "pediatrics", "paedophile": "pedophile", "paedophiles": "pedophiles", "paedophilia": "pedophilia", "palaeolithic": "paleolithic", "palaeontologist": "paleontologist", "palaeontologists": "paleontologists", "palaeontology": "paleontology", "panelled": "paneled", "panelling": "paneling", "panellist": "panelist", "panellists": "panelists", "paralyse": "paralyze", "paralysed": "paralyzed", "paralyses": "paralyzes", "paralysing": "paralyzing", "parcelled": "parceled", "parcelling": "parceling", "parlour": "parlor", "parlours": "parlors", "particularise": "particularize", "particularised": "particularized", "particularises": "particularizes", "particularising": "particularizing", "passivisation": "passivization", "passivise": "passivize", "passivised": "passivized", "passivises": "passivizes", "passivising": "passivizing", "pasteurisation": "pasteurization", "pasteurise": "pasteurize", "pasteurised": "pasteurized", "pasteurises": "pasteurizes", "pasteurising": "pasteurizing", "patronise": "patronize", "patronised": "patronized", "patronises": "patronizes", "patronising": "patronizing", "patronisingly": "patronizingly", "pedalled": "pedaled", "pedalling": "pedaling", "pedestrianisation": "pedestrianization", "pedestrianise": "pedestrianize", "pedestrianised": "pedestrianized", "pedestrianises": "pedestrianizes", "pedestrianising": "pedestrianizing", "penalise": "penalize", "penalised": "penalized", "penalises": "penalizes", "penalising": "penalizing", "pencilled": "penciled", "pencilling": "penciling", "personalise": "personalize", "personalised": "personalized", "personalises": "personalizes", "personalising": "personalizing", "pharmacopoeia": "pharmacopeia", "pharmacopoeias": "pharmacopeias", "philosophise": "philosophize", "philosophised": "philosophized", "philosophises": "philosophizes", "philosophising": "philosophizing", "philtre": "filter", "philtres": "filters", "phoney": "phony", "plagiarise": "plagiarize", "plagiarised": "plagiarized", "plagiarises": "plagiarizes", "plagiarising": "plagiarizing", "plough": "plow", "ploughed": "plowed", "ploughing": "plowing", "ploughman": "plowman", "ploughmen": "plowmen", "ploughs": "plows", "ploughshare": "plowshare", "ploughshares": "plowshares", "polarisation": "polarization", "polarise": "polarize", "polarised": "polarized", "polarises": "polarizes", "polarising": "polarizing", "politicisation": "politicization", "politicise": "politicize", "politicised": "politicized", "politicises": "politicizes", "politicising": "politicizing", "popularisation": "popularization", "popularise": "popularize", "popularised": "popularized", "popularises": "popularizes", "popularising": "popularizing", "pouffe": "pouf", "pouffes": "poufs", "practise": "practice", "practised": "practiced", "practises": "practices", "practising": "practicing", "praesidium": "presidium", "praesidiums": "presidiums", "pressurisation": "pressurization", "pressurise": "pressurize", "pressurised": "pressurized", "pressurises": "pressurizes", "pressurising": "pressurizing", "pretence": "pretense", "pretences": "pretenses", "primaeval": "primeval", "prioritisation": "prioritization", "prioritise": "prioritize", "prioritised": "prioritized", "prioritises": "prioritizes", "prioritising": "prioritizing", "privatisation": "privatization", "privatisations": "privatizations", "privatise": "privatize", "privatised": "privatized", "privatises": "privatizes", "privatising": "privatizing", "professionalisation": "professionalization", "professionalise": "professionalize", "professionalised": "professionalized", "professionalises": "professionalizes", "professionalising": "professionalizing", "programme": "program", "programmes": "programs", "prologue": "prolog", "prologues": "prologs", "propagandise": "propagandize", "propagandised": "propagandized", "propagandises": "propagandizes", "propagandising": "propagandizing", "proselytise": "proselytize", "proselytised": "proselytized", "proselytiser": "proselytizer", "proselytisers": "proselytizers", "proselytises": "proselytizes", "proselytising": "proselytizing", "psychoanalyse": "psychoanalyze", "psychoanalysed": "psychoanalyzed", "psychoanalyses": "psychoanalyzes", "psychoanalysing": "psychoanalyzing", "publicise": "publicize", "publicised": "publicized", "publicises": "publicizes", "publicising": "publicizing", "pulverisation": "pulverization", "pulverise": "pulverize", "pulverised": "pulverized", "pulverises": "pulverizes", "pulverising": "pulverizing", "pummelled": "pummel", "pummelling": "pummeled", "pyjama": "pajama", "pyjamas": "pajamas", "pzazz": "pizzazz", "quarrelled": "quarreled", "quarrelling": "quarreling", "radicalise": "radicalize", "radicalised": "radicalized", "radicalises": "radicalizes", "radicalising": "radicalizing", "rancour": "rancor", "randomise": "randomize", "randomised": "randomized", "randomises": "randomizes", "randomising": "randomizing", "rationalisation": "rationalization", "rationalisations": "rationalizations", "rationalise": "rationalize", "rationalised": "rationalized", "rationalises": "rationalizes", "rationalising": "rationalizing", "ravelled": "raveled", "ravelling": "raveling", "realisable": "realizable", "realisation": "realization", "realisations": "realizations", "realise": "realize", "realised": "realized", "realises": "realizes", "realising": "realizing", "recognisable": "recognizable", "recognisably": "recognizably", "recognisance": "recognizance", "recognise": "recognize", "recognised": "recognized", "recognises": "recognizes", "recognising": "recognizing", "reconnoitre": "reconnoiter", "reconnoitred": "reconnoitered", "reconnoitres": "reconnoiters", "reconnoitring": "reconnoitering", "refuelled": "refueled", "refuelling": "refueling", "regularisation": "regularization", "regularise": "regularize", "regularised": "regularized", "regularises": "regularizes", "regularising": "regularizing", "remodelled": "remodeled", "remodelling": "remodeling", "remould": "remold", "remoulded": "remolded", "remoulding": "remolding", "remoulds": "remolds", "reorganisation": "reorganization", "reorganisations": "reorganizations", "reorganise": "reorganize", "reorganised": "reorganized", "reorganises": "reorganizes", "reorganising": "reorganizing", "revelled": "reveled", "reveller": "reveler", "revellers": "revelers", "revelling": "reveling", "revitalise": "revitalize", "revitalised": "revitalized", "revitalises": "revitalizes", "revitalising": "revitalizing", "revolutionise": "revolutionize", "revolutionised": "revolutionized", "revolutionises": "revolutionizes", "revolutionising": "revolutionizing", "rhapsodise": "rhapsodize", "rhapsodised": "rhapsodized", "rhapsodises": "rhapsodizes", "rhapsodising": "rhapsodizing", "rigour": "rigor", "rigours": "rigors", "ritualised": "ritualized", "rivalled": "rivaled", "rivalling": "rivaling", "romanticise": "romanticize", "romanticised": "romanticized", "romanticises": "romanticizes", "romanticising": "romanticizing", "rumour": "rumor", "rumoured": "rumored", "rumours": "rumors", "sabre": "saber", "sabres": "sabers", "saltpetre": "saltpeter", "sanitise": "sanitize", "sanitised": "sanitized", "sanitises": "sanitizes", "sanitising": "sanitizing", "satirise": "satirize", "satirised": "satirized", "satirises": "satirizes", "satirising": "satirizing", "saviour": "savior", "saviours": "saviors", "savour": "savor", "savoured": "savored", "savouries": "savories", "savouring": "savoring", "savours": "savors", "savoury": "savory", "scandalise": "scandalize", "scandalised": "scandalized", "scandalises": "scandalizes", "scandalising": "scandalizing", "sceptic": "skeptic", "sceptical": "skeptical", "sceptically": "skeptically", "scepticism": "skepticism", "sceptics": "skeptics", "sceptre": "scepter", "sceptres": "scepters", "scrutinise": "scrutinize", "scrutinised": "scrutinized", "scrutinises": "scrutinizes", "scrutinising": "scrutinizing", "secularisation": "secularization", "secularise": "secularize", "secularised": "secularized", "secularises": "secularizes", "secularising": "secularizing", "sensationalise": "sensationalize", "sensationalised": "sensationalized", "sensationalises": "sensationalizes", "sensationalising": "sensationalizing", "sensitise": "sensitize", "sensitised": "sensitized", "sensitises": "sensitizes", "sensitising": "sensitizing", "sentimentalise": "sentimentalize", "sentimentalised": "sentimentalized", "sentimentalises": "sentimentalizes", "sentimentalising": "sentimentalizing", "sepulchre": "sepulcher", "sepulchres": "sepulchers", "serialisation": "serialization", "serialisations": "serializations", "serialise": "serialize", "serialised": "serialized", "serialises": "serializes", "serialising": "serializing", "sermonise": "sermonize", "sermonised": "sermonized", "sermonises": "sermonizes", "sermonising": "sermonizing", "sheikh": "sheik", "shovelled": "shoveled", "shovelling": "shoveling", "shrivelled": "shriveled", "shrivelling": "shriveling", "signalise": "signalize", "signalised": "signalized", "signalises": "signalizes", "signalising": "signalizing", "signalled": "signaled", "signalling": "signaling", "smoulder": "smolder", "smouldered": "smoldered", "smouldering": "smoldering", "smoulders": "smolders", "snivelled": "sniveled", "snivelling": "sniveling", "snorkelled": "snorkeled", "snorkelling": "snorkeling", "snowplough": "snowplow", "snowploughs": "snowplow", "socialisation": "socialization", "socialise": "socialize", "socialised": "socialized", "socialises": "socializes", "socialising": "socializing", "sodomise": "sodomize", "sodomised": "sodomized", "sodomises": "sodomizes", "sodomising": "sodomizing", "solemnise": "solemnize", "solemnised": "solemnized", "solemnises": "solemnizes", "solemnising": "solemnizing", "sombre": "somber", "specialisation": "specialization", "specialisations": "specializations", "specialise": "specialize", "specialised": "specialized", "specialises": "specializes", "specialising": "specializing", "spectre": "specter", "spectres": "specters", "spiralled": "spiraled", "spiralling": "spiraling", "splendour": "splendor", "splendours": "splendors", "squirrelled": "squirreled", "squirrelling": "squirreling", "stabilisation": "stabilization", "stabilise": "stabilize", "stabilised": "stabilized", "stabiliser": "stabilizer", "stabilisers": "stabilizers", "stabilises": "stabilizes", "stabilising": "stabilizing", "standardisation": "standardization", "standardise": "standardize", "standardised": "standardized", "standardises": "standardizes", "standardising": "standardizing", "stencilled": "stenciled", "stencilling": "stenciling", "sterilisation": "sterilization", "sterilisations": "sterilizations", "sterilise": "sterilize", "sterilised": "sterilized", "steriliser": "sterilizer", "sterilisers": "sterilizers", "sterilises": "sterilizes", "sterilising": "sterilizing", "stigmatisation": "stigmatization", "stigmatise": "stigmatize", "stigmatised": "stigmatized", "stigmatises": "stigmatizes", "stigmatising": "stigmatizing", "storey": "story", "storeys": "stories", "subsidisation": "subsidization", "subsidise": "subsidize", "subsidised": "subsidized", "subsidiser": "subsidizer", "subsidisers": "subsidizers", "subsidises": "subsidizes", "subsidising": "subsidizing", "succour": "succor", "succoured": "succored", "succouring": "succoring", "succours": "succors", "sulphate": "sulfate", "sulphates": "sulfates", "sulphide": "sulfide", "sulphides": "sulfides", "sulphur": "sulfur", "sulphurous": "sulfurous", "summarise": "summarize", "summarised": "summarized", "summarises": "summarizes", "summarising": "summarizing", "swivelled": "swiveled", "swivelling": "swiveling", "symbolise": "symbolize", "symbolised": "symbolized", "symbolises": "symbolizes", "symbolising": "symbolizing", "sympathise": "sympathize", "sympathised": "sympathized", "sympathiser": "sympathizer", "sympathisers": "sympathizers", "sympathises": "sympathizes", "sympathising": "sympathizing", "synchronisation": "synchronization", "synchronise": "synchronize", "synchronised": "synchronized", "synchronises": "synchronizes", "synchronising": "synchronizing", "synthesise": "synthesize", "synthesised": "synthesized", "synthesiser": "synthesizer", "synthesisers": "synthesizers", "synthesises": "synthesizes", "synthesising": "synthesizing", "syphon": "siphon", "syphoned": "siphoned", "syphoning": "siphoning", "syphons": "siphons", "systematisation": "systematization", "systematise": "systematize", "systematised": "systematized", "systematises": "systematizes", "systematising": "systematizing", "tantalise": "tantalize", "tantalised": "tantalized", "tantalises": "tantalizes", "tantalising": "tantalizing", "tantalisingly": "tantalizingly", "tasselled": "tasseled", "technicolour": "technicolor", "temporise": "temporize", "temporised": "temporized", "temporises": "temporizes", "temporising": "temporizing", "tenderise": "tenderize", "tenderised": "tenderized", "tenderises": "tenderizes", "tenderising": "tenderizing", "terrorise": "terrorize", "terrorised": "terrorized", "terrorises": "terrorizes", "terrorising": "terrorizing", "theatre": "theater", "theatregoer": "theatergoer", "theatregoers": "theatergoers", "theatres": "theaters", "theorise": "theorize", "theorised": "theorized", "theorises": "theorizes", "theorising": "theorizing", "tonne": "ton", "tonnes": "tons", "towelled": "toweled", "towelling": "toweling", "toxaemia": "toxemia", "tranquillise": "tranquilize", "tranquillised": "tranquilized", "tranquilliser": "tranquilizer", "tranquillisers": "tranquilizers", "tranquillises": "tranquilizes", "tranquillising": "tranquilizing", "tranquillity": "tranquility", "tranquillize": "tranquilize", "tranquillized": "tranquilized", "tranquillizer": "tranquilizer", "tranquillizers": "tranquilizers", "tranquillizes": "tranquilizes", "tranquillizing": "tranquilizing", "tranquilly": "tranquility", "transistorised": "transistorized", "traumatise": "traumatize", "traumatised": "traumatized", "traumatises": "traumatizes", "traumatising": "traumatizing", "travelled": "traveled", "traveller": "traveler", "travellers": "travelers", "travelling": "traveling", "travelog": "travelogue", "travelogs": "travelogues", "trialled": "trialed", "trialling": "trialing", "tricolour": "tricolor", "tricolours": "tricolors", "trivialise": "trivialize", "trivialised": "trivialized", "trivialises": "trivializes", "trivialising": "trivializing", "tumour": "tumor", "tumours": "tumors", "tunnelled": "tunneled", "tunnelling": "tunneling", "tyrannise": "tyrannize", "tyrannised": "tyrannized", "tyrannises": "tyrannizes", "tyrannising": "tyrannizing", "tyre": "tire", "tyres": "tires", "unauthorised": "unauthorized", "uncivilised": "uncivilized", "underutilised": "underutilized", "unequalled": "unequaled", "unfavourable": "unfavorable", "unfavourably": "unfavorably", "unionisation": "unionization", "unionise": "unionize", "unionised": "unionized", "unionises": "unionizes", "unionising": "unionizing", "unorganised": "unorganized", "unravelled": "unraveled", "unravelling": "unraveling", "unrecognisable": "unrecognizable", "unrecognised": "unrecognized", "unrivalled": "unrivaled", "unsavoury": "unsavory", "untrammelled": "untrammeled", "urbanisation": "urbanization", "urbanise": "urbanize", "urbanised": "urbanized", "urbanises": "urbanizes", "urbanising": "urbanizing", "utilisable": "utilizable", "utilisation": "utilization", "utilise": "utilize", "utilised": "utilized", "utilises": "utilizes", "utilising": "utilizing", "valour": "valor", "vandalise": "vandalize", "vandalised": "vandalized", "vandalises": "vandalizes", "vandalising": "vandalizing", "vaporisation": "vaporization", "vaporise": "vaporize", "vaporised": "vaporized", "vaporises": "vaporizes", "vaporising": "vaporizing", "vapour": "vapor", "vapours": "vapors", "verbalise": "verbalize", "verbalised": "verbalized", "verbalises": "verbalizes", "verbalising": "verbalizing", "victimisation": "victimization", "victimise": "victimize", "victimised": "victimized", "victimises": "victimizes", "victimising": "victimizing", "videodisc": "videodisk", "videodiscs": "videodisks", "vigour": "vigor", "visualisation": "visualization", "visualisations": "visualizations", "visualise": "visualize", "visualised": "visualized", "visualises": "visualizes", "visualising": "visualizing", "vocalisation": "vocalization", "vocalisations": "vocalizations", "vocalise": "vocalize", "vocalised": "vocalized", "vocalises": "vocalizes", "vocalising": "vocalizing", "vulcanised": "vulcanized", "vulgarisation": "vulgarization", "vulgarise": "vulgarize", "vulgarised": "vulgarized", "vulgarises": "vulgarizes", "vulgarising": "vulgarizing", "waggon": "wagon", "waggons": "wagons", "watercolour": "watercolor", "watercolours": "watercolors", "weaselled": "weaseled", "weaselling": "weaseling", "westernisation": "westernization", "westernise": "westernize", "westernised": "westernized", "westernises": "westernizes", "westernising": "westernizing", "womanise": "womanize", "womanised": "womanized", "womaniser": "womanizer", "womanisers": "womanizers", "womanises": "womanizes", "womanising": "womanizing", "woollen": "woolen", "woollens": "woolens", "woollies": "woolies", "woolly": "wooly", "worshipped": "worshiped", "worshipping": "worshiping", "worshipper": "worshiper", "yodelled": "yodeled", "yodelling": "yodeling", "yoghourt": "yogurt", "yoghourts": "yogurts", "yoghurt": "yogurt", "yoghurts": "yogurts", "mhm": "hmm", "mmm": "hmm"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550import jsonimport osimport refrom fractions import Fractionfrom typing import Iterator, List, Match, Optional, Union
from more_itertools import windowed
from .basic import remove_symbols_and_diacritics
class EnglishNumberNormalizer: """ Convert any spelled-out numbers into arabic numbers, while handling:
- remove any commas - keep the suffixes such as: `1960s`, `274th`, `32nd`, etc. - spell out currency symbols after the number. e.g. `$20 million` -> `20000000 dollars` - spell out `one` and `ones` - interpret successive single-digit numbers as nominal: `one oh one` -> `101` """
def __init__(self): super().__init__()
self.zeros = {"o", "oh", "zero"} self.ones = { name: i for i, name in enumerate( [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ], start=1, ) } self.ones_plural = { "sixes" if name == "six" else name + "s": (value, "s") for name, value in self.ones.items() } self.ones_ordinal = { "zeroth": (0, "th"), "first": (1, "st"), "second": (2, "nd"), "third": (3, "rd"), "fifth": (5, "th"), "twelfth": (12, "th"), **{ name + ("h" if name.endswith("t") else "th"): (value, "th") for name, value in self.ones.items() if value > 3 and value != 5 and value != 12 }, } self.ones_suffixed = {**self.ones_plural, **self.ones_ordinal}
self.tens = { "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, } self.tens_plural = { name.replace("y", "ies"): (value, "s") for name, value in self.tens.items() } self.tens_ordinal = { name.replace("y", "ieth"): (value, "th") for name, value in self.tens.items() } self.tens_suffixed = {**self.tens_plural, **self.tens_ordinal}
self.multipliers = { "hundred": 100, "thousand": 1_000, "million": 1_000_000, "billion": 1_000_000_000, "trillion": 1_000_000_000_000, "quadrillion": 1_000_000_000_000_000, "quintillion": 1_000_000_000_000_000_000, "sextillion": 1_000_000_000_000_000_000_000, "septillion": 1_000_000_000_000_000_000_000_000, "octillion": 1_000_000_000_000_000_000_000_000_000, "nonillion": 1_000_000_000_000_000_000_000_000_000_000, "decillion": 1_000_000_000_000_000_000_000_000_000_000_000, } self.multipliers_plural = { name + "s": (value, "s") for name, value in self.multipliers.items() } self.multipliers_ordinal = { name + "th": (value, "th") for name, value in self.multipliers.items() } self.multipliers_suffixed = { **self.multipliers_plural, **self.multipliers_ordinal, } self.decimals = {*self.ones, *self.tens, *self.zeros}
self.preceding_prefixers = { "minus": "-", "negative": "-", "plus": "+", "positive": "+", } self.following_prefixers = { "pound": "£", "pounds": "£", "euro": "€", "euros": "€", "dollar": "$", "dollars": "$", "cent": "¢", "cents": "¢", } self.prefixes = set( list(self.preceding_prefixers.values()) + list(self.following_prefixers.values()) ) self.suffixers = { "per": {"cent": "%"}, "percent": "%", } self.specials = {"and", "double", "triple", "point"}
self.words = set( [ key for mapping in [ self.zeros, self.ones, self.ones_suffixed, self.tens, self.tens_suffixed, self.multipliers, self.multipliers_suffixed, self.preceding_prefixers, self.following_prefixers, self.suffixers, self.specials, ] for key in mapping ] ) self.literal_words = {"one", "ones"}
def process_words(self, words: List[str]) -> Iterator[str]: prefix: Optional[str] = None value: Optional[Union[str, int]] = None skip = False
def to_fraction(s: str): try: return Fraction(s) except ValueError: return None
def output(result: Union[str, int]): nonlocal prefix, value result = str(result) if prefix is not None: result = prefix + result value = None prefix = None return result
if len(words) == 0: return
for prev, current, next in windowed([None] + words + [None], 3): if skip: skip = False continue
next_is_numeric = next is not None and re.match(r"^\d+(\.\d+)?$", next) has_prefix = current[0] in self.prefixes current_without_prefix = current[1:] if has_prefix else current if re.match(r"^\d+(\.\d+)?$", current_without_prefix): # arabic numbers (potentially with signs and fractions) f = to_fraction(current_without_prefix) assert f is not None if value is not None: if isinstance(value, str) and value.endswith("."): # concatenate decimals / ip address components value = str(value) + str(current) continue else: yield output(value)
prefix = current[0] if has_prefix else prefix if f.denominator == 1: value = f.numerator # store integers as int else: value = current_without_prefix elif current not in self.words: # non-numeric words if value is not None: yield output(value) yield output(current) elif current in self.zeros: value = str(value or "") + "0" elif current in self.ones: ones = self.ones[current]
if value is None: value = ones elif isinstance(value, str) or prev in self.ones: if ( prev in self.tens and ones < 10 ): # replace the last zero with the digit assert value[-1] == "0" value = value[:-1] + str(ones) else: value = str(value) + str(ones) elif ones < 10: if value % 10 == 0: value += ones else: value = str(value) + str(ones) else: # eleven to nineteen if value % 100 == 0: value += ones else: value = str(value) + str(ones) elif current in self.ones_suffixed: # ordinal or cardinal; yield the number right away ones, suffix = self.ones_suffixed[current] if value is None: yield output(str(ones) + suffix) elif isinstance(value, str) or prev in self.ones: if prev in self.tens and ones < 10: assert value[-1] == "0" yield output(value[:-1] + str(ones) + suffix) else: yield output(str(value) + str(ones) + suffix) elif ones < 10: if value % 10 == 0: yield output(str(value + ones) + suffix) else: yield output(str(value) + str(ones) + suffix) else: # eleven to nineteen if value % 100 == 0: yield output(str(value + ones) + suffix) else: yield output(str(value) + str(ones) + suffix) value = None elif current in self.tens: tens = self.tens[current] if value is None: value = tens elif isinstance(value, str): value = str(value) + str(tens) else: if value % 100 == 0: value += tens else: value = str(value) + str(tens) elif current in self.tens_suffixed: # ordinal or cardinal; yield the number right away tens, suffix = self.tens_suffixed[current] if value is None: yield output(str(tens) + suffix) elif isinstance(value, str): yield output(str(value) + str(tens) + suffix) else: if value % 100 == 0: yield output(str(value + tens) + suffix) else: yield output(str(value) + str(tens) + suffix) elif current in self.multipliers: multiplier = self.multipliers[current] if value is None: value = multiplier elif isinstance(value, str) or value == 0: f = to_fraction(value) p = f * multiplier if f is not None else None if f is not None and p.denominator == 1: value = p.numerator else: yield output(value) value = multiplier else: before = value // 1000 * 1000 residual = value % 1000 value = before + residual * multiplier elif current in self.multipliers_suffixed: multiplier, suffix = self.multipliers_suffixed[current] if value is None: yield output(str(multiplier) + suffix) elif isinstance(value, str): f = to_fraction(value) p = f * multiplier if f is not None else None if f is not None and p.denominator == 1: yield output(str(p.numerator) + suffix) else: yield output(value) yield output(str(multiplier) + suffix) else: # int before = value // 1000 * 1000 residual = value % 1000 value = before + residual * multiplier yield output(str(value) + suffix) value = None elif current in self.preceding_prefixers: # apply prefix (positive, minus, etc.) if it precedes a number if value is not None: yield output(value)
if next in self.words or next_is_numeric: prefix = self.preceding_prefixers[current] else: yield output(current) elif current in self.following_prefixers: # apply prefix (dollars, cents, etc.) only after a number if value is not None: prefix = self.following_prefixers[current] yield output(value) else: yield output(current) elif current in self.suffixers: # apply suffix symbols (percent -> '%') if value is not None: suffix = self.suffixers[current] if isinstance(suffix, dict): if next in suffix: yield output(str(value) + suffix[next]) skip = True else: yield output(value) yield output(current) else: yield output(str(value) + suffix) else: yield output(current) elif current in self.specials: if next not in self.words and not next_is_numeric: # apply special handling only if the next word can be numeric if value is not None: yield output(value) yield output(current) elif current == "and": # ignore "and" after hundreds, thousands, etc. if prev not in self.multipliers: if value is not None: yield output(value) yield output(current) elif current == "double" or current == "triple": if next in self.ones or next in self.zeros: repeats = 2 if current == "double" else 3 ones = self.ones.get(next, 0) value = str(value or "") + str(ones) * repeats skip = True else: if value is not None: yield output(value) yield output(current) elif current == "point": if next in self.decimals or next_is_numeric: value = str(value or "") + "." else: # should all have been covered at this point raise ValueError(f"Unexpected token: {current}") else: # all should have been covered at this point raise ValueError(f"Unexpected token: {current}")
if value is not None: yield output(value)
def preprocess(self, s: str): # replace "<number> and a half" with "<number> point five" results = []
segments = re.split(r"\band\s+a\s+half\b", s) for i, segment in enumerate(segments): if len(segment.strip()) == 0: continue if i == len(segments) - 1: results.append(segment) else: results.append(segment) last_word = segment.rsplit(maxsplit=2)[-1] if last_word in self.decimals or last_word in self.multipliers: results.append("point five") else: results.append("and a half")
s = " ".join(results)
# put a space at number/letter boundary s = re.sub(r"([a-z])([0-9])", r"\1 \2", s) s = re.sub(r"([0-9])([a-z])", r"\1 \2", s)
# but remove spaces which could be a suffix s = re.sub(r"([0-9])\s+(st|nd|rd|th|s)\b", r"\1\2", s)
return s
def postprocess(self, s: str): def combine_cents(m: Match): try: currency = m.group(1) integer = m.group(2) cents = int(m.group(3)) return f"{currency}{integer}.{cents:02d}" except ValueError: return m.string
def extract_cents(m: Match): try: return f"¢{int(m.group(1))}" except ValueError: return m.string
# apply currency postprocessing; "$2 and ¢7" -> "$2.07" s = re.sub(r"([€£$])([0-9]+) (?:and )?¢([0-9]{1,2})\b", combine_cents, s) s = re.sub(r"[€£$]0.([0-9]{1,2})\b", extract_cents, s)
# write "one(s)" instead of "1(s)", just for the readability s = re.sub(r"\b1(s?)\b", r"one\1", s)
return s
def __call__(self, s: str): s = self.preprocess(s) s = " ".join(word for word in self.process_words(s.split()) if word is not None) s = self.postprocess(s)
return s
class EnglishSpellingNormalizer: """ Applies British-American spelling mappings as listed in [1].
[1] https://www.tysto.com/uk-us-spelling-list.html """
def __init__(self): mapping_path = os.path.join(os.path.dirname(__file__), "english.json") self.mapping = json.load(open(mapping_path))
def __call__(self, s: str): return " ".join(self.mapping.get(word, word) for word in s.split())
class EnglishTextNormalizer: def __init__(self): self.ignore_patterns = r"\b(hmm|mm|mhm|mmm|uh|um)\b" self.replacers = { # common contractions r"\bwon't\b": "will not", r"\bcan't\b": "can not", r"\blet's\b": "let us", r"\bain't\b": "aint", r"\by'all\b": "you all", r"\bwanna\b": "want to", r"\bgotta\b": "got to", r"\bgonna\b": "going to", r"\bi'ma\b": "i am going to", r"\bimma\b": "i am going to", r"\bwoulda\b": "would have", r"\bcoulda\b": "could have", r"\bshoulda\b": "should have", r"\bma'am\b": "madam", # contractions in titles/prefixes r"\bmr\b": "mister ", r"\bmrs\b": "missus ", r"\bst\b": "saint ", r"\bdr\b": "doctor ", r"\bprof\b": "professor ", r"\bcapt\b": "captain ", r"\bgov\b": "governor ", r"\bald\b": "alderman ", r"\bgen\b": "general ", r"\bsen\b": "senator ", r"\brep\b": "representative ", r"\bpres\b": "president ", r"\brev\b": "reverend ", r"\bhon\b": "honorable ", r"\basst\b": "assistant ", r"\bassoc\b": "associate ", r"\blt\b": "lieutenant ", r"\bcol\b": "colonel ", r"\bjr\b": "junior ", r"\bsr\b": "senior ", r"\besq\b": "esquire ", # prefect tenses, ideally it should be any past participles, but it's harder.. r"'d been\b": " had been", r"'s been\b": " has been", r"'d gone\b": " had gone", r"'s gone\b": " has gone", r"'d done\b": " had done", # "'s done" is ambiguous r"'s got\b": " has got", # general contractions r"n't\b": " not", r"'re\b": " are", r"'s\b": " is", r"'d\b": " would", r"'ll\b": " will", r"'t\b": " not", r"'ve\b": " have", r"'m\b": " am", } self.standardize_numbers = EnglishNumberNormalizer() self.standardize_spellings = EnglishSpellingNormalizer()
def __call__(self, s: str): s = s.lower()
s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis s = re.sub(self.ignore_patterns, "", s) s = re.sub(r"\s+'", "'", s) # when there's a space before an apostrophe
for pattern, replacement in self.replacers.items(): s = re.sub(pattern, replacement, s)
s = re.sub(r"(\d),(\d)", r"\1\2", s) # remove commas between digits s = re.sub(r"\.([^0-9]|$)", r" \1", s) # remove periods not followed by numbers s = remove_symbols_and_diacritics(s, keep=".%$¢€£") # keep numeric symbols
s = self.standardize_numbers(s) s = self.standardize_spellings(s)
# now remove prefix/suffix symbols that are not preceded/followed by numbers s = re.sub(r"[.$¢€£]([^0-9])", r" \1", s) s = re.sub(r"([^0-9])%", r"\1 ", s)
s = re.sub(r"\s+", " ", s) # replace any successive whitespaces with a space
return s123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385import itertoolsimport subprocessimport warningsfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, List
import numbaimport numpy as npimport torchimport torch.nn.functional as F
from .audio import HOP_LENGTH, SAMPLE_RATE, TOKENS_PER_SECONDfrom .tokenizer import Tokenizer
if TYPE_CHECKING: from .model import Whisper
def median_filter(x: torch.Tensor, filter_width: int): """Apply a median filter of width `filter_width` along the last dimension of `x`""" pad_width = filter_width // 2 if x.shape[-1] <= pad_width: # F.pad requires the padding width to be smaller than the input dimension return x
if (ndim := x.ndim) <= 2: # `F.pad` does not support 1D or 2D inputs for reflect padding but supports 3D and 4D x = x[None, None, :]
assert ( filter_width > 0 and filter_width % 2 == 1 ), "`filter_width` should be an odd number"
result = None x = F.pad(x, (filter_width // 2, filter_width // 2, 0, 0), mode="reflect") if x.is_cuda: try: from .triton_ops import median_filter_cuda
result = median_filter_cuda(x, filter_width) except (RuntimeError, subprocess.CalledProcessError): warnings.warn( "Failed to launch Triton kernels, likely due to missing CUDA toolkit; " "falling back to a slower median kernel implementation..." )
if result is None: # sort() is faster than torch.median (https://github.com/pytorch/pytorch/issues/51450) result = x.unfold(-1, filter_width, 1).sort()[0][..., filter_width // 2]
if ndim <= 2: result = result[0, 0]
return result
@numba.jit(nopython=True)def backtrace(trace: np.ndarray): i = trace.shape[0] - 1 j = trace.shape[1] - 1 trace[0, :] = 2 trace[:, 0] = 1
result = [] while i > 0 or j > 0: result.append((i - 1, j - 1))
if trace[i, j] == 0: i -= 1 j -= 1 elif trace[i, j] == 1: i -= 1 elif trace[i, j] == 2: j -= 1 else: raise ValueError("Unexpected trace[i, j]")
result = np.array(result) return result[::-1, :].T
@numba.jit(nopython=True, parallel=True)def dtw_cpu(x: np.ndarray): N, M = x.shape cost = np.ones((N + 1, M + 1), dtype=np.float32) * np.inf trace = -np.ones((N + 1, M + 1), dtype=np.float32)
cost[0, 0] = 0 for j in range(1, M + 1): for i in range(1, N + 1): c0 = cost[i - 1, j - 1] c1 = cost[i - 1, j] c2 = cost[i, j - 1]
if c0 < c1 and c0 < c2: c, t = c0, 0 elif c1 < c0 and c1 < c2: c, t = c1, 1 else: c, t = c2, 2
cost[i, j] = x[i - 1, j - 1] + c trace[i, j] = t
return backtrace(trace)
def dtw_cuda(x, BLOCK_SIZE=1024): from .triton_ops import dtw_kernel
M, N = x.shape assert M < BLOCK_SIZE, f"M should be smaller than {BLOCK_SIZE=}"
x_skew = ( F.pad(x, (0, M + 1), value=np.inf).flatten()[: M * (N + M)].reshape(M, N + M) ) x_skew = x_skew.T.contiguous() cost = torch.ones(N + M + 2, M + 2) * np.inf cost[0, 0] = 0 cost = cost.cuda() trace = torch.zeros_like(cost, dtype=torch.int32)
dtw_kernel[(1,)]( cost, trace, x_skew, x_skew.stride(0), cost.stride(0), trace.stride(0), N, M, BLOCK_SIZE=BLOCK_SIZE, )
trace = trace.T.flatten()[: (M + 1) * (M + N + 3)].reshape(M + 1, M + N + 3)[ :, : N + 1 ] return backtrace(trace.cpu().numpy())
def dtw(x: torch.Tensor) -> np.ndarray: if x.is_cuda: try: return dtw_cuda(x) except (RuntimeError, subprocess.CalledProcessError): warnings.warn( "Failed to launch Triton kernels, likely due to missing CUDA toolkit; " "falling back to a slower DTW implementation..." )
return dtw_cpu(x.double().cpu().numpy())
@dataclassclass WordTiming: word: str tokens: List[int] start: float end: float probability: float
def find_alignment( model: "Whisper", tokenizer: Tokenizer, text_tokens: List[int], mel: torch.Tensor, num_frames: int, *, medfilt_width: int = 7, qk_scale: float = 1.0,) -> List[WordTiming]: if len(text_tokens) == 0: return []
tokens = torch.tensor( [ *tokenizer.sot_sequence, tokenizer.no_timestamps, *text_tokens, tokenizer.eot, ] ).to(model.device)
# install hooks on the cross attention layers to retrieve the attention weights QKs = [None] * model.dims.n_text_layer hooks = [ block.cross_attn.register_forward_hook( lambda _, ins, outs, index=i: QKs.__setitem__(index, outs[-1][0]) ) for i, block in enumerate(model.decoder.blocks) ]
with torch.no_grad(): logits = model(mel.unsqueeze(0), tokens.unsqueeze(0))[0] sampled_logits = logits[len(tokenizer.sot_sequence) :, : tokenizer.eot] token_probs = sampled_logits.softmax(dim=-1) text_token_probs = token_probs[np.arange(len(text_tokens)), text_tokens] text_token_probs = text_token_probs.tolist()
for hook in hooks: hook.remove()
# heads * tokens * frames weights = torch.stack([QKs[_l][_h] for _l, _h in model.alignment_heads.indices().T]) weights = weights[:, :, : num_frames // 2] weights = (weights * qk_scale).softmax(dim=-1) std, mean = torch.std_mean(weights, dim=-2, keepdim=True, unbiased=False) weights = (weights - mean) / std weights = median_filter(weights, medfilt_width)
matrix = weights.mean(axis=0) matrix = matrix[len(tokenizer.sot_sequence) : -1] text_indices, time_indices = dtw(-matrix)
words, word_tokens = tokenizer.split_to_word_tokens(text_tokens + [tokenizer.eot]) if len(word_tokens) <= 1: # return on eot only # >>> np.pad([], (1, 0)) # array([0.]) # This results in crashes when we lookup jump_times with float, like # IndexError: arrays used as indices must be of integer (or boolean) type return [] word_boundaries = np.pad(np.cumsum([len(t) for t in word_tokens[:-1]]), (1, 0))
jumps = np.pad(np.diff(text_indices), (1, 0), constant_values=1).astype(bool) jump_times = time_indices[jumps] / TOKENS_PER_SECOND start_times = jump_times[word_boundaries[:-1]] end_times = jump_times[word_boundaries[1:]] word_probabilities = [ np.mean(text_token_probs[i:j]) for i, j in zip(word_boundaries[:-1], word_boundaries[1:]) ]
return [ WordTiming(word, tokens, start, end, probability) for word, tokens, start, end, probability in zip( words, word_tokens, start_times, end_times, word_probabilities ) ]
def merge_punctuations(alignment: List[WordTiming], prepended: str, appended: str): # merge prepended punctuations i = len(alignment) - 2 j = len(alignment) - 1 while i >= 0: previous = alignment[i] following = alignment[j] if previous.word.startswith(" ") and previous.word.strip() in prepended: # prepend it to the following word following.word = previous.word + following.word following.tokens = previous.tokens + following.tokens previous.word = "" previous.tokens = [] else: j = i i -= 1
# merge appended punctuations i = 0 j = 1 while j < len(alignment): previous = alignment[i] following = alignment[j] if not previous.word.endswith(" ") and following.word in appended: # append it to the previous word previous.word = previous.word + following.word previous.tokens = previous.tokens + following.tokens following.word = "" following.tokens = [] else: i = j j += 1
def add_word_timestamps( *, segments: List[dict], model: "Whisper", tokenizer: Tokenizer, mel: torch.Tensor, num_frames: int, prepend_punctuations: str = "\"'“¿([{-", append_punctuations: str = "\"'.。,,!!??::”)]}、", last_speech_timestamp: float, **kwargs,): if len(segments) == 0: return
text_tokens_per_segment = [ [token for token in segment["tokens"] if token < tokenizer.eot] for segment in segments ]
text_tokens = list(itertools.chain.from_iterable(text_tokens_per_segment)) alignment = find_alignment(model, tokenizer, text_tokens, mel, num_frames, **kwargs) word_durations = np.array([t.end - t.start for t in alignment]) word_durations = word_durations[word_durations.nonzero()] median_duration = np.median(word_durations) if len(word_durations) > 0 else 0.0 max_duration = median_duration * 2
# hack: truncate long words at sentence boundaries. # a better segmentation algorithm based on VAD should be able to replace this. if len(word_durations) > 0: sentence_end_marks = ".。!!??" # ensure words at sentence boundaries are not longer than twice the median word duration. for i in range(1, len(alignment)): if alignment[i].end - alignment[i].start > max_duration: if alignment[i].word in sentence_end_marks: alignment[i].end = alignment[i].start + max_duration elif alignment[i - 1].word in sentence_end_marks: alignment[i].start = alignment[i].end - max_duration
merge_punctuations(alignment, prepend_punctuations, append_punctuations)
time_offset = segments[0]["seek"] * HOP_LENGTH / SAMPLE_RATE word_index = 0
for segment, text_tokens in zip(segments, text_tokens_per_segment): saved_tokens = 0 words = []
while word_index < len(alignment) and saved_tokens < len(text_tokens): timing = alignment[word_index]
if timing.word: words.append( dict( word=timing.word, start=round(time_offset + timing.start, 2), end=round(time_offset + timing.end, 2), probability=timing.probability, ) )
saved_tokens += len(timing.tokens) word_index += 1
# hack: truncate long words at segment boundaries. # a better segmentation algorithm based on VAD should be able to replace this. if len(words) > 0: # ensure the first and second word after a pause is not longer than # twice the median word duration. if words[0]["end"] - last_speech_timestamp > median_duration * 4 and ( words[0]["end"] - words[0]["start"] > max_duration or ( len(words) > 1 and words[1]["end"] - words[0]["start"] > max_duration * 2 ) ): if ( len(words) > 1 and words[1]["end"] - words[1]["start"] > max_duration ): boundary = max(words[1]["end"] / 2, words[1]["end"] - max_duration) words[0]["end"] = words[1]["start"] = boundary words[0]["start"] = max(0, words[0]["end"] - max_duration)
# prefer the segment-level start timestamp if the first word is too long. if ( segment["start"] < words[0]["end"] and segment["start"] - 0.5 > words[0]["start"] ): words[0]["start"] = max( 0, min(words[0]["end"] - median_duration, segment["start"]) ) else: segment["start"] = words[0]["start"]
# prefer the segment-level end timestamp if the last word is too long. if ( segment["end"] > words[-1]["start"] and segment["end"] + 0.5 < words[-1]["end"] ): words[-1]["end"] = max( words[-1]["start"] + median_duration, segment["end"] ) else: segment["end"] = words[-1]["end"]
last_speech_timestamp = segment["end"]
segment["words"] = words123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import base64import osimport stringfrom dataclasses import dataclass, fieldfrom functools import cached_property, lru_cachefrom typing import Dict, List, Optional, Tuple
import tiktoken
LANGUAGES = { "en": "english", "zh": "chinese", "de": "german", "es": "spanish", "ru": "russian", "ko": "korean", "fr": "french", "ja": "japanese", "pt": "portuguese", "tr": "turkish", "pl": "polish", "ca": "catalan", "nl": "dutch", "ar": "arabic", "sv": "swedish", "it": "italian", "id": "indonesian", "hi": "hindi", "fi": "finnish", "vi": "vietnamese", "he": "hebrew", "uk": "ukrainian", "el": "greek", "ms": "malay", "cs": "czech", "ro": "romanian", "da": "danish", "hu": "hungarian", "ta": "tamil", "no": "norwegian", "th": "thai", "ur": "urdu", "hr": "croatian", "bg": "bulgarian", "lt": "lithuanian", "la": "latin", "mi": "maori", "ml": "malayalam", "cy": "welsh", "sk": "slovak", "te": "telugu", "fa": "persian", "lv": "latvian", "bn": "bengali", "sr": "serbian", "az": "azerbaijani", "sl": "slovenian", "kn": "kannada", "et": "estonian", "mk": "macedonian", "br": "breton", "eu": "basque", "is": "icelandic", "hy": "armenian", "ne": "nepali", "mn": "mongolian", "bs": "bosnian", "kk": "kazakh", "sq": "albanian", "sw": "swahili", "gl": "galician", "mr": "marathi", "pa": "punjabi", "si": "sinhala", "km": "khmer", "sn": "shona", "yo": "yoruba", "so": "somali", "af": "afrikaans", "oc": "occitan", "ka": "georgian", "be": "belarusian", "tg": "tajik", "sd": "sindhi", "gu": "gujarati", "am": "amharic", "yi": "yiddish", "lo": "lao", "uz": "uzbek", "fo": "faroese", "ht": "haitian creole", "ps": "pashto", "tk": "turkmen", "nn": "nynorsk", "mt": "maltese", "sa": "sanskrit", "lb": "luxembourgish", "my": "myanmar", "bo": "tibetan", "tl": "tagalog", "mg": "malagasy", "as": "assamese", "tt": "tatar", "haw": "hawaiian", "ln": "lingala", "ha": "hausa", "ba": "bashkir", "jw": "javanese", "su": "sundanese", "yue": "cantonese",}
# language code lookup by name, with a few language aliasesTO_LANGUAGE_CODE = { **{language: code for code, language in LANGUAGES.items()}, "burmese": "my", "valencian": "ca", "flemish": "nl", "haitian": "ht", "letzeburgesch": "lb", "pushto": "ps", "panjabi": "pa", "moldavian": "ro", "moldovan": "ro", "sinhalese": "si", "castilian": "es", "mandarin": "zh",}
@dataclassclass Tokenizer: """A thin wrapper around `tiktoken` providing quick access to special tokens"""
encoding: tiktoken.Encoding num_languages: int language: Optional[str] = None task: Optional[str] = None sot_sequence: Tuple[int] = () special_tokens: Dict[str, int] = field(default_factory=dict)
def __post_init__(self): for special in self.encoding.special_tokens_set: special_token = self.encoding.encode_single_token(special) self.special_tokens[special] = special_token
sot: int = self.special_tokens["<|startoftranscript|>"] translate: int = self.special_tokens["<|translate|>"] transcribe: int = self.special_tokens["<|transcribe|>"]
langs = tuple(LANGUAGES.keys())[: self.num_languages] sot_sequence = [sot] if self.language is not None: sot_sequence.append(sot + 1 + langs.index(self.language)) if self.task is not None: task_token: int = transcribe if self.task == "transcribe" else translate sot_sequence.append(task_token)
self.sot_sequence = tuple(sot_sequence)
def encode(self, text, **kwargs): return self.encoding.encode(text, **kwargs)
def decode(self, token_ids: List[int], **kwargs) -> str: token_ids = [t for t in token_ids if t < self.timestamp_begin] return self.encoding.decode(token_ids, **kwargs)
def decode_with_timestamps(self, token_ids: List[int], **kwargs) -> str: """ Timestamp tokens are above other special tokens' id range and are ignored by `decode()`. This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>". """ return self.encoding.decode(token_ids, **kwargs)
@cached_property def eot(self) -> int: return self.encoding.eot_token
@cached_property def transcribe(self) -> int: return self.special_tokens["<|transcribe|>"]
@cached_property def translate(self) -> int: return self.special_tokens["<|translate|>"]
@cached_property def sot(self) -> int: return self.special_tokens["<|startoftranscript|>"]
@cached_property def sot_lm(self) -> int: return self.special_tokens["<|startoflm|>"]
@cached_property def sot_prev(self) -> int: return self.special_tokens["<|startofprev|>"]
@cached_property def no_speech(self) -> int: return self.special_tokens["<|nospeech|>"]
@cached_property def no_timestamps(self) -> int: return self.special_tokens["<|notimestamps|>"]
@cached_property def timestamp_begin(self) -> int: return self.special_tokens["<|0.00|>"]
@cached_property def language_token(self) -> int: """Returns the token id corresponding to the value of the `language` field""" if self.language is None: raise ValueError("This tokenizer does not have language token configured")
return self.to_language_token(self.language)
def to_language_token(self, language): if token := self.special_tokens.get(f"<|{language}|>", None): return token
raise KeyError(f"Language {language} not found in tokenizer.")
@cached_property def all_language_tokens(self) -> Tuple[int]: result = [] for token, token_id in self.special_tokens.items(): if token.strip("<|>") in LANGUAGES: result.append(token_id) return tuple(result)[: self.num_languages]
@cached_property def all_language_codes(self) -> Tuple[str]: return tuple(self.decode([_l]).strip("<|>") for _l in self.all_language_tokens)
@cached_property def sot_sequence_including_notimestamps(self) -> Tuple[int]: return tuple(list(self.sot_sequence) + [self.no_timestamps])
@cached_property def non_speech_tokens(self) -> Tuple[int]: """ Returns the list of tokens to suppress in order to avoid any speaker tags or non-speech annotations, to prevent sampling texts that are not actually spoken in the audio, e.g.
- ♪♪♪ - ( SPEAKING FOREIGN LANGUAGE ) - [DAVID] Hey there,
keeping basic punctuations like commas, periods, question marks, exclamation points, etc. """ symbols = list('"#()*+/:;<=>@[\\]^_`{|}~「」『』') symbols += ( "<< >> <<< >>> -- --- -( -[ (' (\" (( )) ((( ))) [[ ]] {{ }} ♪♪ ♪♪♪".split() )
# symbols that may be a single token or multiple tokens depending on the tokenizer. # In case they're multiple tokens, suppress the first token, which is safe because: # These are between U+2640 and U+267F miscellaneous symbols that are okay to suppress # in generations, and in the 3-byte UTF-8 representation they share the first two bytes. miscellaneous = set("♩♪♫♬♭♮♯") assert all(0x2640 <= ord(c) <= 0x267F for c in miscellaneous)
# allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word result = {self.encoding.encode(" -")[0], self.encoding.encode(" '")[0]} for symbol in symbols + list(miscellaneous): for tokens in [ self.encoding.encode(symbol), self.encoding.encode(" " + symbol), ]: if len(tokens) == 1 or symbol in miscellaneous: result.add(tokens[0])
return tuple(sorted(result))
def split_to_word_tokens(self, tokens: List[int]): if self.language in {"zh", "ja", "th", "lo", "my", "yue"}: # These languages don't typically use spaces, so it is difficult to split words # without morpheme analysis. Here, we instead split words at any # position where the tokens are decoded as valid unicode points return self.split_tokens_on_unicode(tokens)
return self.split_tokens_on_spaces(tokens)
def split_tokens_on_unicode(self, tokens: List[int]): decoded_full = self.decode_with_timestamps(tokens) replacement_char = "\ufffd"
words = [] word_tokens = [] current_tokens = [] unicode_offset = 0
for token in tokens: current_tokens.append(token) decoded = self.decode_with_timestamps(current_tokens)
if ( replacement_char not in decoded or decoded_full[unicode_offset + decoded.index(replacement_char)] == replacement_char ): words.append(decoded) word_tokens.append(current_tokens) current_tokens = [] unicode_offset += len(decoded)
return words, word_tokens
def split_tokens_on_spaces(self, tokens: List[int]): subwords, subword_tokens_list = self.split_tokens_on_unicode(tokens) words = [] word_tokens = []
for subword, subword_tokens in zip(subwords, subword_tokens_list): special = subword_tokens[0] >= self.eot with_space = subword.startswith(" ") punctuation = subword.strip() in string.punctuation if special or with_space or punctuation or len(words) == 0: words.append(subword) word_tokens.append(subword_tokens) else: words[-1] = words[-1] + subword word_tokens[-1].extend(subword_tokens)
return words, word_tokens
@lru_cache(maxsize=None)def get_encoding(name: str = "gpt2", num_languages: int = 99): vocab_path = os.path.join(os.path.dirname(__file__), "assets", f"{name}.tiktoken") ranks = { base64.b64decode(token): int(rank) for token, rank in (line.split() for line in open(vocab_path) if line) } n_vocab = len(ranks) special_tokens = {}
specials = [ "<|endoftext|>", "<|startoftranscript|>", *[f"<|{lang}|>" for lang in list(LANGUAGES.keys())[:num_languages]], "<|translate|>", "<|transcribe|>", "<|startoflm|>", "<|startofprev|>", "<|nospeech|>", "<|notimestamps|>", *[f"<|{i * 0.02:.2f}|>" for i in range(1501)], ]
for token in specials: special_tokens[token] = n_vocab n_vocab += 1
return tiktoken.Encoding( name=os.path.basename(vocab_path), explicit_n_vocab=n_vocab, pat_str=r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""", mergeable_ranks=ranks, special_tokens=special_tokens, )
@lru_cache(maxsize=None)def get_tokenizer( multilingual: bool, *, num_languages: int = 99, language: Optional[str] = None, task: Optional[str] = None, # Literal["transcribe", "translate", None]) -> Tokenizer: if language is not None: language = language.lower() if language not in LANGUAGES: if language in TO_LANGUAGE_CODE: language = TO_LANGUAGE_CODE[language] else: raise ValueError(f"Unsupported language: {language}")
if multilingual: encoding_name = "multilingual" language = language or "en" task = task or "transcribe" else: encoding_name = "gpt2" language = None task = None
encoding = get_encoding(name=encoding_name, num_languages=num_languages)
return Tokenizer( encoding=encoding, num_languages=num_languages, language=language, task=task )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486import argparseimport osimport tracebackimport warningsfrom typing import TYPE_CHECKING, Optional, Tuple, Union
import numpy as npimport torchimport tqdm
from .audio import ( FRAMES_PER_SECOND, HOP_LENGTH, N_FRAMES, N_SAMPLES, SAMPLE_RATE, log_mel_spectrogram, pad_or_trim,)from .decoding import DecodingOptions, DecodingResultfrom .timing import add_word_timestampsfrom .tokenizer import LANGUAGES, TO_LANGUAGE_CODE, get_tokenizerfrom .utils import ( exact_div, format_timestamp, get_writer, make_safe, optional_float, optional_int, str2bool,)
if TYPE_CHECKING: from .model import Whisper
def transcribe( model: "Whisper", audio: Union[str, np.ndarray, torch.Tensor], *, verbose: Optional[bool] = None, temperature: Union[float, Tuple[float, ...]] = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0), compression_ratio_threshold: Optional[float] = 2.4, logprob_threshold: Optional[float] = -1.0, no_speech_threshold: Optional[float] = 0.6, condition_on_previous_text: bool = True, initial_prompt: Optional[str] = None, word_timestamps: bool = False, prepend_punctuations: str = "\"'“¿([{-", append_punctuations: str = "\"'.。,,!!??::”)]}、", **decode_options,): """ Transcribe an audio file using Whisper
Parameters ---------- model: Whisper The Whisper model instance
audio: Union[str, np.ndarray, torch.Tensor] The path to the audio file to open, or the audio waveform
verbose: bool Whether to display the text being decoded to the console. If True, displays all the details, If False, displays minimal details. If None, does not display anything
temperature: Union[float, Tuple[float, ...]] Temperature for sampling. It can be a tuple of temperatures, which will be successively used upon failures according to either `compression_ratio_threshold` or `logprob_threshold`.
compression_ratio_threshold: float If the gzip compression ratio is above this value, treat as failed
logprob_threshold: float If the average log probability over sampled tokens is below this value, treat as failed
no_speech_threshold: float If the no_speech probability is higher than this value AND the average log probability over sampled tokens is below `logprob_threshold`, consider the segment as silent
condition_on_previous_text: bool if True, the previous output of the model is provided as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop, such as repetition looping or timestamps going out of sync.
word_timestamps: bool Extract word-level timestamps using the cross-attention pattern and dynamic time warping, and include the timestamps for each word in each segment.
prepend_punctuations: str If word_timestamps is True, merge these punctuation symbols with the next word
append_punctuations: str If word_timestamps is True, merge these punctuation symbols with the previous word
initial_prompt: Optional[str] Optional text to provide as a prompt for the first window. This can be used to provide, or "prompt-engineer" a context for transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those word correctly.
decode_options: dict Keyword arguments to construct `DecodingOptions` instances
Returns ------- A dictionary containing the resulting text ("text") and segment-level details ("segments"), and the spoken language ("language"), which is detected when `decode_options["language"]` is None. """ dtype = torch.float16 if decode_options.get("fp16", True) else torch.float32 if model.device == torch.device("cpu"): if torch.cuda.is_available(): warnings.warn("Performing inference on CPU when CUDA is available") if dtype == torch.float16: warnings.warn("FP16 is not supported on CPU; using FP32 instead") dtype = torch.float32
if dtype == torch.float32: decode_options["fp16"] = False
# Pad 30-seconds of silence to the input audio, for slicing mel = log_mel_spectrogram(audio, model.dims.n_mels, padding=N_SAMPLES) content_frames = mel.shape[-1] - N_FRAMES
if decode_options.get("language", None) is None: if not model.is_multilingual: decode_options["language"] = "en" else: if verbose: print( "Detecting language using up to the first 30 seconds. Use `--language` to specify the language" ) mel_segment = pad_or_trim(mel, N_FRAMES).to(model.device).to(dtype) _, probs = model.detect_language(mel_segment) decode_options["language"] = max(probs, key=probs.get) if verbose is not None: print( f"Detected language: {LANGUAGES[decode_options['language']].title()}" )
language: str = decode_options["language"] task: str = decode_options.get("task", "transcribe") tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages, language=language, task=task, )
if word_timestamps and task == "translate": warnings.warn("Word-level timestamps on translations may not be reliable.")
def decode_with_fallback(segment: torch.Tensor) -> DecodingResult: temperatures = ( [temperature] if isinstance(temperature, (int, float)) else temperature ) decode_result = None
for t in temperatures: kwargs = {**decode_options} if t > 0: # disable beam_size and patience when t > 0 kwargs.pop("beam_size", None) kwargs.pop("patience", None) else: # disable best_of when t == 0 kwargs.pop("best_of", None)
options = DecodingOptions(**kwargs, temperature=t) decode_result = model.decode(segment, options)
needs_fallback = False if ( compression_ratio_threshold is not None and decode_result.compression_ratio > compression_ratio_threshold ): needs_fallback = True # too repetitive if ( logprob_threshold is not None and decode_result.avg_logprob < logprob_threshold ): needs_fallback = True # average log probability is too low if ( no_speech_threshold is not None and decode_result.no_speech_prob > no_speech_threshold ): needs_fallback = False # silence if not needs_fallback: break
return decode_result
seek = 0 input_stride = exact_div( N_FRAMES, model.dims.n_audio_ctx ) # mel frames per output token: 2 time_precision = ( input_stride * HOP_LENGTH / SAMPLE_RATE ) # time per output token: 0.02 (seconds) all_tokens = [] all_segments = [] prompt_reset_since = 0
if initial_prompt is not None: initial_prompt_tokens = tokenizer.encode(" " + initial_prompt.strip()) all_tokens.extend(initial_prompt_tokens) else: initial_prompt_tokens = []
def new_segment( *, start: float, end: float, tokens: torch.Tensor, result: DecodingResult ): tokens = tokens.tolist() text_tokens = [token for token in tokens if token < tokenizer.eot] return { "seek": seek, "start": start, "end": end, "text": tokenizer.decode(text_tokens), "tokens": tokens, "temperature": result.temperature, "avg_logprob": result.avg_logprob, "compression_ratio": result.compression_ratio, "no_speech_prob": result.no_speech_prob, }
# show the progress bar when verbose is False (if True, transcribed text will be printed) with tqdm.tqdm( total=content_frames, unit="frames", disable=verbose is not False ) as pbar: last_speech_timestamp = 0.0 while seek < content_frames: time_offset = float(seek * HOP_LENGTH / SAMPLE_RATE) mel_segment = mel[:, seek : seek + N_FRAMES] segment_size = min(N_FRAMES, content_frames - seek) segment_duration = segment_size * HOP_LENGTH / SAMPLE_RATE mel_segment = pad_or_trim(mel_segment, N_FRAMES).to(model.device).to(dtype)
decode_options["prompt"] = all_tokens[prompt_reset_since:] result: DecodingResult = decode_with_fallback(mel_segment) tokens = torch.tensor(result.tokens)
if no_speech_threshold is not None: # no voice activity check should_skip = result.no_speech_prob > no_speech_threshold if ( logprob_threshold is not None and result.avg_logprob > logprob_threshold ): # don't skip if the logprob is high enough, despite the no_speech_prob should_skip = False
if should_skip: seek += segment_size # fast-forward to the next segment boundary continue
previous_seek = seek current_segments = []
timestamp_tokens: torch.Tensor = tokens.ge(tokenizer.timestamp_begin) single_timestamp_ending = timestamp_tokens[-2:].tolist() == [False, True]
consecutive = torch.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0] consecutive.add_(1) if len(consecutive) > 0: # if the output contains two consecutive timestamp tokens slices = consecutive.tolist() if single_timestamp_ending: slices.append(len(tokens))
last_slice = 0 for current_slice in slices: sliced_tokens = tokens[last_slice:current_slice] start_timestamp_pos = ( sliced_tokens[0].item() - tokenizer.timestamp_begin ) end_timestamp_pos = ( sliced_tokens[-1].item() - tokenizer.timestamp_begin ) current_segments.append( new_segment( start=time_offset + start_timestamp_pos * time_precision, end=time_offset + end_timestamp_pos * time_precision, tokens=sliced_tokens, result=result, ) ) last_slice = current_slice
if single_timestamp_ending: # single timestamp at the end means no speech after the last timestamp. seek += segment_size else: # otherwise, ignore the unfinished segment and seek to the last timestamp last_timestamp_pos = ( tokens[last_slice - 1].item() - tokenizer.timestamp_begin ) seek += last_timestamp_pos * input_stride else: duration = segment_duration timestamps = tokens[timestamp_tokens.nonzero().flatten()] if ( len(timestamps) > 0 and timestamps[-1].item() != tokenizer.timestamp_begin ): # no consecutive timestamps but it has a timestamp; use the last one. last_timestamp_pos = ( timestamps[-1].item() - tokenizer.timestamp_begin ) duration = last_timestamp_pos * time_precision
current_segments.append( new_segment( start=time_offset, end=time_offset + duration, tokens=tokens, result=result, ) ) seek += segment_size
if word_timestamps: add_word_timestamps( segments=current_segments, model=model, tokenizer=tokenizer, mel=mel_segment, num_frames=segment_size, prepend_punctuations=prepend_punctuations, append_punctuations=append_punctuations, last_speech_timestamp=last_speech_timestamp, ) word_end_timestamps = [ w["end"] for s in current_segments for w in s["words"] ] if len(word_end_timestamps) > 0: last_speech_timestamp = word_end_timestamps[-1] if not single_timestamp_ending and len(word_end_timestamps) > 0: seek_shift = round( (word_end_timestamps[-1] - time_offset) * FRAMES_PER_SECOND ) if seek_shift > 0: seek = previous_seek + seek_shift
if verbose: for segment in current_segments: start, end, text = segment["start"], segment["end"], segment["text"] line = f"[{format_timestamp(start)} --> {format_timestamp(end)}] {text}" print(make_safe(line))
# if a segment is instantaneous or does not contain text, clear it for i, segment in enumerate(current_segments): if segment["start"] == segment["end"] or segment["text"].strip() == "": segment["text"] = "" segment["tokens"] = [] segment["words"] = []
all_segments.extend( [ {"id": i, **segment} for i, segment in enumerate( current_segments, start=len(all_segments) ) ] ) all_tokens.extend( [token for segment in current_segments for token in segment["tokens"]] )
if not condition_on_previous_text or result.temperature > 0.5: # do not feed the prompt tokens if a high temperature was used prompt_reset_since = len(all_tokens)
# update progress bar pbar.update(min(content_frames, seek) - previous_seek)
return dict( text=tokenizer.decode(all_tokens[len(initial_prompt_tokens) :]), segments=all_segments, language=language, )
def cli(): from . import available_models
def valid_model_name(name): if name in available_models() or os.path.exists(name): return name raise ValueError( f"model should be one of {available_models()} or path to a model checkpoint" )
# fmt: off parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("audio", nargs="+", type=str, help="audio file(s) to transcribe") parser.add_argument("--model", default="small", type=valid_model_name, help="name of the Whisper model to use") parser.add_argument("--model_dir", type=str, default=None, help="the path to save model files; uses ~/.cache/whisper by default") parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu", help="device to use for PyTorch inference") parser.add_argument("--output_dir", "-o", type=str, default=".", help="directory to save the outputs") parser.add_argument("--output_format", "-f", type=str, default="all", choices=["txt", "vtt", "srt", "tsv", "json", "all"], help="format of the output file; if not specified, all available formats will be produced") parser.add_argument("--verbose", type=str2bool, default=True, help="whether to print out the progress and debug messages")
parser.add_argument("--task", type=str, default="transcribe", choices=["transcribe", "translate"], help="whether to perform X->X speech recognition ('transcribe') or X->English translation ('translate')") parser.add_argument("--language", type=str, default=None, choices=sorted(LANGUAGES.keys()) + sorted([k.title() for k in TO_LANGUAGE_CODE.keys()]), help="language spoken in the audio, specify None to perform language detection")
parser.add_argument("--temperature", type=float, default=0, help="temperature to use for sampling") parser.add_argument("--best_of", type=optional_int, default=5, help="number of candidates when sampling with non-zero temperature") parser.add_argument("--beam_size", type=optional_int, default=5, help="number of beams in beam search, only applicable when temperature is zero") parser.add_argument("--patience", type=float, default=None, help="optional patience value to use in beam decoding, as in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search") parser.add_argument("--length_penalty", type=float, default=None, help="optional token length penalty coefficient (alpha) as in https://arxiv.org/abs/1609.08144, uses simple length normalization by default")
parser.add_argument("--suppress_tokens", type=str, default="-1", help="comma-separated list of token ids to suppress during sampling; '-1' will suppress most special characters except common punctuations") parser.add_argument("--initial_prompt", type=str, default=None, help="optional text to provide as a prompt for the first window.") parser.add_argument("--condition_on_previous_text", type=str2bool, default=True, help="if True, provide the previous output of the model as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop") parser.add_argument("--fp16", type=str2bool, default=True, help="whether to perform inference in fp16; True by default")
parser.add_argument("--temperature_increment_on_fallback", type=optional_float, default=0.2, help="temperature to increase when falling back when the decoding fails to meet either of the thresholds below") parser.add_argument("--compression_ratio_threshold", type=optional_float, default=2.4, help="if the gzip compression ratio is higher than this value, treat the decoding as failed") parser.add_argument("--logprob_threshold", type=optional_float, default=-1.0, help="if the average log probability is lower than this value, treat the decoding as failed") parser.add_argument("--no_speech_threshold", type=optional_float, default=0.6, help="if the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence") parser.add_argument("--word_timestamps", type=str2bool, default=False, help="(experimental) extract word-level timestamps and refine the results based on them") parser.add_argument("--prepend_punctuations", type=str, default="\"\'“¿([{-", help="if word_timestamps is True, merge these punctuation symbols with the next word") parser.add_argument("--append_punctuations", type=str, default="\"\'.。,,!!??::”)]}、", help="if word_timestamps is True, merge these punctuation symbols with the previous word") parser.add_argument("--highlight_words", type=str2bool, default=False, help="(requires --word_timestamps True) underline each word as it is spoken in srt and vtt") parser.add_argument("--max_line_width", type=optional_int, default=None, help="(requires --word_timestamps True) the maximum number of characters in a line before breaking the line") parser.add_argument("--max_line_count", type=optional_int, default=None, help="(requires --word_timestamps True) the maximum number of lines in a segment") parser.add_argument("--max_words_per_line", type=optional_int, default=None, help="(requires --word_timestamps True, no effect with --max_line_width) the maximum number of words in a segment") parser.add_argument("--threads", type=optional_int, default=0, help="number of threads used by torch for CPU inference; supercedes MKL_NUM_THREADS/OMP_NUM_THREADS") # fmt: on
args = parser.parse_args().__dict__ model_name: str = args.pop("model") model_dir: str = args.pop("model_dir") output_dir: str = args.pop("output_dir") output_format: str = args.pop("output_format") device: str = args.pop("device") os.makedirs(output_dir, exist_ok=True)
if model_name.endswith(".en") and args["language"] not in {"en", "English"}: if args["language"] is not None: warnings.warn( f"{model_name} is an English-only model but receipted '{args['language']}'; using English instead." ) args["language"] = "en"
temperature = args.pop("temperature") if (increment := args.pop("temperature_increment_on_fallback")) is not None: temperature = tuple(np.arange(temperature, 1.0 + 1e-6, increment)) else: temperature = [temperature]
if (threads := args.pop("threads")) > 0: torch.set_num_threads(threads)
from . import load_model
model = load_model(model_name, device=device, download_root=model_dir)
writer = get_writer(output_format, output_dir) word_options = [ "highlight_words", "max_line_count", "max_line_width", "max_words_per_line", ] if not args["word_timestamps"]: for option in word_options: if args[option]: parser.error(f"--{option} requires --word_timestamps True") if args["max_line_count"] and not args["max_line_width"]: warnings.warn("--max_line_count has no effect without --max_line_width") if args["max_words_per_line"] and args["max_line_width"]: warnings.warn("--max_words_per_line has no effect with --max_line_width") writer_args = {arg: args.pop(arg) for arg in word_options} for audio_path in args.pop("audio"): try: result = transcribe(model, audio_path, temperature=temperature, **args) writer(result, audio_path, **writer_args) except Exception as e: traceback.print_exc() print(f"Skipping {audio_path} due to {type(e).__name__}: {str(e)}")
if __name__ == "__main__": cli()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302import jsonimport osimport reimport sysimport zlibfrom typing import Callable, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string): # replaces any character not representable using the system default encoding with an '?', # avoiding UnicodeEncodeError (https://github.com/openai/whisper/discussions/729). return string.encode(system_encoding, errors="replace").decode(system_encoding)
else:
def make_safe(string): # utf-8 can encode any Unicode code point, so no need to do the round-trip encoding return string
def exact_div(x, y): assert x % y == 0 return x // y
def str2bool(string): str2val = {"True": True, "False": False} if string in str2val: return str2val[string] else: raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}")
def optional_int(string): return None if string == "None" else int(string)
def optional_float(string): return None if string == "None" else float(string)
def compression_ratio(text) -> float: text_bytes = text.encode("utf-8") return len(text_bytes) / len(zlib.compress(text_bytes))
def format_timestamp( seconds: float, always_include_hours: bool = False, decimal_marker: str = "."): assert seconds >= 0, "non-negative timestamp expected" milliseconds = round(seconds * 1000.0)
hours = milliseconds // 3_600_000 milliseconds -= hours * 3_600_000
minutes = milliseconds // 60_000 milliseconds -= minutes * 60_000
seconds = milliseconds // 1_000 milliseconds -= seconds * 1_000
hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else "" return ( f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}" )
class ResultWriter: extension: str
def __init__(self, output_dir: str): self.output_dir = output_dir
def __call__( self, result: dict, audio_path: str, options: Optional[dict] = None, **kwargs ): audio_basename = os.path.basename(audio_path) audio_basename = os.path.splitext(audio_basename)[0] output_path = os.path.join( self.output_dir, audio_basename + "." + self.extension )
with open(output_path, "w", encoding="utf-8") as f: self.write_result(result, file=f, options=options, **kwargs)
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): raise NotImplementedError
class WriteTXT(ResultWriter): extension: str = "txt"
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): for segment in result["segments"]: print(segment["text"].strip(), file=file, flush=True)
class SubtitlesWriter(ResultWriter): always_include_hours: bool decimal_marker: str
def iterate_result( self, result: dict, options: Optional[dict] = None, *, max_line_width: Optional[int] = None, max_line_count: Optional[int] = None, highlight_words: bool = False, max_words_per_line: Optional[int] = None, ): options = options or {} max_line_width = max_line_width or options.get("max_line_width") max_line_count = max_line_count or options.get("max_line_count") highlight_words = highlight_words or options.get("highlight_words", False) max_words_per_line = max_words_per_line or options.get("max_words_per_line") preserve_segments = max_line_count is None or max_line_width is None max_line_width = max_line_width or 1000 max_words_per_line = max_words_per_line or 1000
def iterate_subtitles(): line_len = 0 line_count = 1 # the next subtitle to yield (a list of word timings with whitespace) subtitle: list[dict] = [] last = result["segments"][0]["words"][0]["start"] for segment in result["segments"]: chunk_index = 0 words_count = max_words_per_line while chunk_index < len(segment["words"]): remaining_words = len(segment["words"]) - chunk_index if max_words_per_line > len(segment["words"]) - chunk_index: words_count = remaining_words for i, original_timing in enumerate( segment["words"][chunk_index : chunk_index + words_count] ): timing = original_timing.copy() long_pause = ( not preserve_segments and timing["start"] - last > 3.0 ) has_room = line_len + len(timing["word"]) <= max_line_width seg_break = i == 0 and len(subtitle) > 0 and preserve_segments if ( line_len > 0 and has_room and not long_pause and not seg_break ): # line continuation line_len += len(timing["word"]) else: # new line timing["word"] = timing["word"].strip() if ( len(subtitle) > 0 and max_line_count is not None and (long_pause or line_count >= max_line_count) or seg_break ): # subtitle break yield subtitle subtitle = [] line_count = 1 elif line_len > 0: # line break line_count += 1 timing["word"] = "\n" + timing["word"] line_len = len(timing["word"].strip()) subtitle.append(timing) last = timing["start"] chunk_index += max_words_per_line if len(subtitle) > 0: yield subtitle
if len(result["segments"]) > 0 and "words" in result["segments"][0]: for subtitle in iterate_subtitles(): subtitle_start = self.format_timestamp(subtitle[0]["start"]) subtitle_end = self.format_timestamp(subtitle[-1]["end"]) subtitle_text = "".join([word["word"] for word in subtitle]) if highlight_words: last = subtitle_start all_words = [timing["word"] for timing in subtitle] for i, this_word in enumerate(subtitle): start = self.format_timestamp(this_word["start"]) end = self.format_timestamp(this_word["end"]) if last != start: yield last, start, subtitle_text
yield start, end, "".join( [ re.sub(r"^(\s*)(.*)$", r"\1<u>\2</u>", word) if j == i else word for j, word in enumerate(all_words) ] ) last = end else: yield subtitle_start, subtitle_end, subtitle_text else: for segment in result["segments"]: segment_start = self.format_timestamp(segment["start"]) segment_end = self.format_timestamp(segment["end"]) segment_text = segment["text"].strip().replace("-->", "->") yield segment_start, segment_end, segment_text
def format_timestamp(self, seconds: float): return format_timestamp( seconds=seconds, always_include_hours=self.always_include_hours, decimal_marker=self.decimal_marker, )
class WriteVTT(SubtitlesWriter): extension: str = "vtt" always_include_hours: bool = False decimal_marker: str = "."
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): print("WEBVTT\n", file=file) for start, end, text in self.iterate_result(result, options, **kwargs): print(f"{start} --> {end}\n{text}\n", file=file, flush=True)
class WriteSRT(SubtitlesWriter): extension: str = "srt" always_include_hours: bool = True decimal_marker: str = ","
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): for i, (start, end, text) in enumerate( self.iterate_result(result, options, **kwargs), start=1 ): print(f"{i}\n{start} --> {end}\n{text}\n", file=file, flush=True)
class WriteTSV(ResultWriter): """ Write a transcript to a file in TSV (tab-separated values) format containing lines like: <start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text>
Using integer milliseconds as start and end times means there's no chance of interference from an environment setting a language encoding that causes the decimal in a floating point number to appear as a comma; also is faster and more efficient to parse & store, e.g., in C++. """
extension: str = "tsv"
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): print("start", "end", "text", sep="\t", file=file) for segment in result["segments"]: print(round(1000 * segment["start"]), file=file, end="\t") print(round(1000 * segment["end"]), file=file, end="\t") print(segment["text"].strip().replace("\t", " "), file=file, flush=True)
class WriteJSON(ResultWriter): extension: str = "json"
def write_result( self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): json.dump(result, file)
def get_writer( output_format: str, output_dir: str) -> Callable[[dict, TextIO, dict], None]: writers = { "txt": WriteTXT, "vtt": WriteVTT, "srt": WriteSRT, "tsv": WriteTSV, "json": WriteJSON, }
if output_format == "all": all_writers = [writer(output_dir) for writer in writers.values()]
def write_all( result: dict, file: TextIO, options: Optional[dict] = None, **kwargs ): for writer in all_writers: writer(result, file, options, **kwargs)
return write_all
return writers[output_format](output_dir)third_party/Matcha-TTS/matcha/models/components/decoder.pyAdded+443
third_party/Matcha-TTS/matcha/models/components/text_encoder.pyAdded+410
third_party/Matcha-TTS/matcha/models/components/transformer.pyAdded+316
third_party/Matcha-TTS/matcha/models/matcha_tts.pyAdded+245
whisper/assets/gpt2.tiktokenAdded
whisper/assets/multilingual.tiktokenAdded
whisper/decoding.pyAdded+826
whisper/model.pyAdded+314
whisper/normalizers/english.jsonAdded+1741
whisper/normalizers/english.pyAdded+550
whisper/timing.pyAdded+385
whisper/tokenizer.pyAdded+395
whisper/transcribe.pyAdded+486
whisper/utils.pyAdded+302