Spaces:
Sleeping
Sleeping
Download app.py from wuyan123258/Study: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/spaces/wuyan123258/Study/resolve/main/app.py
- Command line
-
hf download hf://spaces/wuyan123258/Study/app.py
-
curl -L -o app.py https://huggingface.co/spaces/wuyan123258/Study/resolve/main/app.py
5.86 kB
| import gradio as gr | |
| import whisper | |
| import torch | |
| import os | |
| import json | |
| from datetime import datetime | |
| from pathlib import Path | |
| # 全局变量 | |
| model = None | |
| training_data = [] | |
| def load_base_model(): | |
| """加载基础Whisper模型""" | |
| global model | |
| print("加载基础Whisper模型...") | |
| model = whisper.load_model("base") | |
| model = model.cpu() | |
| print("模型加载完成!") | |
| return "基础模型加载完成!" | |
| def prepare_training_data(audio_files, transcript_files): | |
| """准备训练数据""" | |
| global training_data | |
| training_data = [] | |
| # 简单的数据配对逻辑 | |
| for i, audio_file in enumerate(audio_files): | |
| if i < len(transcript_files): | |
| transcript = transcript_files[i].decode('utf-8').strip() | |
| training_data.append({ | |
| 'audio': audio_file, | |
| 'text': transcript, | |
| 'timestamp': datetime.now().isoformat() | |
| }) | |
| return f"已准备 {len(training_data)} 个训练样本" | |
| def train_model(epochs=1, learning_rate=1e-5): | |
| """训练模型的核心函数""" | |
| global model, training_data | |
| if not training_data: | |
| return "错误:请先准备训练数据" | |
| if model is None: | |
| load_base_model() | |
| # 创建临时目录保存训练数据 | |
| train_dir = Path("/tmp/training_data") | |
| train_dir.mkdir(exist_ok=True) | |
| # 保存训练数据 | |
| data_file = train_dir / "training_data.json" | |
| with open(data_file, 'w', encoding='utf-8') as f: | |
| json.dump(training_data, f, ensure_ascii=False, indent=2) | |
| # 这里应该是实际的训练逻辑 | |
| # 由于在CPU上训练完整模型很耗时,这里简化处理 | |
| training_log = [] | |
| training_log.append(f"开始训练...") | |
| training_log.append(f"训练样本数: {len(training_data)}") | |
| training_log.append(f"训练轮数: {epochs}") | |
| training_log.append(f"学习率: {learning_rate}") | |
| # 模拟训练过程(实际项目中需要实现真实训练) | |
| for epoch in range(epochs): | |
| training_log.append(f"第 {epoch+1}/{epochs} 轮训练中...") | |
| # 这里应该包含实际的训练代码 | |
| # 例如:model.train_on_batch(...) | |
| training_log.append("训练完成!") | |
| # 保存训练后的模型 | |
| model_save_path = train_dir / "fine_tuned_model.pt" | |
| torch.save(model.state_dict(), model_save_path) | |
| training_log.append(f"模型已保存到: {model_save_path}") | |
| return "\n".join(training_log) | |
| def transcribe_with_trained_model(audio_path): | |
| """使用训练后的模型进行转录""" | |
| global model | |
| if model is None: | |
| return "错误:模型未加载" | |
| if audio_path is None: | |
| return "请先上传音频文件" | |
| try: | |
| result = model.transcribe(audio_path, fp16=False) | |
| return result["text"] | |
| except Exception as e: | |
| return f"转录错误: {str(e)}" | |
| # 创建Gradio界面 | |
| with gr.Blocks(title="语音模型训练系统") as demo: | |
| gr.Markdown("# 🎤 语音模型训练系统") | |
| gr.Markdown("上传音频和对应的文本转录来训练您自己的语音识别模型") | |
| with gr.Tab("1. 基础设置"): | |
| gr.Markdown("### 加载基础模型") | |
| load_btn = gr.Button("加载Whisper基础模型") | |
| load_output = gr.Textbox(label="模型状态") | |
| load_btn.click(load_base_model, outputs=load_output) | |
| with gr.Tab("2. 准备训练数据"): | |
| gr.Markdown("### 上传训练数据") | |
| gr.Markdown("请上传配对的音频文件和文本文件(文件名对应,如:audio1.wav 和 audio1.txt)") | |
| audio_inputs = gr.File( | |
| file_count="multiple", | |
| file_types=[".wav", ".mp3", ".m4a"], | |
| label="上传音频文件" | |
| ) | |
| text_inputs = gr.File( | |
| file_count="multiple", | |
| file_types=[".txt"], | |
| label="上传文本转录文件" | |
| ) | |
| prepare_btn = gr.Button("准备训练数据") | |
| data_status = gr.Textbox(label="数据准备状态") | |
| prepare_btn.click( | |
| prepare_training_data, | |
| inputs=[audio_inputs, text_inputs], | |
| outputs=data_status | |
| ) | |
| with gr.Tab("3. 训练模型"): | |
| gr.Markdown("### 训练参数设置") | |
| epochs = gr.Slider(1, 10, value=1, step=1, label="训练轮数") | |
| lr = gr.Number(1e-5, label="学习率") | |
| train_btn = gr.Button("开始训练", variant="primary") | |
| training_output = gr.Textbox(label="训练日志", lines=10) | |
| train_btn.click( | |
| train_model, | |
| inputs=[epochs, lr], | |
| outputs=training_output | |
| ) | |
| with gr.Tab("4. 测试模型"): | |
| gr.Markdown("### 测试训练后的模型") | |
| test_audio = gr.Audio(type="filepath", label="测试音频") | |
| test_btn = gr.Button("转录测试") | |
| test_output = gr.Textbox(label="转录结果") | |
| test_btn.click( | |
| transcribe_with_trained_model, | |
| inputs=test_audio, | |
| outputs=test_output | |
| ) | |
| with gr.Tab("使用说明"): | |
| gr.Markdown(""" | |
| ## 使用指南 | |
| ### 数据格式要求 | |
| - 音频格式:WAV, MP3, M4A | |
| - 文本格式:UTF-8编码的TXT文件 | |
| - 文件对应:audio1.wav 对应 audio1.txt | |
| ### 训练建议 | |
| - 从少量数据开始(5-10个样本) | |
| - 使用1-2轮训练进行测试 | |
| - 确保音频质量良好 | |
| ### 限制说明 | |
| - 免费CPU环境训练较慢 | |
| - 建议使用短音频(<30秒) | |
| - 模型保存为临时文件 | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |