1. Preparation
申请openAI的Key
2. ChatGPT can speak Chinese, English and Japanese.
import openai
import pyttsx3
import os
import time,re
def completions(msg):
openai.api_key = 'Your openAI API Key goes here!'
response = openai.Completion.create(
model='text-davinci-003',
prompt= msg,
temperature=0.5,
max_tokens=300,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.0,
)
return response.choices[0].text
#print(response.choices[0].text)
def contains_chinese(strs):
chinese = re.compile(r'[\u4e00-\u9fa5]')
if chinese.search(strs):
return True
return False
def contains_japanese(strs):
jap = re.compile(r'[\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7A3]') # \uAC00-\uD7A3为匹配韩文的,其余为日文
if jap.search(strs):
return True
return False
def speak_out(msg):
engine = pyttsx3.init()
voices = engine.getProperty('voices')
if contains_japanese(msg):
engine.setProperty('voice', voices[2].id) #changing voice to index 1 for female voice
elif contains_chinese(msg):
engine.setProperty('voice', voices[0].id)
else:
engine.setProperty('voice', voices[3].id)
engine.setProperty('volume', 1.0)
engine.setProperty('rate', 180)
engine.say(msg)
engine.runAndWait()
def chat_log(content):
with open("./ChatLog.txt", "a") as file:
file.write(content + "\n")
def main():
select_menus = ""
while True:
select_menus = ""
print("\n\n************************* ChatGPT *************************")
print("I. ChatGPT II. Quit")
select_menus = input()
if select_menus == "I":
print("Chat Time: " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
chat_log("Chat Time: " + current_time)
while True:
msg = input("You >>>\n")
chat_log("You >>>\n" + msg)
speak_out(msg)
reply = completions(msg)
print("ChatGPT >>>\n" + reply)
speak_out(reply)
chat_log("ChatGPT >>>\n" + reply)
elif select_menus == "II":
break
else:
print("Input error, choose again please!")
if __name__ == "__main__":
main()