聊天机器人开发

聊天机器人开发_第1张图片

 

# -*- coding:utf-8 -*-
#mykey2robot=sk-xo0DRLXavEGxg8IlBZCURwGSBui7sNC4
import openai
import os, sys,time
from tkinter import *
from tkinter.font import Font
from tkinter.ttk import *
import wenxin_api
#pip install wenxin_api
from wenxin_api.tasks.free_qa import FreeQA
import json
import urllib.request
# api_url = "http://openapi.turingapi.com/openapi/api/v2"
# json_path = 'turingreq.json'
# Set the API key for the openai module
with open(r'gpt-key.txt', 'r') as loadbootkeygpt:
    boothidevalue = loadbootkeygpt.read().replace('\n','')
# openai.api_key = "sk-xo0DRLXavEGSBui7sNC4"
openai.api_key =boothidevalue
class Application_ui(Frame):
    # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title('Rogabet chat robot')
        self.master.geometry('955x500')
        self.createWidgets()
    def createWidgets(self):
        self.top = self.winfo_toplevel()
        self.style = Style()
        self.style.configure('Tftitle.TLabelframe', font=('楷体', 12))
        self.style.configure('Tftitle.TLabelframe.Label', font=('楷体', 12))
        self.ftitle = LabelFrame(self.top, text='图灵 + 百度文心一言 + chatGPT', style='Tftitle.TLabelframe')
        self.ftitle.place(relx=0.008, rely=0.017, relwidth=0.982, relheight=0.998)
        self.stext = Text(self.ftitle, font=('楷体', 12) )#, wrap=NONE,
        self.stext.place(relx=0.017, rely=0.036, relwidth=0.957, relheight=0.412)

        # 垂直滚动条
        self.VScroll1 = Scrollbar(self.stext, orient='vertical')
        self.VScroll1.pack(side=RIGHT, fill=Y)
        self.VScroll1.config(command=self.stext.yview) # 将文本框关联到滚动条上,滚动条滑动,文本框跟随滑动
        self.stext.config(yscrollcommand=self.VScroll1.set) # 将滚动条关联到文本框
        # 水平滚动条
        self.stextxscroll = Scrollbar(self.stext, orient=HORIZONTAL)
        self.stextxscroll.pack(side=BOTTOM, fill=X) # side是滚动条放置的位置,上下左右。fill是将滚动条沿着y轴填充
        self.stextxscroll.config(command=self.stext.xview) # 将文本框关联到滚动条上,滚动条滑动,文本框跟随滑动
        self.stext.config(xscrollcommand=self.stextxscroll.set) # 将滚动条关联到文本框

        self.totext = Text(self.ftitle, font=('楷体', 12))# , wrap=NONE
        self.totext.place(relx=0.017, rely=0.552, relwidth=0.957, relheight=0.412)

        self.VScroll2 = Scrollbar(self.totext, orient='vertical')
        self.VScroll2.pack(side=RIGHT, fill=Y)
        # 将滚动条与文本框关联
        self.VScroll2.config(command=self.totext.yview) # 将文本框关联到滚动条上,滚动条滑动,文本框跟随滑动
        self.totext.config(yscrollcommand=self.VScroll2.set) # 将滚动条关联到文本框
        # 水平滚动条
        self.totextxscroll = Scrollbar(self.totext, orient=HORIZONTAL)
        self.totextxscroll.pack(side=BOTTOM, fill=X) # side是滚动条放置的位置,上下左右。fill是将滚动条沿着y轴填充
        self.totextxscroll.config(command=self.totext.xview) # 将文本框关联到滚动条上,滚动条滑动,文本框跟随滑动
        self.totext.config(xscrollcommand=self.totextxscroll.set) # 将滚动条关联到文本框

        def cut(editor, event=None):
            editor.event_generate("<>")

        def copy(editor, event=None):
            editor.event_generate("<>")

        def paste(editor, event=None):
            editor.event_generate('<>')

        def rightKey(event, editor):
            menubar.delete(0, END)
            menubar.add_command(label='剪切', command=lambda: cut(editor))
            menubar.add_command(label='复制', command=lambda: copy(editor))
            menubar.add_command(label='粘贴', command=lambda: paste(editor))
            menubar.post(event.x_root, event.y_root)

        menubar = Menu(self.top, tearoff=False) # 创建一个菜单
        self.stext.bind("", lambda x: rightKey(x, self.stext)) # 绑定右键鼠标事件
        self.totext.bind("", lambda x: rightKey(x, self.totext)) # 绑定右键鼠标事件

        self.style.configure('Tcleartext.TButton', font=('楷体', 12))
        self.cleartext = Button(self.ftitle, text='清空', command=self.cleartext_Cmd, style='Tcleartext.TButton')
        self.cleartext.place(relx=0.039, rely=0.463, relwidth=0.086, relheight=0.073)

        self.style.configure('Taddyh.TButton', font=('楷体', 12))
        self.addyh = Button(self.ftitle, text='GPT-回答', command=self.addyh_Cmd,
                            style='Taddyh.TButton')
        self.addyh.place(relx=0.709, rely=0.463, relwidth=0.1, relheight=0.073)

        self.addyhchutu = Button(self.ftitle, text='GPT出图', command=self.addyh_Cmdiage,
                            style='Taddyh.TButton')
        self.addyhchutu.place(relx=0.809, rely=0.463, relwidth=0.1, relheight=0.073)

        self.addtuling = Button(self.ftitle, text='图灵问答', command=self.addwdtuling,
                                 style='Taddyh.TButton')
        self.addtuling.place(relx=0.139, rely=0.463, relwidth=0.1, relheight=0.073)

        self.addwenxin = Button(self.ftitle, text='文心问答', command=self.wenxin,
                                style='Taddyh.TButton')
        self.addwenxin.place(relx=0.609, rely=0.463, relwidth=0.1, relheight=0.073)

        self.addxunfei = Button(self.ftitle, text='讯飞问答', command=self.xunfei,
                                style='Taddyh.TButton')
        self.addxunfei.place(relx=0.239, rely=0.463, relwidth=0.1, relheight=0.073)

# #addyh_Cmdiage

class Application(Application_ui):
    # 这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。
    def __init__(self, master=None):
        Application_ui.__init__(self, master)

    def cleartext_Cmd(self, event=None):
        # TODO, Please finish the function here!
        # 清空两个文本框
        self.stext.delete(1.0, "end")
        self.totext.delete(1.0, "end")

    def addyh_Cmd(self, event=None): #chatgpt
        # TODO, Please finish the function here!
        self.totext.delete(1.0, "end")
        cookiestext = self.stext.get(1.0, "end")
        # response = openai.Completion.create(
        #     engine="text-davinci-002",
        #     prompt=cookiestext,
        #     max_tokens=1024,
        #     n=1,
        #     temperature=0.5,
        # )
        # answer = (response["choices"][0]["text"]).split(".")
        # for i in answer:
        #     self.totext.insert(1.0, i)
        #
        #     self.totext.update()
        response =openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
        # {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": cookiestext},
        # {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        # {"role": "user", "content": "Where was it played?"}
    ]
)

        answer =response['choices'][0]['message']['content']
        self.totext.insert(1.0, answer)
    def addyh_Cmdiage(self, event=None): #chatgpt image
        # TODO, Please finish the function here!
        cookiestext = self.stext.get(1.0, "end")

        response = openai.Image.create(
            prompt=cookiestext,
            n=1,
            size="1024x1024"
        )
        image_url = response['data'][0]['url']
        print(image_url)
        import webbrowser
        # play_url01 = rst1
        webbrowser.open(image_url)

    def wenxin(self, event=None): #baidu wenxin
        with open(r'bdwx-key1-b.txt', 'r') as wenxinskeyb:
            skey = wenxinskeyb.read().replace('\n', '')
        with open(r'bdwx-key1-a.txt', 'r') as wenxinskeya:
            akey = wenxinskeya.read().replace('\n', '')
        getmyques = self.stext.get(1.0, "end")
        # -------bd  # import wenxin_api  # 可以通过"pip install wenxin-api"命令安装  # pip install --upgrade wenxin-api # https://wenxin.baidu.com/wenxin/docs#2l6tgx5rc
        # runingpb()
        import wenxin_api
        from wenxin_api.tasks.free_qa import FreeQA
        wenxin_api.ak = akey
        wenxin_api.sk = skey
        input_dict = {
            "text": getmyques,
            "seq_len": 512,
            "topp": 0.5,
            "penalty_score": 1.2,
            "min_dec_len": 2,
            "min_dec_penalty_text": "。?:![]",
            "is_unidirectional": 0,
            "task_prompt": "qa",
            "mask_type": "paragraph"
        }

        rstbd = FreeQA.create(**input_dict)['result']
        time.sleep(1)
        print(rstbd)
        self.totext.delete(1.0, 'end')
        self.totext.insert(1.0, rstbd)
        self.totext.update()

    def xunfei(self, event=None): #xunfei xinghuo
        import xunfeichat
    def addwdtuling(self, event=None):    #tuling robot
        import json
        import urllib.request

        api_url = "http://openapi.turingapi.com/openapi/api/v2"
        json_path = 'turingreq.json'
        cookiestextq = self.stext.get(1.0, "end")


        json_path = json_path
        api_url = api_url
        text_input = cookiestextq

        def readJson():
            '''获取json文件'''
            with open(json_path, 'r', encoding='utf-8') as f_json:
                json_data = json.load(f_json)
            return json_data

        def textInput():
            '''用变量text_input替换text的value值'''
            req = readJson()
            req['perception']['inputText']['text'] = text_input
            return req

        def dumpsJson():
            '''将json字符串转化成dict格式'''
            req = textInput()
            req = json.dumps(req, sort_keys=True, indent=4, ).encode('utf8')
            return req

        def urllibRequestResponse():
            req = dumpsJson()
            http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
            response = urllib.request.urlopen(http_post)  # 在urlopen()方法中传入字符串格式的url地址,则此方法会访问目标网址,然后返回访问的结果。
            response_str = response.read().decode('utf8')
            response_dict = json.loads(response_str)  # 将字符串response_str转成字典
            return response_dict

        def getTuringResponse():
            '''取得机器人返回的语句并输出'''
            response_dict = urllibRequestResponse()
            intent_code = response_dict.get('intent')['code']
            results_text = response_dict.get('results')[0]['values']['text']
            print('Turing的回答:')
            # print('code:' + str(intent_code))
            print(results_text)
            answer = results_text.replace("问:", "问:").replace(
                "
答:", "\n答:").replace("
", " ").replace("",
                                                                                             " ").replace(
                "
", " ")
            # answer = results_text
            self.totext.delete(1.0,'end')
            self.totext.insert(1.0, answer)

            self.totext.update()


        getTuringResponse()

if __name__ == "__main__":
    top = Tk()
    Application(top).mainloop()

-----------------------------xunfeichat.py

# -*-coding:UTF-8 -*-
import webbrowser as web
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests,os,time,re
# print('中间滑块验证,需要您自己滑动哦,最后点击进入体验!')
# time.sleep(8)
options = Options()
# options.add_argument('--headless')
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")

driver = webdriver.Chrome(options=options)
urlxunfei='https://passport.xfyun.cn/login'
# urlxunfei2='https://xinghuo.xfyun.cn/desk'
driver.get(urlxunfei)
driver.maximize_window()
# logincard_tag = driver.find_element_by_class_name('

')

logincard_tag = driver.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[3]')
logincard_tag.click()
input_tag = driver.find_element_by_xpath('//*[@id="username"]')
input_tag.send_keys('1367724')  # 回车
password = driver.find_element_by_xpath('//*[@id="password"]')
password.send_keys('Sys123')  # 登录

login_tag = driver.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[2]/div/form/button')
login_tag.click()
time.sleep(7)
#这里自己移动模块


#
login_tag2 = driver.find_element_by_xpath('//*[@id="__next"]/div[1]/div[1]/div[1]/ul/li[3]/a')
login_tag2.click()
#这里自动点击星火模型标签页面

-----turingreq.json

{
    "perception":
    {
        "inputText":
        {
            "text": ""
        },

        "selfInfo":
        {
            "location":
            {
                "city": "上海",
                "province": "海",
                "street": "陆嘴"
            }
        }
    },

    "userInfo":
    {
        "apiKey": "9bef20b25dbe431b0d68f0368",
        "userId": "5841"
    }
}
 


 

你可能感兴趣的:(机器人,python,开发语言)