简体   繁体   English

Python Gtts助手

[英]Python Gtts Assistant

I have written a code for a simple assistant in Python using a tutorial from this website: https://randerson112358.medium.com/build-a-virtual-assistant-using-python-2b0f78e68b94 .我使用以下网站的教程在 Python 中编写了一个简单助手的代码: https://randerson112358.medium.com/build-a-virtual-assistant-using-python-2b0f78e68b94 The code of the creator is wrong though, and I have fixed some of the indentation errors.虽然创建者的代码是错误的,但我已经修复了一些缩进错误。 There are a few other errors to it though, which I'd like to fix.不过还有其他一些错误,我想修复。

Errors, such as:错误,例如:

Traceback (most recent call last):
  File "C:\Users\Johann\Desktop\BIZ\Python\BoringAuto1.py", line 120, in <module>
    assistantResponse(response)
  File "C:\Users\Johann\Desktop\BIZ\Python\BoringAuto1.py", line 33, in assistantResponse
    myobj = gTTS(text=text, lang="en", slow=False)
  File "C:\Users\Johann\AppData\Local\Programs\Python\Python39\lib\site-packages\gtts\tts.py", line 126, in __init__
    assert text, 'No text to speak'
AssertionError: No text to speak

It would be awesome, if you could assist me with that.如果你能帮助我,那就太棒了。 Here is the code:这是代码:

import speech_recognition as sr
import os
import datetime
import warnings
import calendar
from gtts import gTTS
import random
import wikipedia

warnings.filterwarnings('ignore')

def recordAudio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)

    data = ""
    try:
        data = r.recognize_google(audio)
        print("You said:  " + data)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand")
    except sr.RequestError as e:
        print("Request error from Google Speech Recognition")
    return data



def assistantResponse(text):
    print(text)

    myobj = gTTS(text=text, lang="en", slow=False)

    myobj.save("assistant_response.mp3")

    os.system("start assistant_response.mp3")

def wakeWord(text):
    WAKE_WORDS = ["hey computer", "okay boomer"]
    text = text.lower()

    for phrase in WAKE_WORDS:
        if phrase in text:
            return True

    return False



def getDate():
    
    now = datetime.datetime.now()
    my_date = datetime.datetime.today()
    weekday = calendar.day_name[my_date.weekday()]
    monthNum = now.month
    dayNum = now.day
    month_names = ['January', 'February', 'March', 'April', 'May',
       'June', 'July', 'August', 'September', 'October', 'November',   
       'December']
    ordinalNumbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', 
                      '7th', '8th', '9th', '10th', '11th', '12th',                      
                      '13th', '14th', '15th', '16th', '17th', 
                      '18th', '19th', '20th', '21st', '22nd', 
                      '23rd', '24th', '25th', '26th', '27th', 
                      '28th', '29th', '30th', '31st']
   
    return 'Today is ' + weekday + ' ' + month_names[monthNum - 1] + ' the ' + ordinalNumbers[dayNum - 1] + '.'


def greeting(text):
    GREETING_INPUTS = ["hi", "trump", "wassup"]
    GREETING_RESPONSES = ["howdy", "hola", "eyo", "wassup bro"]
    for word in text.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES) + '.'
    return ""


def getPerson(text):
    wordList = text.split()

    for i in range(0, len(wordList)):
        if i + 3 <= len(wordList) - 1 and wordList[i].lower() == 'who' and wordList[i + 1].lower() == 'is':
            return wordList[i + 2] + ' ' + wordList[i + 3]
a = 0
while a < 10:
    text = recordAudio()
    response = ""

    if (wakeWord(text) == True):
        response = response + greeting(text)

        if ("date" in text):
            get_date = getDate()
            response = response + "" + get_date

        if ("time" in text):
            now = datetime.datetime.now()
            meridiem = ""
            if now.hour >= 12:
                meridiem = "p.m."
                hour = now.hour - 12
            else:
                meridiem = "a.m."
                hour = now.hour

            if now.minute < 10:
                    minute = "0"+str(now.minute)
            else:
                minute = str(now.minute)
                        
            response = response + ' '+ 'It is '+ str(hour)+ ':'+minute+' '+meridiem+' .'

    if ("who is" in text):
        person = getPerson(text)
        wiki = wikipedia.summary(person, sentences=2)
        response = response + "" + wiki

    assistantResponse(response)

Thanks in advance!提前致谢!

Best regards, Johann最好的问候,约翰

First, before speaking, check if there is any text to speak:首先,在说话之前,检查是否有任何文字要说话:

if response != "":
  assistantResponse(response)

Secondly, you can wrap the 'who is' function in a try except block to catch 'not found' error.其次,您可以将“谁是” function 包装在 try except 块中以捕获“未找到”错误。

def getPerson(text):
  wordList = text.split()
  for i in range(0, len(wordList)):
    if i + 3 <= len(wordList) - 1 and wordList[i].lower() == 'who' and wordList[i + 1].lower() == 'is':
      return wordList[i + 2] + ' ' + wordList[i + 3]
  return ""
if 'who is' in text:
  person = getPerson(text)
  if person != "":
    wiki = wikipedia.summary(person, sentences=2)
    response += wiki
  else:
    response += "I could not find the person you were looking for"

This should catch all the errors I got when testing your program.这应该会捕获我在测试程序时遇到的所有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM