Update app.py
Browse files9 unmodified lines1011121314151617181 unmodified line20212223242526272829303132333435363738394 unmodified lines4445464748495051525354555657585960616210 unmodified lines737475767778791 unmodified line818283848586878889909119 unmodified lines1111121131141159 unmodified lines# 1. 声明加载的模型MODEL_NAME = "openai/whisper-small"# 2. 全局直接在 "cuda" 设备上初始化 Pipeline!# 官方的 spaces 拦截层会在容器启动时自动拦截它防止在 CPU 阶段报错;# 并在调用带 @spaces.GPU 装饰器的函数时,自动、无损地把它调度到 A100 GPU 显存中运行。pipe = pipeline("automatic-speech-recognition",model=MODEL_NAME,1 unmodified linedevice="cuda")# 3. 核心计算函数(保留 @spaces.GPU 装饰器,确保 Hugging Face 静态扫描通过)@spaces.GPUdef transcribe_core(audio_path: str, target_language: str = None, is_translate: bool = False):# 【最关键的安全操作】绝不手动编写 pipe.model.to("cuda") 或 torch.autocast# 彻底杜绝由于显卡热插拔带来的 RuntimeError!generate_kwargs = {}if target_language:generate_kwargs["language"] = target_languageif is_translate:generate_kwargs["language"] = "english"generate_kwargs["task"] = "translate"# 直接运行推理,ZeroGPU 机制会完美托管这一步result = pipe(audio_path, generate_kwargs=generate_kwargs)return result["text"]4 unmodified linestry:return transcribe_core(audio_path)except Exception as e:return f"转录出错: {str(e)}"demo = gr.Interface(fn=gradio_predict,inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="输入音频"),outputs=gr.Textbox(label="识别出的文本"),title="Whisper 语音识别 API 节点",description="【完美兼容 OpenAI 规范 - A100 GPU 版】支持网页端测试,同时提供 100% 兼容的 /v1/audio/transcriptions & /v1/audio/translations 接口!")app = demo.app# --- 完美兼容 OpenAI 的处理函数 ---async def process_openai_audio_request(file, response_format, language, is_translate):suffix = os.path.splitext(file.filename)[1] or ".mp3"with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:10 unmodified linesif response_format in ["text", "vtt", "srt"]:return PlainTextResponse(text)return JSONResponse(content={"text": text})1 unmodified line@app.post("/v1/audio/transcriptions")async def transcribe_api(file: UploadFile = File(...),model: str = Form("whisper-1"),language: str = Form(None),prompt: str = Form(None),response_format: str = Form("json"),temperature: float = Form(0.0)):return await process_openai_audio_request(file=file,19 unmodified linesis_translate=True)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)9 unmodified lines101112131415161 unmodified line18192021222324252627282930313233344 unmodified lines3940414243444546474849505152535455565758596010 unmodified lines717273747576771 unmodified line798081828384858687888919 unmodified lines1091101111121139 unmodified lines# 1. 声明加载的模型MODEL_NAME = "openai/whisper-small"# 2. 全局初始化 Pipelinepipe = pipeline("automatic-speech-recognition",model=MODEL_NAME,1 unmodified linedevice="cuda")# 3. 核心计算函数@spaces.GPUdef transcribe_core(audio_path: str, target_language: str = None, is_translate: bool = False):generate_kwargs = {}if target_language:generate_kwargs["language"] = target_languageif is_translate:generate_kwargs["language"] = "english"generate_kwargs["task"] = "translate"result = pipe(audio_path, generate_kwargs=generate_kwargs)return result["text"]4 unmodified linestry:return transcribe_core(audio_path)except Exception as e:return f"错误: {str(e)}"demo = gr.Interface(fn=gradio_predict,inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="输入音频"),outputs=gr.Textbox(label="识别出的文本"),title="Whisper 语音识别 API 节点",description="【完美兼容 OpenAI 规范】")# ===========================================================================# 关键修改部分:正确初始化 FastAPI 应用# ===========================================================================app = FastAPI()# 辅助函数:处理 OpenAI 请求async def process_openai_audio_request(file, response_format, language, is_translate):suffix = os.path.splitext(file.filename)[1] or ".mp3"with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:10 unmodified linesif response_format in ["text", "vtt", "srt"]:return PlainTextResponse(text)return JSONResponse(content={"text": text})1 unmodified line@app.post("/v1/audio/transcriptions")async def transcribe_api(file: UploadFile = File(...),model: str = Form("whisper-1"),language: str = Form(None),prompt: str = Form(None),response_format: str = Form("json"),temperature: float = Form(0.0)):return await process_openai_audio_request(file=file,19 unmodified linesis_translate=True)# 6. 将 Gradio 挂载到 FastAPI 应用的根路径(必须放在所有 FastAPI 路由之后!)app = gr.mount_gradio_app(app, demo, path="/")
app.py+19-21