小编趁着有空上去玩了一下,也发现了其中的强大
那么这里我们需要用到这几个库,用pip命令来下载
withst.sidebar:choose=option_menu("工具栏",["简介","AI聊天","AI绘画"],icons=['house','personlinesfill','app-indicator'],menu_icon="list",default_index=0,styles={"container":{"padding":"5!important","background-color":"#fafafa"},"icon":{"color":"orange","font-size":"25px"},"nav-link":{"font-size":"16px","text-align":"left","margin":"0px","--hover-color":"#eee"},"nav-link-selected":{"background-color":"#24A608"},})那么在“简介”这一栏当中,顾名思义就是对该网页简单的介绍,我们简单的写一些介绍,代码如下
ifchoose=="简介":col1,col2=st.columns([0.8,0.2])withcol1:#Todisplaytheheadertextusingcssstylest.markdown("""""",unsafe_allow_html=True)st.markdown('
那么首先我们需要在个人设置里面去获取一个秘钥,
然后选择一个模型,这里我们选择text-davinci-003模型,相比其他而言,性能更好,然后我们调用OpenAI里面的方法来生成回答
defChatGPT(user_query):completion=openai.Completion.create(engine=model_engine,prompt=user_query,max_tokens=1024,n=1,temperature=0.5,)response=completion.choices[0].textreturnresponse然后我们调用该函数结合streamlit当中的输入框,代码如下
elifchoose=="AI聊天":st.title("AI聊天机器人")#设置密匙model_engine="text-davinci-003"defChatGPT(user_query):completion=openai.Completion.create(engine=model_engine,prompt=user_query,max_tokens=1024,n=1,temperature=0.5,)response=completion.choices[0].textreturnresponseuser_query=st.text_input("在这里输入问题,回车查询","Python是什么?")ifuser_query!=":q"oruser_query!="":#将问题提交给ChatGPT,返回结果response=ChatGPT(user_query)st.write(f"{response}")
defimage_generate(user_demand):completion=openai.Image.create(prompt=user_demand,n=2,size="1024x1024")response=completion.get("data")returnresponse[0].get("url")由于返回给我们的是一个URL,因此还需要保存到本地,然后再通过Image模块打开,代码如下
image_url=image_generate(user_query)response=requests.get(image_url,stream=True)try:withopen("./image/01.png",'wb')asf:forchunkinresponse:f.write(chunk)f.close()print("Downloaddone!!")exceptExceptionase:print(e)img1=Image.open(r'./image/01.png')st.image(img1,width=500,caption='ImagebyOpenAI')最后就可以在终端运行下面的代码了,
streamlitrunexample.py我们在浏览器中打开页面,例如我们点击进入“AI聊天”这个模块,我们可以看到右上角处于RUNNING的状态,表示正在运行中,等会儿之后就能看到结果
而点击进入“AI绘画”这个模块,例如想要绘制可爱的猫咪,我们也能看到如下的结果