Search code examples
python-3.xvariablesjoinwebsocket

How to parse JSON data from websocket to variable in Python


I am using agi asterisk for speech recognition. It connects via websocket and receives a response in json. The script collects words and glues them into a phrase. Everything is working at this stage.

I need to use the collected phrase further (send to telegram and then via api to the helpdesk system), but it doesn't work if i just use text as a variable. How to make text a variable?

#!/usr/bin/python3
from asterisk.agi import *
import os
from websocket import create_connection
import json
import traceback
import requests

AUDIO_FD = 3
CONTENT_TYPE = 'audio/l16; rate=8000; channels=1'
ACCEPT = 'audio/pcm'

def telegram_bot_sendtext(text):
    bot_token = '6069wxts_nWcA'
    bot_chatID = '-10300'
    bot_message = text
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&reply_to_message_id=2&parse_mode=Markdown&text=' + bot_message
    response = requests.get(send_text)
    return response.json()

def process_chunk(agi, ws, buf):
    agi.verbose("Processing chunk")
    ws.send_binary(buf)
    res = json.loads(ws.recv())
    agi.verbose("Result: " + str(res))
    if 'result' in res:
        **text = " ".join([w['word'] for w in res['result']])**
        os.system("espeak -w /tmp/response22.wav \"" + text.encode('utf-8') + "\"")
        os.system("sox /tmp/response22.wav -r 8000 /tmp/response.wav")
        agi.stream_file("/tmp/response")
        os.remove("/tmp/response.wav")

def startAGI():
    agi = AGI()
    agi.verbose("EAGI script started...")
    ani = agi.env['agi_callerid']
    did = agi.env['agi_extension']
    agi.verbose("Call answered from: %s to %s" % (ani, did))
    ws = create_connection("ws://localhost:2700")
    ws.send('{ "config" : { "sample_rate" : 8000 } }')
    agi.verbose("Connection created")
    try:
        while True:
            data = os.read(AUDIO_FD, 8000)
            if not data:
                break
            process_chunk(agi, ws, data)
    except Exception as err:
        agi.verbose(''.join(traceback.format_exception(type(err), err, err.__traceback__)).replace('\n', ' '))
    try:
        telegram_bot_sendtext(text)
    except Exception as exc:
        print("Post_Auth_Script_Telega : Error : ", str(exc))
    finally:
        ws.close()

startAGI()

json looks like

Result: {
'result': [
{'conf': 1.0, 'end': 2.07, 'start': 1.71, 'word': 'One'}, 
{'conf': 1.0, 'end': 2.34, 'start': 2.07, 'word': 'Two'}, 
], 
'text': 'One Two'}

Solution

  • Final working verison

    #!/usr/bin/python3
    
    from asterisk.agi import *
    import os
    from websocket import create_connection
    import json
    import traceback
    import requests
    
    AUDIO_FD = 3
    CONTENT_TYPE = 'audio/l16; rate=8000; channels=1'
    ACCEPT = 'audio/pcm'
    
    def telegram_bot_sendtext(text):
        bot_token = '606922aNwxts_nWcA'
        bot_chatID = '-100100'
        bot_message = text 
        send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&reply_to_message_id=2&parse_mode=Markdown&text=' + bot_message
        response = requests.get(send_text)
        return response.json()
    
    def process_chunk(agi, ws, buf):
        agi.verbose("Processing chunk")
        ws.send_binary(buf)
        res = json.loads(ws.recv())
        agi.verbose("Result: " + str(res))
        if 'result' in res:
            text = " ".join([w['word'] for w in res['result']])
            try:
                telegram_bot_sendtext(text)
            except Exception as exc:
                print("rror : ", str(exc))
            os.system("espeak -w /tmp/response22.wav \"" + text.encode('utf-8') + "\"")
            os.system("sox /tmp/response22.wav -r 8000 /tmp/response.wav")
            agi.stream_file("/tmp/response")
            os.remove("/tmp/response.wav")
    
    def startAGI():
        agi = AGI()
        agi.verbose("EAGI script started...")
        ani = agi.env['agi_callerid']
        did = agi.env['agi_extension']
        agi.verbose("Call answered from: %s to %s" % (ani, did))
        ws = create_connection("ws://localhost:2700")
        ws.send('{ "config" : { "sample_rate" : 8000 } }')
        agi.verbose("Connection created")
        try:
            while True:
                data = os.read(AUDIO_FD, 8000)
                if not data:
                    break
                process_chunk(agi, ws, data)
        except Exception as err:
            agi.verbose(''.join(traceback.format_exception(type(err), err, err.__traceback__)).replace('\n', ' '))
    #    try:
    #        telegram_bot_sendtext(text)
    #    except Exception as exc:
    #        print("rror : ", str(exc))
        finally:
            ws.close()
    
    startAGI()