| import os |
| import torch |
| import spaces |
| import gradio as gr |
| from transformers import pipeline |
|
|
| |
| MODEL_NAME = "openai/whisper-small" |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
| pipe = pipeline( |
| "automatic-speech-recognition", |
| model=MODEL_NAME, |
| chunk_length_s=30, |
| device=device |
| ) |
|
|
| |
| @spaces.GPU |
| def run_whisper(audio_path: str, target_language: str = None, is_translate: bool = False): |
| if not audio_path: |
| return "请上传或录制音频文件!" |
| |
| generate_kwargs = {} |
| if target_language and target_language != "auto": |
| generate_kwargs["language"] = target_language |
|
|
| if is_translate: |
| generate_kwargs["language"] = "english" |
| generate_kwargs["task"] = "translate" |
|
|
| result = pipe(audio_path, generate_kwargs=generate_kwargs) |
| return result["text"] |
|
|
| |
| def gradio_predict(audio_input, language, is_translate): |
| if isinstance(audio_input, dict): |
| audio_path = audio_input.get("path") or audio_input.get("name") or audio_input.get("url") |
| else: |
| audio_path = audio_input |
|
|
| return run_whisper(audio_path, target_language=language, is_translate=is_translate) |
|
|
| |
| def api_predict(audio_path: str, language: str = "auto", is_translate: bool = False): |
| return run_whisper(audio_path, target_language=language, is_translate=is_translate) |
|
|
| |
| with gr.Blocks(title="Whisper 语音识别与翻译") as demo: |
| gr.Markdown("## 🎙️ Whisper 语音识别与翻译工具") |
| |
| with gr.Row(): |
| with gr.Column(): |
| audio_input = gr.Audio( |
| sources=["microphone", "upload"], |
| type="filepath", |
| label="上传或录制音频" |
| ) |
| |
| language_dropdown = gr.Dropdown( |
| choices=["auto", "chinese", "english", "japanese", "korean", "cantonese"], |
| value="auto", |
| label="指定源语言 (默认自动识别)" |
| ) |
| |
| translate_checkbox = gr.Checkbox( |
| label="翻译为英文 (Task: Translate to English)", |
| value=False |
| ) |
| |
| submit_btn = gr.Button("开始识别 / 翻译", variant="primary") |
| |
| with gr.Column(): |
| text_output = gr.Textbox(label="识别 / 翻译结果", lines=10) |
|
|
| |
| submit_btn.click( |
| fn=gradio_predict, |
| inputs=[audio_input, language_dropdown, translate_checkbox], |
| outputs=text_output |
| ) |
|
|
| |
| api_path_input = gr.Textbox(visible=False) |
| api_btn = gr.Button("API Path Trigger", visible=False) |
| api_btn.click( |
| fn=api_predict, |
| inputs=[api_path_input, language_dropdown, translate_checkbox], |
| outputs=text_output, |
| api_name="predict_path" |
| ) |
|
|
| |
| if __name__ == "__main__": |
| demo.launch() |