Kxffie

ChatGPT Bot with Speech Recognition

Dec 10th, 2022 (edited)
1,365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | Source Code | 0 0
  1. # For my youtube channel- https://www.youtube.com/watch?v=5QcHZVzTj74
  2. # updated code: you can now say goodbye in a sentence and itll turn off.
  3.  
  4. from pyChatGPT import ChatGPT
  5. from dotenv import load_dotenv
  6. import speech_recognition as sr
  7. import os
  8. import pyttsx3
  9. load_dotenv()
  10. api = ChatGPT(os.getenv('OPENAI_API_KEY'))
  11. stoppingWords = ["stop", "goodbye", "bye", "exit", "quit"]
  12. engine = pyttsx3.init()
  13. engine.setProperty('rate', 130)
  14.  
  15. os.system('cls' if os.name == 'nt' else 'clear')
  16.  
  17. function = input("Would you like to use the chatbot or the voice assistant? (chat/voice) ")
  18. def main():
  19.     if function == "chat":
  20.         print("Type 'stop' to exit the chatbot.")
  21.         inp = input("Type something! > ")
  22.         response = api.send_message(inp)
  23.         print(response["message"])
  24.        
  25.     else:
  26.         r = sr.Recognizer()
  27.         with sr.Microphone() as source:
  28.             r.adjust_for_ambient_noise(source)
  29.             print("Say something!")
  30.             audio = r.listen(source)
  31.            
  32.             try:
  33.                 print(f"You said: {r.recognize_google(audio)}")
  34.                
  35.                 if any(word in r.recognize_google(audio).split() for word in stoppingWords):
  36.                     engine.say("Goodbye!")
  37.                     engine.runAndWait()
  38.                     exit()
  39.                 else:
  40.                     engine.say("Thinking of a response...")
  41.                     engine.runAndWait()
  42.                     response = api.send_message(r.recognize_google(audio))
  43.                     engine.say(response["message"])
  44.                     engine.runAndWait()
  45.                
  46.             except Exception as e:
  47.                 print(f"Error: {e}")
  48.  
  49. while True :
  50.     main()
Advertisement
Add Comment
Please, Sign In to add comment