-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyGpt.py
75 lines (53 loc) · 2.05 KB
/
pyGpt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import gtts
import os
import speech_recognition as sr
from time import sleep
import playsound
import openai
## Assigning API Key
openai.api_key = "Your_API_Key"
class pygpt:
def __init__(self):
return None
## Connecting with ChatGPT
def processing(self,query):
if query:
ans = openai.ChatCompletion.create(model='gpt-3.5-turbo',messages = [{'role':'system', 'content':'You are a helpful assistant'},
{'role':'user','content':query}])
return ans.choices[0].message["content"]
return None
## Function for ability to speak
def speak(self,text):
tts = gtts.gTTS(text,lang='en-In',slow=False)
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
os.remove(filename)
## Function for ability to listen
def get_audio(self):
recognize = sr.Recognizer()
# print(sr.Microphone().list_microphone_names())
with sr.Microphone(device_index=1) as mic:
print("Say Something......")
recognize.adjust_for_ambient_noise(mic,duration=0.2)
user_audio = recognize.listen(mic)
print("Stop")
try:
user_audio_text_data = recognize.recognize_google(audio_data=user_audio, language="en-In")
print(f"User :->> {user_audio_text_data}")
return user_audio_text_data.lower()
except ValueError:
print("I did not get it please try again!")
sleep(2)
return 'None'
## Main Function
if __name__=="__main__":
pg = pygpt()
pg.speak("How May I help you?")
while True:
user_query = pg.get_audio()
if 'exit' in user_query.lower():
break
gpt_reply = pg.processing(user_query)
print("gpt:-->>",gpt_reply)
pg.speak(gpt_reply)