Как написать виртуального ассистента

Вы когда-нибудь задумывались, как здорово было бы иметь своего собственного ИИ-ассистента (типа Д.Ж.А.Р.В.И.С.)? Было бы гораздо легче отправлять письма, искать информацию в Википедии, не открывая браузер, и выполнять ещё много других действий с помощью одного только голоса.

В этом уроке мы узнаем, как написать код собственного голосового помощника на Python.

Перед тем, как начать, мы должны определиться, какими функциями должен обладать наш голосовой помощник:

  • Отправка электронных писем
  • Воспроизведение музыки
  • Запросы в Википедию
  • Открытие сайтов, таких как Google, YouTube, Stackoverflow, freecodecamp и т.д. в браузере
  • Открытие редактора кода или IDE одной голосовой командой

И всё это без ручного ввода запросов в браузере!

А теперь приступим, собственно, к написанию нашего помощника.

И да: не забудьте сперва придумать ему имя :з

Настройка среды

Я использую PyCharm, но вы можете выбрать абсолютно любой удобный вам редактор.

Сперва мы импортируем/установим все необходимые библиотеки:

  • pyttsx3;
  • datetime;
  • speech recognition;
  • wikipedia;
  • webbrowser;
  • os.path;
  • smtplib.

Определение функции воспроизведения речи

Интеллектуальному голосовому помощнику прежде всего полагается говорить. Чтобы бот говорил, мы определим функцию speak(), которая принимает на входе аудио и произносит его.

def speak(audio): pass #пока так, позже мы напишем все условия.

Теперь нам нужно аудио, чтобы обеспечить коммуникацию пользователя и ассистента. Для этого мы установим модуль pyttsx3.

Что такое pyttsx3?

Это библиотека Python, которая поможет нам конвертировать текст в устную речь. Она работает оффлайн и доступна как для Python 3, так и для Python 2.

Установка:

pip install pyttsx3

После успешной установки pyttsx3 нужно импортировать модуль в нашу программу.

Использование:

import pyttsx3

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices') #даёт подробности о текущем установленном голосе
engine.setProperty('voice', voice[1].id)  # 0-мужской , 1-женский

Что такое sapi5? Microsoft Speech API (SAPI5) – технология для распознавания и синтеза речи, предоставленная Microsoft.

VoiceId помогает нам выбирать разные голоса:

  • voice[0].idмужской голос
  • voice[1].id = женский голос

[python_ad_block]

Создание функции speak()

def speak(audio):   
engine.say(audio)    
engine.runAndWait() #Без этой команды мы не услышим речь

Создание функции main()

Теперь определим функцию main() и вызовем функцию speak() внутри неё.

if __name__=="__main__" :

speak('Hello Sir, I am Friday, your Artificial intelligence assistant. Please tell me how may I help you')

P.S. Я назову своего ассистента Friday (Пятница).

Всё, что вы передадите функции speak(), будет полностью преобразовано в звук. Поздравляю: наш голосовой помощник обрел свой голос и готов с нами болтать!

Создание функции wishme()

Теперь мы напишем функцию wishme(), благодаря которой наш голосовой помощник будет приветствовать нас разными способами в зависимости от времени на компьютере.

Чтобы предоставить нашему ассистенту информацию о времени, мы должны импортировать модуль datetime, делается это следующей командой:

import datetime

Теперь напишем функцию wishme():

def wishme():
   hour = int(datetime.datetime.now().hour)

Здесь мы сохраняем целочисленное значение текущего часа в переменную hour. Используем это значение в конструкции if-else:

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")    
    
    elif hour>=12 and hour<18:
        speak("Good Afternoon!")       
    
    else:
        speak("Good Evening!")      
   
   speak('Hello Sir, I am Friday, your Artificial intelligence assistant. Please tell me how may I help you')

Определение функции takeCommand():

Следующий важный аспект в нашем помощнике: он должен уметь принимать команду с помощью микрофона нашей системы. Для этого мы создадим функцию takeCommand().

С помощью takeCommand() наш интеллектуальный ассистент сможет возвращать строку, принимая голосовые команды по микрофону.

Но перед определением takeCommand() мы должны установить модуль speechRecognition следующей командой:

pip install speechRecognition

После установки импортируем модуль в программу:

import speechRecognition as sr

Начнём написание функции takeCommand() :

def takeCommand():
    #Принимает на входе аудио от микрофона, возвращает строку с нашими словами    
     r = sr.Recognizer()
     with sr.Microphone() as source:
         print("Listening...")
         r.pause_threshold = 1
         audio = r.listen(source)

Мы успешно создали нашу функцию takeCommand(). Также мы добавим блок try-except для обработки ошибок.

try:
        print("Recognizing...")    
        query = r.recognize_google(audio, language='en-in') #Используем google для распознания голоса.
        print(f"User said: {query}n")  #Запрос пользователя выведен.    
except Exception as e:
        # print(e)  используйте только если хотите видеть ошибку!
        print("Say that again please...")   #будет выведено, если речь не распознаётся
        return "None" #вернётся строка "Пусто"
    return query

А теперь мы наконец-то можем приступить к определению задач для получения необходимой информации.

Задача 1: поиск по Википедии

Чтобы отправлять поисковые запросы в Википедию, мы должны установить и импортировать в нашу программу модуль wikipedia.

Команда для установки:

pip install wikipedia

После установки используем import, чтобы добавить модуль в программу:

if __name__ == "__main__":
    wishMe()
    while True:
        query = takeCommand().lower() #Приведём запрос к нижему регистру        
        # выполнение задач в соответствии с запросом
        if 'wikipedia' in query:  #если wikipedia встречается в запросе, выполнится блок:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=5) 
            speak("According to Wikipedia")
            print(results)
            speak(results)

В коде выше мы использовали if, чтобы проверить, есть ли в запросе пользователя слово «Википедия». Если слово присутствует, помощник прочитает и озвучит с помощью speak() первые 5 предложений из статьи в Википедии (можно поменять число предложений на любое другое).

Задача 2: открыть YouTube в браузере

Для открытия сайтов мы используем модуль webbrowser.

Это встроенный модуль, так что устанавливать его нам не придётся. Остаётся лишь импортировать его.

Код:

elif 'open youtube' in query:
    webbrowser.open("youtube.com")

Здесь мы используем elif, чтобы проверить наличие «YouTube» в запросе. Предположим, что пользователь даёт команду «Открой YouTube». В этом случае условие в elif выполнится и код будет исполнен.

Задача 3: открыть Google-поиск в браузере

elif 'open google' in query:
    webbrowser.open("google.com")

Открытие Google происходит по той же логике, что и с YouTube.

Задача 4: воспроизвести музыку

Чтобы проигрывать музыку, нужно импортировать модуль os:

elif 'play music' in query:
    music_dir = 'директория_с_музыкой'
    songs = os.listdir(music_dir)
    print(songs)    
    os.startfile(os.path.join(music_dir, songs[0]))

В данном коде мы в первую очередь открываем директорию с музыкой пользователя и перечисляем все песни в директории с помощью модуля os.

os.startfile позволяет нам воспроизвести любую нашу песню. Также можно включить случайно выбранную композицию с помощью модуля random. Каждый раз, когда вы будете просить включить музыку, голосовой помощник будет запускать воспроизведение любой песни из указанной папки.

Задача 5: узнать время

elif 'the time' in query:
    strTime = datetime.datetime.now().strftime("%H:%M:%S")    
    speak(f"Sir, the time is {strTime}")

В этом коде мы используем функцию datetime() и сохраняем текущее время в переменной strTime.

После сохранения времени в strTime мы передаем переменную в качестве аргумента в функцию speak(), чтобы там она превратилась в речь.

Задача 6: открыть StackOverflow

elif 'open stack overflow' in query :                           
    webbrowser.open('stackoverflow.com')

Делаем то же самое, что и в случае с Google/Youtube.

Задача 7: открыть freecodecamp

elif 'open free code camp' in query :            
    webbrowser.open('freecodecamp.org')

Делаем то же самое, что и в случае с Google/Youtube.

Задача 8: открыть PyCharm (или другую IDE):

elif 'open code' in query:
    codePath = "/Applications/PyCharm CE.app" #путь к приложению
    os.startfile(codePath)

Чтобы открыть PyCharm или любое другое приложение, нужно указать путь к нему.

Задача 9: отправить email

Чтобы послать электронное письмо, мы импортируем модуль smtplib.

Simple Mail Transfer Protocol (SMTP) — протокол, позволяющий нам отправлять электронные письма и маршрутизировать электронные письма между разными почтовыми серверами.

Метод sendmail представлен в модуле SMTP. Именно этот метод позволяет отправлять письма.

Он принимает 3 параметра:

  • sender: email-адрес отправителя.
  • receiver: email-адрес получателя.
  • message:  строка с сообщением, которую нужно отправить одному или нескольким адресатам.

Теперь мы можем создать функцию sendEmail(), которой мы будем посылать письма.

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'пароль')
    server.sendmail('youremail@gmail.com', 'кому', 'содержание')
    server.close()

Замечание: не забудьте включить опцию ‘ненадёжные приложения, у которых есть доступ к аккаунту’ в вашем Gmail-аккаунте. Иначе функция sendEmail не сработает нужным образом.

Вызываем sendEmail() внутри main():

elif 'email to receiver's name' in query:
    try:
        speak("What should I say?")
        content = takeCommand()
        to = "receiver's email id"    
        sendEmail(to, content)
        speak("Email has been sent!")
    except Exception as e:
        print(e)
        speak("Sorry sir. I am not able to send this email")

Мы используем блок try-except, чтобы обрабатывать все ошибки, которые могут произойти при отправлении писем.

Повторяем изученное

  • Сначала мы создали функцию wishme(), которая предоставляет функционал для приветствия пользователя в соответствии с системным временем.
  • После wishme() мы создали функцию takeCommand(), которая позволяет ассистенту принимать команды пользователя и действовать в соответствии с ними. Эта функция возвращает запрос пользователя в формате строки.
  • Мы проработали логику для открывания различных сайтов: Google, YouTube, Stackoverflow, freecodecamp, Wikipedia.
  • Мы также добавили возможность открывать IDE PyCharm и другие приложения.
  • В конце мы разработали функцию отправки электронных писем (без написания единого слова, разве не круто?)

И тут последует самый противоречивый вопрос…

Можно ли считать это искусственным интеллектом?

Технически нет, ведь этот помощник – всего лишь результат выполнения набора команд. Но если поподробнее разобраться в вопросе, можно узнать, что цель любого ИИ – просто облегчить человеческую работу, выполняя задания с эффективностью человека (или даже лучше).

А наш голосовой помощник в значительной степени решает эту задачу.

Так что финальный вердикт: это ИИ!

Конец!

Мои поздравления: мы успешно создали нашего личного голосового помощника и сделали ещё один шаг навстречу нашей лени!

Надеюсь, статья вам понравилась!

Чтобы лучше понять код, можно зайти в репозиторий автора на GitHub.

Перевод статьи «A guide to your own A.I. Voice Assistant using Python !!».

Big Data, Искусственный интеллект, Python, Data Mining


Рекомендация: подборка платных и бесплатных курсов Python — https://katalog-kursov.ru/

image

Всем привет!

Кто не хочет роскошь иметь помощника, который всегда прислушивается к вашему звонку, предвидит все ваши потребности и при необходимости принимает меры? Эта роскошь теперь доступна благодаря голосовым помощникам на основе искусственного интеллекта.

Голосовые помощники поставляются в небольших упаковках и могут выполнять различные действия, услышав вашу команду. Они могут включать свет, отвечать на вопросы, играть музыку, размещать онлайн-заказы и делать все виды искусственного интеллекта.

Голосовых помощников не следует путать с виртуальными помощниками, которые являются людьми, которые работают удаленно и поэтому могут выполнять все виды задач. Голосовые помощники основаны на технологии. По мере того, как голосовые помощники становятся более надежными, их полезность как в личной, так и в деловой сферах будет расти.

image

Что такое голосовой помощник?

Голосовой помощник или интеллектуальный личный помощник — это программный агент, который может выполнять задачи или услуги для человека на основе словесных команд, то есть путем интерпретации человеческой речи и ответа посредством синтезированных голосов. Пользователи могут задавать вопросы своему помощнику, с помощью устных команд, управлять устройствами домашней автоматизации и воспроизведением мультимедиа с помощью голоса, а также управлять другими основными задачами, такими как электронная почта, списки дел, открывать или закрывать любое приложение и т.д.

Позвольте мне привести вам пример Braina (Brain Artificial), которая является интеллектуальным личным помощником, интерфейсом на человеческом языке, программным обеспечением для автоматизации и распознавания голоса для ПК с Windows. Braina — это многофункциональное программное обеспечение для искусственного интеллекта, которое позволяет вам взаимодействовать с вашим компьютером с помощью голосовых команд на большинстве языков мира. Braina, помимо этого, точно преобразовывает речь в текст на более чем 100 разных языках мира.

История Голосовых Помощников

image

В последнее время голосовые помощники получили основную платформу после того, как Apple интегрировала самый удивительный Virtual Assistant — Siri, который официально является частью Apple Inc. Но график наибольшего развития начался с события 1962 года на выставке в Сиэтле, где IBM представила уникальный аппарат под названием Shoebox. Это был аппарат размером с обувную коробку, он мог выполнять научные функции и мог воспринимать 16 слов, а также произносить их человеческим узнаваемым голосом, и цифры от 0 до 9.

В течение 1970-х годов исследователи из Университета Карнеги-Меллона в Питтсбурге, штат Пенсильвания, при существенной помощи Министерства обороны США и его Агентства перспективных исследований в области обороны (DARPA), создали Harpy. Она могла понимать почти 1000 слов, что примерно соответствует словарному запасу трехлетнего ребенка.

Крупные организации, такие как Apple и IBM, рано, в 90-х годах, начали создавать вещи, использующие голосовое подтверждение. В 1993 году Macintosh начал создавать системы распознавания речи на своих компьютерах Macintosh с PlainTalk.

В апреле 1997 года Dragon NaturallySpeaking был первым продуктом с постоянной диктовкой, который мог охватить около 100 слов и преобразовать его в читаемый контент.

image

После всего вышесказанного, как здорово было бы создать простой голосовой помощник на рабочем столе/ноутбуке, который мог бы:

  • Открыть subreddit в браузере;
  • Открыть любой веб-сайт в браузере;
  • Отправить электронное письмо своим контактам;
  • Запустить любое системное приложение;
  • Сообщить текущую погоду и температуру любого города;
  • Сообщить текущее время;
  • Поприветствовать / завершить работу;
  • Воспроизвести песню на медиаплеере VLC (конечно, на вашем ноутбуке / настольном компьютере должен быть установлен медиаплеер VLC);
  • Изменить обои для рабочего стола;
  • Сообщить вам последние новости из новостной ленты;
  • Рассказать практически обо всем, что вы просите.

Итак, здесь, в этой статье, мы собираемся создать голосовое приложение, способное выполнять все вышеупомянутые задачи. Но сначала, посмотрите это видео, которое я сделал, когда общался со своим настольным голосовым помощником. И я зову ее София.

Надеюсь, вам, ребята, понравилось вышеупомянутое видео, в котором я общался с Софией. Теперь давайте начнем строить эту классную штуку.

Перед началом изучения рекомендую подробнее почитать о голосовых помощниках, а также следить за новостями в моём телеграм-канале Нейрон (@dataisopen), чтобы не пропустить интересные статьи.

Необходимые системные требования: Python 2.7, Spyder IDE, MacOS Mojave (версия 10.14)
Установите все эти библиотеки Python:

pip install SpeechRecognition
pip install beautifulsoup4
pip install vlc
pip install youtube-dl
pip install pyowm
pip install wikipedia

Давайте начнем создавать наш настольный голосовой помощник с Python

Начните с импорта всех необходимых библиотек:

import speech_recognition as sr
import os
import sys
import re
import webbrowser
import smtplib
import requests
import subprocess
from pyowm import OWM
import youtube_dl
import vlc
import urllib
import urllib2
import json
from bs4 import BeautifulSoup as soup
from urllib2 import urlopen
import wikipedia
import random
from time import strftime

Чтобы наш голосовой помощник выполнил все рассмотренные выше функции, мы должны закодировать логику каждой из них одним способом.

Итак, наш первый шаг — создать метод, который будет интерпретировать голосовой ответ пользователя:

def myCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Say something...')
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
    try:
        command = r.recognize_google(audio).lower()
        print('You said: ' + command + 'n')
    #loop back to continue to listen for commands if unrecognizable speech is received
    except sr.UnknownValueError:
        print('....')
        command = myCommand();
    return command

Затем создайте метод, который будет преобразовывать текст в речь:

def sofiaResponse(audio):
    print(audio)
    for line in audio.splitlines():
        os.system("say " + audio)

Теперь создадим цикл, чтобы продолжить выполнение нескольких команд. Внутри метода assistant () передается пользовательская команда (myCommand ()) в качестве параметра:

while True:
    assistant(myCommand())

Наш следующий шаг — создать несколько операторов if, соответствующих каждой функции. Итак, давайте посмотрим, как создать эти небольшие модули внутри оператора if для каждой команды.

1. Открыть subreddit Reddit в браузере

Пользователь даст любую команду, чтобы открыть любой subreddit из Reddit, и команда должна быть «Эй, София! Можешь ли ты open Reddit subreddit_name».То, что выделено жирным курсивом следует использовать как есть. Вы можете использовать любой вид префикса, просто позаботьтесь о том, что выделено жирным.

Как это работает

Если вам удалось произвести open reddit в вашей команде, то она будет искать имя subreddit в пользовательской команде, используя re.search (). Субредит будет найден с помощью www.reddit.com и будет открыт в браузере с помощью модуля pythons Webbrowser. Модуль Webbrowser предоставляет высокоуровневый интерфейс, позволяющий отображать веб-документы для пользователей.

if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        sofiaResponse('The Reddit content has been opened for you Sir.')

Таким образом, приведенный выше код откроет нужный вам Reddit в браузере по умолчанию.

2. Открыть любой веб-сайт в браузере

Вы можете открыть любой веб-сайт, просто сказав «open website.com» или «open website.org».

Например: «Пожалуйста, открой facebook» или «Эй, вы можете открыть linkedin», так вы можете попросить Софию открыть любой веб-сайт.

Как это работает

Если вы сказали слово open в вашей команде, он будет искать имя веб-сайта в команде пользователя с помощью re.search (). Затем он добавит имя веб-сайта к https: // www. и используя модуль веб-браузера, далее полный URL-адрес открывается в браузере.

elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            sofiaResponse('The website you have requested has been opened for you Sir.')
        else:
            pass

3. Отправить e-mail

Вы также можете попросить вашего настольного помощника отправить электронное письмо.

Как это работает

Если вы сказали слово email в своей команде, тогда бот спросит о получателе. Если мой ответ — rajat, бот будет использовать библиотеку pthons smtplib. Модуль smtplib определяет объект сеанса клиента SMTP, который можно использовать для отправки почты на любой компьютер Интернета с демоном прослушивателя SMTP или ESMTP. Отправка почты осуществляется с помощью smtplib Python с использованием SMTP-сервера. Сначала он инициирует SMTP gmail с помощью smtplib.SMTP (), затем идентифицирует сервер с помощью функции ehlo (), затем кодирует сеанс starttls (), затем входит в свой почтовый ящик с помощью login (), затем отправляет сообщение с помощью sendmail ().

elif 'email' in command:
        sofiaResponse('Who is the recipient?')
        recipient = myCommand()
if 'rajat' in recipient:
            sofiaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            sofiaResponse('Email has been sent successfuly. You can check your inbox.')
else:
            sofiaResponse('I don't know what you mean!')

4. Запустить любое системное приложение

Скажите «Открой календарь» или «Можешь, пожалуйста, запустить Skype» или «София, открой Finder» и т.д. И София запустит для вас это системное приложение.

Как это работает

Если вы сказали слово «запуск» в своей команде, он будет искать имя приложения (если оно присутствует в вашей системе) в пользовательской команде, используя re.search (). Затем он добавит суффикс «.app» к имени приложения. Теперь ваше приложение называется, например, calender.app (в macOS исполняемые файлы заканчиваются расширением .app, в отличие от Windows, который заканчивается на .exe). Таким образом, имя исполняемого приложения будет запущено с использованием функции Popen () подпроцесса Python. Модуль подпроцесса позволяет запускать новые приложения из вашей программы Python.

elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)
sofiaResponse('I have launched the desired application')

5. Сообщить текущую погоду и температуру любого города

София также может сказать вам погоду, максимальную и минимальную температуру любого города мира. Пользователь просто должен сказать что-то вроде «какая сейчас погода в Лондоне» или «скажи мне текущую погоду в Дели».

Как это работает

Если вы произнесли фразу текущей погоды в вашей команде, то она будет искать название города с помощью re.search (). Я использовал библиотеку pythons pyowm, чтобы узнать погоду в любом городе. get_status () расскажет вам о погодных условиях, таких как дымка, облачность, дождь и т. д., а get_tempera () расскажет о максимальной и минимальной температуре города.

elif 'current weather' in command:
     reg_ex = re.search('current weather in (.*)', command)
     if reg_ex:
         city = reg_ex.group(1)
         owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
         obs = owm.weather_at_place(city)
         w = obs.get_weather()
         k = w.get_status()
         x = w.get_temperature(unit='celsius')
         sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))

6. Сообщить текущее время

«София, ты можешь сказать мне текущее время?» Или «Который сейчас час?», и София скажет вам текущее время вашего часового пояса.

Как это работает

Довольно просто

elif 'time' in command:
     import datetime
     now = datetime.datetime.now()
     sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))

7. Приветствие / Завершение

Скажите «Здравствуй, София», чтобы поприветствовать своего голосового помощника, или, когда хотите, чтобы программа завершилась, произнесите что-то вроде «Заверши работу, София» или «София, пожалуйста, заверши работу» и т.д.

Как это работает

Если вы сказали слово «привет» в своей команде, то в зависимости от времени суток бот поприветствует пользователя. Если время больше 12 часов, бот ответит «Здравствуйте. Добрый день», а также, если время превышает 6 часов вечера, бот ответит «Здравствуйте. Добрый вечер». И когда вы даете команду как shutdown, вызывается sys.exit () для завершения программы.

#Greet Sofia
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            sofiaResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            sofiaResponse('Hello Sir. Good afternoon')
        else:
            sofiaResponse('Hello Sir. Good evening')
#to terminate the program
elif 'shutdown' in command:
     sofiaResponse('Bye bye Sir. Have a nice day')
     sys.exit()

8. Воспроизведение песни на медиаплеере VLC

Эта функция позволяет вашему голосовому боту воспроизводить желаемую песню в медиаплеере VLC. Пользователь скажет «София, сыграй мне песню», бот спросит: «Какую песню мне сыграть?». Просто скажите название песни, и София загрузит песню с youtube на ваш локальный диск, воспроизведите эту песню на медиаплеере VLC, и если вы снова воспроизведете песню, ранее загруженная песня будет автоматически удалена.

Как это работает

Если вы сказали, что эта фраза воспроизводит мне песню в вашей команде, то она спросит вас, какую видео песню играть. Песня, которую вы попросите, будет найдена на youtube.com. Если найденная песня будет загружена в ваш локальный каталог с помощью библиотеки pythons youtube_dl. Youtube-dl — это программа командной строки для загрузки видео с YouTube.com и нескольких других сайтов. Теперь песня будет воспроизводиться, как только она будет загружена с использованием библиотеки VLC pythons, и модуль play (path_to__videosong) фактически воспроизводит песню.

Теперь, если в следующий раз вы запросите любую другую песню, локальный каталог будет сброшен, и в этот каталог будет загружена новая песня.

elif 'play me a song' in command:
        path = '/Users/nageshsinghchauhan/Documents/videos/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
sofiaResponse('What song shall I play Sir?')
mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')
            response = urllib2.urlopen(url)
            html = response.read()
            soup1 = soup(html,"lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
url = url_list[0]
            ydl_opts = {}
os.chdir(path)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            vlc.play(path)
if flag == 0:
                sofiaResponse('I have not found anything in Youtube ')

9. Изменить обои для рабочего стола

Вы, также можете изменить обои для рабочего стола, используя эту функцию. Когда вы говорите что-то вроде «Поменять обои» или «София, пожалуйста, поменяй обои», бот загрузит случайные обои с unsplash.com и установит их в качестве фона рабочего стола.

Как это работает

Если вы сказали, что фраза изменяет обои в вашей команде, программа загрузит случайные обои с unsplash.com, сохранит их в локальном каталоге и установит их в качестве фонового рисунка рабочего стола, используя subprocess.call (). Я использовал unsplash API, чтобы получить доступ к его содержимому.

Теперь, если в следующий раз вы попросите изменить обои снова, ваш локальный каталог будет сброшен, и новые обои будут загружены в этот каталог.

elif 'change wallpaper' in command:
        folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib2.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        sofiaResponse('wallpaper changed successfully')

10. Сообщить последние новости из новостной ленты

София также может рассказать вам последние новости. Пользователь просто должен сказать «София, какие новости сегодня самые популярные?» Или «Скажите мне новости на сегодня».

Как это работает

Если вы произвели фразу «новости за сегодня» в своей команде, то она соскребет данные с помощью Beautiful Soup из RSS Новостей Google () и прочитает ее для вас. Для удобства я установил ограничение на количество новостей до 15.

elif 'news for today' in command:
        try:
            news_url="https://news.google.com/news/rss"
            Client=urlopen(news_url)
            xml_page=Client.read()
            Client.close()
            soup_page=soup(xml_page,"xml")
            news_list=soup_page.findAll("item")
            for news in news_list[:15]:
                sofiaResponse(news.title.text.encode('utf-8'))
        except Exception as e:
                print(e)

11. Рассказать практически обо всем, что вы спрашиваете

Ваш бот может получить подробную информацию практически обо всем, что вы у нее спросите. Например, «София расскажи мне о Google» или «Пожалуйста, расскажи мне о суперкомпьютерах» или «Пожалуйста, расскажи мне об Интернете». Итак, как вы можете видеть, вы можете спросить о чем угодно.

Как это работает

Если вы сказали фразу «расскажите мне» в своей команде, то она будет искать ключевое слово в пользовательской команде, используя re.search (). Используя библиотеку pythons wikipedia, она будет искать эту тему и извлекать первые 500 символов (если вы не укажете ограничение, бот будет читать всю страницу за вас). Википедия — это библиотека Python, которая позволяет легко получать и анализировать данные из Википедии.

elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
                sofiaResponse(e)

Давайте сложим все вместе:

import speech_recognition as sr
import os
import sys
import re
import webbrowser
import smtplib
import requests
import subprocess
from pyowm import OWM
import youtube_dl
import vlc
import urllib
import urllib2
import json
from bs4 import BeautifulSoup as soup
from urllib2 import urlopen
import wikipedia
import random
from time import strftime
def sofiaResponse(audio):
    "speaks audio passed as argument"
    print(audio)
    for line in audio.splitlines():
        os.system("say " + audio)
def myCommand():
    "listens for commands"
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Say something...')
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
    try:
        command = r.recognize_google(audio).lower()
        print('You said: ' + command + 'n')
    #loop back to continue to listen for commands if unrecognizable speech is received
    except sr.UnknownValueError:
        print('....')
        command = myCommand();
    return command
def assistant(command):
    "if statements for executing commands"
#open subreddit Reddit
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        sofiaResponse('The Reddit content has been opened for you Sir.')
elif 'shutdown' in command:
        sofiaResponse('Bye bye Sir. Have a nice day')
        sys.exit()
#open website
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            sofiaResponse('The website you have requested has been opened for you Sir.')
        else:
            pass
#greetings
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            sofiaResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            sofiaResponse('Hello Sir. Good afternoon')
        else:
            sofiaResponse('Hello Sir. Good evening')
elif 'help me' in command:
        sofiaResponse("""
        You can use these commands and I'll help you out:
1. Open reddit subreddit : Opens the subreddit in default browser.
        2. Open xyz.com : replace xyz with any website name
        3. Send email/email : Follow up questions such as recipient name, content will be asked in order.
        4. Current weather in {cityname} : Tells you the current condition and temperture
        5. Hello
        6. play me a video : Plays song in your VLC media player
        7. change wallpaper : Change desktop wallpaper
        8. news for today : reads top news of today
        9. time : Current system time
        10. top stories from google news (RSS feeds)
        11. tell me about xyz : tells you about xyz
        """)
#joke
    elif 'joke' in command:
        res = requests.get(
                'https://icanhazdadjoke.com/',
                headers={"Accept":"application/json"})
        if res.status_code == requests.codes.ok:
            sofiaResponse(str(res.json()['joke']))
        else:
            sofiaResponse('oops!I ran out of jokes')
#top stories from google news
    elif 'news for today' in command:
        try:
            news_url="https://news.google.com/news/rss"
            Client=urlopen(news_url)
            xml_page=Client.read()
            Client.close()
            soup_page=soup(xml_page,"xml")
            news_list=soup_page.findAll("item")
            for news in news_list[:15]:
                sofiaResponse(news.title.text.encode('utf-8'))
        except Exception as e:
                print(e)
#current weather
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))
#time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))
elif 'email' in command:
        sofiaResponse('Who is the recipient?')
        recipient = myCommand()
        if 'rajat' in recipient:
            sofiaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            sofiaResponse('Email has been sent successfuly. You can check your inbox.')
        else:
            sofiaResponse('I don't know what you mean!')
#launch any application
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)
sofiaResponse('I have launched the desired application')
#play youtube song
    elif 'play me a song' in command:
        path = '/Users/nageshsinghchauhan/Documents/videos/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
sofiaResponse('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')
            response = urllib2.urlopen(url)
            html = response.read()
            soup1 = soup(html,"lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
url = url_list[0]
            ydl_opts = {}
os.chdir(path)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            vlc.play(path)
if flag == 0:
                sofiaResponse('I have not found anything in Youtube ')
#change wallpaper
    elif 'change wallpaper' in command:
        folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib2.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        sofiaResponse('wallpaper changed successfully')
#askme anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
                print(e)
                sofiaResponse(e)
sofiaResponse('Hi User, I am Sofia and I am your personal voice assistant, Please give a command or say "help me" and I will tell you what all I can do for you.')
#loop to continue executing multiple commands
while True:
    assistant(myCommand())

Итак, вы видели, как, просто написав простые строки кода на Python, мы можем создать очень классного голосового помощника для компьютера. Помимо этих функций, вы также можете включить множество различных функций в свой голосовой помощник.

Вывод

Что ждет нас в будущем, на протяжении всей истории вычислений пользовательские интерфейсы стали все более естественными в использовании. Экран и клавиатура были одним шагом в этом направлении. Мышь и графический интерфейс пользователя были другими. Сенсорные экраны являются самой последней разработкой. Следующий шаг, скорее всего, будет состоять из смеси дополненной реальности, жестов и голосовых команд. В конце концов, часто легче задать вопрос или поговорить, чем набрать что-то или ввести несколько деталей в онлайн-форме.

Чем больше человек взаимодействует с устройствами, активируемыми голосом, тем больше трендов и паттернов, которые система идентифицирует на основе получаемой информации. Затем эти данные можно использовать для определения пользовательских предпочтений и вкусов, что является долгосрочным преимуществом для того, чтобы сделать дом умнее. Google и Amazon стремятся интегрировать голосовой искусственный интеллект, способный анализировать человеческие эмоции и реагировать на них.

Надеюсь, вам понравилось читать эту статью. Поделитесь своими мыслями/комментариями/сомнениями в разделе комментариев.

Всем знаний!

Голосовой бот с искусственным интеллектом на Python

18 февраля 2022 Python

В этом руководстве разберем создание голосового бота использующего технологии нейронных сетей на языке Python. Бот может распознавать человеческий голос в реальном времени с вашего устройства, например с микрофона ноутбука, и произносить осознанные ответы, которые обрабатывает нейронная сеть.

Бот состоит из двух основных частей: это часть обрабатывающая словарь и часть с голосовым ассистентом.

Всю разработку по написанию бота вы можете вести в IDE PyCharm, скачать можно с официального сайта JetBrains.

Все необходимые библиотеки можно установить с помощью PyPI прямо в консоле PyCharm. Команды для установки вы можете найти на официальном сайте в разделе нужной библиотеки.

Официальный сайт PyPI

Проблема возникла только с библиотекой PyAudio в Windows. Помогло следующее решение:

pip install pipwin
pipwin install pyaudio

Дата-сет

Дата-сет — это набор данных для анализа. В нашем случае это будет некий текстовый файл содержащий строки в виде вопросответ.

Все строки текста перебираются с помощью функции for, при этом из текста удаляются все ненужные символы по маске, находящейся в переменной alphabet. Каждое значение строки раздельно заносится в массив dataset.

После обработки текста все его значения преобразуются в вектора с помощью библиотеки для машинного обучения Scikit-learn. В этом примере используется функция CountVectorizer(). Далее всем векторам присваивается класс с помощью классификатора LogisticRegression().

Когда приходит сообщение от пользователя оно так же преобразуется в вектор, и далее нейросеть пытается найти похожий вектор в датасете соответствующий какому-то вопросу, когда вектор найден, мы получим ответ.

Голосовой ассистент

Для распознавания голоса и озвучивания ответов бота, используется библиотека SpeechRecognition. Система ждет в бесконечном цикле, когда придет вопрос, в нашем случае голос с микрофона, после чего преобразует его в текст и отправляет на обработку в нейросеть. После получения текстового ответа он преобразуется в речь, запись сохраняется в папке с проектом и удаляется после воспроизведения. Вот так все просто! Для удобства все сообщения дублируются текстом в консоль.

При дефолтных настройках время ответа было достаточно долгим, иногда нужно было ждать по 15-30 сек. К тому же вопрос принимался от малейшего шума. Помогли следующие настройки:

voice_recognizer.dynamic_energy_threshold = False
voice_recognizer.energy_threshold = 1000
voice_recognizer.pause_threshold = 0.5

И timeout = None, phrase_time_limit = 2 в функции listen()

После чего бот стал отвечать с минимальной задержкой.

Возможно вам подойдут другие значения. Описание этих и других настроек вы можете посмотреть все на том же сайте PyPI в разделе библиотеки SpeechRecognition. Но настройку phrase_time_limit я там почему-то не нашел, наткнулся на нее случайно в Stack Overflow.

Текст дата-сета

Это небольшой пример текста. Конечно же вопросов и ответов должно быть гораздо больше.

приветпривет
как делавсё прекрасно
как деласпасибо отлично
кто тыя бот
что делаешьс тобой разговариваю

Код Python

import speech_recognition as sr
from gtts import gTTS
import playsound
import os
import random
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression

# Словарь
def clean_str(r):
    r = r.lower()
    r = [c for c in r if c in alphabet]
    return ''.join(r)

alphabet = ' 1234567890-йцукенгшщзхъфывапролджэячсмитьбюёqwertyuiopasdfghjklzxcvbnm'

with open('dialogues.txt', encoding='utf-8') as f:
    content = f.read()

blocks = content.split('n')

dataset = []

for block in blocks:
    replicas = block.split('\')[:2]
    if len(replicas) == 2:
        pair = [clean_str(replicas[0]), clean_str(replicas[1])]
        if pair[0] and pair[1]:
            dataset.append(pair)

X_text = []
y = []
for question, answer in dataset[:10000]:
    X_text.append(question)
    y += [answer]

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(X_text)

clf = LogisticRegression()
clf.fit(X, y)

def get_generative_replica(text):
    text_vector = vectorizer.transform([text]).toarray()[0]
    question = clf.predict([text_vector])[0]

    return question

# Голосовой ассистент
def listen():
    voice_recognizer = sr.Recognizer()
    voice_recognizer.dynamic_energy_threshold = False
    voice_recognizer.energy_threshold = 1000
    voice_recognizer.pause_threshold = 0.5

    with sr.Microphone() as source:
        print("Говорите 🎤")
        audio = voice_recognizer.listen(source, timeout = None, phrase_time_limit = 2)
    try:
        voice_text = voice_recognizer.recognize_google(audio, language="ru")
        print(f"Вы сказали: {voice_text}")
        return voice_text
    except sr.UnknownValueError:
        return "Ошибка распознания"
    except sr.RequestError:
        return "Ошибка соединения"

def say(text):
    voice = gTTS(text, lang="ru")
    unique_file = "audio_" + str(random.randint(0, 10000)) + ".mp3"
    voice.save(unique_file)

    playsound.playsound(unique_file)
    os.remove(unique_file)

    print(f"Бот:  {text}")

def handle_command(command):
    command = command.lower()

    reply = get_generative_replica(command)
    say(reply)

def stop():
    say("Пока")

def start():
    print(f"Запуск бота...")

    while True:
        command = listen()
        handle_command(command)

try:
    start()
except KeyboardInterrupt:
    stop()
Работа бота в PyCharm

Пример одного из самых популярных голосовых помощников — это яндекс алиса.

Introduction: How to Make a GUI Virtual Assistant

Millions of people around the world use virtual assistants like google assistant, Siri, Alexa, Bixby etc……..

There a lot of tutorials out there in the internet which teach people how to make their own virtual assistants with just a few lines of code.

But most of them are virtual assistants that run in the console and if you ask me those are quiet boring.

So today I will show you how to make a virtual assistant with a Graphical User Interface (GUI).

A few Prerequisites are:

1] Basic knowledge of python syntax

2] A laptop/desktop which has a microphone and a speaker

Note: 1] I am also a beginner programmer who just started learning 6 months ago. So if you find anyway to improve my code please tell me.

2] This Virtual Assistant will NOT be A.I integrated. You just tell it to do something and it does it So let’s get started

3] Please download the starter file attached below

If you want to see a demo watch the youtube link given below.

Supplies

Step 1: Installing Necessary Packages

First of all you need to install python. I am using Python 3.9, but Python 3.X or higher might do.

Then we have to install a few packages using pip.

The first one is pyttsx3. to install it just type

pip install pyttsx3 

in your command prompt. I will show how you can do that in windows.

Just click the search icon on the taskbar and type ‘cmd’ as shown above.

Then a few more packages are

pip install SpeechRecognition 
pip install wikipedia 
pip install pyjokes 
pip install playsound 

There are many more modules that we will use but those are already built in to python.

Step 2: Importing the Modules

import speech_recognition as sr    #To convert speech into text
import pyttsx3                     #To convert text into speech
import datetime                    #To get the date and time
import wikipedia                   #To get information from wikipedia
import webbrowser                  #To open websites
import os                          #To open files
import time                        #To calculate time
import subprocess                  #To open files
from tkinter import *              #For the graphics
import pyjokes                     #For jokes
from playsound import playsound    #To play sounds
import keyboard                    #To add keyboard activation  

Note:

A lot of these modules have overlapping uses. So you can get rid of the ones you don’t want, but I like it this way

Step 3: Converting Text Into Speech

As mentioned before we will be using pyttsx3 to do this

Before writing the function to do this we have to assign a few variables.

name_assistant = "Cortana" #The name of the assistant


engine = pyttsx3.init('sapi5')   #'sapi5' is the argument you have to use for windows, I am not sure what it is for Mac and Linux
voices = engine.getProperty('voices')  #To get the voice
engine.setProperty('voice', voices[1].id) #defines the gender of the voice. 


# Note: voices[1].id sets it to female and voices[0].id sets it to male
<br>
<br>

Later we will add a feature to change the assistant’s name, but for now lets keep it like this.

Now let’s write the speak() function

def speak(text):
    engine.say(text)
    print(name_assistant + " : "  +  text)
    engine.runAndWait()

It’s pretty self explanatory

Now you can type any thing in the speak function and the assistant will tell it out loud. But remember to put it in inverted commas

Step 4: A Wishing Feature

Now we are going to add a feature where the assistant will wish you when you open the program.

Normally its as simple as speak(«Hello»). But we’re going to do it a bit differently.

The assistant is going to wish ‘Hello Good Morning’. The problem with this is that it can’t wish good morning in the evening. So we have to assign a function.

This is where we are going to use the datetime module. In this evening is defined as after 6:00 p.m.

And afternoon is defined as after 12:00 p.m

The function looks like this:

def wishMe():
    hour=datetime.datetime.now().hour
    if hour>=0 and hour<12:
        speak("Hello,Good Morning")
   
    elif hour>=12 and hour<18:  # This uses the 24 hour system so 18 is actually 6 p.m 
        speak("Hello,Good Afternoon")
 
    else:
        speak("Hello,Good Evening")<br>

This function is also very intuitive.

And remember you have to call the function or else nothing will work

wishMe()

Step 5: What’s Todays Date

This function is a bit tedious because we have to write a list containing all the months and all the ordinal dates. To save the trouble for you I will just paste them here.

month_names = ['Janameary', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] <br>

The function contains a variable for months and a variable for days both are which are later converted into integer values to pick out dates and months from the lists above.

def date():
    now = datetime.datetime.now()
    my_date = datetime.datetime.today()

    month_name = now.month
    day_name = now.day
    month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] 
    

    speak("Today is "+ month_names[month_name-1] +" " + ordinalnames[day_name-1] + '.')<br>

You might ask why there is a -1 when we start picking out elements from the list. That is because The numbering for python lists start from 0 not 1. So we have to account for the extra 0th term.

Now if you call this function the assistant will tell you the date.

date()

Step 6: Make a Note

This is a rather useful feature which will make quick notes and reminders for you.

def note(text):
    date = datetime.datetime.now()
    file_name = str(date).replace(":", "-") + "-note.txt"
    with open(file_name, "w") as f:
        f.write(text)

    subprocess.Popen(["notepad.exe", file_name])

The file’s name will have the date and time in it. It will be stored in the same directory as your file.

The code is also quite simple. This is the only function in which the subprocess module will be used

To test it out just type:

note("Remind me to buy groceries")

and it works like a charm.

Step 7: Getting User Input

To achieve this we are going to use the speech recognition module.

def get_audio(): 

    r = sr.Recognizer() 
    audio = '' 

    with sr.Microphone() as source: 

        print("Listening") 
        playsound("assistant_on.wav")
        audio = r.listen(source, phrase_time_limit = 3) 
        playsound("assistant_off.wav")
        print("Stop.") 
        
    try: 
        text = r.recognize_google(audio, language ='en-US') 
        print('You: ' + ': '+ text)
        return text


    except:

        return "None"<br>

I will attach the two audio files. To call this function you have to do as shown below

text = get_audio()
print(text)

And it works.

Step 8: The Fun Part

Now get rid of all the functions you have called except the wishMe function.(Don’t delete the whole function)

Now this is the fun part where you tell your Assistant to do stuff for you

How to do this??

It’s simple you have to define a variable to the get_audio function and then check whether a few words are there in the variable and if it is there the assistant will have to speak or do something.

I have put all this under a function. So that it is easier to access later.

def Process_audio():

    run = 1
    if __name__=='__main__':
        while run==1:

            app_string = ["open word", "open powerpoint", "open excel", "open zoom","open notepad",  "open chrome"]
            app_link = [r'Microsoft Office Word 2007.lnk',r'Microsoft Office PowerPoint 2007.lnk', r'Microsoft Office Excel 2007.lnk', r'Zoom.lnk', r'Notepad.lnk', r'Google Chrome.lnk' ]
            app_dest = r'C:UsersshrirakshaAppDataRoamingMicrosoftWindowsStart MenuPrograms' # Write the location of your file

            statement = get_audio().lower()
            results = ''
            run +=1

            if "hello" in statement or "hi" in statement:

              wishMe()               


            if "good bye" in statement or "ok bye" in statement or "stop" in statement:
                speak('Your personal assistant ' + name_assistant +' is shutting down, Good bye')
                screen.destroy()
                break

            if 'wikipedia' in statement:
              try:


                speak('Searching Wikipedia...')
                statement = statement.replace("wikipedia", "")
                results = wikipedia.summary(statement, sentences = 3)
                speak("According to Wikipedia")
                wikipedia_screen(results)
              except:
                speak("Error")


            if 'joke' in statement:
              speak(pyjokes.get_joke())    
     
            if 'open youtube' in statement:
                webbrowser.open_new_tab("https://www.youtube.com")
                speak("youtube is open now")
                time.sleep(5)


            if 'open google' in statement:
                    webbrowser.open_new_tab("https://www.google.com")
                    speak("Google chrome is open now")
                    time.sleep(5)


            if 'open gmail' in statement:
                    webbrowser.open_new_tab("mail.google.com")
                    speak("Google Mail open now")
                    time.sleep(5)

            if 'open netflix' in statement:
                    webbrowser.open_new_tab("netflix.com/browse") 
                    speak("Netflix open now")


            if 'open prime video' in statement:
                    webbrowser.open_new_tab("primevideo.com") 
                    speak("Amazon Prime Video open now")
                    time.sleep(5)

            if app_string[0] in statement:
                os.startfile(app_dest + app_link[0])

                speak("Microsoft office Word is opening now")

            if app_string[1] in statement:
                os.startfile(app_dest + app_link[1])
                speak("Microsoft office PowerPoint is opening now")

            if app_string[2] in statement:
                os.startfile(app_dest + app_link[2])
                speak("Microsoft office Excel is opening now")
        
            if app_string[3] in statement:

                os.startfile(app_dest + app_link[3])
                speak("Zoom is opening now")


            if app_string[4] in statement:
                os.startfile(app_dest + app_link[4])
                speak("Notepad is opening now")
        
            if app_string[5] in statement:
                os.startfile(app_dest + app_link[5])
                speak("Google chrome is opening now")
                       

            if 'news' in statement:
                news = webbrowser.open_new_tab("https://timesofindia.indiatimes.com/city/mangalore")
                speak('Here are some headlines from the Times of India, Happy reading')
                time.sleep(6)

            if 'cricket' in statement:
                news = webbrowser.open_new_tab("cricbuzz.com")
                speak('This is live news from cricbuzz')
                time.sleep(6)

            if 'corona' in statement:
                news = webbrowser.open_new_tab("https://www.worldometers.info/coronavirus/")
                speak('Here are the latest covid-19 numbers')
                time.sleep(6)

            if 'time' in statement:
                strTime=datetime.datetime.now().strftime("%H:%M:%S")
                speak(f"the time is {strTime}")

            if 'date' in statement:
                date()

            if 'who are you' in statement or 'what can you do' in statement:
                    speak('I am '+name_assistant+' your personal assistant. I am programmed to minor tasks like opening youtube, google chrome, gmail and search wikipedia etcetra') 


            if "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
                speak("I was built by Abhhi  Sannayya")

            
            if 'make a note' in statement:
                statement = statement.replace("make a note", "")
                note(statement)


            if 'note this' in statement:    
                statement = statement.replace("note this", "")
                note(statement)         

            speak(results)

I will explain a few things and clear somethings up in the next step.

Step 9: Graphical User Interface

I had promised at the beginning of the tutorial that this would not be a boring console assistant. But one with a User interface. We are going to add that right now.

To do this we are going to use tkinter a built in GUI module for python

To understand this better please watch a few tkinter tutorials on youtube.

Write the following code

We will add stuff to the functions later

def change_name():
     pass

def change():
     pass

def info():
     pass
def main_screen():

      global screen
      screen = Tk()
      screen.title(name_assistant)
      screen.geometry("100x250")
      screen.iconbitmap('app_icon.ico')


      name_label = Label(text = name_assistant,width = 300, bg = "black", fg="white", font = ("Calibri", 13))
      name_label.pack()


      microphone_photo = PhotoImage(file = "assistant_logo.png")
      microphone_button = Button(image=microphone_photo, command = Process_audio)
      microphone_button.pack(pady=10)

      settings_photo = PhotoImage(file = "settings.png")
      settings_button = Button(image=settings_photo, command = change_name_window)
      settings_button.pack(pady=10)
       
      info_button = Button(text ="Info", command = info)
      info_button.pack(pady=10)

      screen.mainloop()
    

  

Now you should get a screen that looks like the one above.

You probably got a working GUI now and if you press the star button, you can ask your virtual assistant anything

Step 10: Changing the Name of the Virtual Assistant

This is a feature you won’t find in most other virtual assistants. Each assistant has its own fixed name.

But i don’t like that a whole lot.

So our virtual assistant has the capability to change it’s name.

To do this we have to fill in those functions we defined earlier.

I won’t explain much of this code but if you don’t understand it please watch a few tkinter tutorials

def change_name():

  name_info = name.get()

  file=open("Assistant_name", "w")

  file.write(name_info)

  file.close()

  settings_screen.destroy()

  screen.destroy()


def change_name_window():
    
      global settings_screen
      global name


      settings_screen = Toplevel(screen)
      settings_screen.title("Settings")
      settings_screen.geometry("300x300")
      settings_screen.iconbitmap('app_icon.ico')

      
      name = StringVar()

      current_label = Label(settings_screen, text = "Current name: "+ name_assistant)
      current_label.pack()

      enter_label = Label(settings_screen, text = "Please enter your Virtual Assistant's name below") 
      enter_label.pack(pady=10)   
      

      Name_label = Label(settings_screen, text = "Name")
      Name_label.pack(pady=10)
     
      name_entry = Entry(settings_screen, textvariable = name)
      name_entry.pack()


      change_name_button = Button(settings_screen, text = "Ok", width = 10, height = 1, command = change_name)
      change_name_button.pack(pady=10)

For this to work you have to create an empty file called ‘Assistant_name’. Again I recommend you to watch a few youtube tutorials

And now if you press the cogwheel a new window will pop up prompting you to change the Assistants name.

Step 11: Wikipedia

Right now the wikipedia feature might not work a whole lot right because I forgot to define the wikipedia function. This is a function that displays whatever the assistant told onto the screen. Here is the code.

def wikipedia_screen(text):


  wikipedia_screen = Toplevel(screen)
  wikipedia_screen.title(text)
  wikipedia_screen.iconbitmap('app_icon.ico')

  message = Message(wikipedia_screen, text= text)
  message.pack()

Step 12: An Info Page

This is relatively simple you just have to fill in the info function we defined earlier

def info():

  info_screen = Toplevel(screen)
  info_screen.title("Info")
  info_screen.iconbitmap('app_icon.ico')

  creator_label = Label(info_screen,text = "Created by Abhhi Sannayya")
  creator_label.pack()

  Age_label = Label(info_screen, text= " at the age of 12")
  Age_label.pack()

  for_label = Label(info_screen, text = "For Makerspace")
  for_label.pack()

So now you have a completely working Virtual assistant. Ain’t that cool

Step 13: Adding Keyboard Activation

I want to add the feature in which if you press a button, the voice assistant will get activated. We do this using the keyboard module. I thought we can use the f4 function key to do the job

keyboard.add_hotkey("F4", Process_audio)

This way you don’t have to press the GUI button.

Step 14: Finishing Off

I will give you the whole code here. I highly recommend you not to just copy and paste the code but understand what it is that you are typing.

import speech_recognition as sr    #To convert speech into text
import pyttsx3                     #To convert text into speech
import datetime                    #To get the date and time
import wikipedia                   #To get information from wikipedia
import webbrowser                  #To open websites
import os                          #To open files
import time                        #To calculate time
import subprocess                  #To open files
from tkinter import *              #For the graphics
import pyjokes                     #For some really bad jokes
from playsound import playsound    #To playsound
import keyboard                    #To get keyboard
  
name_file = open("Assistant_name", "r")
name_assistant = name_file.read()

engine = pyttsx3.init('sapi5')  
voices = engine.getProperty('voices')  
engine.setProperty('voice', voices[1].id)
    
def speak(text):
    engine.say(text)
    print(name_assistant + " : "  +  text)
    engine.runAndWait() 


def wishMe():


  hour=datetime.datetime.now().hour

  if hour >= 0 and hour < 12:

      speak("Hello,Good Morning")
 
  elif hour >= 12 and hour < 18:

      speak("Hello,Good Afternoon")

  else:

      speak("Hello,Good Evening")


def get_audio(): 

    r = sr.Recognizer() 
    audio = '' 

    with sr.Microphone() as source: 

        print("Listening") 
        playsound("assistant_on.wav")
        audio = r.listen(source, phrase_time_limit = 3) 
        playsound("assistant_off.wav")
        print("Stop.") 
        
    try: 
        text = r.recognize_google(audio, language ='en-US') 
        print('You: ' + ': ' + text)
        return text


    except:

        return "None"


def note(text):
    date = datetime.datetime.now()
    file_name = str(date).replace(":", "-") + "-note.txt"

    with open(file_name, "w") as f:
        f.write(text)

    subprocess.Popen(["notepad.exe", file_name])


def date():
    now = datetime.datetime.now()
    month_name = now.month
    day_name = now.day
    month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] 

    speak("Today is "+ month_names[month_name-1] +" " + ordinalnames[day_name-1] + '.')

wishMe()


def Process_audio():

    run = 1
    if __name__=='__main__':
        while run==1:

            app_string = ["open word", "open powerpoint", "open excel", "open zoom","open notepad",  "open chrome"]
            app_link = [r'Microsoft Office Word 2007.lnk',r'Microsoft Office PowerPoint 2007.lnk', r'Microsoft Office Excel 2007.lnk', r'Zoom.lnk', r'Notepad.lnk', r'Google Chrome.lnk' ]
            app_dest = r'C:UsersshrirakshaAppDataRoamingMicrosoftWindowsStart MenuPrograms'

            statement = get_audio().lower()
            results = ''
            run +=1

            if "hello" in statement or "hi" in statement:

              wishMe()               


            if "good bye" in statement or "ok bye" in statement or "stop" in statement:
                speak('Your personal assistant ' + name_assistant +' is shutting down, Good bye')
                screen.destroy()
                break

            if 'wikipedia' in statement:
              try:


                speak('Searching Wikipedia...')
                statement = statement.replace("wikipedia", "")
                results = wikipedia.summary(statement, sentences = 3)
                speak("According to Wikipedia")
                wikipedia_screen(results)
              except:
                speak("Error")


            if 'joke' in statement:
              speak(pyjokes.get_joke())    
     
            if 'open youtube' in statement:
                webbrowser.open_new_tab("https://www.youtube.com")
                speak("youtube is open now")
                time.sleep(5)


            if 'open google' in statement:
                    webbrowser.open_new_tab("https://www.google.com")
                    speak("Google chrome is open now")
                    time.sleep(5)


            if 'open gmail' in statement:
                    webbrowser.open_new_tab("mail.google.com")
                    speak("Google Mail open now")
                    time.sleep(5)

            if 'open netflix' in statement:
                    webbrowser.open_new_tab("netflix.com/browse") 
                    speak("Netflix open now")


            if 'open prime video' in statement:
                    webbrowser.open_new_tab("primevideo.com") 
                    speak("Amazon Prime Video open now")
                    time.sleep(5)

            if app_string[0] in statement:
                os.startfile(app_dest + app_link[0])

                speak("Microsoft office Word is opening now")

            if app_string[1] in statement:
                os.startfile(app_dest + app_link[1])
                speak("Microsoft office PowerPoint is opening now")

            if app_string[2] in statement:
                os.startfile(app_dest + app_link[2])
                speak("Microsoft office Excel is opening now")
        
            if app_string[3] in statement:

                os.startfile(app_dest + app_link[3])
                speak("Zoom is opening now")


            if app_string[4] in statement:
                os.startfile(app_dest + app_link[4])
                speak("Notepad is opening now")
        
            if app_string[5] in statement:
                os.startfile(app_dest + app_link[5])
                speak("Google chrome is opening now")
                       

            if 'news' in statement:
                news = webbrowser.open_new_tab("https://timesofindia.indiatimes.com/city/mangalore")
                speak('Here are some headlines from the Times of India, Happy reading')
                time.sleep(6)

            if 'cricket' in statement:
                news = webbrowser.open_new_tab("cricbuzz.com")
                speak('This is live news from cricbuzz')
                time.sleep(6)

            if 'corona' in statement:
                news = webbrowser.open_new_tab("https://www.worldometers.info/coronavirus/")
                speak('Here are the latest covid-19 numbers')
                time.sleep(6)

            if 'time' in statement:
                strTime=datetime.datetime.now().strftime("%H:%M:%S")
                speak(f"the time is {strTime}")

            if 'date' in statement:
                date()

            if 'who are you' in statement or 'what can you do' in statement:
                    speak('I am '+name_assistant+' your personal assistant. I am programmed to minor tasks like opening youtube, google chrome, gmail and search wikipedia etcetra') 


            if "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
                speak("I was built by Abhhi  Sannayya")

            
            if 'make a note' in statement:
                statement = statement.replace("make a note", "")
                note(statement)


            if 'note this' in statement:    
                statement = statement.replace("note this", "")
                note(statement)         

            speak(results)


def change_name():

  name_info = name.get()

  file=open("Assistant_name", "w")

  file.write(name_info)

  file.close()

  settings_screen.destroy()

  screen.destroy()


def change_name_window():
    
      global settings_screen
      global name


      settings_screen = Toplevel(screen)
      settings_screen.title("Settings")
      settings_screen.geometry("300x300")
      settings_screen.iconbitmap('app_icon.ico')

      
      name = StringVar()

      current_label = Label(settings_screen, text = "Current name: "+ name_assistant)
      current_label.pack()

      enter_label = Label(settings_screen, text = "Please enter your Virtual Assistant's name below") 
      enter_label.pack(pady=10)   
      

      Name_label = Label(settings_screen, text = "Name")
      Name_label.pack(pady=10)
     
      name_entry = Entry(settings_screen, textvariable = name)
      name_entry.pack()


      change_name_button = Button(settings_screen, text = "Ok", width = 10, height = 1, command = change_name)
      change_name_button.pack(pady=10)


def info():

  info_screen = Toplevel(screen)
  info_screen.title("Info")
  info_screen.iconbitmap('app_icon.ico')

  creator_label = Label(info_screen,text = "Created by Abhhi Sannayya")
  creator_label.pack()

  Age_label = Label(info_screen, text= " at the age of 12")
  Age_label.pack()

  for_label = Label(info_screen, text = "For Makerspace")
  for_label.pack()

keyboard.add_hotkey("F4", Process_audio)


def wikipedia_screen(text):


  wikipedia_screen = Toplevel(screen)
  wikipedia_screen.title(text)
  wikipedia_screen.iconbitmap('app_icon.ico')

  message = Message(wikipedia_screen, text= text)
  message.pack()



def main_screen():

      global screen
      screen = Tk()
      screen.title(name_assistant)
      screen.geometry("100x250")
      screen.iconbitmap('app_icon.ico')


      name_label = Label(text = name_assistant,width = 300, bg = "black", fg="white", font = ("Calibri", 13))
      name_label.pack()


      microphone_photo = PhotoImage(file = "assistant_logo.png")
      microphone_button = Button(image=microphone_photo, command = Process_audio)
      microphone_button.pack(pady=10)

      settings_photo = PhotoImage(file = "settings.png")
      settings_button = Button(image=settings_photo, command = change_name_window)
      settings_button.pack(pady=10)
       
      info_button = Button(text ="Info", command = info)
      info_button.pack(pady=10)

      screen.mainloop()


main_screen()

Thank you.

Be the First to Share

Recommendations

Introduction: How to Make a GUI Virtual Assistant

Millions of people around the world use virtual assistants like google assistant, Siri, Alexa, Bixby etc……..

There a lot of tutorials out there in the internet which teach people how to make their own virtual assistants with just a few lines of code.

But most of them are virtual assistants that run in the console and if you ask me those are quiet boring.

So today I will show you how to make a virtual assistant with a Graphical User Interface (GUI).

A few Prerequisites are:

1] Basic knowledge of python syntax

2] A laptop/desktop which has a microphone and a speaker

Note: 1] I am also a beginner programmer who just started learning 6 months ago. So if you find anyway to improve my code please tell me.

2] This Virtual Assistant will NOT be A.I integrated. You just tell it to do something and it does it So let’s get started

3] Please download the starter file attached below

If you want to see a demo watch the youtube link given below.

Supplies

Step 1: Installing Necessary Packages

First of all you need to install python. I am using Python 3.9, but Python 3.X or higher might do.

Then we have to install a few packages using pip.

The first one is pyttsx3. to install it just type

pip install pyttsx3 

in your command prompt. I will show how you can do that in windows.

Just click the search icon on the taskbar and type ‘cmd’ as shown above.

Then a few more packages are

pip install SpeechRecognition 
pip install wikipedia 
pip install pyjokes 
pip install playsound 

There are many more modules that we will use but those are already built in to python.

Step 2: Importing the Modules

import speech_recognition as sr    #To convert speech into text
import pyttsx3                     #To convert text into speech
import datetime                    #To get the date and time
import wikipedia                   #To get information from wikipedia
import webbrowser                  #To open websites
import os                          #To open files
import time                        #To calculate time
import subprocess                  #To open files
from tkinter import *              #For the graphics
import pyjokes                     #For jokes
from playsound import playsound    #To play sounds
import keyboard                    #To add keyboard activation  

Note:

A lot of these modules have overlapping uses. So you can get rid of the ones you don’t want, but I like it this way

Step 3: Converting Text Into Speech

As mentioned before we will be using pyttsx3 to do this

Before writing the function to do this we have to assign a few variables.

name_assistant = "Cortana" #The name of the assistant


engine = pyttsx3.init('sapi5')   #'sapi5' is the argument you have to use for windows, I am not sure what it is for Mac and Linux
voices = engine.getProperty('voices')  #To get the voice
engine.setProperty('voice', voices[1].id) #defines the gender of the voice. 


# Note: voices[1].id sets it to female and voices[0].id sets it to male
<br>
<br>

Later we will add a feature to change the assistant’s name, but for now lets keep it like this.

Now let’s write the speak() function

def speak(text):
    engine.say(text)
    print(name_assistant + " : "  +  text)
    engine.runAndWait()

It’s pretty self explanatory

Now you can type any thing in the speak function and the assistant will tell it out loud. But remember to put it in inverted commas

Step 4: A Wishing Feature

Now we are going to add a feature where the assistant will wish you when you open the program.

Normally its as simple as speak(«Hello»). But we’re going to do it a bit differently.

The assistant is going to wish ‘Hello Good Morning’. The problem with this is that it can’t wish good morning in the evening. So we have to assign a function.

This is where we are going to use the datetime module. In this evening is defined as after 6:00 p.m.

And afternoon is defined as after 12:00 p.m

The function looks like this:

def wishMe():
    hour=datetime.datetime.now().hour
    if hour>=0 and hour<12:
        speak("Hello,Good Morning")
   
    elif hour>=12 and hour<18:  # This uses the 24 hour system so 18 is actually 6 p.m 
        speak("Hello,Good Afternoon")
 
    else:
        speak("Hello,Good Evening")<br>

This function is also very intuitive.

And remember you have to call the function or else nothing will work

wishMe()

Step 5: What’s Todays Date

This function is a bit tedious because we have to write a list containing all the months and all the ordinal dates. To save the trouble for you I will just paste them here.

month_names = ['Janameary', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] <br>

The function contains a variable for months and a variable for days both are which are later converted into integer values to pick out dates and months from the lists above.

def date():
    now = datetime.datetime.now()
    my_date = datetime.datetime.today()

    month_name = now.month
    day_name = now.day
    month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] 
    

    speak("Today is "+ month_names[month_name-1] +" " + ordinalnames[day_name-1] + '.')<br>

You might ask why there is a -1 when we start picking out elements from the list. That is because The numbering for python lists start from 0 not 1. So we have to account for the extra 0th term.

Now if you call this function the assistant will tell you the date.

date()

Step 6: Make a Note

This is a rather useful feature which will make quick notes and reminders for you.

def note(text):
    date = datetime.datetime.now()
    file_name = str(date).replace(":", "-") + "-note.txt"
    with open(file_name, "w") as f:
        f.write(text)

    subprocess.Popen(["notepad.exe", file_name])

The file’s name will have the date and time in it. It will be stored in the same directory as your file.

The code is also quite simple. This is the only function in which the subprocess module will be used

To test it out just type:

note("Remind me to buy groceries")

and it works like a charm.

Step 7: Getting User Input

To achieve this we are going to use the speech recognition module.

def get_audio(): 

    r = sr.Recognizer() 
    audio = '' 

    with sr.Microphone() as source: 

        print("Listening") 
        playsound("assistant_on.wav")
        audio = r.listen(source, phrase_time_limit = 3) 
        playsound("assistant_off.wav")
        print("Stop.") 
        
    try: 
        text = r.recognize_google(audio, language ='en-US') 
        print('You: ' + ': '+ text)
        return text


    except:

        return "None"<br>

I will attach the two audio files. To call this function you have to do as shown below

text = get_audio()
print(text)

And it works.

Step 8: The Fun Part

Now get rid of all the functions you have called except the wishMe function.(Don’t delete the whole function)

Now this is the fun part where you tell your Assistant to do stuff for you

How to do this??

It’s simple you have to define a variable to the get_audio function and then check whether a few words are there in the variable and if it is there the assistant will have to speak or do something.

I have put all this under a function. So that it is easier to access later.

def Process_audio():

    run = 1
    if __name__=='__main__':
        while run==1:

            app_string = ["open word", "open powerpoint", "open excel", "open zoom","open notepad",  "open chrome"]
            app_link = [r'Microsoft Office Word 2007.lnk',r'Microsoft Office PowerPoint 2007.lnk', r'Microsoft Office Excel 2007.lnk', r'Zoom.lnk', r'Notepad.lnk', r'Google Chrome.lnk' ]
            app_dest = r'C:UsersshrirakshaAppDataRoamingMicrosoftWindowsStart MenuPrograms' # Write the location of your file

            statement = get_audio().lower()
            results = ''
            run +=1

            if "hello" in statement or "hi" in statement:

              wishMe()               


            if "good bye" in statement or "ok bye" in statement or "stop" in statement:
                speak('Your personal assistant ' + name_assistant +' is shutting down, Good bye')
                screen.destroy()
                break

            if 'wikipedia' in statement:
              try:


                speak('Searching Wikipedia...')
                statement = statement.replace("wikipedia", "")
                results = wikipedia.summary(statement, sentences = 3)
                speak("According to Wikipedia")
                wikipedia_screen(results)
              except:
                speak("Error")


            if 'joke' in statement:
              speak(pyjokes.get_joke())    
     
            if 'open youtube' in statement:
                webbrowser.open_new_tab("https://www.youtube.com")
                speak("youtube is open now")
                time.sleep(5)


            if 'open google' in statement:
                    webbrowser.open_new_tab("https://www.google.com")
                    speak("Google chrome is open now")
                    time.sleep(5)


            if 'open gmail' in statement:
                    webbrowser.open_new_tab("mail.google.com")
                    speak("Google Mail open now")
                    time.sleep(5)

            if 'open netflix' in statement:
                    webbrowser.open_new_tab("netflix.com/browse") 
                    speak("Netflix open now")


            if 'open prime video' in statement:
                    webbrowser.open_new_tab("primevideo.com") 
                    speak("Amazon Prime Video open now")
                    time.sleep(5)

            if app_string[0] in statement:
                os.startfile(app_dest + app_link[0])

                speak("Microsoft office Word is opening now")

            if app_string[1] in statement:
                os.startfile(app_dest + app_link[1])
                speak("Microsoft office PowerPoint is opening now")

            if app_string[2] in statement:
                os.startfile(app_dest + app_link[2])
                speak("Microsoft office Excel is opening now")
        
            if app_string[3] in statement:

                os.startfile(app_dest + app_link[3])
                speak("Zoom is opening now")


            if app_string[4] in statement:
                os.startfile(app_dest + app_link[4])
                speak("Notepad is opening now")
        
            if app_string[5] in statement:
                os.startfile(app_dest + app_link[5])
                speak("Google chrome is opening now")
                       

            if 'news' in statement:
                news = webbrowser.open_new_tab("https://timesofindia.indiatimes.com/city/mangalore")
                speak('Here are some headlines from the Times of India, Happy reading')
                time.sleep(6)

            if 'cricket' in statement:
                news = webbrowser.open_new_tab("cricbuzz.com")
                speak('This is live news from cricbuzz')
                time.sleep(6)

            if 'corona' in statement:
                news = webbrowser.open_new_tab("https://www.worldometers.info/coronavirus/")
                speak('Here are the latest covid-19 numbers')
                time.sleep(6)

            if 'time' in statement:
                strTime=datetime.datetime.now().strftime("%H:%M:%S")
                speak(f"the time is {strTime}")

            if 'date' in statement:
                date()

            if 'who are you' in statement or 'what can you do' in statement:
                    speak('I am '+name_assistant+' your personal assistant. I am programmed to minor tasks like opening youtube, google chrome, gmail and search wikipedia etcetra') 


            if "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
                speak("I was built by Abhhi  Sannayya")

            
            if 'make a note' in statement:
                statement = statement.replace("make a note", "")
                note(statement)


            if 'note this' in statement:    
                statement = statement.replace("note this", "")
                note(statement)         

            speak(results)

I will explain a few things and clear somethings up in the next step.

Step 9: Graphical User Interface

I had promised at the beginning of the tutorial that this would not be a boring console assistant. But one with a User interface. We are going to add that right now.

To do this we are going to use tkinter a built in GUI module for python

To understand this better please watch a few tkinter tutorials on youtube.

Write the following code

We will add stuff to the functions later

def change_name():
     pass

def change():
     pass

def info():
     pass
def main_screen():

      global screen
      screen = Tk()
      screen.title(name_assistant)
      screen.geometry("100x250")
      screen.iconbitmap('app_icon.ico')


      name_label = Label(text = name_assistant,width = 300, bg = "black", fg="white", font = ("Calibri", 13))
      name_label.pack()


      microphone_photo = PhotoImage(file = "assistant_logo.png")
      microphone_button = Button(image=microphone_photo, command = Process_audio)
      microphone_button.pack(pady=10)

      settings_photo = PhotoImage(file = "settings.png")
      settings_button = Button(image=settings_photo, command = change_name_window)
      settings_button.pack(pady=10)
       
      info_button = Button(text ="Info", command = info)
      info_button.pack(pady=10)

      screen.mainloop()
    

  

Now you should get a screen that looks like the one above.

You probably got a working GUI now and if you press the star button, you can ask your virtual assistant anything

Step 10: Changing the Name of the Virtual Assistant

This is a feature you won’t find in most other virtual assistants. Each assistant has its own fixed name.

But i don’t like that a whole lot.

So our virtual assistant has the capability to change it’s name.

To do this we have to fill in those functions we defined earlier.

I won’t explain much of this code but if you don’t understand it please watch a few tkinter tutorials

def change_name():

  name_info = name.get()

  file=open("Assistant_name", "w")

  file.write(name_info)

  file.close()

  settings_screen.destroy()

  screen.destroy()


def change_name_window():
    
      global settings_screen
      global name


      settings_screen = Toplevel(screen)
      settings_screen.title("Settings")
      settings_screen.geometry("300x300")
      settings_screen.iconbitmap('app_icon.ico')

      
      name = StringVar()

      current_label = Label(settings_screen, text = "Current name: "+ name_assistant)
      current_label.pack()

      enter_label = Label(settings_screen, text = "Please enter your Virtual Assistant's name below") 
      enter_label.pack(pady=10)   
      

      Name_label = Label(settings_screen, text = "Name")
      Name_label.pack(pady=10)
     
      name_entry = Entry(settings_screen, textvariable = name)
      name_entry.pack()


      change_name_button = Button(settings_screen, text = "Ok", width = 10, height = 1, command = change_name)
      change_name_button.pack(pady=10)

For this to work you have to create an empty file called ‘Assistant_name’. Again I recommend you to watch a few youtube tutorials

And now if you press the cogwheel a new window will pop up prompting you to change the Assistants name.

Step 11: Wikipedia

Right now the wikipedia feature might not work a whole lot right because I forgot to define the wikipedia function. This is a function that displays whatever the assistant told onto the screen. Here is the code.

def wikipedia_screen(text):


  wikipedia_screen = Toplevel(screen)
  wikipedia_screen.title(text)
  wikipedia_screen.iconbitmap('app_icon.ico')

  message = Message(wikipedia_screen, text= text)
  message.pack()

Step 12: An Info Page

This is relatively simple you just have to fill in the info function we defined earlier

def info():

  info_screen = Toplevel(screen)
  info_screen.title("Info")
  info_screen.iconbitmap('app_icon.ico')

  creator_label = Label(info_screen,text = "Created by Abhhi Sannayya")
  creator_label.pack()

  Age_label = Label(info_screen, text= " at the age of 12")
  Age_label.pack()

  for_label = Label(info_screen, text = "For Makerspace")
  for_label.pack()

So now you have a completely working Virtual assistant. Ain’t that cool

Step 13: Adding Keyboard Activation

I want to add the feature in which if you press a button, the voice assistant will get activated. We do this using the keyboard module. I thought we can use the f4 function key to do the job

keyboard.add_hotkey("F4", Process_audio)

This way you don’t have to press the GUI button.

Step 14: Finishing Off

I will give you the whole code here. I highly recommend you not to just copy and paste the code but understand what it is that you are typing.

import speech_recognition as sr    #To convert speech into text
import pyttsx3                     #To convert text into speech
import datetime                    #To get the date and time
import wikipedia                   #To get information from wikipedia
import webbrowser                  #To open websites
import os                          #To open files
import time                        #To calculate time
import subprocess                  #To open files
from tkinter import *              #For the graphics
import pyjokes                     #For some really bad jokes
from playsound import playsound    #To playsound
import keyboard                    #To get keyboard
  
name_file = open("Assistant_name", "r")
name_assistant = name_file.read()

engine = pyttsx3.init('sapi5')  
voices = engine.getProperty('voices')  
engine.setProperty('voice', voices[1].id)
    
def speak(text):
    engine.say(text)
    print(name_assistant + " : "  +  text)
    engine.runAndWait() 


def wishMe():


  hour=datetime.datetime.now().hour

  if hour >= 0 and hour < 12:

      speak("Hello,Good Morning")
 
  elif hour >= 12 and hour < 18:

      speak("Hello,Good Afternoon")

  else:

      speak("Hello,Good Evening")


def get_audio(): 

    r = sr.Recognizer() 
    audio = '' 

    with sr.Microphone() as source: 

        print("Listening") 
        playsound("assistant_on.wav")
        audio = r.listen(source, phrase_time_limit = 3) 
        playsound("assistant_off.wav")
        print("Stop.") 
        
    try: 
        text = r.recognize_google(audio, language ='en-US') 
        print('You: ' + ': ' + text)
        return text


    except:

        return "None"


def note(text):
    date = datetime.datetime.now()
    file_name = str(date).replace(":", "-") + "-note.txt"

    with open(file_name, "w") as f:
        f.write(text)

    subprocess.Popen(["notepad.exe", file_name])


def date():
    now = datetime.datetime.now()
    month_name = now.month
    day_name = now.day
    month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] 

    speak("Today is "+ month_names[month_name-1] +" " + ordinalnames[day_name-1] + '.')

wishMe()


def Process_audio():

    run = 1
    if __name__=='__main__':
        while run==1:

            app_string = ["open word", "open powerpoint", "open excel", "open zoom","open notepad",  "open chrome"]
            app_link = [r'Microsoft Office Word 2007.lnk',r'Microsoft Office PowerPoint 2007.lnk', r'Microsoft Office Excel 2007.lnk', r'Zoom.lnk', r'Notepad.lnk', r'Google Chrome.lnk' ]
            app_dest = r'C:UsersshrirakshaAppDataRoamingMicrosoftWindowsStart MenuPrograms'

            statement = get_audio().lower()
            results = ''
            run +=1

            if "hello" in statement or "hi" in statement:

              wishMe()               


            if "good bye" in statement or "ok bye" in statement or "stop" in statement:
                speak('Your personal assistant ' + name_assistant +' is shutting down, Good bye')
                screen.destroy()
                break

            if 'wikipedia' in statement:
              try:


                speak('Searching Wikipedia...')
                statement = statement.replace("wikipedia", "")
                results = wikipedia.summary(statement, sentences = 3)
                speak("According to Wikipedia")
                wikipedia_screen(results)
              except:
                speak("Error")


            if 'joke' in statement:
              speak(pyjokes.get_joke())    
     
            if 'open youtube' in statement:
                webbrowser.open_new_tab("https://www.youtube.com")
                speak("youtube is open now")
                time.sleep(5)


            if 'open google' in statement:
                    webbrowser.open_new_tab("https://www.google.com")
                    speak("Google chrome is open now")
                    time.sleep(5)


            if 'open gmail' in statement:
                    webbrowser.open_new_tab("mail.google.com")
                    speak("Google Mail open now")
                    time.sleep(5)

            if 'open netflix' in statement:
                    webbrowser.open_new_tab("netflix.com/browse") 
                    speak("Netflix open now")


            if 'open prime video' in statement:
                    webbrowser.open_new_tab("primevideo.com") 
                    speak("Amazon Prime Video open now")
                    time.sleep(5)

            if app_string[0] in statement:
                os.startfile(app_dest + app_link[0])

                speak("Microsoft office Word is opening now")

            if app_string[1] in statement:
                os.startfile(app_dest + app_link[1])
                speak("Microsoft office PowerPoint is opening now")

            if app_string[2] in statement:
                os.startfile(app_dest + app_link[2])
                speak("Microsoft office Excel is opening now")
        
            if app_string[3] in statement:

                os.startfile(app_dest + app_link[3])
                speak("Zoom is opening now")


            if app_string[4] in statement:
                os.startfile(app_dest + app_link[4])
                speak("Notepad is opening now")
        
            if app_string[5] in statement:
                os.startfile(app_dest + app_link[5])
                speak("Google chrome is opening now")
                       

            if 'news' in statement:
                news = webbrowser.open_new_tab("https://timesofindia.indiatimes.com/city/mangalore")
                speak('Here are some headlines from the Times of India, Happy reading')
                time.sleep(6)

            if 'cricket' in statement:
                news = webbrowser.open_new_tab("cricbuzz.com")
                speak('This is live news from cricbuzz')
                time.sleep(6)

            if 'corona' in statement:
                news = webbrowser.open_new_tab("https://www.worldometers.info/coronavirus/")
                speak('Here are the latest covid-19 numbers')
                time.sleep(6)

            if 'time' in statement:
                strTime=datetime.datetime.now().strftime("%H:%M:%S")
                speak(f"the time is {strTime}")

            if 'date' in statement:
                date()

            if 'who are you' in statement or 'what can you do' in statement:
                    speak('I am '+name_assistant+' your personal assistant. I am programmed to minor tasks like opening youtube, google chrome, gmail and search wikipedia etcetra') 


            if "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
                speak("I was built by Abhhi  Sannayya")

            
            if 'make a note' in statement:
                statement = statement.replace("make a note", "")
                note(statement)


            if 'note this' in statement:    
                statement = statement.replace("note this", "")
                note(statement)         

            speak(results)


def change_name():

  name_info = name.get()

  file=open("Assistant_name", "w")

  file.write(name_info)

  file.close()

  settings_screen.destroy()

  screen.destroy()


def change_name_window():
    
      global settings_screen
      global name


      settings_screen = Toplevel(screen)
      settings_screen.title("Settings")
      settings_screen.geometry("300x300")
      settings_screen.iconbitmap('app_icon.ico')

      
      name = StringVar()

      current_label = Label(settings_screen, text = "Current name: "+ name_assistant)
      current_label.pack()

      enter_label = Label(settings_screen, text = "Please enter your Virtual Assistant's name below") 
      enter_label.pack(pady=10)   
      

      Name_label = Label(settings_screen, text = "Name")
      Name_label.pack(pady=10)
     
      name_entry = Entry(settings_screen, textvariable = name)
      name_entry.pack()


      change_name_button = Button(settings_screen, text = "Ok", width = 10, height = 1, command = change_name)
      change_name_button.pack(pady=10)


def info():

  info_screen = Toplevel(screen)
  info_screen.title("Info")
  info_screen.iconbitmap('app_icon.ico')

  creator_label = Label(info_screen,text = "Created by Abhhi Sannayya")
  creator_label.pack()

  Age_label = Label(info_screen, text= " at the age of 12")
  Age_label.pack()

  for_label = Label(info_screen, text = "For Makerspace")
  for_label.pack()

keyboard.add_hotkey("F4", Process_audio)


def wikipedia_screen(text):


  wikipedia_screen = Toplevel(screen)
  wikipedia_screen.title(text)
  wikipedia_screen.iconbitmap('app_icon.ico')

  message = Message(wikipedia_screen, text= text)
  message.pack()



def main_screen():

      global screen
      screen = Tk()
      screen.title(name_assistant)
      screen.geometry("100x250")
      screen.iconbitmap('app_icon.ico')


      name_label = Label(text = name_assistant,width = 300, bg = "black", fg="white", font = ("Calibri", 13))
      name_label.pack()


      microphone_photo = PhotoImage(file = "assistant_logo.png")
      microphone_button = Button(image=microphone_photo, command = Process_audio)
      microphone_button.pack(pady=10)

      settings_photo = PhotoImage(file = "settings.png")
      settings_button = Button(image=settings_photo, command = change_name_window)
      settings_button.pack(pady=10)
       
      info_button = Button(text ="Info", command = info)
      info_button.pack(pady=10)

      screen.mainloop()


main_screen()

Thank you.

Be the First to Share

Recommendations

Понравилась статья? Поделить с друзьями:
  • Как написать вин плюс р
  • Как написать вилле вало
  • Как написать викторину на питоне
  • Как написать викторину на python
  • Как написать вики макарской