client.mic.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import json
  2. import pyaudio
  3. import sys
  4. from MLLPStreamingClient import MLLPStreamingClient
  5. server_hostname = "<SERVER_ADDRESS>"
  6. server_port = "<PORT>"
  7. api_user = "<YOU_API_USER>"
  8. api_secret = "<YOUR_API_KEY>"
  9. server_ssl_cert_file = "<CRT_FILE>"
  10. #Client object creation
  11. cli = MLLPStreamingClient(server_hostname, server_port, api_user,api_secret, server_ssl_cert_file)
  12. #Get Token for the session
  13. cli.getAuthToken()
  14. #Get available systems, a dictionary with the information related to the available systems and languages
  15. systems = cli.getTranscribeSystemsInfo()
  16. #Audio streaming iterator to send the audio file
  17. def myStreamIterator():
  18. #Audio features
  19. CHUNK = 1024
  20. #1 channel, 16Khz, int16 audio
  21. FORMAT = pyaudio.paInt16
  22. CHANNELS = 1
  23. RATE = 16000
  24. #Limits the recording to 120 seconds
  25. RECORD_SECONDS = 120
  26. p = pyaudio.PyAudio()
  27. stream = p.open(format=FORMAT,
  28. channels=CHANNELS,
  29. rate=RATE,
  30. input=True,
  31. frames_per_buffer=CHUNK)
  32. print("Sending data..")
  33. #Sends data in chunks of 1024 bytes
  34. for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  35. data = stream.read(CHUNK)
  36. yield data
  37. #Stops and close the stream
  38. stream.stop_stream()
  39. stream.close()
  40. p.terminate()
  41. es_system = {}
  42. #Select Spanish system for testing
  43. for system in systems:
  44. if system['info']['langs'][0]['code'] == "es":
  45. es_system = system
  46. if es_system == {}:
  47. raise Exception("Spanish system not found")
  48. #Selects the system with the system id for the Spanish system, updated in Feb20
  49. for resp in cli.transcribe(es_system, myStreamIterator):
  50. # Hyp_var contains part of the hypothesis that is not consolidated yet (hypothesis could change)
  51. if resp["hyp_var"] != "":
  52. print("VAR")
  53. sys.stdout.write("{} ".format(resp["hyp_var"].strip().replace("[SILENCE]","")))
  54. if resp["eos"]:
  55. sys.stdout.write("\n")
  56. sys.stdout.flush()
  57. # Hyp_novar contains part of the hypothesis that is consolidated (hypothesis will not change)
  58. if resp["hyp_novar"] != "":
  59. print("\nNOVAR")
  60. sys.stdout.write("{} ".format(resp["hyp_novar"].strip()))
  61. if resp["eos"]:
  62. sys.stdout.write("\n")
  63. sys.stdout.flush()