Wataru commited on
Commit
7410e2f
1 Parent(s): 7b5f5d6

initial commit

Browse files
Files changed (9) hide show
  1. .gitattributes +2 -0
  2. .gitignore +3 -0
  3. LICENSE +7 -0
  4. demo.py +56 -0
  5. epoch=3-step=7459.ckpt +3 -0
  6. lightning_module.py +41 -0
  7. model.py +191 -0
  8. requirements.txt +94 -0
  9. wav2vec_small.pt +3 -0
.gitattributes CHANGED
@@ -25,3 +25,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ epoch=3-step=7459.ckpt filter=lfs diff=lfs merge=lfs -text
29
+ wav2vec_small.pt filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ demo/
2
+ __pycache__/
3
+ flagged/
LICENSE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
1
+ Copyright 2022 sarulab-speech
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
demo.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from random import sample
3
+ import gradio as gr
4
+ import torchaudio
5
+ import torch
6
+ import torch.nn as nn
7
+ import lightning_module
8
+
9
+ class ChangeSampleRate(nn.Module):
10
+ def __init__(self, input_rate: int, output_rate: int):
11
+ super().__init__()
12
+ self.output_rate = output_rate
13
+ self.input_rate = input_rate
14
+
15
+ def forward(self, wav: torch.tensor) -> torch.tensor:
16
+ # Only accepts 1-channel waveform input
17
+ wav = wav.view(wav.size(0), -1)
18
+ new_length = wav.size(-1) * self.output_rate // self.input_rate
19
+ indices = (torch.arange(new_length) * (self.input_rate / self.output_rate))
20
+ round_down = wav[:, indices.long()]
21
+ round_up = wav[:, (indices.long() + 1).clamp(max=wav.size(-1) - 1)]
22
+ output = round_down * (1. - indices.fmod(1.)).unsqueeze(0) + round_up * indices.fmod(1.).unsqueeze(0)
23
+ return output
24
+
25
+ model = lightning_module.BaselineLightningModule.load_from_checkpoint("epoch=3-step=7459.ckpt")
26
+ def calc_mos(audio_path):
27
+ wav, sr = torchaudio.load(audio_path)
28
+ osr = 16_000
29
+ batch = wav.unsqueeze(0).repeat(10, 1, 1)
30
+ csr = ChangeSampleRate(sr, osr)
31
+ out_wavs = csr(wav)
32
+ batch = {
33
+ 'wav': out_wavs,
34
+ 'domains': torch.tensor([0]),
35
+ 'judge_id': torch.tensor([288])
36
+ }
37
+ output = model(batch)
38
+ return output.mean(dim=1).squeeze().detach().numpy()*2 + 3
39
+
40
+
41
+ description ="""
42
+ This model is trained on BVCC dataset.
43
+ """
44
+
45
+ iface = gr.Interface(
46
+ fn=calc_mos,
47
+ inputs=gr.inputs.Audio(type='filepath'),
48
+ outputs="text",
49
+ title="UTMOS demo page",
50
+ description=description,
51
+ allow_flagging=False,
52
+
53
+ ).launch(
54
+ auth=("test", "sarulab-test"),
55
+ share=True
56
+ )
epoch=3-step=7459.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44c57e3e4135a243b43d2c82b6a693fcd56f15f9ad0e1eb2a8b31fdecd3a49b8
3
+ size 1238128841
lightning_module.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytorch_lightning as pl
2
+ import torch
3
+ import torch.nn as nn
4
+ import os
5
+ import numpy as np
6
+ import hydra
7
+ from model import load_ssl_model, PhonemeEncoder, DomainEmbedding, LDConditioner, Projection
8
+
9
+
10
+ class BaselineLightningModule(pl.LightningModule):
11
+ def __init__(self, cfg):
12
+ super().__init__()
13
+ self.cfg = cfg
14
+ self.construct_model()
15
+ self.save_hyperparameters()
16
+
17
+ def construct_model(self):
18
+ self.feature_extractors = nn.ModuleList([
19
+ load_ssl_model(cp_path='wav2vec_small.pt'),
20
+ DomainEmbedding(3,128),
21
+ ])
22
+ output_dim = sum([ feature_extractor.get_output_dim() for feature_extractor in self.feature_extractors])
23
+ output_layers = [
24
+ LDConditioner(judge_dim=128,num_judges=3000,input_dim=output_dim)
25
+ ]
26
+ output_dim = output_layers[-1].get_output_dim()
27
+ output_layers.append(
28
+ Projection(hidden_dim=2048,activation=torch.nn.ReLU(),range_clipping=False,input_dim=output_dim)
29
+
30
+ )
31
+
32
+ self.output_layers = nn.ModuleList(output_layers)
33
+
34
+ def forward(self, inputs):
35
+ outputs = {}
36
+ for feature_extractor in self.feature_extractors:
37
+ outputs.update(feature_extractor(inputs))
38
+ x = outputs
39
+ for output_layer in self.output_layers:
40
+ x = output_layer(x,inputs)
41
+ return x
model.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import fairseq
4
+ import os
5
+ import hydra
6
+
7
+ def load_ssl_model(cp_path):
8
+ ssl_model_type = cp_path.split("/")[-1]
9
+ wavlm = "WavLM" in ssl_model_type
10
+ if wavlm:
11
+ checkpoint = torch.load(cp_path)
12
+ cfg = WavLMConfig(checkpoint['cfg'])
13
+ ssl_model = WavLM(cfg)
14
+ ssl_model.load_state_dict(checkpoint['model'])
15
+ if 'Large' in ssl_model_type:
16
+ SSL_OUT_DIM = 1024
17
+ else:
18
+ SSL_OUT_DIM = 768
19
+ else:
20
+ if ssl_model_type == "wav2vec_small.pt":
21
+ SSL_OUT_DIM = 768
22
+ elif ssl_model_type in ["w2v_large_lv_fsh_swbd_cv.pt", "xlsr_53_56k.pt"]:
23
+ SSL_OUT_DIM = 1024
24
+ else:
25
+ print("*** ERROR *** SSL model type " + ssl_model_type + " not supported.")
26
+ exit()
27
+ model, cfg, task = fairseq.checkpoint_utils.load_model_ensemble_and_task(
28
+ [cp_path]
29
+ )
30
+ ssl_model = model[0]
31
+ ssl_model.remove_pretraining_modules()
32
+ return SSL_model(ssl_model, SSL_OUT_DIM, wavlm)
33
+
34
+ class SSL_model(nn.Module):
35
+ def __init__(self,ssl_model,ssl_out_dim,wavlm) -> None:
36
+ super(SSL_model,self).__init__()
37
+ self.ssl_model, self.ssl_out_dim = ssl_model, ssl_out_dim
38
+ self.WavLM = wavlm
39
+
40
+ def forward(self,batch):
41
+ wav = batch['wav']
42
+ wav = wav.squeeze(1) # [batches, audio_len]
43
+ if self.WavLM:
44
+ x = self.ssl_model.extract_features(wav)[0]
45
+ else:
46
+ res = self.ssl_model(wav, mask=False, features_only=True)
47
+ x = res["x"]
48
+ return {"ssl-feature":x}
49
+ def get_output_dim(self):
50
+ return self.ssl_out_dim
51
+
52
+
53
+ class PhonemeEncoder(nn.Module):
54
+ '''
55
+ PhonemeEncoder consists of an embedding layer, an LSTM layer, and a linear layer.
56
+ Args:
57
+ vocab_size: the size of the vocabulary
58
+ hidden_dim: the size of the hidden state of the LSTM
59
+ emb_dim: the size of the embedding layer
60
+ out_dim: the size of the output of the linear layer
61
+ n_lstm_layers: the number of LSTM layers
62
+ '''
63
+ def __init__(self, vocab_size, hidden_dim, emb_dim, out_dim,n_lstm_layers,with_reference=True) -> None:
64
+ super().__init__()
65
+ self.with_reference = with_reference
66
+ self.embedding = nn.Embedding(vocab_size, emb_dim)
67
+ self.encoder = nn.LSTM(emb_dim, hidden_dim,
68
+ num_layers=n_lstm_layers, dropout=0.1, bidirectional=True)
69
+ self.linear = nn.Sequential(
70
+ nn.Linear(hidden_dim + hidden_dim*self.with_reference, out_dim),
71
+ nn.ReLU()
72
+ )
73
+ self.out_dim = out_dim
74
+
75
+ def forward(self,batch):
76
+ seq = batch['phonemes']
77
+ lens = batch['phoneme_lens']
78
+ reference_seq = batch['reference']
79
+ reference_lens = batch['reference_lens']
80
+ emb = self.embedding(seq)
81
+ emb = torch.nn.utils.rnn.pack_padded_sequence(
82
+ emb, lens, batch_first=True, enforce_sorted=False)
83
+ _, (ht, _) = self.encoder(emb)
84
+ feature = ht[-1] + ht[0]
85
+ if self.with_reference:
86
+ if reference_seq==None or reference_lens ==None:
87
+ raise ValueError("reference_batch and reference_lens should not be None when with_reference is True")
88
+ reference_emb = self.embedding(reference_seq)
89
+ reference_emb = torch.nn.utils.rnn.pack_padded_sequence(
90
+ reference_emb, reference_lens, batch_first=True, enforce_sorted=False)
91
+ _, (ht_ref, _) = self.encoder(emb)
92
+ reference_feature = ht_ref[-1] + ht_ref[0]
93
+ feature = self.linear(torch.cat([feature,reference_feature],1))
94
+ else:
95
+ feature = self.linear(feature)
96
+ return {"phoneme-feature": feature}
97
+ def get_output_dim(self):
98
+ return self.out_dim
99
+
100
+ class DomainEmbedding(nn.Module):
101
+ def __init__(self,n_domains,domain_dim) -> None:
102
+ super().__init__()
103
+ self.embedding = nn.Embedding(n_domains,domain_dim)
104
+ self.output_dim = domain_dim
105
+ def forward(self, batch):
106
+ return {"domain-feature": self.embedding(batch['domains'])}
107
+ def get_output_dim(self):
108
+ return self.output_dim
109
+
110
+
111
+ class LDConditioner(nn.Module):
112
+ '''
113
+ Conditions ssl output by listener embedding
114
+ '''
115
+ def __init__(self,input_dim, judge_dim, num_judges=None):
116
+ super().__init__()
117
+ self.input_dim = input_dim
118
+ self.judge_dim = judge_dim
119
+ self.num_judges = num_judges
120
+ assert num_judges !=None
121
+ self.judge_embedding = nn.Embedding(num_judges, self.judge_dim)
122
+ # concat [self.output_layer, phoneme features]
123
+
124
+ self.decoder_rnn = nn.LSTM(
125
+ input_size = self.input_dim + self.judge_dim,
126
+ hidden_size = 512,
127
+ num_layers = 1,
128
+ batch_first = True,
129
+ bidirectional = True
130
+ ) # linear?
131
+ self.out_dim = self.decoder_rnn.hidden_size*2
132
+
133
+ def get_output_dim(self):
134
+ return self.out_dim
135
+
136
+
137
+ def forward(self, x, batch):
138
+ judge_ids = batch['judge_id']
139
+ if 'phoneme-feature' in x.keys():
140
+ concatenated_feature = torch.cat((x['ssl-feature'], x['phoneme-feature'].unsqueeze(1).expand(-1,x['ssl-feature'].size(1) ,-1)),dim=2)
141
+ else:
142
+ concatenated_feature = x['ssl-feature']
143
+ if 'domain-feature' in x.keys():
144
+ concatenated_feature = torch.cat(
145
+ (
146
+ concatenated_feature,
147
+ x['domain-feature']
148
+ .unsqueeze(1)
149
+ .expand(-1, concatenated_feature.size(1), -1),
150
+ ),
151
+ dim=2,
152
+ )
153
+ if judge_ids != None:
154
+ concatenated_feature = torch.cat(
155
+ (
156
+ concatenated_feature,
157
+ self.judge_embedding(judge_ids)
158
+ .unsqueeze(1)
159
+ .expand(-1, concatenated_feature.size(1), -1),
160
+ ),
161
+ dim=2,
162
+ )
163
+ decoder_output, (h, c) = self.decoder_rnn(concatenated_feature)
164
+ return decoder_output
165
+
166
+ class Projection(nn.Module):
167
+ def __init__(self, input_dim, hidden_dim, activation, range_clipping=False):
168
+ super(Projection, self).__init__()
169
+ self.range_clipping = range_clipping
170
+ output_dim = 1
171
+ if range_clipping:
172
+ self.proj = nn.Tanh()
173
+
174
+ self.net = nn.Sequential(
175
+ nn.Linear(input_dim, hidden_dim),
176
+ activation,
177
+ nn.Dropout(0.3),
178
+ nn.Linear(hidden_dim, output_dim),
179
+ )
180
+ self.output_dim = output_dim
181
+
182
+ def forward(self, x, batch):
183
+ output = self.net(x)
184
+
185
+ # range clipping
186
+ if self.range_clipping:
187
+ return self.proj(output) * 2.0 + 3
188
+ else:
189
+ return output
190
+ def get_output_dim(self):
191
+ return self.output_dim
requirements.txt ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==1.0.0
2
+ aiohttp==3.8.1
3
+ aiosignal==1.2.0
4
+ analytics-python==1.4.0
5
+ antlr4-python3-runtime==4.8
6
+ anyio==3.5.0
7
+ asgiref==3.5.0
8
+ async-timeout==4.0.2
9
+ attrs==21.4.0
10
+ backoff==1.10.0
11
+ bcrypt==3.2.0
12
+ bitarray==2.4.0
13
+ cachetools==5.0.0
14
+ certifi==2021.10.8
15
+ cffi==1.15.0
16
+ charset-normalizer==2.0.12
17
+ click==8.0.4
18
+ colorama==0.4.4
19
+ cryptography==36.0.1
20
+ cycler==0.11.0
21
+ Cython==0.29.28
22
+ fairseq @ git+https://github.com/pytorch/fairseq.git@d03f4e771484a433f025f47744017c2eb6e9c6bc
23
+ fastapi==0.75.0
24
+ ffmpy==0.3.0
25
+ fonttools==4.30.0
26
+ frozenlist==1.3.0
27
+ fsspec==2022.2.0
28
+ future==0.18.2
29
+ google-auth==2.6.0
30
+ google-auth-oauthlib==0.4.6
31
+ gradio==2.8.10
32
+ grpcio==1.44.0
33
+ h11==0.13.0
34
+ hydra-core==1.0.7
35
+ idna==3.3
36
+ importlib-metadata==4.11.3
37
+ Jinja2==3.0.3
38
+ kiwisolver==1.3.2
39
+ linkify-it-py==1.0.3
40
+ Markdown==3.3.6
41
+ markdown-it-py==2.0.1
42
+ MarkupSafe==2.1.0
43
+ matplotlib==3.5.1
44
+ mdit-py-plugins==0.3.0
45
+ mdurl==0.1.0
46
+ monotonic==1.6
47
+ multidict==6.0.2
48
+ numpy==1.22.3
49
+ oauthlib==3.2.0
50
+ omegaconf==2.0.6
51
+ orjson==3.6.7
52
+ packaging==21.3
53
+ pandas==1.4.1
54
+ paramiko==2.10.1
55
+ Pillow==9.0.1
56
+ portalocker==2.4.0
57
+ protobuf==3.19.4
58
+ pyasn1==0.4.8
59
+ pyasn1-modules==0.2.8
60
+ pycparser==2.21
61
+ pycryptodome==3.14.1
62
+ pydantic==1.9.0
63
+ pyDeprecate==0.3.1
64
+ pydub==0.25.1
65
+ PyNaCl==1.5.0
66
+ pyparsing==3.0.7
67
+ python-dateutil==2.8.2
68
+ python-multipart==0.0.5
69
+ pytorch-lightning==1.5.10
70
+ pytz==2021.3
71
+ PyYAML==6.0
72
+ regex==2022.3.2
73
+ requests==2.27.1
74
+ requests-oauthlib==1.3.1
75
+ rsa==4.8
76
+ sacrebleu==2.0.0
77
+ six==1.16.0
78
+ sniffio==1.2.0
79
+ starlette==0.17.1
80
+ tabulate==0.8.9
81
+ tensorboard==2.8.0
82
+ tensorboard-data-server==0.6.1
83
+ tensorboard-plugin-wit==1.8.1
84
+ torch==1.11.0
85
+ torchaudio==0.11.0
86
+ torchmetrics==0.7.2
87
+ tqdm==4.63.0
88
+ typing-extensions==4.1.1
89
+ uc-micro-py==1.0.1
90
+ urllib3==1.26.8
91
+ uvicorn==0.17.6
92
+ Werkzeug==2.0.3
93
+ yarl==1.7.2
94
+ zipp==3.7.0
wav2vec_small.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c66c39eaed1b79a61ea8573f71e08f6641ff156b6a8f458cfaab53877dfa4a26
3
+ size 950500491