stt_whisper.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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("tiny")
  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. print("클라이언트 대기중......")
  21. audio_chunk = await websocket.receive_bytes()
  22. # 오디오 데이터를 새로운 버퍼에 저장 (기존 데이터 누적 방지)
  23. audio_buffer = bytearray(audio_chunk) # 🔥 새로운 데이터로 덮어쓰기
  24. # 수신 크기 확인
  25. print(f"Received data size: {len(audio_chunk)} bytes")
  26. # 오디오 바이너리 데이터 => 숫자배열(numpy)로 해석
  27. audio_np = np.frombuffer(audio_buffer, dtype=np.int16).copy()
  28. # WAV 파일로 저장 (덮어쓰기)
  29. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  30. output_file = f"recorded_audio_{timestamp}.wav"
  31. wavfile.write(output_file, 16000, audio_np)
  32. # STT 처리
  33. print("STT 처리중.....")
  34. stt_result = model.transcribe(output_file, language="ko")
  35. transcription = stt_result["text"]
  36. print("STT 처리완료!")
  37. # 빈 문자열이 아닌 경우만 전송
  38. if transcription.strip():
  39. print("클라이언트에 데이터 전송")
  40. await websocket.send_text(transcription)
  41. print("=================== END =======================")
  42. except WebSocketDisconnect:
  43. print(f"Client {client_id} disconnected")
  44. del clients[client_id]
  45. except Exception as e:
  46. print(f"Error: {e}")
  47. await websocket.send_text(f"Error: {str(e)}")
  48. if __name__ == "__main__":
  49. import uvicorn
  50. uvicorn.run(app, host="0.0.0.0", port=8000)