Upload 3 files
Browse filesTraining and speech generation scripts.
- expandnumbers.py +63 -0
- generateSpeechT5ttsHF.ipynb +151 -0
- trainSpeechT5ttsGetallen.py +354 -0
expandnumbers.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def number_in_words(getal):
|
| 5 |
+
eenheden = ["", "een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen"]
|
| 6 |
+
tientallen = ["", "", "twintig", "dertig", "veertig", "vijftig", "zestig", "zeventig", "tachtig", "negentig"]
|
| 7 |
+
|
| 8 |
+
miljoentallen = ""
|
| 9 |
+
duizendtallen = ""
|
| 10 |
+
if getal >= 1000000:
|
| 11 |
+
miljoentallen = number_to_hundreds(getal // 1000000) + "miljoen "
|
| 12 |
+
getal = getal % 1000000
|
| 13 |
+
|
| 14 |
+
if getal >= 1000:
|
| 15 |
+
duizendtallen = number_to_hundreds(getal // 1000) + "duizend "
|
| 16 |
+
getal = getal % 1000
|
| 17 |
+
|
| 18 |
+
return miljoentallen + duizendtallen + number_to_hundreds(getal)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def number_to_hundreds(num):
|
| 22 |
+
eenheden = ["", "een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "tien"]
|
| 23 |
+
tientallen = ["", "", "twintig", "dertig", "veertig", "vijftig", "zestig", "zeventig", "tachtig", "negentig"]
|
| 24 |
+
res = ""
|
| 25 |
+
|
| 26 |
+
if num >= 100:
|
| 27 |
+
res = eenheden[num // 100] + "honderd"
|
| 28 |
+
num = num % 100
|
| 29 |
+
|
| 30 |
+
if 10 < num < 20:
|
| 31 |
+
special_cases = {
|
| 32 |
+
11: "elf", 12: "twaalf", 13: "dertien", 14: "veertien", 15: "vijftien",
|
| 33 |
+
16: "zestien", 17: "zeventien", 18: "achttien", 19: "negentien"
|
| 34 |
+
}
|
| 35 |
+
res += special_cases[num]
|
| 36 |
+
elif num >= 20:
|
| 37 |
+
if num % 10 != 0:
|
| 38 |
+
res += eenheden[num % 10] + "en"
|
| 39 |
+
res += tientallen[num // 10]
|
| 40 |
+
# elif num == 10:
|
| 41 |
+
# res += eenheden[0]
|
| 42 |
+
else:
|
| 43 |
+
print('num', num)
|
| 44 |
+
res += eenheden[num]
|
| 45 |
+
|
| 46 |
+
return res
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
|
| 52 |
+
for d in range(10):
|
| 53 |
+
|
| 54 |
+
case = {}
|
| 55 |
+
|
| 56 |
+
getal = random.randint(1, 1000)
|
| 57 |
+
|
| 58 |
+
print('getal', getal)
|
| 59 |
+
|
| 60 |
+
woorden = number_in_words(getal)
|
| 61 |
+
print(woorden)
|
| 62 |
+
|
| 63 |
+
|
generateSpeechT5ttsHF.ipynb
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 12,
|
| 6 |
+
"id": "58146025",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"model & processor loaded\n",
|
| 14 |
+
"speaker embeddings & vocoder loaded\n"
|
| 15 |
+
]
|
| 16 |
+
}
|
| 17 |
+
],
|
| 18 |
+
"source": [
|
| 19 |
+
"import os\n",
|
| 20 |
+
"os.environ[\"WANDB_MODE\"] = \"disabled\"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"import torch\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"import soundfile as sf\n",
|
| 25 |
+
"import sounddevice as sd\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"from datasets import load_dataset \n",
|
| 28 |
+
"\n",
|
| 29 |
+
"from transformers import SpeechT5ForTextToSpeech, SpeechT5Processor\n",
|
| 30 |
+
"from transformers import SpeechT5HifiGan\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"MODEL_NAME = \"microsoft/speecht5_tts\"\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"CACHE_DIR = \"D:/LanguageModels/cache\"\n",
|
| 36 |
+
"DATASET_DIR = \"D:/LanguageModels/dataset/\"\n",
|
| 37 |
+
"AUDIO_DIR = \"D:/LanguageModels/dataset/audio/\"\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"finetuned = True\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"if finetuned:\n",
|
| 42 |
+
" model = SpeechT5ForTextToSpeech.from_pretrained(\"D:/LanguageModels/ftT5modelGetallen\")\n",
|
| 43 |
+
" processor = SpeechT5Processor.from_pretrained(\"D:/LanguageModels/ftT5processorGetallen\")\n",
|
| 44 |
+
"else:\n",
|
| 45 |
+
" model = SpeechT5ForTextToSpeech.from_pretrained(MODEL_NAME , cache_dir=CACHE_DIR)\n",
|
| 46 |
+
" processor = SpeechT5Processor.from_pretrained(MODEL_NAME , cache_dir=CACHE_DIR)\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"print('model & processor loaded')\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"embeddings_dataset = load_dataset(\"Matthijs/cmu-arctic-xvectors\", split=\"validation\" , cache_dir=CACHE_DIR)\n",
|
| 51 |
+
"speaker_embeddings = torch.tensor(embeddings_dataset[7306][\"xvector\"]).unsqueeze(0)\n",
|
| 52 |
+
"vocoder = SpeechT5HifiGan.from_pretrained(\"microsoft/speecht5_hifigan\" , cache_dir=CACHE_DIR)\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"print('speaker embeddings & vocoder loaded')"
|
| 55 |
+
]
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"execution_count": 14,
|
| 60 |
+
"id": "e0c771b3",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"outputs": [
|
| 63 |
+
{
|
| 64 |
+
"name": "stdout",
|
| 65 |
+
"output_type": "stream",
|
| 66 |
+
"text": [
|
| 67 |
+
"num 9\n",
|
| 68 |
+
"negen\n",
|
| 69 |
+
"inputs[\"input_ids\"] tensor([[ 4, 9, 5, 21, 5, 9, 2]])\n",
|
| 70 |
+
"spectrogram tensor([[-6.1973, -6.0982, -6.2766, ..., -7.5271, -7.3350, -7.0105],\n",
|
| 71 |
+
" [-5.0723, -5.2716, -5.1717, ..., -5.6201, -5.4415, -5.4130],\n",
|
| 72 |
+
" [-4.9598, -5.0752, -4.9666, ..., -5.1151, -4.9876, -5.0876],\n",
|
| 73 |
+
" ...,\n",
|
| 74 |
+
" [-4.9689, -4.7987, -4.7155, ..., -4.8989, -4.9458, -4.9992],\n",
|
| 75 |
+
" [-4.7762, -4.8095, -4.8122, ..., -4.8018, -4.8213, -4.8536],\n",
|
| 76 |
+
" [-4.4982, -4.5212, -4.4879, ..., -4.7741, -4.8168, -4.8919]])\n",
|
| 77 |
+
"spectrogram type <class 'torch.Tensor'>\n",
|
| 78 |
+
"speech tensor([ 7.7491e-06, 1.3468e-05, -1.8129e-06, ..., -9.3731e-06,\n",
|
| 79 |
+
" 1.2687e-05, 3.4955e-07])\n",
|
| 80 |
+
"speech shape torch.Size([14848])\n",
|
| 81 |
+
"Speech synthesis complete and saved for number negen to ./output/negen_T5modelFineGetallen.wav\n"
|
| 82 |
+
]
|
| 83 |
+
}
|
| 84 |
+
],
|
| 85 |
+
"source": [
|
| 86 |
+
"from expandnumbers import getal_in_woorden\n",
|
| 87 |
+
"import re\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"# Replace numbers with words\n",
|
| 91 |
+
"def replace_numbers(text):\n",
|
| 92 |
+
" return re.sub(r'\\d+', lambda x: getal_in_woorden(int(x.group())), text)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"number = '9'\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"number = replace_numbers(number)\n",
|
| 98 |
+
"print(number)\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"inputs = processor(text = number, return_tensors=\"pt\")\n",
|
| 101 |
+
"print('inputs[\"input_ids\"]' , inputs[\"input_ids\"] )\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"spectrogram = model.generate_speech(inputs[\"input_ids\"], speaker_embeddings)\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"print('spectrogram' , spectrogram)\n",
|
| 106 |
+
"print('spectrogram type' , type(spectrogram))\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"speech = model.generate_speech(inputs[\"input_ids\"], speaker_embeddings, vocoder=vocoder)\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"print('speech' , speech)\n",
|
| 111 |
+
"print('speech shape' , speech.shape)\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"# Play the sound\n",
|
| 114 |
+
"sd.play(speech, 16000)\n",
|
| 115 |
+
"sd.wait() # Wait until playback finishes\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"outfilename = ''\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"if finetuned:\n",
|
| 120 |
+
" outfilename = './output/' + number + '_T5modelFineGetallen.wav'\n",
|
| 121 |
+
"else:\n",
|
| 122 |
+
" outfilename = './output/' + number + '_T5modelOrigGetallen.wav'\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"sf.write(outfilename, speech, 16000)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"print(\"Speech synthesis complete and saved for number \" + number + ' to ' + outfilename)\n"
|
| 127 |
+
]
|
| 128 |
+
}
|
| 129 |
+
],
|
| 130 |
+
"metadata": {
|
| 131 |
+
"kernelspec": {
|
| 132 |
+
"display_name": "Python 3",
|
| 133 |
+
"language": "python",
|
| 134 |
+
"name": "python3"
|
| 135 |
+
},
|
| 136 |
+
"language_info": {
|
| 137 |
+
"codemirror_mode": {
|
| 138 |
+
"name": "ipython",
|
| 139 |
+
"version": 3
|
| 140 |
+
},
|
| 141 |
+
"file_extension": ".py",
|
| 142 |
+
"mimetype": "text/x-python",
|
| 143 |
+
"name": "python",
|
| 144 |
+
"nbconvert_exporter": "python",
|
| 145 |
+
"pygments_lexer": "ipython3",
|
| 146 |
+
"version": "3.11.9"
|
| 147 |
+
}
|
| 148 |
+
},
|
| 149 |
+
"nbformat": 4,
|
| 150 |
+
"nbformat_minor": 5
|
| 151 |
+
}
|
trainSpeechT5ttsGetallen.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
os.environ["WANDB_MODE"] = "disabled"
|
| 4 |
+
|
| 5 |
+
import tensorflow as tf
|
| 6 |
+
import torch
|
| 7 |
+
import torchaudio
|
| 8 |
+
|
| 9 |
+
from transformers import TrainingArguments, Trainer
|
| 10 |
+
from transformers import SpeechT5HifiGan
|
| 11 |
+
from transformers import TrainerCallback
|
| 12 |
+
|
| 13 |
+
from datasets import load_dataset , Audio
|
| 14 |
+
from datasets import concatenate_datasets
|
| 15 |
+
|
| 16 |
+
# from peft import get_peft_model, LoraConfig
|
| 17 |
+
|
| 18 |
+
MODEL_NAME = "microsoft/speecht5_tts"
|
| 19 |
+
|
| 20 |
+
CACHE_DIR = "D:/LanguageModels/cache"
|
| 21 |
+
|
| 22 |
+
DATASET_DIR = "./numberaudiodata/"
|
| 23 |
+
AUDIO_DIR = "./numberaudiodata/"
|
| 24 |
+
|
| 25 |
+
dataset = load_dataset("json", data_files = DATASET_DIR + "trainNL.json")
|
| 26 |
+
|
| 27 |
+
print('dataset' , dataset)
|
| 28 |
+
|
| 29 |
+
dataset = dataset["train"] # Ensure correct split selection
|
| 30 |
+
|
| 31 |
+
print('dataset["train"]' , dataset)
|
| 32 |
+
|
| 33 |
+
# Replicate the dataset to make it 10 times larger
|
| 34 |
+
datasets = []
|
| 35 |
+
|
| 36 |
+
for d in range(10):
|
| 37 |
+
datasets.append(dataset)
|
| 38 |
+
|
| 39 |
+
dataset = concatenate_datasets(datasets)
|
| 40 |
+
|
| 41 |
+
print(len(dataset)) # Check new dataset size
|
| 42 |
+
|
| 43 |
+
exit()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# gender_mapping = {"number1.wav": "male", "number2.wav": "female"} # Example mapping
|
| 47 |
+
# dataset = dataset.map(lambda example: {**example, "gender": gender_mapping.get(example["audio"], "unknown")})
|
| 48 |
+
print(type(dataset))
|
| 49 |
+
print(len(dataset))
|
| 50 |
+
print(dataset[0])
|
| 51 |
+
|
| 52 |
+
audio_id = 1
|
| 53 |
+
|
| 54 |
+
def update_example(example, audio_id):
|
| 55 |
+
example['audio_id'] = audio_id
|
| 56 |
+
example['language'] = 9
|
| 57 |
+
example['gender'] = 'female'
|
| 58 |
+
example['speaker_id'] = '1122'
|
| 59 |
+
example['is_gold_transcript'] = True
|
| 60 |
+
example['accent'] = 'None'
|
| 61 |
+
|
| 62 |
+
waveform, sampling_rate = torchaudio.load(AUDIO_DIR + example['audiofile'])
|
| 63 |
+
# Convert to NumPy
|
| 64 |
+
audio_array = waveform.numpy()
|
| 65 |
+
# print(audio_array.flatten())
|
| 66 |
+
example['audio'] = {}
|
| 67 |
+
example['audio']['array'] = audio_array.flatten()
|
| 68 |
+
example['audio']['sampling_rate'] = sampling_rate
|
| 69 |
+
|
| 70 |
+
return example
|
| 71 |
+
|
| 72 |
+
# Use `enumerate` with `map()` to update dataset
|
| 73 |
+
dataset = dataset.map(lambda example, idx: update_example(example, idx + 1), with_indices=True)
|
| 74 |
+
|
| 75 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
|
| 76 |
+
|
| 77 |
+
print(dataset[3])
|
| 78 |
+
# exit(0)
|
| 79 |
+
|
| 80 |
+
from transformers import SpeechT5ForTextToSpeech, SpeechT5Processor
|
| 81 |
+
|
| 82 |
+
processor = SpeechT5Processor.from_pretrained(MODEL_NAME , cache_dir=CACHE_DIR)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def prepare_dataset(example):
|
| 87 |
+
|
| 88 |
+
audio = example["audio"]
|
| 89 |
+
|
| 90 |
+
example = processor(
|
| 91 |
+
text=example["text"],
|
| 92 |
+
audio_target=audio["array"],
|
| 93 |
+
sampling_rate=audio["sampling_rate"],
|
| 94 |
+
return_attention_mask=False,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# strip off the batch dimension
|
| 98 |
+
example["labels"] = example["labels"][0]
|
| 99 |
+
|
| 100 |
+
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation" , cache_dir=CACHE_DIR)
|
| 101 |
+
|
| 102 |
+
speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"])
|
| 103 |
+
|
| 104 |
+
example["speaker_embeddings"] = speaker_embeddings
|
| 105 |
+
|
| 106 |
+
return example
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
processed_example = prepare_dataset(dataset[0])
|
| 110 |
+
print(list(processed_example.keys()))
|
| 111 |
+
print(processed_example["speaker_embeddings"].shape)
|
| 112 |
+
print('type(processed_example["labels"])' , type(processed_example["labels"]))
|
| 113 |
+
|
| 114 |
+
dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names)
|
| 115 |
+
|
| 116 |
+
print('dataset.column_names' , dataset.column_names)
|
| 117 |
+
print('training data negen input_ids' , dataset[8]['input_ids'])
|
| 118 |
+
print('training data negen labels' , dataset[8]['labels'][0])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
loadedspectrogram = dataset[8]['labels']
|
| 122 |
+
print('loadedspectrogram is ' , type(loadedspectrogram))
|
| 123 |
+
|
| 124 |
+
# Ensure spectrogram is a PyTorch tensor
|
| 125 |
+
spectrogram = torch.tensor(loadedspectrogram)
|
| 126 |
+
|
| 127 |
+
# spectrogram = torch.tensor(loadedspectrogram).unsqueeze(0) # Add batch dimension if needed
|
| 128 |
+
|
| 129 |
+
vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan" , cache_dir=CACHE_DIR)
|
| 130 |
+
# speech = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
|
| 131 |
+
|
| 132 |
+
print('vocoder loaded')
|
| 133 |
+
|
| 134 |
+
# Generate waveform from spectrogram
|
| 135 |
+
speech = vocoder(spectrogram).detach()
|
| 136 |
+
|
| 137 |
+
print('speech' , speech)
|
| 138 |
+
print('speech shape' , speech.shape)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# Play the sound
|
| 143 |
+
# sd.play(speech, 16000)
|
| 144 |
+
# sd.wait() # Wait until playback finishes
|
| 145 |
+
|
| 146 |
+
# sf.write('./output/loaded_negenGetallen.wav', speech, 16000)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# dataset = dataset.train_test_split(test_size=0.1)
|
| 150 |
+
|
| 151 |
+
from dataclasses import dataclass
|
| 152 |
+
from typing import Any, Dict, List, Union
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@dataclass
|
| 156 |
+
class TTSDataCollatorWithPadding:
|
| 157 |
+
processor: Any
|
| 158 |
+
|
| 159 |
+
def __call__(
|
| 160 |
+
self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
|
| 161 |
+
) -> Dict[str, torch.Tensor]:
|
| 162 |
+
|
| 163 |
+
input_ids = [{"input_ids": feature["input_ids"]} for feature in features]
|
| 164 |
+
label_features = [{"input_values": feature["labels"]} for feature in features]
|
| 165 |
+
|
| 166 |
+
speaker_features = [feature["speaker_embeddings"] for feature in features]
|
| 167 |
+
|
| 168 |
+
# collate the inputs and targets into a batch
|
| 169 |
+
batch = processor.pad(
|
| 170 |
+
input_ids=input_ids, labels=label_features, return_tensors="pt"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# replace padding with -100 to ignore loss correctly
|
| 174 |
+
batch["labels"] = batch["labels"].masked_fill(
|
| 175 |
+
batch.decoder_attention_mask.unsqueeze(-1).ne(1), -100
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# not used during fine-tuning
|
| 179 |
+
del batch["decoder_attention_mask"]
|
| 180 |
+
|
| 181 |
+
# round down target lengths to multiple of reduction factor
|
| 182 |
+
if model.config.reduction_factor > 1:
|
| 183 |
+
target_lengths = torch.tensor(
|
| 184 |
+
[len(feature["input_values"]) for feature in label_features]
|
| 185 |
+
)
|
| 186 |
+
target_lengths = target_lengths.new(
|
| 187 |
+
[
|
| 188 |
+
length - length % model.config.reduction_factor
|
| 189 |
+
for length in target_lengths
|
| 190 |
+
]
|
| 191 |
+
)
|
| 192 |
+
max_length = max(target_lengths)
|
| 193 |
+
batch["labels"] = batch["labels"][:, :max_length]
|
| 194 |
+
|
| 195 |
+
# also add in the speaker embeddings
|
| 196 |
+
batch["speaker_embeddings"] = torch.tensor(speaker_features)
|
| 197 |
+
|
| 198 |
+
# print('batch["input_ids"]' , batch["input_ids"][3])
|
| 199 |
+
# print('batch["labels"]' , batch["labels"][3])
|
| 200 |
+
|
| 201 |
+
return batch
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
data_collator = TTSDataCollatorWithPadding(processor=processor)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
training = True
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class SaveBestModelCallback(TrainerCallback):
|
| 211 |
+
def __init__(self, model, processor, save_path, best_loss=float("inf")):
|
| 212 |
+
self.model = model
|
| 213 |
+
self.processor = processor
|
| 214 |
+
self.save_path = save_path
|
| 215 |
+
self.best_loss = best_loss
|
| 216 |
+
|
| 217 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 218 |
+
if state.log_history and "loss" in state.log_history[-1]:
|
| 219 |
+
current_loss = state.log_history[-1]["loss"]
|
| 220 |
+
if current_loss < 1.00 and current_loss < self.best_loss:
|
| 221 |
+
self.best_loss = current_loss
|
| 222 |
+
print(f"New best loss: {self.best_loss} - Saving model...")
|
| 223 |
+
self.model.save_pretrained(self.save_path)
|
| 224 |
+
self.processor.save_pretrained(self.save_path)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
import torch.nn as nn
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class MSETrainer(Trainer):
|
| 231 |
+
|
| 232 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 233 |
+
|
| 234 |
+
labels = inputs.pop("labels", None) # Extract target speech outputs
|
| 235 |
+
if labels is None:
|
| 236 |
+
raise ValueError("Labels are missing in inputs!")
|
| 237 |
+
else:
|
| 238 |
+
print('labels' , labels)
|
| 239 |
+
|
| 240 |
+
# Ensure inputs are valid before passing to model
|
| 241 |
+
for key, value in inputs.items():
|
| 242 |
+
if value is None:
|
| 243 |
+
raise ValueError(f"Input '{key}' is None! Check preprocessing.")
|
| 244 |
+
|
| 245 |
+
print(' inputs are valid before passing to model')
|
| 246 |
+
|
| 247 |
+
outputs = model(**inputs) # Forward pass to get predictions
|
| 248 |
+
|
| 249 |
+
print('outputs' , outputs)
|
| 250 |
+
|
| 251 |
+
loss_fn = nn.MSELoss() # Define MSE loss function
|
| 252 |
+
loss = loss_fn(outputs.logits, labels) # Compute loss between predictions & labels
|
| 253 |
+
|
| 254 |
+
print('loss' , loss)
|
| 255 |
+
|
| 256 |
+
return (loss, outputs) if return_outputs else loss
|
| 257 |
+
|
| 258 |
+
# def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 259 |
+
|
| 260 |
+
# # labels = inputs.pop("labels") # Extract target speech outputs
|
| 261 |
+
# # outputs = model(**inputs) # Model prediction
|
| 262 |
+
# loss = super().compute_loss(model, inputs, return_outputs)
|
| 263 |
+
|
| 264 |
+
# # loss = torch.nn.MSELoss()(outputs.logits, labels) # Compute MSE loss
|
| 265 |
+
|
| 266 |
+
# return loss
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
if training:
|
| 271 |
+
|
| 272 |
+
print('now training')
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
model = SpeechT5ForTextToSpeech.from_pretrained(MODEL_NAME , cache_dir=CACHE_DIR)
|
| 276 |
+
|
| 277 |
+
print(model.config)
|
| 278 |
+
targetmodules = []
|
| 279 |
+
nall = 0
|
| 280 |
+
ntarget = 0
|
| 281 |
+
for name, module in model.named_modules():
|
| 282 |
+
nall += 1
|
| 283 |
+
if 'speech_decoder_postnet' in name:
|
| 284 |
+
ntarget +=1
|
| 285 |
+
targetmodules.append(name)
|
| 286 |
+
print(name, "->", type(module))
|
| 287 |
+
|
| 288 |
+
print('nall' , nall , 'ntarget' , ntarget)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
print(dir(model))
|
| 292 |
+
|
| 293 |
+
print(model.named_parameters())
|
| 294 |
+
|
| 295 |
+
# exit()
|
| 296 |
+
|
| 297 |
+
# Fine-tune only the postnet
|
| 298 |
+
for param in model.parameters():
|
| 299 |
+
param.requires_grad = False # Freeze all layers
|
| 300 |
+
for param in model.speech_decoder_postnet.parameters():
|
| 301 |
+
param.requires_grad = True # Unfreeze postnet
|
| 302 |
+
|
| 303 |
+
# config = LoraConfig(
|
| 304 |
+
# r=8, # Rank of LoRA matrices
|
| 305 |
+
# lora_alpha=32,
|
| 306 |
+
# lora_dropout=0.1,
|
| 307 |
+
# # target_modules=targetmodules # Apply LoRA to decoder layers
|
| 308 |
+
# target_modules = ["speech_decoder_postnet.feat_out", "speech_decoder_postnet.prob_out"] # Example names
|
| 309 |
+
|
| 310 |
+
# # target_modules=["decoder.block", "decoder.attention", "speech_decoder_prenet"], # Adjust based on model structure
|
| 311 |
+
# # target_modules=["decoder.layers"], # Apply LoRA to decoder layers
|
| 312 |
+
# )
|
| 313 |
+
|
| 314 |
+
# peftmodel = get_peft_model(model, config)
|
| 315 |
+
|
| 316 |
+
training_args = TrainingArguments(
|
| 317 |
+
output_dir="D:/LanguageModels/out_T5tts",
|
| 318 |
+
run_name="tts_exp",
|
| 319 |
+
per_device_train_batch_size=32,
|
| 320 |
+
gradient_accumulation_steps=1,
|
| 321 |
+
num_train_epochs=100,
|
| 322 |
+
save_steps=100,
|
| 323 |
+
save_total_limit=2,
|
| 324 |
+
# logging_dir="D:/LanguageModels/logs",
|
| 325 |
+
logging_steps=1,
|
| 326 |
+
learning_rate=0.001,
|
| 327 |
+
optim="adamw_torch_fused",
|
| 328 |
+
eval_strategy="no",
|
| 329 |
+
# eval_strategy="steps",
|
| 330 |
+
eval_steps=500,
|
| 331 |
+
weight_decay=0.0,
|
| 332 |
+
fp16=True
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
# from transformers import DataCollatorWithPadding
|
| 336 |
+
|
| 337 |
+
# collator = DataCollatorWithPadding(tokenizer=processor.tokenizer, padding=True)
|
| 338 |
+
|
| 339 |
+
trainer = Trainer(
|
| 340 |
+
model = model,
|
| 341 |
+
args = training_args,
|
| 342 |
+
train_dataset = dataset,
|
| 343 |
+
data_collator = data_collator,
|
| 344 |
+
callbacks=[SaveBestModelCallback(model, processor, "D:/LanguageModels/ftT5modelDutchNumbers")]
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
trainer.train()
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# model.save_pretrained("D:/LanguageModels/ftT5modelGetallen")
|
| 351 |
+
# processor.save_pretrained("D:/LanguageModels/ftT5processorGetallen")
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
|