junnei commited on
Commit
b91ae85
Β·
verified Β·
1 Parent(s): 1966d65

Upload evaluate_speech.py

Browse files
Files changed (1) hide show
  1. examples/evaluate_speech.py +435 -0
examples/evaluate_speech.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from urllib.request import urlopen
3
+ import soundfile
4
+ import torch
5
+ from datasets import load_dataset, Audio
6
+ import numpy as np
7
+ from transformers import AutoModel, AutoProcessor, BatchFeature
8
+ from tqdm import tqdm
9
+ import json
10
+ import os
11
+ import time
12
+ from datetime import datetime
13
+ from whisper_normalizer.english import EnglishTextNormalizer
14
+ from whisper_normalizer.basic import BasicTextNormalizer
15
+ import sacrebleu
16
+ from jiwer import cer, wer
17
+ from torch.utils.data import Dataset, DataLoader
18
+ import soundfile as sf
19
+ import re
20
+
21
+ normalizer = {
22
+ "en_us" : EnglishTextNormalizer(),
23
+ "ko_kr" : BasicTextNormalizer()
24
+ }
25
+
26
+ # λͺ¨λΈ 및 ν”„λ‘œμ„Έμ„œ λ‘œλ“œ
27
+ model_id = "junnei/gemma-3-4b-it-speech"
28
+ revision = "v1.0"
29
+
30
+ model = AutoModel.from_pretrained(
31
+ model_id, device_map="auto", revision = revision, trust_remote_code=True
32
+ ).eval()
33
+
34
+ processor = AutoProcessor.from_pretrained(
35
+ model_id, revision = revision, trust_remote_code=True
36
+ )
37
+
38
+ # κ²°κ³Ό μ €μž₯ 디렉토리 생성
39
+ results_dir = f"evaluation_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
40
+ os.makedirs(results_dir, exist_ok=True)
41
+
42
+
43
+ INSTRUCTION = {
44
+ "ast": "Translate the audio to {0}.",
45
+ "asr": "Transcribe the audio clip into text.",
46
+ }
47
+
48
+ class CoVoSTDataset(Dataset):
49
+ def __init__(self, processor, data_dir, ast=False,
50
+ lang=("en_ko", "Korean")):
51
+ self.data = load_dataset("junnei/covost2",
52
+ lang[0],
53
+ data_dir=data_dir,
54
+ split='test',
55
+ trust_remote_code=True
56
+ )
57
+
58
+ original_size = len(self.data)
59
+ self.data = self.data.cast_column("audio", Audio(decode=False))
60
+
61
+ def identify_corrupted_files(example):
62
+ try:
63
+ # λ””μ½”λ”© μ‹œλ„
64
+ sf.read(example["audio"]["path"])
65
+ if example['translation'] == "" or example['sentence'] == "":
66
+ return False
67
+ return True
68
+ except Exception:
69
+ return False
70
+
71
+ self.data = self.data.filter(identify_corrupted_files, num_proc=16)
72
+ validated_size = len(self.data)
73
+ self.data = self.data.cast_column("audio", Audio(sampling_rate = 16000, decode=True))
74
+
75
+ self.lang = lang[0]
76
+ self.ast = ast
77
+
78
+ print(f"- {self.lang}: {('AST' if self.ast else 'ASR')}")
79
+ print(f"원본 데이터 개수: {original_size}")
80
+ print(f"μ—λŸ¬ 데이터 개수: {original_size - validated_size}")
81
+ print(f"필터링 λΉ„μœ¨: {validated_size/original_size:.2%}")
82
+
83
+ self.processor = processor
84
+ self.instruction = INSTRUCTION["ast"].format(lang[1]) if ast else INSTRUCTION["asr"]
85
+
86
+ def __len__(self):
87
+ return len(self.data)
88
+
89
+ def __getitem__(self, idx):
90
+ data = self.data[idx]
91
+ user_message = {
92
+ 'role': 'user',
93
+ 'content': '<start_of_audio>' + self.instruction,
94
+ }
95
+ prompt = self.processor.tokenizer.apply_chat_template(
96
+ [user_message], tokenize=False, add_generation_prompt=True, add_bos=True
97
+ )
98
+ inputs = self.processor(text=prompt, audio=[data["audio"]["array"]], add_special_tokens=False, return_tensors='pt')
99
+ sentence = data['sentence'].replace('"', '')
100
+ answer = f"{data['translation'] if self.ast else sentence}"
101
+
102
+ return {
103
+ 'input_ids': inputs.input_ids,
104
+ 'attention_mask': inputs.attention_mask,
105
+ 'token_type_ids': inputs.token_type_ids,
106
+ 'input_modes': inputs.input_modes,
107
+ 'input_audio_embeds': inputs.input_audio_embeds,
108
+ 'audio_embed_sizes': inputs.audio_embed_sizes,
109
+ 'sentence': sentence,
110
+ 'answer': answer,
111
+ }
112
+
113
+ def select(self, indices):
114
+ self.data = self.data.select(indices)
115
+ return self
116
+
117
+ def pad_sequence(sequences, padding_side='right', padding_value=0):
118
+ """
119
+ Pad a list of sequences to the same length.
120
+ sequences: list of tensors in [seq_len, *] shape
121
+ """
122
+ assert padding_side in ['right', 'left']
123
+ max_size = sequences[0].size()
124
+ trailing_dims = max_size[1:]
125
+ max_len = max(len(seq) for seq in sequences)
126
+ batch_size = len(sequences)
127
+ output = sequences[0].new_full((batch_size, max_len) + trailing_dims, padding_value)
128
+ for i, seq in enumerate(sequences):
129
+ length = seq.size(0)
130
+ if padding_side == 'right':
131
+ output.data[i, :length] = seq
132
+ else:
133
+ output.data[i, -length:] = seq
134
+ return output
135
+
136
+ def cat_with_pad(tensors, dim, padding_value=0):
137
+ """
138
+ cat along dim, while pad to max for all other dims
139
+ """
140
+ ndim = tensors[0].dim()
141
+ assert all(
142
+ t.dim() == ndim for t in tensors[1:]
143
+ ), 'All tensors must have the same number of dimensions'
144
+
145
+ out_size = [max(t.shape[i] for t in tensors) for i in range(ndim)]
146
+ out_size[dim] = sum(t.shape[dim] for t in tensors)
147
+ output = tensors[0].new_full(out_size, padding_value)
148
+
149
+ index = 0
150
+ for t in tensors:
151
+ # Create a slice list where every dimension except dim is full slice
152
+ slices = [slice(0, t.shape[d]) for d in range(ndim)]
153
+ # Update only the concat dimension slice
154
+ slices[dim] = slice(index, index + t.shape[dim])
155
+
156
+ output[slices] = t
157
+ index += t.shape[dim]
158
+
159
+ return output
160
+
161
+ def covost_collate_fn(batch):
162
+ input_ids_list = []
163
+ input_audio_embeds_list = []
164
+ audio_embed_sizes_list = []
165
+ audio_attention_mask_list = []
166
+ input_modes_list = []
167
+ sentence_list = []
168
+ answer_list = []
169
+ for inputs in batch:
170
+ input_ids_list.append(inputs['input_ids'][0])
171
+ input_audio_embeds_list.append(inputs['input_audio_embeds'])
172
+ audio_embed_sizes_list.append(inputs['audio_embed_sizes'])
173
+ audio_attention_mask_list.append(
174
+ inputs['input_audio_embeds'].new_full((inputs['input_audio_embeds'].size(1),), True, dtype=torch.bool)
175
+ )
176
+ input_modes_list.append(inputs['input_modes'])
177
+ sentence_list.append(inputs['sentence'])
178
+ answer_list.append(inputs['answer'])
179
+
180
+ try:
181
+ input_ids = pad_sequence(input_ids_list, padding_side='left', padding_value=0)
182
+ audio_attention_mask = (
183
+ pad_sequence(audio_attention_mask_list, padding_side='right', padding_value=False)
184
+ if len(audio_attention_mask_list) > 1
185
+ else None
186
+ )
187
+ except Exception as e:
188
+ print(e)
189
+ print(input_ids_list)
190
+ print(audio_attention_mask)
191
+ raise
192
+ attention_mask = (input_ids != 0).long()
193
+ input_audio_embeds = cat_with_pad(input_audio_embeds_list, dim=0)
194
+ audio_embed_sizes = torch.cat(audio_embed_sizes_list)
195
+ input_modes = torch.cat(input_modes_list)
196
+
197
+ return BatchFeature(
198
+ {
199
+ 'input_ids': input_ids,
200
+ 'attention_mask': attention_mask,
201
+ 'input_audio_embeds': input_audio_embeds,
202
+ 'audio_embed_sizes': audio_embed_sizes,
203
+ 'audio_attention_mask': audio_attention_mask,
204
+ 'input_modes': input_modes,
205
+ 'sentence': sentence_list,
206
+ 'answer': answer_list,
207
+ }
208
+ )
209
+
210
+ def save_results(results, task, source_lang, target_lang=None, sample_idx=None):
211
+ """κ²°κ³Όλ₯Ό JSON 파일둜 μ €μž₯"""
212
+ filename = f"{task}_{source_lang}"
213
+ if target_lang:
214
+ filename += f"_to_{target_lang}"
215
+ if sample_idx is not None:
216
+ filename += f"_sample_{sample_idx}"
217
+
218
+ filepath = os.path.join(results_dir, f"{filename}.json")
219
+
220
+ # 결과에 νƒ€μž„μŠ€νƒ¬ν”„ μΆ”κ°€
221
+ results["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
222
+
223
+ with open(filepath, 'w', encoding='utf-8') as f:
224
+ json.dump(results, f, ensure_ascii=False, indent=2)
225
+
226
+ print(f"κ²°κ³Όκ°€ {filepath}에 μ €μž₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
227
+ return filepath
228
+
229
+ def evaluate_task(dataset, source_lang, target_lang, num_samples=-1, batch_size = 32, is_asr=True):
230
+ """ASR(μžλ™ μŒμ„± 인식) μ„±λŠ₯ 평가"""
231
+ task_type = "asr" if is_asr else "translation"
232
+ eval_lang = source_lang if is_asr else target_lang
233
+ eval_normalizer = normalizer[eval_lang]
234
+ sample_results = []
235
+
236
+ # μƒ˜ν”Œ 수 처리
237
+ if num_samples > 0 and num_samples < len(dataset):
238
+ indices = np.random.choice(len(dataset), num_samples, replace=False)
239
+ dataset = dataset.select(indices)
240
+
241
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=covost_collate_fn)
242
+
243
+ evaluated_samples = {}
244
+
245
+ # 배치 λ‹¨μœ„λ‘œ 처리
246
+ for batch_idx, batch in enumerate(tqdm(dataloader)):
247
+ batch_sentences = batch.pop("sentence")
248
+ batch_references = batch.pop("answer")
249
+
250
+ # GPU둜 이동
251
+ if torch.cuda.is_available():
252
+ batch = {k: v.to("cuda") for k, v in batch.items()}
253
+
254
+ # 배치 μΆ”λ‘ 
255
+ with torch.inference_mode():
256
+ generate_ids = model.generate(**batch, max_new_tokens=256, do_sample=False)
257
+
258
+ input_lengths = batch['input_ids'].shape[1]
259
+ generate_ids = generate_ids[:, input_lengths:]
260
+
261
+ # λ””μ½”λ”©
262
+ batch_predictions = processor.batch_decode(
263
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
264
+ )
265
+
266
+ # κ²°κ³Ό μ €μž₯
267
+ for i, (sentence, reference, prediction) in enumerate(zip(batch_sentences, batch_references, batch_predictions)):
268
+ idx = batch_idx * batch_size + i
269
+ sample_result = {
270
+ "id": idx,
271
+ "sentence": sentence,
272
+ "reference": reference,
273
+ "prediction": prediction
274
+ }
275
+ sample_results.append(sample_result)
276
+
277
+ # 10λ°°μΉ˜λ§ˆλ‹€ 쀑간 κ²°κ³Ό μ €μž₯
278
+ if (batch_idx + 1) % 10 == 0:
279
+ temp_results = []
280
+
281
+ # λͺ¨λ“  μƒ˜ν”Œμ— λŒ€ν•΄ 처리
282
+ for item in sample_results:
283
+ sample_id = item["id"]
284
+
285
+ # 이미 ν‰κ°€λœ μƒ˜ν”Œμ€ 평가 κ²°κ³Όλ₯Ό μž¬μ‚¬μš©
286
+ if sample_id in evaluated_samples:
287
+ temp_item = item.copy()
288
+ temp_item.update(evaluated_samples[sample_id])
289
+ temp_results.append(temp_item)
290
+ else:
291
+ # 아직 ν‰κ°€λ˜μ§€ μ•Šμ€ μƒ˜ν”Œμ€ μƒˆλ‘œ 평가
292
+ temp_item = item.copy()
293
+ try:
294
+ ref = eval_normalizer(item["reference"])
295
+ pred = eval_normalizer(item["prediction"])
296
+
297
+ # BLEU, WER/CER 계산
298
+ utt_bleu = sacrebleu.sentence_bleu(pred, [ref]).score
299
+ utt_cer = round(cer(re.sub(r"\s+", "", ref), re.sub(r"\s+", "", pred)) * 100, 2)
300
+ utt_wer = round(wer(ref, pred) * 100, 2)
301
+
302
+ metrics = {
303
+ "bleu": utt_bleu,
304
+ "cer": utt_cer,
305
+ "wer": utt_wer
306
+ }
307
+
308
+ # 평가 κ²°κ³Ό μ €μž₯
309
+ evaluated_samples[sample_id] = metrics
310
+ temp_item.update(metrics)
311
+ except Exception as e:
312
+ print(f"Error evaluating sample {sample_id}: {e}")
313
+ # 였λ₯˜ λ°œμƒ μ‹œ κΈ°λ³Έκ°’ μ„€μ •
314
+ metrics = {
315
+ "bleu": 0,
316
+ "cer": 100,
317
+ "wer": 100,
318
+ "error": str(e)
319
+ }
320
+ evaluated_samples[sample_id] = metrics
321
+ temp_item.update(metrics)
322
+
323
+ temp_results.append(temp_item)
324
+
325
+ partial_results = {
326
+ "task": task_type,
327
+ "source_lang": source_lang,
328
+ "target_lang": target_lang,
329
+ "num_samples": len(temp_results),
330
+ "sample_results": temp_results
331
+ }
332
+ save_results(partial_results, task_type, source_lang, target_lang)
333
+
334
+ for item in sample_results:
335
+ ref = eval_normalizer(item["reference"])
336
+ pred = eval_normalizer(item["prediction"])
337
+
338
+ # BLEU, WER/CER 계산
339
+ utt_bleu = sacrebleu.sentence_bleu(pred, [ref]).score
340
+ utt_cer = round(cer(re.sub(r"\s+", "", ref), re.sub(r"\s+", "", pred)) * 100, 2)
341
+ utt_wer = round(wer(ref, pred) * 100, 2)
342
+
343
+ item.update({
344
+ "bleu": utt_bleu,
345
+ "cer": utt_cer,
346
+ "wer": utt_wer
347
+ })
348
+
349
+ avg_bleu = sum(item["bleu"] for item in sample_results) / len(sample_results)
350
+ avg_cer = sum(item["cer"] for item in sample_results) / len(sample_results)
351
+ avg_wer = sum(item["wer"] for item in sample_results) / len(sample_results)
352
+
353
+ results = {
354
+ "task": task_type,
355
+ "source_lang": source_lang,
356
+ "target_lang": target_lang,
357
+ "num_samples": len(sample_results),
358
+ "metrics": {
359
+ "bleu": avg_bleu,
360
+ "cer": avg_cer,
361
+ "wer": avg_wer
362
+ },
363
+ "sample_results": sample_results
364
+ }
365
+
366
+ # μ΅œμ’… κ²°κ³Ό μ €μž₯
367
+ save_results(results, task_type, source_lang, target_lang)
368
+ return results
369
+
370
+ # 메인 μ‹€ν–‰ μ½”λ“œ
371
+ if __name__ == "__main__":
372
+ # 평가할 μ–Έμ–΄ λͺ©λ‘ (μ†ŒμŠ€ μ–Έμ–΄)
373
+ source_languages = [
374
+ ("en_us", "English"), # μ˜μ–΄ (λ―Έκ΅­)
375
+ #("ko_kr", "Korean"),
376
+ ]
377
+
378
+ # λ²ˆμ—­ λŒ€μƒ μ–Έμ–΄ λͺ©λ‘ (μ½”λ“œ, 이름)
379
+ target_languages = [
380
+ ("ko_kr", "Korean"),
381
+ #("en_us", "English"),
382
+ ]
383
+
384
+ data_dir = {
385
+ "en_us" : "/workspace/CommonVoice/EN",
386
+ #"ko_kr" : "/workspace/CommonVoice/ko",
387
+ }
388
+
389
+ # μƒ˜ν”Œ 수 μ„€μ • (-1은 전체 데이터셋 μ‚¬μš©)
390
+ num_samples = -1
391
+ batch_size = 16
392
+
393
+ # λͺ¨λ“  μ†ŒμŠ€ 언어에 λŒ€ν•΄ ASR 평가
394
+ for source_lang, target_lang in zip(source_languages, target_languages):
395
+ print(f"\n===== {source_lang[0]} ASR 평가 μ‹œμž‘ =====")
396
+
397
+ # 데이터셋 λ‘œλ“œ
398
+ covost = CoVoSTDataset(processor, data_dir[source_lang[0]], ast=False, lang=(f"{source_lang[0].split('_')[0]}_{target_lang[0].split('_')[0]}", f"{target_lang[1]}"))
399
+
400
+ # ASR 평가
401
+ asr_results = evaluate_task(covost, source_lang[0], target_lang[0], num_samples, batch_size=batch_size, is_asr = True)
402
+
403
+ print(f"\n=== {source_lang[0]} ASR κ²°κ³Ό ===")
404
+ print(f"BLEU: {asr_results.get('metrics', {}).get('bleu', 'N/A')}")
405
+ print(f"WER: {asr_results.get('metrics', {}).get('wer', 'N/A')}")
406
+ print(f"CER: {asr_results.get('metrics', {}).get('cer', 'N/A')}")
407
+
408
+ try:
409
+ print(f"\n===== {source_lang[0]} -> {target_lang[0]} λ²ˆμ—­ 평가 μ‹œμž‘ =====")
410
+
411
+ # 데이터셋 λ‘œλ“œ
412
+ covost = CoVoSTDataset(processor, data_dir[source_lang[0]], ast=True, lang=(f"{source_lang[0].split('_')[0]}_{target_lang[0].split('_')[0]}", f"{target_lang[1]}"))
413
+
414
+ # λ²ˆμ—­ 평가
415
+ translation_results = evaluate_task(covost, source_lang[0], target_lang[0], num_samples, batch_size=batch_size, is_asr = False)
416
+
417
+ print(f"\n=== {source_lang[0]} -> {target_lang[0]} λ²ˆμ—­ κ²°κ³Ό ===")
418
+ print(f"BLEU: {translation_results.get('metrics', {}).get('bleu', 'N/A')}")
419
+ print(f"WER: {translation_results.get('metrics', {}).get('wer', 'N/A')}")
420
+ print(f"CER: {translation_results.get('metrics', {}).get('cer', 'N/A')}")
421
+
422
+ except Exception as e:
423
+ error_info = {
424
+ "error": str(e),
425
+ "source_lang": source_lang[0],
426
+ "target_lang": target_lang[0],
427
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
428
+ }
429
+ error_file = os.path.join(results_dir, f"error_translation_{source_lang[0]}_to_{target_lang[0]}_global.json")
430
+ with open(error_file, 'w') as f:
431
+ json.dump(error_info, f, indent=2)
432
+ print(f"{source_lang[0]} -> {target_lang[0]} λ²ˆμ—­ 평가 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
433
+ continue
434
+
435
+ print(f"\nλͺ¨λ“  평가가 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. κ²°κ³ΌλŠ” {results_dir} 디렉토리에 μ €μž₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")