-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·194 lines (160 loc) · 6.12 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from flask import Flask, render_template, session
from flask.ext.socketio import SocketIO, emit
import os
import base64
from os import path
import subprocess
import random
import threading
import string
from uuid import uuid4
from pipes import quote
# instantiate and configure app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'qw234l2elkjwerljwerlqwe'
app.debug = True
socketio = SocketIO(app)
# set up environment and variables
VOLUMES_DIR = '/Volumes'
RAMDISK = 'ramdisk'
RAMDISK_SIZE = 20480
if not path.exists(path.join(VOLUMES_DIR,RAMDISK)):
os.system("diskutil erasevolume HFS+ '" + RAMDISK + "' `hdiutil attach -nomount ram://" + str(RAMDISK_SIZE) + "`")
SOCKET_NAMESPACE = '/spooky'
VOICE_OPTIONS = filter(None,[x.split(' ')[0] for x in os.popen('say -v ?').read().split('\n')])
print VOICE_OPTIONS
LOCK = threading.Lock()
CREEPY_THINGS_TO_SAY = ['ahhhhhhhh', 'boooooooooo', 'gahhhhhhh']
global ALL_WORDS_ENTERED
ALL_WORDS_ENTERED = []
DEFAULT_SPEED = 120
# routes and socket events
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@socketio.on('motion_detected', namespace=SOCKET_NAMESPACE)
def motion_detected(message):
print message
if session['locked']: return
session['locked'] = True
b64_data = get_base64_data(get_words(),get_speed(message),get_voice(message))
session['locked'] = False
if b64_data: emit('sound', {'type': 'mp3', 'data': b64_data})
@socketio.on('say_word', namespace=SOCKET_NAMESPACE)
def say_word(message):
if len(message['data']) > 200: return
session['locked'] = True
b64_data = get_base64_data(get_words(message),get_speed(message),get_voice(message))
session['locked'] = False
if b64_data: emit('sound', {'type': 'mp3', 'data': b64_data})
@socketio.on('word_added', namespace=SOCKET_NAMESPACE)
def word_added(message):
if len(message['data']) > 200: return
global ALL_WORDS_ENTERED
session['words'] += [message['data']]
ALL_WORDS_ENTERED += [message['data']]
emit('word_added', {'data': message['data']}, broadcast=True)
@socketio.on('word_removed', namespace=SOCKET_NAMESPACE)
def word_removed(message):
if message['data'] in session['words']: session['words'].remove(message['data'])
emit('word_removed', {'data': "Removed"})
@socketio.on('voice_added', namespace=SOCKET_NAMESPACE)
def voice_added(message):
if len(message['data']) > 200: return
print 'Adding voice: ' + message['data']
if message['data'] not in session['voices']:
session['voices'] += [message['data']]
print session['voices']
@socketio.on('voice_removed', namespace=SOCKET_NAMESPACE)
def voice_removed(message):
if len(message['data']) > 200: return
print 'Removing voice: ' + message['data']
if message['data'] in session['voices']:
session['voices'].remove(message['data'])
@socketio.on('set_speed', namespace=SOCKET_NAMESPACE)
def set_speed(message):
spd = message['data']
if spd is None and 'speed' in session:
session['speed'] = None
else:
try:
spd = int(spd)
if isinstance(spd,int):
session['speed'] = spd
except:
return
@socketio.on('all_voices', namespace=SOCKET_NAMESPACE)
def all_voices():
print "setting all voices"
session['voices'] = list(VOICE_OPTIONS)
@socketio.on('clear_voices', namespace=SOCKET_NAMESPACE)
def clear_voices():
print "clearing all voices"
session['voices'] = []
@socketio.on('connect', namespace=SOCKET_NAMESPACE)
def connect():
print 'Client connected'
session['id'] = str(uuid4())
session['words'] = []
session['voices'] = list(VOICE_OPTIONS)
session['locked'] = False
session['speed'] = None
emit('connection_response', {'data': 'Connected', 'voices': VOICE_OPTIONS, 'words' : ALL_WORDS_ENTERED})
@socketio.on('disconnect', namespace=SOCKET_NAMESPACE)
def disconnect():
print 'Client with id ' + session['id'] + ' disconnected'
def get_base64_data(words, speed, voice):
try:
# generate sound file and write to ramdisk
filename = path.join(VOLUMES_DIR, RAMDISK, ''.join(random.sample(string.ascii_lowercase, 10)))
create_binary_data(quote(words), str(speed), quote(voice), filename)
binaryFile = open((filename + ".mp3"), "rb")
binaryData = binaryFile.read()
binaryFile.close()
# convert sound data into base64
b64_data = base64.b64encode(binaryData)
print "sending " + str(((len(b64_data) / 3) * 4)/1000) + " kilobytes to client with id: " + session['id']
# cleanup file
cmd = 'rm ' + filename + '.mp3 && rm ' + filename + '.aiff'
p = subprocess.Popen(cmd, shell=True)
p.wait()
return b64_data
except:
print "Can't create sound for: " + words
return False
def create_binary_data(words, speed, voice, filename):
cmd = 'say ' + words + ' -r ' + speed + ' -v ' + voice + ' -o ' + filename + '.aiff && lame -m m ' + filename + '.aiff ' + filename + '.mp3'
print cmd
s = subprocess.Popen(cmd, shell=True)
s.wait()
def get_words(message=None):
output = ''
if message is not None and 'data' in message:
output = message['data']
else:
if len(session['words']) > 0:
output = random.choice(session['words'])
if not output and random.random() > 0.5:
cmd = 'ruby faker.rb'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
if not output:
print "creepy things..."
output = random.choice(CREEPY_THINGS_TO_SAY)
return output
def get_speed(message):
if 'speed' in session and isinstance(session['speed'],int):
return session['speed']
elif 'speed' in message and isinstance(message['speed'],int):
return int(message['speed']*2.5)
else:
return DEFAULT_SPEED
def get_voice(message):
if 'voice' in message:
return message['voice']
elif 'voices' in session and len(session['voices']) > 0:
return random.choice(session['voices'])
else:
return random.choice(VOICE_OPTIONS)
if __name__ == '__main__':
socketio.run(app)