Googles Text to speech (PYTHON CODE HELP)

I thought id give it a try here since the pythons forum is no help. if anyone knows how to implement text to speech code in python. Im trying to have my virtual assistant read me back the first couple lines of my google search. code provided.

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import time
import webbrowser
import os
import smtplib
from googlesearch import *

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)


def speak(audio):
    engine.say(audio)
    engine.runAndWait()


def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        print("Good Morning Justin.")
        speak("Good Morning Justin!")

    elif hour>=12 and hour<18:
        print("Good Afternoon Justin.")
        speak("Good Afternoon Justin!")

    else:
        print("Good Evening Justin.")
        speak("Good Evening Justin!")

    print("Initializing SAM...")

    time.sleep(3) # Sleep for 3 seconds

    print("Waiting for your command...")
    speak("Waiting for your command...")

def takeCommand():
    #It takes microphone input from the user and returns string output

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        # print(e)
        print("Say that again please...")
        return "None"
    return query

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('')
    server.sendmail('', to, content)
    server.close()

if __name__ == " __main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()

        # Logic for executing tasks based on query
        if 'who' in query:
            print("Searching Google...")
            speak('Searching Google...')
            query = query.replace("google", "")
            chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
            for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
                webbrowser.open("https://google.com/search?q=%s" % query)
            print("This is what I found according to your search")
            speak("This is what I found according to your search")

        elif 'what' in query:
            print("Searching Google...")
            speak('Searching Google...')
            query = query.replace("google", "")
            chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
            for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
                webbrowser.open("https://google.com/search?q=%s" % query)
            print("This is what I found according to your search")
            speak("This is what I found according to your search")

        elif 'when' in query:
            print("Searching Google...")
            speak('Searching Google...')
            query = query.replace("google", "")
            chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
            for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
                webbrowser.open("https://google.com/search?q=%s" % query)
            print("This is what I found according to your search")
            speak("This is what I found according to your search")

        elif 'where' in query:
            print("Searching Google...")
            speak('Searching Google...')
            query = query.replace("google", "")
            chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
            for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
                webbrowser.open("https://google.com/search?q=%s" % query)
            print("This is what I found according to your search")
            speak("This is what I found according to your search")

        elif 'why' in query:
            print("Searching Google...")
            speak('Searching Google...')
            query = query.replace("google", "")
            chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
            for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
                webbrowser.open("https://google.com/search?q=%s" % query)
            print("This is what I found according to your search")
            speak("This is what I found according to your search")

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

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

        elif 'goodbye sam' in query:
            speak('Goodbye Justin')
            quit()

        elif 'play music' in query:
            webbrowser.open("")

        elif 'time' in query:
            strTime = datetime.datetime.now().strftime("%I:%M: %p")
            speak(f"the time is {strTime}")

        elif 'date' in query:
            strTime = datetime.datetime.now().strftime("%Y/%m/%d")
            speak(f"the date is {strTime}")

        elif 'open code' in query:
            codePath = "C:\\Users\\Owner\\Desktop\\SAM"
            os.startfile(codePath)

        elif 'email danny' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = ""
                sendEmail(to, content)
                speak("Email sent.")
            except Exception as e:
                print(e)
                speak("Sorry Justin. I was not able to send this email")
1 Like

First, did you mean to say “google’s speech to text”?  I’m guessing that the text-to-speech part is actually working (i.e. in “wishMe”).

So you don’t tell us how it “fails”. Have you played back the recorded audio to check for quality, ambient noise, etc?

ah yes my apologies, so everything works good. when i ask the virtual assistant my question, it searches good but what i’m trying to make it do is repeat the first two lines or so of the search result back to me in audio form. that’s all, i just don’t know how to implement something like that.

google is what i meant, not good

what i’m trying to make it do is repeat the first two lines or so of the search result back to me in audio form. 

Right. This is called “web scraping”. Here are a couple of possibly useful links. The beautifulsoup library has a good rep.

Link 1

Link 2

thank you, i’ll see if it works

by any chance do you have any recommendations on what to add or change to the code? im fairly new to python and im leaning towards to starting to add my own code to this virtual assitant. 

Less “python” and more general programming principles. E.g. I’d apply the DRY (“don’t repeat yourself”) principle to the who/what/why/etc tests:

# actually move to initialization
google_words = ['who','what','why','when','where','how']

if any(word in query for word in google_words):
    letmegooglethatforyou(query)
    continue

if (... more pattern tests...)

where “letmegooglethatforyou” is a function. You’ll be extending that to voice the results, might as well do that once and not many times. And you can easily add more words without copy-pasting code.

Keep in mind that python’s “in” test is “greedy”: the word “how” will match “however”, “shower”, etc. That might not matter to you.

It looks pretty straightforward to me!

My problem is this. Ive figured out how to add more words to the query but i also need to add the other words to the .replace i just dont know how.

elif 'where is' in query or 'where\'s' in query:
            query = query.replace("where is", "")
            webbrowser.open(f'https://www.google.nl/maps/place/?q={query}')
            speak("here is where it is.")

notice how there are two words in the top query list “where is” and “where’s”, i want to add that additional “where/'s” to the “query.replace” so it will exclude the “where’s” from the search of the user. every time i try i always get an error of the string not being able to become a list.

update: figured out this issue by just adding another .replace after the previous .replace

Still trying to figure out how to get the virtual assitant to repeat the search results back to me.