Guest User

Untitled

a guest
Nov 27th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. def speech_to_text(
  2. file_name, auth_file='auth.json', output_dir='output', opt_out=False,
  3. tokenauth=None,
  4. model='en-US_BroadbandModel', content_type='audio/wav',
  5. threads=1
  6. ):
  7. """
  8. Convert given audio file to text.
  9. """
  10. # logging
  11. # log.startLogging(sys.stdout)
  12.  
  13. # add audio files to the processing queue
  14. q = Queue.Queue()
  15. file_number = 0
  16. q.put((file_number, file_name))
  17.  
  18. hostname = "stream.watsonplatform.net"
  19. headers = {}
  20. if (opt_out is True):
  21. headers['X-WDC-PL-OPT-OUT'] = '1'
  22.  
  23. try:
  24. with open(auth_file) as authfile:
  25. auth_data = json.load(authfile)
  26. username = auth_data['stt']['username']
  27. password = auth_data['stt']['password']
  28. except:
  29. raise
  30. # authentication header
  31. if tokenauth:
  32. headers['X-Watson-Authorization-Token'] = (
  33. Utils.getAuthenticationToken(
  34. "https://" + hostname, 'speech-to-text',
  35. username, password))
  36. else:
  37. string = username + ":" + password
  38. headers["Authorization"] = "Basic " + base64.b64encode(string)
  39.  
  40. # create a WS server factory with our protocol
  41. url = "wss://" + hostname + "/speech-to-text/api/v1/recognize?model="
  42. + model
  43. summary = {}
  44. factory = WSInterfaceFactory(q, summary, output_dir, content_type,
  45. model, url, headers, debug=False)
  46. factory.protocol = WSInterfaceProtocol
  47.  
  48. for i in range(min(int(threads), q.qsize())):
  49.  
  50. factory.prepareUtterance()
  51.  
  52. # SSL client context: default
  53. if factory.isSecure:
  54. context_factory = ssl.ClientContextFactory()
  55. else:
  56. context_factory = None
  57. connectWS(factory, context_factory)
  58.  
  59. reactor.run()
  60.  
  61. value = summary[0]
  62. if value['status']['code'] == 1000:
  63. return value['hypothesis'].encode('utf-8')
  64. else:
  65. return False
Add Comment
Please, Sign In to add comment