如何在Python中从WebSocket解析JSON数据到变量

huangapple go评论138阅读模式
英文:

How to parse JSON data from websocket to variable in Python

问题

我使用AGI Asterisk进行语音识别。它通过WebSocket连接并接收JSON响应。
脚本收集单词并将它们粘合成短语。
到目前为止,一切都正常。

我需要进一步使用收集到的短语(发送到Telegram,然后通过API发送到帮助台系统),但如果我只使用text作为变量,它不起作用。
如何将text设置为变量?

  1. #!/usr/bin/python3
  2. from asterisk.agi import *
  3. import os
  4. from websocket import create_connection
  5. import json
  6. import traceback
  7. import requests
  8. AUDIO_FD = 3
  9. CONTENT_TYPE = 'audio/l16; rate=8000; channels=1'
  10. ACCEPT = 'audio/pcm'
  11. def telegram_bot_sendtext(text):
  12. bot_token = '6069wxts_nWcA'
  13. bot_chatID = '-10300'
  14. bot_message = text
  15. 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
  16. response = requests.get(send_text)
  17. return response.json()
  18. def process_chunk(agi, ws, buf):
  19. agi.verbose("Processing chunk")
  20. ws.send_binary(buf)
  21. res = json.loads(ws.recv())
  22. agi.verbose("Result: " + str(res))
  23. if 'result' in res:
  24. text = " ".join([w['word'] for w in res['result']])
  25. os.system("espeak -w /tmp/response22.wav \"" + text.encode('utf-8') + "\"")
  26. os.system("sox /tmp/response22.wav -r 8000 /tmp/response.wav")
  27. agi.stream_file("/tmp/response")
  28. os.remove("/tmp/response.wav")
  29. def startAGI():
  30. agi = AGI()
  31. agi.verbose("EAGI script started...")
  32. ani = agi.env['agi_callerid']
  33. did = agi.env['agi_extension']
  34. agi.verbose("Call answered from: %s to %s" % (ani, did))
  35. ws = create_connection("ws://localhost:2700")
  36. ws.send('{ "config" : { "sample_rate" : 8000 } }')
  37. agi.verbose("Connection created")
  38. try:
  39. while True:
  40. data = os.read(AUDIO_FD, 8000)
  41. if not data:
  42. break
  43. process_chunk(agi, ws, data)
  44. except Exception as err:
  45. agi.verbose(''.join(traceback.format_exception(type(err), err, err.__traceback__)).replace('\n', ' '))
  46. try:
  47. telegram_bot_sendtext(text)
  48. except Exception as exc:
  49. print("Post_Auth_Script_Telega : Error : ", str(exc))
  50. finally:
  51. ws.close()
  52. 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'}

  1. <details>
  2. <summary>英文:</summary>
  3. I am using agi asterisk for speech recognition. It connects via websocket and receives a response in json.
  4. The script collects words and glues them into a phrase.
  5. Everything is working at this stage.
  6. I need to use the collected phrase further (send to telegram and then via api to the helpdesk system), but it doesn&#39;t work if i just use **text** as a variable.
  7. How to make ***text*** a variable?
  8. #!/usr/bin/python3
  9. from asterisk.agi import *
  10. import os
  11. from websocket import create_connection
  12. import json
  13. import traceback
  14. import requests
  15. AUDIO_FD = 3
  16. CONTENT_TYPE = &#39;audio/l16; rate=8000; channels=1&#39;
  17. ACCEPT = &#39;audio/pcm&#39;
  18. def telegram_bot_sendtext(text):
  19. bot_token = &#39;6069wxts_nWcA&#39;
  20. bot_chatID = &#39;-10300&#39;
  21. bot_message = text
  22. send_text = &#39;https://api.telegram.org/bot&#39; + bot_token + &#39;/sendMessage?chat_id=&#39; + bot_chatID + &#39;&amp;reply_to_message_id=2&amp;parse_mode=Markdown&amp;text=&#39; + bot_message
  23. response = requests.get(send_text)
  24. return response.json()
  25. def process_chunk(agi, ws, buf):
  26. agi.verbose(&quot;Processing chunk&quot;)
  27. ws.send_binary(buf)
  28. res = json.loads(ws.recv())
  29. agi.verbose(&quot;Result: &quot; + str(res))
  30. if &#39;result&#39; in res:
  31. **text = &quot; &quot;.join([w[&#39;word&#39;] for w in res[&#39;result&#39;]])**
  32. os.system(&quot;espeak -w /tmp/response22.wav \&quot;&quot; + text.encode(&#39;utf-8&#39;) + &quot;\&quot;&quot;)
  33. os.system(&quot;sox /tmp/response22.wav -r 8000 /tmp/response.wav&quot;)
  34. agi.stream_file(&quot;/tmp/response&quot;)
  35. os.remove(&quot;/tmp/response.wav&quot;)
  36. def startAGI():
  37. agi = AGI()
  38. agi.verbose(&quot;EAGI script started...&quot;)
  39. ani = agi.env[&#39;agi_callerid&#39;]
  40. did = agi.env[&#39;agi_extension&#39;]
  41. agi.verbose(&quot;Call answered from: %s to %s&quot; % (ani, did))
  42. ws = create_connection(&quot;ws://localhost:2700&quot;)
  43. ws.send(&#39;{ &quot;config&quot; : { &quot;sample_rate&quot; : 8000 } }&#39;)
  44. agi.verbose(&quot;Connection created&quot;)
  45. try:
  46. while True:
  47. data = os.read(AUDIO_FD, 8000)
  48. if not data:
  49. break
  50. process_chunk(agi, ws, data)
  51. except Exception as err:
  52. agi.verbose(&#39;&#39;.join(traceback.format_exception(type(err), err, err.__traceback__)).replace(&#39;\n&#39;, &#39; &#39;))
  53. try:
  54. telegram_bot_sendtext(text)
  55. except Exception as exc:
  56. print(&quot;Post_Auth_Script_Telega : Error : &quot;, str(exc))
  57. finally:
  58. ws.close()
  59. startAGI()
  60. json looks like
  61. Result: {
  62. &#39;result&#39;: [
  63. {&#39;conf&#39;: 1.0, &#39;end&#39;: 2.07, &#39;start&#39;: 1.71, &#39;word&#39;: &#39;One&#39;},
  64. {&#39;conf&#39;: 1.0, &#39;end&#39;: 2.34, &#39;start&#39;: 2.07, &#39;word&#39;: &#39;Two&#39;},
  65. ],
  66. &#39;text&#39;: &#39;One Two&#39;}
  67. </details>
  68. # 答案1
  69. **得分**: 0
  70. 以下是代码的翻译部分:
  71. ```python
  72. #!/usr/bin/python3
  73. from asterisk.agi import *
  74. import os
  75. from websocket import create_connection
  76. import json
  77. import traceback
  78. import requests
  79. AUDIO_FD = 3
  80. CONTENT_TYPE = 'audio/l16; rate=8000; channels=1'
  81. ACCEPT = 'audio/pcm'
  82. def telegram_bot_sendtext(text):
  83. bot_token = '606922aNwxts_nWcA'
  84. bot_chatID = '-100100'
  85. bot_message = text
  86. send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&amp;reply_to_message_id=2&amp;parse_mode=Markdown&amp;text=' + bot_message
  87. response = requests.get(send_text)
  88. return response.json()
  89. def process_chunk(agi, ws, buf):
  90. agi.verbose("Processing chunk")
  91. ws.send_binary(buf)
  92. res = json.loads(ws.recv())
  93. agi.verbose("Result: " + str(res))
  94. if 'result' in res:
  95. text = " ".join([w['word'] for w in res['result']])
  96. try:
  97. telegram_bot_sendtext(text)
  98. except Exception as exc:
  99. print("Error: ", str(exc))
  100. os.system("espeak -w /tmp/response22.wav \"" + text.encode('utf-8') + "\"")
  101. os.system("sox /tmp/response22.wav -r 8000 /tmp/response.wav")
  102. agi.stream_file("/tmp/response")
  103. os.remove("/tmp/response.wav")
  104. def startAGI():
  105. agi = AGI()
  106. agi.verbose("EAGI script started...")
  107. ani = agi.env['agi_callerid']
  108. did = agi.env['agi_extension']
  109. agi.verbose("Call answered from: %s to %s" % (ani, did))
  110. ws = create_connection("ws://localhost:2700")
  111. ws.send('{ "config" : { "sample_rate" : 8000 } }')
  112. agi.verbose("Connection created")
  113. try:
  114. while True:
  115. data = os.read(AUDIO_FD, 8000)
  116. if not data:
  117. break
  118. process_chunk(agi, ws, data)
  119. except Exception as err:
  120. agi.verbose(' '.join(traceback.format_exception(type(err), err, err.__traceback__)).replace('\n', ' '))
  121. # try:
  122. # telegram_bot_sendtext(text)
  123. # except Exception as exc:
  124. # print("Error: ", str(exc))
  125. finally:
  126. ws.close()
  127. startAGI()

希望这对你有所帮助。如果你需要进一步的信息或翻译,请告诉我。

英文:

Final working verison

  1. #!/usr/bin/python3
  2. from asterisk.agi import *
  3. import os
  4. from websocket import create_connection
  5. import json
  6. import traceback
  7. import requests
  8. AUDIO_FD = 3
  9. CONTENT_TYPE = &#39;audio/l16; rate=8000; channels=1&#39;
  10. ACCEPT = &#39;audio/pcm&#39;
  11. def telegram_bot_sendtext(text):
  12. bot_token = &#39;606922aNwxts_nWcA&#39;
  13. bot_chatID = &#39;-100100&#39;
  14. bot_message = text
  15. send_text = &#39;https://api.telegram.org/bot&#39; + bot_token + &#39;/sendMessage?chat_id=&#39; + bot_chatID + &#39;&amp;reply_to_message_id=2&amp;parse_mode=Markdown&amp;text=&#39; + bot_message
  16. response = requests.get(send_text)
  17. return response.json()
  18. def process_chunk(agi, ws, buf):
  19. agi.verbose(&quot;Processing chunk&quot;)
  20. ws.send_binary(buf)
  21. res = json.loads(ws.recv())
  22. agi.verbose(&quot;Result: &quot; + str(res))
  23. if &#39;result&#39; in res:
  24. text = &quot; &quot;.join([w[&#39;word&#39;] for w in res[&#39;result&#39;]])
  25. try:
  26. telegram_bot_sendtext(text)
  27. except Exception as exc:
  28. print(&quot;rror : &quot;, str(exc))
  29. os.system(&quot;espeak -w /tmp/response22.wav \&quot;&quot; + text.encode(&#39;utf-8&#39;) + &quot;\&quot;&quot;)
  30. os.system(&quot;sox /tmp/response22.wav -r 8000 /tmp/response.wav&quot;)
  31. agi.stream_file(&quot;/tmp/response&quot;)
  32. os.remove(&quot;/tmp/response.wav&quot;)
  33. def startAGI():
  34. agi = AGI()
  35. agi.verbose(&quot;EAGI script started...&quot;)
  36. ani = agi.env[&#39;agi_callerid&#39;]
  37. did = agi.env[&#39;agi_extension&#39;]
  38. agi.verbose(&quot;Call answered from: %s to %s&quot; % (ani, did))
  39. ws = create_connection(&quot;ws://localhost:2700&quot;)
  40. ws.send(&#39;{ &quot;config&quot; : { &quot;sample_rate&quot; : 8000 } }&#39;)
  41. agi.verbose(&quot;Connection created&quot;)
  42. try:
  43. while True:
  44. data = os.read(AUDIO_FD, 8000)
  45. if not data:
  46. break
  47. process_chunk(agi, ws, data)
  48. except Exception as err:
  49. agi.verbose(&#39;&#39;.join(traceback.format_exception(type(err), err, err.__traceback__)).replace(&#39;\n&#39;, &#39; &#39;))
  50. # try:
  51. # telegram_bot_sendtext(text)
  52. # except Exception as exc:
  53. # print(&quot;rror : &quot;, str(exc))
  54. finally:
  55. ws.close()
  56. startAGI()

huangapple
  • 本文由 发表于 2023年7月27日 20:38:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定