forked from jim-schwoebel/nala
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nala.py
1849 lines (1590 loc) · 70.8 KB
/
nala.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
############################################################################
## NALA REPOSITORY ##
############################################################################
repository name: nala
repository version: 1.0
repository link: https://github.com/jim-schwoebel/nala
author: Jim Schwoebel
author contact: js@neurolex.co
description: Nala is an open source voice assistant.
license category: opensource
license: Apache 2.0 license
organization name: NeuroLex Laboratories, Inc.
location: Seattle, WA
website: https://neurolex.ai
release date: 2018-09-28
This code (nala) is hereby released under a Apache 2.0 license license.
For more information, check out the license terms below.
##############################################################################
## LICENSE TERMS ##
##############################################################################
Copyright 2018 NeuroLex Laboratories, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
##############################################################################
## SERVICE STATEMENT ##
##############################################################################
If you are using the code written for a larger project, we are
happy to consult with you and help you with deployment. Our team
has >10 world experts in kafka distributed architectures, microservices
built on top of Node.JS / Python / Docker, and applying machine learning to
model speech and text data.
We have helped a wide variety of enterprises - small businesses,
researchers, enterprises, and/or independent developers.
If you would like to work with us let us know @ js@neurolex.co.
##############################################################################
## RELEASE NOTES ##
##############################################################################
Nala is a verastile open-source voice assistant to improve the workflow of
your daily life. Nala uses actions which can be triggered by user voice queries.
All the user needs to do is say 'hey nala' and it will spark Nala to listen
and respond to requests.
Nala uses machine learning to parse through user intents. If a request is not
understood or is an anomaly, a web search is performed to give th user an answer.
FOR NEW USERS:
--> be sure to include google application credentials as a .json file
e.g. export GOOGLE_APPLICATION_CREDENTIALS='/Users/jimschwoebel/Desktop/appcreds/NLX-infrastructure-b9201d884ea5.json'
'''
##############################################################################
## IMPORT STATEMENT ##
##############################################################################
import smtplib, os, glob, time, getpass, socket, pyaudio, pygame, wave
import shutil, importlib, geocoder, librosa, json, re, platform, urllib, contextlib
import requests, random, webbrowser, pickle, pyperclip, sys, struct, collections
from pydub import AudioSegment
from datetime import datetime
from sys import byteorder
from array import array
from struct import pack
import soundfile as sf
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import urllib.request
import speech_recognition as sr_audio
import pyttsx3 as pyttsx
import soundfile as sf
from data.models import ps_transcribe as pst
##############################################################################
## HELPER FUNCTIONS ##
##############################################################################
def speaktext(hostdir,text):
# speak to user from a text sample (tts system)
curdir=os.getcwd()
os.chdir(hostdir+'/actions')
os.system("python3 speak.py '%s'"%(str(text)))
os.chdir(curdir)
def wakeup(wake_type):
if wake_type == 'porcupine':
os.system('python3 wake_porcupine.py')
elif wake_type == 'snowboy':
os.system('python3 wake_snow.py')
elif wake_type == 'sphinx':
os.system('python3 wake_pocket.py')
else:
# default to porcupine if don't know
os.system('python3 wake_porcupine.py')
def curloc():
# get current location, limit 1000 requests/day
r=requests.get('http://ipinfo.io')
location=r.json()
return location
def get_date():
return str(datetime.now())
def record_to_file(path,filename,recordtime):
# record 3 second voice file
CHUNK = 1024
FORMAT = pyaudio.paInt16 #paInt8
CHANNELS = 1
RATE = 16000 #sample rate
RECORD_SECONDS = recordtime
WAVE_OUTPUT_FILENAME = filename
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK) #buffer
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data) # 2 bytes(16 bits) per channel
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def transcribe_audio(filename,hostdir,transcript_type):
# transcribe the audio according to transcript type
# google or sphinx (custom model)
try:
if transcript_type == 'sphinx':
transcript=pst.transcribe(hostdir,filename)
print('pocket: '+transcript)
elif transcript_type == 'google':
try:
# try google if you can, otherwise use sphinx
r=sr_audio.Recognizer()
with sr_audio.AudioFile(filename) as source:
audio = r.record(source)
transcript=r.recognize_google_cloud(audio)
print('google: '+transcript)
except:
print('error using google transcription, need to put API key in environment vars')
print('defaulting to pocketsphinx...')
r=sr_audio.Recognizer()
with sr_audio.AudioFile(filename) as source:
audio = r.record(source)
transcript=r.recognize_sphinx(audio)
print('sphinx (failed google): '+transcript)
else:
# default to sphinx if not sphinx or google inputs
transcript=pst.transcribe(hostdir,filename)
print('pocket: '+transcript)
except:
transcript=''
return transcript
def playbackaudio(filename):
# takes in a question and a filename to open and plays back the audio
# file and prints on the screen the question for the user
pygame.mixer.init()
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
time.sleep(0.5)
return "playback completed"
def get_clipboard():
# gets the results from the current clipboard
text=pyperclip.paste()
return text
def get_seconds(transcript):
# assume minutes are coming in
# assume max of 10 mintues
minute=60
transcript=transcript.lower()
if transcript.find('one')>=0:
seconds=minute
elif transcript.find('two')>=0:
seconds=2*minute
elif transcript.find('three')>=0:
seconds=3*minute
elif transcript.find('four')>=0:
seconds=4*minute
elif transcript.find('five')>=0:
seconds=5*minute
elif transcript.find('six')>=0:
seconds=6*minute
elif transcript.find('seven')>=0:
seconds=7*minute
elif transcript.find('eight')>=0:
seconds=8*minute
elif transcript.find('nine')>=0:
seconds=9*minute
elif transcript.find('ten')>=0:
seconds=10*minute
else:
# get back numbers by removing characters if not typed out
chars=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z',' ','.',"'",'<','>','"',
'[',']','-','=','+','(',')','*','&','^','%','$','#','@','!','~',
'`']
mins=transcript
for i in range(len(chars)):
mins=mins.replace(chars[i],'')
try:
seconds=int(mins)*60
minutes=int(mins)
except:
print('error converting')
# default to 1 minute
seconds=60
minutes=1
print(minutes)
print(seconds)
return seconds, minutes
def capture_video(filename, timesplit):
video=cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_width = int(video.get(3))
frame_height = int(video.get(4))
out = cv2.VideoWriter(filename,cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
a=0
start=time.time()
while True:
a=a+1
check, frame=video.read()
#print(check)
#print(frame)
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
out.write(frame)
#cv2.imshow("frame",gray)
end=time.time()
if end-start>timesplit:
break
#print(end-start)
print(a)
video.release()
out.release()
cv2.destroyAllWindows()
return filename
def cut_faces(modeldir,filename):
# import data later
hostdir=os.getcwd()
capture_video(filename, 10)
face_cascade = cv2.CascadeClassifier(modeldir+'/data/models/haarcascade_frontalface_default.xml')
foldername=filename[0:-4]+'_faces'
try:
os.mkdir(foldername)
except:
shutil.rmtree(foldername)
os.mkdir(foldername)
shutil.move(hostdir+'/'+filename, hostdir+'/'+foldername+'/'+filename)
os.chdir(foldername)
videodata=skvideo.io.vread(filename)
frames, rows, cols, channels = videodata.shape
metadata=skvideo.io.ffprobe(filename)
frame=videodata[0]
r,c,ch=frame.shape
for i in range(0,len(videodata),25):
#row, col, channels
skvideo.io.vwrite("output"+str(i)+".png", videodata[i])
listdir=os.listdir()
facenums=0
for i in range(len(listdir)):
if listdir[i][-4:]=='.png':
try:
image_file = listdir[i]
img = cv2.imread(hostdir+'/'+foldername+'/'+image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
increment=0
print(len(faces))
if len(faces) == 0:
pass
else:
for (x,y,w,h) in faces:
os.chdir(hostdir+'/'+foldername)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
newimg=img[y:y+h,x:x+w]
new_image_file=image_file[0:-4] + '_face_' + str(increment) + '.png'
cv2.imwrite(new_image_file, newimg)
facenums=facenums+1
except:
print('error')
os.chdir(hostdir+'/'+foldername)
listdir=os.listdir()
print(listdir)
for i in range(len(listdir)):
if listdir[i][-4:]=='.png':
if listdir[i].find('face') < 0:
os.remove(listdir[i])
return facenums
def save_query_json(wavfile, query, hostdir):
# save queries in .json format in the queries folder
curdir=os.getcwd()
os.chdir(hostdir)
jsonfilename=wavfile[0:-4]+'.json'
jsonfile=open(jsonfilename, 'w')
json.dump(query,jsonfile)
jsonfile.close()
shutil.move(hostdir+'/'+jsonfilename,hostdir+'/data/queries/'+jsonfilename)
os.chdir(curdir)
def register_user(action_list, hostdir):
# hostdir
os.chdir(hostdir)
hostdir=os.getcwd()
# assume default directory is hostdir
# if any folders exist delete them
try:
os.mkdir(hostdir+'/data/wakewords')
except:
shutil.rmtree(hostdir+'/data/wakewords')
os.mkdir(hostdir+'/data/wakewords')
try:
os.mkdir(hostdir+'/data/actions')
except:
shutil.rmtree(hostdir+'/data/actions')
os.mkdir(hostdir+'/data/actions')
try:
os.mkdir(hostdir+'/data/queries')
except:
shutil.rmtree(hostdir+'/data/queries')
os.mkdir(hostdir+'/data/queries')
try:
os.mkdir(hostdir+'/data/baseline')
except:
shutil.rmtree(hostdir+'/data/baseline')
os.mkdir(hostdir+'/data/baseline')
os.chdir(hostdir+'/data/baseline')
# get name from user profile name, if not record it
speaktext(hostdir, 'To begin, you must register with us. I have a few quick questions for you. Please type in the answers to the following questions.')
email=input('what is your email? \n')
name=input('what is your name (leave blank for %s)? \n'%(getpass.getuser()))
budget=input('what is the budget that you have to go out with friends? (e.g. 30) \n')
genre=input('what is your favorite music genre? (e.g. rock) \n')
# now get some wakewords to authenticate the user's identity
os.chdir(hostdir+'/data/wakewords')
speaktext(hostdir, 'Okay, can you say Hey Nala for me?')
playbackaudio(hostdir+'/data/tone.wav')
record_to_file(os.getcwd(),'hey_nala_1.wav', 3)
speaktext(hostdir, 'Can you say Hey Nala again?')
playbackaudio(hostdir+'/data/tone.wav')
record_to_file(os.getcwd(),'hey_nala_2.wav', 3)
speaktext(hostdir, 'One more time.')
playbackaudio(hostdir+'/data/tone.wav')
record_to_file(os.getcwd(),'hey_nala_3.wav', 3)
# go back to baseline directory to save databases
os.chdir(hostdir+'/data/baseline')
if name == '':
name=getpass.getuser()
speaktext(hostdir, 'Now give us a few seconds to make an account for you.')
facenums=cut_faces(hostdir, name+'.avi')
os.chdir(hostdir+'/data/baseline')
jsonfile=open('settings.json','w')
data = {
# alarm True = on, False = off at designated time
'alarm': False,
# the time the alarm would go off at (in 24 hour time, 8 = 8AM, 13 = 1 PM)
# if the alarm action is turned on.
'alarm time': 8,
# if True, then Nala will greet you every time you login and get the weather (default).
# If False, she will not do this.
'greeting': True,
# the last time that you updated the database (this is useful for understanding sessions).
'end': time.time(),
# options are ‘sphinx’, ‘google’ (recommended to use sphinx to not waste money )
# if using google, make sure you have the right environment variables (e.g.
# export GOOGLE_APPLICATION_CREDENTIALS='/Users/NLX-infrastructure-b9201d884ea5.json')
'transcript type': 'sphinx',
# Wakeword detector used to detect user queries.
# Default is ‘porcupine’ as it is the most accurate wakeword detector.
# options are 'sphinx', 'snowboy', 'porcupine' (default)
'wake type': 'porcupine',
#Time in seconds of each query when Nala is activated. The default query time is
# 2 seconds (from trial-and-error).
'query time':3,
# Multi-query capability allows you to separate queries with AND in the transcript,
# so it doesn’t stop after one query. Default is True.
'multi query':True,
# Ability to save queries once they have been propagated. Otherwise, they are deleted.
# This is useful if you want to cache query data or build a dataset. Default is True.
'query save':True,
# Store face when user registers to authenticate later with facial recognition. Default is True.
'register face': True,
# The time (in minutes) that Nala will sleep if you trigger the “Go to sleep” action query. Default is 30 minutes.
'sleep time': 30,
# save .json queries as well in the data/queries folder to match audio (e.g. sample.wav --> sample.json with query info)
# if True, does this. If not, does not save .json in the folder.
'query json': True,
# budget (user query above)
'budget': budget,
# genre (user query above)
'genre': genre,
}
jsonfile=open('settings.json','w')
json.dump(data,jsonfile)
jsonfile.close()
jsonfile=open('registration.json','w')
data = {
'name': name,
'email': email,
'userID': 0,
'hostdir': os.getcwd(),
'location': curloc(),
'rest time': 0.10,
'facenums': facenums,
'registration date': get_date(),
'tts': 'com.apple.speech.synthesis.voice.fiona',
}
json.dump(data,jsonfile)
jsonfile.close()
jsonfile=open('actions.json','w')
data = {
'logins': [], # login datetime
'logouts': [], # logout datetime (last time before login)
'active session': [],
'sessions': [],
'query count': 0,
'queries': [],
'noise': [],
'action count': 0,
'action log': [], #action, datetime, other stuff
'loopnum': 0,
'available actions': action_list,
}
json.dump(data, jsonfile)
jsonfile.close()
# store 2 copies in case of deletion
shutil.copy(os.getcwd()+'/registration.json', hostdir+'/registration.json')
shutil.copy(os.getcwd()+'/settings.json', hostdir+'/settings.json')
shutil.copy(os.getcwd()+'/actions.json', hostdir+'/actions.json')
speaktext(hostdir, 'Thank you, you are now registered.')
def update_database(hostdir,logins,logouts,session,sessions,query_count,queries,noise,action_count,loopnum, alarm, end):
curdir=os.getcwd()
os.chdir(hostdir)
# update only the fields that matter
data=json.load(open('actions.json'))
data['logins']=logins
data['logouts']=logouts
data['active session']=session
data['sessions']=sessions
data['query count']=query_count
data['queries']=queries
data['noise']=noise
data['action count']=action_count
data['loopnum']=loopnum
jsonfile=open('actions.json','w')
json.dump(data,jsonfile)
jsonfile.close()
data=json.load(open('settings.json'))
data['alarm']=alarm
data['end']=end
jsonfile=open('settings.json','w')
json.dump(data,jsonfile)
jsonfile.close()
# store backup copy just in case of either database being corrupted
os.chdir(hostdir+'/data/baseline')
os.remove('actions.json')
os.remove('settings.json')
shutil.copy(hostdir+'/actions.json',os.getcwd()+'/actions.json')
shutil.copy(hostdir+'/settings.json',os.getcwd()+'/settings.json')
os.chdir(curdir)
def wav_cleanup():
# remove .wav files in current directory to clean it up
# before next query
listdir=os.listdir()
for i in range(len(listdir)):
if listdir[i][-4:]=='.wav':
os.remove(listdir[i])
##############################################################################
## ACTIONS LOADED ##
##############################################################################
hostdir = os.getcwd()
os.chdir(hostdir+'/actions')
listdir=os.listdir()
action_list=list()
for i in range(len(listdir)):
if listdir[i][-3:]=='.py':
action_list.append(listdir[i])
os.chdir(hostdir)
##############################################################################
## LOAD DATABASE ##
##############################################################################
# try to load vars in baseline.json file or register a user
os.chdir(hostdir)
if 'actions.json' not in os.listdir():
# you only use these modules if you register, so put them here
import cv2
import skvideo.io, skvideo.motion, skvideo.measure
from moviepy.editor import VideoFileClip
from PIL import Image
register_user(action_list, hostdir)
try:
# load database
os.chdir(hostdir)
# registration.json data
try:
database=json.load(open('registration.json'))
except:
# restore database if corrupted
print('registration database corrupted, restoring...')
os.chdir(hostdir+'/data/baseline/')
database=json.load(open('registration.json'))
os.chdir(hostdir)
os.remove('registration.json')
shutil.copy(hostdir+'/data/baseline/registration.json',hostdir+'/registration.json')
name=database['name']
regdate=database['registration date']
rest_time=database['rest time']
# actions.json data
try:
database=json.load(open('actions.json'))
except:
# restore database if corrupted
print('actions database corrupted, restoring...')
os.chdir(hostdir+'/data/baseline/')
database=json.load(open('actions.json'))
os.chdir(hostdir)
os.remove('actions.json')
shutil.copy(hostdir+'/data/baseline/actions.json',hostdir+'/actions.json')
logins=database['logins']
logouts=database['logouts']
session=database['active session']
sessions=database['sessions']
query_count=database['query count']
queries=database['queries']
noise=database['noise']
action_count=database['action count']
action_log=database['action log']
loopnum=database['loopnum']
avail_actions = database['available actions']
#print(database)
# settings.json data
try:
database=json.load(open('settings.json'))
except:
# restore database if corrupted
print('settings database corrupted, restoring...')
os.chdir(hostdir+'/data/baseline/')
database=json.load(open('settings.json'))
os.chdir(hostdir)
os.remove('settings.json')
shutil.copy(hostdir+'/data/baseline/settings.json',hostdir+'/settings.json')
alarm=database['alarm']
alarm_time=database['alarm time']
greeting=database['greeting']
end=database['end']
transcript_type=database['transcript type']
wake_type=database['wake type']
query_time=database['query time']
multi_query=database['multi query']
query_save=database['query save']
register_face=database['register face']
sleep_time=database['sleep time']
query_json=database['query json']
# instantiate variables
logins.append(get_date())
t=1
query_request=False
turn_off = False
except:
# register user if no user exists
print('registering new user!')
# you only use these modules if you register, so put them here
import cv2
import skvideo.io, skvideo.motion, skvideo.measure
from moviepy.editor import VideoFileClip
from PIL import Image
register_user(action_list, hostdir)
# load database
os.chdir(hostdir)
# registration data
database=json.load(open('registration.json'))
name=database['name']
regdate=database['registration date']
rest_time=database['rest time']
# action data
database=json.load(open('actions.json'))
logins=database['logins']
logouts=database['logouts']
session=database['active session']
sessions=database['sessions']
query_count=database['query count']
queries=database['queries']
noise=database['noise']
action_count=database['action count']
action_log=database['action log']
loopnum=database['loopnum']
avail_actions = database['available actions']
# settings.json
database=json.load(open('settings.json'))
alarm=database['alarm']
alarm_time=database['alarm time']
greeting=database['greeting']
end=database['end']
transcript_type=database['transcript type']
wake_type=database['wake type']
query_time=database['query time']
multi_query=database['multi query']
query_save=database['query save']
register_face=database['register face']
sleep_time=database['sleep time']
query_json=database['query json']
# instantiate variables
logins.append(get_date())
t=1
query_request=False
turn_off = False
##############################################################################
## MAIN SCRIPT ##
##############################################################################
while turn_off == False:
# record a 3.0 second voice sample
# use try statement to avoid errors
try:
# welcome user back if it's been over an hour since login
start=time.time()
# set alarm and make false after you trigger alarm
if alarm == True and alarm_time == datetime.now().hour:
os.chdir(hostdir+'/actions')
os.system('python3 alarm.py %s'%(hostdir))
alarm == False
os.chdir(hostdir)
if abs(end-start) > 60*60:
end=time.time()
if greeting == True:
speaktext(hostdir,'welcome back, %s'%(name.split()[0]))
os.chdir(hostdir+'/actions')
os.system('python3 weather.py %s'%(hostdir))
os.system('python3 news.py %s'%(hostdir))
os.system('python3 events.py %s'%(hostdir))
os.chdir(hostdir)
# log session if the time of activity is greater than 60 minutes
sessions.append(session)
# start a new session
session=list()
# change to host directory
os.chdir(hostdir)
# wakeup according to wake_type then activate the query
os.chdir(hostdir+'/data/models/')
wakeup(wake_type)
query_num=0
query_request=False
while query_request==False and query_num <= 3:
os.chdir(hostdir)
if query_num==0:
# if the first query, ask how you can help
speaktext(hostdir,'how can I help you?')
playbackaudio(hostdir+'/data/tone.wav')
else:
# the prior sample was noise, so we must add it as such
message="Sorry, I didn't get that. How can I help?"
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript,
'transcript': transcript,
'response': [],
'meta': [message],
}
noise.append(query)
session.append(query)
# now ask user for another sample because previous sample was noise
speaktext(hostdir,"Sorry, I did not get that. How can I help?")
playbackaudio(hostdir+'/data/tone.wav')
# record audio and initiate query
time.sleep(0.50)
unique_sample='sample'+str(loopnum)+'_'+str(query_num)+'.wav'
record_to_file(os.getcwd(),unique_sample, query_time)
# transcribe audio according to transcript_type (in settings.json)
transcript=transcribe_audio(unique_sample, hostdir, transcript_type)
# only save the query if you'd like to with query_save variable (in settings.json)
if query_save == True:
shutil.move(hostdir+'/'+unique_sample,hostdir+'/data/queries/'+unique_sample)
else:
os.remove(unique_sample)
query_transcript=transcript.lower().split()
# enable multiple queries if it is activated
if multi_query == True:
and_num = query_transcript.count('and')
else:
and_num = 0
# break if it finds a query
for i in range(len(query_transcript)):
# iterate through transcript
os.chdir(hostdir+'/actions')
print(query_transcript[i])
if query_transcript[i] in ['weather', 'whether']:
command='python3 weather.py %s'%(hostdir)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
# save query to json
try:
if query_json == True:
save_query_json(unique_sample, query, hostdir)
except:
print('error')
query_count=query_count+1
queries.append(query)
session.append(query)
action_count=action_count+1
query_request=True
if and_num == 0:
break
else:
and_num=and_num-1
elif query_transcript[i] in ['event','social', 'friends', 'go out']:
# either get a meetup or pull from db
randint=random.randint(0,1)
if randint==0:
command='python3 events.py %s'%(hostdir)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
elif randint==1:
command='python3 social.py %s'%(hostdir)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
# save query to json
try:
if query_json == True:
save_query_json(unique_sample, query, hostdir)
except:
print('error')
query_count=query_count+1
queries.append(query)
session.append(query)
action_count=action_count+1
query_request=True
if and_num == 0:
break
else:
and_num=and_num-1
elif query_transcript[i] in ['coffee']:
command='python3 yelp.py %s coffee'%(hostdir)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
# save query to json
try:
if query_json == True:
save_query_json(unique_sample, query, hostdir)
except:
print('error')
query_count=query_count+1
queries.append(query)
session.append(query)
action_count=action_count+1
query_request=True
if and_num == 0:
break
else:
and_num=and_num-1
elif query_transcript[i] in ['news']:
command='python3 news.py %s'%(hostdir)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
# save query to json
try:
if query_json == True:
save_query_json(unique_sample, query, hostdir)
except:
print('error')
query_count=query_count+1
queries.append(query)
session.append(query)
action_count=action_count+1
query_request=True
if and_num == 0:
break
else:
and_num=and_num-1
elif query_transcript[i] in ['music']:
command="python3 music.py %s '%s'"%(hostdir, transcript)
os.system(command)
query={
'date':get_date(),
'audio': unique_sample,
'transcript type': transcript_type,
'query transcript': query_transcript[i],
'transcript': transcript,
'response': command,
'meta': list(),
}
# save query to json
try:
if query_json == True:
save_query_json(unique_sample, query, hostdir)
except:
print('error')
query_count=query_count+1