Monday 22 January 2024

A simple Turkish speaking chatbot example (and working)


 

Not: Bazı şirketler telefonla arayan müşterilere otomatik olarak ne istediklerini sorup ona göre yönlendiriyorlar. Aslında bir kaç saatlik basit bir iş. İnternetteki bilgileri kullanarak kolayca yaptım bunu.

# -*- coding: utf-8 -*-

"""

Created on Fri Jan 19 15:43:41 2024

pip install speechRecognition

pip install gTTS

pip install pyaudio

@author: ars

"""

 

import speech_recognition as sr

from gtts import gTTS

import os

import datetime

import numpy as np

import time

 

# Beginning of the AI

class ChatBot():

    def __init__(self, name):

        print("----- starting up", name, "-----")

        self.name = name

        self.text = ""  # Initialize text attribute

       

    def speech_to_text(self):

        recognizer = sr.Recognizer()

        with sr.Microphone() as mic:

             print("dinliyorum...")

             audio = recognizer.listen(mic)

        try:

             self.text = recognizer.recognize_google(audio, language="tr-TR")

             print("me --> ", self.text)

             if "dur" in self.text.lower(): return False

        except:

             print("me -->  ERROR")

   

    def wake_up(self, text):

        return True if self.name in text.lower() else False

 

    @staticmethod

    def text_to_speech(text):

        print("AI --> ", text)

        speaker = gTTS(text=text, lang="tr", slow=False)

        speaker.save("res.mp3")

        mp3_path = os.path.join(os.getcwd(), "res.mp3")

        print(mp3_path)

        statbuf = os.stat("res.mp3")

        mbytes = statbuf.st_size / 1024

        duration = mbytes / 200

        os.system("start res.mp3")  #if you have a macbook->afplay or for windows use->start

        #os.remove("res.mp3")

        time.sleep(int(50*duration))

        os.remove("res.mp3")

       

    @staticmethod

    def action_time():

        return datetime.datetime.now().time().strftime('%H:%M')

    #and run the script after adding the above function to the AI class

 

# Execute the AI

if __name__ == "__main__":

    ai = ChatBot(name="başla")       

 

# Execute the AI

if __name__ == "__main__":

     ai = ChatBot(name="başla")

     while True:

         if ai.speech_to_text() == False:

             break

         # Default response

         res = "Anlayamadım. Tekrarlar mısınız?"

 

        ## wake up

         if ai.wake_up(ai.text) is True:

             res = "Merhaba ben suni zeka, sizin için ne yapabilirim?"

             ai.text = "xxx"

         ## do any action

         elif "saat" in ai.text:

            res = ai.action_time()

         ## respond politely

         elif any(i in ai.text for i in ["teşekkür","sağolun"]):

            res = np.random.choice(

                  ["estağfurullah!","her zaman!",

                   "sorun değil!","güzel!",

                   "İhtiyacınız olursa ben buradayım!","önemli değil!"])

         ai.text_to_speech(res)