import argparse
def parse_args():
parser = argparse.ArgumentParser(description="Encode the Common Voice dataset using Encodec model for Polish language")
parser.add_argument('--download_to', type=str, default="/content/drive/MyDrive/archiwum/BAK-programowanie/cv-corpus-19.0-2024-09-13/pl", help="Directory where the Common Voice dataset is located")
parser.add_argument('--save_dir', type=str, default="/content/processed_data", help="Path to save the manifest, phonemes, and Encodec codes")
parser.add_argument('--encodec_model_path', type=str, default="/path/to/encodec_model/checkpoint.th", help="Path to the Encodec model checkpoint")
parser.add_argument('--n_workers', type=int, default=4, help="Number of parallel worker processes")
parser.add_argument('--mega_batch_size', type=int, default=100, help="Number of samples in each mega batch for multiprocess dataloading")
parser.add_argument('--batch_size', type=int, default=4, help="Batch size for Encodec encoding, decrease it if OOM")
parser.add_argument('--model_sr', type=int, default=16000, help='Encodec model input audio sample rate')
parser.add_argument('--downsample_rate', type=int, default=320, help='Encodec downsample rate')
parser.add_argument('--model_code_sr', type=int, default=50, help='Encodec model code sample rate')
parser.add_argument('--len_cap', type=float, default=35.0, help='Will drop audios that are longer than this number (in seconds)')
parser.add_argument('--max_len', type=int, default=30000, help='Max length of audio in samples, if exceed, will cut a batch into half to process, decrease this number if OOM')
return parser.parse_args()
if __name__ == "__main__":
import logging
formatter = (
"%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d || %(message)s"
)
logging.basicConfig(format=formatter, level=logging.INFO)
args = parse_args()
import os
import numpy as np
import torch
import tqdm
import time
import pandas as pd
from tokenizer import TextTokenizer, tokenize_text # You need to provide a tokenizer module or adjust accordingly
# Define the paths
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])))
# Phonemization
logging.info("Starting phonemization...")
from phonemizer.phonemize import phonemize
from phonemizer.backend import EspeakBackend
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'),
}
# Load tokenizer (if you have a custom tokenizer, you need to implement or import it)
# For Polish phonemization, we can use phonemizer with espeak backend
# You can adjust the backend and language code if needed
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}")
# Load the Encodec model
from audiocraft.models import EncodecModel
from audiocraft.models.encodec.utils import convert_audio
# Ensure you have installed the necessary package for Encodec model
logging.info("Loading Encodec model...")
model = EncodecModel.encodec_model_24khz()
model.set_target_bandwidth(6.0)
model = model.cuda()
model.eval()
# Define dataset class
class CommonVoiceDataset(torch.utils.data.Dataset):
def __init__(self, split):
super().__init__()
tsv_file = split_files[split]
self.data_dir = data_dir
self.df = pd.read_csv(tsv_file, sep='\t')
self.audio_dir = os.path.join(self.data_dir, 'clips')
def __len__(self):
return len(self.df)
def __getitem__(self, idx):
item = self.df.iloc[idx]
path = item['path']
sentence = item['sentence']
audio_path = os.path.join(self.audio_dir, path)
try:
import soundfile as sf
waveform, sr = sf.read(audio_path)
waveform = torch.from_numpy(waveform).float()
if len(waveform.size()) > 1:
waveform = waveform.mean(dim=1) # Convert to mono
waveform = convert_audio(waveform, sr, args.model_sr, model.channels)
duration = waveform.shape[-1] / args.model_sr
return path.replace('.mp3', ''), waveform, args.model_sr, sentence, duration
except Exception as e:
logging.warning(f"Failed to load audio {audio_path}: {e}")
return None, None, None, None, None
def collate(self, batch):
res = {'path': [], "audio": [], "sr": [], "text": [], "duration": []}
for item in batch:
if item[0] is not None:
res['path'].append(item[0])
res['audio'].append(item[1])
res['sr'].append(item[2])
res['text'].append(item[3])
res['duration'].append(item[4])
return res
# Encodec codes extraction
logging.info("Starting Encodec encoding...")
datasets = {}
dataloaders = {}
for split in splits:
dataset = CommonVoiceDataset(split)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.mega_batch_size, shuffle=False, drop_last=False, num_workers=args.n_workers, collate_fn=dataset.collate)
datasets[split] = dataset
dataloaders[split] = dataloader
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 # Duration in seconds
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.append(model.encode(inwav[:len(inwav)//2])[0].cpu())
codes.append(model.encode(inwav[len(inwav)//2:])[0].cpu())
codes = torch.cat(codes, 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)) # Avoid index out of range
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.")
Notes:
- This script reads the Common Voice dataset from the specified directory, processes the text to phonemes using the
phonemizer library (which supports Polish), encodes the audio using Encodec, and saves the outputs.
- Ensure that you have the necessary modules installed:
phonemizer, pandas, tqdm, torch, soundfile, and audiocraft (for Encodec).
- Replace
"/path/to/encodec_model/checkpoint.th" with the actual path to your Encodec model checkpoint.
- Customize the paths and parameters as needed, especially
args.download_to, args.save_dir, and args.encodec_model_path.
- The script assumes that the audio files are in MP3 format in the
clips directory and that the sample rate for the model is 16000 Hz.
- The
tokenizer module (with TextTokenizer and tokenize_text) should be provided or adjusted accordingly if you have a custom tokenizer. Since we're using phonemizer, you might not need this module for phonemization.
- The processing includes error handling to skip problematic samples and logs helpful messages during processing.
Before running the script:
Running the script:
This script will process your Common Voice dataset in Polish, performing the tasks you outlined:
- Prepare speech and their transcriptions.
- Encode the speech into codes using Encodec.
- Convert transcriptions to sequences of phonemes using a phonemizer that supports the Polish language.