Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 537d5c4

Browse filesBrowse files
committed
grpc with tornado web server
1 parent 1be3bfc commit 537d5c4
Copy full SHA for 537d5c4

File tree

Expand file treeCollapse file tree

16 files changed

+1550
-44
lines changed
Filter options
Expand file treeCollapse file tree

16 files changed

+1550
-44
lines changed

‎speech/.idea/inspectionProfiles/profiles_settings.xml

Copy file name to clipboardExpand all lines: speech/.idea/inspectionProfiles/profiles_settings.xml
+7Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎speech/.idea/misc.xml

Copy file name to clipboardExpand all lines: speech/.idea/misc.xml
+4Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎speech/.idea/modules.xml

Copy file name to clipboardExpand all lines: speech/.idea/modules.xml
+8Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎speech/.idea/speech.iml

Copy file name to clipboardExpand all lines: speech/.idea/speech.iml
+11Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎speech/.idea/workspace.xml

Copy file name to clipboardExpand all lines: speech/.idea/workspace.xml
+760Lines changed: 760 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎speech/grpc/chatdemo.py

Copy file name to clipboard
+121Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
#!/usr/bin/env python
2+
#
3+
# Copyright 2009 Facebook
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
6+
# not use this file except in compliance with the License. You may obtain
7+
# a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14+
# License for the specific language governing permissions and limitations
15+
# under the License.
16+
"""Simplified chat demo for websockets.
17+
18+
Authentication, error handling, etc are left as an exercise for the reader :)
19+
"""
20+
21+
import logging
22+
import tornado.escape
23+
import tornado.ioloop
24+
import tornado.options
25+
import tornado.web
26+
import tornado.websocket
27+
import os.path
28+
import uuid
29+
30+
from tornado.options import define, options
31+
32+
define("port", default=8888, help="run on the given port", type=int)
33+
34+
35+
class Application(tornado.web.Application):
36+
def __init__(self):
37+
handlers = [
38+
(r"/", MainHandler),
39+
(r"/test", TestHandler),
40+
(r"/chatsocket", ChatSocketHandler),
41+
]
42+
settings = dict(
43+
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
44+
template_path=os.path.join(os.path.dirname(__file__), "templates"),
45+
static_path=os.path.join(os.path.dirname(__file__), "static"),
46+
xsrf_cookies=False,
47+
)
48+
super(Application, self).__init__(handlers, **settings)
49+
50+
51+
class MainHandler(tornado.web.RequestHandler):
52+
def get(self):
53+
self.render("index.html", messages=ChatSocketHandler.cache)\
54+
55+
class TestHandler(tornado.web.RequestHandler):
56+
def post(self):
57+
self.set_header("Content-Type", "text/plain")
58+
self.write("You wrote " + self.get_body_argument("message"))
59+
60+
# def post(self, message):
61+
# # self.render("index.html", messages=ChatSocketHandler.cache)
62+
# logging.info(message)
63+
chat = {'body': u'{}'.format(self.get_body_argument("message")),
64+
'html': '<div class="message" id="mcf6aef33-cb77-4df5-91a4-852d560ef097">dasdasda</div>\n',
65+
'id': 'cf6aef33-cb77-4df5-91a4-852d560ef097'}
66+
ChatSocketHandler.send_updates(chat)
67+
68+
class ChatSocketHandler(tornado.websocket.WebSocketHandler):
69+
waiters = set()
70+
cache = []
71+
cache_size = 200
72+
73+
def get_compression_options(self):
74+
# Non-None enables compression with default options.
75+
return {}
76+
77+
def open(self):
78+
ChatSocketHandler.waiters.add(self)
79+
80+
def on_close(self):
81+
ChatSocketHandler.waiters.remove(self)
82+
83+
@classmethod
84+
def update_cache(cls, chat):
85+
cls.cache.append(chat)
86+
if len(cls.cache) > cls.cache_size:
87+
cls.cache = cls.cache[-cls.cache_size:]
88+
89+
@classmethod
90+
def send_updates(cls, chat):
91+
logging.info("sending message to %d waiters", len(cls.waiters))
92+
print(chat)
93+
for waiter in cls.waiters:
94+
try:
95+
waiter.write_message(chat)
96+
except:
97+
logging.error("Error sending message", exc_info=True)
98+
99+
def on_message(self, message):
100+
logging.info("got message %r", message)
101+
parsed = tornado.escape.json_decode(message)
102+
chat = {
103+
"id": str(uuid.uuid4()),
104+
"body": parsed["body"],
105+
}
106+
chat["html"] = tornado.escape.to_basestring(
107+
self.render_string("message.html", message=chat))
108+
109+
ChatSocketHandler.update_cache(chat)
110+
ChatSocketHandler.send_updates(chat)
111+
112+
113+
def main():
114+
tornado.options.parse_command_line()
115+
app = Application()
116+
app.listen(options.port)
117+
tornado.ioloop.IOLoop.current().start()
118+
119+
120+
if __name__ == "__main__":
121+
main()

‎speech/grpc/requirements.txt

Copy file name to clipboard
+53-3Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,56 @@
1+
appdirs==1.4.3
2+
awscli==1.11.61
3+
awsebcli==3.10.0
4+
backports-abc==0.5
5+
backports.ssl-match-hostname==3.5.0.1
6+
beautifulsoup4==4.5.3
7+
biopython==1.68
8+
blessed==1.14.1
9+
boto3==1.4.3
10+
botocore==1.5.26
11+
bs4==0.0.1
12+
cement==2.8.2
13+
certifi==2017.1.23
14+
colorama==0.3.7
15+
docker-py==1.7.2
16+
dockerpty==0.4.1
17+
docopt==0.6.2
18+
docutils==0.13.1
19+
enum34==1.1.6
20+
futures==3.0.5
21+
google-auth==0.8.0
22+
googleapis-common-protos==1.5.2
123
grpcio==1.1.0
2-
PyAudio==0.2.10
24+
html5lib==0.999999999
25+
httplib2==0.10.3
26+
jmespath==0.9.2
27+
lxml==3.7.3
28+
mechanize==0.2.5
29+
numpy==1.12.0
30+
oauth2client==3.0.0
31+
packaging==16.8
32+
pandas==0.19.2
33+
pathspec==0.5.0
334
proto-google-cloud-speech-v1beta1==0.15.1
35+
protobuf==3.2.0
36+
pyasn1==0.2.3
37+
pyasn1-modules==0.0.8
38+
PyAudio==0.2.10
39+
PyExecJS==1.4.0
40+
pyparsing==2.2.0
41+
python-dateutil==2.6.0
42+
pytz==2016.10
43+
PyYAML==3.12
44+
requests==2.9.1
45+
rsa==3.4.2
46+
s3transfer==0.1.10
47+
selenium==3.3.1
48+
semantic-version==2.5.0
49+
singledispatch==3.4.0.3
450
six==1.10.0
5-
requests==2.13.0
6-
google-auth==0.8.0
51+
tabulate==0.7.5
52+
termcolor==1.1.0
53+
tornado==4.4.2
54+
wcwidth==0.1.7
55+
webencodings==0.5
56+
websocket-client==0.40.0

‎speech/grpc/static/chat.css

Copy file name to clipboard
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Copyright 2009 FriendFeed
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may
5+
* not use this file except in compliance with the License. You may obtain
6+
* a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
17+
body {
18+
background: white;
19+
margin: 10px;
20+
}
21+
22+
body,
23+
input {
24+
font-family: sans-serif;
25+
font-size: 10pt;
26+
color: black;
27+
}
28+
29+
table {
30+
border-collapse: collapse;
31+
border: 0;
32+
}
33+
34+
td {
35+
border: 0;
36+
padding: 0;
37+
}
38+
39+
#body {
40+
position: absolute;
41+
bottom: 10px;
42+
left: 10px;
43+
}
44+
45+
#input {
46+
margin-top: 0.5em;
47+
}
48+
49+
#inbox .message {
50+
padding-top: 0.25em;
51+
}
52+
53+
#nav {
54+
float: right;
55+
z-index: 99;
56+
}

‎speech/grpc/static/chat.js

Copy file name to clipboard
+71Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Copyright 2009 FriendFeed
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License"); you may
4+
// not use this file except in compliance with the License. You may obtain
5+
// a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11+
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+
// License for the specific language governing permissions and limitations
13+
// under the License.
14+
15+
$(document).ready(function() {
16+
if (!window.console) window.console = {};
17+
if (!window.console.log) window.console.log = function() {};
18+
19+
$("#messageform").on("submit", function() {
20+
newMessage($(this));
21+
return false;
22+
});
23+
$("#messageform").on("keypress", function(e) {
24+
if (e.keyCode == 13) {
25+
newMessage($(this));
26+
return false;
27+
}
28+
});
29+
$("#message").select();
30+
updater.start();
31+
});
32+
33+
function newMessage(form) {
34+
var message = form.formToDict();
35+
updater.socket.send(JSON.stringify(message));
36+
form.find("input[type=text]").val("").select();
37+
}
38+
39+
jQuery.fn.formToDict = function() {
40+
var fields = this.serializeArray();
41+
var json = {}
42+
for (var i = 0; i < fields.length; i++) {
43+
json[fields[i].name] = fields[i].value;
44+
}
45+
if (json.next) delete json.next;
46+
return json;
47+
};
48+
49+
var updater = {
50+
socket: null,
51+
52+
start: function() {
53+
var url = "ws://" + location.host + "/chatsocket";
54+
console.log("received message");
55+
updater.socket = new WebSocket(url);
56+
updater.socket.onmessage = function(event) {
57+
updater.showMessage(JSON.parse(event.data));
58+
console.log("received message "+JSON.parse(event.data).body);
59+
responsiveVoice.speak(JSON.parse(event.data).body, 'Thai Female');
60+
}
61+
},
62+
63+
showMessage: function(message) {
64+
var existing = $("#m" + message.id);
65+
if (existing.length > 0) return;
66+
var node = $(message.html);
67+
node.hide();
68+
$("#inbox").append(node);
69+
node.slideDown();
70+
}
71+
};

‎speech/grpc/templates/index.html

Copy file name to clipboard
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Tornado Chat Demo</title>
6+
<link rel="stylesheet" href="{{ static_url("chat.css") }}" type="text/css">
7+
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
8+
</head>
9+
<body>
10+
<div id="body">
11+
<div id="inbox">
12+
{% for message in messages %}
13+
{% include "message.html" %}
14+
{% end %}
15+
</div>
16+
<div id="input">
17+
<form action="/a/message/new" method="post" id="messageform">
18+
<table>
19+
<tr>
20+
<td><input name="body" id="message" style="width:500px"></td>
21+
<td style="padding-left:5px">
22+
<input type="submit" value="{{ _("Post") }}">
23+
<input type="hidden" name="next" value="{{ request.path }}">
24+
{% module xsrf_form_html() %}
25+
</td>
26+
</tr>
27+
</table>
28+
</form>
29+
</div>
30+
</div>
31+
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" type="text/javascript"></script>
32+
<script src="{{ static_url("chat.js") }}" type="text/javascript"></script>
33+
</body>
34+
</html>

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.