Spaces:
Build error
Build error
Create server.py
Browse files
server.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import websockets
|
| 3 |
+
import os
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from pydub import AudioSegment
|
| 6 |
+
from utils import transcribe_audio, get_response_llm, play_text_to_speech, load_whisper
|
| 7 |
+
|
| 8 |
+
# Load Whisper Model
|
| 9 |
+
model = load_whisper()
|
| 10 |
+
|
| 11 |
+
# Store connected clients
|
| 12 |
+
clients = set()
|
| 13 |
+
|
| 14 |
+
async def handle_audio_stream(websocket):
|
| 15 |
+
"""Handles incoming live audio stream from users."""
|
| 16 |
+
clients.add(websocket)
|
| 17 |
+
try:
|
| 18 |
+
while True:
|
| 19 |
+
audio_chunk = await websocket.recv()
|
| 20 |
+
if not audio_chunk:
|
| 21 |
+
break
|
| 22 |
+
|
| 23 |
+
# Convert received bytes to WAV file
|
| 24 |
+
audio = AudioSegment.from_file(BytesIO(audio_chunk))
|
| 25 |
+
audio.export("temp_audio_chunk.wav", format="wav")
|
| 26 |
+
|
| 27 |
+
# Transcribe
|
| 28 |
+
text = transcribe_audio(model, "temp_audio_chunk.wav")
|
| 29 |
+
if text:
|
| 30 |
+
print(f"User: {text}")
|
| 31 |
+
|
| 32 |
+
# Generate response
|
| 33 |
+
response_llm = get_response_llm(user_question=text)
|
| 34 |
+
|
| 35 |
+
# Play response
|
| 36 |
+
play_text_to_speech(text=response_llm)
|
| 37 |
+
|
| 38 |
+
# Send response to WebSocket client
|
| 39 |
+
await websocket.send(response_llm)
|
| 40 |
+
except:
|
| 41 |
+
pass
|
| 42 |
+
finally:
|
| 43 |
+
clients.remove(websocket)
|
| 44 |
+
|
| 45 |
+
async def main():
|
| 46 |
+
async with websockets.serve(handle_audio_stream, "0.0.0.0", 8765):
|
| 47 |
+
await asyncio.Future() # Keeps the server running
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
asyncio.run(main())
|