Commit
·
b778085
1
Parent(s):
d22e86b
Upload main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model, Wav2Vec2Processor, Wav2Vec2CTCTokenizer
|
| 2 |
+
import torchaudio
|
| 3 |
+
import torch
|
| 4 |
+
from huggingface_hub import notebook_login
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
import re
|
| 7 |
+
from transformers import Wav2Vec2ForCTC
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
|
| 10 |
+
organization_name = "ASR-Erzya-Final-Project"
|
| 11 |
+
#organization_name = "zmmccormick3"
|
| 12 |
+
dataset_name = "asr_erzya_final_data"
|
| 13 |
+
|
| 14 |
+
dataset = load_dataset(f"{organization_name}/{dataset_name}")
|
| 15 |
+
|
| 16 |
+
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 17 |
+
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
|
| 18 |
+
|
| 19 |
+
#://huggingface.co/datasets/ASR-Erzya-Final-Project/asr_erzya_final_data/tree/main
|
| 20 |
+
|
| 21 |
+
def preprocess_data(batch):
|
| 22 |
+
inputs = processor(batch["audio"], return_tensors="pt", sampling_rate=16000)
|
| 23 |
+
targets = processor(batch["text"], return_tensors="pt", padding=True)
|
| 24 |
+
|
| 25 |
+
# Ensure that target tensor is of shape (batch_size, sequence_length)
|
| 26 |
+
targets["input_ids"] = targets["input_ids"].unsqueeze(0)
|
| 27 |
+
|
| 28 |
+
return inputs, targets
|
| 29 |
+
|
| 30 |
+
# Create DataLoader for training data
|
| 31 |
+
train_data_loader = DataLoader(dataset["train"], batch_size=4, collate_fn=preprocess_data)
|
| 32 |
+
|
| 33 |
+
# Training loop
|
| 34 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 35 |
+
model.to(device)
|
| 36 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
|
| 37 |
+
|
| 38 |
+
for epoch in range(5): # Set the number of epochs you want to train for
|
| 39 |
+
model.train()
|
| 40 |
+
for batch in train_data_loader:
|
| 41 |
+
inputs, targets = batch
|
| 42 |
+
inputs = {key: value.to(device) for key, value in inputs.items()}
|
| 43 |
+
targets = {key: value.to(device) for key, value in targets.items()}
|
| 44 |
+
|
| 45 |
+
optimizer.zero_grad()
|
| 46 |
+
outputs = model(**inputs, labels=targets["input_ids"])
|
| 47 |
+
loss = outputs.loss
|
| 48 |
+
loss.backward()
|
| 49 |
+
optimizer.step()
|
| 50 |
+
|
| 51 |
+
# Save the trained model
|
| 52 |
+
model.save_pretrained("your-organization/your-wav2vec-ctc-model")
|
| 53 |
+
processor.save_pretrained("your-organization/your-wav2vec-ctc-model")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
#common_voice_train = load_dataset(f"{organization_name}/{dataset_name}", split="train")
|
| 57 |
+
#common_voice_test = load_dataset(f"{organization_name}/{dataset_name}", split="test")
|
| 58 |
+
|
| 59 |
+
# notebook_login()
|
| 60 |
+
|
| 61 |
+
common_voice_train = load_dataset("common_voice", "myv", split="train")
|
| 62 |
+
common_voice_test = load_dataset("common_voice", "myv", split="test")
|
| 63 |
+
|
| 64 |
+
# Remove unnecessary columns
|
| 65 |
+
common_voice_train = common_voice_train.remove_columns(["accent", "age", "client_id", "down_votes", "gender", "locale", "segment", "up_votes"])
|
| 66 |
+
common_voice_test = common_voice_test.remove_columns(["accent", "age", "client_id", "down_votes", "gender", "locale", "segment", "up_votes"])
|
| 67 |
+
|
| 68 |
+
chars_to_remove_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\']'
|
| 69 |
+
|
| 70 |
+
def remove_special_characters(batch):
|
| 71 |
+
batch["sentence"] = re.sub(chars_to_remove_regex, '', batch["sentence"]).lower()
|
| 72 |
+
return batch
|
| 73 |
+
|
| 74 |
+
common_voice_train = common_voice_train.map(remove_special_characters)
|
| 75 |
+
common_voice_test = common_voice_test.map(remove_special_characters)
|
| 76 |
+
|
| 77 |
+
def replace_hatted_characters(batch):
|
| 78 |
+
batch["sentence"] = re.sub('[â]', 'a', batch["sentence"])
|
| 79 |
+
# Add similar lines for other hat characters if needed
|
| 80 |
+
return batch
|
| 81 |
+
|
| 82 |
+
common_voice_train = common_voice_train.map(replace_hatted_characters)
|
| 83 |
+
common_voice_test = common_voice_test.map(replace_hatted_characters)
|
| 84 |
+
|
| 85 |
+
def extract_all_chars(batch):
|
| 86 |
+
all_text = " ".join(batch["sentence"])
|
| 87 |
+
vocab = list(set(all_text))
|
| 88 |
+
return {"vocab": [vocab], "all_text": [all_text]}
|
| 89 |
+
|
| 90 |
+
vocab_train = common_voice_train.map(extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=common_voice_train.column_names)
|
| 91 |
+
vocab_test = common_voice_test.map(extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=common_voice_test.column_names)
|
| 92 |
+
|
| 93 |
+
vocab_list = list(set(vocab_train["vocab"][0]) | set(vocab_test["vocab"][0]))
|
| 94 |
+
vocab_dict = {v: k for k, v in enumerate(sorted(vocab_list))}
|
| 95 |
+
vocab_dict["|"] = vocab_dict[" "]
|
| 96 |
+
del vocab_dict[" "]
|
| 97 |
+
vocab_dict["[UNK]"] = len(vocab_dict)
|
| 98 |
+
vocab_dict["[PAD]"] = len(vocab_dict)
|
| 99 |
+
|
| 100 |
+
import json
|
| 101 |
+
with open('vocab.json', 'w') as vocab_file:
|
| 102 |
+
json.dump(vocab_dict, vocab_file)
|
| 103 |
+
|
| 104 |
+
tokenizer = Wav2Vec2CTCTokenizer.from_pretrained("./", unk_token="[UNK]", pad_token="[PAD]", word_delimiter_token="|")
|
| 105 |
+
|
| 106 |
+
repo_name = "wav2vec2-large-xls-r-300m-tr-colab" # TK repository name
|
| 107 |
+
tokenizer.push_to_hub(repo_name)
|
| 108 |
+
|
| 109 |
+
# tokenizer = Wav2Vec2CTCTokenizer.from_pretrained() # TK
|
| 110 |
+
# feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def downsample(batch):
|
| 114 |
+
resample = torchaudio.transforms.Resample(orig_freq=48_000, new_freq=16_000)
|
| 115 |
+
batch["audio"] = resample(batch["audio"])
|
| 116 |
+
return batch
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
common_voice_train = common_voice_train.map(downsample)
|
| 120 |
+
common_voice_test = common_voice_test.map(downsample)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
feature_extractor = Wav2Vec2FeatureExtractor(feature_size=1, sampling_rate=16000, padding_value=0.0, do_normalize=True, return_attention_mask=True)
|
| 124 |
+
# processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 125 |
+
processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
|
| 126 |
+
|
| 127 |
+
'''
|
| 128 |
+
model = Wav2Vec2Model.from_pretrained("Link/to/HuggingfaceModel")
|
| 129 |
+
array, fs = torchaudio.load("/Local/link/to/your/audio.wav"
|
| 130 |
+
input_input = processor(array.squeeze(), sampling_rate=fs, return_tensors="pt")
|
| 131 |
+
with torch.no_grad():
|
| 132 |
+
outputs = model(**input_input)
|
| 133 |
+
print(f"Hidden state shape: {outputs.last_hidden_state.numpy().shape}")
|
| 134 |
+
'''
|