Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,7 @@ device = 0 if torch.cuda.is_available() else -1
|
|
| 8 |
print(f"正在加载模型,使用设备: {'GPU' if device == 0 else 'CPU'}...")
|
| 9 |
pipe = pipeline(
|
| 10 |
task="automatic-speech-recognition",
|
| 11 |
-
model="openai/whisper-tiny", # 免费
|
| 12 |
device=device
|
| 13 |
)
|
| 14 |
|
|
@@ -17,43 +17,43 @@ def transcribe_audio(audio_path):
|
|
| 17 |
自动识别语音语言:说中文出中文,说英文出英文
|
| 18 |
"""
|
| 19 |
if audio_path is None:
|
| 20 |
-
return "
|
| 21 |
|
| 22 |
-
# 不强制设置 language,让 Whisper 自动检测语种
|
| 23 |
-
# 加入 rep_penalty 防止环境噪音引发韩文/乱码重复循环
|
| 24 |
result = pipe(
|
| 25 |
audio_path,
|
| 26 |
generate_kwargs={
|
| 27 |
-
"task": "transcribe", # 纯语音转写
|
| 28 |
"max_new_tokens": 256,
|
| 29 |
-
"repetition_penalty": 1.2 #
|
| 30 |
}
|
| 31 |
)
|
| 32 |
return result["text"]
|
| 33 |
|
| 34 |
# 构建 Gradio 6.x 界面
|
| 35 |
-
with gr.Blocks(title="Whisper 语音识别
|
| 36 |
gr.Markdown("# 🎙️ 多语言语音转文本系统")
|
| 37 |
-
gr.Markdown("
|
| 38 |
|
| 39 |
with gr.Row():
|
| 40 |
with gr.Column():
|
|
|
|
| 41 |
audio_input = gr.Audio(
|
| 42 |
sources=["upload", "microphone"],
|
| 43 |
type="filepath",
|
| 44 |
-
label="音频输入"
|
| 45 |
)
|
| 46 |
-
submit_btn = gr.Button("开始识别", variant="primary")
|
| 47 |
|
| 48 |
with gr.Column():
|
|
|
|
| 49 |
text_output = gr.Textbox(
|
| 50 |
label="识别结果",
|
| 51 |
-
placeholder="识别
|
| 52 |
lines=5
|
| 53 |
)
|
| 54 |
|
| 55 |
-
#
|
| 56 |
-
|
|
|
|
| 57 |
fn=transcribe_audio,
|
| 58 |
inputs=audio_input,
|
| 59 |
outputs=text_output
|
|
|
|
| 8 |
print(f"正在加载模型,使用设备: {'GPU' if device == 0 else 'CPU'}...")
|
| 9 |
pipe = pipeline(
|
| 10 |
task="automatic-speech-recognition",
|
| 11 |
+
model="openai/whisper-tiny", # 免费环境提速推荐
|
| 12 |
device=device
|
| 13 |
)
|
| 14 |
|
|
|
|
| 17 |
自动识别语音语言:说中文出中文,说英文出英文
|
| 18 |
"""
|
| 19 |
if audio_path is None:
|
| 20 |
+
return ""
|
| 21 |
|
|
|
|
|
|
|
| 22 |
result = pipe(
|
| 23 |
audio_path,
|
| 24 |
generate_kwargs={
|
| 25 |
+
"task": "transcribe", # 纯语音转写
|
| 26 |
"max_new_tokens": 256,
|
| 27 |
+
"repetition_penalty": 1.2 # 抑制重复
|
| 28 |
}
|
| 29 |
)
|
| 30 |
return result["text"]
|
| 31 |
|
| 32 |
# 构建 Gradio 6.x 界面
|
| 33 |
+
with gr.Blocks(title="Whisper 实时语音识别 system") as demo:
|
| 34 |
gr.Markdown("# 🎙️ 多语言语音转文本系统")
|
| 35 |
+
gr.Markdown("录音结束或上传音频后,**自动触发转换**(无需点击按钮)。")
|
| 36 |
|
| 37 |
with gr.Row():
|
| 38 |
with gr.Column():
|
| 39 |
+
# 1. 音频输入组件
|
| 40 |
audio_input = gr.Audio(
|
| 41 |
sources=["upload", "microphone"],
|
| 42 |
type="filepath",
|
| 43 |
+
label="音频输入(录音停止后自动转换)"
|
| 44 |
)
|
|
|
|
| 45 |
|
| 46 |
with gr.Column():
|
| 47 |
+
# 2. 文本输出组件
|
| 48 |
text_output = gr.Textbox(
|
| 49 |
label="识别结果",
|
| 50 |
+
placeholder="录音或上传完成后,识别结果会自动显示在这里...",
|
| 51 |
lines=5
|
| 52 |
)
|
| 53 |
|
| 54 |
+
# 3. 核心改动:监听 audio_input 的 change 事件
|
| 55 |
+
# 当你按下停止录音或文件上传成功时,自动调用 transcribe_audio
|
| 56 |
+
audio_input.change(
|
| 57 |
fn=transcribe_audio,
|
| 58 |
inputs=audio_input,
|
| 59 |
outputs=text_output
|