shahid202 commited on
Commit
9323c84
·
verified ·
1 Parent(s): 7e3d86e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +12 -9
main.py CHANGED
@@ -9,6 +9,7 @@ import numpy as np
9
  app = FastAPI()
10
  app.mount("/static", StaticFiles(directory="static"), name="static")
11
 
 
12
  llm = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-360M-Instruct")
13
  tts = KPipeline(lang_code='a', model='shahid202/Kokoro-82M-TTS')
14
 
@@ -19,16 +20,18 @@ async def get_index():
19
  @app.websocket("/ws/chat")
20
  async def websocket_endpoint(websocket: WebSocket):
21
  await websocket.accept()
22
- try:
23
- while True:
24
  user_msg = await websocket.receive_text()
25
- # Generate response
26
- response = llm(f"User: {user_msg}\nBella:", max_new_tokens=30)[0]['generated_text']
27
- text = response.split("Bella:")[-1].strip()
 
28
 
29
- # Stream audio
30
  for _, _, audio in tts(text, voice="af_heart", speed=1.0):
31
  await websocket.send_bytes(audio.astype(np.float32).tobytes())
32
- await asyncio.sleep(0.01)
33
- except Exception as e:
34
- print(f"Connection closed: {e}")
 
 
9
  app = FastAPI()
10
  app.mount("/static", StaticFiles(directory="static"), name="static")
11
 
12
+ # Initialize pipelines
13
  llm = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-360M-Instruct")
14
  tts = KPipeline(lang_code='a', model='shahid202/Kokoro-82M-TTS')
15
 
 
20
  @app.websocket("/ws/chat")
21
  async def websocket_endpoint(websocket: WebSocket):
22
  await websocket.accept()
23
+ while True:
24
+ try:
25
  user_msg = await websocket.receive_text()
26
+ # Generate LLM response
27
+ output = llm(f"User: {user_msg}\nBella:", max_new_tokens=30, clean_up_tokenization_spaces=False)
28
+ full_text = output[0]['generated_text']
29
+ text = full_text.split("Bella:")[-1].strip()
30
 
31
+ # Stream audio chunks
32
  for _, _, audio in tts(text, voice="af_heart", speed=1.0):
33
  await websocket.send_bytes(audio.astype(np.float32).tobytes())
34
+ await asyncio.sleep(0.01) # Small buffer delay for stability
35
+ except Exception as e:
36
+ print(f"Error in WebSocket: {e}")
37
+ break