forked from alexa-pi/AlexaPiDEPRECATED
-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.py
executable file
·717 lines (594 loc) · 20.2 KB
/
main.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
#! /usr/bin/env python
import os
import random
import time
import RPi.GPIO as GPIO
import alsaaudio
import wave
import random
import requests
import json
import re
import vlc
import threading
import cgi
import email
import pyaudio
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#Settings
button = 18 # GPIO Pin with button connected
plb_light = 24 # GPIO Pin for the playback/activity light
rec_light = 25 # GPIO Pin for the recording light
lights = [plb_light, rec_light] # GPIO Pins with LED's connected
device = "plughw:1" # Name of your microphone/sound card in arecord -L
#Debug
debug = 1
i = vlc.Instance('--aout=alsa')
currentState = 0
def start():
global abcdefgh
abcdefgh = vlcplayer(i)
# while True:
GPIO.add_event_detect(button, GPIO.FALLING, callback=detect_button, bouncetime=100)
print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC))
# GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed
playa = vlcplayer(i)
print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC))
# start = time.time()
recordAudio()
# file_path = recordwrite()
file_path = tmpfolder() +'recording.wav'
r = alexa_speech_recognizer(file_path, gettoken())
process_response(r, playa)
return playa
TOP_DIR = os.path.dirname(os.path.abspath(__file__))
DETECT_DING = os.path.join(TOP_DIR, "resources/ding.wav")
def detect_button(channel):
global button_pressed
if debug: print("{}Button Pressed! Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC))
time.sleep(.05) # time for the button input to settle down
while (GPIO.input(button)==0):
button_pressed = True
abcdefgh.stop()
# if debug: print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC))
# button_pressed = False
def killswitch(playa):
abcdefgh.stop()
playa.stop()
def recordAudio():
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 500
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "recording.wav"
audio = pyaudio.PyAudio()
play_audio_file(DETECT_DING)
# start Recording
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print "recording..."
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print "finished recording"
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
def play_audio_file(fname=DETECT_DING):
"""Simple callback function to play a wave file. By default it plays
a Ding sound.
:param str fname: wave file name
:return: None
"""
ding_wav = wave.open(fname, 'rb')
ding_data = ding_wav.readframes(ding_wav.getnframes())
audio = pyaudio.PyAudio()
stream_out = audio.open(
format=audio.get_format_from_width(ding_wav.getsampwidth()),
channels=ding_wav.getnchannels(),
rate=ding_wav.getframerate(), input=False, output=True)
stream_out.start_stream()
stream_out.write(ding_data)
time.sleep(0.2)
stream_out.stop_stream()
stream_out.close()
audio.terminate()
def vlcplayer(i):
p = i.media_player_new()
p.audio_set_volume(100)
return p
def nextItemX(navtoke, playa):
print "------- . ..... .> perhaps i need to wait here - and not get so excited"
r = alexa_getnextitem(navtoke)
process_response(r, playa)
def state_callback(event, player):
global currentState
global abcdefgh
state = player.get_state()
currentState = state
print ">>--->> CALLBACK <<---<<"
print state
if (state == 6) or (state == 7):
if len(songs) == 0:
if continueitems is not None:
if len(continueitems) > 0:
nextItemX(continueitems[0], player)
if len(songs) > 0:
playNext()
# if (state == 7) and (player.is_playing == 0):
# ifweerroroutreload()
currentState = player.get_state()
if currentState != 6:
abcdefgh = player
print "set player"
def playNext():
global songs, playa
player = vlcplayer(i)
playa = player
pthread = threading.Thread(target=playa_play, args=(playa, songs[0]))
songs.pop(0)
pthread.start()
def ifweerroroutreload():
#do a reload or resend of the last command if we crash?
playa = vlcplayer(i)
file_path = datum.tmpfolder() +'recording.wav'
r = alexa_speech_recognizer(file_path, gettoken())
process_response(r, playa)
# ---------------------------------------- ----------------------------------------
# ---------------------------------------- processing code----------------------------------------
# ---------------------------------------- ----------------------------------------
def process_response(r, playa):
global i, songs, continueitems
continueitems = []
print "begin finding content"
content = showjsoncontent(json.dumps(json_response(r)))
acontent = defineAudioContent(json.dumps(json_response(r)))
print "add any downloadable content"
songs = playfirstcontent(audioDownloadsList(r), playa)
print 'add any streams'
songs = playsecondcontent(content, playa, songs)
print 'add anything else'
songs = playaudioitems(acontent, playa, songs)
print "set next round"
continueitems = shouldwecontinueon(content, acontent, playa)
print continueitems
print len(continueitems)
print "------>>>> song list"
print len(songs)
if len(songs) > 0:
print "------>>>> song list"
print len(songs)
print songs[0]
pthread = threading.Thread(target=playa_play, args=(playa, ""))
pthread.start()
# songs.pop(0)
print "----------------------- >>>>>>>> end"
def playfirstcontent(playlist, playa):
print ">>----------------------------------> FIRST CONTENT"
threadlist = []
for song in playlist:
print ">>----------------------------------> SPEAK"
threadlist.append(song)
return threadlist
def playsecondcontent(audio, playa, tlist):
print ">>----------------------------------> SECOND CONTENT"
for item in audio:
if item.name == "play":
print ">>----------------------------->>>> PLAY"
for link in item.streamurls:
dbrief = item.navtoken[0].find('DailyBriefing')
if (link.find('opml.radiotime.com') != -1) and dbrief != -1: # and (link.find('cid') == -1):
content = findUsableStream(link)
tlist.append(content)
elif (link.find('opml.radiotime.com') != -1) and dbrief == -1:
content = findUsableStream(link)
tlist.append(content)
elif link.find("cid") == -1:
tlist.append(link)
return tlist
def playaudioitems(audio, playa, songlist):
print ">>-------------------------->>> Audio Items"
for item in audio:
print item.name # item name checked here
if item.name == "audioContent":
for link in item.streamurls:
if (link.find('opml.radiotime.com') != -1): # and (link.find('cid') == -1):
content = findUsableStream(link)
print content
songlist.append(content)
# elif link.find("cid") == -1:
else:
print "else"
songlist.append(link)
print link
print songlist
return songlist
def shouldwecontinueon(content, acontent, playa):
print "------------------------>>> should we continue?"
continueitem = []
for item in content:
if len(item.navtoken) != 0:
continueitem.append(item.navtoken[0])
for item in acontent:
if len(item.navtoken) != 0:
continueitem.append(item.navtoken[0])
print len(continueitem)
return continueitem
def playa_play(playa, content):
global i
m = i.media_new(content)
playa.set_media(m)
#------> call back code? will it work
mm = m.event_manager()
mm.event_attach(vlc.EventType.MediaStateChanged, state_callback, playa)
playa.play()
# ---------------------------------------- ----------------------------------------
# ---------------------------------------- setup code ----------------------------------------
# ---------------------------------------- ----------------------------------------
def setupGPIO():
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(lights, GPIO.OUT)
GPIO.output(lights, GPIO.LOW)
def runGPIO(lght, low, high, sleeptime):
for x in range(low, high):
time.sleep(sleeptime)
GPIO.output(lght, GPIO.HIGH)
time.sleep(sleeptime)
GPIO.output(lght, GPIO.LOW)
def setup():
setupGPIO()
while internet_on() == False:
print(".")
token = gettoken()
if token == False:
while True:
runGPIO(rec_light, 0, 5, .1)
runGPIO(plb_light, 0, 5, .1)
# ---------------------------------------- ----------------------------------------
# ---------------------------------------- decoding code ----------------------------------------
# ---------------------------------------- ----------------------------------------
def json_response(r):
if r.status_code == 200:
payloads = createPayloads(r)
for payload in payloads:
if payload.get_content_type() == "application/json":
j = returnedJson(payload)
print "j"
return j
def returnedJson(payload):
if payload.get_content_type() == "application/json":
j = json.loads(payload.get_payload())
if debug: print("{}JSON String Returned:{} {}".format(bcolors.OKBLUE, bcolors.ENDC, json.dumps(j)))
return j
def createPayloads(r):
data = "Content-Type: " + r.headers['content-type'] +'\r\n\r\n'+ r.content
msg = email.message_from_string(data)
return msg.get_payload()
##from stackoverflow
def find_values(id, json_repr):
results = []
def _decode_dict(a_dict):
try: results.append(a_dict[id])
except KeyError: pass
return a_dict
json.loads(json_repr, object_hook=_decode_dict) # return value ignored
return results
def findUsableStream(stream):
x = requests.get(stream).content.strip().split('\n')[0]
if (x[-4:] == '.mp3') or (x[-4:] == '.acc') or (x[-4:] == '.wav') or (x[-4:] == '8008') or (x[-4:] == '9008'):return x
elif (x[-4:] == '.pls'):
return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', requests.get(x).content)[0]
else:return x[:-4]
def showjsoncontent(test):
objectsX = []
boox = test.split('{"namespace"')
boox.pop(0)
newlist = []
for item in boox:
newlist.append('{"namespace"'+item)
# print item
print " "
for item in newlist:
ab = item.rsplit(',',1)[0]
print ""
if ab[-2:] == "]}":
sob = returnSOB(ab[:-2])
else:
sob = returnSOB(ab)
print ""
objectsX.append(sob)
return objectsX
def defineAudioContent(test):
objectsX = []
if test.find("directives"):
print " ------->>>>> audio item"
boox = test.split('{"audioItem"')
boox.pop(0)
newlist = []
for item in boox:
newlist.append('{"audioItem"'+item)
print " "
for item in newlist:
ab = item.rsplit(',',1)[0]
print ""
if ab[-2:] == "]}":
sob = returnSOBAudio(ab[:-2])
else:
sob = returnSOBAudio(ab)
print ""
objectsX.append(sob)
return objectsX
def returnSOB(ab):
return makeStreamObject(find_values('name', ab)[0],
find_values('namespace', ab)[0],
find_values('navigationToken', ab),
find_values('contentIdentifier', ab),
find_values('audioContent', ab),
find_values('playBehavior', ab),
find_values('streamId', ab),
find_values('streamUrl', ab))
def returnSOBAudio(ab):
return makeStreamObject("audioContent",
find_values('namespace', ab),
find_values('navigationToken', ab),
find_values('contentIdentifier', ab),
find_values('audioContent', ab),
find_values('playBehavior', ab),
find_values('streamId', ab),
find_values('streamUrl', ab))
def makeStreamObject(name, namespace, navtoken, contentid, audiocontent, playbehavior, streamids, streamurls):
sobj = streamObject()
sobj.name = name
sobj.namespace = namespace
sobj.navtoken = navtoken
sobj.contentid = contentid
sobj.audiocontent = audiocontent
sobj.playbehavior = playbehavior
sobj.streamids = streamids
sobj.streamurls = streamurls
return sobj
class streamObject(object):
name = ""
namespace = ""
navtoken = ""
contentid = ""
audiocontent = ""
playbehavior = ""
streamids = ""
streamurls = ""
class jsonobject(object):
type = ""
sobject = ""
# ---------------------------------------- ----------------------------------------
# ---------------------------------------- data code ----------------------------------------
# ---------------------------------------- ----------------------------------------
import RPi.GPIO as GPIO
import alsaaudio
import os
import email
button = 18 # GPIO Pin with button connected
plb_light = 24 # GPIO Pin for the playback/activity light
rec_light = 25 # GPIO Pin for the recording light
lights = [plb_light, rec_light] # GPIO Pins with LED's connected
device = "plughw:1" # Name of your microphone/sound card in arecord -L
#Debug
debug = 1
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def recordwrite():
GPIO.output(rec_light, GPIO.HIGH)
inp = generateINP()
audio = ""
time.clock()
elapsed = 0
while elapsed < seconds:
file_path = recordwrite()
elapsed = time.time() - start
print "loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed)
# while(GPIO.input(button)==0): # we keep recording while the button is pressed
l, data = inp.read()
if l:
audio += data
time.sleep(1)
print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC))
file_path = tmpfolder() +'recording.wav'
rf = open(file_path, 'w')
rf.write(audio)
rf.close()
inp = None
return file_path
def generateINP():
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device)
inp.setchannels(1)
inp.setrate(16000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(500)
return inp
def tmpfolder():
return os.path.realpath(__file__).rstrip(os.path.basename(__file__))
def audioDownloadsList(r):
audioList = []
if r.status_code == 200:
payloads = createPayloads(r)
num = 0
for payload in payloads:
if payload.get_content_type() == "audio/mpeg":
print num
num += 1
filename = tmpfolder() + "tmpcontent/"+"response"+str(num)+".mp3"
with open(filename, 'wb') as f:
f.write(payload.get_payload())
audioList.append(filename)
return audioList
def createPayloads(r):
data = "Content-Type: " + r.headers['content-type'] +'\r\n\r\n'+ r.content
msg = email.message_from_string(data)
return msg.get_payload()
# -------------------------------- ----------------------------
# -------------------------------- sending code----------------------------
# -------------------------------- ----------------------------
import requests
from memcache import Client
from creds import *
import json
import time
servers = ["127.0.0.1:11211"]
mc = Client(servers, debug=1)
# button = 18 # GPIO Pin with button connected
# plb_light = 24 # GPIO Pin for the playback/activity light
# rec_light = 25 # GPIO Pin for the recording light
# lights = [plb_light, rec_light] # GPIO Pins with LED's connected
# device = "plughw:1" # Name of your microphone/sound card in arecord -L
# #Debug
# debug = 1
def alexa_speech_recognizer(file_path, token):
if debug: print("{}Sending Speech Request...{}".format(bcolors.OKBLUE, bcolors.ENDC))
GPIO.output(plb_light, GPIO.HIGH)
url = 'https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize'
headers = {'Authorization' : 'Bearer %s' % gettoken()}
d = {
"messageHeader": {
"deviceContext": [
{
"name": "playbackState",
"namespace": "AudioPlayer",
"payload": {
"streamId": "",
"offsetInMilliseconds": "0",
"playerActivity": "IDLE"
}
}
]
},
"messageBody": {
"profile": "alexa-close-talk",
"locale": "en-us",
"format": "audio/L16; rate=16000; channels=1"
}
}
with open(file_path) as inf:
files = [
('file', ('request', json.dumps(d), 'application/json; charset=UTF-8')),
('file', ('audio', inf, 'audio/L16; rate=16000; channels=1'))
]
print " >>>---->>"
r = requests.post(url, headers=headers, files=files)
return r
def internet_on():
print("Checking Internet Connection...")
try:
r =requests.get('https://api.amazon.com/auth/o2/token')
print("Connection {}OK{}".format(bcolors.OKGREEN, bcolors.ENDC))
return True
except:
print("Connection {}Failed{}".format(bcolors.WARNING, bcolors.ENDC))
return False
def gettoken():
token = mc.get("access_token")
refresh = refresh_token
if token:
return token
elif refresh:
payload = {"client_id" : Client_ID, "client_secret" : Client_Secret, "refresh_token" : refresh, "grant_type" : "refresh_token", }
url = "https://api.amazon.com/auth/o2/token"
r = requests.post(url, data = payload)
resp = json.loads(r.text)
mc.set("access_token", resp['access_token'], 3570)
return resp['access_token']
else:
return False
def alexa_getnextitem(nav_token):
# https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/rest/audioplayer-getnextitem-request
time.sleep(0.5)
# if audioplaying == False:
if debug: print("{}Sending GetNextItem Request...{}".format(bcolors.OKBLUE, bcolors.ENDC))
GPIO.output(plb_light, GPIO.HIGH)
url = 'https://access-alexa-na.amazon.com/v1/avs/audioplayer/getNextItem'
headers = {'Authorization' : 'Bearer %s' % gettoken(), 'content-type' : 'application/json; charset=UTF-8'}
d = {
"messageHeader": {},
"messageBody": {
"navigationToken": nav_token
}
}
r = requests.post(url, headers=headers, data=json.dumps(d))
return r
def alexa_playback_progress_report_request(requestType, playerActivity, streamid):
# https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/rest/audioplayer-events-requests
# streamId Specifies the identifier for the current stream.
# offsetInMilliseconds Specifies the current position in the track, in milliseconds.
# playerActivity IDLE, PAUSED, or PLAYING
if debug: print("{}Sending Playback Progress Report Request...{}".format(bcolors.OKBLUE, bcolors.ENDC))
headers = {'Authorization' : 'Bearer %s' % gettoken()}
d = {
"messageHeader": {},
"messageBody": {
"playbackState": {
"streamId": streamid,
"offsetInMilliseconds": 0,
"playerActivity": playerActivity.upper()
}
}
}
url = urlofRequestType(requestType)
r = requests.post(url, headers=headers, data=json.dumps(d))
if r.status_code != 204:
print("{}(alexa_playback_progress_report_request Response){} {}".format(bcolors.WARNING, bcolors.ENDC, r))
else:
if debug: print("{}Playback Progress Report was {}Successful!{}".format(bcolors.OKBLUE, bcolors.OKGREEN, bcolors.ENDC))
def urlofRequestType(requestType):
if requestType.upper() == "ERROR":
# The Playback Error method sends a notification to AVS that the audio player has experienced an issue during playback.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackError"
elif requestType.upper() == "FINISHED":
# The Playback Finished method sends a notification to AVS that the audio player has completed playback.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackFinished"
elif requestType.upper() == "IDLE":
# The Playback Idle method sends a notification to AVS that the audio player has reached the end of the playlist.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackIdle"
elif requestType.upper() == "INTERRUPTED":
# The Playback Interrupted method sends a notification to AVS that the audio player has been interrupted.
# Note: The audio player may have been interrupted by a previous stop Directive.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackInterrupted"
elif requestType.upper() == "PROGRESS_REPORT":
# The Playback Progress Report method sends a notification to AVS with the current state of the audio player.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackProgressReport"
elif requestType.upper() == "STARTED":
# The Playback Started method sends a notification to AVS that the audio player has started playing.
url = "https://access-alexa-na.amazon.com/v1/avs/audioplayer/playbackStarted"
else:
url = ""
return url
# -------------------------------- ----------------------------
# -------------------------------- starting code----------------------------
# -------------------------------- ----------------------------