forked from nickbild/voice_chatgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoice_chat.py
164 lines (122 loc) · 4.35 KB
/
voice_chat.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
################################################################
# Nick Bild
# January 2023
# https://github.com/nickbild/voice_chatgpt
#
# Voice-controlled ChatGPT prompt
################################################################
import os
import io
import sys
import asyncio
import argparse
import pyaudio
import wave
from google.cloud import speech
from google.cloud import texttospeech
from ChatGPT_lite.ChatGPT import Chatbot
gpt_response = ""
def speech_to_text(speech_file):
client = speech.SpeechClient()
with io.open(speech_file, "rb") as audio_file:
content = audio_file.read()
audio = speech.RecognitionAudio(content=content)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
language_code="en-US",
)
# Detects speech in the audio file
response = client.recognize(config=config, audio=audio)
stt = ""
for result in response.results:
stt += result.alternatives[0].transcript
return stt
def ask_chat_gpt(args, prompt):
global gpt_response
chat = Chatbot(args.session_token, args.bypass_node)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(chat.wait_for_ready())
response = loop.run_until_complete(chat.ask(prompt))
chat.close()
loop.stop()
gpt_response = response['answer']
return
def text_to_speech(tts):
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(text=tts)
# Build the voice request, select the language code ("en-US") and the ssml
voice = texttospeech.VoiceSelectionParams(
language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE
)
# Select the type of audio file you want returned
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.LINEAR16
)
# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(
input=synthesis_input, voice=voice, audio_config=audio_config
)
# The response's audio_content is binary.
with open("result.wav", "wb") as out:
# Write the response to the output file.
out.write(response.audio_content)
return
def record_wav():
form_1 = pyaudio.paInt16
chans = 1
samp_rate = 16000
chunk = 4096
record_secs = 3
dev_index = 1
wav_output_filename = 'input.wav'
audio = pyaudio.PyAudio()
# Create pyaudio stream.
stream = audio.open(format = form_1,rate = samp_rate,channels = chans, \
input_device_index = dev_index,input = True, \
frames_per_buffer=chunk)
print("recording")
frames = []
# Loop through stream and append audio chunks to frame array.
for ii in range(0,int((samp_rate/chunk)*record_secs)):
data = stream.read(chunk)
frames.append(data)
print("finished recording")
# Stop the stream, close it, and terminate the pyaudio instantiation.
stream.stop_stream()
stream.close()
audio.terminate()
# Save the audio frames as .wav file.
wavefile = wave.open(wav_output_filename,'wb')
wavefile.setnchannels(chans)
wavefile.setsampwidth(audio.get_sample_size(form_1))
wavefile.setframerate(samp_rate)
wavefile.writeframes(b''.join(frames))
wavefile.close()
return
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--session_token_file', type=str, default="openai_session.txt")
parser.add_argument('--bypass_node', type=str, default="https://gpt.pawan.krd")
args = parser.parse_args()
# Get OpenAI credentials from file.
text_file = open(args.session_token_file, "r")
args.session_token = text_file.read()
text_file.close()
# Get WAV from microphone.
record_wav()
# Convert audio into text.
question = speech_to_text("input.wav")
# Send text to ChatGPT.
print("Asking: {0}".format(question))
asyncio.coroutine(ask_chat_gpt(args, question))
print("Response: {0}".format(gpt_response))
# Convert ChatGPT response into audio.
text_to_speech(gpt_response)
# Play audio of reponse.
os.system("aplay result.wav")
if __name__ == "__main__":
main()