安裝whisper的教程,已在
https://blog.csdn.net/qq_23938507/article/details/149394418
和
https://blog.csdn.net/qq_23938507/article/details/149326290
中說明。
1、創建whisperDemo1.py
from fastapi import FastAPI, UploadFile, File
import whisper
import osapp = FastAPI()# 加載Whisper模型
model = whisper.load_model("medium") # 可替換為 small/medium/large@app.post("/transcribe/")
async def transcribe_audio(file: UploadFile = File(...)):try:# 臨時保存上傳的文件[7](@ref)temp_path = f"temp_{file.filename}"with open(temp_path, "wb") as f:f.write(await file.read())# 使用Whisper轉錄[7](@ref)result = model.transcribe(temp_path)# 刪除臨時文件os.remove(temp_path)return {"text": result["text"]}except Exception as e:return {"error": str(e)}
2、創建request001.py
import requestsdef upload_file(file_path, server_url):try:# 以二進制模式打開文件并上傳[8](@ref)[9](@ref)with open(file_path, 'rb') as f:files = {'file': f}response = requests.post(server_url, files=files, timeout=600)# 檢查響應狀態碼[9](@ref)if response.status_code == 200:try:# 嘗試解析JSON響應[3](@ref)result = response.json()print("上傳成功,轉錄結果:", result['text'])except ValueError:print("服務器返回非JSON響應:", response.text)else:print(f"上傳失敗,狀態碼:{response.status_code}\n響應內容:{response.text}")except FileNotFoundError:print(f"錯誤:文件 {file_path} 不存在")except requests.exceptions.RequestException as e:print(f"網絡請求失敗:{e}")# 使用示例
if __name__ == "__main__":upload_file(file_path="001.mp3",server_url=" http://127.0.0.1:8000/transcribe/")
3、運行whisperDemo1
在終端輸入:
uvicorn whisperDemo1:app --host 0.0.0.0 --port 8000
可以通過pip安裝uvicorn、fastapi
可以驗證服務是否 有開啟成功
啟動后,在瀏覽器輸入:
127.0.0.1:8000/docs