Spaces:
Running on Zero

macvinh commited on
Commit
fa22051
·
verified ·
1 Parent(s): 4cc4d42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -43
app.py CHANGED
@@ -1,52 +1,34 @@
1
  # =====================================================================
2
  # Chép lời tiếng Việt — ZipFormer-150M fine-tuned
3
- # Hugging Face Space (Gradio). Logic nạp model/giải mã CTC được chuyển
4
- # nguyên từ notebook Fine_Tune_ZipFormer_150M_Vietnamese (mục 3–6).
5
  # =====================================================================
6
- import torch
7
-
8
- try:
9
- torch.set_num_interop_threads(1)
10
- except RuntimeError:
11
- pass
12
-
13
- # Sau đó mới đến các lệnh import còn lại
14
- import torchaudio
15
- # ...
16
- from train import get_model, get_parser, get_params
17
- import os, sys, types, subprocess
18
  from pathlib import Path
19
 
20
  import torch
21
  import torch.nn.functional as F
22
  import torchaudio
23
- import gradio as gr
24
  from torch.nn.utils.rnn import pad_sequence
25
- import spaces # Thư viện ZeroGPU của Hugging Face
26
- import torch
27
  import gradio as gr
 
28
 
29
- # Hàm xử lý được gắn nhãn @spaces.GPU sẽ tự động được cấp phát GPU A10G khi chạy
30
- @spaces.GPU
31
- def transcribe(audio_path):
32
- # Code xử lý GPU tại đây
33
- waveform = waveform.to("cuda")
34
- # ...
35
- return text
36
 
37
  MODEL_REPO = "hynt/ZipFormer-150M-CR-CTC-RNNT-6000h"
38
- # Checkpoint đã fine-tune: hoặc để sẵn tại Space theo đường dẫn FINETUNED_CKPT,
39
- # hoặc (khuyên dùng, tránh giới hạn 1GB private storage) đặt biến môi trường
40
- # FINETUNED_REPO trong Settings -> Variables and secrets của Space, trỏ tới
41
- # 1 Model repo Public chứa file zipformer_best.pt. Xem README.md.
42
  FINETUNED_CKPT = "checkpoints/zipformer_best.pt"
43
  FINETUNED_REPO = os.environ.get("FINETUNED_REPO", "").strip()
44
  AUDIO_SCALE = 1.0
45
  MAX_SEC = 90
46
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
47
 
48
 
49
- # ---------- 1. K2 stub (giống notebook, mục 3) ----------
50
  def swoosh_l(x):
51
  return (F.softplus(x - 4.0) - 0.08 * x - 0.035).to(x.dtype)
52
 
@@ -92,7 +74,7 @@ sys.modules.update({
92
  })
93
 
94
 
95
- # ---------- 2. Tải pretrained + Icefall (mục 4) ----------
96
  from huggingface_hub import snapshot_download
97
 
98
  repo_path = snapshot_download(repo_id=MODEL_REPO,
@@ -106,12 +88,11 @@ for p in ["/tmp/icefall", "/tmp/icefall/egs/librispeech/ASR",
106
  if p not in sys.path:
107
  sys.path.append(p)
108
 
109
- import scaling # noqa: F401 (đăng ký các lớp scaling cần cho get_model)
110
  from train import get_model, get_parser, get_params
111
 
112
 
113
- # ---------- 3. Dựng model & nạp trọng số (mục 5) ----------
114
- import sentencepiece as spm
115
  import train as _train
116
  _train.get_env_info = lambda: {"k2-version": "stub"}
117
 
@@ -150,15 +131,13 @@ model = get_model(params)
150
  res = model.load_state_dict(state_dict, strict=False)
151
  assert len(res.missing_keys) == 0, f"Thiếu trọng số: {res.missing_keys[:5]}"
152
 
153
- # Nạp đè bằng checkpoint đã fine-tune: ưu tiên tải từ FINETUNED_REPO (Model
154
- # repo riêng trên Hugging Face) nếu có khai báo, sau đó mới tới file local.
155
  ft_path = None
156
  if FINETUNED_REPO:
157
  try:
158
  ft_dir = snapshot_download(repo_id=FINETUNED_REPO, allow_patterns=["*.pt"])
159
  cand = sorted(Path(ft_dir).rglob("*.pt"))
160
  ft_path = str(cand[0]) if cand else None
161
- except Exception as e: # noqa: BLE001
162
  print(f"Không tải được FINETUNED_REPO={FINETUNED_REPO}: {e}")
163
  if ft_path is None and os.path.exists(FINETUNED_CKPT):
164
  ft_path = FINETUNED_CKPT
@@ -171,15 +150,15 @@ if ft_path:
171
  f"unexpected={len(r.unexpected_keys)}")
172
  USING_FINETUNED = True
173
  else:
174
- print("CHƯA có checkpoint fine-tune (FINETUNED_REPO hoặc "
175
- f"{FINETUNED_CKPT}) — đang dùng model gốc (chưa fine-tune).")
176
  USING_FINETUNED = False
177
 
178
- model.to(device).eval()
 
179
  N_PARAMS = sum(p.numel() for p in model.parameters()) / 1e6
180
 
181
 
182
- # ---------- 4. Fbank + giải mã CTC (mục 6) ----------
183
  def load_fbank(path):
184
  wav, sr = torchaudio.load(path)
185
  if wav.size(0) > 1:
@@ -202,7 +181,8 @@ def encode(model, x, x_lens):
202
 
203
  @torch.no_grad()
204
  def ctc_greedy_decode(model, paths, batch_size=4):
205
- model.eval()
 
206
  hyps = []
207
  for i in range(0, len(paths), batch_size):
208
  feats = [load_fbank(p) for p in paths[i:i + batch_size]]
@@ -221,7 +201,8 @@ def sentence_case(t: str) -> str:
221
  return t[0].upper() + t[1:] if t else t
222
 
223
 
224
- # ---------- 5. Giao diện web (Gradio) ----------
 
225
  def transcribe(audio_path):
226
  if not audio_path:
227
  return "", ""
@@ -231,6 +212,7 @@ def transcribe(audio_path):
231
  raise gr.Error("Âm thanh quá ngắn (dưới 0,3 giây).")
232
  if duration > MAX_SEC:
233
  raise gr.Error(f"Âm thanh dài {duration:.0f} giây, vượt giới hạn {MAX_SEC} giây.")
 
234
  text = ctc_greedy_decode(model, [audio_path])[0]
235
  status = f"{duration:.1f} giây · " + (
236
  "mô hình đã fine-tune" if USING_FINETUNED else
 
1
  # =====================================================================
2
  # Chép lời tiếng Việt — ZipFormer-150M fine-tuned
3
+ # Hugging Face Space (Gradio + ZeroGPU).
 
4
  # =====================================================================
5
+ import os
6
+ import sys
7
+ import types
8
+ import subprocess
 
 
 
 
 
 
 
 
9
  from pathlib import Path
10
 
11
  import torch
12
  import torch.nn.functional as F
13
  import torchaudio
 
14
  from torch.nn.utils.rnn import pad_sequence
15
+ import sentencepiece as spm
 
16
  import gradio as gr
17
+ import spaces # Thư viện ZeroGPU của Hugging Face
18
 
19
+ try:
20
+ torch.set_num_interop_threads(1)
21
+ except RuntimeError:
22
+ pass
 
 
 
23
 
24
  MODEL_REPO = "hynt/ZipFormer-150M-CR-CTC-RNNT-6000h"
 
 
 
 
25
  FINETUNED_CKPT = "checkpoints/zipformer_best.pt"
26
  FINETUNED_REPO = os.environ.get("FINETUNED_REPO", "").strip()
27
  AUDIO_SCALE = 1.0
28
  MAX_SEC = 90
 
29
 
30
 
31
+ # ---------- 1. K2 stub ----------
32
  def swoosh_l(x):
33
  return (F.softplus(x - 4.0) - 0.08 * x - 0.035).to(x.dtype)
34
 
 
74
  })
75
 
76
 
77
+ # ---------- 2. Tải pretrained + Icefall ----------
78
  from huggingface_hub import snapshot_download
79
 
80
  repo_path = snapshot_download(repo_id=MODEL_REPO,
 
88
  if p not in sys.path:
89
  sys.path.append(p)
90
 
91
+ import scaling # noqa: F401
92
  from train import get_model, get_parser, get_params
93
 
94
 
95
+ # ---------- 3. Dựng model & nạp trọng số ----------
 
96
  import train as _train
97
  _train.get_env_info = lambda: {"k2-version": "stub"}
98
 
 
131
  res = model.load_state_dict(state_dict, strict=False)
132
  assert len(res.missing_keys) == 0, f"Thiếu trọng số: {res.missing_keys[:5]}"
133
 
 
 
134
  ft_path = None
135
  if FINETUNED_REPO:
136
  try:
137
  ft_dir = snapshot_download(repo_id=FINETUNED_REPO, allow_patterns=["*.pt"])
138
  cand = sorted(Path(ft_dir).rglob("*.pt"))
139
  ft_path = str(cand[0]) if cand else None
140
+ except Exception as e:
141
  print(f"Không tải được FINETUNED_REPO={FINETUNED_REPO}: {e}")
142
  if ft_path is None and os.path.exists(FINETUNED_CKPT):
143
  ft_path = FINETUNED_CKPT
 
150
  f"unexpected={len(r.unexpected_keys)}")
151
  USING_FINETUNED = True
152
  else:
153
+ print("CHƯA có checkpoint fine-tune — đang dùng model gốc.")
 
154
  USING_FINETUNED = False
155
 
156
+ # Giữ mô hình trên CPU lúc khởi tạo để tương thích ZeroGPU
157
+ model.to("cpu").eval()
158
  N_PARAMS = sum(p.numel() for p in model.parameters()) / 1e6
159
 
160
 
161
+ # ---------- 4. Fbank + giải mã CTC ----------
162
  def load_fbank(path):
163
  wav, sr = torchaudio.load(path)
164
  if wav.size(0) > 1:
 
181
 
182
  @torch.no_grad()
183
  def ctc_greedy_decode(model, paths, batch_size=4):
184
+ device = "cuda" if torch.cuda.is_available() else "cpu"
185
+ model.to(device).eval()
186
  hyps = []
187
  for i in range(0, len(paths), batch_size):
188
  feats = [load_fbank(p) for p in paths[i:i + batch_size]]
 
201
  return t[0].upper() + t[1:] if t else t
202
 
203
 
204
+ # ---------- 5. Giao diện web (Gradio + ZeroGPU) ----------
205
+ @spaces.GPU
206
  def transcribe(audio_path):
207
  if not audio_path:
208
  return "", ""
 
212
  raise gr.Error("Âm thanh quá ngắn (dưới 0,3 giây).")
213
  if duration > MAX_SEC:
214
  raise gr.Error(f"Âm thanh dài {duration:.0f} giây, vượt giới hạn {MAX_SEC} giây.")
215
+
216
  text = ctc_greedy_decode(model, [audio_path])[0]
217
  status = f"{duration:.1f} giây · " + (
218
  "mô hình đã fine-tune" if USING_FINETUNED else