ChatBot with OpenAI API
import speech_recognition as sr
from gtts import gTTS
import pygame
import openai
import os
# Initialize the OpenAI API with your key
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
def recognize_speech_from_mic(recognizer, microphone):
"""Capture speech from the microphone and convert it to text."""
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
return recognizer.recognize_google(audio)
except sr.RequestError:
# API was unreachable or unresponsive
return "API unavailable"
except sr.UnknownValueError:
# Speech was unintelligible
return "Unable to recognize speech"
def get_openai_response(text):
backoff_time = 1
while True:
try:
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": text},
]
)
response_text = response.choices[0].message.content
print("Robot: " + response_text)
return response_text
except openai.RateLimitError:
print("Rate limit exceeded, waiting for " + str(backoff_time) +" seconds.")
time.sleep(backoff_time)
backoff_time *= 2
def speak(text):
"""Convert text to speech and play it."""
tts = gTTS(text=text, lang='en')
tts.save("response.mp3")
pygame.mixer.init()
pygame.mixer.music.load("response.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy(): # wait for audio to finish playing
continue
os.remove("response.mp3")
def start_chat():
recognizer = sr.Recognizer()
microphone = sr.Microphone(device_index=12)
speak("Hello, I'm Robot, what is your questions?")
while True:
print("Say something!")
speech_text = recognize_speech_from_mic(recognizer, microphone)
if speech_text not in ["API unavailable", "Unable to recognize speech"]:
if speech_text.upper() != "GOODBYE": #.find("GOOD BYE") != -1:
response_text = get_openai_response(speech_text)
speak(response_text)
else:
speak("Bye bye!")
return
if __name__ == "__main__":
start_chat()