HK0712 commited on
Commit
5d4c1d3
·
1 Parent(s): a309cba

changed dockerfile

Browse files
.devcontainer/devcontainer.json CHANGED
@@ -1,6 +1,11 @@
1
  {
2
  "name": "FYP Backend (GPU)",
3
- "image": "e226274b3239", // 直接使用您已有的鏡像 ID
 
 
 
 
 
4
 
5
  // 這是最最最關鍵的部分!
6
  "runArgs": [
@@ -18,7 +23,7 @@
18
  "shutdownAction": "none",
19
 
20
  // 在容器創建後運行的命令 (可選,但推薦)
21
- "postCreateCommand": "pip install -r requirements.txt",
22
 
23
  // VS Code 擴展推薦 (可選)
24
  "customizations": {
 
1
  {
2
  "name": "FYP Backend (GPU)",
3
+
4
+ "build": {
5
+ // 假設您的 Dockerfile 位於專案根目錄
6
+ "dockerfile": "../Dockerfile",
7
+ "context": ".."
8
+ },
9
 
10
  // 這是最最最關鍵的部分!
11
  "runArgs": [
 
23
  "shutdownAction": "none",
24
 
25
  // 在容器創建後運行的命令 (可選,但推薦)
26
+ //"postCreateCommand": "pip install -r requirements.txt",
27
 
28
  // VS Code 擴展推薦 (可選)
29
  "customizations": {
Dockerfile CHANGED
@@ -11,6 +11,11 @@ WORKDIR /app
11
  # -y 自動回答 'yes'
12
  # --no-install-recommends 避免安裝不必要的建議套件,保持映像檔小巧
13
  RUN apt-get update && apt-get install -y --no-install-recommends \
 
 
 
 
 
14
  espeak-ng \
15
  libsndfile1 \
16
  ffmpeg \
@@ -20,6 +25,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
20
 
21
  # 4. 複製 requirements.txt 檔案到容器中並安裝 Python 套件
22
  COPY requirements.txt .
 
23
  RUN pip install --no-cache-dir -r requirements.txt
24
 
25
  # 5. 將專案中的所有其他檔案複製到容器中
 
11
  # -y 自動回答 'yes'
12
  # --no-install-recommends 避免安裝不必要的建議套件,保持映像檔小巧
13
  RUN apt-get update && apt-get install -y --no-install-recommends \
14
+ build-essential \
15
+ cmake \
16
+ mecab \
17
+ libmecab-dev \
18
+ mecab-ipadic-utf8 \
19
  espeak-ng \
20
  libsndfile1 \
21
  ffmpeg \
 
25
 
26
  # 4. 複製 requirements.txt 檔案到容器中並安裝 Python 套件
27
  COPY requirements.txt .
28
+ RUN pip install --upgrade pip
29
  RUN pip install --no-cache-dir -r requirements.txt
30
 
31
  # 5. 將專案中的所有其他檔案複製到容器中
analyzer/ASR_jp_jp.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =======================================================================
2
+ # 1. 匯入區 (Imports)
3
+ # 【關鍵修改】新增了 pyopenjtalk 和 MeCab 的匯入
4
+ # =======================================================================
5
+ import torch
6
+ import soundfile as sf
7
+ import librosa
8
+ from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
9
+ import os
10
+ import pyopenjtalk
11
+ import MeCab
12
+ import numpy as np
13
+ from datetime import datetime, timezone
14
+ import re
15
+
16
+ # =======================================================================
17
+ # 2. 全域變數與配置區 (Global Variables & Config)
18
+ # =======================================================================
19
+ # 【關鍵修改】自動檢測可用設備
20
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
21
+ print(f"INFO: ASR_jp_jp.py is configured to use device: {DEVICE}")
22
+
23
+ # 【關鍵修改】設定為日語 ASR 模型
24
+ MODEL_NAME = "prj-beatrice/japanese-hubert-base-phoneme-ctc-v3"
25
+
26
+ processor = None
27
+ model = None
28
+
29
+ # 【關鍵修改】初始化 MeCab 分詞器
30
+ # 我們使用 -Owakati 選項來獲得以空格分隔的單詞列表
31
+ mecab_tagger = MeCab.Tagger("-Owakati")
32
+
33
+ # =======================================================================
34
+ # 3. 核心業務邏輯區 (Core Business Logic)
35
+ # =======================================================================
36
+
37
+ # -----------------------------------------------------------------------
38
+ # 3.1. 模型載入函數 (與其他版本邏輯相同)
39
+ # -----------------------------------------------------------------------
40
+ def load_model():
41
+ """
42
+ 載入日語 ASR 模型和對應的處理器。
43
+ """
44
+ global processor, model
45
+ if processor and model:
46
+ print(f"模型 '{MODEL_NAME}' 已載入,跳過。")
47
+ return True
48
+
49
+ print(f"正在準備 ASR 模型 '{MODEL_NAME}'...")
50
+ try:
51
+ processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
52
+ model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)
53
+ model.to(DEVICE)
54
+ print(f"模型 '{MODEL_NAME}' 和處理器載入成功!")
55
+ return True
56
+ except Exception as e:
57
+ print(f"處理或載入模型 '{MODEL_NAME}' 時發生錯誤: {e}")
58
+ raise RuntimeError(f"Failed to load model '{MODEL_NAME}': {e}")
59
+
60
+ # -----------------------------------------------------------------------
61
+ # 3.2. 日語 G2P 輔助函數 (這是此檔案最核心的新增部分)
62
+ # -----------------------------------------------------------------------
63
+ def japanese_g2p(text: str) -> list[tuple[str, str]]:
64
+ """
65
+ 將日語句子轉換為 (單詞, 對應音素) 的元組列表。
66
+ 這是我們為日語定製的 G2P 核心。
67
+ """
68
+ # 1. 使用 MeCab 進行分詞
69
+ words = mecab_tagger.parse(text).strip().split(' ')
70
+
71
+ # 2. 對整個句子使用 PyOpenJTalk 獲取完整的音素序列
72
+ # 我們直接使用 pyopenjtalk.g2p,它輸出的就是以空格分隔的音素
73
+ full_phonemes_str = pyopenjtalk.g2p(text)
74
+
75
+ # 3. 進行音素清理,以匹配 ASR 模型的輸出
76
+ # ASR 模型輸出的是清音,所以我們移除濁音、半濁音、長音等符號
77
+ cleaned_phonemes = full_phonemes_str.replace('pau', ' ').replace(' ', '').replace('N', 'n').replace('cl', '')
78
+
79
+ # 4. 將單詞和音素進行配對
80
+ # 這是一個簡化的配對邏輯:我們假設音素的數量和假名的數量大致對應
81
+ # 這在大多數情況下是有效的,因為日語是音節語言
82
+ result = []
83
+ phoneme_idx = 0
84
+ for word in words:
85
+ # 計算當前單詞大致對應多少個音素 (假名數量)
86
+ num_mora = len(word)
87
+
88
+ # 提取對應的音素片段
89
+ word_phonemes = cleaned_phonemes[phoneme_idx : phoneme_idx + num_mora]
90
+
91
+ # 檢查提取的音素是否為空,避免無效單詞的影響
92
+ if word_phonemes:
93
+ result.append((word, word_phonemes))
94
+
95
+ phoneme_idx += num_mora
96
+
97
+ return result
98
+
99
+ # -----------------------------------------------------------------------
100
+ # 3.3. 音素切分函數 (與其他版本邏輯相同,但更通用)
101
+ # -----------------------------------------------------------------------
102
+ def _tokenize_ipa(ipa_string: str) -> list:
103
+ """
104
+ 將音素字串切分為列表。對於日語,直接按字元切分即可。
105
+ """
106
+ # 日語 ASR 模型的輸出是單字元音素,所以直接轉換為列表
107
+ return list(ipa_string)
108
+
109
+ # -----------------------------------------------------------------------
110
+ # 3.4. 核心分析函數 (主入口,已修改為日語邏輯)
111
+ # -----------------------------------------------------------------------
112
+ def analyze(audio_file_path: str, target_sentence: str) -> dict:
113
+ """
114
+ 接收音訊檔案路徑和目標日語句子,回傳詳細的發音分析字典。
115
+ """
116
+ if not processor or not model:
117
+ raise RuntimeError("模型尚未載入。請確保在呼叫 analyze 之前已成功執行 load_model()。")
118
+
119
+ # 【關鍵修改】使用我們新的日語 G2P 函數
120
+ g2p_result = japanese_g2p(target_sentence)
121
+
122
+ # 從 G2P 結果中提取原始單詞列表和按單詞劃分的音素列表
123
+ target_words_original = [item[0] for item in g2p_result]
124
+ target_ipa_by_word = [_tokenize_ipa(item[1]) for item in g2p_result]
125
+
126
+ # 載入並處理音訊 (與其他版本邏輯相同)
127
+ try:
128
+ speech, sample_rate = sf.read(audio_file_path)
129
+ if sample_rate != 16000:
130
+ speech = librosa.resample(y=speech, orig_sr=sample_rate, target_sr=16000)
131
+ except Exception as e:
132
+ raise IOError(f"讀取或處理音訊時發生錯誤: {e}")
133
+
134
+ # 進行 ASR 推論 (與其他版本邏輯相同)
135
+ input_values = processor(speech, sampling_rate=16000, return_tensors="pt").input_values
136
+ input_values = input_values.to(DEVICE)
137
+ with torch.no_grad():
138
+ logits = model(input_values).logits
139
+ predicted_ids = torch.argmax(logits, dim=-1)
140
+ user_ipa_full = processor.decode(predicted_ids[0])
141
+
142
+ # 進行對齊 (與其他版本邏輯相同)
143
+ word_alignments = _get_phoneme_alignments_by_word(user_ipa_full, target_ipa_by_word)
144
+
145
+ # 格式化輸出 (與其他版本邏輯相同)
146
+ return _format_to_json_structure(word_alignments, target_sentence, target_words_original)
147
+
148
+ # =======================================================================
149
+ # 4. 對齊與格式化函數區 (Alignment & Formatting)
150
+ # 【注意】這些函數是語言無關的,直接從英文版複製,無需修改
151
+ # =======================================================================
152
+
153
+ # -----------------------------------------------------------------------
154
+ # 4.1. 對齊函數
155
+ # -----------------------------------------------------------------------
156
+ def _get_phoneme_alignments_by_word(user_phoneme_str, target_words_ipa_tokenized):
157
+ """
158
+ 執行音素對齊。此函數是語言無關的。
159
+ """
160
+ user_phonemes = _tokenize_ipa(user_phoneme_str)
161
+
162
+ target_phonemes_flat = []
163
+ word_boundaries_indices = []
164
+ current_idx = 0
165
+ for word_ipa_tokens in target_words_ipa_tokenized:
166
+ target_phonemes_flat.extend(word_ipa_tokens)
167
+ current_idx += len(word_ipa_tokens)
168
+ word_boundaries_indices.append(current_idx - 1)
169
+
170
+ dp = np.zeros((len(user_phonemes) + 1, len(target_phonemes_flat) + 1))
171
+ for i in range(1, len(user_phonemes) + 1): dp[i][0] = i
172
+ for j in range(1, len(target_phonemes_flat) + 1): dp[0][j] = j
173
+ for i in range(1, len(user_phonemes) + 1):
174
+ for j in range(1, len(target_phonemes_flat) + 1):
175
+ cost = 0 if user_phonemes[i-1] == target_phonemes_flat[j-1] else 1
176
+ dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost)
177
+
178
+ i, j = len(user_phonemes), len(target_phonemes_flat)
179
+ user_path, target_path = [], []
180
+ while i > 0 or j > 0:
181
+ cost = float('inf') if i == 0 or j == 0 else (0 if user_phonemes[i-1] == target_phonemes_flat[j-1] else 1)
182
+ if i > 0 and j > 0 and dp[i][j] == dp[i-1][j-1] + cost:
183
+ user_path.insert(0, user_phonemes[i-1]); target_path.insert(0, target_phonemes_flat[j-1]); i -= 1; j -= 1
184
+ elif i > 0 and dp[i][j] == dp[i-1][j] + 1:
185
+ user_path.insert(0, user_phonemes[i-1]); target_path.insert(0, '-'); i -= 1
186
+ else:
187
+ user_path.insert(0, '-'); target_path.insert(0, target_phonemes_flat[j-1]); j -= 1
188
+
189
+ alignments_by_word = []
190
+ word_start_idx_in_path = 0
191
+ target_phoneme_counter_in_path = 0
192
+
193
+ for path_idx, p in enumerate(target_path):
194
+ if p != '-':
195
+ if target_phoneme_counter_in_path in word_boundaries_indices:
196
+ target_alignment = target_path[word_start_idx_in_path : path_idx + 1]
197
+ user_alignment = user_path[word_start_idx_in_path : path_idx + 1]
198
+
199
+ alignments_by_word.append({
200
+ "target": target_alignment,
201
+ "user": user_alignment
202
+ })
203
+
204
+ word_start_idx_in_path = path_idx + 1
205
+
206
+ target_phoneme_counter_in_path += 1
207
+
208
+ return alignments_by_word
209
+
210
+ # -----------------------------------------------------------------------
211
+ # 4.2. 格式化函數
212
+ # -----------------------------------------------------------------------
213
+ def _format_to_json_structure(alignments, sentence, original_words) -> dict:
214
+ """
215
+ 將對齊結果格式化為最終的 JSON 結構。此函數是語言無關的。
216
+ """
217
+ total_phonemes = 0
218
+ total_errors = 0
219
+ correct_words_count = 0
220
+ words_data = []
221
+
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
+ for j in range(len(alignment['target'])):
230
+ target_phoneme = alignment['target'][j]
231
+ user_phoneme = alignment['user'][j]
232
+ is_match = (user_phoneme == target_phoneme)
233
+
234
+ phonemes_data.append({
235
+ "target": target_phoneme,
236
+ "user": user_phoneme,
237
+ "isMatch": is_match
238
+ })
239
+
240
+ if not is_match:
241
+ word_is_correct = False
242
+ if not (user_phoneme == '-' and target_phoneme == '-'):
243
+ total_errors += 1
244
+
245
+ if word_is_correct:
246
+ correct_words_count += 1
247
+
248
+ words_data.append({
249
+ "word": original_words[i],
250
+ "isCorrect": word_is_correct,
251
+ "phonemes": phonemes_data
252
+ })
253
+
254
+ total_phonemes += sum(1 for p in alignment['target'] if p != '-')
255
+
256
+ total_words = len(original_words)
257
+ if len(alignments) < total_words:
258
+ for i in range(len(alignments), total_words):
259
+ # 處理使用者未說出的單詞
260
+ missed_word_ipa = _tokenize_ipa(japanese_g2p(original_words[i])[0][1]) # 重新獲取音素
261
+ phonemes_data = []
262
+ for p_ipa in missed_word_ipa:
263
+ phonemes_data.append({"target": p_ipa, "user": "-", "isMatch": False})
264
+ total_errors += 1
265
+ total_phonemes += 1
266
+
267
+ words_data.append({
268
+ "word": original_words[i],
269
+ "isCorrect": False,
270
+ "phonemes": phonemes_data
271
+ })
272
+
273
+ overall_score = (correct_words_count / total_words) * 100 if total_words > 0 else 0
274
+ phoneme_error_rate = (total_errors / total_phonemes) * 100 if total_phonemes > 0 else 0
275
+
276
+ final_result = {
277
+ "sentence": sentence,
278
+ "analysisTimestampUTC": datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S (UTC)'),
279
+ "summary": {
280
+ "overallScore": round(overall_score, 1),
281
+ "totalWords": total_words,
282
+ "correctWords": correct_words_count,
283
+ "phonemeErrorRate": round(phoneme_error_rate, 2),
284
+ "total_errors": total_errors,
285
+ "total_target_phonemes": total_phonemes
286
+ },
287
+ "words": words_data
288
+ }
289
+
290
+ return final_result
requirements.txt CHANGED
@@ -9,4 +9,6 @@ transformers
9
  phonemizer[espeak]
10
  numpy
11
  epitran
12
- g2p
 
 
 
9
  phonemizer[espeak]
10
  numpy
11
  epitran
12
+ g2p
13
+ pyopenjtalk
14
+ mecab-python3