-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_wav2vec2.py
More file actions
192 lines (147 loc) · 4.34 KB
/
train_wav2vec2.py
File metadata and controls
192 lines (147 loc) · 4.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import os
import random
import librosa
import numpy as np
import torch
from datasets import Dataset
from transformers import (
Wav2Vec2FeatureExtractor,
Wav2Vec2ForSequenceClassification,
TrainingArguments,
Trainer
)
# =========================
# CONFIG
# =========================
BASE = "/home/aids/Downloads/HCL-DATA"
HUMAN_DIR = os.path.join(BASE, "human")
AI_DIR = os.path.join(BASE, "ai_generated")
LANGS = ["tamil","english","hindi","malayalam","telugu"]
SAMPLES_PER_LANG_PER_CLASS = 1500
MAX_SEC = 7
MODEL_NAME = "facebook/wav2vec2-large-xlsr-53"
# =========================
# AUDIO AUGMENTATIONS
# =========================
def augment_audio(y):
if random.random() < 0.5:
# random gain
y = y * random.uniform(0.8, 1.2)
if random.random() < 0.3:
# noise injection
noise = np.random.randn(len(y)) * 0.003
y = y + noise
if random.random() < 0.3:
# pitch shift
y = librosa.effects.pitch_shift(y, sr=16000, n_steps=random.uniform(-2,2))
if random.random() < 0.3:
# time stretch
rate = random.uniform(0.9, 1.1)
y = librosa.effects.time_stretch(y, rate)
return y
# =========================
# COLLECT BALANCED DATA
# =========================
data = []
for lang in LANGS:
print("Collecting:", lang)
human_files = os.listdir(f"{HUMAN_DIR}/{lang}/clips")
ai_files = os.listdir(f"{AI_DIR}/{lang}")
random.shuffle(human_files)
random.shuffle(ai_files)
human_files = human_files[:SAMPLES_PER_LANG_PER_CLASS]
ai_files = ai_files[:SAMPLES_PER_LANG_PER_CLASS]
for f in human_files:
data.append({"path": f"{HUMAN_DIR}/{lang}/clips/{f}", "label": 0})
for f in ai_files:
data.append({"path": f"{AI_DIR}/{lang}/{f}", "label": 1})
print("Total samples:", len(data))
dataset = Dataset.from_list(data)
# =========================
# FEATURE EXTRACTOR
# =========================
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_NAME)
def preprocess(example):
try:
speech, sr = librosa.load(example["path"], sr=16000)
# crop
speech = speech[:16000 * MAX_SEC]
# augment only for training
speech = augment_audio(speech)
speech = speech.astype(np.float32)
inputs = feature_extractor(
speech,
sampling_rate=16000,
return_tensors="np"
)
return {
"input_values": inputs["input_values"][0],
"label": example["label"]
}
except:
return {"input_values": None, "label": example["label"]}
dataset = dataset.map(preprocess, num_proc=4)
dataset = dataset.filter(lambda x: x["input_values"] is not None)
# =========================
# SPLIT
# =========================
split = dataset.train_test_split(test_size=0.1)
train_ds = split["train"]
test_ds = split["test"]
# =========================
# MODEL
# =========================
model = Wav2Vec2ForSequenceClassification.from_pretrained(
MODEL_NAME,
num_labels=2
)
# Freeze lower layers (critical)
model.freeze_feature_encoder()
# =========================
# TRAINING SETTINGS
# =========================
training_args = TrainingArguments(
output_dir="./FINAL_ai_voice_detector",
per_device_train_batch_size=1,
per_device_eval_batch_size=1,
gradient_accumulation_steps=8,
evaluation_strategy="epoch",
save_strategy="epoch",
num_train_epochs=7,
learning_rate=2e-6,
warmup_steps=500,
fp16=True,
logging_steps=20,
save_total_limit=2,
load_best_model_at_end=True,
metric_for_best_model="eval_loss"
)
# =========================
# TRAINER
# =========================
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_ds,
eval_dataset=test_ds,
tokenizer=feature_extractor
)
# =========================
# TRAIN
# =========================
trainer.train()
# =========================
# UNFREEZE + FINE POLISH
# =========================
print("Fine tuning full network...")
for param in model.parameters():
param.requires_grad = True
training_args.num_train_epochs = 2
training_args.learning_rate = 1e-6
trainer.train()
# =========================
# SAVE FINAL MODEL
# =========================
trainer.save_model("./FINAL_ai_voice_detector")
feature_extractor.save_pretrained("./FINAL_ai_voice_detector")
print("ULTIMATE MODEL READY")