James commited on
Commit ·
d2ed7e8
1
Parent(s): dd150f6
Add realtime streaming ASR UI
Browse filesFiles changed (2)
- app.py+94-41
- transcribe.py+111-10
1234563 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import osimport gradio as grfrom transcribe import transcribeMODEL_CHOICES = ["离线模型",3 unmodified lines"流式 1920ms",]def predict_asr(input_audio, model_mode):"""Gradio 音频组件在 type="numpy" 时,会传入 (sample_rate, audio_data)。"""if input_audio is None:return "请先上传或录制音频!"# 2. 运行 ASR 推理# Whisper/Wav2Vec2 的 Pipeline 会自动读取路径并完成 Fbank 提取与解码result = transcribe(input_audio, model_mode=model_mode)# 3. 返回识别出的文本结果 (对应 outputs 的文本框)return result["text"]# 4. 准备一条默认音频作为示例# 💡 提示:请确保在你的脚本同级目录下,真的存在一个名为 "default_sample.wav" 的真实音频文件default_audio_path = "default_sample.mp3"# 如果文件不存在,我们先临时创建一个空文件作为占位,防止 Gradio 启动时找不到文件崩掉if not os.path.exists(default_audio_path):with open(default_audio_path, "wb") as f:pass # 实际运行前请替换为真实的语音测试文件(如一段 Fbank 完好的 wav 语音)# 5. 构建 ASR 交互界面gradio_app = gr.Interface(fn=predict_asr,inputs=[gr.Audio(label="上传语音或点击录音", sources=["upload", "microphone"], type="numpy"),gr.Dropdown(label="模型模式",choices=MODEL_CHOICES,value="离线模型",interactive=True,),],outputs=gr.Textbox(label="ASR 识别文本结果"),title="Zipformer-large 语音识别系统",examples=[[default_audio_path, "离线模型"],[default_audio_path, "流式 160ms"],[default_audio_path, "流式 480ms"],[default_audio_path, "流式 960ms"],[default_audio_path, "流式 1920ms"],],example_labels=["默认音频 - 离线模型","默认音频 - 流式 160ms","默认音频 - 流式 480ms","默认音频 - 流式 960ms","默认音频 - 流式 1920ms",],cache_examples=False,)if __name__ == "__main__":# share=True 可以白嫖一个公网链接,方便在没有 GUI 的 Linux 训练服务器上进行远程前端调试gradio_app.launch(share=False)123456789101112133 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import osimport gradio as grfrom transcribe import (finish_streaming_realtime,reset_realtime_stream,transcribe,transcribe_streaming_realtime,)MODEL_CHOICES = ["离线模型",3 unmodified lines"流式 1920ms",]STREAMING_CHOICES = MODEL_CHOICES[1:]def predict_asr(input_audio, model_mode):if input_audio is None:return "请先上传或录制音频!"result = transcribe(input_audio, model_mode=model_mode)return result["text"]default_audio_path = "default_sample.mp3"if not os.path.exists(default_audio_path):with open(default_audio_path, "wb") as f:passwith gr.Blocks(title="Zipformer-large 语音识别系统") as gradio_app:gr.Markdown("# Zipformer-large 语音识别系统")with gr.Tab("整段识别"):batch_audio = gr.Audio(label="上传语音或点击录音",sources=["upload", "microphone"],type="numpy",)batch_mode = gr.Dropdown(label="模型模式",choices=MODEL_CHOICES,value="离线模型",interactive=True,)batch_button = gr.Button("识别", variant="primary")batch_output = gr.Textbox(label="ASR 识别文本结果")gr.Examples(examples=[[default_audio_path, "离线模型"],[default_audio_path, "流式 160ms"],[default_audio_path, "流式 480ms"],[default_audio_path, "流式 960ms"],[default_audio_path, "流式 1920ms"],],inputs=[batch_audio, batch_mode],outputs=batch_output,fn=predict_asr,cache_examples=False,)with gr.Tab("实时流式识别"):stream_mode = gr.Dropdown(label="流式模型",choices=STREAMING_CHOICES,value="流式 160ms",interactive=True,)stream_audio = gr.Audio(label="麦克风",sources=["microphone"],type="numpy",streaming=True,)stream_output = gr.Textbox(label="实时识别文本")stream_state = gr.State({})with gr.Row():reset_button = gr.Button("重置")finish_button = gr.Button("结束")stream_audio.stream(fn=transcribe_streaming_realtime,inputs=[stream_audio, stream_state, stream_mode],outputs=[stream_output, stream_state],show_progress="hidden",)stream_mode.change(fn=reset_realtime_stream,inputs=stream_mode,outputs=[stream_output, stream_state],show_progress="hidden",)reset_button.click(fn=reset_realtime_stream,inputs=stream_mode,outputs=[stream_output, stream_state],show_progress="hidden",)finish_button.click(fn=finish_streaming_realtime,inputs=[stream_state, stream_mode],outputs=[stream_output, stream_state],show_progress="hidden",)batch_button.click(fn=predict_asr,inputs=[batch_audio, batch_mode],outputs=batch_output,)if __name__ == "__main__":gradio_app.launch(share=False)
325 unmodified lines32632732832933033133221 unmodified lines35435535635735835915 unmodified lines3753763773783793803813823833843853863873888 unmodified lines397398399400401402403404405406407408409410411412413414302 unmodified lines71771871972072172227 unmodified lines75075175275375475575675721 unmodified lines779780781782783784325 unmodified linesself.init_encoder_metadata()self.init_decoder_metadata()self.init_joiner_metadata()self.reset_states()def init_encoder_metadata(self):encoder_meta = self.encoder.get_modelmeta().custom_metadata_map21 unmodified linesreturn list(map(int, value.split(",")))def reset_states(self, batch_size: int = 1):states = []for i, num_layers in enumerate(self.num_encoder_layers):key_dim = self.query_head_dims[i] * self.num_heads[i]15 unmodified linesstates.append(np.zeros((batch_size, 128, 3, 19), dtype=np.float32))states.append(np.zeros((batch_size,), dtype=np.int64))self.states = statesdef build_encoder_inputs(self, x: torch.Tensor) -> Tuple[Dict[str, np.ndarray], List[str]]:encoder_input = {"x": x.numpy()}encoder_output = ["encoder_out"]for i in range(len(self.states[:-2]) // 6):tensors = self.states[i * 6 : (i + 1) * 6]for tensor, name in zip(tensors,[8 unmodified linesencoder_input[name] = tensorencoder_output.append(f"new_{name}")encoder_input["embed_states"] = self.states[-2]encoder_output.append("new_embed_states")encoder_input["processed_lens"] = self.states[-1]encoder_output.append("new_processed_lens")return encoder_input, encoder_outputdef run_encoder(self, x: torch.Tensor) -> torch.Tensor:encoder_input, encoder_output_names = self.build_encoder_inputs(x)out = self.encoder.run(encoder_output_names, encoder_input)self.states = out[1:]return torch.from_numpy(out[0])def run_decoder(self, decoder_input: torch.Tensor) -> torch.Tensor:out = self.decoder.run([self.decoder.get_outputs()[0].name],302 unmodified lines)def streaming_greedy_search(model: StreamingOnnxModel,encoder_out: torch.Tensor,27 unmodified linesmodel = get_streaming_model(model_mode)model.reset_states()config = STREAMING_MODELS[model_mode]token_table = load_tokens(resolve_streaming_repo_file(config, "tokens"))waves = read_audio_input(audio=audio, expected_sample_rate=sample_rate)wave = waves[0].contiguous()21 unmodified linesreturn {"text": token_ids_to_text(hyp[model.context_size :], token_table)}@torch.no_grad()def transcribe(filepath, model_mode: str = "离线模型"):if model_mode in STREAMING_MODELS:325 unmodified lines32632732832933033121 unmodified lines35335435535635735835936036115 unmodified lines3773783793803813823833843853863873883893903913928 unmodified lines401402403404405406407408409410411412413414415416417418419420421422423424425302 unmodified lines72872973073173273373473573673773873927 unmodified lines76776876977077177277321 unmodified lines795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885325 unmodified linesself.init_encoder_metadata()self.init_decoder_metadata()self.init_joiner_metadata()def init_encoder_metadata(self):encoder_meta = self.encoder.get_modelmeta().custom_metadata_map21 unmodified linesreturn list(map(int, value.split(",")))def reset_states(self, batch_size: int = 1):self.states = self.make_initial_states(batch_size)def make_initial_states(self, batch_size: int = 1) -> List[np.ndarray]:states = []for i, num_layers in enumerate(self.num_encoder_layers):key_dim = self.query_head_dims[i] * self.num_heads[i]15 unmodified linesstates.append(np.zeros((batch_size, 128, 3, 19), dtype=np.float32))states.append(np.zeros((batch_size,), dtype=np.int64))return statesdef build_encoder_inputs(self, x: torch.Tensor, states: List[np.ndarray]) -> Tuple[Dict[str, np.ndarray], List[str]]:encoder_input = {"x": x.numpy()}encoder_output = ["encoder_out"]for i in range(len(states[:-2]) // 6):tensors = states[i * 6 : (i + 1) * 6]for tensor, name in zip(tensors,[8 unmodified linesencoder_input[name] = tensorencoder_output.append(f"new_{name}")encoder_input["embed_states"] = states[-2]encoder_output.append("new_embed_states")encoder_input["processed_lens"] = states[-1]encoder_output.append("new_processed_lens")return encoder_input, encoder_outputdef run_encoder(self, x: torch.Tensor) -> torch.Tensor:encoder_input, encoder_output_names = self.build_encoder_inputs(x, self.states)out = self.encoder.run(encoder_output_names, encoder_input)self.states = out[1:]return torch.from_numpy(out[0])def run_encoder_with_states(self, x: torch.Tensor, states: List[np.ndarray]) -> Tuple[torch.Tensor, List[np.ndarray]]:encoder_input, encoder_output_names = self.build_encoder_inputs(x, states)out = self.encoder.run(encoder_output_names, encoder_input)return torch.from_numpy(out[0]), out[1:]def run_decoder(self, decoder_input: torch.Tensor) -> torch.Tensor:out = self.decoder.run([self.decoder.get_outputs()[0].name],302 unmodified lines)@lru_cache(maxsize=4)def get_streaming_tokens(model_mode: str) -> Dict[int, str]:config = STREAMING_MODELS[model_mode]return load_tokens(resolve_streaming_repo_file(config, "tokens"))def streaming_greedy_search(model: StreamingOnnxModel,encoder_out: torch.Tensor,27 unmodified linesmodel = get_streaming_model(model_mode)model.reset_states()token_table = get_streaming_tokens(model_mode)waves = read_audio_input(audio=audio, expected_sample_rate=sample_rate)wave = waves[0].contiguous()21 unmodified linesreturn {"text": token_ids_to_text(hyp[model.context_size :], token_table)}def new_streaming_state(model_mode: str) -> Dict:model = get_streaming_model(model_mode)hyp = [0] * model.context_sizedecoder_input = torch.tensor([hyp], dtype=torch.int64)decoder_out = model.run_decoder(decoder_input)return {"model_mode": model_mode,"states": model.make_initial_states(),"hyp": hyp,"decoder_out": decoder_out,"wave": np.empty((0,), dtype=np.float32),"num_processed_frames": 0,"num_samples_seen": 0,}def reset_realtime_stream(model_mode: str) -> Tuple[str, Dict]:if model_mode not in STREAMING_MODELS:return "", {}return "", new_streaming_state(model_mode)@torch.no_grad()def transcribe_streaming_realtime(audio, state, model_mode: str) -> Tuple[str, Dict]:if audio is None:return "", state or {}if model_mode not in STREAMING_MODELS:return "请选择一个流式模型。", state or {}sample_rate = 16000model = get_streaming_model(model_mode)if not state or state.get("model_mode") != model_mode:state = new_streaming_state(model_mode)chunk = read_audio_input(audio=audio, expected_sample_rate=sample_rate)[0]chunk_np = chunk.contiguous().numpy().astype(np.float32)samples_seen = int(state.get("num_samples_seen", 0))if chunk_np.shape[0] >= samples_seen:new_samples = chunk_np[samples_seen:]state["num_samples_seen"] = chunk_np.shape[0]else:new_samples = chunk_npstate["num_samples_seen"] = samples_seen + chunk_np.shape[0]if new_samples.size == 0:token_table = get_streaming_tokens(model_mode)return token_ids_to_text(state["hyp"][model.context_size :], token_table), statestate["wave"] = np.concatenate([state["wave"], new_samples])wave = torch.from_numpy(state["wave"]).float()features = compute_fbank([wave], sample_rate)[0]while state["num_processed_frames"] + model.segment <= features.size(0):start = state["num_processed_frames"]frames = features[start : start + model.segment]state["num_processed_frames"] += model.offsetencoder_out, state["states"] = model.run_encoder_with_states(frames.unsqueeze(0),state["states"],)state["hyp"], state["decoder_out"] = streaming_greedy_search(model=model,encoder_out=encoder_out,decoder_out=state["decoder_out"],hyp=state["hyp"],)token_table = get_streaming_tokens(model_mode)text = token_ids_to_text(state["hyp"][model.context_size :], token_table)return text, state@torch.no_grad()def finish_streaming_realtime(state, model_mode: str) -> Tuple[str, Dict]:if not state or model_mode not in STREAMING_MODELS:return "", state or {}sample_rate = 16000tail = np.zeros((int(0.3 * sample_rate),), dtype=np.float32)audio = (sample_rate, tail)return transcribe_streaming_realtime(audio, state, model_mode)@torch.no_grad()def transcribe(filepath, model_mode: str = "离线模型"):if model_mode in STREAMING_MODELS:
app.py+94-41
transcribe.py+111-10