Python Forum

Full Version: Speak results from Pywhatkit
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm working on my voice assistant and I'm trying to get it to speak the returned results from: pywhatkit.info(command, lines = 4)

    #Find info about stuff
    if ('what is' in command):
        command = command.replace("what is", "")
        speak('Searching' + command)
        result = pywhatkit.info(command, lines = 4)
        speak(result)
For example, if said 'What is a bridge' it prints/returns:
Output:
A bridge is a structure built to span a physical obstacle (such as a body of water, valley, road, or rail) without blocking the way underneath. It is constructed for the purpose of providing passage over the obstacle, which is usually something that is otherwise difficult or impossible to cross. There are many different designs of bridges, each serving a particular purpose and applicable to different situations. Designs of bridges vary depending on factors such as the function of the bridge, the nature of the terrain where the bridge is constructed and anchored, and the material used to make it, and the funds available to build it.
But it keeps saying 'none' (or at least thats what it sound like to me) instead of speaking what it returned (the result).

Is there a way to get it to speak the returned result?

Thanks in advance.


Full code:
#----------------------------------------------------------------------------------------------
#                                  Table Of Contents/Overview
#----------------------------------------------------------------------------------------------
# Imports
# Commander & A.I Name
# Fancy Output for Terminal
# Voice Settings
# Listen Function
# WishMe Function

# Main
# - General Conversation
# -- Search Wikipedia
# --- Search Wolfram Alpha
# ---- Open Stuff on Internet
# ----- Open Stuff on Computer
# ------ Stop Program

# Run Program
#----------------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------
#                                  Imports
#-------------------------------------------------------------------------------------
import json
import random
import datetime
import operator
import os
import subprocess
import time
import sys
import webbrowser
import requests
from bs4 import BeautifulSoup
import wikipedia
import wolframalpha
import pyttsx3
import speech_recognition as sr
import pywhatkit
 
from Intents import greetings, farewell

from rich import print
from rich.panel import Panel
from rich.text import Text
#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'Baxter'
#-------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------
                            #Fancy Output for Terminal
#-------------------------------------------------------------------------------------
def BaxterOutput(text):
    output = Text(text)
    output.stylize("bold green")
    print("\n")
    print(Panel(output, title="[green]B.A.X.T.E.R"))

def CommanderInput(text):
    input = Text(text)
    input.stylize("bold yellow")
    print("\n")
    print(Panel(input, title="[yellow]" + Commander))
#-------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------
#                                  Voice Settings
#-------------------------------------------------------------------------------------
def speak(audio):
    speaker = pyttsx3.init ()
    voices = speaker.getProperty('voices')
    speaker.setProperty('voice',voices[2].id)
    speaker.setProperty ('rate', 180)
    speaker.say (audio)
    speaker.runAndWait () 
# # Test to see all avaliable voices
# engine = pyttsx3.init()
# voices = engine.getProperty('voices')
# for voice in voices:
#     print(voice, voice.id)
#     engine.setProperty('voice', voice.id)
#     engine.say("Hello World!")
#     engine.runAndWait()
#     engine.stop()
#-------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------
#                                Listen Function
#-------------------------------------------------------------------------------------
def listen():
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        BaxterOutput("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        BaxterOutput("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        # CommanderInput(f'{Commander} : {command}\n')
        CommanderInput(command)

        # # Wait for WakeWord
        # if (command.split(' ')[0] == AI_Name):
        #     speak("Executing Command")
        #     process(command)
    #--------------------------------

    except:
            pass

    return command 
#-------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------
#                                  WishMe Function
#-------------------------------------------------------------------------------------
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)   
    else:
        speak("Good Evening" + Commander) 
#-------------------------------------------------------------------------------------


#-------------------------------------------------------------------------------------
#                                       Main
#-------------------------------------------------------------------------------------
def BAXTER():
    command = listen()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #General Conversation (From Intents.py) 
    #-------------------------------------------------------------------------------------
    #Greetings
    patterns, responses = greetings()
    if (command in patterns):
        response = (random.choice(responses))
        BaxterOutput(response)
        speak(response)

    #Farewell
    patterns, responses = farewell()
    if (command in patterns):
        response = (random.choice(responses))
        BaxterOutput(response)
        speak(response)

    # #-------------------------------------------------------------------------------------
    #                         #Search Wikipedia (General Info)
    # #-------------------------------------------------------------------------------------
    # if ('weather' not in command): 
    #     if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command):
    #         if ('time' not in command):
    #             if ('news' not in command):
    #                 speak('Searching Wikipedia...')
    #                 command = command.replace("who is","")
    #                 command = command.replace("what is the","")
    #                 command = command.replace("what is a","")
    #                 command = command.replace("what is","")
    #                 results = wikipedia.summary(command, sentences = 2)
    #                 #----------------------
    #                 #Auto typing animation:
    #                 print("Baxter: ", end="")
    #                 for i in results:
    #                     sys.stdout.write(i)
    #                     sys.stdout.flush()
    #                     time.sleep(0.05)
    #                 print("\n")
    #                 #----------------------
    #                 speak(results) 
                    
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('news' not in command):
            if ('calculate' in command) or ("what's" in command) or ('define' in command):
                speak('Searching Wolfram Alpha...')
                command = command.replace("calculate","")
                command = command.replace("what's","")
                command = command.replace("define","")
                # Wolframalpha App Id
                appId = 'JH9XHR-W9J76L7H5A'
                # Wolfram Instance
                client = wolframalpha.Client(appId)
                res = client.query(''.join(command))
                results = next(res.results).text
                #----------------------
                #Auto typing animation:
                print("Baxter: ", end="")
                for i in results:
                    sys.stdout.write(i)
                    sys.stdout.flush()
                    time.sleep(0.05)
                print("\n")
                #----------------------
                speak(results)

    #-------------------------------------------------------------------------------------
                            #Open Stuff on the Internet
    #-------------------------------------------------------------------------------------
    #Open Youtube Videos (Ex: 'Play __ on youtube')
    if ('youtube' in command):
        speak('Launching Youtube')
        command = command.replace("youtube","")
        pywhatkit.playonyt(command)

    #Open Google Maps and Find The Location of A You Want
    if ('where is' in command):
        command = command.replace("where is","")
        speak('Locating' + command)
        webbrowser.open_new_tab("https://www.google.com/maps/place/" + command)

    #Search Stuff on Google
    if ('search' in command):
        command = command.replace("search", "")
        speak('Searching' + command)
        pywhatkit.search(command)
    
    #Find info about stuff
    if ('what is' in command):
        command = command.replace("what is", "")
        speak('Searching' + command)
        pywhatkit.info(command, lines = 4)

    #Close Firefox
    if ('close firefox' in command):
        speak('Closing Firefox')
        command = command.replace("close firefox", "")
        browser = "firefox.exe"
        os.system("taskkill /f /im " + browser)   

    #-------------------------------------------------------------------------------------
                            #Open Stuff on the Computer
    #-------------------------------------------------------------------------------------
    #Open Windows Media Player and Auto Play the Playlist Called Music
    if ('play music' in command) or ('media player' in command) or ('drop the needle' in command):
        speak('Launching Music')
        command = command.replace("play music", "")
        command = command.replace("media player", "")
        command = command.replace("drop the needle", "") 
        subprocess.Popen("C:\Program Files (x86)\Windows Media Player\wmplayer.exe /Playlist Music")

    #Close Windows Media Player
    if ('stop music' in command):
        speak('Closing Music')
        command = command.replace("stop music", "")
        mediaPlayer = "wmplayer.exe"
        os.system("taskkill /f /im " + mediaPlayer)   

    #-------------------------------------------------------------------------------------
                            #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    if ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        response = "Terminating program..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------

#------------------------------------------------------------------------------------------
#                                   Run The Program
#------------------------------------------------------------------------------------------
wishMe()
speak("How may I be of service?") 

while True:
    BAXTER()
#------------------------------------------------------------------------------------------
I believe it is speaking the returned result. No paragraph is returned if the topic is not found. Add a print command to print the result. Come back and post results if the printed results don't match the spoken results.

Or you could do try handling a None result.
#Find info about stuff
if ('what is' in command):
    command = command.replace("what is", "")
    speak('Searching' + command)
    result = pywhatkit.info(command, lines = 4)
    if result:
        speak(result)
    else:
        speak(f"No results found for query {command}")