-
Notifications
You must be signed in to change notification settings - Fork 0
/
SiriProtocolHandler.py
404 lines (371 loc) · 22.7 KB
/
SiriProtocolHandler.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/python
# -*- coding: utf-8 -*-
from OpenSSL import crypto
from SiriCore import Siri
import db
from db import Assistant
from httpClient import AsyncOpenHttp
from siriObjects.baseObjects import ObjectIsCommand, RequestCompleted
from siriObjects.speechObjects import Phrase, Recognition, SpeechRecognized, \
Token, Interpretation, StartSpeech, SpeechFailure, StartSpeechRequest, \
StartSpeechDictation, FinishSpeech, SpeechPacket
from siriObjects.systemObjects import StartRequest, SendCommands, CancelRequest, \
CancelSucceeded, GetSessionCertificate, GetSessionCertificateResponse, \
CreateSessionInfoRequest, CommandFailed
from siriObjects.uiObjects import AddViews, AssistantUtteranceView, Button
import PluginManager
import flac
import json
import pprint
import speex
if db.db_type == "mysql":
import MySQLdb.cursors
else:
import sqlite3
import time
import uuid
import twisted
import urllib2
from xml.dom.minidom import parseString
class SiriProtocolHandler(Siri):
__not_recognized = {"de-DE": u"Entschuldigung, ich verstehe \"{0}\" nicht.", "en-US": u"Sorry I don't understand {0}", "fr-FR": u"Désolé je ne comprends pas ce que \"{0}\" veut dire."}
__websearch = {"de-DE": u"Websuche", "en-US": u"Websearch", "fr-FR": u"Rechercher sur le Web"}
__scheduling_interval_timeout__ = 20
__timeout_delay = 10
def __init__(self, server, peer):
Siri.__init__(self, server, peer)
self.lastPing = 0
self.pong = 0
self.plugin_lastAceId = ""
self.current_running_plugin = None
self.dbConnection = server.dbConnection
self.assistant = None
self.speech = dict()
self.httpClient = AsyncOpenHttp(self.handle_google_data)
self.current_google_request = None
self.current_location = None
self.lastPingTime = time.time()
self.timeoutschedule = twisted.internet.reactor.callLater(SiriProtocolHandler.__scheduling_interval_timeout__, self.checkTimeout)
def seconds_since_last_ping(self):
return time.time() - self.lastPingTime
def connectionLost(self, reason):
try:
self.timeoutschedule.cancel()
except:
pass
self.current_running_plugin = None
self.dbConnection = None
self.speech = None
self.httpClient = None
Siri.connectionLost(self, reason)
def checkTimeout(self):
if self.seconds_since_last_ping() > SiriProtocolHandler.__timeout_delay:
self.logger.info("Connection timed out")
self.transport.loseConnection()
else:
self.timeoutschedule = twisted.internet.reactor.callLater(SiriProtocolHandler.__scheduling_interval_timeout__, self.checkTimeout)
def handle_google_data(self, body, requestId, dictation):
self.current_google_request = None
if (body != None):
googleAnswer = json.loads(body)
self.process_recognized_speech(googleAnswer, requestId, dictation)
else:
self.send_object(SpeechFailure(requestId, "No connection to Google possible"))
self.send_object(RequestCompleted(requestId))
def received_ping(self, numOfPing):
self.pong += 1
self.lastPing = numOfPing
self.lastPingTime = time.time()
self.send_pong(self.pong)
def process_recognized_speech(self, googleJson, requestId, dictation):
possible_matches = googleJson['hypotheses']
if len(possible_matches) > 0:
best_match = possible_matches[0]['utterance']
if len(best_match) == 1:
best_match = best_match.upper()
else:
best_match = best_match[0].upper() + best_match[1:]
best_match_confidence = possible_matches[0]['confidence']
self.logger.info(u"Best matching result: \"{0}\" with a confidence of {1}%".format(best_match, round(float(best_match_confidence) * 100, 2)))
# construct a SpeechRecognized
token = Token(best_match, 0, 0, 1000.0, True, True)
interpretation = Interpretation([token])
phrase = Phrase(lowConfidence=False, interpretations=[interpretation])
recognition = Recognition([phrase])
recognized = SpeechRecognized(requestId, recognition)
if not dictation:
if self.current_running_plugin == None:
plugin = PluginManager.getPluginForImmediateExecution(self.assistant.assistantId, best_match, self.assistant.language, (self.send_object, self.send_plist, self.assistant, self.current_location))
if plugin != None:
plugin.refId = requestId
plugin.connection = self
self.current_running_plugin = plugin
self.send_object(recognized)
self.current_running_plugin.start()
else:
self.send_object(recognized)
view = AddViews(requestId)
errorText = best_match
errorText = errorText.replace(' ', '%20')
errorText = errorText.replace('?', '%3F')
errorText = errorText.replace('$', '%24')
errorText = errorText.replace('+', '%2B')
errorText = errorText.replace(',', '%2C')
errorText = errorText.replace('/', '%2F')
errorText = errorText.replace(':', '%3A')
errorText = errorText.replace(';', '%3B')
errorText = errorText.replace('=', '%3D')
errorText = errorText.replace('@', '%40')
#implement language switch
file = urllib2.urlopen('http://www.pandorabots.com/pandora/talk-xml?botid=a9481f8c7e347656&input=%s' % (errorText))
data = file.read()
file.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('that')[0].toxml()
xmlData=xmlTag.replace('<that>','').replace('</that>','')
#convert symbols
xmlData = xmlData.replace('"', '"')
xmlData = xmlData.replace('<', '<')
xmlData = xmlData.replace('>', '>')
xmlData = xmlData.replace('&', '&')
xmlData = xmlData.replace('<br>', ' ')
xmlData = xmlData.replace('Eve.', 'i4Siri.')
xmlData = xmlData.replace('Eve?', 'i4Siri?')
xmlData = xmlData.replace('Eve!', 'i4Siri!')
xmlData = xmlData.replace('Eve,', 'i4Siri,')
errorText = xmlData
view.views += [AssistantUtteranceView(errorText, errorText)]
self.send_object(view)
self.send_object(RequestCompleted(requestId))
elif self.current_running_plugin.waitForResponse != None:
# do we need to send a speech recognized here? i.d.k
self.current_running_plugin.response = best_match
self.current_running_plugin.refId = requestId
self.current_running_plugin.waitForResponse.set()
else:
self.send_object(recognized)
self.send_object(RequestCompleted(requestId))
else:
self.send_object(recognized)
self.send_object(RequestCompleted(requestId))
def received_plist(self, plist):
self.logger.debug("Packet with class: {0}".format(plist['class']))
self.logger.debug("packet with content:\n{0}".format(pprint.pformat(plist, width=40)))
# first handle speech stuff
if 'refId' in plist:
# if the following holds, this packet is an answer to a request by a plugin
if plist['refId'] == self.plugin_lastAceId and self.current_running_plugin != None:
if self.current_running_plugin.waitForResponse != None:
# just forward the object to the
# don't change it's refId, further requests must reference last FinishSpeech
self.logger.debug("Forwarding object to plugin")
self.plugin_lastAceId = None
self.current_running_plugin.response = plist if plist['class'] != "StartRequest" else plist['properties']['utterance']
self.current_running_plugin.waitForResponse.set()
return
if ObjectIsCommand(plist, StartSpeechRequest) or ObjectIsCommand(plist, StartSpeechDictation):
self.logger.debug("New start of speech received")
startSpeech = None
if ObjectIsCommand(plist, StartSpeechDictation):
dictation = True
startSpeech = StartSpeechDictation(plist)
else:
dictation = False
startSpeech = StartSpeechRequest(plist)
decoder = speex.Decoder()
encoder = flac.Encoder()
speexUsed = False
if startSpeech.codec == StartSpeech.CodecSpeex_WB_Quality8Value:
decoder.initialize(mode=speex.SPEEX_MODEID_WB)
encoder.initialize(16000, 1, 16)
speexUsed = True
elif startSpeech.codec == StartSpeech.CodecSpeex_NB_Quality7Value:
decoder.initialize(mode=speex.SPEEX_MODEID_NB)
encoder.initialize(16000, 1, 16)
speexUsed = True
elif startSpeech.codec == StartSpeech.CodecPCM_Mono_16Bit_8000HzValue:
encoder.initialize(8000, 1, 16)
elif startSpeech.codec == StartSpeech.CodecPCM_Mono_16Bit_11025HzValue:
encoder.initialize(11025, 1, 16)
elif startSpeech.coded == StartSpeech.CodecPCM_Mono_16Bit_16000HzValue:
encoder.initialize(16000, 1, 16)
elif startSpeech.coded == StartSpeech.CodecPCM_Mono_16Bit_22050HzValue:
encoder.initialize(22050, 1, 16)
elif startSpeech.coded == StartSpeech.CodecPCM_Mono_16Bit_32000HzValue:
encoder.initialize(32000, 1, 16)
# we probably need resampling for sample rates other than 16kHz...
self.speech[startSpeech.aceId] = (decoder if speexUsed else None, encoder, dictation)
elif ObjectIsCommand(plist, SpeechPacket):
self.logger.debug("Decoding speech packet")
speechPacket = SpeechPacket(plist)
if speechPacket.refId in self.speech:
(decoder, encoder, dictation) = self.speech[speechPacket.refId]
if decoder:
pcm = decoder.decode(speechPacket.packets)
else:
pcm = SpeechPacket.data # <- probably data... if pcm
encoder.encode(pcm)
else:
self.logger.debug("Got a speech packet that did not match any current request")
elif plist['class'] == 'StartCorrectedSpeechRequest':
self.process_recognized_speech({u'hypotheses': [{'confidence': 1.0, 'utterance': plist['properties']['utterance']}]}, plist['aceId'], False)
elif ObjectIsCommand(plist, FinishSpeech):
self.logger.debug("End of speech received")
finishSpeech = FinishSpeech(plist)
if finishSpeech.refId in self.speech:
(decoder, encoder, dictation) = self.speech[finishSpeech.refId]
if decoder:
decoder.destroy()
encoder.finish()
flacBin = encoder.getBinary()
encoder.destroy()
del self.speech[finishSpeech.refId]
self.logger.info("Sending flac to google for recognition")
try:
self.current_google_request = self.httpClient.make_google_request(flacBin, finishSpeech.refId, dictation, language=self.assistant.language, allowCurses=True)
except (AttributeError, TypeError):
self.logger.warning("Unable to find language record for this assistant. Try turning Siri off and then back on.")
else:
self.logger.debug("Got a finish speech packet that did not match any current request")
elif ObjectIsCommand(plist, CancelRequest):
# this is probably called when we need to kill a plugin
# wait for thread to finish a send
self.logger.debug("Should cancel current request")
cancelRequest = CancelRequest(plist)
if cancelRequest.refId in self.speech:
del self.speech[cancelRequest.refId]
if self.current_google_request != None:
self.current_google_request.cancel()
#abort a running plugin
if self.current_running_plugin != None:
self.current_running_plugin._abortPluginRun()
if self.current_running_plugin.waitForResponse != None:
self.current_running_plugin.waitForResponse.set()
self.send_object(CancelSucceeded(cancelRequest.aceId))
elif ObjectIsCommand(plist, GetSessionCertificate):
getSessionCertificate = GetSessionCertificate(plist)
sessionCA_DER = crypto.dump_certificate(crypto.FILETYPE_ASN1, self.server.sessionCACert)
sessionCert_DER = crypto.dump_certificate(crypto.FILETYPE_ASN1, self.server.sessionCert)
response = GetSessionCertificateResponse(getSessionCertificate.aceId, sessionCA_DER, sessionCert_DER)
self.send_object(response)
elif ObjectIsCommand(plist, CreateSessionInfoRequest):
# how does a positive answer look like?
createSessionInfoRequest = CreateSessionInfoRequest(plist)
fail = CommandFailed(createSessionInfoRequest.aceId)
fail.reason = "Not authenticated"
fail.errorCode = 0
self.send_object(fail)
#self.send_plist({"class":"SessionValidationFailed", "properties":{"errorCode":"UnsupportedHardwareVersion"}, "aceId": str(uuid.uuid4()), "refId":plist['aceId'], "group":"com.apple.ace.system"})
elif plist['class'] == 'CreateAssistant':
#create a new assistant
helper = Assistant()
helper.assistantId=str.upper(str(uuid.uuid4()))
helper.speechId=str.upper(str(uuid.uuid4()))
c = self.dbConnection.cursor()
noError = True
try:
if db.db_type == "mysql":
print 'works'
c.execute("INSERT INTO `assistants` (assistantId,speechId,censorSpeech,timeZoneId,language,region,firstName,nickName,date_created) values (%s,%s,%s,%s,%s,%s,%s,%s,NOW())", (helper.assistantId, helper.speechId,"","","","","",""))
else:
c.execute("insert into assistants(assistantId, assistant) values (?,?)", (helper.assistantId, helper))
self.dbConnection.commit()
except MySQLdb.Error, e:
noError = False
self.logger.warning("Database error on creating assistant")
except sqlite3.Error, e:
noError = False
self.logger.warning("Database error on creating assistant")
c.close()
if noError:
self.assistant = helper
self.send_plist({"class": "AssistantCreated", "properties": {"speechId": helper.speechId, "assistantId": helper.assistantId}, "group":"com.apple.ace.system", "callbacks":[], "aceId": str(uuid.uuid4()), "refId": plist['aceId']})
else:
self.send_plist({"class":"CommandFailed", "properties": {"reason":"Database error", "errorCode":2, "callbacks":[]}, "aceId": str(uuid.uuid4()), "refId": plist['aceId'], "group":"com.apple.ace.system"})
elif plist['class'] == 'SetAssistantData':
# fill assistant
if self.assistant != None:
try:
c = self.dbConnection.cursor()
objProperties = plist['properties']
self.assistant.censorSpeech = objProperties['censorSpeech']
self.assistant.timeZoneId = objProperties['timeZoneId']
self.assistant.language = objProperties['language']
self.assistant.region = objProperties['region']
#Record the user firstName and nickName
try:
self.assistant.firstName = objProperties["meCards"][0]["properties"]["firstName"].encode("utf-8")
except KeyError:
self.assistant.firstName = u''
try:
self.assistant.nickName = objProperties["meCards"][0]["properties"]["nickName"].encode("utf-8")
except KeyError:
self.assistant.nickName = u''
#Done recording
if db.db_type == "mysql":
c.execute("UPDATE `assistants` set censorSpeech=%s,timeZoneId=%s,language=%s,region=%s,firstName=%s,nickName=%s where assistantId = %s", (self.assistant.censorSpeech,self.assistant.timeZoneId, self.assistant.language,self.assistant.region,self.assistant.firstName,self.assistant.nickName,self.assistant.assistantId))
else:
c.execute("update assistants set assistant = ? where assistantId = ?", (self.assistant, self.assistant.assistantId))
self.dbConnection.commit()
c.close()
except:
self.send_plist({"class":"CommandFailed", "properties": {"reason":"Database error", "errorCode":2, "callbacks":[]}, "aceId": str(uuid.uuid4()), "refId": plist['aceId'], "group":"com.apple.ace.system"})
self.logger.error("Database Error on setting assistant data")
else:
self.send_plist({"class":"CommandFailed", "properties": {"reason":"Assistant to set data not found", "errorCode":2, "callbacks":[]}, "aceId": str(uuid.uuid4()), "refId": plist['aceId'], "group":"com.apple.ace.system"})
self.logger.warning("Trying to set assistant data without having a valid assistant")
elif plist['class'] == 'LoadAssistant':
if db.db_type == "mysql":
c = self.dbConnection.cursor(MySQLdb.cursors.DictCursor)
c.execute("SELECT * FROM `assistants` WHERE assistantId = %s", (plist['properties']['assistantId']))
else:
c = self.dbConnection.cursor()
c.execute("select assistant from assistants where assistantId = ?", (plist['properties']['assistantId'],))
self.dbConnection.commit()
result = c.fetchone()
if result == None:
self.send_plist({"class": "AssistantNotFound", "aceId":str(uuid.uuid4()), "refId":plist['aceId'], "group":"com.apple.ace.system"})
self.logger.warning("Assistant not found in database!!")
else:
self.assistant = Assistant()
self.assistant.censorSpeech = result['censorSpeech']
self.assistant.timeZoneId = result['timeZoneId']
self.assistant.language = result['language']
self.assistant.region = result['region']
#Record the user firstName and nickName
try:
self.assistant.firstName = result["firstName"].encode("utf-8")
except KeyError:
self.assistant.firstName = u''
try:
self.assistant.nickName = result["nickName"].encode("utf-8")
except KeyError:
self.assistant.nickName = u''
if self.assistant.language == '' or self.assistant.language == None:
self.logger.error ("No language is set for this assistant")
if db.db_type == "mysql":
c.execute("DELETE from `assistants` where assistantId = %s", (plist['properties']['assistantId']))
else:
c.execute("delete from assistants where assistantId = ?", (plist['properties']['assistantId'],))
self.dbConnection.commit()
self.send_plist({"class":"CommandFailed", "properties": {"reason":"Database error Assistant not found or language settings ", "errorCode":2, "callbacks":[]}, "aceId": str(uuid.uuid4()), "refId": plist['aceId'], "group":"com.apple.ace.system"})
else:
self.send_plist({"class": "AssistantLoaded", "properties": {"version": "20111216-32234-branches/telluride?cnxn=293552c2-8e11-4920-9131-5f5651ce244e", "requestSync":False, "dataAnchor":"removed"}, "aceId":str(uuid.uuid4()), "refId":plist['aceId'], "group":"com.apple.ace.system"})
c.close()
elif plist['class'] == 'DestroyAssistant':
try:
c = self.dbConnection.cursor()
if db.db_type == "mysql":
c.execute("DELETE from `assistants` where assistantId = %s", (plist['properties']['assistantId']))
else:
c.execute("delete from assistants where assistantId = ?", (plist['properties']['assistantId'],))
self.dbConnection.commit()
c.close()
self.send_plist({"class": "AssistantDestroyed", "properties": {"assistantId": plist['properties']['assistantId']}, "aceId":str(uuid.uuid4()), "refId":plist['aceId'], "group":"com.apple.ace.system"})
except:
self.send_plist({"class": "AssistantNotFound", "aceId":str(uuid.uuid4()), "refId":plist['aceId'], "group":"com.apple.ace.system"})
self.logger.error("Database error on deleting assistant")
elif plist['class'] == 'StartRequest':
#this should also be handeled by special plugins, so lets call the plugin handling stuff
self.process_recognized_speech({'hypotheses': [{'utterance': plist['properties']['utterance'], 'confidence': 1.0}]}, plist['aceId'], False)
pass