Uotpia commited on
Commit
9f78068
·
verified ·
1 Parent(s): af84515

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -65
app.py CHANGED
@@ -1,15 +1,10 @@
1
  import os
2
- import shutil
3
- import tempfile
4
  import torch
5
  import spaces
6
  import gradio as gr
7
- from fastapi import UploadFile, File, Form, HTTPException
8
- from fastapi.middleware.cors import CORSMiddleware
9
- from fastapi.responses import JSONResponse, PlainTextResponse
10
  from transformers import pipeline
11
 
12
- # 1. 初始化模型
13
  MODEL_NAME = "openai/whisper-small"
14
  device = "cuda" if torch.cuda.is_available() else "cpu"
15
 
@@ -20,11 +15,14 @@ pipe = pipeline(
20
  device=device
21
  )
22
 
23
- # 2. 顶层 ZeroGPU 函数
24
  @spaces.GPU
25
  def run_whisper(audio_path: str, target_language: str = None, is_translate: bool = False):
 
 
 
26
  generate_kwargs = {}
27
- if target_language:
28
  generate_kwargs["language"] = target_language
29
 
30
  if is_translate:
@@ -34,64 +32,46 @@ def run_whisper(audio_path: str, target_language: str = None, is_translate: bool
34
  result = pipe(audio_path, generate_kwargs=generate_kwargs)
35
  return result["text"]
36
 
37
- # 3. Gradio 界面定义
38
- def gradio_predict(audio_path):
39
- if audio_path is None:
40
- return "请上传音频文件!"
41
- return run_whisper(audio_path)
42
 
43
- demo = gr.Interface(
44
- fn=gradio_predict,
45
- inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="输入"),
46
- outputs=gr.Textbox(label="识别结果"),
47
- title="Whisper API Node"
48
- )
49
-
50
- # 4. 获取 FastAPI 实例并添加 CORS 跨域支持
51
- app = demo.app
52
-
53
- app.add_middleware(
54
- CORSMiddleware,
55
- allow_origins=["*"],
56
- allow_credentials=True,
57
- allow_methods=["*"],
58
- allow_headers=["*"],
59
- )
60
-
61
- async def process_audio(file: UploadFile, response_format: str, language: str, is_translate: bool):
62
- suffix = os.path.splitext(file.filename)[1] or ".wav"
63
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
64
- shutil.copyfileobj(file.file, temp_file)
65
- temp_path = temp_file.name
66
-
67
- try:
68
- text = run_whisper(temp_path, target_language=language, is_translate=is_translate)
69
- except Exception as e:
70
- raise HTTPException(status_code=500, detail=str(e))
71
- finally:
72
- if os.path.exists(temp_path):
73
- os.remove(temp_path)
74
-
75
- if response_format in ["text", "vtt", "srt"]:
76
- return PlainTextResponse(text)
77
- return JSONResponse(content={"text": text})
78
-
79
- @app.post("/v1/audio/transcriptions")
80
- async def transcribe_api(
81
- file: UploadFile = File(...),
82
- model: str = Form("whisper-1"),
83
- language: str = Form(None),
84
- response_format: str = Form("json")
85
- ):
86
- return await process_audio(file, response_format, language, is_translate=False)
87
 
88
- @app.post("/v1/audio/translations")
89
- async def translate_api(
90
- file: UploadFile = File(...),
91
- model: str = Form("whisper-1"),
92
- response_format: str = Form("json")
93
- ):
94
- return await process_audio(file, response_format, language="english", is_translate=True)
95
 
96
  # 5. 启动服务
97
- demo.launch()
 
 
1
  import os
 
 
2
  import torch
3
  import spaces
4
  import gradio as gr
 
 
 
5
  from transformers import pipeline
6
 
7
+ # 1. 初始化 Whisper 模型
8
  MODEL_NAME = "openai/whisper-small"
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
 
 
15
  device=device
16
  )
17
 
18
+ # 2. ZeroGPU 动态调用函数
19
  @spaces.GPU
20
  def run_whisper(audio_path: str, target_language: str = None, is_translate: bool = False):
21
+ if not audio_path:
22
+ return "请上传或录制音频文件!"
23
+
24
  generate_kwargs = {}
25
+ if target_language and target_language != "auto":
26
  generate_kwargs["language"] = target_language
27
 
28
  if is_translate:
 
32
  result = pipe(audio_path, generate_kwargs=generate_kwargs)
33
  return result["text"]
34
 
35
+ # 3. Gradio 交互逻辑
36
+ def gradio_predict(audio_path, language, is_translate):
37
+ return run_whisper(audio_path, target_language=language, is_translate=is_translate)
 
 
38
 
39
+ # 4. 构建 Gradio 界面
40
+ with gr.Blocks(title="Whisper 语音识别与翻译") as demo:
41
+ gr.Markdown("## 🎙️ Whisper 识别与翻译工具")
42
+
43
+ with gr.Row():
44
+ with gr.Column():
45
+ audio_input = gr.Audio(
46
+ sources=["microphone", "upload"],
47
+ type="filepath",
48
+ label="上传或录制音频"
49
+ )
50
+
51
+ # 增加常用语言选择与翻译开关选项
52
+ language_dropdown = gr.Dropdown(
53
+ choices=["auto", "chinese", "english", "japanese", "korean", "cantonese"],
54
+ value="auto",
55
+ label="指定源语言 (默认自动识别)"
56
+ )
57
+
58
+ translate_checkbox = gr.Checkbox(
59
+ label="翻译为英文 (Task: Translate to English)",
60
+ value=False
61
+ )
62
+
63
+ submit_btn = gr.Button("开始识别 / 翻译", variant="primary")
64
+
65
+ with gr.Column():
66
+ text_output = gr.Textbox(label="识别 / 翻译结果", lines=10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ # 绑定事件
69
+ submit_btn.click(
70
+ fn=gradio_predict,
71
+ inputs=[audio_input, language_dropdown, translate_checkbox],
72
+ outputs=text_output
73
+ )
 
74
 
75
  # 5. 启动服务
76
+ if __name__ == "__main__":
77
+ demo.launch()