Exemple #1
0
    def _check_tags_process(self, talk_msg):
        """
        检查用户反馈的分类名称
        句子中是否有分类名称,没有或者返回多个分类名称,再次询问
        :param talk_msg:
        :return:
        """
        talk = Talk(talk_msg)
        keywords_list = talk.get_keywords_list()
        tags_list = []
        for tags in self.tags_list:
            if tags.get_tag_name() in keywords_list:
                tags_list.append(tags)

        # 未匹配到分类,不更改 框架状态 保持 12
        if len(tags_list) == 1:
            self.frame_tag = tags_list[0]
            self.__update_state_code(13)  # 即将开始匹配答案状态
            return
        elif len(tags_list) > 1:
            self.frame_wait_next_talk_state = True
            return "你好像说了好几个分类的名称哦!"
        else:
            self.error_number += 1
            self.frame_wait_next_talk_state = True
            return "~小N~,没有明白你在说什么?"
Exemple #2
0
    def __get_tags(self, talk_msg):
        """
        从问题中,找出问题在那个分类中,找出返回1,没找出 返回 0
        :param talk_msg: 句子
        :return:  找到分类1 没找到分类 0
        """
        t = Talk(talk_msg)
        key_words_list = t.get_keywords_list()

        if not key_words_list:  # 没找到关键词
            return 0

        results_tags_id_tuple = mysql_query_wherein(
            SQL_GET_TAGS_ID, key_words_list)  # 从数据库 查找 关键词,获得 tags_id的列表
        if not results_tags_id_tuple:
            return 0  # 从关键词数据库中,未找到 tags_id的列表

        tags_id_list = []
        for result in results_tags_id_tuple:
            tags_id_list.append(result[0])

        self.tags_weight_dict = self.__tags_weight(key_words_list,
                                                   tags_id_list)  # 计算标签权重
        if max(self.tags_weight_dict, key=self.tags_weight_dict.get) >= 0.5:
            return 1
        else:
            return 2
Exemple #3
0
    def talk(self):
        """
        Handle VoIP talking.

        The client sends a target client, and a randomly generated
        number (session key). The targeted client then responds with
        the number and an action based on what the client wants to do.

        The actions are:
            REQUEST - request a conversation
            ACCEPT  - accept a request for a conversation
            DENY    - deny a request for a conversation
            END     - end a conversation

        """
        talk = None
        action = self.data.split(":")[1].strip()
        try:
            target = self.data.split(":")[0].split()[1]
        except IndexError:
            target = None
        logging.debug("Talk action '%s'" % action)
        try:
            if action == "REQUEST":
                session_key = random.randint(100000000000000, 999999999999999)
                while session_key in Talk.talk_sessions:
                    session_key = random.randint(100000000000000, 999999999999999)
                talk = Talk(session_key)
                self.server.queue_message(
                    "TALK %s %s: REQUEST\r\n" % (target, session_key),
                    self.sender_socket
                )
                self.server.queue_message_to_client(
                    "TALK %s %s: REQUEST\r\n" % (self.sender_client.user.nickname, session_key),
                    target,
                    self.sender_socket
                )
                talk.tcp_clients.append(self.sender_client)
                thread = threading.Thread(target=talk.run)
                thread.start()
            else:
                session_key = int(self.data.split(":")[0].split()[1])
                try:
                    talk = Talk.talk_sessions[session_key]
                except KeyError:
                    self.server.queue_message(
                        "TALK: BADSESSIONKEY\r\n", self.sender_socket
                    )
        except IndexError:
            logging.warning("Something went wrong parsin '%s'" % self.data)
        if talk is not None:
            if self.sender_client not in talk.tcp_clients:
                talk.tcp_clients.append(self.sender_client)
            if action == "END":
                talk.close()
            else:
                talk_action = TalkAction(self.sender_client, target, action)
                talk.add_action(talk_action)
Exemple #4
0
    def __init__(self, *, library_path, keyword_file_paths, model_file_path):
        """
        :param library_path: path of the porcupine shared library
        :param keyword_file_paths: path of the ppn files of porcupine
        :param model_file_path: porcupine model file .pv
        """

        sensitivities = [0.5] * len(keyword_file_paths)
        self.listener = Listener(library_path, model_file_path,
                                 keyword_file_paths, sensitivities)
        self.talker = Talk()
        self.state = None
Exemple #5
0
    def __init__(self, id=None, password=None, authToken=None):
        if not (id and password or authToken):
            msg = "`id` and `password` or `authToken` is needed"
            raise Exception(msg)

        self._session = requests.Session()
        self.talk = Talk(self.name, self.creator, self._session)

        self.id = id
        self.password = password

        if authToken:
            self.line = LineClient(authToken=authToken)
        else:
            self.line = LineClient(self.id, self.password)
Exemple #6
0
    def __init__(self, id=None, password=None, authToken=None):
        if not (id and password or authToken):
            msg = "`id` and `password` or `authToken` is needed"
            raise Exception(msg)

        self._session = requests.Session()
        self.talk     = Talk(self.name, self.creator, self._session) 

        self.id       = id
        self.password = password

        if authToken:
            self.line = LineClient(authToken=authToken)
        else:
            self.line = LineClient(self.id, self.password)
Exemple #7
0
class Black(object):
    prefix  = "!"

    name    = "검정봇"
    creator = "carpedm20"

    def __init__(self, id=None, password=None, authToken=None):
        if not (id and password or authToken):
            msg = "`id` and `password` or `authToken` is needed"
            raise Exception(msg)

        self._session = requests.Session()
        self.talk     = Talk(self.name, self.creator, self._session) 

        self.id       = id
        self.password = password

        if authToken:
            self.line = LineClient(authToken=authToken)
        else:
            self.line = LineClient(self.id, self.password)

    def run(self):
        ops = []

        for op in self.line.longPoll():
            ops.append(op)

        for op in ops:
            sender   = op[0]
            receiver = op[1]
            message  = op[2]

            try:
                if message.text[0] == self.prefix:
                    response = self.talk.get_message(sender,
                                                     receiver,
                                                     message.text[1:])

                    receiver.sendMessage(response)
                else:
                    pass
            except Exception as e:
                print e
Exemple #8
0
class Black(object):
    prefix = "!"

    name = "검정봇"
    creator = "carpedm20"

    def __init__(self, id=None, password=None, authToken=None):
        if not (id and password or authToken):
            msg = "`id` and `password` or `authToken` is needed"
            raise Exception(msg)

        self._session = requests.Session()
        self.talk = Talk(self.name, self.creator, self._session)

        self.id = id
        self.password = password

        if authToken:
            self.line = LineClient(authToken=authToken)
        else:
            self.line = LineClient(self.id, self.password)

    def run(self):
        ops = []

        for op in self.line.longPoll():
            ops.append(op)

        for op in ops:
            sender = op[0]
            receiver = op[1]
            message = op[2]

            try:
                if message.text[0] == self.prefix:
                    response = self.talk.get_message(sender, receiver,
                                                     message.text[1:])

                    receiver.sendMessage(response)
                else:
                    pass
            except Exception as e:
                print e
class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        self.r = Talk()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Click me to record speech to text!"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="bottom")

        self.quit = tk.Button(self,
                              text="QUIT",
                              fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print(self.r.record(5, "testing"))
Exemple #10
0
    def _response_answer_process(self, talk_msg):
        """
        匹配答案
        :param talk_msg:
        :return:
        """
        talk = Talk(self.questions_words_last)
        self.frame_wait_next_talk_state = True
        results_questions_tuple = mysql_query_where_equal(
            SQL_GET_QUESTIONS_FOR_TAGS_ID,
            self.frame_tag.get_tag_id())  # 查询符合的问题
        if len(results_questions_tuple) == 0:
            return self.__collect_questions(talk)

        questions_list = []
        for result in results_questions_tuple:
            q = Questions(result[0], result[1])
            if q.get_keywords_list():  # 问题的关键词列表不为空时 有效,防止垃圾数据的影响
                questions_list.append(q)
        if not questions_list:  # 防止 问题列表 为空
            return self.__collect_questions(talk)

        self.questions_weight_dict = self.__questions_weight(
            questions_list, talk)  # 获取问题权重
        if not self.questions_weight_dict:
            return self.__collect_questions(talk)

        question_name = max(self.questions_weight_dict,
                            key=self.questions_weight_dict.get)  # 获取最大值
        for question in questions_list:
            if question.get_question_name() == question_name:
                response_question = question
                response_answer = self.__get_answer(response_question)
                response_words = "太棒了~已经找到了你可能要想要的结果!\n 匹配的问题:【{0}】\n 回答:{1}"\
                    .format(response_question.get_question_name(), response_answer)
                self.__update_state_code(10)  # 重新进入等待问题
                return response_words
elif (len(sys.argv) > 5):
  for i in range(len(sys.argv) - 4, len(sys.argv)):
    words.append(sys.argv[i])

# Initialize talks list
talks = []

# Initialize browser
browser = webdriver.Firefox()
browser.get(url)

# Get list of talks
elem = browser.find_elements_by_class_name("lumen-tile__link");
for e in elem:
    speaker = e.find_element_by_class_name("lumen-tile__content").get_attribute('innerHTML')
    title = e.find_element_by_class_name("lumen-tile__title").find_element_by_tag_name('div').get_attribute('innerHTML')
    link = e.get_attribute('href')
    talks.append(Talk(speaker, title, link))

for t in talks:
    f.write(t.toString())
    browser.get(t.link)
    body = browser.find_element_by_class_name("body-block")
    paragraphs = body.find_elements_by_tag_name("p")
    for p in paragraphs:
        for w in words:
            if (p.text.find(w) != -1):
                f.write(p.text + '\n')
    f.write('\n')
f.close()
Exemple #12
0
 def __init__(self, master=None):
     super().__init__(master)
     self.master = master
     self.pack()
     self.create_widgets()
     self.r = Talk()
Exemple #13
0
class Assistant:
    # states of the assistant
    # the assistant starts from the None state and the states that it can go are stated as list
    states = {
        None: ["hello cat", "open folder", "open app"],
        "hello cat": ["open folder", "open app"],
        "open app": [
            "firefox", "visual code", "ins ta gram", "duo lingo", "twitter",
            "git hub", "g mail"
        ],
        "open folder": ["thesis"]
    }

    # replies that will be played by talker
    replies = {
        "hello cat": "hello",
        "open app": "which app?",
        "open folder": "which folder?",
        "ins ta gram": "opening instagram",
        "duo lingo": "opening duolingo",
        "twitter": "opening twitter",
        "git hub": "opening github",
        "g mail": "opening gmail",
        "thesis": "opening thesis folder",
        "firefox": "opening firefox."
    }

    # what to run with which command
    commands = {
        "firefox": "firefox",
        "thesis": "nautilus /home/khedd/Documents/thesis/",
        "ins ta gram": "firefox www.instagram.com",
        "duo lingo": "firefox www.duolingo.com",
        "git hub": "firefox www.github.com/trending",
        "g mail": "firefox https://mail.google.com/mail/u/0/",
        "twitter": "firefox www.twitter.com"
    }

    def __init__(self, *, library_path, keyword_file_paths, model_file_path):
        """
        :param library_path: path of the porcupine shared library
        :param keyword_file_paths: path of the ppn files of porcupine
        :param model_file_path: porcupine model file .pv
        """

        sensitivities = [0.5] * len(keyword_file_paths)
        self.listener = Listener(library_path, model_file_path,
                                 keyword_file_paths, sensitivities)
        self.talker = Talk()
        self.state = None

    # infinite loop until keypress
    def run(self):
        try:
            while True:
                result = self.listener.listen()

                avail_states = self.states.get(self.state, None)
                if result:
                    print(result)
                    if result in avail_states:
                        self.state = result
                        reply = self.replies.get(result, None)

                        if reply:
                            self.talker.talk(reply)

                        command = self.commands.get(result, None)
                        if command:
                            system(command)
                            system("xdotool getactivewindow getwindowname")

                    if result == "cancel":
                        self.state = None

                avail_states = self.states.get(self.state, None)
                if not avail_states:
                    self.state = None

        except KeyboardInterrupt:
            print('Stopping ...')
        finally:
            pass
Exemple #14
0
 def setUp(self):
     """Start unittest attributes"""
     self.maxDiff = None
     self.talk = Talk([
         "Writing Fast Tests Against Enterprise Rails 60min",
         "Overdoing it in Python 45min", "Lua for the Masses 30min",
         "Ruby Errors from Mismatched Gem Versions 45min",
         "Common Ruby Errors 45min",
         "Rails for Python Developers lightning",
         "Communicating Over Distance 60min",
         "Accounting-Driven Development 45min", "Woah 30min",
         "Sit Down and Write 30min", "Pair Programming vs Noise 45min",
         "Rails Magic 60min", "Ruby on Rails: Why We Should Move On 60min",
         "Clojure Ate Scala (on my project) 45min",
         "Programming in the Boondocks of Seattle 30min",
         "Ruby vs. Clojure for Back-End Development 30min",
         "Ruby on Rails Legacy App Maintenance 60min",
         "A World Without HackerNews 30min",
         "User Interface CSS in Rails Apps 30min"
     ])
     self.talk_objects = [{
         "title": "Writing Fast Tests Against Enterprise"
         " Rails 60min",
         "minute": timedelta(minutes=60)
     }, {
         "title": "Overdoing it in Python 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Lua for the Masses 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "Ruby Errors from Mismatched Gem"
         " Versions 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Common Ruby Errors 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Rails for Python Developers lightning",
         "minute": ""
     }, {
         "title": "Communicating Over Distance 60min",
         "minute": timedelta(minutes=60)
     }, {
         "title": "Accounting-Driven Development 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Woah 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "Sit Down and Write 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "Pair Programming vs Noise 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Rails Magic 60min",
         "minute": timedelta(minutes=60)
     }, {
         "title": "Ruby on Rails: Why We Should Move On"
         " 60min",
         "minute": timedelta(minutes=60)
     }, {
         "title": "Clojure Ate Scala (on my project)"
         " 45min",
         "minute": timedelta(minutes=45)
     }, {
         "title": "Programming in the Boondocks of"
         " Seattle 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "Ruby vs. Clojure for Back-End"
         " Development 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "Ruby on Rails Legacy App Maintenance"
         " 60min",
         "minute": timedelta(minutes=60)
     }, {
         "title": "A World Without HackerNews 30min",
         "minute": timedelta(minutes=30)
     }, {
         "title": "User Interface CSS in Rails Apps"
         " 30min",
         "minute": timedelta(minutes=30)
     }]
Exemple #15
0
 def test_talk_raise(self):
     with self.assertRaises(Exception):
         Talk(["A World Without HackerNews 450min"])
Exemple #16
0
from talk import Talk

from keras.models import Sequential
from keras.layers import Dense, Flatten, Embedding
from keras.optimizers import Adam

from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory


if __name__ == "__main__":

    # Get the environment and extract the number of actions.
    env = Talk()
    # np.random.seed(123)
    # env.seed(123)
    nb_actions = env.action_space.n

    # model parameters
    max_features = len(env.tokenizer.word_index)
    embedding_dims = 10
    input_length = env.INPUT_MAXLEN

    # Next, we build a very simple model regardless of the dueling architecture
    # if you enable dueling network in DQN , DQN will build a dueling network base on your model automatically
    # Also, you can build a dueling network by yourself and turn off the dueling network in DQN.
    # TODO: change models
    model = Sequential()
    model.add(Embedding(max_features,
Exemple #17
0
    # On quitte la portion critique donc on relache le lock
    finally:
        aLock.release()


# Définition du callback lors de la réception d'un message venant d'internet
# Ce callback prend en compte l'analyse des messages venant d'internet et
# l'action associée
#
def processDataFromInternet(receivedData):

    print receivedData


# Initialisation de l'objet global de communication
talk = Talk(LOGGER, LOCALE, HTTP_BASE_URL, HTTP_USER, HTTP_PWD,
            processDataFromInternet)

# On connecte les Arduinos au Raspberry
talk.addArduino(ARD1, ARD1_PORT, ARD_SPEED, processDataFromArduino)
talk.addArduino(ARD2, ARD2_PORT, ARD_SPEED, processDataFromArduino)

# On initialise les paramètres sous contrôle de l'unité
params = Params()

# On initialise les éléments de menu
menu = Menu()

# On fait tourner le programme un moment
while running == True:
    try:
        talk.sendArduino(ARD2, 'RGB', [255, 0, 0])
Exemple #18
0
# -*- coding: utf-8 -*-
import sys

from talk import Talk

if __name__ == '__main__':
    # inputs
    print("Digite os itens, um por linha. Para salvar aperte ctrl + d:")
    items = []
    for item in sys.stdin.read().split("\n"):
        if item:
            items.append(item)
    Talk(items).output()