asr_api.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # asr_api.py
  2. import os
  3. import tempfile
  4. from fastapi import FastAPI, File, UploadFile, HTTPException
  5. from fastapi.responses import JSONResponse
  6. import logging
  7. from dotenv import load_dotenv
  8. from whisper import transcribe, post_process_transcript, setup_logger
  9. # 加载环境变量
  10. load_dotenv('environment.env')
  11. # 设置日志
  12. logger = setup_logger()
  13. app = FastAPI()
  14. @app.post("/transcribe/")
  15. async def transcribe_audio(file: UploadFile = File(...)):
  16. try:
  17. content_type = file.content_type
  18. logger.info(f"Received file: {file.filename}, Content-Type: {content_type}")
  19. if content_type not in ["audio/mpeg", "audio/mp4", "audio/x-m4a", "audio/wav"]:
  20. raise HTTPException(status_code=400, detail=f"Unsupported file type: {content_type}")
  21. with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
  22. content = await file.read()
  23. temp_file.write(content)
  24. temp_file.flush()
  25. logger.info(f"Temporary file created: {temp_file.name}")
  26. transcript = transcribe(temp_file.name)
  27. os.unlink(temp_file.name)
  28. logger.info(f"Temporary file deleted: {temp_file.name}")
  29. if transcript is None:
  30. raise ValueError("Transcription failed. Check server logs for details.")
  31. corrected_transcript = post_process_transcript(transcript)
  32. return JSONResponse(content={
  33. "original_transcript": transcript,
  34. "corrected_transcript": corrected_transcript
  35. })
  36. except ValueError as ve:
  37. logger.exception("Transcription failed")
  38. raise HTTPException(status_code=400, detail=str(ve))
  39. except Exception as e:
  40. logger.exception("An unexpected error occurred during transcription")
  41. raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
  42. if __name__ == "__main__":
  43. import uvicorn
  44. uvicorn.run("asr_api:app", host="0.0.0.0", port=8000, reload=True)