client.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. from colorama import Fore, Back, Style
  2. import websockets
  3. import colorama
  4. import keyboard
  5. import asyncio
  6. import json
  7. import os
  8. colorama.init()
  9. SEND_START_COMMAND = False
  10. HOST = 'localhost:5025'
  11. URI = f'ws://{HOST}'
  12. RECONNECT_DELAY = 5
  13. full_sentences = []
  14. def clear_console():
  15. os.system('clear' if os.name == 'posix' else 'cls')
  16. def update_displayed_text(text = ""):
  17. sentences_with_style = [
  18. f"{Fore.YELLOW + sentence + Style.RESET_ALL if i % 2 == 0 else Fore.CYAN + sentence + Style.RESET_ALL} "
  19. for i, sentence in enumerate(full_sentences)
  20. ]
  21. text = "".join(sentences_with_style).strip() + " " + text if len(sentences_with_style) > 0 else text
  22. clear_console()
  23. print("CLIENT retrieved text:")
  24. print()
  25. print(text)
  26. async def send_start_recording(websocket):
  27. command = {
  28. "type": "command",
  29. "content": "start-recording"
  30. }
  31. await websocket.send(json.dumps(command))
  32. async def test_client():
  33. while True:
  34. try:
  35. async with websockets.connect(URI, ping_interval=None) as websocket:
  36. if SEND_START_COMMAND:
  37. # New: Check for space bar press and send start-recording message
  38. async def check_space_keypress():
  39. while True:
  40. if keyboard.is_pressed('space'):
  41. print ("Space bar pressed. Sending start-recording message to server.")
  42. await send_start_recording(websocket)
  43. await asyncio.sleep(1)
  44. await asyncio.sleep(0.02)
  45. # Start a task to monitor the space keypress
  46. print ("Press space bar to start recording.")
  47. asyncio.create_task(check_space_keypress())
  48. while True:
  49. message = await websocket.recv()
  50. message_obj = json.loads(message)
  51. if message_obj["type"] == "realtime":
  52. clear_console()
  53. print (message_obj["content"])
  54. elif message_obj["type"] == "full":
  55. clear_console()
  56. colored_message = Fore.YELLOW + message_obj["content"] + Style.RESET_ALL
  57. print (colored_message)
  58. print ()
  59. if SEND_START_COMMAND:
  60. print ("Press space bar to start recording.")
  61. full_sentences.append(message_obj["content"])
  62. elif message_obj["type"] == "record_start":
  63. print ("recording started.")
  64. elif message_obj["type"] == "vad_start":
  65. print ("vad started.")
  66. elif message_obj["type"] == "wakeword_start":
  67. print ("wakeword started.")
  68. elif message_obj["type"] == "transcript_start":
  69. print ("transcript started.")
  70. else:
  71. print (f"Unknown message: {message_obj}")
  72. except websockets.ConnectionClosed:
  73. print("Connection with server closed. Reconnecting in", RECONNECT_DELAY, "seconds...")
  74. await asyncio.sleep(RECONNECT_DELAY)
  75. except KeyboardInterrupt:
  76. print("Gracefully shutting down the client.")
  77. break
  78. except Exception as e:
  79. print(f"An error occurred: {e}. Reconnecting in", RECONNECT_DELAY, "seconds...")
  80. await asyncio.sleep(RECONNECT_DELAY)
  81. asyncio.run(test_client())