Spaces:
Sleeping
Sleeping
File size: 5,856 Bytes
8c2e4c3 d52dd83 1e45be9 8c2e4c3 1e45be9 d52dd83 1e45be9 8c2e4c3 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 1e45be9 d52dd83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | 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) |