HK0712 commited on
Commit
f70e266
·
1 Parent(s): 67ff0ae

ADD: PT_BR

Browse files
Files changed (2) hide show
  1. analyzer/ASR_nl_nl.py +6 -2
  2. analyzer/ASR_pt_br.py +273 -0
analyzer/ASR_nl_nl.py CHANGED
@@ -198,8 +198,12 @@ def _format_to_json_structure(alignments, sentence, original_words) -> dict:
198
  "sentence": sentence,
199
  "analysisTimestampUTC": datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S (UTC)'),
200
  "summary": {
201
- "overallScore": round(overall_score, 1), "totalWords": total_words, "correctWords": correct_words_count,
202
- "phonemeErrorRate": round(phoneme_error_rate, 2), "total_errors": total_errors, "total_target_phonemes": total_phonemes
 
 
 
 
203
  },
204
  "words": words_data
205
  }
 
198
  "sentence": sentence,
199
  "analysisTimestampUTC": datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S (UTC)'),
200
  "summary": {
201
+ "overallScore": round(overall_score, 1),
202
+ "totalWords": total_words,
203
+ "correctWords": correct_words_count,
204
+ "phonemeErrorRate": round(phoneme_error_rate, 2),
205
+ "total_errors": total_errors,
206
+ "total_target_phonemes": total_phonemes
207
  },
208
  "words": words_data
209
  }
analyzer/ASR_pt_br.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =======================================================================
2
+ # 1. 匯入區 (Imports)
3
+ # - 與英文版完全相同,因為我們使用相同的工具鏈。
4
+ # =======================================================================
5
+ import torch
6
+ import soundfile as sf
7
+ import librosa
8
+ from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
9
+ import os
10
+ from phonemizer import phonemize
11
+ import numpy as np
12
+ from datetime import datetime, timezone
13
+ import re
14
+ import unicodedata
15
+
16
+ # =======================================================================
17
+ # 2. 全域變數與配置區 (Global Variables & Config)
18
+ # =======================================================================
19
+ # 自動檢測可用設備
20
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
21
+ print(f"INFO: ASR_pt_br.py is configured to use device: {DEVICE}")
22
+
23
+ # 【【【【【 關鍵修改 1:設定為葡萄牙語 ASR 模型 】】】】】
24
+ MODEL_NAME = "caiocrocha/wav2vec2-large-xlsr-53-phoneme-portuguese"
25
+
26
+ processor = None
27
+ model = None
28
+
29
+ # =======================================================================
30
+ # 3. 核心業務邏輯區 (Core Business Logic)
31
+ # =======================================================================
32
+
33
+ # -----------------------------------------------------------------------
34
+ # 3.1. 模型載入函數
35
+ # - 與英文版邏輯完全相同,僅替換模型名稱。
36
+ # -----------------------------------------------------------------------
37
+ def load_model():
38
+ """
39
+ 載入葡萄牙語 ASR 模型和對應的處理器。
40
+ """
41
+ global processor, model
42
+ if processor and model:
43
+ print(f"模型 '{MODEL_NAME}' 已載入,跳過。")
44
+ return True
45
+
46
+ print(f"正在準備 ASR 模型 '{MODEL_NAME}'...")
47
+ try:
48
+ # 這些模型通常使用標準的 Wav2Vec2Processor 和 Wav2Vec2ForCTC
49
+ processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
50
+ model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)
51
+ model.to(DEVICE)
52
+ print(f"模型 '{MODEL_NAME}' 和處理器載入成功!")
53
+ return True
54
+ except Exception as e:
55
+ print(f"處理或載入模型 '{MODEL_NAME}' 時發生錯誤: {e}")
56
+ raise RuntimeError(f"Failed to load model '{MODEL_NAME}': {e}")
57
+
58
+ # -----------------------------------------------------------------------
59
+ # 3.2. 智能 IPA 切分函數
60
+ # - 【關鍵修改 2】針對葡萄牙語的 IPA 特性進行調整。
61
+ # -----------------------------------------------------------------------
62
+ def _tokenize_ipa(ipa_string: str) -> list:
63
+ """
64
+ 將 IPA 字串智能地切分為音素列表。
65
+ 這個版本能處理葡萄牙語中常見的多字元音素和帶有附加符號的音素。
66
+ """
67
+ phonemes = []
68
+ # 移除所有由 phonemizer 產生的多餘空格
69
+ s = ipa_string.replace(' ', '')
70
+ i = 0
71
+ while i < len(s):
72
+ # 檢查葡萄牙語中常見的雙字元塞擦音
73
+ if i + 1 < len(s) and s[i:i+2] in {'dʒ', 'tʃ'}:
74
+ phonemes.append(s[i:i+2])
75
+ i += 2
76
+ continue
77
+
78
+ # 處理帶有鼻化符 (波浪號) 的元音
79
+ # unicodedata.category(char) == 'Mn' 用於檢測非間距標記 (例如波浪號)
80
+ current_char = s[i]
81
+ i += 1
82
+ while i < len(s) and unicodedata.category(s[i]) == 'Mn':
83
+ current_char += s[i]
84
+ i += 1
85
+ phonemes.append(current_char)
86
+
87
+ return phonemes
88
+
89
+ # -----------------------------------------------------------------------
90
+ # 3.3. 核心分析函數 (主入口)
91
+ # - 【關鍵修改 3】將 G2P 語言設定為 'pt-br'。
92
+ # -----------------------------------------------------------------------
93
+ def analyze(audio_file_path: str, target_sentence: str) -> dict:
94
+ """
95
+ 接收音訊檔案路徑和目標葡萄牙語句子,回傳詳細的發音分析字典。
96
+ """
97
+ if not processor or not model:
98
+ raise RuntimeError("模型尚未載入。請確保在呼叫 analyze 之前已成功執行 load_model()。")
99
+
100
+ # --- G2P 步驟 ---
101
+ # 1. 使用正則表達式來準確地分割單詞,並自動忽略標點符號
102
+ target_words_original = re.findall(r"[\w'-]+", target_sentence)
103
+ # 2. 將分割好的、乾淨的單詞重新組合,再傳給 phonemizer
104
+ cleaned_sentence = " ".join(target_words_original)
105
+
106
+ # 3. 呼叫 phonemizer,並將語言設定為 'pt-br' (巴西葡萄牙語)
107
+ target_ipa_by_word_str = phonemize(
108
+ cleaned_sentence,
109
+ language='pt-br',
110
+ backend='espeak',
111
+ with_stress=True, # 保留重音符號以便後續處理
112
+ strip=True
113
+ ).split()
114
+
115
+ # 4. 確保單詞列表和音素列表的長度一致,以防 G2P 工具出錯
116
+ if len(target_words_original) != len(target_ipa_by_word_str):
117
+ print(f"警告:單詞數量 ({len(target_words_original)}) 與 G2P 結果數量 ({len(target_ipa_by_word_str)}) 不匹配。將進行截斷處理。")
118
+ min_len = min(len(target_words_original), len(target_ipa_by_word_str))
119
+ target_words_original = target_words_original[:min_len]
120
+ target_ipa_by_word_str = target_ipa_by_word_str[:min_len]
121
+
122
+ # 5. 清理 G2P 輸出的音素,並使用我們為葡萄牙語定製的切分函數
123
+ target_ipa_by_word = [
124
+ _tokenize_ipa(word.replace('ˈ', '').replace('ˌ', '').replace('ː', ''))
125
+ for word in target_ipa_by_word_str
126
+ ]
127
+
128
+ # --- ASR 步驟 ---
129
+ try:
130
+ speech, sample_rate = sf.read(audio_file_path)
131
+ if len(speech) == 0:
132
+ print("警告: 音訊檔案為空。")
133
+ user_ipa_full = ""
134
+ else:
135
+ if sample_rate != 16000:
136
+ speech = librosa.resample(y=speech, orig_sr=sample_rate, target_sr=16000)
137
+
138
+ input_values = processor(speech, sampling_rate=16000, return_tensors="pt").input_values
139
+ input_values = input_values.to(DEVICE)
140
+ with torch.no_grad():
141
+ logits = model(input_values).logits
142
+ predicted_ids = torch.argmax(logits, dim=-1)
143
+ # 解碼後,移除模型可能產生的分隔符 '|'
144
+ user_ipa_full = processor.decode(predicted_ids[0]).replace('|', '')
145
+
146
+ except Exception as e:
147
+ raise IOError(f"讀取或處理音訊時發生錯誤: {e}")
148
+
149
+ # --- 對齊與格式化步驟 (與英文版邏輯完全相同) ---
150
+ word_alignments = _get_phoneme_alignments_by_word(user_ipa_full, target_ipa_by_word)
151
+ return _format_to_json_structure(word_alignments, target_sentence, target_words_original)
152
+
153
+ # =======================================================================
154
+ # 4. 對齊與格式化函數區 (Alignment & Formatting)
155
+ # - 【注意】這些函數是語言無關的,直接從英文版複製而來,無需修改。
156
+ # =======================================================================
157
+
158
+ # -----------------------------------------------------------------------
159
+ # 4.1. 對齊函數 (語言無關)
160
+ # -----------------------------------------------------------------------
161
+ def _get_phoneme_alignments_by_word(user_phoneme_str, target_words_ipa_tokenized):
162
+ """
163
+ 使用動態規劃執行音素對齊。此函數是語言無關的。
164
+ """
165
+ # 對於 ASR 的輸出,我們也使用相同的、更通用的切分函數
166
+ user_phonemes = _tokenize_ipa(user_phoneme_str)
167
+
168
+ target_phonemes_flat = [p for word in target_words_ipa_tokenized for p in word]
169
+
170
+ # 如果目標音素為空 (例如,輸入句子只有標點符號),返回空對齊
171
+ if not target_phonemes_flat:
172
+ return []
173
+
174
+ word_boundaries_indices = np.cumsum([len(word) for word in target_words_ipa_tokenized]) - 1
175
+
176
+ dp = np.zeros((len(user_phonemes) + 1, len(target_phonemes_flat) + 1))
177
+ for i in range(1, len(user_phonemes) + 1): dp[i][0] = i
178
+ for j in range(1, len(target_phonemes_flat) + 1): dp[0][j] = j
179
+ for i in range(1, len(user_phonemes) + 1):
180
+ for j in range(1, len(target_phonemes_flat) + 1):
181
+ cost = 0 if user_phonemes[i-1] == target_phonemes_flat[j-1] else 1
182
+ dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost)
183
+
184
+ i, j = len(user_phonemes), len(target_phonemes_flat)
185
+ user_path, target_path = [], []
186
+ while i > 0 or j > 0:
187
+ cost = float('inf') if i == 0 or j == 0 else (0 if user_phonemes[i-1] == target_phonemes_flat[j-1] else 1)
188
+ if i > 0 and j > 0 and dp[i][j] == dp[i-1][j-1] + cost:
189
+ user_path.insert(0, user_phonemes[i-1]); target_path.insert(0, target_phonemes_flat[j-1]); i -= 1; j -= 1
190
+ elif i > 0 and (j == 0 or dp[i][j] == dp[i-1][j] + 1):
191
+ user_path.insert(0, user_phonemes[i-1]); target_path.insert(0, '-'); i -= 1
192
+ elif j > 0 and (i == 0 or dp[i][j] == dp[i][j-1] + 1):
193
+ user_path.insert(0, '-'); target_path.insert(0, target_phonemes_flat[j-1]); j -= 1
194
+ else: break
195
+
196
+ alignments_by_word = []
197
+ word_start_idx_in_path = 0
198
+ target_phoneme_counter_in_path = 0
199
+ word_boundary_iter = iter(word_boundaries_indices)
200
+ current_word_boundary = next(word_boundary_iter, -1)
201
+ for path_idx, p in enumerate(target_path):
202
+ if p != '-':
203
+ if target_phoneme_counter_in_path == current_word_boundary:
204
+ alignments_by_word.append({
205
+ "target": target_path[word_start_idx_in_path : path_idx + 1],
206
+ "user": user_path[word_start_idx_in_path : path_idx + 1]
207
+ })
208
+ word_start_idx_in_path = path_idx + 1
209
+ current_word_boundary = next(word_boundary_iter, -1)
210
+ target_phoneme_counter_in_path += 1
211
+ return alignments_by_word
212
+
213
+ # -----------------------------------------------------------------------
214
+ # 4.2. 格式化函數 (語言無關)
215
+ # -----------------------------------------------------------------------
216
+ def _format_to_json_structure(alignments, sentence, original_words) -> dict:
217
+ """
218
+ 將對齊結果格式化為最終的 JSON 結構��此函數是語言無關的。
219
+ """
220
+ total_phonemes, total_errors, correct_words_count = 0, 0, 0
221
+ words_data = []
222
+ num_words_to_process = min(len(alignments), len(original_words))
223
+
224
+ for i in range(num_words_to_process):
225
+ alignment = alignments[i]
226
+ word_is_correct = True
227
+ phonemes_data = []
228
+
229
+ # 增加一個健壯性檢查,以防對齊演算法返回長度不一的列表
230
+ min_len = min(len(alignment.get('target', [])), len(alignment.get('user', [])))
231
+ for j in range(min_len):
232
+ target_phoneme, user_phoneme = alignment['target'][j], alignment['user'][j]
233
+ is_match = (user_phoneme == target_phoneme)
234
+ phonemes_data.append({"target": target_phoneme, "user": user_phoneme, "isMatch": is_match})
235
+ if not is_match:
236
+ word_is_correct = False
237
+ if not (user_phoneme == '-' and target_phoneme == '-'): total_errors += 1
238
+
239
+ if word_is_correct and min_len > 0: correct_words_count += 1
240
+
241
+ words_data.append({"word": original_words[i], "isCorrect": word_is_correct, "phonemes": phonemes_data})
242
+ total_phonemes += sum(1 for p in alignment.get('target', []) if p != '-')
243
+
244
+ # 【Fuse Logic】處理使用者漏講了單詞的情況
245
+ if len(alignments) < len(original_words):
246
+ for i in range(len(alignments), len(original_words)):
247
+ # 【關鍵修改 4】確保這裡也使用 'pt-br'
248
+ missed_word_ipa_str = phonemize(original_words[i], language='pt-br', backend='espeak', strip=True).replace('ː', '')
249
+ missed_word_ipa = _tokenize_ipa(missed_word_ipa_str)
250
+ phonemes_data = []
251
+ for p_ipa in missed_word_ipa:
252
+ phonemes_data.append({"target": p_ipa, "user": "-", "isMatch": False})
253
+ total_errors += 1
254
+ total_phonemes += 1
255
+ words_data.append({"word": original_words[i], "isCorrect": False, "phonemes": phonemes_data})
256
+
257
+ total_words = len(original_words)
258
+ overall_score = (correct_words_count / total_words) * 100 if total_words > 0 else 0
259
+ phoneme_error_rate = (total_errors / total_phonemes) * 100 if total_phonemes > 0 else 0
260
+
261
+ return {
262
+ "sentence": sentence,
263
+ "analysisTimestampUTC": datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S (UTC)'),
264
+ "summary": {
265
+ "overallScore": round(overall_score, 1),
266
+ "totalWords": total_words,
267
+ "correctWords": correct_words_count,
268
+ "phonemeErrorRate": round(phoneme_error_rate, 2),
269
+ "total_errors": total_errors,
270
+ "total_target_phonemes": total_phonemes
271
+ },
272
+ "words": words_data
273
+ }