skip to Main Content

I downloaded the module ‘SpeechRecognition’ in my Python project. But somehow I am unable to import it in my file. Here is the code:

import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import random
import linecache
import pygame
import os

# Variables

# notes and game variables
notesLIST = []
turns = 0
playerscore = 0
botscore = 0

# Sapi5 is a speech recognition api
# It will be used for voice of our assistant
engine = pyttsx3.init('sapi5')

# Our assistant's voices are stored in this variable
voices = engine.getProperty('voices')
# Setting the voices
# We are getting the first voice
engine.setProperty('voices', voices[1].id)


# Functions

# Making our assistant say something
def speak(audio):
    engine.say(audio)
    engine.runAndWait()


def intro():
    """
    This functions will run when the program starts, it'll wish us and then ask us for a command
    """

    curHour = int(datetime.datetime.now().hour)
    if curHour >= 0 and curHour < 12:
        speak("Hi Sir, Good Morning.")
        print("Hi Sir, Good Morning.")
    elif curHour >= 12 and curHour < 16:
        speak("Hi Sir, Good Afternoon.")
        print("Hi Sir, Good Afternoon.")
    else:
        speak("Hi Sir, Good Evening.")
        print("Hi Sir, Good Evening.")

    print("My name is P.A.L, I am a Virtual Assistant. How may I help you?")
    speak("My name is Pal and I am a Virtual Assistant. How may I help you?")


def userCommand():
    """
    This program is used to convert user's speech to text
    """
    speech = sr.Recognizer()
    with sr.Microphone() as source:
        print("Speak now...")
        # This describes how loudly you have to say, preferred in places with loud background noise
        speech.energy_threshold = 600
        audio = speech.listen(source)

    try:
        speak("Interpreting...")
        # This stores the string value of our speech
        command = speech.recognize_google(audio, language='en-in')
        print("Your Command: ", command)

    except Exception as e:
        print("Please say that again...")
        return ""
    return command


if __name__ == '__main__':
    intro()

    # Infinite Loop
    while True:
        # Turning into lowercase string
        command = userCommand().lower()
        # Main Logic for execution of command

        if 'wikipedia' in command:
            speak("Searching Wikipedia...")
            # Replacing wikipedia string in command with blank
            command = command.replace("wikipedia", "")
            # Getting results from wikipedia
            wikiResult = wikipedia.summary(command, sentences=2)
            print(wikiResult)
            speak("The results from wikipedia show that")
            speak(wikiResult)

        elif 'what can you do' in command:
            speak("Sir, I can open websites like youtube, stackoverflow, chess.com, I can search for stuff on google, "
                  "I can open chrome, I can open VS Code, I can play music, I can even search for people's "
                  "information on wikipedia, and I can tell you the time. I am being developed, and many new features "
                  "are "
                  "yet to come...")

        # Fun questions
        elif 'hello' in command:
            speak("Hi Sir. How can I help you")

        elif 'how are you' in command:
            speak("I am really well sir. I am glad you asked")

        elif 'tell me a joke' in command:
            randomNumber = random.randint(1, 4)
            joke = linecache.getline("jokes.txt", randomNumber)
            speak(joke)
            print(joke)
            pygame.mixer.init()
            pygame.mixer.music.load("laughter.mp3")
            pygame.mixer.music.play()

        elif 'i am feeling bored' in command or 'entertain me' in command or "let's play a game" in command:
            speak("Sure, let's play Rock Paper Scissors Game!")
            while turns < 5:
                speak("Type a Number: 1 for Rock 2 for Paper and 3 for Scissor")
                rock_paper_or_scissor = int(input("Type a Number: 1 for Rock 2 for Paper "
                                                  "and 3 for Scissor"))

                botnumber = random.randrange(1, 4)
                # 1 = rock
                # 2 = paper
                # 3 = scissor
                if (rock_paper_or_scissor == 1 and botnumber == 1):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("0 points")
                    speak("0 points")
                    turns += 1

                elif (rock_paper_or_scissor == 1 and botnumber == 2):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to Computer")
                    speak("1 point to Computer")
                    botscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 1 and botnumber == 3):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to you")
                    speak("1 point to you")
                    playerscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 2 and botnumber == 1):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to you")
                    speak("1 point to you")
                    playerscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 2 and botnumber == 2):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("Draw")
                    speak("Draw")
                    turns += 1

                elif (rock_paper_or_scissor == 2 and botnumber == 3):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to Computer")
                    speak("1 point to Computer")
                    botscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 3 and botnumber == 1):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to Computer")
                    speak("1 point to Computer")
                    botscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 3 and botnumber == 2):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("1 point to you")
                    speak("1 point to you")
                    playerscore += 1
                    turns += 1

                elif (rock_paper_or_scissor == 3 and botnumber == 3):
                    print("Computer played " + str(botnumber))
                    speak("Computer played " + str(botnumber))
                    print("You Played " + str(rock_paper_or_scissor))
                    speak("You Played " + str(rock_paper_or_scissor))
                    print("Draw")
                    speak("Draw")
                    turns += 1

                elif (rock_paper_or_scissor > 3):
                    print("Error: Please enter a number less than or equal to 3 and greater than 0")
                    speak("Error: Please enter a number less than or equal to 3 and greater than 0")
                    turns -= 1

            print("-------------------------------------nYour Score = " + str(playerscore))
            speak("Your Score = " + str(playerscore))
            print("Computer Score = " + str(botscore))
            speak("Computer Score = " + str(botscore))
            if playerscore == botscore:
                print("That's a Draw!")
                speak("That's a Draw!")
            elif playerscore > botscore:
                print("You WIN! Congratulations Sir!")
                speak("You WIN! Congratulations Sir!")
            elif playerscore < botscore:
                print("Computer WINS! Better luck next time")
                speak("Computer WINS! Better luck next time")

        elif 'thank you' in command:
            speak("My pleasure sir!")

        elif 'who created you' in command:
            speak("Sir, I was created by Sai Mishra")
            print("Sir, I was created by Sai Mishra")

        elif 'who made you' in command:
            speak("Sir, I was made by Sai Mishra")
            print("Sir, I was made by Sai Mishra")

        elif 'who is sahi mishra' in command:
            speak("Sir, Sai Mishra is a 13 year old YouTuber, programmer, web developer and an android developer")
            print("Sir, Sai Mishra is a 13 year old YouTuber, programmer, web developer and an android developer")

        elif 'when were you made' in command:
            speak("Sir, I was made on 31st August, in Bihar State of India, by Sai Mishra")
            print("Sir, I was made on 31st August, in Bihar State of India, by Sai Mishra")

        elif 'exit' in command:
            speak("Closing Program, bye sir!")
            curHour = int(datetime.datetime.now().hour)
            if 0 <= curHour < 16:
                speak("Have a nice day!")
                print("Have a nice day!")
            if 16 <= curHour < 20:
                speak("I hope I was helpful!")
                print("I hope I was helpful!")
            exit()

        elif 'take a note' in command or 'save a note' in command:
            speak("What note should I make?")
            userNote = userCommand()
            if userNote == "":
                speak("Cannot save a blank note")
            else:
                Writingfile = open("notes.txt", "a")
                Writingfile.write(userNote + "n")
                Writingfile.close()
                speak("Done sir. Saved the note successfully. If you want to see your notes then say - 'Show me my "
                      "notes'")
                print("Done sir. Saved the note successfully. If you want to see your notes then say - 'Show me my "
                      "notes'")

        elif 'show me my notes' in command:
            print("Your note(s)")
            speak("Your notes")
            Readingfile = open("notes.txt", "r")
            print(Readingfile.read())
            speak(Readingfile.read())

        elif 'open youtube' in command:
            speak("Opening Youtube Sir...")
            # In python "Null" is called "None"
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("youtube.com")

        elif 'open stack overflow' in command:
            speak("Opening Stackoverflow...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("stackoverflow.com")

        elif 'open chess' in command:
            speak("Opening Chess.com...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("chess.com")

        elif 'open gmail' in command:
            speak("Opening Gmail...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("https://mail.google.com/mail/u/1/#inbox")

        elif 'show me my mails' in command:
            speak("Opening Gmail...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("https://mail.google.com/mail/u/1/#inbox")

        elif 'what are my new mails' in command:
            speak("Opening Gmail...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("https://mail.google.com/mail/u/1/#inbox")

        elif 'open remove.bg' in command:
            speak("Opening Remove.bg...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("https://www.remove.bg/")

        elif 'play music' in command:
            speak("Playing Music...")
            music_path = 'C:\Users\shiva\Desktop\Favorite songs'
            songs = os.listdir(music_path)
            os.startfile(os.path.join(music_path, songs[0]))

        elif 'sing a song' in command:
            speak("Twinkle Twinkle Little star, how I wonder what you are. Up above the world so high. Like a diamond "
                  "in the sky.")
            speak("I know I sang really bad, can you please ask me something else?")

        elif 'the time' in command:
            # Getting time in hours and minutes
            timeStr = datetime.datetime.now().strftime("%H:%M")
            print("The current time is " + timeStr)
            speak("The current time is " + timeStr)

        elif 'open vs code' in command:
            speak("Opening Visual Studio Code")
            vscPath = "C:\Users\shiva\AppData\Local\Programs\Microsoft VS Code\Code.exe"
            os.startfile(vscPath)

        elif 'open chrome' in command:
            speak("Opening Google Chrome")
            chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
            os.startfile(chromePath)

        elif 'open photoshop' in command:
            speak("Opening Adobe Photoshop")
            photoshopPath = "C:\Program Files\Adobe\Adobe Photoshop 2021\Photoshop.exe"
            os.startfile(photoshopPath)

        elif 'open important' in command:
            speak("Opening Important Tutorials Folder")
            imptutPath = "C:\Users\shiva\Desktop\Coding\Important Tutorials"
            os.startfile(imptutPath)

        elif 'search' in command:
            speak("What should I search")
            searchContent = userCommand()
            speak("Searching Google...")
            webbrowser.register('chrome', None,
                                webbrowser.BackgroundBrowser
                                ("C://Program Files//GoogleChrome//Application//chrome.exe"))
            webbrowser.get('chrome').open("https://www.google.com/search?q=" + searchContent +
                                          "&oq=wht&aqs=chrome..69i57j0i10l3j0i10i433l3j0i10j0i10i433l2."
                                          "1465j0j7&sourceid=chrome&ie=UTF-8")


        else:
            speak("Sorry sir, I can't do that currently")

I first installed the SpeechRecognition module using ‘pip install SpeechRecognition’
I had already made a project like this in the past and didn’t face any issue. Can anyone tell me what’s wrong?

2

Answers


  1. Try checking if the python version you’re using to run the script is the same you installed the module for.

    Login or Signup to reply.
  2. I suspect one of two issues here, so we need to tackle them separately:

    1. You are using a venv or other virtual environment, and the SpeechRecognition module is not loaded in that environment, as the comments suggest.
    2. Or, installing the SpeechRecognition module with pip install SpeechRecognition has failed in some way. This module has several dependencies. So, could you please provide the output of python -m speech_recognition – as the docs suggest – to prove that the package has been installed correctly?
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search