def bye(query, txt): speak('Goodbye', txt) for process in psutil.process_iter(): proc_name = process.name() if proc_name == 'chrome.exe': process.kill() exit()
def who_are_you(query, txt): messages = [ "I am Automate your loyal personal assistant.", "Automate, didn't I tell you before?", "You ask that so many times! I am automate." ] speak(random.choice(messages), txt)
def clear_notes(txt): con = sqlite3.connect('automate.db') cursor = con.cursor() username = cursor.execute('SELECT * FROM current_user').fetchone()[0] cursor.execute('DELETE FROM notes WHERE username = "******"') con.commit() con.close() speak('All notes have been erased.', txt)
def translate(l, say): translate = Translator() result = translate.translate(say, dest=lan.get(l)) #result = translate.translate(say ,dest=lan.get('日文')) #result = translate.translate('我想吃晚餐',dest=lan.get('日文')) speak(result.text, lan.get(l)) print(result.text) return result.text
def news(query, txt): news_url = "https://news.google.com/news/rss" client = urlopen(news_url) xml_page = client.read() client.close() soup_page = BeautifulSoup(xml_page, "xml") news_list = soup_page.findAll("item") del news_list[3:] for news_item in news_list: speak(news_item.title.text, txt)
def set_note(query, txt): con = sqlite3.connect('automate.db') cursor = con.cursor() username = cursor.execute('SELECT * FROM current_user').fetchone()[0] cursor.execute( "INSERT INTO notes VALUES (?, ?, ?)", (username, query, datetime.strftime(datetime.now(), '%d-%m-%Y'))) con.commit() con.close() speak('Your note has been saved.', txt)
def translateTo(): sen = speech_recognition.Recognizer() with speech_recognition.Microphone() as source: sen.adjust_for_ambient_noise(source, duration=5) speak('正在翻譯...','zh-TW') print('正在翻譯...') audio = sen.listen(source) print(sen.recognize_google(audio, language='zh-TW')) return sen.recognize_google(audio, language='zh-TW')
def note(query, txt): if 'read' in query or 'show' in query or 'tell' in query or 'display' in query or 'what' in query: get_note(txt) elif 'clear' in query or 'delete' in query or 'erase' in query: clear_notes(txt) else: query = query.replace('note', '').replace('memorize', '').strip() if query == '': speak('There is nothing to note.', txt) return set_note(query, txt)
def gmail_sign_in(self, password): self.master.destroy() try: self.server.starttls() self.server.login(self.email_id, password) except (gaierror, SMTPConnectError, SMTPServerDisconnected): speak('The server could not be reached', self.txt) except SMTPAuthenticationError: speak('Invalid credentials', self.txt) else: EmailSend(self.email_id, self.server, Toplevel(), self.txt)
def listenToNews(): r = speech_recognition.Recognizer() with speech_recognition.Microphone() as source: r.adjust_for_ambient_noise(source, duration=5) print("請選擇搜尋方式(頭條/關鍵字)") speak('請選擇搜尋方式', 'zh-TW') time.sleep(2) audio = r.listen(source) return r.recognize_google(audio, language='zh-TW')
def keyword(): w = speech_recognition.Recognizer() with speech_recognition.Microphone() as source: w.adjust_for_ambient_noise(source, duration=5) print("請選擇關鍵字") speak('請選擇關鍵字', 'zh-TW') time.sleep(2) audio = w.listen(source) print(w.recognize_google(audio, language='zh-TW')) return w.recognize_google(audio, language='zh-TW')
def play_media(query, txt): from Settings_Frame import music_path, video_path global media_name, media_flag media_flag = False media_name = query.replace('play', '').replace('mp3', '').replace('song', '').replace('video', '').lower().strip() if 'mp3' in query or 'song' in query: search_song(music_path.get(), txt) else: search_video(video_path.get(), txt) if not media_flag: speak('Sorry, the media is not available.', txt)
def search_song(root, txt): global media_name, media_flag if media_flag: return for file in os.listdir(root): cur_path = os.path.join(root, file) if os.path.isdir(cur_path): search_song(cur_path, txt) else: if file.endswith('.mp3'): if re.search(media_name, file.lower()): media_flag = True speak('Playing song ' + media_name, txt) os.startfile(cur_path) break
def weather(query, txt): owm = pyowm.OWM('61cf9c73e72fb837f80c3e97ecd03a37') con = sqlite3.connect('automate.db') cursor = con.cursor() location = cursor.execute('SELECT * FROM current_user').fetchone()[8] con.close() report = owm.weather_at_place(location) result = report.get_weather() detailed_status = result.get_detailed_status() temp = result.get_temperature(unit='celsius') weather_result = 'It is ' \ + detailed_status + ' in ' \ + location + '. The temperature is ' \ + str(temp.get('temp')) + '° Celsius.' speak(weather_result, txt)
def search_video(root, txt): global media_name, media_flag if media_flag: return for file in os.listdir(root): cur_path = os.path.join(root, file) if os.path.isdir(cur_path): search_video(cur_path, txt) else: if file.endswith('.mp4') or file.endswith('.MP4') or file.endswith('.mkv') or file.endswith( '.MKV') or file.endswith('.avi') or file.endswith('.WEBM'): if re.search(media_name, file.lower()): media_flag = True speak('Playing video ' + media_name, txt) os.startfile(cur_path) break
def joke(query, txt): global joke_count jokes = [ 'What happens to a frogs car when it breaks down? It gets toad away.', 'Why was six scared of seven? Because seven ate nine.', 'Why are mountains so funny? Because they are hill areas.', 'Have you ever tried to eat a clock?' 'I hear it is very time consuming.', 'What happened when the wheel was invented? A revolution.', 'What do you call a fake noodle? An impasta!', 'Did you hear about that new broom? It is sweeping the nation!', 'What is heavy forward but not backward? Ton.', 'No, I always forget the punch line.' ] speak(jokes[joke_count], txt) joke_count += 1
def langue(): r = speech_recognition.Recognizer() with speech_recognition.Microphone() as source: r.adjust_for_ambient_noise(source, duration=5) speak('請選擇要翻譯的語言','zh-TW') print('請選擇要翻譯的語言(英/中/日)') audio = r.listen(source) try: print(r.recognize_google(audio, language='zh-TW')) except: speak('我正在聽','zh-TW') return r.recognize_google(audio, language='zh-TW')
def wish_me(txt): hour = int(datetime.datetime.now().hour) if 0 <= hour < 12: speak("Good morning.", txt) elif 12 <= hour < 18: speak("Good afternoon.", txt) else: speak("Good evening.", txt) speak("I am automate. How may I help you?", txt)
def wikipedia(query, txt): try: speak('searching wikipedia', txt) query = query.replace('search', '').replace('wikipedia', '').replace('for', '').strip() results = wiki.summary(query, sentences=2) speak('according to wikipedia', txt) speak(results, txt) except Exception as e: speak(e, txt)
def all_news(last): ticks = time.time() for i in range(0, 1): #print(top_headlines['articles'][i]['title']) #print(top_headlines['articles'][i]['description']) if last['articles'][i]['description'] == None: news = last['articles'][i]['title'] + '。\n' else: news = last['articles'][i]['title'] + '。\n' + last['articles'][i][ 'description'] + '。\n' print(news) speak(news, 'zh-TW') ticks2 = time.time() print(ticks2 - ticks) return news
def __init__(self, email_id, master, txt): try: self.server = SMTP('smtp.gmail.com', 587) except (gaierror, SMTPConnectError, SMTPServerDisconnected): speak('The server could not be reached', txt) self.email_id = email_id self.master = master self.master.title('Login to Gmail') self.txt = txt email_auth_frame = Frame(self.master, padx=10, pady=10) email_auth_frame.grid(row=0, column=0, sticky=N + S + E + W) Label(email_auth_frame, text='Enter Gmail Password', font=('', 25), pady=10).grid(row=0, column=0, sticky=N + E + W + S, columnspan=2) Label(email_auth_frame, text='Password : '******'', 20), pady=5, padx=5).grid(row=2, column=0, sticky=N + E + W + S) password_entry = Entry(email_auth_frame, show='*', bd=5, font=('', 15)) password_entry.grid(row=2, column=1, sticky=N + S + E + W) Button(email_auth_frame, text='Sign in', bd=3, font=('', 15), padx=5, pady=5, command=lambda: self.gmail_sign_in(password_entry.get())).grid( row=3, column=1, sticky=N + S + E + W)
def day_date_time(query, txt): if 'time' in query: speak("The time is " + datetime.strftime(datetime.now(), '%H:%M:%S'), txt) if 'date' in query: speak("The date is " + datetime.strftime(datetime.now(), '%m/%d/%Y'), txt) if 'day' in query: speak("The day is " + datetime.strftime(datetime.now(), '%A'), txt)
def take_command(txt): while True: r = speech_recognition.Recognizer() with speech_recognition.Microphone() as source: print('Listening....') txt.insert(INSERT, 'Listening....\n') txt.update() r.pause_threshold = 1 audio = r.listen(source) try: print('Recognizing...') txt.insert(INSERT, 'Recognizing...\n') txt.update() query = r.recognize_google(audio, language='en-in') print('User : '******'\n') txt.insert(INSERT, 'User : '******'\n') txt.update() except Exception as e: print(e) speak("Say again please...", txt) continue return query
def action_detection(action): print(action) if action == "weather-search": spotifycontrol("暫停","") location = format(response.query_result.parameters['Taiwan-city']) date = format(response.query_result.parameters['date']) print(date) if date == "": weather_current(location) else: weather_forecast(date,location) elif action == "music-play": music_action = format(response.query_result.parameters['music-action']) music_category= format(response.query_result.parameters['music-category']) music_artist = format(response.query_result.parameters['music-artist']) if music_action == "播放": if music_category == "" and music_artist == "": music_category_null = "" spotifycontrol(music_action,music_category_null) elif music_artist == "": spotifycontrol("搜尋播放清單",music_category) elif music_category == "": spotifycontrol("搜尋歌手",music_artist) else: spotifycontrol(music_action,music_category) elif action == "news-broadcast": spotifycontrol("暫停","") new_action = format(response.query_result.parameters['news-action']) new_category = format(response.query_result.parameters['news-category']) if new_category == "頭條": post("頭條") else: print("我不懂") elif action == "translater" translate_action = format(response.query_result.parameters['translate-action']) translate_language = format(response.query_result.parameters['translate-language1']) translate(translate_language) elif action == "input.unknown": speak("我不懂","zh-tw")
def general_conversation(query, txt): dictionary = dict([('who_are_you', ['what', 'name', 'who', 'are', 'you', 'identification']), ('toss_coin', ['heads', 'tails', 'flip', 'toss', 'coin']), ('how_am_i', ['how', 'am', 'i', 'look', 'looking']), ('who_am_i', ['who', 'am', 'i']), ('where_born', ['who', 'made', 'created', 'where', 'born', 'birth']), ('how_are_you', ['how', 'are', 'you']), ('are_you_up', ['you', 'up']), ('love_you', ['love', 'you']), ('marry_me', ['marry', 'me'])]) score = dict([('who_are_you', 0), ('toss_coin', 0), ('how_am_i', 0), ('who_am_i', 0), ('where_born', 0), ('how_are_you', 0), ('are_you_up', 0), ('love_you', 0), ('marry_me', 0)]) words = query.split(' ') for word in words: for keyword in dictionary: for value in dictionary.get(keyword): if word == value: score[keyword] += 1 break max_score = max(score, key=score.get) if score.get(max_score) == 0: speak('I am not sure about this', txt) else: getattr(GeneralConversations, max_score)(query, txt)
def send_email(self, recipient, subject, body): sender = self.email_id receiver = recipient if isinstance(recipient, list) else [recipient] if len(receiver) == 0 or body == '': speak('Please type the message content', self.txt) return self.master.destroy() message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (sender, ", ".join(receiver), subject, body) try: self.server.sendmail(sender, receiver, message) self.server.close() except SMTPRecipientsRefused: speak('Recipient Email ID incorrect', self.txt) except SMTPServerDisconnected: speak('The server could not be reached', self.txt) else: speak('The mail was delivered successfully.', self.txt)
def get_note(txt): con = sqlite3.connect('automate.db') cursor = con.cursor() username = cursor.execute('SELECT * FROM current_user').fetchone()[0] rows = cursor.execute('SELECT * FROM notes WHERE username = "******"').fetchall() if len(rows) == 0: speak('You have no notes', txt) else: speak('Your notes are as follows :', txt) for row in rows: speak(row[1], txt) con.close()
def movie(query, txt): from Settings_Frame import movie_path global movie_count movie_count = 0 search_movie(movie_path.get(), txt) if movie_count == 0: speak('The movies folder is empty.', txt) return while True: try: speak('Select a number', txt) os.startfile(movie_list[int(take_command(txt))]) break except KeyError: speak('Invalid number. Please select a number in the given range.', txt) continue
ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) if time.time() - start_time < 10: for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Draw a rectangle around the faces if time.time() - start_time > 10: for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) speak('file.mp3') start_time = time.time() # Display the resulting frame cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): exit() # When everything is done, release the capture video_capture.release() cv2.destroyAllWindows()
def marry_me(query, txt): speak('I have been receiving a lot of marriage proposals recently.', txt)