stt_whisper.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from datetime import datetime
  2. import numpy as np
  3. import scipy.io.wavfile as wavfile
  4. import whisper
  5. from fastapi import FastAPI, WebSocket, WebSocketDisconnect
  6. app = FastAPI()
  7. # Whisper 모델 로드 (tiny 모델로 실시간성 유지)
  8. model = whisper.load_model("base")
  9. # 클라이언트 관리
  10. clients = {}
  11. @app.websocket("/audio-stream")
  12. async def websocket_endpoint(websocket: WebSocket):
  13. await websocket.accept()
  14. client_id = str(id(websocket))
  15. clients[client_id] = websocket
  16. print(f"Client {client_id} connected")
  17. try:
  18. while True:
  19. # 오디오 청크 수신
  20. audio_chunk = await websocket.receive_bytes()
  21. # 오디오 데이터를 새로운 버퍼에 저장 (기존 데이터 누적 방지)
  22. audio_buffer = bytearray(audio_chunk) # 🔥 새로운 데이터로 덮어쓰기
  23. # 수신 크기 확인
  24. print(f"Received data size: {len(audio_chunk)} bytes")
  25. # 오디오 바이너리 데이터 => 숫자배열(numpy)로 해석
  26. audio_np = np.frombuffer(audio_buffer, dtype=np.int16).copy()
  27. # WAV 파일로 저장 (덮어쓰기)
  28. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  29. output_file = f"recorded_audio_{timestamp}.wav"
  30. wavfile.write(output_file, 16000, audio_np)
  31. # STT 처리
  32. stt_result = model.transcribe(output_file, language="ko")
  33. transcription = stt_result["text"]
  34. # 클라이언트에 데이터 전송
  35. print("클라이언트에 데이터 전송")
  36. await websocket.send_text(transcription)
  37. except WebSocketDisconnect:
  38. print(f"Client {client_id} disconnected")
  39. del clients[client_id]
  40. except Exception as e:
  41. print(f"Error: {e}")
  42. await websocket.send_text(f"Error: {str(e)}")
  43. if __name__ == "__main__":
  44. import uvicorn
  45. uvicorn.run(app, host="0.0.0.0", port=8000)