英文:
How to parse JSON data from websocket to variable in Python
问题
我使用AGI Asterisk进行语音识别。它通过WebSocket连接并接收JSON响应。
脚本收集单词并将它们粘合成短语。
到目前为止,一切都正常。
我需要进一步使用收集到的短语(发送到Telegram,然后通过API发送到帮助台系统),但如果我只使用text作为变量,它不起作用。
如何将text设置为变量?
#!/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看起来像这样
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'}
<details>
<summary>英文:</summary>
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'}
</details>
# 答案1
**得分**: 0
以下是代码的翻译部分:
```python
#!/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("Error: ", 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("Error: ", str(exc))
finally:
ws.close()
startAGI()
希望这对你有所帮助。如果你需要进一步的信息或翻译,请告诉我。
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论