heldtomaturity commited on
Commit
9aa0b19
Β·
1 Parent(s): 770a612

fix produced_phoneme AttributeError

Browse files
Files changed (2) hide show
  1. app.py +65 -148
  2. feedback_generator.py +1 -1
app.py CHANGED
@@ -1,16 +1,11 @@
1
  """
2
- Mispronunciation Detection & Diagnosis β€” HuggingFace Space
3
- ===========================================================
4
- Wires together:
5
- 1. PhonologicalWav2Vec2 (your best_model.pt, loaded once at cold start)
6
- 2. G2P (user types normal English β†’ auto-converted to ARPAbet)
7
- 3. MDD engine (per-feature NW alignment β†’ errors + score)
8
- 4. Feedback generator (rule engine + optional LLM rewriter)
9
-
10
- Environment variables (Space β†’ Settings β†’ Variables and secrets):
11
- HF_TOKEN (secret) β€” read token for your private model repo
12
- HF_MODEL_REPO (variable) β€” e.g. "Backlighteu/phonological-mdd"
13
- HF_MODEL_FILENAME (variable) β€” e.g. "best_model.pt"
14
  """
15
 
16
  import os
@@ -22,7 +17,7 @@ import gradio as gr
22
  import librosa
23
  import pronouncing
24
 
25
- from huggingface_hub import hf_hub_download, snapshot_download
26
  from transformers import Wav2Vec2FeatureExtractor
27
 
28
  from wav2vec2_phonological import PhonologicalWav2Vec2
@@ -31,7 +26,7 @@ from feedback_generator import generate_feedback
31
  from phonological_features import CMU_39_PHONEMES
32
 
33
  # ─────────────────────────────────────────────────────────────────────────────
34
- # 1. Model β€” loaded once, reused for every request
35
  # ─────────────────────────────────────────────────────────────────────────────
36
 
37
  _model = None
@@ -49,231 +44,153 @@ def load_model():
49
  if _model is not None:
50
  return
51
 
52
- print(f"[startup] Caching {MODEL_REPO} to ./model_cache ...")
53
- snapshot_download(
54
- repo_id=MODEL_REPO,
55
- token=HF_TOKEN,
56
- local_dir="./model_cache",
57
- )
58
- weights_path = "./model_cache/best_model.pt"
59
- print(f"[startup] Loading weights from {weights_path}")
60
 
61
  model = PhonologicalWav2Vec2(
62
  pretrained_model_name=PRETRAINED_BASE,
63
  num_output_nodes=71,
64
  freeze_cnn_encoder=True,
65
  )
66
- state_dict = torch.load(weights_path, map_location=_device)
67
  model.load_state_dict(state_dict)
68
  model.to(_device)
69
  model.eval()
70
  _model = model
71
- print(f"[startup] Model ready on {_device}.")
72
 
73
- print(f"[startup] Loading feature extractor ...")
74
  _feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(PRETRAINED_BASE)
75
- print("[startup] Feature extractor ready.")
76
 
77
 
78
  # ─────────────────────────────────────────────────────────────────────────────
79
- # 2. G2P β€” normal English words β†’ CMU-39 ARPAbet phonemes
80
  # ─────────────────────────────────────────────────────────────────────────────
81
 
82
  _CMU_39 = set(CMU_39_PHONEMES)
83
 
84
 
85
- def _word_to_phonemes(word: str) -> list[str] | None:
86
- """Convert one word to CMU-39 phonemes using the bundled CMU dict."""
87
- results = pronouncing.phones_for_word(word.lower())
88
- if not results:
89
- return None
90
- phones = results[0].split() # take first (most common) pronunciation
91
- return [
92
- re.sub(r"[0-9]", "", p).lower() # strip stress digits
93
- for p in phones
94
- if re.sub(r"[0-9]", "", p).lower() in _CMU_39
95
- ]
96
-
97
-
98
  def sentence_to_phonemes(sentence: str) -> tuple[list[str], list[str]]:
99
- """
100
- Convert a plain English sentence to a CMU-39 phoneme list.
101
- Returns (phonemes, unknown_words).
102
- Unknown words (not in CMU dict) are skipped and reported separately.
103
- """
104
  words = re.sub(r"[^a-zA-Z\s]", "", sentence).split()
105
- all_phonemes, unknown = [], []
106
  for word in words:
107
- phones = _word_to_phonemes(word)
108
- if phones:
109
- all_phonemes.extend(phones)
 
 
 
110
  else:
111
  unknown.append(word)
112
- return all_phonemes, unknown
113
 
114
 
115
  # ─────────────────────────────────────────────────────────────────────────────
116
- # 3. Audio β†’ decoded feature sequences
117
  # ─────────────────────────────────────────────────────────────────────────────
118
 
119
- TARGET_SR = 16_000
120
-
121
-
122
  def decode_audio(audio_path: str) -> list[list[int]]:
123
  load_model()
124
-
125
- waveform, _ = librosa.load(audio_path, sr=TARGET_SR, mono=True)
126
- waveform = waveform.astype(np.float32)
127
-
128
  inputs = _feature_extractor(
129
- waveform,
130
- sampling_rate=TARGET_SR,
131
- return_tensors="pt",
132
- padding=True,
133
  )
134
-
135
  input_values = inputs.input_values.to(_device)
136
  attention_mask = inputs.get("attention_mask")
137
  if attention_mask is not None:
138
  attention_mask = attention_mask.to(_device)
139
 
140
  with torch.no_grad():
141
- logits, output_lengths = _model(
142
- input_values, attention_mask, apply_spec_augment=False
143
- )
144
 
145
- # decode() returns list[B][35][list[bool]]
146
  decoded_35 = _model.decode(logits, output_lengths)[0]
147
  return [[1 if v else 0 for v in seq] for seq in decoded_35]
148
 
149
 
150
  # ─────────────────────────────────────────────────────────────────────────────
151
- # 4. Gradio processing function
152
  # ─────────────────────────────────────────────────────────────────────────────
153
 
154
- def process(audio_input, sentence_text, use_llm, max_issues):
155
  if audio_input is None:
156
- return "Please record or upload audio first.", "", "", "{}"
157
-
158
- sentence_text = sentence_text.strip()
159
- if not sentence_text:
160
- return "Please type the sentence you want to practise.", "", "", "{}"
161
 
162
- # G2P conversion
163
- target_phonemes, unknown_words = sentence_to_phonemes(sentence_text)
164
  if not target_phonemes:
165
- return (
166
- "Could not convert the sentence to phonemes. "
167
- "Please use common English words.",
168
- "", "", "{}",
169
- )
170
-
171
- phoneme_display = " ".join(target_phonemes)
172
- unknown_msg = ""
173
- if unknown_words:
174
- unknown_msg = f"\n\n⚠️ Words not found in dictionary (skipped): *{', '.join(unknown_words)}*"
175
 
176
- # Audio inference
177
  try:
178
  actual_feature_seqs = decode_audio(audio_input)
179
  except Exception as e:
180
- return f"Audio processing error: {e}", "", "", "{}"
181
 
182
  # MDD
183
  try:
184
- result = run_mdd(
185
- actual_feature_seqs=actual_feature_seqs,
186
- target_phonemes=target_phonemes,
187
- )
188
  except Exception as e:
189
- return f"MDD engine error: {e}", "", "", "{}"
190
 
191
  # Feedback
192
- feedback_dict = generate_feedback(result, use_llm=use_llm, max_issues=int(max_issues))
193
 
194
  score = feedback_dict["score"]
195
- main_feedback = (
196
- f"**Score: {score}/100**{unknown_msg}\n\n"
197
- + feedback_dict["final_feedback"]
198
- )
199
 
200
- # Per-phoneme detail
201
- detail_lines = ["### Per-phoneme breakdown\n"]
202
  for e in feedback_dict["error_summary"]:
203
- del_tag = " *(deleted)*" if e.get("is_deletion") else ""
204
- detail_lines.append(
205
- f"- **/{e['target']}/** (position {e['position']}){del_tag}: "
206
- f"severity=`{e['severity']}`, accuracy={e['accuracy']:.0%}\n"
207
- f" - Missing: {', '.join(e['missing_features']) or 'β€”'}\n"
208
- f" - Extra: {', '.join(e['extra_features']) or 'β€”'}"
209
  )
210
- if not feedback_dict["error_summary"]:
211
- detail_lines.append("βœ… No errors detected β€” great pronunciation!")
212
-
213
- json_output = json.dumps({
214
- "score": feedback_dict["score"],
215
- "target_phonemes": target_phonemes,
216
- "deletion_count": result.deletion_count,
217
- "insertion_count": result.insertion_count,
218
- "feature_error_counts": feedback_dict["feature_error_counts"],
219
- "actual_seq_lengths": [len(s) for s in actual_feature_seqs],
220
- }, indent=2)
221
 
222
- return main_feedback, phoneme_display, "\n".join(detail_lines), json_output
223
 
224
 
225
  # ─────────────────────────────────────────────────────────────────────────────
226
- # 5. Gradio UI
227
  # ─────────────────────────────────────────────────────────────────────────────
228
 
229
- with gr.Blocks(title="Pronunciation Coach", theme=gr.themes.Soft()) as demo:
230
- gr.Markdown(
231
- """
232
- # πŸ—£οΈ Pronunciation Coach
233
- Type a sentence in plain English, record yourself saying it,
234
- and get phonological-feature-level feedback with articulation tips.
235
- """
236
- )
237
 
238
  with gr.Row():
239
  with gr.Column(scale=1):
240
  sentence_input = gr.Textbox(
241
  label="Sentence to practise",
242
- placeholder="e.g. The cat sat on the mat",
243
  lines=2,
244
  )
245
  audio_input = gr.Audio(
246
  sources=["microphone", "upload"],
247
  type="filepath",
248
- label="Your speech β€” record or upload",
249
  )
250
- with gr.Row():
251
- use_llm = gr.Checkbox(value=False, label="LLM feedback rewriter")
252
- max_issues = gr.Slider(1, 5, value=3, step=1, label="Max issues shown")
253
  submit_btn = gr.Button("Analyse", variant="primary")
254
 
255
  with gr.Column(scale=2):
256
- feedback_out = gr.Markdown(label="Coaching feedback")
257
- phoneme_out = gr.Textbox(label="Auto-detected phonemes", interactive=False)
258
  with gr.Accordion("Per-phoneme detail", open=False):
259
  detail_out = gr.Markdown()
260
- with gr.Accordion("Raw JSON (developers)", open=False):
261
- json_out = gr.Code(language="json")
262
 
263
  submit_btn.click(
264
  fn=process,
265
- inputs=[audio_input, sentence_input, use_llm, max_issues],
266
- outputs=[feedback_out, phoneme_out, detail_out, json_out],
267
- )
268
-
269
- gr.Markdown(
270
- """
271
- ---
272
- Just type any English sentence and hit **Analyse** β€” the app converts
273
- it to phonemes automatically using the CMU Pronouncing Dictionary.
274
- """
275
  )
276
 
277
-
278
  if __name__ == "__main__":
279
- demo.launch()
 
1
  """
2
+ Pronunciation Coach β€” HuggingFace Space
3
+ ========================================
4
+ 1. User types a normal English sentence
5
+ 2. User records themselves saying it
6
+ 3. App runs phonological model β†’ 35 CTC feature sequences
7
+ 4. MDD engine aligns them against canonical sequences β†’ errors + score
8
+ 5. Feedback generator returns coaching tips
 
 
 
 
 
9
  """
10
 
11
  import os
 
17
  import librosa
18
  import pronouncing
19
 
20
+ from huggingface_hub import snapshot_download
21
  from transformers import Wav2Vec2FeatureExtractor
22
 
23
  from wav2vec2_phonological import PhonologicalWav2Vec2
 
26
  from phonological_features import CMU_39_PHONEMES
27
 
28
  # ─────────────────────────────────────────────────────────────────────────────
29
+ # Model globals
30
  # ─────────────────────────────────────────────────────────────────────────────
31
 
32
  _model = None
 
44
  if _model is not None:
45
  return
46
 
47
+ print(f"[startup] Downloading {MODEL_REPO}/{MODEL_FILENAME} ...")
48
+ snapshot_download(repo_id=MODEL_REPO, token=HF_TOKEN, local_dir="./model_cache")
 
 
 
 
 
 
49
 
50
  model = PhonologicalWav2Vec2(
51
  pretrained_model_name=PRETRAINED_BASE,
52
  num_output_nodes=71,
53
  freeze_cnn_encoder=True,
54
  )
55
+ state_dict = torch.load("./model_cache/best_model.pt", map_location=_device)
56
  model.load_state_dict(state_dict)
57
  model.to(_device)
58
  model.eval()
59
  _model = model
 
60
 
 
61
  _feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(PRETRAINED_BASE)
62
+ print(f"[startup] Ready on {_device}.")
63
 
64
 
65
  # ─────────────────────────────────────────────────────────────────────────────
66
+ # G2P β€” plain English β†’ CMU-39 phonemes
67
  # ─────────────────────────────────────────────────────────────────────────────
68
 
69
  _CMU_39 = set(CMU_39_PHONEMES)
70
 
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def sentence_to_phonemes(sentence: str) -> tuple[list[str], list[str]]:
 
 
 
 
 
73
  words = re.sub(r"[^a-zA-Z\s]", "", sentence).split()
74
+ phonemes, unknown = [], []
75
  for word in words:
76
+ results = pronouncing.phones_for_word(word.lower())
77
+ if results:
78
+ for p in results[0].split():
79
+ p = re.sub(r"[0-9]", "", p).lower()
80
+ if p in _CMU_39:
81
+ phonemes.append(p)
82
  else:
83
  unknown.append(word)
84
+ return phonemes, unknown
85
 
86
 
87
  # ─────────────────────────────────────────────────────────────────────────────
88
+ # Audio inference
89
  # ─────────────────────────────────────────────────────────────────────────────
90
 
 
 
 
91
  def decode_audio(audio_path: str) -> list[list[int]]:
92
  load_model()
93
+ waveform, _ = librosa.load(audio_path, sr=16000, mono=True)
 
 
 
94
  inputs = _feature_extractor(
95
+ waveform.astype(np.float32), sampling_rate=16000,
96
+ return_tensors="pt", padding=True,
 
 
97
  )
 
98
  input_values = inputs.input_values.to(_device)
99
  attention_mask = inputs.get("attention_mask")
100
  if attention_mask is not None:
101
  attention_mask = attention_mask.to(_device)
102
 
103
  with torch.no_grad():
104
+ logits, output_lengths = _model(input_values, attention_mask,
105
+ apply_spec_augment=False)
 
106
 
 
107
  decoded_35 = _model.decode(logits, output_lengths)[0]
108
  return [[1 if v else 0 for v in seq] for seq in decoded_35]
109
 
110
 
111
  # ─────────────────────────────────────────────────────────────────────────────
112
+ # Main handler
113
  # ─────────────────────────────────────────────────────────────────────────────
114
 
115
+ def process(audio_input, sentence_text, max_issues):
116
  if audio_input is None:
117
+ return "⚠️ Please record or upload audio.", ""
118
+ if not sentence_text.strip():
119
+ return "⚠️ Please type the sentence you want to practise.", ""
 
 
120
 
121
+ # G2P
122
+ target_phonemes, unknown = sentence_to_phonemes(sentence_text.strip())
123
  if not target_phonemes:
124
+ return "⚠️ Could not convert sentence to phonemes. Try simpler English words.", ""
 
 
 
 
 
 
 
 
 
125
 
126
+ # Model inference
127
  try:
128
  actual_feature_seqs = decode_audio(audio_input)
129
  except Exception as e:
130
+ return f"❌ Audio error: {e}", ""
131
 
132
  # MDD
133
  try:
134
+ result = run_mdd(actual_feature_seqs=actual_feature_seqs,
135
+ target_phonemes=target_phonemes)
 
 
136
  except Exception as e:
137
+ return f"❌ MDD error: {e}", ""
138
 
139
  # Feedback
140
+ feedback_dict = generate_feedback(result, use_llm=False, max_issues=int(max_issues))
141
 
142
  score = feedback_dict["score"]
143
+ main_out = f"**Score: {score}/100**\n\n" + feedback_dict["final_feedback"]
144
+ if unknown:
145
+ main_out += f"\n\n⚠️ Words not in dictionary (skipped): *{', '.join(unknown)}*"
 
146
 
147
+ # Detail
148
+ lines = []
149
  for e in feedback_dict["error_summary"]:
150
+ tag = " *(deleted)*" if e.get("is_deletion") else ""
151
+ lines.append(
152
+ f"**/{e['target']}/** pos {e['position']}{tag} β€” "
153
+ f"{e['severity']}, {e['accuracy']:.0%} accurate \n"
154
+ f"Missing: {', '.join(e['missing_features']) or 'β€”'} | "
155
+ f"Extra: {', '.join(e['extra_features']) or 'β€”'}"
156
  )
157
+ detail_out = "\n\n".join(lines) if lines else "βœ… No errors detected!"
 
 
 
 
 
 
 
 
 
 
158
 
159
+ return main_out, detail_out
160
 
161
 
162
  # ─────────────────────────────────────────────────────────────────────────────
163
+ # Gradio UI β€” clean and simple
164
  # ─────────────────────────────────────────────────────────────────────────────
165
 
166
+ with gr.Blocks(title="Pronunciation Coach") as demo:
167
+ gr.Markdown("# πŸ—£οΈ Pronunciation Coach\nType a sentence, record yourself saying it, get feedback.")
 
 
 
 
 
 
168
 
169
  with gr.Row():
170
  with gr.Column(scale=1):
171
  sentence_input = gr.Textbox(
172
  label="Sentence to practise",
173
+ placeholder="The cat sat on the mat",
174
  lines=2,
175
  )
176
  audio_input = gr.Audio(
177
  sources=["microphone", "upload"],
178
  type="filepath",
179
+ label="Your speech",
180
  )
181
+ max_issues = gr.Slider(1, 5, value=3, step=1, label="Max issues to show")
 
 
182
  submit_btn = gr.Button("Analyse", variant="primary")
183
 
184
  with gr.Column(scale=2):
185
+ feedback_out = gr.Markdown(label="Feedback")
 
186
  with gr.Accordion("Per-phoneme detail", open=False):
187
  detail_out = gr.Markdown()
 
 
188
 
189
  submit_btn.click(
190
  fn=process,
191
+ inputs=[audio_input, sentence_input, max_issues],
192
+ outputs=[feedback_out, detail_out],
 
 
 
 
 
 
 
 
193
  )
194
 
 
195
  if __name__ == "__main__":
196
+ demo.launch(theme=gr.themes.Soft())
feedback_generator.py CHANGED
@@ -664,7 +664,7 @@ def generate_feedback(
664
  {
665
  "position": e.position,
666
  "target": e.target_phoneme,
667
- "produced": e.produced_phoneme,
668
  "missing_features": e.missing_features,
669
  "extra_features": e.extra_features,
670
  "accuracy": round(e.feature_accuracy, 3),
 
664
  {
665
  "position": e.position,
666
  "target": e.target_phoneme,
667
+ "is_deletion": e.is_deletion,
668
  "missing_features": e.missing_features,
669
  "extra_features": e.extra_features,
670
  "accuracy": round(e.feature_accuracy, 3),