Spaces:
Runtime error
Runtime error
import openai | |
import pyttsx3 | |
import speech_recognition as sr | |
openai.api_key = "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" | |
#initialize engine (text to speech) | |
engine = pyttsx3.init() | |
def transcribe_audio_to_tell(filename): | |
recognizer = sr.Recognizer() | |
with sr.Audiofile(filename) as source: | |
audio = recognizer.record(source) | |
try: | |
return recognizer.recognize_google(audio) | |
except: | |
print('Skipping unknown error') | |
def generate_response(prompt): | |
response = openai.Completion.create( | |
engine = "text-davinci-003", | |
prompt = prompt, | |
max_token = 4000, | |
n = 1, | |
stop = None, | |
temperature = 0.5, | |
) | |
return response["choices"][0]["text"] | |
def speak_text(text): | |
engine.say(text) | |
engine.runAndWait() | |
def main(): | |
while True: | |
print("say 'Genius' to start recording your question...") | |
with sr.Microphone() as source: | |
recognizer = sr.recognizer() | |
audio = recognizer.listen(source) | |
try: | |
transcription = recognizer.recognize_google(audio) | |
if transcription.lower() == "genius": | |
#RECORD AUDIO | |
filename = "input.wav" | |
print("say your question") | |
with sr.Microphone() as source: | |
recognizer = sr,recognizer() | |
source.pause_threshold = 1 | |
audio = recognizer.listen(source, phrase_time_limit = None, timeout = None) | |
with open(filename, "wb") as f: | |
f.write(audio.get_wav_data()) | |
#AUDIO TO TEXT | |
text = transcribe_audio_to_tell(filename) | |
if text: | |
print(f"you said: {text}") | |
#RESPONSE USING GPT | |
response = geneate_response(text) | |
print(f"GPT-3 says: {response}") | |
#RECORD AUDIO USING GTTS | |
tts = gTTS(text=response, lang='en') | |
tts.save("sample.mp3") | |
#RESPONSE FROM TEXT TO SPEECH | |
speak_text(response) | |
except Exception as e: | |
print("An error occured: {}".format(e)) | |
if __name__=="__main__": | |
main() |