File size: 1,678 Bytes
034895f
 
 
 
 
4cdfeed
034895f
 
 
43a9c3d
034895f
 
 
 
 
 
 
 
 
 
 
4cdfeed
034895f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d0165
034895f
 
 
 
 
 
 
 
 
 
37f7177
034895f
fee5ff6
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
#pip install openai
#pip install gradio
#pip install pyttsx3
#pip install pydantic
#pip install openai gradio pyttsx3 pydantic
#pip install python-dotenv

import gradio as gr
import openai
import pyttsx3
#import pydantic

from dotenv import load_dotenv
import os
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

#openai.api_key = ""

#   Global variable to hold the chat history, initialise with system role
conversation = [
        {"role": "system", "content": "You are an intelligent professor."}
        ]

#   transcribe function to record the audio input

def transcribe(audio):
    print(audio)

#   Whisper API

    audio_file = open(audio, "rb")
    transcript = openai.Audio.transcribe("whisper-1", audio_file)


    print(transcript)

#   ChatGPT API

#   append user's inut to conversation
    conversation.append({"role": "user", "content": transcript["text"]})

    response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=conversation
    )
    
    print(response)

#   system_message is the response from ChatGPT API
    system_message = response["choices"][0]["message"]["content"]

#   append ChatGPT response (assistant role) back to conversation
    conversation.append({"role": "assistant", "content": system_message})


#   Text to speech
    engine = pyttsx3.init()
    engine.setProperty("rate", 150)
    engine.setProperty("voice", "english-us")
    engine.save_to_file(system_message, "response.mp3")
    engine.runAndWait()

    return "response.mp3"

#   Gradio output

bot = gr.Interface(fn=transcribe, inputs=gr.Audio(source="microphone", type="filepath"), outputs="audio")
bot.launch(share=False)

iface.share()