importasyncioimportwebsocketsimportjsonimportrequestsimportpyaudioimporttime# Variables to use for recording audioCHUNK=1024FORMAT=pyaudio.paInt16
CHANNELS=2RATE=16000p=pyaudio.PyAudio()# This is the language model to use to transcribe the audiomodel="en-US_BroadbandModel"# These are the urls we will be using to communicate with Watsondefault_url="https://stream.watsonplatform.net/speech-to-text/api"token_url="https://stream.watsonplatform.net/authorization/api/v1/token?"\"url=https://stream.watsonplatform.net/speech-to-text/api"url="wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?model=en-US_BroadbandModel"# BlueMix app credentialsusername=""# Your Bluemix App usernamepassword=""# Your Bluemix App password# Send a request to get an authorization keyr=requests.get(token_url,auth=(username,password))auth_token=r.text
token_header={"X-Watson-Authorization-Token":auth_token}# Params to use for Watson APIparams={"word_confidence":True,"content_type":"audio/l16;rate=16000;channels=2","action":"start","interim_results":True}# Opens the stream to start recording from the default microphonestream=p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,output=True,frames_per_buffer=CHUNK)asyncdefsend_audio(ws):# Starts recording of microphoneprint("* READY *")start=time.time()whileTrue:try:print(".")data=stream.read(CHUNK)await ws.send(data)iftime.time()-start>20:# Records for n secondsawait ws.send(json.dumps({'action':'stop'}))returnFalseexceptExceptionase:print(e)returnFalse# Stop the stream and terminate the recordingstream.stop_stream()stream.close()p.terminate()asyncdefspeech_to_text():asyncwithwebsockets.connect(url,extra_headers=token_header)asconn:# Send request to watson and waits for the listening responsesend=await conn.send(json.dumps(params))rec=await conn.recv()print(rec)asyncio.ensure_future(send_audio(conn))# Keeps receiving transcript until we have the final transcriptwhileTrue:try:rec=await conn.recv()parsed=json.loads(rec)transcript=parsed["results"][0]["alternatives"][0]["transcript"]print(transcript)#print(parsed)if"results"inparsed:iflen(parsed["results"])>0:if"final"inparsed["results"][0]:ifparsed["results"][0]["final"]:#conn.close()#return FalsepassexceptKeyError:conn.close()returnFalse# Starts the application looploop=asyncio.get_event_loop()loop.run_until_complete(speech_to_text())loop.close()