The Wayback Machine - https://web.archive.org/web/20241001215621/https://www.geeksforgeeks.org/personal-voice-assistant-in-python/
Open In App

Personal Voice Assistant in Python

Last Updated : 25 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we know Python is a suitable language for script writers and developers. Let’s write a script for Personal Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. The implemented assistant can open up the application (if it’s installed in the system), search Google, Wikipedia and YouTube about the query, calculate any mathematical question, etc by just giving the voice command. We can process the data as per the need or can add the functionality, depends upon how we code things. We are using Google speech recognition API and google text to speech for voice input and output respectively. Also, for calculating mathematical expression WolframAlpha API can be used. Playsound Package is used to play the saved mp3 sound from the system. 

Python external Package Requirements:

-> gTTS – Google Text To Speech, for converting the given text to speech -> speech_recognition – for recognizing the voice command and converting to text -> selenium – for web based work from browser -> wolframalpha – for calculation given by user -> playsound – for playing the saved audio file. -> playaudio – for voice engine in python

Well, let’s get started with code. We will divide each function as a single code for easy understanding. Here’s the main function, with get_audio() and assistant_speaks function. get_audio() function is created to get the audio from user using microphone, the phrase limit is set to 5 seconds (you can change it). Assistant speaks function is created to provide the output according to the processed data. 

Python3




# importing speech recognition package from google api
import speech_recognition as sr
import playsound # to play saved mp3 file
from gtts import gTTS # google text to speech
import os # to save/open files
import wolframalpha # to calculate strings into formula
from selenium import webdriver # to control browser operations
 
num = 1
def assistant_speaks(output):
    global num
 
    # num to rename every audio file
    # with different name to remove ambiguity
    num += 1
    print("PerSon : ", output)
 
    toSpeak = gTTS(text = output, lang ='en', slow = False)
    # saving the audio file given by google text to speech
    file = str(num)+".mp3
    toSpeak.save(file)
     
    # playsound package is used to play the same file.
    playsound.playsound(file, True)
    os.remove(file)
 
 
 
def get_audio():
 
    rObject = sr.Recognizer()
    audio = ''
 
    with sr.Microphone() as source:
        print("Speak...")
         
        # recording the audio using speech recognition
        audio = rObject.listen(source, phrase_time_limit = 5)
    print("Stop.") # limit 5 secs
 
    try:
 
        text = rObject.recognize_google(audio, language ='en-US')
        print("You : ", text)
        return text
 
    except:
 
        assistant_speaks("Could not understand your audio, PLease try again !")
        return 0
 
 
# Driver Code
if __name__ == "__main__":
    assistant_speaks("What's your name, Human?")
    name ='Human'
    name = get_audio()
    assistant_speaks("Hello, " + name + '.')
     
    while(1):
 
        assistant_speaks("What can i do for you?")
        text = get_audio().lower()
 
        if text == 0:
            continue
 
        if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text):
            assistant_speaks("Ok bye, "+ name+'.')
            break
 
        # calling process text to process the query
        process_text(text)


So, we have got an idea here how we are giving voice to the machine and take input from user. The next step and the main step is how you want to process your input. This is just basic code, there is a lot of other algorithms(NLP) can be used to process the text in a proper manner. We have made it static. Also, Wolframalpha api has been used to calculate the calculations part. 

Python3




def process_text(input):
    try:
        if 'search' in input or 'play' in input:
            # a basic web crawler using selenium
            search_web(input)
            return
 
        elif "who are you" in input or "define yourself" in input:
            speak = '''Hello, I am Person. Your personal Assistant.
            I am here to make your life easier. You can command me to perform
            various tasks such as calculating sums or opening applications etcetra'''
            assistant_speaks(speak)
            return
 
        elif "who made you" in input or "created you" in input:
            speak = "I have been created by Sheetansh Kumar."
            assistant_speaks(speak)
            return
 
        elif "geeksforgeeks" in input:# just
            speak = """Geeks for Geeks is the Best Online Coding Platform for learning."""
            assistant_speaks(speak)
            return
 
        elif "calculate" in input.lower():
             
            # write your wolframalpha app_id here
            app_id = "WOLFRAMALPHA_APP_ID"
            client = wolframalpha.Client(app_id)
 
            indx = input.lower().split().index('calculate')
            query = input.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            assistant_speaks("The answer is " + answer)
            return
 
        elif 'open' in input:
             
            # another function to open
            # different application available
            open_application(input.lower())
            return
 
        else:
 
            assistant_speaks("I can search the web for you, Do you want to continue?")
            ans = get_audio()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                search_web(input)
            else:
                return
    except :
 
        assistant_speaks("I don't understand, I can search the web for you, Do you want to continue?")
        ans = get_audio()
        if 'yes' in str(ans) or 'yeah' in str(ans):
            search_web(input)


Now we have processed the input, it’s time for action! There are two functions included that is search_web and open_application. search_web is just a web crawler which uses selenium package to process. It can search google, wikipedia and can open YouTube. You just have to say include the name and it will open it in the Firefox browser. For other browsers, you need to install a proper browser package in selenium. Here we are using webdriver for Firefox. open_application is just a function uses os package to open the application present in the system. 

Python3




def search_web(input):
 
    driver = webdriver.Firefox()
    driver.implicitly_wait(1)
    driver.maximize_window()
 
    if 'youtube' in input.lower():
 
        assistant_speaks("Opening in youtube")
        indx = input.lower().split().index('youtube')
        query = input.split()[indx + 1:]
        driver.get("http://www.youtube.com/results?search_query =" + '+'.join(query))
        return
 
    elif 'wikipedia' in input.lower():
 
        assistant_speaks("Opening Wikipedia")
        indx = input.lower().split().index('wikipedia')
        query = input.split()[indx + 1:]
        driver.get("https://en.wikipedia.org/wiki/" + '_'.join(query))
        return
 
    else:
 
        if 'google' in input:
 
            indx = input.lower().split().index('google')
            query = input.split()[indx + 1:]
            driver.get("https://www.google.com/search?q =" + '+'.join(query))
 
        elif 'search' in input:
 
            indx = input.lower().split().index('google')
            query = input.split()[indx + 1:]
            driver.get("https://www.google.com/search?q =" + '+'.join(query))
 
        else:
 
            driver.get("https://www.google.com/search?q =" + '+'.join(input.split()))
 
        return
 
 
# function used to open application
# present inside the system.
def open_application(input):
 
    if "chrome" in input:
        assistant_speaks("Google Chrome")
        os.startfile('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
        return
 
    elif "firefox" in input or "mozilla" in input:
        assistant_speaks("Opening Mozilla Firefox")
        os.startfile('C:\Program Files\Mozilla Firefox\\firefox.exe')
        return
 
    elif "word" in input:
        assistant_speaks("Opening Microsoft Word")
        os.startfile('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Word 2013.lnk')
        return
 
    elif "excel" in input:
        assistant_speaks("Opening Microsoft Excel")
        os.startfile('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Excel 2013.lnk')
        return
 
    else:
 
        assistant_speaks("Application not available")
        return


Here are some of the examples and output, which can help you understand how the above processing works.

1. Say "Search google Geeks for Geeks"
2. Say "Play Youtube your favourite song"
3. Say "Wikipedia Dhoni"
4. Say "Open Microsoft Word"
5. Say "Calculate anything you want"

In all the above cases, it will give do what is told. If the assistant can’t understand what is told it will ask you to google search it. For the thing which assistant can’t do is handled by this assistant. Below are some screenshots for the talk between human and the assistant. Well, that’s it. The above functionality can be coded in many ways, this is a basic implementation. Make sure you have the latest version of all the above packages for smooth work. To run the above code combine all the functions in same file.



Previous Article
Next Article

Similar Reads

Voice Assistant using python
As we know Python is a suitable language for scriptwriters and developers. Let’s write a script for Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an
11 min read
Voice Assistant for Movies using Python
In this article, we will see how a voice assistant can be made for searching for movies or films. After giving input as movie name in audio format and it will give the information about that movie in audio format as well. As we know the greatest searching website for movies is IMDb. IMDb is an online database of information related to films, televi
6 min read
How to make a voice assistant for E-mail in Python?
As we know, emails are very important for communication as each professional communication can be done by emails and the best service for sending and receiving mails is as we all know GMAIL. Gmail is a free email service developed by Google. Users can access Gmail on the web and using third-party programs that synchronize email content through POP
9 min read
Project Idea | (A Personal Assistant)
Project Title : Acolyte - a personal assistant Introduction: The basic idea behind this project is to create a simple stand-alone application that helps less tech savvy people in the world to use the computer without feeling ignorant or computer illiterate. Computers have became a very important devices and as well as less expensive over time. The
5 min read
Text-To-Speech changing voice in Python
There are several APIs available to convert text to speech in python. One such APIs is the Python Text to Speech API commonly known as the pyttsx3 API. pyttsx3 is a very easy to use tool which converts the text entered, into audio. Installation To install the pyttsx3 API, open terminal and write pip install pyttsx3 This library is dependent on win3
3 min read
Voice search Wikipedia using Python
Every day, we visit so many applications, be it messaging platforms like Messenger, Telegram or ordering products on Amazon, Flipkart, or knowing about weather and the list can go on. And we see that these websites have their own software program for initiating conversations with human beings using rules or artificial intelligence. Users interact w
5 min read
Create a Voice Recorder using Python
Python can be used to perform a variety of tasks. One of them is creating a voice recorder. We can use python's sounddevice module to record and play audio. This module along with the wavio or the scipy module provides a way to save recorded audio. Installation:sounddevice: This module provides functions to play and record NumPy arrays containing a
3 min read
Build a Voice Recorder GUI using Python
Prerequisites: Python GUI – tkinter, Create a Voice Recorder using Python Python provides various tools and can be used for various purposes. One such purpose is recording voice. It can be done using the sounddevice module. This recorded file can be saved using the soundfile module Module NeededSounddevice: The sounddevice module provides bindings
2 min read
Python Script to Shutdown your PC using Voice Commands
Yes, it is possible with the help of terminal and some modules in Python through which one can shut down a PC by just using voice commands Required Modules:OS module: It is an in-built module in python that provides function for interacting with the operating system.Speech Recognition module: It is an external module in python whose functionality d
6 min read
How to make a voice unlock system in Python?
A voice-based unlock system for our computer will be the application that will take our voice as input and process that voice converts it into a text-based instruction for our computer and then perform an action based on that instruction. This process uses The State-of-the-art process in a speech to text, Natural Language Understanding, and Deep Le
4 min read
Create a real time voice translator using Python
In this article, we are going to create a real-time voice translator in Python. Module neededplaysound: This module is used to play sound in Pythonpip install playsoundSpeech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition.pip install SpeechRecognitiongoogl
7 min read
Build Your Own Voice-Activated Calculator Using Python
In this article, you'll be delving into the development of a voice command calculator using Python, taking advantage of libraries like Speech-Recognition and PyAudio that will allow users with swift means of performing arithmetic operations. Developing such a program will require you to go through some of the basics of speech recognition and PyAudi
6 min read
Python | Create a simple assistant using Wolfram Alpha API.
The Wolfram|Alpha Webservice API provides a web-based API allowing the computational and presentation capabilities of Wolfram|Alpha to be integrated into web, mobile, desktop, and enterprise applications. Wolfram Alpha is an API which can compute expert-level answers using Wolfram’s algorithms, knowledgebase and AI technology. It is made possible b
2 min read
Build a Virtual Assistant Using Python
Virtual desktop assistant is an awesome thing. If you want your machine to run on your command like Jarvis did for Tony. Yes it is possible. It is possible using Python. Python offers a good major library so that we can use it for making a virtual assistant. Windows has Sapi5 and Linux has Espeak which can help us in having the voice from our machi
8 min read
Voice Based Android Mail System for Visually Impaired
A voice dependent email system is an android solution which allows the user to send and receive emails without using any visual features, which means everything can be done by voice commands. This application is designed and engineered especially for people with visual disabilities. According to a survey, around 250 million and more visually challe
4 min read
Project Idea | Voice Based Email for Visually Challenged
Project Title: Voice based Email service for visually challenged people We have seen that the inception of Internet has dramatically revolutionized many fields. Internet has made life of people so easy that people today have access to any information they want sitting at their home. One of the main fields that Internet has revolutionized is communi
8 min read
Personal Hotel web UI
Designing UI (User Interface) for a Personal Hotel Website needs designing pages that are based on Principles of UI and functionality. The UI should highlight the hotel images, ratings, prices and availability of the Hotels. In this article, we will explore the important concepts needed to design an effective Personal Hotel Web UI. Designing the We
3 min read
UI Design of a Personal Service Based Website
A personal service based company website must be beautiful in terms of designing and animations. A personal service based company website UI have great animations and use elegant features of style and UI/UX features. In this article we will cover the aspects of designing a personal service based website and how some basic designing principles will
3 min read
Creating a Personal Finance Manager App with React and Chart.js
We will explore how to build a simple yet powerful Personal Finance Manager App using React.js for the frontend and Chart.js for visualizing financial data. Managing personal finances effectively is crucial for financial stability and growth. Preview of Final Output: Steps to Creating a Personal Finance Manager App with React and Chart.jsStep 1: Cr
4 min read
Create a Personal Budgeting App using React and D3.js
In this article, we'll explore how to build a Personal Budgeting App using React for the frontend and D3.js for data visualization. A Personal Budgeting App can provide valuable insights into spending habits, help set financial goals, and track progress over time. Output Preview: Let us have a look at how the final output will look like. Prerequisi
6 min read
Personal Finance Tracker using Django
In this tutorial, we'll develop a Personal Finance Tracker using Django. We'll implement a robust login and logout system, and then proceed to establish CRUD (Create, Read, Update, Delete) operations for efficiently managing our expenses. The system will empower users to seamlessly delete or update their data with a single click, avoiding the need
11 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Visualizing O(n) using Python
Introduction Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions. Complexity. Why it matters? Computational complexity is a venerable su
3 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read