def bandsintownCall(artist): # Call the LRU here, checking to see if its in the list # if not add it tts.speak(artist) if (' ' in artist): artistParam = artist artistParam = artistParam.replace(' ', '%20') artistParam = artistParam.strip() params = (bandsintown + artistParam + '/events?' + 'app_id=' + bandsintownKey + '&date=upcoming') else: artistParam = artist params = (bandsintown + artistParam + '/events?' + 'app_id=' + bandsintownKey + '&date=upcoming') print(params) response = requests.get(params).json() for event in response: # Using the cleanEvent() query above to manipulate the data. date = cleanEvent(event) file.writelines('\n%s\n' % date + artist) file.writelines('\n%s' % event["venue"]["city"]) total = event['venue']['city'] + date tts.speak(total) print(total) file.close()
def start(self): totalanswers = len(self.words) print u'Question language: "en", "ru" (default "en")' question_lang = raw_input() print u'Repeat question (default 3)' repeat = raw_input() print u'Order of words: "b" - with begin, "e" - with end: "r" - randomly. (Default "b")' rand = raw_input() print u"Range of words - 1 {0} (default - 1 {0})".format(totalanswers) rangewords = raw_input().split() if rangewords: self.words.trim_words(int(rangewords[0])-1, int(rangewords[1])) print u'Enable tts: enable - "e", disable - "d" (Default "d")' self.tts_mode = False if raw_input() == 'e' else True question_lang = question_lang if question_lang else 'en' repeat = int(repeat) if repeat else 3 rand = rand if rand else 'b' while self.words: if rand == 'b': self.w = self.words.get_word() elif rand == 'e': self.w = self.words.get_word(first=False) elif rand == 'r': self.w = self.words.get_random_word() msg_inline(self.w[question_lang][0]) if question_lang == 'en' else msg_inline(self.w[question_lang]) if question_lang == 'en': tts.speak(self.w['en'][0][0], self.tts_mode) self.survey(self.w['en'], repeat) else: print u'Happy end!' print u'Press enter to return' raw_input() return
def hotword_detected(): mixer.music.play() text = listen() try: action(text) except: speak("Sorry I don't know that one!")
def start(number: int, difficulty: str, guesses: int): tts.speak("Welcome to the number guessing game") tts.speak("Pick a difficulty between Easy, Normal, and Hard") difficulty_prompt: str = input("Difficulty: ") if difficulty_prompt.lower() == "easy": tts.speak( "You picked easy difficulty so you have to guess a number between 1-5 and you have 3 guesses" ) difficulty = "easy" number = random.randint(1, 5) guesses = 3 elif difficulty_prompt.lower() == "normal": tts.speak( "You picked normal difficulty so you have to guess a number between 1-9 and you have 5 guesses" ) difficulty = "normal" number = random.randint(1, 9) guesses = 5 elif difficulty_prompt.lower() == "hard": tts.speak( "You picked hard difficulty so you have to guess a number between 1-15 and you have 7 guesses" ) difficulty = "hard" number = random.randint(1, 15) guesses = 7 return number, difficulty, guesses
def delay_tts(self, text): while not self.tts_mode: tts.speak(text) answer = raw_input().decode(encoding) if answer: return answer return raw_input().decode(encoding)
def upcoming(): file = open('bin/UpcomingAlbums/upcomingRelease.txt', 'r') f = file.readlines() for x in f: # Output each line in the file tts.speak(x) print(x)
def start_a_new_sequence(self, message, *args): self.__init__() # ------------------------------------------------------------------------------- Read The File for coding in ['windows-1252', 'windows-1252', 'UTF-8', 'ASCII', 'ISO-8859-1']: try: seq_file = open(message[2], 'r') content = seq_file.read() seq_file.close() self.base_seq_dir = os.path.dirname(message[2]) Logger.info("start_a_new_sequence: base folder: {}".format(self.base_seq_dir)) Logger.info("start_a_new_sequence: {} well decoded in {}".format(message[2], coding)) #Logger.info("start_a_new_sequence: Testo:\n{}".format(content)) break except UnicodeDecodeError: Logger.critical( "start_a_new_sequence: {} Tentata codifica {} errata".format(message[2], coding)) pass # ------------------------------------------------------------------------------- First Parsing: find separator max_count = 0 for s in self.separators: occurrences = content.count(s) if occurrences > max_count: self.official_separator = s max_count = occurrences parameter = True page_rst = "{}\n===========\n{}".format(self.title, content) page_line_count = 0 for s in content.replace('\r', '').split('\n'): # ----------------------------------------------------------------------------- Parsing High part, Title, etc. if parameter: val = s.split(self.official_separator) if val[0].find("Start of the sequence") > -1: # Inizio Sequenza ____________________________ parameter = False else: # is a valid parameter _______________________________ try: setattr(self, val[0], val[1]) # ToDo in python 3 remove! page_rst = "{}\n===========\n\nSelf Generated sequence:\n\n".format(self.title) except UnicodeEncodeError: setattr(self, 'title', val[1]) # ToDo in python 3 remove! Logger.debug('start_a_new_sequence: Tarokked the title: {}'.format(val[1])) # ----------------------------------------------------------------------------- Parsing Excercises else: # Decoding istructions from here _______________________________________________ if s.count(self.official_separator) >= 2: # It is a valid instruction, at least 3 operand self.new_activity(["", "", s]) # ToDo Valutation about this mess page_line_count += 1 page_rst += "{:02d}. {}\n\n".format(page_line_count, s) self._initialize_image(0) rst_file = os.path.join(self.base_seq_dir, 'info.rst') if not os.path.exists(rst_file): page_file = open(rst_file, 'w') page_file.write(page_rst) page_file.close() self.push_message([rst_file], '/sld') Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) tts.speak("Sequence Loaded")
def _say(self, key: str=None, text: str=None): if key is not None: text = self.textdb.get_text(key) if not self.debug: old_col = self.bonnet.current_col self.bonnet.set_colour(self.bonnet.col_speak) speak(text, self.lang) if not self.debug: self.bonnet.set_colour(old_col)
def main(): tts.set_output(cmd.args.sapi) with open(cmd.args.file) as f1: for line in f1: tts.speak(line, False) while True: if tts.get_output().name == "sapi5" and tts.is_speaking: time.sleep(0.05) else: break
def addF(): if (txtbx.get() != ""): try: txt = txtbx.get() speak(txt,"en") status_label.configure(text ="successfully completed") except: status_label.configure(text ="The text is not in proper format.") else: status_label.configure(text ="fill in the text, please.")
def question_translate(self, to, repeat, rand, silence=False): s = 0 if rand == 'b': word = self.words.get_word() elif rand == 'e': word = self.words.get_word(first=False) elif rand == 'r': word = self.words.get_random_word() if not silence: print u'Words left - {0}'.format(len(self.words)) while s < repeat : if not silence: print u'Enter your answer - attempts {0}'.format(repeat-s) s+=1 if to=='ru': for i in word.en: print i if word.multiru: print u'Variants for translate {0}'.format(len(word.ru)) elif to=='en': for i in word.ru: print i if word.multien: print u'Variants for translate {0}'.format(len(word.en)) if to == 'ru': if not word.irregularverb: answer = self.delay_tts(', '.join(word.en)) else: answer = self.delay_tts(', '.join([', '.join(word.en[0]), ', '.join(word.en[1]), ', '.join(word.en[2])])) else: answer = raw_input().decode(encoding) if word.iscorrect(answer): if not silence: print u'Correct, {0}'.format(answer) if to == 'en': tts.speak(answer, silence=self.tts_mode) if to=='ru' and word.multiru: print u'All variants:' for i in word.ru: print i elif to=='en' and word.multien: print u'All variants:' for i in word.en: print i return True else: if not silence: print u'Incorrect, please try again!' else: if not silence: print u"Correct answer was:" if to=='ru': for i in word.ru: print i elif to=='en': for i in word.en: print i tts.speak(', '.join(word.en), silence=self.tts_mode) return False
def updateRow(topic,value): print"update" global srf row=topic[12:] row=int(row)-1; pygame.draw.rect(srf, (60,60,60), [maxX-580, 150+(90*row), 280, 80]) pygame.draw.rect(srf, (0,100,60), [maxX-300, 150+(90*row), 280, 80]) srf.blit(f.render(str(row+1),True,(255,0,0)),(maxX-450,140+(90*row))) srf.blit(f.render(str(value),True,(255,0,0)),(maxX-180,140+(90*row))) pygame.display.update() speak(str(value),topic[12:])
def tell_grade(grade: str): if int(grade) == 1: print("Gideon: You are in " + grade + "st") tts.speak_without_print("You are in first grade") elif int(grade) == 2: print("Gideon: You are in " + grade + "nd") tts.speak_without_print("You are in second grade") elif int(grade) == 3: print("Gideon: You are in " + grade + "rd") tts.speak_without_print("You are in third grade") else: tts.speak("You are in grade " + grade)
def button_callback(channel): print("Button was pushed!") listLenght = len(myJokeList) print('The list has %s items' % listLenght) myRandomNumber = random.randint(0, (listLenght - 1)) print('The randon number is %s' % myRandomNumber) print(myJokeList[myRandomNumber]) tts.speak(myJokeList[myRandomNumber]) time.sleep(1)
def main(): tts.speak('Saylem initialized. Say my name when you would like to start') print('Saylem initialized. Say my name when you would like to start') print('---------------------') start = speech.speech() # start = input() print(start) reminder.checkForReminder() if ('Sale' or 'Salem' in start): main_flow()
def ticketMasterCall(city, results): if (' ' in city): city = city.replace(' ', '+') params = (ticketmaster + 'apikey=' + ticketMasterKey + '&sort=date,asc&city=' + city + '&size=' + results) response = requests.get(params).json() print(params) for event in response["_embedded"]["events"]: tts.speak(event['name']) print(event['name']) file.writelines('%s\n' % event["name"]) file.close()
def process(lst): sb = cStringIO.StringIO() for item in lst: if isinstance(item, basestring): sb.write(item) elif isinstance(item, tuple): sb.write(item[0](item[1])) v = sb.getvalue() if v.strip() == '': return if cmd.args.espeak!="": synth.speak(v) else: tts.speak(v, False)
def upcomingShows(): tts.speak('would you like all concerts or a specific artist') print('would you like all concerts or a specific artist') print('---------------------') # concertType = input() concertType = speech.speech() print(concertType) if ('concert' in concertType): # getting all upcoming concerts tts.speak('Specify a location') print('specify a location') print('---------------------') # city = input() city = speech.speech() tts.speak('Is there a limit you would like to set on the results') print('Is there a limit you would like to set on the results') print('---------------------') # limit = input() limit = speech.speech() if ('no' in limit): uc.concertCall('all', city, '40') else: uc.concertCall('all', city, limit) else: # getting artist specific concerts tts.speak('what artist would you like?') print('what artist would you like') print('---------------------') # artistCall = input() artistCall = speech.speech() uc.concertCall(artistCall, None, None)
def say_something(message, *args): msg = message[2] #Logger.debug("say_something: TTS is talking: {}. Status is: {}-{}".format( # tts.isSpeaking(), say_something.time_end_step, time.time())) # if msg != say_something.last_message: if tts.isSpeaking(): # or say_something.time_end_step > time.time(): pass # Logger.debug("say_something: Still talking, doing nothing until {}. Now is".format( # say_something.time_end_step < time.time())) else: #say_something.last_message = msg #Logger.debug("say_something: tts.speak({}, {})".format(msg, 'IT')) #say_something.status = tts.speak(msg, 'IT')
def checkForReminder(): f = open('bin/Reminder/reminderOne.txt', 'r') today = date.today() todayDateDay = today.strftime('%d').lstrip('0') todayDateMonth = today.strftime('%m').lstrip('0') todayDate = todayDateDay + ' ' + todayDateMonth for line in f: if todayDate in line: print('found') total = f.readlines() artist = total[0].strip() venue = total[1].strip() tts.speak(artist + ' is on today at ' + venue) print(artist + ' is on today at ' + venue)
def send_email(candid, attach_photo_flag): attachment = './captured_images/candidate_{0}.jpg'.format(candid) toemail = '*****@*****.**' fromemail = '*****@*****.**' msg = MIMEMultipart() # msg["To"] = '*****@*****.**' # msg["From"] = '*****@*****.**' msg["Subject"] = 'Candidate {0} has arrived for interview.'.format(candid) body = "dummy" if attach_photo_flag: body = "Hi Recruitment Team,<br><br>Please be informed that below candiate : {0} has arrived for interview.<br><br>Thanks & Regards,<br>FrontDesk ChatBot. <hr>".format( candid) msgText = MIMEText( '<b>%s</b><br><img src="cid:%s"><br>' % (body, attachment), 'html') msg.attach(msgText) # Added, and edited the previous line fp = open(attachment, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', '<{}>'.format(attachment)) msg.attach(img) else: body = "Hi Recruitment Team,<br><br>Please be informed that the candiate : {0} has arrived for interview.<br><br>Thanks & Regards,<br>FrontDesk ChatBot.".format( candid) msgText = MIMEText('<b>%s</b><br>' % (body), 'html') msg.attach(msgText) # Added, and edited the previous line # Gmail Sign In gmail_sender = '*****@*****.**' gmail_passwd = 'mybot@123' server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_sender, gmail_passwd) # print(msg.as_string()) try: server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) print('email has been sent successfully') speak('email has been sent successfully', speech_flag) except: print('there was some error sending mail') speak('there was some error sending mail', speech_flag) server.quit()
def start_a_new_sequence(self, message, *args): self.__init__() max_count = 0 for coding in ['windows-1252', 'windows-1252', 'UTF-8', 'ASCII', 'ISO-8859-1']: try: seq_file = open(message[2], 'r') content = seq_file.read() seq_file.close() self.base_seq_dir = os.path.dirname(message[2]) Logger.info("start_a_new_sequence: base folder: {}".format(self.base_seq_dir)) Logger.info("start_a_new_sequence: {} well decoded in {}".format(message[2], coding)) Logger.info("start_a_new_sequence: Testo:\n{}".format(content)) break except UnicodeDecodeError: Logger.critical( "start_a_new_sequence: {} Tentata codifica {} errata".format(message[2], coding)) pass for s in self.separators: occurrences = content.count(s) if occurrences > max_count: self.official_separator = s max_count = occurrences parameter = True #setattr(self, 'title', 'now works') for s in content.replace('\r', '').split('\n'): if parameter: val = s.split(self.official_separator) print val[0], val[1] if val[0].find("Start of the sequence") > -1: # Inizio Sequenza ____________________________ parameter = False else: # is a valid parameter _______________________________ try: setattr(self, val[0], val[1]) # ToDo in python 3 remove! except UnicodeEncodeError: setattr(self, 'title', val[1]) # ToDo in python 3 remove! Logger.debug('start_a_new_sequence: Tarokked the title: {}'.format(val[1])) else: # Decoding istructions from here _______________________________________________ if s.count(self.official_separator) > 1: # It is a valid instruction, at least 3 operand self.new_activity(["", "", s]) # ToDo Valutation about this mess self._initialize_image(0) Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) tts.speak("Sequence Loaded: {}".format(self.title))
def main(): # Turn off hotword detector detector.terminate() # Ask replies = ["是,主人", "有什麼吩咐嗎", "是"] tts.speak(random.choice(replies)) play_file() # Listen print("Listening...") sentence = recognizer.recognize() # Processing print("Processing...") success = sentence[0] userSays = " ".join(sentence[1]) if success: confidence = classifier.getProbability(userSays, classifier.classify(userSays)) intention = classifier.classify(userSays) print(confidence) # FEATURES if intention in features and confidence > 0.70: # confidence boundary answer = features[intention]() # CONVERSATION elif confidence > 0.70: response = classifier.response(userSays) answer = response # NO ANSWER else: answer = "對不起,我聽不太懂" if tts.speak(answer): play_file() else: if tts.speak(userSays): play_file() # Turn back on hotword detector listen()
def process_user_query(): while True: user_query = sr.get_audio_to_text() #checking query is empty or not if user_query != None: user_query = user_query.lower() # if query has exit keywords, close the application if exit_keyword[0] in user_query or exit_keyword[ 1] in user_query or exit_keyword[3] in user_query: tts.speak("exit") break # else execute the command else: filter_query_trigger(user_query) #asking for next query tts.speak("askNext")
def call(artistName, limit): # Check in LRU if (' ' in artistName): artistName = artistName.replace(' ', '+') artistName = artistName.strip() params = ('method=artist.getSimilar&artist=' + artistName + '&api_key=' + apiKey + '&format=json&limit=' + limit) response = requests.get(apiUrl + params).json() file = open('bin/SimilarArtist/artistOne.txt', 'w') for artist in response["similarartists"]["artist"]: print(artist['name']) tts.speak(artist['name']) file.writelines('%s\n' % artist['name']) file.close()
def main(): #Prints the arguments passed for arg in sys.argv: print arg home = ['Welcome home!', 'Hi again!', 'Hello there, welcome back!'] if sys.argv[1] == "home": print "home" tts.speak(random.choice(home)) leaving = ['See you later.', 'Goodbye!', 'Be safe out there!'] if sys.argv[1] == "leaving": print "leaving" tts.speak(random.choice(leaving))
def main(): # Turn off hotword detector detector.terminate() # Ask tts.speak("네! 주인님") play_file() # Listen print("Listening...") sentence = recognizer.recognize() # Processing print("Processing...") if sentence[0]: # answer = dialogflow.ask(sentence[1]) confidence = classifier.getProbability( sentence[1], classifier.classify(sentence[1])) intention = classifier.classify(sentence[1]) # FEATURES if intention in features: answer = features[intention]() # CONVERSATION elif confidence > 0.21: # confidence boundary response = classifier.response(sentence[1]) answer = response # NO ANSWER else: answer = "잘 모르겠어요" if tts.speak(answer): play_file() else: if tts.speak(sentence[1]): play_file() # Turn back on hotword detector listen()
def audioClip(): tts.speak('what artist would you like to hear a clip of?') print('what artist') # audioClipArtist = input() audioClipArtist = speech.speech() tts.speak('Audio preview of ' + audioClipArtist + ' starting now.') tts.speak('Please wait a moment while it loads') ap.getUrl(audioClipArtist)
def reminders(): tts.speak('What artist would you like to set a reminder for') print('What artist would you like to set a reminder for') # remindArtist = input() remindArtist = speech.speech() tts.speak('What is the venue') print('What is the venue') # remindVenue = input() remindVenue = speech.speech() tts.speak('What is the date. Specify in date month format') print('What is the date. Specify in date month format') # remindDate = input() remindDate = speech.speech() reminder.setReminder(remindDate, remindArtist, remindVenue) tts.speak('Your reminder has been set')
def survey(self, forms, repeat): forms = list(forms) f = 0 while any(forms) and f <= 2: print self.msg_forms[f] s = 0 while forms[f] and s <= 2: answer = raw_input().decode(encoding) try: forms[f].remove(answer) print u'is correct' tts.speak(answer, self.tts_mode) if forms[f]: print u'Enter next variant:' except ValueError: print u'Incorrect, please try again!' s+=1 if s == repeat: print u'Answer was:' msg_multiline(forms[f], endline=' ') tts.speak(forms[f][0], self.tts_mode) else: f+=1
def load_tabata(self, message, *args): self.__init__() seconds_go, seconds_rest, excercises, rounds = message[2:] self.title = 'Timer: {} Round {} exercises.{} sec wkout, {} rest.'.format( rounds, excercises, seconds_go, seconds_rest) description = 'Starting the following sequence:.{} Round of {} exercises.Practice for {} seconds, rest for {} seconds.Prepare to sweat!'.format( rounds, excercises, seconds_go, seconds_rest) self.seq_timings.append(10) self.time_duration += 10 self.seq_modes.append('TTS_EN') self.seq_images.append('images/love_burpees.png') self.seq_text_messages.append(description) self.seq_snds.append('default') for j in range(int(rounds)): for i in range(int(excercises)): # Init start sequence self.seq_timings.append(int(seconds_go)) self.time_duration += int(seconds_go) self.seq_modes.append('TTS_EN') self.seq_images.append('images/love_burpees.png') if i < 1: self.seq_text_messages.append('Start Round {}.Exercise {}.'.format(j+1, i+1)) else: self.seq_text_messages.append('Start exercise {}.'.format(i+1)) self.seq_snds.append('default') # Init Rest Sequence if int(seconds_rest) > 0: self.seq_timings.append(int(seconds_rest)) self.time_duration += int(seconds_rest) self.seq_modes.append('TTS_EN') self.seq_images.append('images/now_rest.png') self.seq_text_messages.append('Now rest') self.seq_snds.append('default') self._initialize_image(0) Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) tts.speak("Sequence Loaded")
def exec_actual_activity(self): if tts.isSpeaking(): self.res_last_action = -1 Logger.debug("exec_actual_activity: Still talking") elif self.seq_modes[self.idx_stp][0:4] == "TTS_": #self.sound_manager.set_volume(0.1) # ToDo sound_manager lng = self.seq_modes[self.idx_stp][-2:] msg = self.seq_text_messages[self.idx_stp] Logger.debug("Sequence exec_actual_activity: tts.speak({}, {})".format(msg, lng)) self.res_last_action = tts.speak(msg, lng) else: Logger.debug("Sequence exec_actual_activity: VIRTUAL{} {})".format( self.seq_modes[self.idx_stp], self.seq_text_messages[self.idx_stp])) self.res_last_action = 0 # show must go on!
def start(): tts.speak("What is your Name") name = input("Name: ") tts.speak("What is your age") age = input("age: ") tts.speak("What grade/class are you in") grade = input("Grade/Class: ") return name, age, grade
def exec_actual_activity(self): """ :return: -1 if system not ready and need to be called later 0 if OK """ if tts.isSpeaking(): #adding last sound played return -1 Logger.debug("exec_actual_activity: Still talking") elif self.seq_modes[self.idx_stp][0:4] == "TTS_": #self.sound_manager.set_volume(0.1) # ToDo sound_manager lng = self.seq_modes[self.idx_stp][-2:] msg = self.seq_text_messages[self.idx_stp] Logger.debug("Sequence exec_actual_activity: tts.speak({}, {})".format(msg, lng)) return tts.speak(msg, lng) else: Logger.debug("Sequence exec_actual_activity: VIRTUAL{} {})".format( self.seq_modes[self.idx_stp], self.seq_text_messages[self.idx_stp])) return 0 # show must go on!
def similarArtist(): tts.speak('what artist') print('what artist?') print('---------------------') # artist = input() artist = speech.speech() tts.speak('how many results would you like') print('how many results would you like') print('---------------------') # limit = input() limit = speech.speech() tts.speak('artists that are similar to ' + artist + ' are...') print('artists that are similar to ' + artist + ' are...') print('---------------------') sa.call(artist, limit)
def user_interaction(): try: bot_input = "" user_input = "" while True: if user_input == "": user_input = input("[USER]: ") speak(user_input) else: bot_input = get_final_reply(user_input) print("[{}]:".format(NAME), bot_input[0], "Confidence level:", bot_input[1]) speak(bot_input[0]) user_input = input("[USER]: ") speak(user_input) except Exception as e: print("\n[ERRORS]:\n") print(str(e)) print("Closing the conversation...") con.commit()
import cv2 from imagecapture import capture_image from sendemail import send_email from tts import speak speech_flag = True print("Hello, welcome to JP Morgan Chase & Co. (Say 'Hi' to begin) ") speak("Hello, welcome to JP Morgan Chase & Co. (Say 'Hi' to begin) ", speech_flag) input() print("please provide your candidate Id :") speak("please provide your candidate Id :", speech_flag) candid = input() speak(candid, speech_flag) # send email, photo to HR, interviewer intimating candidate has arrived. print( "Shall I take your Photo and send to Recruitment team to inform about your arrival ? select (y/n)" ) speak( "Shall I take your Photo and send to Recruitment team to inform about your arrival ? select (y/n)", speech_flag) res = input() speak(res, speech_flag) print( "Please wait while we capture your photo, keep your head still and smile!!......." )
def _play_next_msg_part(self): s, lv, rv = self._queue.pop(0) if is_text(s): tts.speak(s) else: self._play(s, lv, rv)
def convertFile(): filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("Text Files","*.txt"),("all files","*.*"))) with open(filename, 'rt') as f: text = f.read() speak(text,"en") status_label.configure(text ="successfully completed")
def _cannot_alter(self, flavor): if(self.name[0].lower() in ['a', 'e', 'i', 'o', 'u']): article = 'an' else: article = 'a' tts.speak("There are no " + flavor + " ingredients in " + article + ' ' + self.name)
import SpeechRego as sr import tts import subprocess as sp import youtube_play as yp import installModule as im import file_operations as fo import execute_commands as ec import google_search as gs import directory_op as do import service as se # program exit keywords exit_keyword = ['quit', 'exit', 'cancel', 'close'] #intro message tts.speak("welcome") tts.speak("ask") def process_user_query(): while True: user_query = sr.get_audio_to_text() #checking query is empty or not if user_query != None: user_query = user_query.lower() # if query has exit keywords, close the application
from tts import speak text = input("Enter the text: ") language = 'en' speak(text, language)
import cmd, platform, sys import tts, time if platform.system() == 'Windows': import fix_win32com if hasattr(sys, "frozen"): fix_win32com.fix() tts.set_output(cmd.args.sapi) if platform.system() == 'Windows': with open(cmd.args.file) as f1: for line in f1: tts.speak(line, False) while True: if tts.get_output().name == "sapi5" and tts.is_speaking: time.sleep(0.05) else: break else: tts.speak(cmd.args.text, False) time.sleep(len(cmd.args.text) * cmd.args.wait)
def start_a_new_timing_sequence(self, message, *args): self.__init__() messages = message[2].split('.') if len(messages) == 4: seconds_go, seconds_rest, excercises, rounds = messages self.title = 'Timer: {} Round {} exercises.{} sec wkout, {} rest.'.format( rounds, excercises, seconds_go, seconds_rest) description = 'Starting the following sequence:.{} Round of {} exercises.Practice for {} seconds, rest for {} seconds.Prepare to sweat!'.format( rounds, excercises, seconds_go, seconds_rest) self.seq_timings.append(10) self.time_duration += 10 self.seq_modes.append('TTS_EN') self.seq_images.append('images/love_burpees.png') self.seq_text_messages.append(description) self.seq_snds.append('default') for j in range(int(rounds)): for i in range(int(excercises)): # Init start sequence self.seq_timings.append(int(seconds_go)) self.time_duration += int(seconds_go) self.seq_modes.append('TTS_EN') self.seq_images.append('images/love_burpees.png') if i < 1: self.seq_text_messages.append('Start Round {}.Exercise {}.'.format(j+1, i+1)) else: self.seq_text_messages.append('Start exercise {}.'.format(i+1)) self.seq_snds.append('default') # Init Rest Sequence if int(seconds_rest) > 0: self.seq_timings.append(int(seconds_rest)) self.time_duration += int(seconds_rest) self.seq_modes.append('TTS_EN') self.seq_images.append('images/now_rest.png') self.seq_text_messages.append('Now rest') self.seq_snds.append('default') self._initialize_image(0) Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) elif len(messages) == 2: # Simple Timer: minutes.seconds mm, sec = messages duration_all = int(mm)*60 + int(sec) timer = [[30, "30 seconds"], [30, "1 minute"], [60, "2 minutes"], [180, "5 minutes"], [300, "10 minutes"], [300, "15 minutes"], [900, "30 minutes"], [900, "45 minutes"], [900, "1 hour"], [900, "1 hour and 15 minutes"], [900, "1 hour and 30 minutes"], [900, "1 hour and 45 minutes"], [900, "2 hours"], ] actual = 0 index = -1 while actual+timer[index+1][0] < duration_all: index += 1 actual += timer[index][0] Logger.debug("{} - {}".format(duration_all, actual)) Logger.debug("{} - {} = {}".format(duration_all, actual, duration_all - actual)) self.seq_timings.append(duration_all - actual) self.time_duration += self.seq_timings[-1] self.seq_modes.append('TTS_EN') self.seq_images.append('images/bk_nw.png') self.seq_text_messages.append('{} minute and {} seconds left.'.format(mm, sec)) self.title = 'Timer of {} minute and {} seconds.'.format(mm, sec) self.seq_snds.append('default') while index >= 0: self.seq_timings.append(timer[index][0]) Logger.debug(str(timer[index][0])) self.time_duration += timer[index][0] self.seq_modes.append('TTS_EN') self.seq_images.append('images/bk_nw.png') self.seq_text_messages.append('{} left.'.format(timer[index][1])) self.seq_snds.append('default') index -= 1 tts.speak("Sequence Loaded")
def action(text): if text.find("YouTube") != -1: search_term = text[text.index("play") + 4: text.index("on YouTube")] got, dur = get_youtube(search_term) list =[got , dur] speak("playing" + search_term + "on youtube") push("youtube", list) elif text.find("turn on lights") != -1: rqst.get("http://192.168.1.150:91/?socket=1On") speak("turning on lights") elif text.find("stop") != -1: pause_music() push("youtube","stop") speak("ok") elif text.find("turn off lights") != -1: rqst.get("http://192.168.1.150:91/?socket=1Off") speak("turning off lights") elif text.find("tell me something about") != -1: search_wiki = text[text.index("tell me something about") + len("tell me something about"):] got_wiki = wiki(search_wiki) push("wiki", got_wiki) speak(got_wiki) elif text.find("play") != 1: global search_music search_music = text[text.index("play") + len("play"):] speak("playing" + search_music) worker().start() elif text.find("show me a picture of") != 1: search_image = text[text.index("show me a picture of") + len("show me a picture of"):].replace(" ", "") print(search_image) push("images", find_image(search_image)) speak("ok! heres how" + search_image + "looks ")