ASLP-lab commited on
Commit
1798e4b
·
1 Parent(s): e51b59c
Files changed (2) hide show
  1. README.md +201 -0
  2. checkpoint.pt +3 -0
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+ ## Emotion2Vec-S
5
+
6
+ For more information, please refer to github [C2SER](https://github.com/zxzhao0/C2SER)
7
+
8
+ ## Emotion2Vec-S
9
+
10
+ ## Introduction
11
+
12
+ This repository contains the implementation of Emotion2Vec-S, a self-supervised learning (SSL) model for speech emotion recognition, as presented in our paper "Steering Language Model to Stable Speech Emotion Recognition via Contextual Perception and Chain of Thought".
13
+
14
+ ## Requirements and Installation
15
+
16
+ This project follows the fairseq installation process.
17
+
18
+ ### Requirements
19
+
20
+ - PyTorch version >= 1.10.0
21
+ - Python version >= 3.8
22
+
23
+ ### Installation
24
+
25
+ To install fairseq and develop locally:
26
+
27
+ ```bash
28
+ git clone https://github.com/pytorch/fairseq
29
+ cd fairseq
30
+ pip install --editable ./
31
+ ```
32
+
33
+ ### Feature Extraction
34
+
35
+ You can download the pre-trained [Emotion2vec-S model](https://drive.google.com/drive/folders/1LWWi6bahzn7fJP4fCgPleOyQ30sD_BWO?usp=drive_link) and put it in the `./Emotion2Vec-S/ckpt` folder.
36
+ Meanwhile,we have provided the pretrained checkpoints in the huggingface model hub. You can also download ckpt file from [here](https://huggingface.co/ASLP-lab/Emotion2Vec-S). We also provide [here](https://drive.google.com/drive/folders/12AOVJT7I9GSLJnjHa-Elc-UKgog-mZR2) the feature files for the Emo-Emilia dataset extracted using Emotion2vec-S.
37
+
38
+ If you want to extract features using Emotion2Vec-S,you will also need to provide a `wav.scp` file and place it in the `./Emotion2Vec-S` directory. Here is an example of the `wav.scp` file::
39
+ ```pgsql
40
+ audio_name1 /path/to/audio_name1.wav
41
+ audio_name2 /path/to/audio_name2.wav
42
+ audio_name3 /path/to/audio_name3.wav
43
+ ```
44
+
45
+ Next, you can directly run the following code to extract features:
46
+ ```python
47
+ import torch
48
+ import os
49
+ import sys
50
+ import json
51
+ import numpy as np
52
+ import argparse
53
+ from tqdm import tqdm
54
+ import torchaudio
55
+ import torch.nn.functional as F
56
+ import fairseq
57
+ from dataclasses import dataclass
58
+
59
+ SAMPLING_RATE=16000
60
+
61
+ @dataclass
62
+ class UserDirModule:
63
+ user_dir: str
64
+
65
+ def extract_fairseq_feature(wav_path, model, device):
66
+ try:
67
+ wav, sr = torchaudio.load(wav_path)
68
+ # 合并多声道为单声道(取平均)
69
+ if wav.size(0) > 1:
70
+ wav = torch.mean(wav, dim=0, keepdim=True)
71
+ if sr != SAMPLING_RATE:
72
+ wav = torchaudio.functional.resample(wav, sr, SAMPLING_RATE)
73
+ wav = wav[0, :].view(1, -1)
74
+ wav = wav.to(device)
75
+ out = model.extract_features(wav)
76
+ return out
77
+ except Exception as e:
78
+ print(f"Error processing audio file {wav_path}: {e}")
79
+ return None
80
+
81
+ if __name__ == '__main__':
82
+
83
+ parser = argparse.ArgumentParser()
84
+ parser.add_argument('--model_path', type=str, default="./Emotion2Vec-S/ckpt/checkpoint.pt")
85
+ parser.add_argument('--model_dir', type=str, default="./Emotion2Vec-S/examples/data2vec/")
86
+ parser.add_argument('--dump_dir', type=str, default="./Emotion2Vec-S/features_frm")
87
+ parser.add_argument('--device', type=str, default='cuda')
88
+ parser.add_argument('--data', type=str, default="./Emotion2Vec-S/wav.scp")
89
+ parser.add_argument('--level', type=str, default="frame", help="frame or utterance")
90
+ args = parser.parse_args()
91
+
92
+ data = {}
93
+ with open(args.data, 'r') as f:
94
+ for line in f:
95
+ seg_id, wav_path = line.strip().split(maxsplit=1)
96
+ data[seg_id] = wav_path
97
+
98
+ os.makedirs(args.dump_dir, exist_ok=True)
99
+
100
+ seg_ids = data.keys()
101
+ print(f'Loaded {len(seg_ids)} audio entries')
102
+ # load models
103
+ my_model_path = UserDirModule(args.model_dir)
104
+ fairseq.utils.import_user_module(my_model_path)
105
+ model, cfg, task = fairseq.checkpoint_utils.load_model_ensemble_and_task([args.model_path])
106
+ model = model[0].to(args.device)
107
+
108
+ for seg_id in tqdm(seg_ids):
109
+
110
+ wav_path = data[seg_id]
111
+ if not os.path.exists(wav_path):
112
+ print(f"WARNING: {wav_path} does not exist")
113
+ continue
114
+ try:
115
+ torchaudio.load(wav_path)
116
+ except:
117
+ print(f'ERROR: Failed to load {wav_path}')
118
+ continue
119
+
120
+ feat = extract_fairseq_feature(wav_path, model, args.device)
121
+
122
+ if feat is not None:
123
+ if args.level == 'frame':
124
+ feat = feat['x'].cpu().detach().numpy()[0]
125
+ elif args.level == 'utterance':
126
+ feat = feat['utt_x'].cpu().detach().numpy()[0]
127
+ else:
128
+ raise ValueError("Unknown level: {}".format(args.level))
129
+
130
+ save_path = os.path.join(args.dump_dir, f"{seg_id}.npy")
131
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
132
+ np.save(save_path, feat)
133
+ print(f"Processed: {seg_id} | Shape: {feat.shape} | Saved to: {save_path}")
134
+ else:
135
+ print(f"Skipped problematic file: {seg_id}")
136
+
137
+ ```
138
+ Alternatively, you can adjust the code according to your needs. The code path is `./Emotion2Vec-S/speech_feature_extraction.py`. You can also use the `./Emotion2Vec-S/extract_feature.sh` script to batch process features for multiple datasets. The script supports parallel processing and offers the following parameters:
139
+
140
+ - `--model_path`: Path to the checkpoint file
141
+ - `--model_dir`: Path to the model
142
+ - `--dump_dir`: Directory to save extracted features
143
+ - `--device`: Device to run the model on (e.g., 'cuda:0')
144
+ - `--data`: Path to the dataset scp file
145
+ - `--level`: Level of feature (frame level or utterance level)
146
+
147
+ ## 2. Training and testing on EmoBox using extracted features
148
+
149
+ If you want to test our model on other datasets using [EmoBox](https://github.com/emo-box/EmoBox/tree/main). There is also an example provided below, which you can modify to suit your needs:
150
+
151
+ Use k-fold cross-validation with learning rates (1e-3, 1e-4) and hidden sizes (128, 256):
152
+
153
+ ```bash
154
+ cd examples/sb
155
+ data=/path/to/your/data_files
156
+ lrs=(1e-3 1e-4) # Learning rate list
157
+ hidden_sizes=(128 256) # Hidden size list
158
+ gpus=(0 1 2 3) # GPU list
159
+ task_id=0
160
+ declare -A dataset_folds=(
161
+ ["mesd"]=1
162
+ )
163
+ declare -A dataset_classes=(
164
+ ["mesd"]=6
165
+ )
166
+ datasets=("mesd")
167
+
168
+ for dataset in "${datasets[@]}"; do
169
+ folds=${dataset_folds[$dataset]}
170
+ n_classes=${dataset_classes[$dataset]}
171
+
172
+ for lr in "${lrs[@]}"; do
173
+ for hidden_size in "${hidden_sizes[@]}"; do
174
+ gpu=${gpus[$task_id % ${#gpus[@]}]}
175
+ export CUDA_VISIBLE_DEVICES=$gpu
176
+ task_number=$((task_id + 1))
177
+ for fold in $(seq 1 $folds); do
178
+ echo "Training fold $fold with lr=$lr, hidden_size=$hidden_size on GPU $gpu, task_number=$task_number, dataset=$dataset..."
179
+ python3 train.py \
180
+ hparams/data2vec2-large_freeze.yaml \
181
+ --output_folder /path/to/your/${dataset}-S/fold${fold}_lr${lr}_hidden${hidden_size} \
182
+ --seed 1234 \
183
+ --batch_size 32 \
184
+ --lr $lr \
185
+ --train_annotation ${data}/${dataset}/fold_${fold}/${dataset}_train_fold_${fold}.json \
186
+ --test_annotation ${data}/${dataset}/fold_${fold}/${dataset}_test_fold_${fold}.json \
187
+ --number_of_epochs 100 \
188
+ --feat_dir /path/to/your/dump_${dataset}-S \
189
+ --label_map ${data}/${dataset}/label_map.json \
190
+ --device cuda \
191
+ --out_n_neurons ${n_classes} \
192
+ --hidden_size $hidden_size &
193
+ done
194
+ task_id=$((task_id + 1))
195
+ done
196
+ done
197
+ done
198
+
199
+ wait
200
+ echo "All training tasks completed."
201
+ ```
checkpoint.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:411cefa265f1e138744ea7102546ece71df6e1873b8c7db0c8938c4ebf2608bd
3
+ size 1132759210