Рубрики
Без рубрики

Простой чат-бот с поддержкой голоса на Python.

Краткое руководство о том, как создать чат-бота, используя только чистый Python.

Автор оригинала: Edward Zion Saji.

Я думал, есть ли способ закодировать чат-бота, используя только чистый Python. Хотя этот метод может быть не таким “умным” или “быстрым”, как AIM или скрипт чата, он все равно очень прост. Это помогает новичкам понять, что такое чат-бот и как он работает.

Во-первых, важно понять разницу между чат-ботом и личным помощником ИИ. Чат-бот-это программа, которая может общаться с человеком естественным образом. Но это не значит, что он умный. Чат-бот требует предустановленной библиотеки ответов на набор вопросов.

Помощник по искусственному интеллекту собирает информацию, такую как ваши данные о просмотре и ваши интересы, и облегчает ваш опыт работы в Интернете. Это поможет вам легко выполнять определенные задачи, такие как магазин. Одним из примеров является помощник Amazon, который помогает вам, давая предложения, основанные на ваших интересах.

Итак, вот учебник о том, как создать чат-бота с поддержкой голоса, используя чистый Python. В этом уроке мы будем использовать Python 3. Я предлагаю использовать PyCharm для кодирования на Python. Версия сообщества бесплатна. Вы все еще можете использовать ПРАЗДНЫЕ или другие идеи.

  1. Сначала установите все необходимые модули с помощью pip. Прежде чем мы продолжим, нам нужно будет установить некоторые внешние модули.
pip install pyttsx3
pip install wikipedia
pip install SpeechRecognition
pip install pygame
pip install pyown

Поскольку мы используем интерфейс микрофона, нам нужно будет установить pyaudio.

pip install pyaudio

Если вы не знаете, как использовать pip, следуйте этому руководству

Мы собираемся использовать pyttsx3 для преобразования текста в речь, Википедию для получения данных из Интернета, pyowm для получения данных о погоде и speech_recognition для преобразования речи в текст с помощью механизма распознавания речи Google.

Чтобы использовать pyowm, вам понадобится ключ API. Вы можете получить ключ API бесплатно по адресу https://home.openweathermap.org/users/sign_up 2) Импортируйте все необходимые модули. Мы собираемся использовать модуль random для генерации случайных ответов из нашего списка ответов. Импортируйте следующие модули в новый файл Python.

import random
import datetime
import webbrowser
import pyttsx3
import wikipedia
from pygame import mixer
import speech_recognition as sr
  1. Настройте и откалибруйте механизм преобразования текста в речь. Теперь нам нужно установить скорость передачи голоса, двигатель и т. Д.
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
volume = engine.getProperty('volume')
engine.setProperty('volume', 10.0)
rate = engine.getProperty('rate')
engine.setProperty('rate', rate - 25)
  1. Создавайте списки с заранее заданными ответами на вопросы. Чем больше списков, тем лучше. Но слишком много списков может замедлить работу чат-бота.
greetings = ['hey there', 'hello', 'hi', 'Hai', 'hey!', 'hey']
question = ['How are you?', 'How are you doing?']
responses = ['Okay', "I'm fine"]
var1 = ['who made you', 'who created you']
var2 = ['I_was_created_by_Edward_right_in_his_computer.', 'Edward', 'Some_guy_whom_i_never_got_to_know.']
var3 = ['what time is it', 'what is the time', 'time']
var4 = ['who are you', 'what is you name']
cmd1 = ['open browser', 'open google']
cmd2 = ['play music', 'play songs', 'play a song', 'open music player']
cmd3 = ['tell a joke', 'tell me a joke', 'say something funny', 'tell something funny']
jokes = ['Can a kangaroo jump higher than a house? Of course, a house doesn't jump at all.', 'My dog used to chase people on a bike a lot. It got so bad, finally I had to take his bike away.', 'Doctor: Im sorry but you suffer from a terminal illness and have only 10 to live.Patient: What do you mean, 10? 10 what? Months? Weeks?!"Doctor: Nine.']
cmd4 = ['open youtube', 'i want to watch a video']
cmd5 = ['tell me the weather', 'weather', 'what about the weather']
cmd6 = ['exit', 'close', 'goodbye', 'nothing']
cmd7 = ['what is your color', 'what is your colour', 'your color', 'your color?']
colrep = ['Right now its rainbow', 'Right now its transparent', 'Right now its non chromatic']
cmd8 = ['what is you favourite colour', 'what is your favourite color']
cmd9 = ['thank you']
repfr9 = ['youre welcome', 'glad i could help you']
  1. Откалибруйте механизм распознавания речи. Мы собираемся использовать механизм распознавания речи Google. Установите детали двигателя. Также используйте цикл while для перезапуска двигателя в случае каких-либо ошибок.
while True:
    now = datetime.datetime.now()
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Tell me something:")
        audio = r.listen(source)
        try:
            print("You said:- " + r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Could not understand audio")
            engine.say('I didnt get that. Rerun the code')
            engine.runAndWait()
            
            
  1. Используйте код цикла с random и Wikipedia, чтобы закончить код. Мы собираемся использовать вышеупомянутые модули в циклическом коде для создания основного функционального кода.
if r.recognize_google(audio) in greetings:
       random_greeting = random.choice(greetings)
       print(random_greeting)
       engine.say(random_greeting)
       engine.runAndWait()
   elif r.recognize_google(audio) in question:
       engine.say('I am fine')
       engine.runAndWait()
       print('I am fine')
   elif r.recognize_google(audio) in var1:
       engine.say('I was made by edward')
       engine.runAndWait()
       reply = random.choice(var2)
       print(reply)
   elif r.recognize_google(audio) in cmd9:
       print(random.choice(repfr9))
       engine.say(random.choice(repfr9))
       engine.runAndWait()
   elif r.recognize_google(audio) in cmd7:
       print(random.choice(colrep))
       engine.say(random.choice(colrep))
       engine.runAndWait()
       print('It keeps changing every micro second')
       engine.say('It keeps changing every micro second')
       engine.runAndWait()
   elif r.recognize_google(audio) in cmd8:
       print(random.choice(colrep))
       engine.say(random.choice(colrep))
       engine.runAndWait()
       print('It keeps changing every micro second')
       engine.say('It keeps changing every micro second')
       engine.runAndWait()
   elif r.recognize_google(audio) in cmd2:
       mixer.init()
       mixer.music.load("C:\\Users\Edward Zion SAJI\Downloads\Mighty_God_-_Martin__Colleen_Rebeiro.55145718.wav")
       mixer.music.play()
   elif r.recognize_google(audio) in var4:
       engine.say('I am edza your personal AI assistant')
       engine.runAndWait()
   elif r.recognize_google(audio) in cmd4:
       webbrowser.open('www.youtube.com')
   elif r.recognize_google(audio) in cmd6:
       print('see you later')
       engine.say('see you later')
       engine.runAndWait()
       exit()
   elif r.recognize_google(audio) in cmd5:
       owm = pyowm.OWM('YOUR_API_KEY')
       observation = owm.weather_at_place('Bangalore, IN')
       observation_list = owm.weather_around_coords(12.972442, 77.580643)
       w = observation.get_weather()
       w.get_wind()
       w.get_humidity()
       w.get_temperature('celsius')
       print(w)
       print(w.get_wind())
       print(w.get_humidity())
       print(w.get_temperature('celsius'))
       engine.say(w.get_wind())
       engine.runAndWait()
       engine.say('humidity')
       engine.runAndWait()
       engine.say(w.get_humidity())
       engine.runAndWait()
       engine.say('temperature')
       engine.runAndWait()
       engine.say(w.get_temperature('celsius'))
       engine.runAndWait()
   elif r.recognize_google(audio) in var3:

       print("Current date and time : ")
       print(now.strftime("The time is %H:%M"))
       engine.say(now.strftime("The time is %H:%M"))
       engine.runAndWait()
   elif r.recognize_google(audio) in cmd1:
       webbrowser.open('www.google.com')
   elif r.recognize_google(audio) in cmd3:
       jokrep = random.choice(jokes)
       engine.say(jokrep)
       engine.runAndWait()
   else:
       engine.say("please wait")
       engine.runAndWait()
       print(wikipedia.summary(r.recognize_google(audio)))
       engine.say(wikipedia.summary(r.recognize_google(audio)))
       engine.runAndWait()
       userInput3 = input("or else search in google")
       webbrowser.open_new('www.google.com/search?q=' + userInput3)
  1. Настройте код по своему усмотрению и создайте окончательный код. Теперь соедините все фрагменты кода. У тебя должно быть что-то вроде этого.
import random
import datetime
import webbrowser
import pyttsx3
import wikipedia
from pygame import mixer
import speech_recognition as sr
from speech_recognition.__main__ import r, audio

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
volume = engine.getProperty('volume')
engine.setProperty('volume', 10.0)
rate = engine.getProperty('rate')

engine.setProperty('rate', rate - 25)

greetings = ['hey there', 'hello', 'hi', 'Hai', 'hey!', 'hey']
question = ['How are you?', 'How are you doing?']
responses = ['Okay', "I'm fine"]
var1 = ['who made you', 'who created you']
var2 = ['I_was_created_by_Edward_right_in_his_computer.', 'Edward', 'Some_guy_whom_i_never_got_to_know.']
var3 = ['what time is it', 'what is the time', 'time']
var4 = ['who are you', 'what is you name']
cmd1 = ['open browser', 'open google']
cmd2 = ['play music', 'play songs', 'play a song', 'open music player']
cmd3 = ['tell a joke', 'tell me a joke', 'say something funny', 'tell something funny']
jokes = ['Can a kangaroo jump higher than a house? Of course, a house doesn't jump at all.', 'My dog used to chase people on a bike a lot. It got so bad, finally I had to take his bike away.', 'Doctor: Im sorry but you suffer from a terminal illness and have only 10 to live.Patient: What do you mean, 10? 10 what? Months? Weeks?!"Doctor: Nine.']
cmd4 = ['open youtube', 'i want to watch a video']
cmd5 = ['tell me the weather', 'weather', 'what about the weather']
cmd6 = ['exit', 'close', 'goodbye', 'nothing']
cmd7 = ['what is your color', 'what is your colour', 'your color', 'your color?']
colrep = ['Right now its rainbow', 'Right now its transparent', 'Right now its non chromatic']
cmd8 = ['what is you favourite colour', 'what is your favourite color']
cmd9 = ['thank you']

repfr9 = ['youre welcome', 'glad i could help you']

while True:
    now = datetime.datetime.now()
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Tell me something:")
        audio = r.listen(source)
        try:
            print("You said:- " + r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Could not understand audio")
            engine.say('I didnt get that. Rerun the code')

            engine.runAndWait()
    if r.recognize_google(audio) in greetings:
        random_greeting = random.choice(greetings)
        print(random_greeting)
        engine.say(random_greeting)
        engine.runAndWait()
    elif r.recognize_google(audio) in question:
        engine.say('I am fine')
        engine.runAndWait()
        print('I am fine')
    elif r.recognize_google(audio) in var1:
        engine.say('I was made by edward')
        engine.runAndWait()
        reply = random.choice(var2)
        print(reply)
    elif r.recognize_google(audio) in cmd9:
        print(random.choice(repfr9))
        engine.say(random.choice(repfr9))
        engine.runAndWait()
    elif r.recognize_google(audio) in cmd7:
        print(random.choice(colrep))
        engine.say(random.choice(colrep))
        engine.runAndWait()
        print('It keeps changing every micro second')
        engine.say('It keeps changing every micro second')
        engine.runAndWait()
    elif r.recognize_google(audio) in cmd8:
        print(random.choice(colrep))
        engine.say(random.choice(colrep))
        engine.runAndWait()
        print('It keeps changing every micro second')
        engine.say('It keeps changing every micro second')
        engine.runAndWait()
    elif r.recognize_google(audio) in cmd2:
        mixer.init()
        mixer.music.load("song.wav")
        mixer.music.play()
    elif r.recognize_google(audio) in var4:
        engine.say('I am a bot, silly')
        engine.runAndWait()
    elif r.recognize_google(audio) in cmd4:
        webbrowser.open('www.youtube.com')
    elif r.recognize_google(audio) in cmd6:
        print('see you later')
        engine.say('see you later')
        engine.runAndWait()
        exit()
    elif r.recognize_google(audio) in cmd5:
        owm = pyowm.OWM('YOUR_API_KEY')
        observation = owm.weather_at_place('Bangalore, IN')
        observation_list = owm.weather_around_coords(12.972442, 77.580643)
        w = observation.get_weather()
        w.get_wind()
        w.get_humidity()
        w.get_temperature('celsius')
        print(w)
        print(w.get_wind())
        print(w.get_humidity())
        print(w.get_temperature('celsius'))
        engine.say(w.get_wind())
        engine.runAndWait()
        engine.say('humidity')
        engine.runAndWait()
        engine.say(w.get_humidity())
        engine.runAndWait()
        engine.say('temperature')
        engine.runAndWait()
        engine.say(w.get_temperature('celsius'))
        engine.runAndWait()
    elif r.recognize_google(audio) in var3:

        print("Current date and time : ")
        print(now.strftime("The time is %H:%M"))
        engine.say(now.strftime("The time is %H:%M"))
        engine.runAndWait()
    elif r.recognize_google(audio) in cmd1:
        webbrowser.open('www.google.com')
    elif r.recognize_google(audio) in cmd3:
        jokrep = random.choice(jokes)
        engine.say(jokrep)
        engine.runAndWait()
    else:
        engine.say("please wait")
        engine.runAndWait()
        print(wikipedia.summary(r.recognize_google(audio)))
        engine.say(wikipedia.summary(r.recognize_google(audio)))
        engine.runAndWait()
        userInput3 = input("or else search in google")
        webbrowser.open_new('www.google.com/search?q=' + userInput3)

В случае, если вы получите ошибку, связанную с win32, запустите “ pip install pypiwin32

If you have more questions, leave a comment.


Thats all! Now test out your code and have fun!
Happy Coding!!!