-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1326 lines (1109 loc) · 46.4 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
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
print("Pocket Assistant Starting....")
#Imports
import datetime
import speech_recognition as sr
#from TTS.api import TTS
from pydub import AudioSegment
from pydub.playback import play
import RPi.GPIO as GPIO
import os
import pytz
from base64 import b64encode, b64decode
import hashlib
from AesEverywhere import aes256
import random
#from pydub import AudioSegment
import random
import string
import time
#import pyaudio
import calendar
from playsound import playsound
import pygame
import firstaid
import textdistance
import sqlite3
import hashlib
from nltk.corpus import wordnet
import nltk
import time
from pygame import mixer
import threading
import glob
import sounddevice as sd
import soundfile as sf
global stopwatchtime
global musicDirectory
global musicIndex
global selected
global timerminutes
global metronomebpm
global metronomesound
global stop_event
global recording_minutes
selected = 0
global picked
picked = 0
global music_start_time
global time_date_time
time_date_time=time.time()
print("Imports complete")
current_pid = os.getpid()
with open('pid.txt', 'w') as file:
file.write(str(current_pid))
DB_PATH = "todos.db"
conn = sqlite3.connect(DB_PATH)
global todoCursor
global notesCursor
todoCursor, notesCursor=0, 0
#pygame.init()
pygame.mixer.init()
def hashString(string):
return (hashlib.sha256(string.encode()).hexdigest())
def speak(command):
command=str(command).lower()
print("saying:", command)
global old_command
old_command = command
filename = command.replace(" ", "")+".wav"
if filename in os.listdir("/home/pi/BackpackPhrases/"):
os.system("aplay -D hw:0 /home/pi/BackpackPhrases/"+filename)
else:
sound("interpretting")
print("mimic3 --voice 'en_US/hifi-tts_low' '"+command+"' > /home/pi/BackpackPhrases/"+filename)
os.system("mimic3 --voice 'en_US/hifi-tts_low' '"+command+"' > /home/pi/BackpackPhrases/"+filename)
os.system("aplay -D hw:0 /home/pi/BackpackPhrases/"+filename)
def sound(sound):
if (sound=="interpretting"):
os.system("aplay beep.wav")
elif sound=="volume":
print("Volume test")
elif sound=="timerfinished":
os.system("aplay -D hw:0 /home/pi/BackpackPhrases/timerfinished.wav")
def getVoice(starter=None):
with mic as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source, timeout=2)
sound("interpretting")
voice = r.recognize_whisper(audio, language="english")
print("Heard: ", voice)
return(voice)
return(input("Voice: "))
def none(t="t"):
pass
def error():
print("There's been an error in the program. This is likely a programming issue, not anything you can fix while in use.")
speak("There's been an error in the program. This is likely a programming issue, not anything you can fix while in use.")
def encrypt(plaintext, key):
return(aes256.encrypt(plaintext, key))
def decrypt(ciphertext, key):
return(aes256.decrypt(ciphertext, key))
def startAssistant(t="t"):
speak("What do you need?")
request = getVoice()
def spell(t="t"):
speak("What do you want to spell?")
word = getVoice()
for i in word:
speak(i)
def removeGPIO():
GPIO.remove_event_detect(21)
GPIO.remove_event_detect(11)
GPIO.remove_event_detect(12)
GPIO.remove_event_detect(13)
GPIO.remove_event_detect(15)
GPIO.remove_event_detect(16)
GPIO.remove_event_detect(18)
GPIO.remove_event_detect(19)
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.split():
if word not in numwords:
raise Exception("Illegal word: " + word)
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
def startStopwatch(t="t"):
global stopwatchtime
speak("Starting stopwatch")
speak("three, two, one, go")
stopwatchtime=time.time()
def readStopwatch(t="t"):
global stopwatchtime
remaining=time.time()-stopwatchtime
numminutes=remaining//60
minutes=str(remaining//60)
seconds=str(remaining%60)[:-13]
speak("Stopwatch at")
if (numminutes)<0.0000001:
speak(seconds+" seconds")
else:
speak(minutes+" minutes, "+seconds+" seconds")
def stopStopwatch(t="t"):
global stopwatchtime
remaining=time.time()-stopwatchtime
numminutes=remaining//60
minutes=str(remaining//60)
seconds=str(remaining%60)[:-13]
if (numminutes)<0.0000001:
speak("Stopwatch finished at "+seconds+" seconds")
else:
speak("Stopwatch finished at "+minutes+" minutes, "+seconds+" seconds")
def timerMinuteUp(t="t"):
global timerminutes
timerminutes+=1
speak(str(timerminutes))
def timerMinuteDown(t="t"):
global timerminutes
timerminutes-=1
speak(str(timerminutes))
def timerThread():
global timerminutes
time.sleep(timerminutes*60)
sound("timerfinished")
speak("Timer finished")
sound("timerfinished")
def startTimer(t="t"):
global timerminutes
speak("Starting timer")
thread = threading.Thread(target=timerThread)
thread.start()
startMainMenu()
def startTimerMenu(t="t"):
speak("Timer menu")
global timerminutes
timerminutes=0
speak("How many minutes do you want the timer to be?")
removeGPIO()
GPIO.add_event_detect(21,GPIO.RISING,callback=startTimer, bouncetime=500)
GPIO.add_event_detect(11,GPIO.RISING,callback=timerMinuteUp, bouncetime=500)
GPIO.add_event_detect(12,GPIO.RISING,callback=timerMinuteDown, bouncetime=500)
GPIO.add_event_detect(13,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(15,GPIO.RISING,callback=volumeUp, bouncetime=500)
GPIO.add_event_detect(16,GPIO.RISING,callback=volumeDown, bouncetime=500)
GPIO.add_event_detect(18,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(19,GPIO.RISING,callback=startMainMenu, bouncetime=500)
def takeNote(t="t"):
speak("Taking a note")
current_time = datetime.datetime.now(pytz.timezone('America/Chicago'))
speak("What's the title?")
title = getVoice()
speak("Do you want to write a body paragraph?")
contentBool = getButton("bool")
#Listen for button. Top button is yes, second button is no
if (contentBool==True):
speak("What do you want to write?")
content = getVoice()
speak("Accepted. Do you want to password-protect it?")
passwordBool = getButton("bool")
if passwordBool == False:
speak("No password saved.")
f = open("backpack/pi/data/notes/"+title+" - "+str(current_time)+".txt", "w")
print("saved to", "backpack/pi/data/notes/"+title+" - "+str(current_time)+".txt")
f.write(content)
f.close()
speak("Note written")
elif passwordBool == True:
speak("What do you want your password to be?")
password = getVoice()
content = encrypt(content, password)
f = open("backpack/pi/data/notes/"+title+" - "+str(current_time)+".txt", "w")
f.write(str(content))
f.close()
speak("Note written")
else:
f = open("backpack/pi/data/notes/"+title+" - "+str(current_time)+".txt", "w")
f.close()
speak("Note written")
def threadRecording(t="t"):
global recording_minutes
os.system("arecord --duration="+str(recording_minutes)+" /home/pi/recordings/"+str(time.time())+".wav")
def record(t="t"):
global recording_minutes
speak("Recording for")
speak(recording_minutes)
speak("minutes")
recordingThread = threading.Thread(target=threadRecording)
recordingThread.start()
startMainMenu()
def recordingMinutesUpOne(t="t"):
global recording_minutes
recording_minutes+=1
speak(recording_minutes)
def recordingMinutesUpFive(t="t"):
global recording_minutes
recording_minutes+=5
speak(recording_minutes)
def recordingMinutesDownOne(t="t"):
global recording_minutes
recording_minutes-=1
speak(recording_minutes)
def recordingMinutesDownFive(t="t"):
global recording_minutes
recording_minutes-=5
speak(recording_minutes)
def startRecordingMenu(t="t"):
speak("Recording Menu")
global recording_minutes
recording_minutes=0
removeGPIO()
GPIO.add_event_detect(21,GPIO.RISING,callback=recordingMinutesUpOne, bouncetime=500)
GPIO.add_event_detect(11,GPIO.RISING,callback=recordingMinutesUpFive, bouncetime=500)
GPIO.add_event_detect(12,GPIO.RISING,callback=recordingMinutesDownOne, bouncetime=500)
GPIO.add_event_detect(13,GPIO.RISING,callback=recordingMinutesDownFive, bouncetime=500)
GPIO.add_event_detect(15,GPIO.RISING,callback=record, bouncetime=500)
GPIO.add_event_detect(16,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(18,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(19,GPIO.RISING,callback=startMainMenu, bouncetime=500)
def play_audio(file_path):
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
def pause_audio():
pygame.mixer.music.pause()
def unpause_audio():
pygame.mixer.music.unpause()
def skip_audio():
pygame.mixer.music.stop()
def play_music():
global musicDirectory
global musicIndex
song="/home/pi/Music/"+musicDirectory[musicIndex]
pygame.mixer.music.load(song)
pygame.mixer.music.play()
def playpause(t="t"):
if pygame.mixer.music.get_busy():
pause_audio()
else:
unpause_audio()
def shuffleMusic(t="t"):
global musicDirectory
global musicIndex
speak("Shuffling music")
music_dir="/home/pi/Music"
music_list = os.listdir("/home/pi/Music")
for i in music_list: # Removes first four (additional) letters
os.system("mv '"+music_dir+"/"+i+"' '"+music_dir+"/"+i[-(len(i)-4):]+"'")
musicDirectory = os.listdir("/home/pi/Music")
for i in musicDirectory: # Adds three random letters and a dash
addLet = (random.choice(string.ascii_letters)+random.choice(string.ascii_letters)+random.choice(string.ascii_letters)+"-")
os.system("mv '"+music_dir+"/"+i+"' '"+music_dir+"/"+addLet+i+"'")
musicDirectory = os.listdir("/home/pi/Music")
def playMusic(t="t"):
global music_start_time
if pygame.mixer.music.get_busy() and time.time()-music_start_time>5:
stopMusic()
else:
global musicDirectory
global musicIndex
music_start_time=time.time()
musicIndex=0
speak("Playing music")
shuffleMusic()
musicDirectory = glob.glob('/home/pi/Music/*.mp3')
if not musicDirectory:
print("No audio files found in the specified directory.")
pygame.quit()
return
play_audio(musicDirectory[musicIndex])
def pauseMusic(t="t"):
pygame.mixer.music.pause()
speak("Music paused")
def stopMusic(t="t"):
global musicDirectory
global musicIndex
pygame.mixer.music.stop()
speak("Music stopped")
startMainMenu()
def skipMusic(t="t"):
global musicDirectory
global musicIndex
skip_audio()
musicIndex = (musicIndex + 1) % len(musicDirectory)
play_audio(musicDirectory[musicIndex])
def backwordsMusic(t="t"):
global musicDirectory
global musicIndex
musicIndex-=1
skip_audio()
play_audio(musicDirectory[musicIndex])
def connectBluetooth(t="t"):
os.system("./connect_bluetooth.sh")
def getDate(t="t"):
today = datetime.datetime.now()
days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eigth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eithteenth", "ninteenth", "twentieth", "twenty first", "twenty second", "twenty third", "twenty fourth", "twenty fifth", "twenty sixth", "twenty seventh", "twenty eigth", "twenty ninth", "thirtieth", "thirty first", "thirty second"]
months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
day = days[today.day-1]
month = months[today.month-1]
year = today.year
weekday = (today.strftime("%A"))
speak("It is "+weekday+", "+month+" "+day)
def getTime(t="t"):
global time_date_time
now = datetime.datetime.now()
if time.time() - time_date_time > 5:
speak(now.strftime("Its "+'%H:%M'))
else:
getDate()
time_date_time = time.time()
def repeatStatement():
speak(old_command)
def readEbook(t="t"):
speak("Have a library of ebooks for reading offline")
def CPRBeat():#Need a way to use button to stop met
while True:
pygame.mixer.music.play()
time.sleep(0.6)
def firstAid(t="t"):
startFirstAid(False)
startMainMenu()
def volumeUp(t="t"):
os.system("amixer -D pulse sset Master 5%+")
os.system("aplay volume.wav")
def volumeDown(t="t"):
os.system("amixer -D pulse sset Master 5%-")
os.system("aplay volume.wav")
def changeMetronome(t="t"):
global metronomesound
sounds=["met-woodblock", "met-clap", "met-beep", "met-bell"]
current=sounds.index(metronomesound)
if current==len(sounds)-1:
metronomesound="met-woodblock"
else:
metronomesound=sounds[current+1]
pygame.mixer.music.stop()
pygame.mixer.music.load("/home/pi/BackpackPhrases/"+metronomesound+".wav")
def bpmUpOne(t="t"):
global metronomebpm
metronomebpm+=1
speak(metronomebpm)
def bpmUpFive(t="t"):
global metronomebpm
metronomebpm+=5
speak(metronomebpm)
def bpmDownOne(t="t"):
global metronomebpm
metronomebpm-=1
speak(metronomebpm)
def bpmDownFive(t="t"):
global metronomebpm
metronomebpm-=5
speak(metronomebpm)
def metronome_threader():
while not stop_event.is_set():
pygame.mixer.music.play()
time.sleep(60 / metronomebpm)
def stopMetronome(t="t"):
stop_event.set()
startMainMenu()
def startMetronome():
global stop_event
global metronomebpm
global metronomesound
metronomesound="met-woodblock"
metronomebpm=60
speak("Starting metronome")
stop_event = threading.Event()
pygame.mixer.music.load("/home/pi/BackpackPhrases/met-woodblock.wav")
metronome_thread = threading.Thread(target=metronome_threader)
metronome_thread.start()
def say(thing):
speak(thing)
def audiobook(): #AudioBook directories (titles) have to be formated by hand to be a readable sentence
book="bill nye and boomerang" #Need a button interupt
f=open("audiobok.txt", "r")
database = f.readlines()
f.close()
for i in database:
if i==book:
chapter = database[i+1]
break
chapters = os.listdir("audiooks/"+book)
while chapter<len(chapters-1):
os.system("mpg123 "+chapters[chapter])
#This is if button interrupt above
speak("What chapter?")
chap = int(getVoice())
books = os.listdir("back/pi/date/audiooks")
if book in books:
speak("Book found.")
def quit(t="t"):
speak("Quitting")
quit()
def define():
say("What word do you want to define?")
word=getVoice()
syns = wordnet.synsets(word)
try:
print(syns[0].definition())
except IndexError:
say("There is no definition for that word")
except:
error()
def searchWikipedia(toSearch, t="t"):
toReturn="No article found"
distance=0
speak("Searching Wikipedia")
toSearch=toSearch.lower()
firstFour=toSearch[0:4]
f=open("wikipedia2/"+firstFour+".txt", "r")
lines=f.readlines()
print(len(lines))
for i in lines:
if i!="\n":
topic = i[0:i.index("<")]
if(textdistance.levenshtein.normalized_similarity(topic, toSearch))>distance:
distance=textdistance.levenshtein.normalized_similarity(topic, toSearch)
toReturn=i
print(toReturn)
f.close()
def navigate(t="t"):
say("Navigate using osmmaps and the gps")
def empty(t="t"):
pass
def pauseResumeStopwatch(t="t"):
say("Toggle puase of stopwatch")
def remoteUp(t="t"):
say("Up on remote")
def remoteRight(t="t"):
say("Right on remote")
def remoteDown(t="t"):
say("Down on remote")
def remoteLeft(t="t"):
say("Left on remote")
def remoteClick(t="t"):
say("Press circle on the remote")
def remotePausePlay(t="t"):
say("Toggle puase or play on the remote")
def remoteBack(t="t"):
say("Back button on the remote")
def none(t="t"):
pass
def markyes(t="t"):
print("Marked yes")
global yes_no
yes_no=True
def markno(t="t"):
speak("Marked no")
global yes_no
yes_no=False
def noo():
speak("Call nine one one.")
def shock():
speak("If you notice signs of shock,")
speak("Lay the victim down and elevate the legs slightly.")
speak("Keep the victim still and don't move them.")
speak("Begin see pee are if necessary.")
speak("loosen tight clothing and jewelry, and cover with a blanket to prevent chilling.")
speak("Don't let the victim eat or drink.")
speak("If the victim is vomitting or bleeding out of the mouth, and no spinal injury is suspected, turn the victim on their side to prevent choking.")
speak("Treat for injuries.")
speak("Calmly reassure the victim.")
def heartAttack():
speak("Heart attack first aid.")
noo()
speak("chew and swallow aspririn, if possible.")
speak("If the victim becomes unconcious or doesn't have a pulse, begin see pee are.")
def stroke():
speak("Stroke first aid.")
noo()
def cut():
speak("Severe bleeding first aid")
speak("If the wound is deep or you're not sure how serious it is, call nine one one")
speak("If there is a foreign object left deep in the wound, do not remove it, place bandages around it.")
speak("Remove clothing or debris from the wound, Look for the source of the bleeding. There might be more than one wound. Do not try to clean the wound")
speak("Cover the wound with sterile gauze or a clean cloth. Apply pressure. Do not apply pressure on a head wound if you suspect a skull fracture")
speak("Wrap the wound in a thick bandage and tape. Lift the wound above the heart if possible.")
speak("Have the victim lie down. If possibnle, cover the victim with a rug or blanket to prevent loss of body heat.")
shock()
speak("If the blood seeps through the applied bandages, apply more clean bandages and continue pressing on the injured area")
speak("Keep the person still, and continue to try to get emergency help from an emergency room or nine one one")
speak("After the victim is helped, wash your hands, even if it seems no blood got on you")
def majorBurn():
speak("Major burn first aid.")
speak("Protect the victim from further harm. Remove them from the source of the burn.")
speak("Make sure that the victim is breathing.")
speak("Remove jewelry, belts, and other tight items.")
speak("Cover the burn loosely with a cloth or gauze.")
speak("Raise the burned area if possible")
shock()
def minorBurn():
speak("Minor burn first aid")
speak("Run the burn under cold water for ten minutes.")
speak("Remove jewelry or other tight items from burn area.")
speak("Don't break blisters, as they help defend aginst infection. If one pops, gently clean out the area with water and apply antibiotic ointment")
speak("Apply lotion. This helps prevent drying and provides relief.")
speak("Bandage the burn loosely with a clean bandage.")
def whichBurn():
speak("Is it a major burn or minor burn")
m=getVoice()
return m
def burn():
speak("Burn first aid.")
while True:
m=whichBurn()
if "major" in m:
majorBurn()
break
elif "minor" in m:
minorBurn()
break
elif "explain" in m:
print("Diagnose burn?")
else:
speak("Did not understand, say major or minor burn, or say explain to know the difference")
def choking():
speak("Choking first aid.")
speak("For an adult, stand to the side and just behind the victim. Place your arm accross the victim's chest to support their body.")
speak("Bend the victim at the waist to face the ground.")
speak("Strike five seperate times bectween the victim's shoulderblades with the heel of your hand.")
speak("If the back blows don't work, give five abdominal thrusts, also known as the heimlich manuver.")
speak("Alternate between the blows and the thrusts until the blockage is removed")
def dislocated():
speak("Dislocation first aid.")
noo()
speak("Don't move the joint. Splint the affected area nd keep it still. Don't try to force it back into place.")
speak("Put ice on the injured joint. This can help reduce swelling.")
def electrocuted():
speak("Electrocution first aid")
speak("Don't touch the victim if they are still in contact with the electricity source.")
speak("Don't move a victim with an electrical injury unless there is immediate danger.")
speak("Call nine one one if there are any exposed wiring or power lines")
speak("Call nine one one if the following condiions are met.")
speak("The victim has confusion, severe burns, difficulty breathing, heart rythm problems, cardiac arrest, muscle pain or contractions, seizures, or loss of conciousness")
speak("Turn off the source of electricity, if possible. If not, use a nonconductive object made of cardboard, plastic, or wood to move the victim from the source of electricity.")
speak("Begin see pee are if the victim shows no sign of breathing, coughing, or movement.")
shock()
speak("Apply a bandage or clean cloth loosely to the wound, Don't use a blanket or towel, as fibers can stick to the burns.")
def fainted():
speak("Fainting first aid.")
speak("Position the victim on their back.")
speak("If the victim is not breathing, begin see pee are and call nine one one. Continue until the victim regains conciuosness or help arrives.")
speak("If the victim is breathing and the victim doesn't have any injuries, raise the legs above heart level about a foot if possible. Loosen belts, collars, or other constrictive clothing.")
speak("If the victim does not regain conciousness within one minute, call nine one one.")
def brokenBone():
speak("Broken bone first aid.")
speak("Call nine one one if the following conditions are met.")
speak("The broken bone was the result of a major trauma, if the victim isn't breathing or responsive, there is heavy bleeding, the limb or joint appears deformed, the bone has pierced the skin, the extremity of the limb is numb or blue at the end, or if you think a bone is broken in the neck, head, or back.")
speak("Next, stop any bleeding")
speak("immobilize the injured area, don't realign the bone.")
speak("Apply ice pack to limit swelling and reduce pain")
shock()
def heatStroke():
speak("Heatstroke first aid")
noo()
speak("Do whatever you can to cool the victim. You could")
speak("Put the victim in a tub of cool water")
speak("Spray the victim with a garden hose.")
speak("Sponge the victim with cool water")
speak("Fan the victim while misting with cool water.")
speak("Place ice packs or cool, wet towels on th neck, armpits, and groin.")
speak("Cover the victim with cool, damp sheets.")
speak("If the victim is concious, offer chilled water, a sports drink containing electrolytes, or a non alcoholic beverage containing caffeine.")
speak("Begin see pee are if necessary.")
def hypothermia():
speak("Hypothermia first aid")
noo()
speak("Remove the victim from the cold. Go inside if possible.")
speak("Gently remove wet clothing. Replace wet clothing with warm, dry clothing or blankets.")
speak("If further warming is necessary, do so gradually. For example, apply dry compresses to the cneter of the body, chest, neck, and groin.")
speak("Use an electric blanket if available.")
speak("If you use a warm water bottle, wrap it in a towel first.")
speak("Offer the victim warm, sweet, non alcoholic drinks.")
speak("Begin see pee are if necessary.")
speak("Do not warn the victim too quickly, such as with a heating lamp or a warm bath.")
speak("Don't attempt to warm the arms or legs. Massaging or heating the limbs can stress the heart and lungs.")
def sting():
speak("Animal bite or sting first aid")
speak("Call nine one one if the victim has trouble breathing, swelling in the face or throat, dizziness, fainting, unconciousness, a weak or rapid pulse, hives, nasuea, vomiting, diarrhea, the wound is deep or you don't know how serious it is, the skin is badly torn, crushed, or bleeding significantly, you notice swelling, redness, or oozing, you were in contact with a bat, or if you think the animal might have had rabies.")
speak("While waiting for emergency help, ask the victim if they have an epinephrine injectory and whether you should inject it, loosen tight clothing and jewelry, don't offer anything to drink, and if needed, position the victim to prevent choking on vomit.")
speak("For mild reactions, move to a safe area, remove any stingers, gently wash the area with soap and water, and apply cold water or ice for ten to twenty minutes.")
def spiderBite():
speak("Spider bite first aid.")
speak("Call nine one one if the victim was bitten by a dangerous spider, you are unsure if the spider was dangerous, the victim has severe pain, the victim has cramping, the victim has a growing wound at the bite site, the victim has problems breathing or swallowing, or if the area has spreading redness or red streaks.")
def snakeBite():
speak("Snake bite first aid.")
speak("If the snake bite was from a venomous snake, or if the bite area changes color, begins to dwell, or is painful, call nine one one.")
speak("While waiting for emergency assistance, move beyond the snake's striking distance, keep the victim calm to slow the spread of venom, remove tight clothing or jewerly, position the victim so the bite is below the heart, clean the wound with soap and water, and cover it with a dry dressing.")
speak("Do not use a tourniquet or apply ice.")
speak("Do not cut the wound or attempt to remove the venom.")
speak("Do not drink caffeine or alchohol.")
speak("Do not try to capture the snake. Try to remember the snake's color and shape, and if possible, take a picture of it.")
def tick():
speak("Tick first aid.")
speak("Get tweezers. Grasp the tick as close to the skin as possible, and gently pull it out with a slow and steady upward motion. When it's out, take a picture of it to show a doctor.")
speak("Do not twist or squeeze the tick with the tweezers. Do not use your bare hands. Do not use petroleum jelly, nail polish, or matches.")
speak("Secure the tick by sticking it to a piece of tape and take a picture of it, if you haven't done so already.")
speak("Wash your hands and the area with soap and water.")
speak("Call nine one one if you develop a severe headache, have difficulty breathing, have paralysis, or heart palpitations.")
speak("Contact your doctor if you aren't able to compeletely remove the tick, the rash at the site gets bigger after removal, you develop flu like symptoms, you think the bite is infected, or if you think you were bitten by a deer tick.")
def poison():
speak("Poison first aid")
speak("If the victim is not experiencing symptoms, or is being transported to medical help, visit poison dot org to get instructions.")
speak("If the victim is eperiencing symptoms, or overdosed, call nine one one")
speak("Visit poison dot org or call the poison hot line at eight hundered, two two two, one two two two for assistance.")
speak("While waiting for emergency help to arrive, remove the victim from the poison.")
speak("If the poison was swallowed, remove any remaining poison from the victim's mouth. If the poison was from a cleaning solution, read the bottle's label for instructions on accidental poisoning.")
speak("If the poison is on the skin, remove any contaminated clothing and rinse the affected areas under water for fifteen to twenty minutes.")
speak("If the posion is in the eye, remove any contact lenses and rinse the affected eye with lukewarm water for twenty minutes.")
speak("If the poison was inhaled, get the person into fresh air.")
speak("If the victim vomites, turn their head to the side to avoid choking.")
speak("Have someone gather pill bottles, cleaning containers, or labels about the poison to give the medical assistance. ")
def sprain():
speak("Sprain first aid.")
speak("Follow the instructions for rice.")
speak("Rest the injured limb. Try not to put weight on it.")
speak("Ice the areas soon as possible. Continue to ice it for fifteen to twenty minutes, four to eight times a day for two days.")
speak("Compress the area with an elastic wrap or bandage.")
speak("Elevate the area above the heart to prevent swelling.")
speak("Get medical help if you're unable to put weight on the joint, the joint feels numb, you can't move the joint, you develop redness or red streaks which start at the injured area, you have pain directly over the bones of an injured joint, you have injured an area which has been injured many times in the past, or you have severe pain.")
def headTrauma():
speak("Head trauma first aid.")
speak("Call nine one one if the following conditions are met.")
speak("Severe head or facial bleeding, blood or leakage from nose or ears, vomiting, severe headache, change in conciousness for more than a few seconds, black and blue discoloration below the eyes or behind the ears, confusion, agitation, loss of balance, weakness or inability to use an arm or a leg, unequal pupil size, slurred speech, or seizures.")
speak("While waiting for nine one one, keep the victim still. Lie the victim down with their head and shoulders slightly elevated. Don't move them unless absolutely necessary, if the victim is wearing a helmet, don't remove it.")
speak("Stop any bleeding with gently applied pressure with clean washclothes or gauze.")
speak("Watch for changes in breathing and alertness.")
def spinalInjury():
speak("Spinal injury first aid.")
noo()
speak("Don't move the victim. Place rolled up heavy towels or blankets on either side of the victim's head to keep the victim's head and neck still.")
speak("If see pee are is necessary, do chest compressions and pull the jaw forward to give mouth to mouth.")
speak("If you need to roll the victim over to prevent choking, do so with one person rolling the head while another rolls the side to keep the neck and back aligned.")
def frostBite():
speak("Frostbite first aid.")
speak("Protect the skin from further damage.")
speak("Check for signs of hypothermia.")
speak("Get the victim out of the cold.")
speak("Gently warm the affected areas by soaking the area in very warm, not hot, water for twenty to thirty minutes.")
speak("If you cannot soak the area in water, apply warm, wet washcloths.")
speak("Do not warm frotbitten with direct heat, such as a stove, lamp, fireplace, or heating pad, as this can cause burns.")
speak("Drink non alcoholic, warm liquids.")
speak("As the skin warms, the victim should feel tingling. Do not break any blisters that form.")
speak("for anything more than mild frostbite, seek medical help.")
def overdose():
speak("Drug overdose first aid.")
noo()
speak("Wear gloves when helping the victim. Don't touch any pills, bottles, or powder you see.")
speak("Do not enter any area that appears unsafe.")
speak("Administer Naloxone if available.")
speak("Roll the victim on their side and keep the airway open to prevent choking.")
speak("Monitor the victim and give see pee are if necessary.")
def diagnose():
speak("Diagnose")
def causeKnown():
speak("What is the cause?")
input("Looking for cause, which is known")
if "heart attack" in cause:
heartAttack()
elif "stroke" in cause and "heat" not in cause:
stroke()
elif "cut" in cause or "stab" in cause or "scrape" in cause:
cut()
elif "burns" in cause or "burn" in cause:
burn()
elif "choking" in cause:
choking()
elif "dislocate" in cause or "dislocation" in cause or "dislocated" in cause:
dislocated()
elif "shock" in cause or "electric" in cause or "electrocution" in cause or "electrocuted" in cause or "shocked" in cause:
electrocuted()
elif "faint" in cause or "fainted" in cause:
fainted()
elif "broken" in cause or "broke" in cause:
brokenBone()
elif "heat" in cause or "heatstroke" in cause:
heatStroke()
elif "hypothermia" in cause:
hypothermia()
elif "frostbite" in cause:
frostBite()
elif "snake" in cause:
snakeBite()
elif "spider" in cause:
spiderBite()
elif "tick" in cause:
tick()
elif "bite" in cause or "sting" in cause or "stung" in cause or "bit" in cause:
sting()
elif "poison" in cause or "toxic" in cause or "chemical" in cause or "chemicals" in cause:
poison()
elif "sprain" in cause or "sprained" in cause or "twisted" in cause or "twist" in cause:
sprain()
elif "head" in cause:
headTrauma()
elif "overdose" in cause or "overdosed" in cause or "over" and "dose" in cause:
overdose()
def startFirstAid(again):
# The buttons do yes/no and scroll through conditions if the conditions is known
removeGPIO()
GPIO.add_event_detect(21,GPIO.RISING,callback=markyes, bouncetime=500)
GPIO.add_event_detect(11,GPIO.RISING,callback=markno, bouncetime=500)
GPIO.add_event_detect(12,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(13,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(15,GPIO.RISING,callback=volumeUp, bouncetime=500)
GPIO.add_event_detect(16,GPIO.RISING,callback=volumeDown, bouncetime=500)
GPIO.add_event_detect(18,GPIO.RISING,callback=none, bouncetime=500)
GPIO.add_event_detect(19,GPIO.RISING,callback=none, bouncetime=500)
speak("Do you know what the problem is?")
i=0
while i<600:
if yes_no!="":
if yes_no==True:
causeKnown()
break
elif yes_no==False:
diagnose()
break
i+=1
time.sleep(0.1)
if i==599:
#Never responded, go back to main menu
print("Done")
else:
print("Got an answer")
print("yes_no:", yes_no)
yes_no=""
def generate_todo_id(title, t="t"):
hash_str = str(time.time()) + title
hash_obj = hashlib.sha256(hash_str.encode())
return hash_obj.hexdigest()[:10]
def create_todo(title, description=None, t="t"):
todo_id = generate_todo_id(title)
cursor = conn.cursor()
cursor.execute("INSERT INTO todos (todo_id, title, description) VALUES (?, ?, ?)", (todo_id, title, description))
conn.commit()
return("Success")
def delete_todo(t="t"):
global selected
print(selected)
if selected==None: selected=0
try:
delete_id=read_todos()[selected][0]
except IndexError:
speak("Todo list is already empty")
return
cursor = conn.cursor()
cursor.execute("DELETE FROM todos WHERE todo_id=?", (delete_id,))
conn.commit()
if selected!=0: selected-=1
return("Success")
def read_todos(t="t"):
cursor = conn.cursor()
cursor.execute("SELECT * FROM todos;")
rows = cursor.fetchall()
return rows
def increase_selected(t="t"):
global selected
print("Length of todo lsit", len(read_todos()))
if selected==len(read_todos())-1:
speak("Cursor already at max")
return
if selected==None:
selected=0
return
print("Increasing selected", selected)
selected+=1
speak(read_selected_todo())
def decrease_selected(t="t"):
global selected
if selected==0:
speak("Cursor already at minimum")
return
if selected==None:
selected=0
selected-=1
speak(read_selected_todo())
def get_selected_todo(t="t"):
global selected
if selected is None:
selected=0
return read_todos()[0]#Return the first item in the table