Spaces:
Sleeping
Sleeping
Download app.py from BrucePWH/my-audio2text: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/BrucePWH/my-audio2text/resolve/main/app.py
- Command line
-
hf download hf://spaces/BrucePWH/my-audio2text/app.py
-
curl -L -o app.py https://huggingface.co/spaces/BrucePWH/my-audio2text/resolve/main/app.py
11.5 kB
| # app.py - Hugging Face Spaces 版本 | |
| import os | |
| import gradio as gr | |
| import whisper | |
| import torch | |
| from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer | |
| import traceback | |
| import warnings | |
| # 忽略警告 | |
| warnings.filterwarnings("ignore") | |
| # ========== 全局变量 ========== | |
| model_asr = None | |
| tokenizer = None | |
| model_trans = None | |
| device = None | |
| # ========== 语言代码映射 ========== | |
| LANG_CODE = { | |
| "English": "en", | |
| "Chinese": "zh", | |
| "Malay": "ms", | |
| } | |
| # ========== 模型加载函数 ========== | |
| def load_models(): | |
| """加载模型并处理可能的错误""" | |
| global model_asr, tokenizer, model_trans, device | |
| try: | |
| # 检测设备 | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| print(f"使用设备: {device}") | |
| # 加载 Whisper 模型 (使用 tiny 模型适应 Spaces 资源限制) | |
| print("正在加载 Whisper 'tiny' 模型...") | |
| model_asr = whisper.load_model("tiny") | |
| print("✅ Whisper 模型加载成功") | |
| # 加载 M2M100 模型 | |
| m2m_model_name = "facebook/m2m100_418M" | |
| print(f"正在加载 M2M100 模型: {m2m_model_name}") | |
| tokenizer = M2M100Tokenizer.from_pretrained(m2m_model_name) | |
| model_trans = M2M100ForConditionalGeneration.from_pretrained( | |
| m2m_model_name, | |
| torch_dtype=torch.float16 if device == "cuda" else torch.float32 | |
| ) | |
| model_trans = model_trans.to(device) | |
| print("✅ M2M100 模型加载成功") | |
| return True | |
| except Exception as e: | |
| print(f"❌ 模型加载失败: {str(e)}") | |
| print(f"详细错误信息:\n{traceback.format_exc()}") | |
| return False | |
| # ========== 音频转录函数 ========== | |
| def transcribe_audio(audio): | |
| """改进的音频转录函数""" | |
| try: | |
| if model_asr is None: | |
| return "❌ 语音识别模型未加载,请稍后再试" | |
| if audio is None: | |
| return "❌ 请上传或录制音频文件" | |
| if not os.path.exists(audio): | |
| return "❌ 音频文件不存在" | |
| print(f"正在转录音频: {audio}") | |
| asr_result = model_asr.transcribe(audio, fp16=False) | |
| transcribed_text = asr_result["text"].strip() | |
| if not transcribed_text: | |
| return "⚠️ 未检测到语音内容" | |
| print(f"转录完成: {transcribed_text[:50]}...") | |
| return transcribed_text | |
| except Exception as e: | |
| error_msg = f"❌ 转录失败: {str(e)}" | |
| print(error_msg) | |
| print(f"详细错误:\n{traceback.format_exc()}") | |
| return error_msg | |
| # ========== 文本翻译函数 ========== | |
| def translate_text(asr_text, ui_source_lang, ui_target_lang): | |
| """改进的翻译函数""" | |
| try: | |
| if tokenizer is None or model_trans is None: | |
| return "❌ 翻译模型未加载,请稍后再试" | |
| # 输入验证 | |
| if not asr_text or not asr_text.strip(): | |
| return "❌ 没有文本需要翻译" | |
| if ui_source_lang not in LANG_CODE or ui_target_lang not in LANG_CODE: | |
| return "❌ 不支持的语言选择" | |
| # 获取语言代码 | |
| source_lang_code = LANG_CODE[ui_source_lang] | |
| target_lang_code = LANG_CODE[ui_target_lang] | |
| # 如果源语言和目标语言相同,直接返回 | |
| if source_lang_code == target_lang_code: | |
| return f"💡 源语言和目标语言相同,无需翻译:\n{asr_text}" | |
| print(f"正在翻译: {source_lang_code} -> {target_lang_code}") | |
| # 设置源语言 | |
| tokenizer.src_lang = source_lang_code | |
| # 编码输入 | |
| inputs = tokenizer(asr_text, return_tensors="pt", max_length=512, truncation=True) | |
| inputs = {k: v.to(device) for k, v in inputs.items()} | |
| # 获取目标语言的强制开始标记 | |
| forced_bos_token_id = tokenizer.get_lang_id(target_lang_code) | |
| # 生成翻译 | |
| with torch.no_grad(): # 节省内存 | |
| output_tokens = model_trans.generate( | |
| **inputs, | |
| forced_bos_token_id=forced_bos_token_id, | |
| max_length=512, | |
| num_beams=2, # 减少 beam 数量以适应 Spaces 资源 | |
| length_penalty=1.0, | |
| early_stopping=True | |
| ) | |
| # 解码输出 | |
| translated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True) | |
| if not translated_text.strip(): | |
| return "⚠️ 翻译结果为空" | |
| print(f"翻译完成: {translated_text[:50]}...") | |
| return translated_text | |
| except Exception as e: | |
| error_msg = f"❌ 翻译失败: {str(e)}" | |
| print(error_msg) | |
| print(f"详细错误:\n{traceback.format_exc()}") | |
| return error_msg | |
| # ========== 构建用户界面 ========== | |
| def build_ui(): | |
| """构建改进的用户界面""" | |
| # 检查模型状态 | |
| models_loaded = model_asr is not None and tokenizer is not None and model_trans is not None | |
| # 自定义CSS样式 | |
| custom_css = """ | |
| .gradio-container { | |
| max-width: 1200px !important; | |
| margin: auto; | |
| } | |
| .output-text { | |
| font-family: 'Courier New', monospace; | |
| } | |
| .status-box { | |
| padding: 10px; | |
| border-radius: 5px; | |
| margin: 10px 0; | |
| } | |
| .status-success { | |
| background-color: #d4edda; | |
| border: 1px solid #c3e6cb; | |
| color: #155724; | |
| } | |
| .status-error { | |
| background-color: #f8d7da; | |
| border: 1px solid #f5c6cb; | |
| color: #721c24; | |
| } | |
| """ | |
| with gr.Blocks( | |
| title="🎤 多语言语音识别与翻译系统", | |
| theme=gr.themes.Soft(), | |
| css=custom_css | |
| ) as demo: | |
| gr.Markdown(""" | |
| # 🎤 多语言语音识别与翻译系统 | |
| ### 基于 Whisper + M2M100 的两步式处理 | |
| **支持语言**: 英语 ↔️ 中文 ↔️ 马来语 | |
| """) | |
| # 模型状态显示 | |
| if models_loaded: | |
| gr.Markdown(""" | |
| <div class="status-box status-success"> | |
| ✅ <strong>系统状态</strong>: 所有模型已成功加载,系统就绪! | |
| </div> | |
| """) | |
| else: | |
| gr.Markdown(""" | |
| <div class="status-box status-error"> | |
| ❌ <strong>系统状态</strong>: 模型加载失败,请刷新页面重试 | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 📝 第一步:语音识别 (Whisper)") | |
| audio_in = gr.Audio( | |
| type="filepath", | |
| label="上传音频或录制语音" | |
| ) | |
| btn_transcribe = gr.Button( | |
| "🎯 开始识别", | |
| variant="primary", | |
| size="lg", | |
| interactive=models_loaded | |
| ) | |
| asr_textbox = gr.Textbox( | |
| label="识别结果 (可编辑)", | |
| placeholder="Whisper 识别的文本将显示在这里,您可以手动编辑...", | |
| lines=6, | |
| max_lines=10 | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 🌍 第二步:文本翻译 (M2M100)") | |
| with gr.Row(): | |
| source_lang_radio = gr.Radio( | |
| choices=["English", "Chinese", "Malay"], | |
| value="English", | |
| label="源语言", | |
| interactive=True | |
| ) | |
| target_lang_radio = gr.Radio( | |
| choices=["English", "Chinese", "Malay"], | |
| value="Chinese", | |
| label="目标语言", | |
| interactive=True | |
| ) | |
| btn_translate = gr.Button( | |
| "🔄 开始翻译", | |
| variant="secondary", | |
| size="lg", | |
| interactive=models_loaded | |
| ) | |
| trans_output = gr.Textbox( | |
| label="翻译结果", | |
| placeholder="翻译后的文本将显示在这里...", | |
| lines=6, | |
| max_lines=10, | |
| elem_classes=["output-text"] | |
| ) | |
| # 事件绑定 | |
| if models_loaded: | |
| btn_transcribe.click( | |
| fn=transcribe_audio, | |
| inputs=[audio_in], | |
| outputs=[asr_textbox], | |
| show_progress=True | |
| ) | |
| btn_translate.click( | |
| fn=translate_text, | |
| inputs=[asr_textbox, source_lang_radio, target_lang_radio], | |
| outputs=[trans_output], | |
| show_progress=True | |
| ) | |
| # 使用说明 | |
| with gr.Accordion("📖 使用说明", open=False): | |
| gr.Markdown(""" | |
| ### 💡 操作步骤: | |
| 1. **上传音频**:点击麦克风图标录制,或上传音频文件(支持 wav, mp3, m4a 等格式) | |
| 2. **语音识别**:点击"开始识别"按钮,Whisper 会将语音转为文字 | |
| 3. **编辑文本**:如有识别错误,可以手动编辑识别结果 | |
| 4. **选择语言**:设置源语言和目标语言 | |
| 5. **开始翻译**:点击"开始翻译"按钮获得最终结果 | |
| ### 🌍 支持的语言: | |
| - **English** (英语) - 支持各种英语方言 | |
| - **Chinese** (中文) - 支持普通话 | |
| - **Malay** (马来语) - 支持标准马来语 | |
| ### ⚠️ 注意事项: | |
| - 建议音频清晰,背景噪音较少 | |
| - 单次音频建议不超过 30 秒以获得最佳效果 | |
| - 支持的音频格式:WAV, MP3, M4A, FLAC 等 | |
| - 首次使用可能需要等待模型加载完成 | |
| ### 🔧 技术信息: | |
| - **语音识别**: OpenAI Whisper (tiny 模型) | |
| - **文本翻译**: Facebook M2M100 (418M 参数) | |
| - **运行环境**: Hugging Face Spaces | |
| """) | |
| # 页脚信息 | |
| gr.Markdown(""" | |
| --- | |
| <div style="text-align: center; color: #666; font-size: 0.9em;"> | |
| 🚀 由 <a href="https://huggingface.co/spaces" target="_blank">Hugging Face Spaces</a> 提供支持 | | |
| 📝 基于 Whisper 和 M2M100 构建 | |
| </div> | |
| """) | |
| return demo | |
| # ========== 主程序入口 ========== | |
| if __name__ == "__main__": | |
| print("🚀 正在启动多语言语音识别与翻译系统...") | |
| print("📦 正在加载模型,请稍候...") | |
| # 加载模型 | |
| models_loaded = load_models() | |
| if models_loaded: | |
| print("✅ 所有模型加载完成!") | |
| else: | |
| print("❌ 模型加载失败,但仍会启动界面") | |
| # 构建并启动界面 | |
| print("🌐 正在启动 Web 界面...") | |
| demo = build_ui() | |
| # 启动应用 (Hugging Face Spaces 会自动处理端口) | |
| demo.launch() |