Dionyssos commited on
Commit
a1338da
·
1 Parent(s): 02bf1ff

Audionar long form

Browse files
Files changed (6) hide show
  1. README.md +3 -3
  2. Utils/text_utils.py +5 -17
  3. audiobook.py +2 -1
  4. correct_figure.py +0 -378
  5. demo.py +4 -4
  6. visualize_per_sentence.py +0 -251
README.md CHANGED
@@ -14,13 +14,13 @@ tags:
14
  - mimic3
15
  ---
16
 
17
- Audionar - StyleTTS2 of speakers pregenerated by another TTS
18
 
19
  [![Beta Text 2 Speech Tool](assets/shift_banner.png?raw=true)](https://shift-europe.eu/)
20
 
21
  ##
22
 
23
- # SHIFT TTS / AudioGen
24
 
25
  Phonetic variation of [SHIFT TTS](https://audeering.github.io/shift/) blend to [AudioGen soundscapes](https://huggingface.co/dkounadis/artificial-styletts2/discussions/3)
26
  - [Analysis of emotion of SHIFT TTS](https://huggingface.co/dkounadis/artificial-styletts2/discussions/2)
@@ -82,7 +82,7 @@ python tts.py --text assets/ocr.txt --image assets/ocr.jpg --soundscape "battle
82
 
83
  ## Landscape 2 Soundscapes
84
 
85
- The following needs `api.py` to be already running on a tmux session.
86
 
87
  ```python
88
  # TTS & soundscape - output .mp4 saved in ./out/
 
14
  - mimic3
15
  ---
16
 
17
+ Audionar - Phonetic Variation of StyleTTS2 blend to AudioGen SoundScapes
18
 
19
  [![Beta Text 2 Speech Tool](assets/shift_banner.png?raw=true)](https://shift-europe.eu/)
20
 
21
  ##
22
 
23
+ # SHIFT TTS / Audionar
24
 
25
  Phonetic variation of [SHIFT TTS](https://audeering.github.io/shift/) blend to [AudioGen soundscapes](https://huggingface.co/dkounadis/artificial-styletts2/discussions/3)
26
  - [Analysis of emotion of SHIFT TTS](https://huggingface.co/dkounadis/artificial-styletts2/discussions/2)
 
82
 
83
  ## Landscape 2 Soundscapes
84
 
85
+ The following needs `api.py` to be already running on another terminal
86
 
87
  ```python
88
  # TTS & soundscape - output .mp4 saved in ./out/
Utils/text_utils.py CHANGED
@@ -5,6 +5,10 @@ import textwrap
5
  from num2words import num2words
6
  # IPA Phonemizer: https://github.com/bootphon/phonemizer
7
  import nltk
 
 
 
 
8
  _pad = "$"
9
  _punctuation = ';:,.!?¡¿—…"«»“” '
10
  _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
@@ -35,23 +39,7 @@ class TextCleaner:
35
 
36
  def split_into_sentences(text, max_len=120):
37
  sentences = nltk.sent_tokenize(text)
38
- limited_sentences = []
39
-
40
- for sentence in sentences:
41
- if len(sentence) <= max_len:
42
- limited_sentences.append(sentence)
43
- else:
44
- # If a sentence is too long, try to split it more intelligently
45
- current_chunk = ""
46
- words = sentence.split()
47
- for word in words:
48
- if len(current_chunk) + len(word) + 1 <= max_len: # +1 for space
49
- current_chunk += (word + " ").strip()
50
- else:
51
- limited_sentences.append(current_chunk.strip())
52
- current_chunk = (word + " ").strip()
53
- if current_chunk: # Add any remaining part
54
- limited_sentences.append(current_chunk.strip())
55
  return limited_sentences
56
 
57
 
 
5
  from num2words import num2words
6
  # IPA Phonemizer: https://github.com/bootphon/phonemizer
7
  import nltk
8
+ #nltk.download('punkt', download_dir='./')
9
+ #nltk.download('punkt_tab', download_dir='./')
10
+ nltk.data.path.append('.')
11
+
12
  _pad = "$"
13
  _punctuation = ';:,.!?¡¿—…"«»“” '
14
  _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
 
39
 
40
  def split_into_sentences(text, max_len=120):
41
  sentences = nltk.sent_tokenize(text)
42
+ limited_sentences = [i for sent in sentences for i in textwrap.wrap(sent, width=max_len)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  return limited_sentences
44
 
45
 
audiobook.py CHANGED
@@ -194,7 +194,8 @@ for vox in voices:
194
  # SILENT CLIP
195
 
196
  clip_silent = ImageClip(STATIC_FRAME).set_duration(5) # as long as the audio - TTS first
197
- clip_silent.write_videofile(SILENT_VIDEO, fps=24)
 
198
 
199
 
200
 
 
194
  # SILENT CLIP
195
 
196
  clip_silent = ImageClip(STATIC_FRAME).set_duration(5) # as long as the audio - TTS first
197
+ clip_silent.fps = 24
198
+ clip_silent.write_videofile(SILENT_VIDEO)
199
 
200
 
201
 
correct_figure.py DELETED
@@ -1,378 +0,0 @@
1
- # we have to evaluate emotion & cer per sentence -> not audinterface sliding window
2
- import os
3
- import audresample
4
- import torch
5
- import matplotlib.pyplot as plt
6
- import soundfile
7
- import json
8
- import audb
9
- from transformers import AutoModelForAudioClassification
10
- from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2PreTrainedModel
11
- import types
12
- from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
13
- import pandas as pd
14
- import json
15
- import numpy as np
16
- from pathlib import Path
17
- import transformers
18
- import torch
19
- import audmodel
20
- import audiofile
21
- import jiwer
22
- # https://arxiv.org/pdf/2407.12229
23
- # https://arxiv.org/pdf/2312.05187
24
- # https://arxiv.org/abs/2407.05407
25
- # https://arxiv.org/pdf/2408.06577
26
- # https://arxiv.org/pdf/2309.07405
27
- import msinference
28
- import os
29
- from random import shuffle
30
-
31
- config = transformers.Wav2Vec2Config() #finetuning_task='spef2feat_reg')
32
- config.dev = torch.device('cuda:0')
33
- config.dev2 = torch.device('cuda:0')
34
-
35
-
36
-
37
-
38
- LABELS = ['arousal', 'dominance', 'valence',
39
- 'Angry',
40
- 'Sad',
41
- 'Happy',
42
- 'Surprise',
43
- 'Fear',
44
- 'Disgust',
45
- 'Contempt',
46
- 'Neutral'
47
- ]
48
-
49
- config = transformers.Wav2Vec2Config() #finetuning_task='spef2feat_reg')
50
- config.dev = torch.device('cuda:0')
51
- config.dev2 = torch.device('cuda:0')
52
-
53
-
54
-
55
-
56
- # https://arxiv.org/pdf/2407.12229
57
- # https://arxiv.org/pdf/2312.05187
58
- # https://arxiv.org/abs/2407.05407
59
- # https://arxiv.org/pdf/2408.06577
60
- # https://arxiv.org/pdf/2309.07405
61
-
62
-
63
- def _infer(self, x):
64
- '''x: (batch, audio-samples-16KHz)'''
65
- x = (x + self.config.mean) / self.config.std # plus
66
- x = self.ssl_model(x, attention_mask=None).last_hidden_state
67
- # pool
68
- h = self.pool_model.sap_linear(x).tanh()
69
- w = torch.matmul(h, self.pool_model.attention)
70
- w = w.softmax(1)
71
- mu = (x * w).sum(1)
72
- x = torch.cat(
73
- [
74
- mu,
75
- ((x * x * w).sum(1) - mu * mu).clamp(min=1e-7).sqrt()
76
- ], 1)
77
- return self.ser_model(x)
78
-
79
- teacher_cat = AutoModelForAudioClassification.from_pretrained(
80
- '3loi/SER-Odyssey-Baseline-WavLM-Categorical-Attributes',
81
- trust_remote_code=True # fun definitions see 3loi/SER-.. repo
82
- ).to(config.dev2).eval()
83
- teacher_cat.forward = types.MethodType(_infer, teacher_cat)
84
-
85
-
86
- # ===================[:]===================== Dawn
87
- def _prenorm(x, attention_mask=None):
88
- '''mean/var'''
89
- if attention_mask is not None:
90
- N = attention_mask.sum(1, keepdim=True) # here attn msk is unprocessed just the original input
91
- x -= x.sum(1, keepdim=True) / N
92
- var = (x * x).sum(1, keepdim=True) / N
93
-
94
- else:
95
- x -= x.mean(1, keepdim=True) # mean is an onnx operator reducemean saves some ops compared to casting integer N to float and the div
96
- var = (x * x).mean(1, keepdim=True)
97
- return x / torch.sqrt(var + 1e-7)
98
-
99
- from torch import nn
100
- from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2PreTrainedModel, Wav2Vec2Model
101
- class RegressionHead(nn.Module):
102
- r"""Classification head."""
103
-
104
- def __init__(self, config):
105
-
106
- super().__init__()
107
-
108
- self.dense = nn.Linear(config.hidden_size, config.hidden_size)
109
- self.dropout = nn.Dropout(config.final_dropout)
110
- self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
111
-
112
- def forward(self, features, **kwargs):
113
-
114
- x = features
115
- x = self.dropout(x)
116
- x = self.dense(x)
117
- x = torch.tanh(x)
118
- x = self.dropout(x)
119
- x = self.out_proj(x)
120
-
121
- return x
122
-
123
-
124
- class Dawn(Wav2Vec2PreTrainedModel):
125
- r"""Speech emotion classifier."""
126
-
127
- def __init__(self, config):
128
-
129
- super().__init__(config)
130
-
131
- self.config = config
132
- self.wav2vec2 = Wav2Vec2Model(config)
133
- self.classifier = RegressionHead(config)
134
- self.init_weights()
135
-
136
- def forward(
137
- self,
138
- input_values,
139
- attention_mask=None,
140
- ):
141
- x = _prenorm(input_values, attention_mask=attention_mask)
142
- outputs = self.wav2vec2(x, attention_mask=attention_mask)
143
- hidden_states = outputs[0]
144
- hidden_states = torch.mean(hidden_states, dim=1)
145
- logits = self.classifier(hidden_states)
146
- return logits
147
- # return {'hidden_states': hidden_states,
148
- # 'logits': logits}
149
- dawn = Dawn.from_pretrained('audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim').to(config.dev).eval()
150
- # =======================================
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
-
161
-
162
- torch_dtype = torch.float16 #if torch.cuda.is_available() else torch.float32
163
- model_id = "openai/whisper-large-v3"
164
- model = AutoModelForSpeechSeq2Seq.from_pretrained(
165
- model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
166
- ).to(config.dev)
167
- processor = AutoProcessor.from_pretrained(model_id)
168
- _pipe = pipeline(
169
- "automatic-speech-recognition",
170
- model=model,
171
- tokenizer=processor.tokenizer,
172
- feature_extractor=processor.feature_extractor,
173
- max_new_tokens=128,
174
- chunk_length_s=30,
175
- batch_size=16,
176
- return_timestamps=True,
177
- torch_dtype=torch_dtype,
178
- device=config.dev,
179
- )
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
-
190
- def process_function(x, sampling_rate, idx):
191
- # x = x[None , :] ASaHSuFDCN
192
- # {0: 'Angry', 1: 'Sad', 2: 'Happy', 3: 'Surprise',
193
- # 4: 'Fear', 5: 'Disgust', 6: 'Contempt', 7: 'Neutral'}
194
- #tensor([[0.0015, 0.3651, 0.0593, 0.0315, 0.0600, 0.0125, 0.0319, 0.4382]])
195
- logits_cat = teacher_cat(torch.from_numpy(x).to(config.dev)).softmax(1)
196
- logits_adv = dawn(torch.from_numpy(x).to(config.dev))
197
-
198
- out = torch.cat([logits_adv,
199
- logits_cat],
200
- 1).cpu().detach().numpy()
201
- # print(out.shape)
202
- return out[0, :]
203
-
204
-
205
-
206
- def load_speech(split=None):
207
- DB = [
208
- # [dataset, version, table, has_timdeltas_or_is_full_wavfile]
209
- # ['crema-d', '1.1.1', 'emotion.voice.test', False],
210
- #['librispeech', '3.1.0', 'test-clean', False],
211
- ['emodb', '1.2.0', 'emotion.categories.train.gold_standard', False],
212
- # ['entertain-playtestcloud', '1.1.0', 'emotion.categories.train.gold_standard', True],
213
- # ['erik', '2.2.0', 'emotion.categories.train.gold_standard', True],
214
- # ['meld', '1.3.1', 'emotion.categories.train.gold_standard', False],
215
- # ['msppodcast', '5.0.0', 'emotion.categories.train.gold_standard', False], # tandalone bucket because it has gt labels?
216
- # ['myai', '1.0.1', 'emotion.categories.train.gold_standard', False],
217
- # ['casia', None, 'emotion.categories.gold_standard', False],
218
- # ['switchboard-1', None, 'sentiment', True],
219
- # ['swiss-parliament', None, 'segments', True],
220
- # ['argentinian-parliament', None, 'segments', True],
221
- # ['austrian-parliament', None, 'segments', True],
222
- # #'german', --> bundestag
223
- # ['brazilian-parliament', None, 'segments', True],
224
- # ['mexican-parliament', None, 'segments', True],
225
- # ['portuguese-parliament', None, 'segments', True],
226
- # ['spanish-parliament', None, 'segments', True],
227
- # ['chinese-vocal-emotions-liu-pell', None, 'emotion.categories.desired', False],
228
- # peoples-speech slow
229
- # ['peoples-speech', None, 'train-initial', False]
230
- ]
231
-
232
- output_list = []
233
- for database_name, ver, table, has_timedeltas in DB:
234
-
235
- a = audb.load(database_name,
236
- sampling_rate=16000,
237
- format='wav',
238
- mixdown=True,
239
- version=ver,
240
- cache_root='/cache/audb/')
241
- a = a[table].get()
242
- if has_timedeltas:
243
- print(f'{has_timedeltas=}')
244
- # a = a.reset_index()[['file', 'start', 'end']]
245
- # output_list += [[*t] for t
246
- # in zip(a.file.values, a.start.dt.total_seconds().values, a.end.dt.total_seconds().values)]
247
- else:
248
- output_list += [f for f in a.index] # use file (no timedeltas)
249
- return output_list
250
-
251
-
252
-
253
-
254
-
255
-
256
-
257
-
258
-
259
-
260
-
261
- natural_wav_paths = load_speech()
262
-
263
-
264
-
265
-
266
-
267
-
268
-
269
- with open('harvard.json', 'r') as f:
270
- harvard_individual_sentences = json.load(f)['sentences']
271
-
272
-
273
-
274
- synthetic_wav_paths = ['./enslow/' + i for i in
275
- os.listdir('./enslow/')]
276
- synthetic_wav_paths_4x = ['./style_vector_v2/' + i for i in
277
- os.listdir('./style_vector_v2/')]
278
- synthetic_wav_paths_foreign = ['./mimic3_foreign/' + i for i in os.listdir('./mimic3_foreign/') if 'en_U' not in i]
279
- synthetic_wav_paths_foreign_4x = ['./mimic3_foreign_4x/' + i for i in os.listdir('./mimic3_foreign_4x/') if 'en_U' not in i] # very short segments
280
-
281
- # filter very short styles
282
- synthetic_wav_paths_foreign = [i for i in synthetic_wav_paths_foreign if audiofile.duration(i) > 2]
283
- synthetic_wav_paths_foreign_4x = [i for i in synthetic_wav_paths_foreign_4x if audiofile.duration(i) > 2]
284
- synthetic_wav_paths = [i for i in synthetic_wav_paths if audiofile.duration(i) > 2]
285
- synthetic_wav_pathsn_4x = [i for i in synthetic_wav_paths_4x if audiofile.duration(i) > 2]
286
-
287
- shuffle(synthetic_wav_paths_foreign_4x)
288
- shuffle(synthetic_wav_paths_foreign)
289
- shuffle(synthetic_wav_paths)
290
- shuffle(synthetic_wav_paths_4x)
291
- print(len(synthetic_wav_paths_foreign_4x), len(synthetic_wav_paths_foreign),
292
- len(synthetic_wav_paths), len(synthetic_wav_paths_4x)) # 134 204 134 204
293
-
294
-
295
-
296
- for audio_prompt in ['english',
297
- 'english_4x',
298
- 'human',
299
- 'foreign',
300
- 'foreign_4x']: # each of these creates a separate pkl - so outer for
301
- #
302
- data = np.zeros((770, len(LABELS)*2 + 2)) # 768 x LABELS-prompt & LABELS-stts2 & cer-prompt & cer-stts2
303
-
304
-
305
-
306
- #
307
-
308
- OUT_FILE = f'{audio_prompt}_analytic.pkl'
309
- if not os.path.isfile(OUT_FILE):
310
- ix = 0
311
- for list_of_10 in harvard_individual_sentences[:10004]:
312
- # long_sentence = ' '.join(list_of_10['sentences'])
313
- # harvard.append(long_sentence.replace('.', ' '))
314
- for text in list_of_10['sentences']:
315
- if audio_prompt == 'english':
316
- _p = synthetic_wav_paths[ix % len(synthetic_wav_paths)]
317
- # 134
318
- style_vec = msinference.compute_style(_p)
319
- elif audio_prompt == 'english_4x':
320
- _p = synthetic_wav_paths_4x[ix % len(synthetic_wav_paths_4x)]
321
- # 134]
322
- style_vec = msinference.compute_style(_p)
323
- elif audio_prompt == 'human':
324
- _p = natural_wav_paths[ix % len(natural_wav_paths)]
325
- # ?
326
- style_vec = msinference.compute_style(_p)
327
- elif audio_prompt == 'foreign':
328
- _p = synthetic_wav_paths_foreign[ix % len(synthetic_wav_paths_foreign)]
329
- # 204 some short styles are discarded ~ 1180
330
- style_vec = msinference.compute_style(_p)
331
- elif audio_prompt == 'foreign_4x':
332
- _p = synthetic_wav_paths_foreign_4x[ix % len(synthetic_wav_paths_foreign_4x)]
333
- # 174
334
- style_vec = msinference.compute_style(_p)
335
- else:
336
- print('unknonw list of style vector')
337
-
338
- x = msinference.inference(text,
339
- style_vec,
340
- alpha=0.3,
341
- beta=0.7,
342
- diffusion_steps=7,
343
- embedding_scale=1)
344
- x = audresample.resample(x, 24000, 16000)
345
-
346
-
347
- _st, fsr = audiofile.read(_p)
348
- _st = audresample.resample(_st, fsr, 16000)
349
- print(_st.shape, x.shape)
350
-
351
- emotion_of_prompt = process_function(_st, 16000, None)
352
- emotion_of_out = process_function(x, 16000, None)
353
- data[ix, :11] = emotion_of_prompt
354
- data[ix, 11:22] = emotion_of_out
355
-
356
- # 2 last columns is cer-prompt cer-styletts2
357
-
358
- transcription_prompt = _pipe(_st[0])
359
- transcription_styletts2 = _pipe(x[0]) # allow singleton for EMO process func
360
- # print(len(emotion_of_prompt + emotion_of_out), ix, text)
361
- print(transcription_prompt, transcription_styletts2)
362
-
363
- data[ix, 22] = jiwer.cer('Sweet dreams are made of this. I travel the world and the seven seas.',
364
- transcription_prompt['text'])
365
-
366
- data[ix, 23] = jiwer.cer(text,
367
- transcription_styletts2['text'])
368
- print(data[ix, :])
369
-
370
- ix += 1
371
-
372
- df = pd.DataFrame(data, columns=['prompt-' + i for i in LABELS] + ['styletts2-' + i for i in LABELS] + ['cer-prompt', 'cer-styletts2'])
373
- df.to_pickle(OUT_FILE)
374
- else:
375
-
376
- df = pd.read_pickle(OUT_FILE)
377
- print('\nALREADY EXISTS\n{df}')
378
- # From the pickle we should also run cer and whisper on every prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo.py CHANGED
@@ -1,7 +1,7 @@
1
  import numpy as np
2
  import soundfile
3
- import msinference # If using api.py/live_demo.py instead of this demo.py has also split into sentences for long form text OOM
4
- from audiocraft.builders import AudioGen # has custom accelerations for long form text - needs 14 GB of cuda
5
 
6
  def tts_entry(text='A quick brown fox jumps over the lazy dog. Sweet dreams are made of this, I traveled the world and the seven seas.',
7
  voice='en_US/m-ailabs_low#mary_ann', # Listen to voices https://huggingface.co/dkounadis/artificial-styletts2/discussions/1
@@ -29,10 +29,10 @@ def tts_entry(text='A quick brown fox jumps over the lazy dog. Sweet dreams are
29
 
30
  x = msinference.foreign(text=text, lang=voice)
31
 
32
- x /= 1.02 * np.abs(x).max() + 1e-7 # volume amplify full [-1,1]
33
  if soundscape is not None:
34
  sound_gen = AudioGen().to('cuda:0').eval()
35
- background = sound_gen.generate(soundscape, duration=len(x)/16000 + .74, # sound duration seconds
36
  ).detach().cpu().numpy()
37
  x = .6 * x + .4 * background[:len(x)]
38
  return x
 
1
  import numpy as np
2
  import soundfile
3
+ import msinference # Prefer live_demo.py instead as this demo.py has no split to sentences to prevent OOM
4
+ from audiocraft.builders import AudioGen # fixed bug for repeated calls
5
 
6
  def tts_entry(text='A quick brown fox jumps over the lazy dog. Sweet dreams are made of this, I traveled the world and the seven seas.',
7
  voice='en_US/m-ailabs_low#mary_ann', # Listen to voices https://huggingface.co/dkounadis/artificial-styletts2/discussions/1
 
29
 
30
  x = msinference.foreign(text=text, lang=voice)
31
 
32
+ x /= 1.02 * np.abs(x).max() + 1e-7 # volume amplify to [-1,1]
33
  if soundscape is not None:
34
  sound_gen = AudioGen().to('cuda:0').eval()
35
+ background = sound_gen.generate(soundscape, duration=len(x)/16000 + .74, # sound duration in seconds
36
  ).detach().cpu().numpy()
37
  x = .6 * x + .4 * background[:len(x)]
38
  return x
visualize_per_sentence.py DELETED
@@ -1,251 +0,0 @@
1
- # PREREQUISITY
2
-
3
- # correct_figure.py -> makes analytic.pkl & CER -> per sentence No Audinterface sliding window
4
- import pandas as pd
5
- import os
6
- import numpy as np
7
- from pathlib import Path
8
- import matplotlib.pyplot as plt
9
- import audiofile
10
-
11
- columns = ['prompt-arousal',
12
- 'prompt-dominance',
13
- 'prompt-valence',
14
- 'prompt-Angry',
15
- 'prompt-Sad',
16
- 'prompt-Happy',
17
- 'prompt-Surprise',
18
- 'prompt-Fear',
19
- 'prompt-Disgust',
20
- 'prompt-Contempt',
21
- 'prompt-Neutral',
22
- 'styletts2-arousal',
23
- 'styletts2-dominance',
24
- 'styletts2-valence',
25
- 'styletts2-Angry',
26
- 'styletts2-Sad',
27
- 'styletts2-Happy',
28
- 'styletts2-Surprise',
29
- 'styletts2-Fear',
30
- 'styletts2-Disgust',
31
- 'styletts2-Contempt',
32
- 'styletts2-Neutral',
33
- 'cer-prompt',
34
- 'cer-styletts2']
35
-
36
- FULL_PKL = ['english_4x_analytic.pkl',
37
- 'english_analytic.pkl',
38
- 'foreign_4x_analytic.pkl',
39
- 'foreign_analytic.pkl',
40
- 'human_analytic.pkl']
41
- # -------------------------------------------
42
-
43
-
44
-
45
- LABELS = ['arousal', 'dominance', 'valence',
46
- # 'speech_synthesizer', 'synthetic_singing',
47
- 'Angry',
48
- 'Sad',
49
- 'Happy',
50
- 'Surprise',
51
- 'Fear',
52
- 'Disgust',
53
- 'Contempt',
54
- 'Neutral'
55
- ]
56
-
57
-
58
-
59
-
60
- # https://arxiv.org/pdf/2407.12229
61
- # https://arxiv.org/pdf/2312.05187
62
- # https://arxiv.org/abs/2407.05407
63
- # https://arxiv.org/pdf/2408.06577
64
- # https://arxiv.org/pdf/2309.07405
65
- preds = {}
66
-
67
- for file_interface in FULL_PKL:
68
- y = pd.read_pickle(file_interface)
69
- # y = y.rolling(20).mean()[19:] --> avoid when printing character error rate
70
- preds[file_interface] = y #.sort_values('styletts2-valence')
71
- print(f'\n\n {file_interface}\n_____________________________\n',
72
- f"{y['cer-prompt'].mean()=}",
73
- f"{y['cer-styletts2'].mean()=}\n\n")
74
-
75
-
76
-
77
- # =================================== cER ---------------------------
78
-
79
-
80
- for lang in ['english',
81
- 'foreign']:
82
-
83
-
84
- fig, ax = plt.subplots(nrows=8, ncols=2, figsize=(24,20.7),
85
- gridspec_kw={'hspace': 0, 'wspace': .04})
86
-
87
-
88
-
89
-
90
- time_stamp = np.arange(len(preds['english_analytic.pkl']))
91
- _z = np.zeros(len(preds['english_analytic.pkl']))
92
- for j, dim in enumerate(['arousal', 'dominance', 'valence']):
93
-
94
- # MIMIC3
95
-
96
- ax[j, 0].plot(time_stamp, preds[f'{lang}_analytic.pkl'][f'styletts2-{dim}'],
97
- color=(0,104/255,139/255),
98
- label='mean_1',
99
- linewidth=2)
100
- ax[j, 0].fill_between(time_stamp,
101
-
102
- _z,
103
- preds['human_analytic.pkl'][f'styletts2-{dim}'],
104
-
105
- color=(.2,.2,.2),
106
- alpha=0.244)
107
- if j == 0:
108
- if lang == 'english':
109
- desc = 'English'
110
- else:
111
- desc = 'Non-English'
112
- ax[j, 0].legend([f'StyleTTS2 using Mimic-3 {desc}',
113
- f'StyleTTS2 uising EmoDB'],
114
- prop={'size': 14},
115
- )
116
- ax[j, 0].set_ylabel(dim.lower(), color=(.4, .4, .4), fontsize=17)
117
-
118
- # TICK
119
- ax[j, 0].set_ylim([1e-7, .9999])
120
- # ax[j, 0].set_yticks([.25, .5,.75])
121
- # ax[j, 0].set_yticklabels(['0.25', '.5', '0.75'])
122
- ax[j, 0].set_xticklabels(['' for _ in ax[j, 0].get_xticklabels()])
123
- ax[j, 0].set_xlim([time_stamp[0], time_stamp[-1]])
124
-
125
-
126
- # MIMIC3 4x speed
127
-
128
-
129
- ax[j, 1].plot(time_stamp, preds[f'{lang}_4x_analytic.pkl'][f'styletts2-{dim}'],
130
- color=(0,104/255,139/255),
131
- label='mean_1',
132
- linewidth=2)
133
- ax[j, 1].fill_between(time_stamp,
134
-
135
- _z,
136
- preds['human_analytic.pkl'][f'styletts2-{dim}'],
137
-
138
- color=(.2,.2,.2),
139
- alpha=0.244)
140
- if j == 0:
141
- if lang == 'english':
142
- desc = 'English'
143
- else:
144
- desc = 'Non-English'
145
- ax[j, 1].legend([f'StyleTTS2 using Mimic-3 {desc} 4x speed',
146
- f'StyleTTS2 using EmoDB'],
147
- prop={'size': 14},
148
- # loc='lower right'
149
- )
150
-
151
-
152
- ax[j, 1].set_xlabel('720 Harvard Sentences')
153
-
154
-
155
-
156
- # TICK
157
- ax[j, 1].set_ylim([1e-7, .9999])
158
- # ax[j, 1].set_yticklabels(['' for _ in ax[j, 1].get_yticklabels()])
159
- ax[j, 1].set_xticklabels(['' for _ in ax[j, 0].get_xticklabels()])
160
- ax[j, 1].set_xlim([time_stamp[0], time_stamp[-1]])
161
-
162
-
163
-
164
-
165
- ax[j, 0].grid()
166
- ax[j, 1].grid()
167
- # CATEGORIE
168
-
169
-
170
-
171
-
172
-
173
-
174
- for j, dim in enumerate(['Angry',
175
- 'Sad',
176
- 'Happy',
177
- # 'Surprise',
178
- 'Fear',
179
- 'Disgust',
180
- # 'Contempt',
181
- # 'Neutral'
182
- ]): # ASaHSuFDCN
183
- j = j + 3 # skip A/D/V suplt
184
-
185
- # MIMIC3
186
-
187
- ax[j, 0].plot(time_stamp, preds[f'{lang}_analytic.pkl'][f'styletts2-{dim}'],
188
- color=(0,104/255,139/255),
189
- label='mean_1',
190
- linewidth=2)
191
- ax[j, 0].fill_between(time_stamp,
192
-
193
- _z,
194
- preds['human_analytic.pkl'][f'styletts2-{dim}'],
195
-
196
- color=(.2,.2,.2),
197
- alpha=0.244)
198
- # ax[j, 0].legend(['StyleTTS2 style mimic3',
199
- # 'StyleTTS2 style crema-d'],
200
- # prop={'size': 10},
201
- # # loc='upper left'
202
- # )
203
-
204
-
205
- ax[j, 0].set_ylabel(dim.lower(), color=(.4, .4, .4), fontsize=17)
206
-
207
- # TICKS
208
- ax[j, 0].set_ylim([1e-7, .9999])
209
- ax[j, 0].set_xlim([time_stamp[0], time_stamp[-1]])
210
- ax[j, 0].set_xticklabels(['' for _ in ax[j, 0].get_xticklabels()])
211
- ax[j, 0].set_xlabel('720 Harvard Sentences', fontsize=17, color=(.2,.2,.2))
212
-
213
-
214
- # MIMIC3 4x speed
215
-
216
-
217
- ax[j, 1].plot(time_stamp, preds[f'{lang}_4x_analytic.pkl'][f'styletts2-{dim}'],
218
- color=(0,104/255,139/255),
219
- label='mean_1',
220
- linewidth=2)
221
- ax[j, 1].fill_between(time_stamp,
222
-
223
- _z,
224
- preds['human_analytic.pkl'][f'styletts2-{dim}'],
225
-
226
- color=(.2,.2,.2),
227
- alpha=0.244)
228
- # ax[j, 1].legend(['StyleTTS2 style mimic3 4x speed',
229
- # 'StyleTTS2 style crema-d'],
230
- # prop={'size': 10},
231
- # # loc='upper left'
232
- # )
233
- ax[j, 1].set_xlabel('720 Harvard Sentences', fontsize=17, color=(.2,.2,.2))
234
- ax[j, 1].set_ylim([1e-7, .9999])
235
- # ax[j, 1].set_yticklabels(['' for _ in ax[j, 1].get_yticklabels()])
236
- ax[j, 1].set_xticklabels(['' for _ in ax[j, 1].get_xticklabels()])
237
- ax[j, 1].set_xlim([time_stamp[0], time_stamp[-1]])
238
-
239
-
240
-
241
-
242
-
243
-
244
- ax[j, 0].grid()
245
- ax[j, 1].grid()
246
-
247
-
248
-
249
- plt.savefig(f'persentence_{lang}.pdf', bbox_inches='tight')
250
- plt.close()
251
-