Przygotuj ten kod do współpracy z danymi w języku polskim. Moje dane są zawarte w path = "/content/drive/MyDrive/archiwum/BAK-programowanie/cv-corpus-19.0-2024-09-13/pl" i wyglądają następująco:
"clip_durations.tsv # oto kilka pierwszych wierszy
clip duration[ms] common_voice_pl_25218083.mp3 3420 common_voice_pl_20605986.mp3 3936
clips # ten folder zawiera pliki mp3 // tak wyglądają nazwy plików: 1. common_voice_pl_20547774 2. common_voice_pl_20547775.mp3
dev.tsv
invalidated.tsv
other.tsv
reported.tsv
test.tsv # oto kilka pierwszych wierszy
client_id path sentence_id sentence sentence_domain up_votes down_votes age gender accents variant locale 02eb087ff2dda32b8dd01a85b4693569a62d56033bf17d7f0565aa45fa29b850e53f808baf94fef3d89be8a5ed0432675594297e47f8e5ea0ddfe86e81a21711 common_voice_pl_24005493.mp3 3538b2608e1451fa8cb7aea203d1515df86d6a4f933bdea56bd32440ffd0daa7 Ostatnie słowa wymówił syczącym szeptem i ze złośliwym uśmiechem. 2 0 pl 039674fdf440f2c9e53ff991cf27230071a2d969342dfd22d7b53d51b5d2d2468daec87b4edc41741e38f4388168950a8f52529f890f50ff0f660c786cde57bb common_voice_pl_20605240.mp3 52f0b3164e79636bfc13b1cebe4c5665bb215bcf26095ee099261b2b775e6cc4 Gdzież tu powód do wyrzutów? 5 0 pl
train.tsv # --||--
unvalidated_sentences.tsv # --||--
validated_sentences.tsv # --||--
validated.tsv # --||--"
Szkolenie
Celem jest wytrenowanie modelu VoiceCraft, aby to zrobić należy przygotować następujące części. Zadanie które mają zostać wykonane przez ten kod python obejmują:
1. Wypowiedzi i ich transkrypcje
2. Zakodować wypowiedzi w kody za pomocą np. Encodec
3. Konwertuje transkrypcje na sekwencję fonemów i zestaw fonemów dla języka polskiego
Niestety mam doczynienia z błędem:
0%| | 4/20597 [00:00<26:23, 13.01it/s]WARNING:phonemizer:words count mismatch on 100.0% of the lines (1/1)
9%|▉ | 1898/20597 [04:13<38:41, 8.05it/s]WARNING:root:Phonemization failed for common_voice_pl_25357496.mp3: /tmp/tmpw7llza_g/libespeak-ng.so.1.1.49: failed to map segment from shared object
WARNING:root:Phonemization failed for common_voice_pl_25357497.mp3: /tmp/tmpj5pf41m9/libespeak-ng.so.1.1.49: failed to map segment from shared object
27%|██▋ | 5609/20597 [06:25<03:47, 65.93it/s]WARNING:root:Phonemization failed for common_voice_pl_38523809.mp3:
WARNING:root:Phonemization failed for common_voice_pl_38523810.mp3:
WARNING:root:Phonemization failed for common_voice_pl_38523811.mp3:
27%|██▋ | 5612/20597 [06:25<17:08, 14.57it/s]
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
File "", line 85, in <cell line: 69>
phn = phonemize(text, language='pl', backend='espeak', strip=True, preserve_punctuation=True, njobs=1)
File "/usr/local/lib/python3.10/dist-packages/phonemizer/phonemize.py", line 206, in phonemize
phonemizer = BACKENDS[backend](
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/espeak.py", line 45, in
super().(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 39, in
super().(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/base.py", line 76, in
if not self.is_available():
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 87, in is_available
EspeakWrapper()
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 60, in
self._espeak = EspeakAPI(self.library())
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 147, in library
ctypes.util.find_library('espeak-ng') or
File "/usr/lib/python3.10/ctypes/util.py", line 340, in find_library
return _findSoname_ldconfig(name) or
File "/usr/lib/python3.10/ctypes/util.py", line 305, in _findSoname_ldconfig
res = re.search(regex, p.stdout.read())
File "/usr/lib/python3.10/re.py", line 200, in search
return _compile(pattern, flags).search(string)
MemoryError
Assistant
init
init
init
init
init
init
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 91, in <cell line: 69>
except Exception as e:
MemoryError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'MemoryError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1101, in get_records
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/usr/lib/python3.10/inspect.py", line 1662, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
File "/usr/lib/python3.10/inspect.py", line 1620, in getframeinfo
filename = getsourcefile(frame) or getfile(frame)
File "/usr/lib/python3.10/inspect.py", line 829, in getsourcefile
module = getmodule(object, filename)
File "/usr/lib/python3.10/inspect.py", line 868, in getmodule
for modname, module in sys.modules.copy().items():
MemoryError
Traceback (most recent call last):
File "", line 85, in <cell line: 69>
phn = phonemize(text, language='pl', backend='espeak', strip=True, preserve_punctuation=True, njobs=1)
File "/usr/local/lib/python3.10/dist-packages/phonemizer/phonemize.py", line 206, in phonemize
phonemizer = BACKENDS[backend](
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/espeak.py", line 45, in init
super().init(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 39, in init
super().init(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/base.py", line 76, in init
if not self.is_available():
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 87, in is_available
EspeakWrapper()
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 60, in init
self._espeak = EspeakAPI(self.library())
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 147, in library
ctypes.util.find_library('espeak-ng') or
File "/usr/lib/python3.10/ctypes/util.py", line 340, in find_library
return _findSoname_ldconfig(name) or
File "/usr/lib/python3.10/ctypes/util.py", line 305, in _findSoname_ldconfig
res = re.search(regex, p.stdout.read())
File "/usr/lib/python3.10/re.py", line 200, in search
return _compile(pattern, flags).search(string)
MemoryError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 91, in <cell line: 69>
except Exception as e:
MemoryError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'MemoryError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3473, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3575, in run_code
self.showtraceback(running_compiled_code=True)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2101, in showtraceback
stb = self.InteractiveTB.structured_traceback(etype,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1367, in structured_traceback
return FormattedTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1267, in structured_traceback
return VerboseTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1124, in structured_traceback
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1082, in format_exception_as_a_whole
last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 382, in find_recursion
return len(records), 0
TypeError: object of type 'NoneType' has no len()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'TypeError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1101, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/usr/lib/python3.10/inspect.py", line 1662, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
File "/usr/lib/python3.10/inspect.py", line 1620, in getframeinfo
filename = getsourcefile(frame) or getfile(frame)
File "/usr/lib/python3.10/inspect.py", line 829, in getsourcefile
module = getmodule(object, filename)
File "/usr/lib/python3.10/inspect.py", line 868, in getmodule
for modname, module in sys.modules.copy().items():
MemoryError
Traceback (most recent call last):
File "", line 85, in <cell line: 69>
phn = phonemize(text, language='pl', backend='espeak', strip=True, preserve_punctuation=True, njobs=1)
File "/usr/local/lib/python3.10/dist-packages/phonemizer/phonemize.py", line 206, in phonemize
phonemizer = BACKENDS[backend](
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/espeak.py", line 45, in init
super().init(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 39, in init
super().init(
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/base.py", line 76, in init
if not self.is_available():
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/base.py", line 87, in is_available
EspeakWrapper()
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 60, in init
self._espeak = EspeakAPI(self.library())
File "/usr/local/lib/python3.10/dist-packages/phonemizer/backend/espeak/wrapper.py", line 147, in library
ctypes.util.find_library('espeak-ng') or
File "/usr/lib/python3.10/ctypes/util.py", line 340, in find_library
return _findSoname_ldconfig(name) or
File "/usr/lib/python3.10/ctypes/util.py", line 305, in _findSoname_ldconfig
res = re.search(regex, p.stdout.read())
File "/usr/lib/python3.10/re.py", line 200, in search
return _compile(pattern, flags).search(string)
MemoryError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 91, in <cell line: 69>
except Exception as e:
MemoryError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'MemoryError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3473, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3575, in run_code
self.showtraceback(running_compiled_code=True)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2101, in showtraceback
stb = self.InteractiveTB.structured_traceback(etype,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1367, in structured_traceback
return FormattedTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1267, in structured_traceback
return VerboseTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1124, in structured_traceback
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1082, in format_exception_as_a_whole
last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 382, in find_recursion
return len(records), 0
TypeError: object of type 'NoneType' has no len()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'TypeError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3030, in _run_cell
return runner(coro)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/async_helpers.py", line 78, in _pseudo_sync_runner
coro.send(None)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3257, in run_cell_async
has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 3492, in run_ast_nodes
self.showtraceback()
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2101, in showtraceback
stb = self.InteractiveTB.structured_traceback(etype,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1367, in structured_traceback
return FormattedTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1267, in structured_traceback
return VerboseTB.structured_traceback(
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1142, in structured_traceback
formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1082, in format_exception_as_a_whole
last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 382, in find_recursion
return len(records), 0
TypeError: object of type 'NoneType' has no len()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py", line 2099, in showtraceback
stb = value.render_traceback()
AttributeError: 'TypeError' object has no attribute 'render_traceback'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 1101, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/usr/lib/python3.10/inspect.py", line 1662, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
File "/usr/lib/python3.10/inspect.py", line 1620, in getframeinfo
filename = getsourcefile(frame) or getfile(frame)
File "/usr/lib/python3.10/inspect.py", line 829, in getsourcefile
module = getmodule(object, filename)
File "/usr/lib/python3.10/inspect.py", line 868, in getmodule
for modname, module in sys.modules.copy().items():
MemoryError
Oto kod który wywołuję:
Importowanie niezbędnych bibliotek
import os
import numpy as np
import torch
import tqdm
import time
import pandas as pd
import logging
from audiocraft.models import EncodecModel
from audiocraft.data.audio_utils import convert_audio
from phonemizer.phonemize import phonemize
def write_array_to_txt_file(array, filename):
with open(filename, 'w') as f:
for a in array[:-1]:
f.write(' '.join(map(str, a))+'\n')
f.write(' '.join(map(str, array[-1])))
for split in splits:
skip = 0
logging.info(f"Now processing split {split}...")
total_samples = len(datasets[split])
mega_n_steps = int(np.ceil(total_samples / args.mega_batch_size))
logging.info(f"Partitioning the split {split} into {mega_n_steps} parts, each has {args.mega_batch_size} samples")
for m, mega_batch in enumerate(dataloaders[split]):
logging.info(f"====================================")
logging.info(f"Now processing mega step {m+1}/{mega_n_steps}")
durations = mega_batch['duration']
lengths = durations # Czas trwania w sekundach
sorted_inds = sort_by_audio_len(lengths)
for j in range(len(sorted_inds) -1, -1, -1):
if lengths[sorted_inds[j]] < 0.2 or lengths[sorted_inds[j]] > args.len_cap:
skip += 1
del sorted_inds[j]
n_steps = int(np.ceil(len(sorted_inds) / args.batch_size))
for n in tqdm.tqdm(range(n_steps)):
inds_used = sorted_inds[n*args.batch_size:(n+1)*args.batch_size]
if len(inds_used) == 0:
continue
audio_batch = [mega_batch['audio'][id] for id in inds_used]
sr_batch = [mega_batch['sr'][id] for id in inds_used]
path_batch = [mega_batch['path'][id] for id in inds_used]
text_batch = [mega_batch['text'][id] for id in inds_used]
padded_wav = torch.nn.utils.rnn.pad_sequence(audio_batch, batch_first=True).unsqueeze(1) # [B, 1, T]
all_lens = [lengths[id] for id in inds_used]
try:
with torch.no_grad():
if max(all_lens) > args.max_len / args.model_sr and len(all_lens) > 1:
codes = []
inwav = padded_wav.cuda()
codes_first_half = model.encode(inwav[:len(inwav)//2])[0].cpu()
codes_second_half = model.encode(inwav[len(inwav)//2:])[0].cpu()
codes = torch.cat([codes_first_half, codes_second_half], dim=0)
else:
encoded_frames = model.encode(padded_wav.cuda())
codes = encoded_frames[0].cpu()
for i, length in enumerate(all_lens):
save_fn = os.path.join(codes_save_root, path_batch[i] + ".txt")
actual_len = min(codes.size(2), round(length * args.model_code_sr)) # Unikamy przekroczenia indeksu
cur_code = codes[i, :, :actual_len].tolist()
write_array_to_txt_file(cur_code, save_fn)
except Exception as e:
logging.warning(f"Encoding failed at step {n+1} in mega step {m+1}: {e}")
continue
logging.info(f"Finished processing split {split}, skipped {skip} samples due to length constraints")
logging.info("Processing complete.")
Wygląda na to, że napotykasz błąd MemoryError podczas fonemizacji tekstu w języku polskim za pomocą pakietu phonemizer i back-endu espeak. Ten błąd jest prawdopodobnie spowodowany problemem z biblioteką espeak-ng, która nie jest poprawnie zainstalowana lub nie jest dostępna dla pakietu phonemizer. W środowisku Colab (lub ogólnie w systemach Linux) biblioteka espeak-ng musi być zainstalowana systemowo, aby phonemizer mógł z niej korzystać.
Rozwiązanie polega na zainstalowaniu biblioteki espeak-ng przed uruchomieniem kodu. Możesz to zrobić, wykonując następujące polecenia na początku swojego skryptu lub notebooka:
!apt-get update
!apt-get install espeak-ng -y
Następnie upewnij się, że masz zainstalowany pakiet phonemizer:
!pip install phonemizer
Poniżej znajduje się zmodyfikowany kod z dodanymi poleceniami instalacji:
# Instalacja espeak-ng i phonemizer
!apt-get update
!apt-get install espeak-ng -y
!pip install phonemizer
# Importowanie niezbędnych bibliotek
import os
import numpy as np
import torch
import tqdm
import time
import pandas as pd
import logging
from audiocraft.models import EncodecModel
from audiocraft.data.audio_utils import convert_audio
from phonemizer.phonemize import phonemize
# Definiowanie argumentów bezpośrednio w kodzie
class Args:
download_to = "/content/drive/MyDrive/archiwum/BAK-programowanie/cv-corpus-19.0-2024-09-13/pl"
save_dir = "/content/processed_data"
n_workers = 4
mega_batch_size = 100
batch_size = 4
model_sr = 16000
downsample_rate = 320
model_code_sr = 50
len_cap = 35.0
max_len = 30000
args = Args()
# Konfiguracja logowania
formatter = "%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d || %(message)s"
logging.basicConfig(format=formatter, level=logging.INFO)
# Definiowanie ścieżek
data_dir = args.download_to
phn_save_root = os.path.join(args.save_dir, "phonemes")
codes_save_root = os.path.join(args.save_dir, "encodec_16khz_4codebooks")
vocab_fn = os.path.join(args.save_dir, "vocab.txt")
os.makedirs(phn_save_root, exist_ok=True)
os.makedirs(codes_save_root, exist_ok=True)
def sort_by_audio_len(lens):
inds = np.argsort(lens).tolist()
logging.info(f"longest: {lens[inds[-1]]*args.model_code_sr} encodec codes, {lens[inds[-1]]:.2f} sec.")
logging.info(f"shortest: {lens[inds[0]]*args.model_code_sr} encodec codes, {lens[inds[0]]:.2f} sec.")
logging.info(f"median: {lens[inds[len(inds)//2]]*args.model_code_sr} encodec codes, {lens[inds[len(inds)//2]]:.2f} sec.")
logging.info(f"95 percentile longest: {lens[inds[int(len(inds)*0.95)]]*args.model_code_sr} encodec codes, {lens[inds[int(len(inds)*0.95)]]:.2f} sec.")
return inds[::-1]
def write_array_to_txt_file(array, filename):
with open(filename, 'w') as f:
for a in array[:-1]:
f.write(' '.join(map(str, a))+'\n')
f.write(' '.join(map(str, array[-1])))
# Fonemizacja
logging.info("Starting phonemization...")
phn_vocab = set()
all_lens = []
splits = ['train', 'validation', 'test']
split_files = {
'train': os.path.join(data_dir, 'train.tsv'),
'validation': os.path.join(data_dir, 'dev.tsv'),
'test': os.path.join(data_dir, 'test.tsv'),
}
# Dla fonemizacji języka polskiego używamy phonemizer z backendem espeak
for split in splits:
skip = 0
logging.info(f"Now processing split {split}...")
tsv_file = split_files[split]
df = pd.read_csv(tsv_file, sep='\t')
for index, item in tqdm.tqdm(df.iterrows(), total=len(df)):
client_id = item['client_id']
path = item['path']
sentence = item['sentence']
save_fn = os.path.join(phn_save_root, path.replace('.mp3', '') + ".txt")
text = sentence.strip()
if not isinstance(text, str) or not text:
logging.info(f"Skipping empty sentence at {path}")
skip += 1
continue
try:
phn = phonemize(text, language='pl', backend='espeak', strip=True, preserve_punctuation=True, njobs=1)
phn_seq = phn.strip()
phn_vocab.update(phn_seq.split())
all_lens.append(len(phn_seq.split()))
with open(save_fn, "w") as f:
f.write(phn_seq)
except Exception as e:
logging.warning(f"Phonemization failed for {path}: {e}")
skip += 1
continue
logging.info(f"Split {split} has {len(df)} samples in total, skipped {skip} due to errors")
logging.info(f"Phoneme vocabulary size: {len(phn_vocab)}")
logging.info(f"Phoneme sequence stats:")
logging.info(f"Longest sequence: {max(all_lens)} phonemes")
logging.info(f"Shortest sequence: {min(all_lens)} phonemes")
logging.info(f"Median sequence length: {np.quantile(all_lens, 0.5)} phonemes")
logging.info(f"95th percentile sequence length: {np.quantile(all_lens, 0.95)} phonemes")
logging.info(f"Writing vocabulary to {vocab_fn}")
with open(vocab_fn, "w") as f:
for i, phn in enumerate(sorted(list(phn_vocab))):
if i < len(phn_vocab) - 1:
f.write(f"{str(i)} {phn}\n")
else:
f.write(f"{str(i)} {phn}")
# Reszta kodu...
Dodanie instalacji pakietu espeak-ng przed importowaniem phonemizer powinno rozwiązać problem. Pakiet phonemizer będzie teraz w stanie znaleźć i użyć biblioteki espeak-ng zainstalowanej w systemie, co powinno zapobiec błędom związanym z pamięcią i pozwolić na poprawną fonemizację tekstu.
Wyjaśnienie:
Problem z biblioteką espeak-ng: Błąd MemoryError w trakcie korzystania z phonemizer często jest wynikiem niepoprawnej instalacji lub braku biblioteki espeak-ng. Pakiet phonemizer próbuje wtedy pobrać i skompilować bibliotekę w folderze tymczasowym dla każdego procesu, co może prowadzić do problemów z pamięcią.
Rozwiązanie poprzez instalację espeak-ng: Instalując espeak-ng systemowo za pomocą apt-get, zapewniasz, że phonemizer znajdzie i użyje istniejącej biblioteki, nie próbując jej ponownie pobierać i kompilować.
Dlaczego to działa: Gdy phonemizer znajdzie zainstalowaną bibliotekę espeak-ng, użyje jej bezpośrednio, co znacząco zmniejsza obciążenie pamięci i zapobiega błędom podczas fonemizacji.
Dodatkowe uwagi: Upewnij się, że uruchamiasz te polecenia na początku swojego skryptu lub notebooka, przed wykonaniem jakichkolwiek operacji fonemizacji.
Mam nadzieję, że to pomoże rozwiązać Twój problem!