IbnAoudi commited on
Commit
73d1bf6
·
verified ·
1 Parent(s): f236b57

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +191 -0
  2. kenlm_5gram.arpa +0 -0
  3. requirements.txt +8 -0
  4. start.sh +13 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — Gradio ASR avec fallback (LM si disponible)
2
+ import os, time, json
3
+ import torch
4
+ import numpy as np
5
+ import librosa
6
+ from scipy.special import log_softmax
7
+ import gradio as gr
8
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
9
+
10
+ # Try to import pyctcdecode (may fail if kenlm not installed)
11
+ try:
12
+ from pyctcdecode import build_ctcdecoder
13
+ PYCTC_OK = True
14
+ except Exception as e:
15
+ build_ctcdecoder = None
16
+ PYCTC_OK = False
17
+
18
+ # ---------- CONFIG ----------
19
+ MODEL_ID = "IbnAoudi/fulfulfudecameroun" # already pushed on HF
20
+ KENLM_ARPA_PATH = "kenlm_5gram.arpa" # place this file in the Space root
21
+ SAMPLE_RATE = 16000
22
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
23
+ # ----------------------------
24
+
25
+ print("Loading model from:", MODEL_ID)
26
+ processor = Wav2Vec2Processor.from_pretrained(MODEL_ID)
27
+ model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID)
28
+ model.to(DEVICE)
29
+ model.eval()
30
+ print("Model loaded. Device:", DEVICE)
31
+
32
+ # --- Build safe alphabet for decoder ---
33
+ tokenizer = processor.tokenizer
34
+ vocab_size = getattr(tokenizer, "vocab_size", None) or len(tokenizer.get_vocab())
35
+ # convert ids -> tokens in id order (robust)
36
+ tokens = tokenizer.convert_ids_to_tokens(list(range(vocab_size)))
37
+ # create alphabet_for_decoder where index i corresponds to token id i
38
+ alphabet_for_decoder = []
39
+ pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else None
40
+ unk_id = tokenizer.unk_token_id if hasattr(tokenizer, "unk_token_id") else None
41
+
42
+ for i, tok in enumerate(tokens):
43
+ # Standardize special tokens: pad/unk/cls/special to empty string (pyctcdecode expects blank token as "")
44
+ if pad_id is not None and i == pad_id:
45
+ alphabet_for_decoder.append("") # blank (CTC)
46
+ elif tok in {tokenizer.pad_token, tokenizer.eos_token, tokenizer.bos_token, tokenizer.cls_token,
47
+ tokenizer.sep_token, tokenizer.unk_token, "<s>", "</s>", "<pad>", "<unk>"}:
48
+ alphabet_for_decoder.append("") # remove special tokens for decoder
49
+ else:
50
+ # Some tokenizers return tokens like "▁a" or "Ġa" for wordpieces — keep them as-is or strip special markers if needed
51
+ # For CTC char-based decoders it's good to keep the visible character
52
+ alphabet_for_decoder.append(tok)
53
+
54
+ print("Alphabet length:", len(alphabet_for_decoder))
55
+
56
+ decoder = None
57
+ if PYCTC_OK and os.path.exists(KENLM_ARPA_PATH):
58
+ try:
59
+ t0 = time.time()
60
+ decoder = build_ctcdecoder(alphabet_for_decoder, KENLM_ARPA_PATH)
61
+ print("Decoder built (KenLM) in {:.1f}s".format(time.time() - t0))
62
+ except Exception as e:
63
+ print("Warning: failed to build decoder (pyctcdecode/kenlm). LM disabled. Error:", e)
64
+ decoder = None
65
+ else:
66
+ if not PYCTC_OK:
67
+ print("pyctcdecode not available -> LM disabled (decoder=None).")
68
+ else:
69
+ print(f"KenLM ARPA file not found at {KENLM_ARPA_PATH} -> LM disabled.")
70
+
71
+ # --- normalisation (same style as compute_metrics_fast) ---
72
+ import re, unicodedata
73
+ def normalize_text(s: str):
74
+ if s is None: return ""
75
+ s = unicodedata.normalize("NFKC", str(s)).lower().strip()
76
+ s = re.sub(r"[’`ʼ‹›´]", "'", s)
77
+ s = s.replace("|", " ")
78
+ s = re.sub(r"[^0-9a-zɓɗŋƴɲəàáâãäçèéêëìíîïòóôõöùúûüÿ'\t \-]", " ", s)
79
+ s = re.sub(r"\s+", " ", s).strip()
80
+ return s
81
+
82
+ # --- decoder helper with safe confidence estimation ---
83
+ def decode_with_lm_np(logits_np: np.array, beam_width=50, alpha=0.8, beta=1.0):
84
+ lp = log_softmax(logits_np, axis=-1)
85
+ # try decoder
86
+ try:
87
+ text = decoder.decode(lp, beam_width=int(beam_width), alpha=float(alpha), beta=float(beta))
88
+ # pyctcdecode does not always return a stable 'score' value; compute a fallback confidence
89
+ # heuristic: average max timestep prob (from softmax)
90
+ max_probs = np.max(np.exp(lp), axis=-1)
91
+ conf = float(np.mean(max_probs))
92
+ conf = max(0.0, min(1.0, conf))
93
+ except Exception as e:
94
+ # fallback: greedy decode
95
+ pred_ids = np.argmax(logits_np, axis=-1)
96
+ prev = None
97
+ out = []
98
+ for p in pred_ids:
99
+ if p != prev:
100
+ out.append(p)
101
+ prev = p
102
+ out = [p for p in out if p != tokenizer.pad_token_id]
103
+ text = processor.batch_decode([out])[0]
104
+ max_probs = np.max(np.exp(lp), axis=-1)
105
+ conf = float(np.mean(max_probs))
106
+ conf = max(0.0, min(1.0, conf))
107
+ return text, conf
108
+
109
+ # --- main transcribe function ---
110
+ def transcribe(audio, beam_width=50, alpha=0.8, beta=1.0, use_lm=True):
111
+ if audio is None:
112
+ return {"transcription": "", "transcription_norm": "", "confidence": 0.0}
113
+ # gradio: numpy tuple (sr, array) or path string
114
+ if isinstance(audio, tuple) and len(audio) == 2:
115
+ sr, wav_np = audio # some gradio versions invert order
116
+ # handle both patterns:
117
+ if isinstance(sr, np.ndarray):
118
+ # sometimes returns (np_array, sr)
119
+ wav_np, sr = sr, wav_np
120
+ elif isinstance(audio, str) and os.path.exists(audio):
121
+ wav_np, sr = librosa.load(audio, sr=None)
122
+ else:
123
+ # assume np array + SAMPLE_RATE
124
+ wav_np = np.array(audio)
125
+ sr = SAMPLE_RATE
126
+
127
+ # resample if needed
128
+ if sr != SAMPLE_RATE:
129
+ wav_np = librosa.resample(wav_np.astype(float), orig_sr=sr, target_sr=SAMPLE_RATE)
130
+ sr = SAMPLE_RATE
131
+
132
+ if wav_np.ndim > 1:
133
+ wav_np = np.mean(wav_np, axis=1)
134
+ wav_np = wav_np.astype(np.float32)
135
+
136
+ inputs = processor(wav_np, sampling_rate=SAMPLE_RATE, return_tensors="pt", padding=True)
137
+ input_values = inputs.input_values.to(DEVICE)
138
+
139
+ with torch.no_grad():
140
+ logits = model(input_values).logits.cpu().numpy() # (B, T, V)
141
+
142
+ logits_np = logits[0]
143
+
144
+ if use_lm and decoder is not None:
145
+ raw_pred, conf = decode_with_lm_np(logits_np, beam_width=int(beam_width), alpha=float(alpha), beta=float(beta))
146
+ else:
147
+ # greedy
148
+ pred_ids = np.argmax(logits_np, axis=-1)
149
+ prev = None
150
+ out = []
151
+ for p in pred_ids:
152
+ if p != prev:
153
+ out.append(p)
154
+ prev = p
155
+ out = [p for p in out if p != tokenizer.pad_token_id]
156
+ raw_pred = processor.batch_decode([out])[0]
157
+ lp = log_softmax(logits_np, axis=-1)
158
+ max_probs = np.max(np.exp(lp), axis=-1)
159
+ conf = float(np.mean(max_probs))
160
+ conf = max(0.0, min(1.0, conf))
161
+
162
+ pred_norm = normalize_text(raw_pred)
163
+ return {"transcription": raw_pred, "transcription_norm": pred_norm, "confidence": round(float(conf), 4)}
164
+
165
+ # --- Gradio UI ---
166
+ title = "ASR XLS-R 300m — Live transcription (LM optional)"
167
+ description = "Record or upload audio. If KenLM is available, decoding uses pyctcdecode+KenLM. Otherwise greedy fallback."
168
+
169
+ with gr.Blocks() as demo:
170
+ gr.Markdown(f"## {title}\n\nDevice: **{DEVICE}**\n\n{description}")
171
+ with gr.Row():
172
+ with gr.Column(scale=2):
173
+ audio_in = gr.Audio(source="microphone", type="numpy", label="Record or upload audio (wav)")
174
+ use_lm_checkbox = gr.Checkbox(value=True, label="Use LM (pyctcdecode + KenLM)")
175
+ beam_slider = gr.Slider(minimum=1, maximum=200, step=1, value=50, label="Beam width (LM)")
176
+ alpha_slider = gr.Slider(minimum=0.0, maximum=4.0, step=0.05, value=0.8, label="LM weight (alpha)")
177
+ beta_slider = gr.Slider(minimum=0.0, maximum=4.0, step=0.05, value=1.0, label="Word insertion (beta)")
178
+ btn = gr.Button("Transcribe")
179
+ with gr.Column(scale=3):
180
+ out_txt = gr.Textbox(label="Transcription (raw)", lines=4)
181
+ out_norm = gr.Textbox(label="Transcription (normalized)", lines=2)
182
+ out_conf = gr.Textbox(label="Confidence")
183
+ def _run(a, use_lm, beam, a_w, b_w):
184
+ res = transcribe(a, beam_width=beam, alpha=a_w, beta=b_w, use_lm=use_lm)
185
+ return res["transcription"], res["transcription_norm"], str(res["confidence"])
186
+ btn.click(_run, inputs=[audio_in, use_lm_checkbox, beam_slider, alpha_slider, beta_slider],
187
+ outputs=[out_txt, out_norm, out_conf])
188
+
189
+ if __name__ == "__main__":
190
+ # On Spaces, no need for share=True. On Colab you may want share=True.
191
+ demo.launch()
kenlm_5gram.arpa ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch # let Space choose supported version; or pin if needed
2
+ transformers==4.57.0
3
+ librosa==0.10.1
4
+ soundfile==0.12.1
5
+ gradio==3.39.0
6
+ pyctcdecode==0.34.0
7
+ scipy
8
+ numpy
start.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -e
3
+
4
+ echo "Installing system deps for KenLM..."
5
+ apt-get update && apt-get install -y build-essential cmake libbz2-dev liblzma-dev zlib1g-dev
6
+
7
+ echo "Installing kenlm from GitHub (may take a while)..."
8
+ pip install --no-cache-dir https://github.com/kpu/kenlm/archive/master.zip
9
+
10
+ echo "Installing pyctcdecode with kenlm support..."
11
+ pip install --no-cache-dir pyctcdecode[kenlm]
12
+
13
+ echo "Done start.sh"