heldtomaturity commited on
Commit
770a612
Β·
1 Parent(s): 0515ef3

add automatic G2P - users type normal English now

Browse files
Files changed (2) hide show
  1. app.py +99 -107
  2. requirements.txt +1 -7
app.py CHANGED
@@ -3,21 +3,24 @@ Mispronunciation Detection & Diagnosis β€” HuggingFace Space
3
  ===========================================================
4
  Wires together:
5
  1. PhonologicalWav2Vec2 (your best_model.pt, loaded once at cold start)
6
- 2. MDD engine (per-feature NW alignment β†’ errors + score)
7
- 3. Feedback generator (rule engine + optional LLM rewriter)
 
8
 
9
- Environment variables to set in Space β†’ Settings β†’ Variables and secrets:
10
  HF_TOKEN (secret) β€” read token for your private model repo
11
  HF_MODEL_REPO (variable) β€” e.g. "Backlighteu/phonological-mdd"
12
- HF_MODEL_FILENAME (variable) β€” e.g. "best_model.pt" (default)
13
  """
14
 
15
  import os
 
16
  import json
17
  import torch
18
  import numpy as np
19
  import gradio as gr
20
  import librosa
 
21
 
22
  from huggingface_hub import hf_hub_download, snapshot_download
23
  from transformers import Wav2Vec2FeatureExtractor
@@ -25,12 +28,10 @@ from transformers import Wav2Vec2FeatureExtractor
25
  from wav2vec2_phonological import PhonologicalWav2Vec2
26
  from mdd_engine import run_mdd
27
  from feedback_generator import generate_feedback
28
- from phonological_features import (
29
- CMU_39_PHONEMES,
30
- )
31
 
32
  # ─────────────────────────────────────────────────────────────────────────────
33
- # 1. Model β€” loaded once at cold start, reused for every request
34
  # ─────────────────────────────────────────────────────────────────────────────
35
 
36
  _model = None
@@ -45,12 +46,9 @@ HF_TOKEN = os.environ.get("HF_TOKEN", None)
45
 
46
  def load_model():
47
  global _model, _feature_extractor
48
-
49
  if _model is not None:
50
  return
51
 
52
- # Download entire repo into ./model_cache once, then load from disk.
53
- # hf_hub_download checks cache first β€” no re-download if already present.
54
  print(f"[startup] Caching {MODEL_REPO} to ./model_cache ...")
55
  snapshot_download(
56
  repo_id=MODEL_REPO,
@@ -65,7 +63,6 @@ def load_model():
65
  num_output_nodes=71,
66
  freeze_cnn_encoder=True,
67
  )
68
-
69
  state_dict = torch.load(weights_path, map_location=_device)
70
  model.load_state_dict(state_dict)
71
  model.to(_device)
@@ -73,29 +70,59 @@ def load_model():
73
  _model = model
74
  print(f"[startup] Model ready on {_device}.")
75
 
76
- print(f"[startup] Loading feature extractor from '{PRETRAINED_BASE}' ...")
77
  _feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(PRETRAINED_BASE)
78
  print("[startup] Feature extractor ready.")
79
 
 
80
  # ─────────────────────────────────────────────────────────────────────────────
81
- # 2. Audio β†’ decoded feature sequences
82
  # ─────────────────────────────────────────────────────────────────────────────
83
 
84
- TARGET_SR = 16_000
85
 
86
 
87
- def decode_audio(audio_path: str) -> list:
88
- """
89
- Load audio, run the phonological model, return CTC-decoded feature seqs.
 
 
 
 
 
 
 
 
90
 
91
- Returns
92
- -------
93
- actual_feature_seqs : list of 35 lists of int (0 or 1)
94
- CTC-decoded +att / -att sequence for each of the 35 features.
 
 
95
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  load_model()
97
 
98
- waveform, sr = librosa.load(audio_path, sr=TARGET_SR, mono=True)
99
  waveform = waveform.astype(np.float32)
100
 
101
  inputs = _feature_extractor(
@@ -112,154 +139,122 @@ def decode_audio(audio_path: str) -> list:
112
 
113
  with torch.no_grad():
114
  logits, output_lengths = _model(
115
- input_values,
116
- attention_mask,
117
- apply_spec_augment=False,
118
  )
119
 
120
- # model.decode() returns list[B][35][list[bool]] β€” True=+att, False=-att
121
- decoded_batch = _model.decode(logits, output_lengths)
122
- decoded_35 = decoded_batch[0] # [35][list[bool]]
123
-
124
- # Convert bool β†’ int (1/0)
125
- actual_feature_seqs = [
126
- [1 if v else 0 for v in feat_seq]
127
- for feat_seq in decoded_35
128
- ]
129
-
130
- return actual_feature_seqs
131
-
132
-
133
- # ─────────────────────────────────────────────────────────────────────────────
134
- # 3. Text β†’ canonical phoneme sequence
135
- # ─────────────────────────────────────────────────────────────────────────────
136
-
137
- _VALID_PHONEMES = set(CMU_39_PHONEMES) | {"sil"}
138
-
139
-
140
- def parse_phoneme_input(text: str) -> list:
141
- """
142
- Accept space-separated CMU ARPAbet tokens typed by the user.
143
- Unknown tokens are skipped with a warning.
144
- """
145
- tokens = text.lower().split()
146
- valid, skipped = [], []
147
- for t in tokens:
148
- if t in _VALID_PHONEMES:
149
- valid.append(t)
150
- else:
151
- skipped.append(t)
152
- if skipped:
153
- print(f"[warning] Unrecognised tokens skipped: {skipped}")
154
- return valid if valid else ["sil"]
155
 
156
 
157
  # ─────────────────────────────────────────────────────────────────────────────
158
  # 4. Gradio processing function
159
  # ─────────────────────────────────────────────────────────────────────────────
160
 
161
- def process(audio_input, script_text, use_llm, max_issues):
162
  if audio_input is None:
163
- return "Please record or upload audio first.", "", "{}"
164
 
165
- script_text = script_text.strip()
166
- if not script_text:
 
 
 
 
 
167
  return (
168
- "Please type the target sentence as ARPAbet phoneme tokens.\n"
169
- "Example: `dh ae k ae t` for 'the cat'",
170
- "", "{}",
171
  )
172
 
 
 
 
 
 
 
173
  try:
174
  actual_feature_seqs = decode_audio(audio_input)
175
  except Exception as e:
176
- return f"Audio processing error: {e}", "", "{}"
177
-
178
- target_phonemes = parse_phoneme_input(script_text)
179
 
 
180
  try:
181
  result = run_mdd(
182
  actual_feature_seqs=actual_feature_seqs,
183
  target_phonemes=target_phonemes,
184
  )
185
  except Exception as e:
186
- return f"MDD engine error: {e}", "", "{}"
187
 
188
- feedback_dict = generate_feedback(
189
- result,
190
- use_llm=use_llm,
191
- max_issues=int(max_issues),
192
- )
193
 
194
  score = feedback_dict["score"]
195
  main_feedback = (
196
- f"**Pronunciation Score: {score}/100**\n\n"
197
  + feedback_dict["final_feedback"]
198
  )
199
 
200
- detail_lines = ["### Per-phoneme detail\n"]
 
201
  for e in feedback_dict["error_summary"]:
202
- deletion_tag = " *(deleted)*" if e.get("is_deletion") else ""
203
  detail_lines.append(
204
- f"- **/{e['target']}/** (pos {e['position']}){deletion_tag}: "
205
  f"severity=`{e['severity']}`, accuracy={e['accuracy']:.0%}\n"
206
  f" - Missing: {', '.join(e['missing_features']) or 'β€”'}\n"
207
  f" - Extra: {', '.join(e['extra_features']) or 'β€”'}"
208
  )
209
  if not feedback_dict["error_summary"]:
210
- detail_lines.append("No feature-level errors detected β€” great pronunciation!")
211
-
212
- detail_text = "\n".join(detail_lines)
213
 
214
  json_output = json.dumps({
215
  "score": feedback_dict["score"],
 
216
  "deletion_count": result.deletion_count,
217
  "insertion_count": result.insertion_count,
218
  "feature_error_counts": feedback_dict["feature_error_counts"],
219
- "rules_triggered": feedback_dict["rules_triggered"],
220
- "target_phonemes": target_phonemes,
221
  "actual_seq_lengths": [len(s) for s in actual_feature_seqs],
222
  }, indent=2)
223
 
224
- return main_feedback, detail_text, json_output
225
 
226
 
227
  # ─────────────────────────────────────────────────────────────────────────────
228
  # 5. Gradio UI
229
  # ─────────────────────────────────────────────────────────────────────────────
230
 
231
- VALID_PHONEME_LIST = ", ".join(sorted(CMU_39_PHONEMES))
232
-
233
  with gr.Blocks(title="Pronunciation Coach", theme=gr.themes.Soft()) as demo:
234
  gr.Markdown(
235
  """
236
- # Pronunciation Coach
237
- Speak a sentence, type what you meant to say as **ARPAbet phoneme tokens**,
238
  and get phonological-feature-level feedback with articulation tips.
239
  """
240
  )
241
 
242
  with gr.Row():
243
  with gr.Column(scale=1):
 
 
 
 
 
244
  audio_input = gr.Audio(
245
  sources=["microphone", "upload"],
246
  type="filepath",
247
- label="Your speech",
248
- )
249
- script_input = gr.Textbox(
250
- label="Target sentence β€” space-separated ARPAbet tokens",
251
- placeholder="e.g. dh ae k ae t (= 'the cat')",
252
- lines=2,
253
  )
254
- with gr.Accordion("Valid phoneme tokens", open=False):
255
- gr.Markdown(f"`{VALID_PHONEME_LIST}`")
256
  with gr.Row():
257
  use_llm = gr.Checkbox(value=False, label="LLM feedback rewriter")
258
  max_issues = gr.Slider(1, 5, value=3, step=1, label="Max issues shown")
259
  submit_btn = gr.Button("Analyse", variant="primary")
260
 
261
  with gr.Column(scale=2):
262
- feedback_out = gr.Markdown(label="Coaching feedback")
 
263
  with gr.Accordion("Per-phoneme detail", open=False):
264
  detail_out = gr.Markdown()
265
  with gr.Accordion("Raw JSON (developers)", open=False):
@@ -267,18 +262,15 @@ with gr.Blocks(title="Pronunciation Coach", theme=gr.themes.Soft()) as demo:
267
 
268
  submit_btn.click(
269
  fn=process,
270
- inputs=[audio_input, script_input, use_llm, max_issues],
271
- outputs=[feedback_out, detail_out, json_out],
272
  )
273
 
274
  gr.Markdown(
275
  """
276
  ---
277
- **How to enter the target sentence:**
278
- Convert your sentence to ARPAbet using the
279
- [CMU Pronouncing Dictionary](http://www.speech.cs.cmu.edu/cgi-bin/cmudict)
280
- then paste the space-separated tokens here.
281
- Example: *"the cat sat"* β†’ `dh ax k ae t s ae t`
282
  """
283
  )
284
 
 
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
17
+ import re
18
  import json
19
  import torch
20
  import numpy as np
21
  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
 
28
  from wav2vec2_phonological import PhonologicalWav2Vec2
29
  from mdd_engine import run_mdd
30
  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
 
46
 
47
  def load_model():
48
  global _model, _feature_extractor
 
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,
 
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)
 
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(
 
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):
 
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
 
requirements.txt CHANGED
@@ -1,17 +1,11 @@
1
- # Core
2
  gradio>=4.0.0
3
  numpy>=1.24.0
4
  scipy>=1.10.0
5
-
6
- # Model
7
  torch>=2.0.0
8
  transformers>=4.40.0
9
  huggingface_hub>=0.20.0
10
-
11
- # Audio
12
  librosa>=0.10.0
13
  soundfile>=0.12.0
14
-
15
- # Optional LLM rewriter
16
  accelerate>=0.27.0
17
  httpx>=0.25.0
 
 
 
1
  gradio>=4.0.0
2
  numpy>=1.24.0
3
  scipy>=1.10.0
 
 
4
  torch>=2.0.0
5
  transformers>=4.40.0
6
  huggingface_hub>=0.20.0
 
 
7
  librosa>=0.10.0
8
  soundfile>=0.12.0
 
 
9
  accelerate>=0.27.0
10
  httpx>=0.25.0
11
+ pronouncing>=0.2.0