Javascript 如何在python中的两个WebSocket之间共享数据?
我成功地建立了一个连接到Twilio服务器的websocket,当我呼叫它时,它会将我的对话流式传输到一个电话号码。然后,代码使用google语音文本API转录调用并将其打印到我的命令行 我的下一步是在生成每个转录的单词时,将其流式传输到网页的“主页”路径。所以当我对着电话讲话时,这些话就会出现在网页上 我的问题是,在设置单独的websocket处理程序时,我似乎无法访问变量“translation”,然后我将使用它来更新“home”路由。socketio.emit似乎未连接到socketio处理程序?这是最好的方式吗?有人知道我该怎么做吗?server.py中以#开头的代码是我为尝试创建第二个websocket而添加的代码,这些代码没有按预期工作。我的代码如下: server.pyJavascript 如何在python中的两个WebSocket之间共享数据?,javascript,html,python-3.x,twilio,flask-socketio,Javascript,Html,Python 3.x,Twilio,Flask Socketio,我成功地建立了一个连接到Twilio服务器的websocket,当我呼叫它时,它会将我的对话流式传输到一个电话号码。然后,代码使用google语音文本API转录调用并将其打印到我的命令行 我的下一步是在生成每个转录的单词时,将其流式传输到网页的“主页”路径。所以当我对着电话讲话时,这些话就会出现在网页上 我的问题是,在设置单独的websocket处理程序时,我似乎无法访问变量“translation”,然后我将使用它来更新“home”路由。socketio.emit似乎未连接到socketio处
from flask import Flask, render_template, session
from flask_sockets import Sockets
from flask_socketio import SocketIO, emit
from SpeechClientBridge import SpeechClientBridge
from google.cloud.speech import enums
from google.cloud.speech import types
import json
import base64
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"
HTTP_SERVER_PORT = 5000
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.MULAW,
sample_rate_hertz=8000,
language_code='en-US')
streaming_config = types.StreamingRecognitionConfig(
config=config,
interim_results=True)
app = Flask(__name__)
sockets = Sockets(app)
#socketio = SocketIO(app)
@app.route('/home')
def home():
return render_template("index.html")
@app.route('/twiml', methods=['POST'])
def return_twiml():
print("POST TwiML")
return render_template('streams.xml')
def on_transcription_response(response):
if not response.results:
return
result = response.results[0]
if not result.alternatives:
return
transcription = result.alternatives[0].transcript
#session['newword'] = transcription
print("Transcription: " + transcription)
@sockets.route('/')
def transcript(ws):
print("WS connection opened")
bridge = SpeechClientBridge(
streaming_config,
on_transcription_response
)
while not ws.closed:
message = ws.receive()
if message is None:
bridge.terminate()
break
data = json.loads(message)
if data["event"] in ("connected", "start"):
print(f"Media WS: Received event '{data['event']}': {message}")
continue
if data["event"] == "media":
media = data["media"]
chunk = base64.b64decode(media["payload"])
bridge.add_request(chunk)
if data["event"] == "stop":
print(f"Media WS: Received event 'stop': {message}")
print("Stopping...")
break
bridge.terminate()
print("WS connection closed")
#@socketio.on('connect', namespace='/test')
#def test_connect():
#word = session.get('newword',None)
#socketio.emit('newword', {'newword': word}, namespace='/test')
#print('Client connected')
if __name__ == '__main__':
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler)
print("Server listening on: http://localhost:" + str(HTTP_SERVER_PORT))
server.serve_forever()
#socketio.run(app)
streams.xml
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Start>
<Stream url="wss://1812ce142529.ngrok.io/"></Stream>
</Start>
<Say>Thanks for calling!</Say>
<Pause length="40"/>
</Response>
谢谢你的来电!
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Transcription with Twilio Media Streams</title>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="static/css/application.js"></script>
<link rel="stylesheet" type="text/css" href="static/css/style.css" />
</head>
<body>
<h1>Live Transcription with Twilio Media Streams</h1>
<img src="static/css/twilio-logo-red.png" />
<img src="static/css/cloudspeechtotext.png" />
<div class="container" id="content">
<div class="row">
<p>Asynchronous page updates will appear here:</p>
<h3>Transcription:</h3>
<div id="log">
</div> <!-- /#log -->
</div>
</div>
</body>
</html>
使用Twilio媒体流进行实时转录
使用Twilio媒体流进行实时转录
异步页面更新将显示在此处:
转录:
application.js
$(document).ready(function(){
//connect to the socket server.
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var words_received = [];
//receive details from server
socket.on('newword', function(msg) {
console.log("Received word" + msg.word);
//maintain a list of ten words
if (words_received.length >= 10){
words_received.shift()
}
words_received.push(msg.words);
words_string = '';
for (var i = 0; i < words_received.length; i++){
words_string = words_string + '<p>' + words_received[i].toString() + '</p>';
}
$('#log').html(words_string);
});
});
$(文档).ready(函数(){
//连接到套接字服务器。
var socket=io.connect('http://'+document.domain+':'+location.port+'/test');
var words_received=[];
//从服务器接收详细信息
socket.on('newword',函数(msg){
console.log(“接收到的字”+msg.word);
//列出十个单词
如果(字数_received.length>=10){
收到的字数。shift()
}
文字_已接收。推送(msg.words);
单词_字符串=“”;
for(var i=0;i';
}
$('#log').html(单词字符串);
});
});
我对这一切都很陌生,到目前为止,我已经把很多其他人的代码拼凑在一起,所以我现在被卡住了。非常感谢您的帮助。在服务器上,您正在发出一个名为
word
的事件,但在application.js中,您有一个newword
事件的处理程序。也许这就是问题所在?谢谢你的评论。你说的前后矛盾是对的。我已经用修改和我的最新一轮代码迭代更新了问题中的代码。但是,这些更改仍然不起作用。我不知道由Flask Sockets和Flask SocketIO扩展启动的服务器是否兼容,从未见过有人同时使用这两个。也许您应该考虑为两台服务器编写单独的进程,以防止两个扩展之间发生任何冲突。嗨,我正在尝试做类似的事情,但我无法从Twilio接收媒体流,我使用的是flask socketio,但是,我注意到您使用的是flask socketio,您使用的是flask socketio吗?它不起作用了吗?在服务器上,您正在发出一个名为word
的事件,但在application.js中,您有一个newword
事件的处理程序。也许这就是问题所在?谢谢你的评论。你说的前后矛盾是对的。我已经用修改和我的最新一轮代码迭代更新了问题中的代码。但是,这些更改仍然不起作用。我不知道由Flask Sockets和Flask SocketIO扩展启动的服务器是否兼容,从未见过有人同时使用这两个。也许您应该考虑为两台服务器编写单独的进程,以防止两个扩展之间发生任何冲突。嗨,我正在尝试做类似的事情,但我无法从Twilio接收媒体流,我使用的是flask socketio,但是,我注意到您使用的是flask socketio,您使用的是flask socketio吗?没用吗?