WJ88 commited on
Commit
41d27d9
Β·
verified Β·
1 Parent(s): d22d81d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimised NeMo Parakeet-TDT streaming demo for CPU-only Hugging Face Spaces
3
+ """
4
+
5
+ import os, time, threading, queue, logging
6
+ import numpy as np
7
+ import gradio as gr
8
+ from scipy import signal
9
+ import torch
10
+ from nemo.collections.asr.models import ASRModel
11
+
12
+ # ────────────────────────────────────────────────
13
+ # General CPU settings (2 vCPU space)
14
+ # ────────────────────────────────────────────────
15
+ os.environ["OMP_NUM_THREADS"] = "2" # One MKL/OpenMP thread per vCPU
16
+ torch.set_num_threads(2)
17
+ torch.backends.quantized.engine = "fbgemm" # Fastest INT8 kernels on x86
18
+
19
+ # ────────────────────────────────────────────────
20
+ # Logging
21
+ # ────────────────────────────────────────────────
22
+ logging.basicConfig(
23
+ level=logging.INFO,
24
+ format="%(asctime)s - %(message)s",
25
+ datefmt="%H:%M:%S",
26
+ )
27
+ logger = logging.getLogger("asr_app")
28
+
29
+ # ────────────────────────────────────────────────
30
+ # Constants
31
+ # ────────────────────────────────────────────────
32
+ SR = 16_000 # Model sample-rate
33
+ CHUNK_SECONDS = 4 # seconds per inference window
34
+ CHUNK_SAMPLES = SR * CHUNK_SECONDS
35
+
36
+ # ────────────────────────────────────────────────
37
+ # ASR Application
38
+ # ────────────────────────────────────────────────
39
+ class ASRApp:
40
+ def __init__(self):
41
+ self.audio_queue = queue.Queue(maxsize=100)
42
+ self.transcript_queue = queue.Queue()
43
+ self.transcript_list = []
44
+ self._load_model()
45
+ self._start_worker()
46
+
47
+ # ---------- helpers ----------
48
+ def _log(self, func: str, msg: str):
49
+ logger.info(
50
+ f"{func} | audio_q={self.audio_queue.qsize():02}, "
51
+ f"txt_q={self.transcript_queue.qsize():02} | {msg}"
52
+ )
53
+
54
+ # ---------- model ----------
55
+ def _load_model(self):
56
+ self._log("load_model", "loading Parakeet-TDT-0.6B-V2 (CPU)…")
57
+ t0 = time.time()
58
+ model = ASRModel.from_pretrained(
59
+ model_name="nvidia/parakeet-tdt-0.6b-v2",
60
+ map_location="cpu",
61
+ )
62
+ model.eval() # inference mode
63
+ # ---- dynamic INT8 quantisation ----
64
+ try:
65
+ model = torch.quantization.quantize_dynamic(
66
+ model,
67
+ {torch.nn.Linear, torch.nn.LSTM, torch.nn.GRU},
68
+ dtype=torch.qint8,
69
+ )
70
+ self._log("load_model", "INT8 quantisation applied")
71
+ except Exception as e:
72
+ self._log("load_model", f"quantisation skipped ({e})")
73
+ self.asr_model = model
74
+ self._log("load_model", f"model ready in {time.time()-t0:.1f}s")
75
+ # warm-up (1 Γ— 1 s of zeros)
76
+ with torch.inference_mode():
77
+ _ = self.asr_model.transcribe(
78
+ [np.zeros(SR, dtype=np.float32)]
79
+ )
80
+ self._log("load_model", "warm-up done")
81
+
82
+ # ---------- threading ----------
83
+ def _start_worker(self):
84
+ threading.Thread(
85
+ target=self._worker,
86
+ daemon=True,
87
+ ).start()
88
+
89
+ def _worker(self):
90
+ buf = np.array([], dtype=np.float32)
91
+ while True:
92
+ try:
93
+ # accumulate until CHUNK_SAMPLES
94
+ while len(buf) < CHUNK_SAMPLES:
95
+ buf = np.concatenate([buf, self.audio_queue.get()])
96
+ self._log("_worker", f"buffer={len(buf)}")
97
+ chunk, buf = buf[:CHUNK_SAMPLES], buf[CHUNK_SAMPLES:]
98
+ self._log("_worker", f"β†’ transcribe {len(chunk)} samples")
99
+ t0 = time.time()
100
+ with torch.inference_mode():
101
+ out = self.asr_model.transcribe([chunk])
102
+ dur = time.time() - t0
103
+ text = out[0].text
104
+ self._log("_worker", f"inference {dur:.2f}s β†’ β€œ{text}”")
105
+ self.transcript_queue.put(text)
106
+ except Exception as e:
107
+ self._log("_worker", f"ASR error: {e}")
108
+
109
+ # ---------- audio preprocessing ----------
110
+ def _preprocess(self, audio):
111
+ sr, y = audio
112
+ if y.ndim > 1:
113
+ y = y.mean(axis=1)
114
+ if sr != SR:
115
+ # resample faster with polyphase filter
116
+ y = signal.resample_poly(y, SR, sr)
117
+ y = y.astype(np.float32)
118
+ y /= (np.abs(y).max() + 1e-9)
119
+ return y
120
+
121
+ # ---------- Gradio stream callback ----------
122
+ def stream_fn(self, audio):
123
+ self._log("stream_fn", "audio arrived")
124
+ self.audio_queue.put(self._preprocess(audio))
125
+ while not self.transcript_queue.empty():
126
+ self.transcript_list.append(self.transcript_queue.get())
127
+ return (
128
+ " ".join(self.transcript_list)
129
+ if self.transcript_list
130
+ else "…listening…"
131
+ )
132
+
133
+ # ────────────────────────────────────────────────
134
+ # Gradio UI
135
+ # ────────────────────────────────────────────────
136
+ asr_app = ASRApp()
137
+ with gr.Blocks() as demo:
138
+ mic = gr.Audio(
139
+ sources=["microphone"],
140
+ type="numpy",
141
+ streaming=True,
142
+ label="Microphone",
143
+ )
144
+ out = gr.Textbox(label="Transcription")
145
+ mic.stream(
146
+ fn=asr_app.stream_fn,
147
+ inputs=mic,
148
+ outputs=out,
149
+ stream_every=0.5, # ↓ UI calls per second
150
+ )
151
+
152
+ asr_app._log("main", "launching UI")
153
+ demo.launch()