コード例 #1
0
ファイル: takenote.py プロジェクト: peter3125/Dragonfire
    def getnote_compare1(self, com, note_taker, user_answering_note, userin,
                         user_prefix):
        """Method to dragonfire's first command struct of getting note ability.

                Args:
                    com (str):                 User's command.
                    note_taker (object):        note_taker class's object.
                    user_answering_note:       User answering string array.
                    userin:                    :class:`dragonfire.utilities.TextToAction` instance.
                    user_prefix:               user's preferred titles.
                """
        doc = nlp(com)
        h = Helper(doc)
        if h.check_verb_lemma("say") or h.check_verb_lemma(
                "get") or h.check_verb_lemma("give"):

            if h.check_noun_lemma("note") or h.check_noun_lemma("notes"):
                return userin.say(note_taker.db_get(None, None))

            if h.check_verb_lemma("do") or (h.check_verb_lemma("do")
                                            and h.check_noun_lemma("list")):
                takenote_query = ""
                for token in doc:
                    if not (token.lemma_ == "say" or token.lemma_ == "get"
                            or token.lemma_ == "give" or token.lemma_ == "do"
                            or token.lemma_ == "list"
                            or token.lemma_ == "dragonfire" or token.is_stop):
                        takenote_query += ' ' + token.text
                takenote_query = takenote_query.strip()
                if not takenote_query:  # when command come without note.
                    user_answering_note['has_listname'] = False
                    return userin.say(
                        choice([
                            "which list", "Alright, say a list name",
                            "Okay, What is the name of list", "List name"
                        ]) + choice(["?", ", " + user_prefix + "?"]))
                else:  # when command came with note.                    # BU KISMI HALLEDECEĞİM. SİLME İŞLEMLERİ, TOPLU SİLME, İTEM SİLME,
                    result = note_taker.db_get(None, com, True)
                    if result == "*#$":
                        user_answering_note['has_listname'] = False
                        return userin.say(
                            choice([
                                "This name is not exist",
                                "I couldn't find it, say again",
                                "Not found, Repeat", "Not exist, speak again"
                            ]) + choice(["?", ", " + user_prefix + "?"]))
                    else:
                        return userin.say(note_taker.db_get(None, com, True))
        return None
コード例 #2
0
ファイル: __init__.py プロジェクト: zhangxuelei86/Dragonfire
    def command(self, com):
        """Function that serves as the entry point for each one of the user commands.

        This function goes through these steps for each one of user's commands, respectively:

        - Search across the built-in commands via a simple if-else control flow.
        - Try to get a response from :func:`dragonfire.arithmetic.arithmetic_parse` function.
        - Try to get a response from :func:`dragonfire.learn.Learner.respond` method.
        - Try to get a answer from :func:`dragonfire.odqa.ODQA.respond` method.
        - Try to get a response from :func:`dragonfire.deepconv.DeepConversation.respond` method.

        Args:
            com (str):  User's command.

        Returns:
            str:  Response.
        """

        if not self.args["server"]:
            global config_file
            global e
            if (e.is_set()):  # System Tray Icon exit must trigger this
                exit(0)
        args = self.args
        userin = self.userin
        user_full_name = self.user_full_name
        user_prefix = self.user_prefix
        if self.testing:
            config_file = self.config_file

        if isinstance(com, str) and com:
            com = com.strip()
        else:
            return False

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)
        self.h = h

        if args["verbose"]:
            userin.pretty_print_nlp_parsing_results(doc)

        # Input: DRAGONFIRE | WAKE UP | HEY
        if self.inactive and not self.check_wake_up_intent:
            return ""

        # User is answering to Dragonfire
        if user_answering['status']:
            if com.startswith("FIRST") or com.startswith(
                    "THE FIRST") or com.startswith("SECOND") or com.startswith(
                        "THE SECOND") or com.startswith(
                            "THIRD") or com.startswith("THE THIRD"):
                user_answering['status'] = False
                selection = None
                if com.startswith("FIRST") or com.startswith("THE FIRST"):
                    selection = 0
                elif com.startswith("SECOND") or com.startswith("THE SECOND"):
                    selection = 1
                elif com.startswith("THIRD") or com.startswith("THE THIRD"):
                    selection = 2

                if user_answering['for'] == 'wikipedia':
                    with nostderr():
                        search_query = user_answering['options'][selection]
                        try:
                            return self.wikisearch(search_query)
                        except requests.exceptions.ConnectionError:
                            return self.wikipedia_connection_error()
                        except WikipediaNoResultsFoundError:
                            return self.wikipedia_no_results_found_error(
                                search_query)
                        except Exception:
                            return False

        # Input: DRAGONFIRE | WAKE UP | HEY
        if self.check_wake_up_intent():
            self.inactive = False
            return userin.say(
                choice([
                    "Yes, " + user_prefix + ".", "Yes. I'm waiting.",
                    "What is your order?", "Ready for the orders!",
                    user_prefix.capitalize() + ", tell me your wish."
                ]))
        # Input: GO TO SLEEP
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (
                h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            self.inactive = True
            userin.execute([
                "echo"
            ], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'"
                           )
            return userin.say("I'm going to sleep")
        # Input: ENOUGH | SHUT UP
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut")
                                            and h.check_nth_lemma(-1, "up")):
            tts_kill()
            msg = "Dragonfire quiets."
            print(msg)
            return msg
        # Input: WHAT IS YOUR NAME
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            return userin.execute([" "], "My name is Dragonfire.", True)
        # Input: WHAT IS YOUR GENDER
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            return userin.say(
                "I have a female voice but I don't have a gender identity. I'm a computer program, "
                + user_prefix + ".")
        # Input: WHO AM I | SAY MY NAME
        if (h.check_wh_lemma("who")
                and h.check_text("I")) or (h.check_verb_lemma("say")
                                           and h.check_text("my")
                                           and h.check_lemma("name")):
            userin.execute([" "], user_full_name)
            return userin.say("Your name is " + user_full_name + ", " +
                              user_prefix + ".")

        # Input: OPEN [CAMERA, CALENDAR, CALCULATOR, STEAM, BLENDER, WRITER, MATH, IMPRESS, DRAW, TERMINAL]
        if h.check_verb_lemma("open") or h.check_adj_lemma(
                "open") or h.check_verb_lemma("run") or h.check_verb_lemma(
                    "start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                return userin.say("Blender 3D computer graphics software")
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                return userin.say("Opening LibreOffice Draw")
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"],
                               "LibreOffice Impress")
                return userin.say("Opening LibreOffice Impress")
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                return userin.say("Opening LibreOffice Math")
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"],
                               "LibreOffice Writer")
                return userin.say("Opening LibreOffice Writer")
            if h.check_noun_lemma("browser") or h.check_text(
                    "chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                return userin.say("Web browser")
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                return userin.say("Opening Steam Game Store")
            if h.check_text("files"):
                return self.start_file_manager()
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                return userin.say("Camera")
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                return userin.say("Calendar")
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"],
                               "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                return userin.say("Calculator")
            if h.check_noun_lemma("console") or h.check_noun_lemma("terminal"):
                userin.execute(["konsole"], "Terminal")  # KDE neon
                userin.execute(["gnome-terminal"],
                               "Terminal")  # elementary OS & Ubuntu
                userin.execute(["guake"], "Terminal")  # Guake
                return userin.say("Terminal")
        # Input FILE MANAGER | FILE EXPLORER
        if h.check_noun_lemma("file") and (h.check_noun_lemma("manager")
                                           or h.check_noun_lemma("explorer")):
            return self.start_file_manager()
        # Input: SOFTWARE CENTER
        if h.check_noun_lemma("software") and h.check_text("center"):
            userin.execute(["plasma-discover"], "Software Center")  # KDE neon
            userin.execute(["software-center"],
                           "Software Center")  # elementary OS & Ubuntu
            return userin.say("Software Center")
        # Input: OFFICE SUITE
        if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
            userin.execute(["libreoffice"], "LibreOffice")
            return userin.say("Opening LibreOffice")
        # Input: GIMP | PHOTOSHOP | PHOTO EDITOR
        if h.check_text("gimp") or (h.check_noun_lemma("photo") and
                                    (h.check_noun_lemma("editor")
                                     or h.check_noun_lemma("shop"))):
            userin.execute(["gimp"], "GIMP")
            return userin.say("Opening the photo editor software.")
        # Input: INKSCAPE | VECTOR GRAPHICS
        if h.check_text("inkscape") or (h.check_noun_lemma("vector")
                                        and h.check_noun_lemma("graphic")) or (
                                            h.check_text("vectorial")
                                            and h.check_text("drawing")):
            userin.execute(["inkscape"], "Inkscape")
            return userin.say("Opening the vectorial drawing software.")
        # Input: Kdenlive | VIDEO EDITOR
        if h.check_text("kdenlive") or (h.check_noun_lemma("video")
                                        and h.check_noun_lemma("editor")):
            userin.execute(["kdenlive"], "Kdenlive")
            return userin.say("Opening the video editor software.")

        # Input: MY TITLE IS LADY | I'M A LADY | I'M A WOMAN | I'M A GIRL
        if h.check_lemma("be") and h.check_lemma(
                "-PRON-") and h.check_gender_lemmas('female'):
            return self.gender_update('female')
        # Input: MY TITLE IS SIR | I'M A MAN | I'M A BOY
        if h.check_lemma("be") and h.check_lemma(
                "-PRON-") and h.check_gender_lemmas('male'):
            return self.gender_update('male')
        # Input: CALL ME *
        if h.check_lemma("call") and h.check_lemma("-PRON-"):
            title = ""
            for token in doc:
                if token.pos_ == "NOUN":
                    title += ' ' + token.text
            title = title.strip()
            if not args["server"]:
                callme_config = config_file.search(
                    Query().datatype == 'callme')
                if callme_config:
                    config_file.update({'title': title},
                                       Query().datatype == 'callme')
                else:
                    config_file.insert({'datatype': 'callme', 'title': title})
            self.user_prefix = title
            user_prefix = self.user_prefix
            return userin.say("OK, " + user_prefix + ".")

        # Input: WHAT'S THE TEMPERATURE IN *
        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                try:
                    weather = owm.weather_at_id(
                        reg.ids_for(city)[0][0]).get_weather()
                    fmt = "The temperature in {} is {} degrees celsius"
                    msg = fmt.format(
                        city,
                        weather.get_temperature('celsius')['temp'])
                    userin.execute([" "], msg)
                    return userin.say(msg)
                except IndexError:
                    msg = "Sorry, " + user_prefix + " but I couldn't find a city named " + city + " on the internet."
                    userin.execute([" "], msg)
                    return userin.say(msg)
        # Input: WHAT TIME IS IT
        if h.check_wh_lemma("what") and h.check_noun_lemma(
                "time") and h.check_verb_lemma("be") and h.check_text("it"):
            return userin.say("It's " +
                              datetime.datetime.now().strftime("%I:%M %p") +
                              choice([", " + user_prefix + ".", "."]))

        # Input: KEYBOARD *
        if (h.check_nth_lemma(0, "keyboard")
                or h.check_nth_lemma(0, "type")) and not args["server"]:
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        for character in com[n:]:
                            k.tap_key(character)
                        k.tap_key(" ")
            return "keyboard"
        # Input: ENTER | NEW TAB | SWITCH TAB | CLOSE | GO BACK | GO FORWARD
        if (h.directly_equal(["enter"]) or
            (h.check_adj_lemma("new")
             and h.check_noun_lemma("line"))) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(k.enter_key)
            return "enter"
        if h.check_adj_lemma("new") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 't'])
            return "new tab"
        if h.check_verb_lemma("switch") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, k.tab_key])
            return "switch tab"
        if h.directly_equal(["CLOSE", "ESCAPE"]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 'w'])
                        k.tap_key(k.escape_key)
            return "close"
        if self.check_browser_history_nav_intent("back"):
            return self.press_browser_history_nav("back")
        if self.check_browser_history_nav_intent("forward"):
            return self.press_browser_history_nav("forward")
        # Input: SCROLL LEFT | SCROLL RIGHT | SCROLL UP | SCROLL DOWN
        if (h.check_text("swipe")
                or h.check_text("scroll")) and not args["server"]:
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, -5)
                return "swipe left"
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, 5)
                return "swipe right"
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(5, 0)
                return "swipe up"
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(-5, 0)
                return "swipe down"
        # Input: PLAY | PAUSE | SPACEBAR
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"
                             ]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(" ")
            return "play"

        # Input: SHUT DOWN THE COMPUTER
        if ((h.check_text("shut") and h.check_text("down")) or
            (h.check_text("power") and h.check_text("off"))
            ) and h.check_text("computer") and not args["server"]:
            return userin.execute(["sudo", "poweroff"], "Shutting down", True,
                                  3)
        # Input: GOODBYE | BYE BYE | SEE YOU LATER
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(
                0, "bye") or (h.check_verb_lemma("see") and h.check_text("you")
                              and h.check_adv_lemma("later")):
            response = userin.say("Goodbye, " + user_prefix)
            if not args["server"] and not self.testing:
                # raise KeyboardInterrupt
                thread.interrupt_main()
            return response

        # Input: (SEARCH|FIND) * (IN|ON|AT|USING) WIKIPEDIA
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("Wikipedia"):
            with nostderr():
                search_query = self.strip_the_search_query_by_intent(
                    doc, "Wikipedia")
                if search_query:
                    try:
                        return self.wikisearch(search_query)
                    except requests.exceptions.ConnectionError:
                        return self.wikipedia_connection_error()
                    except wikipedia.exceptions.DisambiguationError as disambiguation:
                        user_answering['status'] = True
                        user_answering['for'] = 'wikipedia'
                        user_answering['reason'] = 'disambiguation'
                        user_answering['options'] = disambiguation.options[:3]
                        notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + disambiguation.options[
                            0]
                        msg = user_prefix + ", there is a disambiguation. Which one of these you meant? " + disambiguation.options[
                            0]
                        for option in disambiguation.options[1:3]:
                            msg += ", or " + option
                            notify += "\n - " + option
                        notify += '\nSay, for example: "THE FIRST ONE" to choose.'
                        userin.execute([" "], notify)
                        return userin.say(msg)
                    except WikipediaNoResultsFoundError:
                        return self.wikipedia_no_results_found_error(
                            search_query)
                    except Exception:
                        pass
        # Input: (SEARCH|FIND) * (IN|ON|AT|USING) YOUTUBE
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("YouTube"):
            with nostdout():
                with nostderr():
                    search_query = self.strip_the_search_query_by_intent(
                        doc, "YouTube")
                    if search_query:
                        info = youtube_dl.YoutubeDL({}).extract_info(
                            'ytsearch:' + search_query,
                            download=False,
                            ie_key='YoutubeSearch')
                        if len(info['entries']) > 0:
                            youtube_title = info['entries'][0]['title']
                            youtube_url = "https://www.youtube.com/watch?v=%s" % (
                                info['entries'][0]['id'])
                            userin.execute(["sensible-browser", youtube_url],
                                           youtube_title)
                            youtube_title = TextToAction.fix_the_encoding_in_text_for_tts(
                                youtube_title)
                            response = userin.say(
                                youtube_title,
                                ["sensible-browser", youtube_url])
                        else:
                            youtube_title = "No video found, " + user_prefix + "."
                            response = userin.say(youtube_title)
                        k = PyKeyboard()
                        if not args["server"] and not self.testing:
                            time.sleep(5)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key('f')
                        return response
        # Input: (SEARCH|FIND) * (IN|ON|AT|USING) (GOOGLE|WEB)
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("Google") or h.check_lemma("web")
                or h.check_lemma("internet")) and not h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "Google"
                                or token.lemma_ == "web" or token.lemma_
                                == "internet" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query
                        return userin.execute(["sensible-browser", tab_url],
                                              search_query, True)
        # Input: (SEARCH IMAGES OF|FIND IMAGES OF|SEARCH|FIND) * (IN|ON|AT|USING) (GOOGLE|WEB|GOOGLE IMAGES|WEB IMAGES)
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("Google") or h.check_lemma("web")
                or h.check_lemma("internet")) and h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "Google"
                                or token.lemma_ == "web"
                                or token.lemma_ == "internet"
                                or token.lemma_ == "image" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch"
                        return userin.execute(["sensible-browser", tab_url],
                                              search_query, True)

        original_com = com
        com = coref.resolve(com)
        if args["verbose"]:
            print("After Coref Resolution: " + com)
        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            return userin.say(arithmetic_response)
        else:
            learner_response = learner.respond(com)
            if learner_response:
                return userin.say(learner_response)
            else:
                odqa_response = odqa.respond(com, not args["silent"], userin,
                                             user_prefix, args["server"])
                if odqa_response:
                    return userin.say(odqa_response)
                else:
                    dc_response = dc.respond(original_com, user_prefix)
                    if dc_response:
                        return userin.say(dc_response)
コード例 #3
0
    def command(com, args, tw_user=None):

        global e
        if (e.is_set()):  # System Tray Icon exit must trigger this
            exit(0)

        if not com.strip() or not isinstance(com, str):
            return False

        global inactive
        global user_full_name
        global user_prefix
        global config_file

        userin.twitter_user = tw_user

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)

        if args["verbose"]:
            if len(doc) > 0:
                print("")
                print("{:12}  {:12}  {:12}  {:12} {:12}  {:12}  {:12}  {:12}".
                      format("TEXT", "LEMMA", "POS", "TAG", "DEP", "SHAPE",
                             "ALPHA", "STOP"))
                for token in doc:
                    print(
                        "{:12}  {:12}  {:12}  {:12} {:12}  {:12}  {:12}  {:12}"
                        .format(token.text, token.lemma_, token.pos_,
                                token.tag_, token.dep_, token.shape_,
                                str(token.is_alpha), str(token.is_stop)))
                print("")
            if len(list(doc.noun_chunks)) > 0:
                print("{:12}  {:12}  {:12}  {:12}".format(
                    "TEXT", "ROOT.TEXT", "ROOT.DEP_", "ROOT.HEAD.TEXT"))
                for chunk in doc.noun_chunks:
                    print("{:12}  {:12}  {:12}  {:12}".format(
                        chunk.text, chunk.root.text, chunk.root.dep_,
                        chunk.root.head.text))
                print("")

        if inactive and not (
                h.directly_equal(["dragonfire", "hey"]) or
            (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or
            (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire")
             and h.max_word_count(2))):
            return True

        if USER_ANSWERING['status']:
            if com.startswith("FIRST") or com.startswith(
                    "THE FIRST") or com.startswith("SECOND") or com.startswith(
                        "THE SECOND") or com.startswith(
                            "THIRD") or com.startswith("THE THIRD"):
                USER_ANSWERING['status'] = False
                selection = None
                if com.startswith("FIRST") or com.startswith("THE FIRST"):
                    selection = 0
                elif com.startswith("SECOND") or com.startswith("THE SECOND"):
                    selection = 1
                elif com.startswith("THIRD") or com.startswith("THE THIRD"):
                    selection = 2

                if USER_ANSWERING['for'] == 'wikipedia':
                    with nostderr():
                        search_query = USER_ANSWERING['options'][selection]
                        try:
                            wikiresult = wikipedia.search(search_query)
                            if len(wikiresult) == 0:
                                userin.say(
                                    "Sorry, " + user_prefix +
                                    ". But I couldn't find anything about " +
                                    search_query + " in Wikipedia.")
                                return True
                            wikipage = wikipedia.page(wikiresult[0])
                            wikicontent = "".join([
                                i if ord(i) < 128 else ' '
                                for i in wikipage.content
                            ])
                            wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                            userin.execute(["sensible-browser", wikipage.url],
                                           search_query)
                            userin.say(wikicontent)
                            return True
                        except requests.exceptions.ConnectionError:
                            userin.execute([" "],
                                           "Wikipedia connection error.")
                            userin.say(
                                "Sorry, " + user_prefix +
                                ". But I'm unable to connect to Wikipedia servers."
                            )
                            return True
                        except Exception:
                            return True

        if h.directly_equal([
                "dragonfire", "hey"
        ]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (
                h.check_nth_lemma(0, "dragon")
                and h.check_nth_lemma(1, "fire") and h.max_word_count(2)):
            inactive = False
            userin.say(
                choice([
                    "Yes, " + user_prefix + ".", "Yes. I'm waiting.",
                    "What is your order?", "Ready for the orders!",
                    user_prefix + ", tell me your wish."
                ]))
            return True
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (
                h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            inactive = True
            userin.execute([
                "echo"
            ], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'"
                           )
            userin.say("I'm going to sleep")
            return True
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut")
                                            and h.check_nth_lemma(-1, "up")):
            tts_kill()
            print("Dragonfire quiets.")
            return True
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            userin.execute([" "], "My name is Dragonfire.", True)
            return True
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            userin.say(
                "I have a female voice but I don't have a gender identity. I'm a computer program, "
                + user_prefix + ".")
            return True
        if (h.check_wh_lemma("who")
                and h.check_text("I")) or (h.check_verb_lemma("say")
                                           and h.check_text("my")
                                           and check_lemma("name")):
            userin.execute([" "], user_full_name)
            userin.say("Your name is " + user_full_name + ", " + user_prefix +
                       ".")
            return True
        if h.check_verb_lemma("open") or h.check_adj_lemma(
                "open") or h.check_verb_lemma("run") or h.check_verb_lemma(
                    "start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                userin.say("Blender 3D computer graphics software")
                return True
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                userin.say("Opening LibreOffice Draw")
                return True
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"],
                               "LibreOffice Impress")
                userin.say("Opening LibreOffice Impress")
                return True
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                userin.say("Opening LibreOffice Math")
                return True
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"],
                               "LibreOffice Writer")
                userin.say("Opening LibreOffice Writer")
                return True
            if h.check_text("gimp") or (h.check_noun_lemma("photo") and
                                        (h.check_noun_lemma("editor")
                                         or h.check_noun_lemma("shop"))):
                userin.execute(["gimp"], "GIMP")
                userin.say("Opening the photo editor software.")
                return True
            if h.check_text("inkscape") or (h.check_noun_lemma("vector")
                                            and h.check_noun_lemma("graphic")
                                            ) or (h.check_text("vectorial")
                                                  and h.check_text("drawing")):
                userin.execute(["inkscape"], "Inkscape")
                userin.say("Opening the vectorial drawing software.")
                return True
            if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
                userin.execute(["libreoffice"], "LibreOffice")
                userin.say("Opening LibreOffice")
                return True
            if h.check_text("kdenlive") or (h.check_noun_lemma("video")
                                            and h.check_noun_lemma("editor")):
                userin.execute(["kdenlive"], "Kdenlive")
                userin.say("Opening the video editor software.")
                return True
            if h.check_noun_lemma("browser") or h.check_noun_lemma(
                    "chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                userin.say("Web browser")
                return True
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                userin.say("Opening Steam Game Store")
                return True
            if h.check_text("files") or (h.check_noun_lemma("file")
                                         and h.check_noun_lemma("manager")):
                userin.execute(["dolphin"], "File Manager")  # KDE neon
                userin.execute(["pantheon-files"],
                               "File Manager")  # elementary OS
                userin.execute(["nautilus", "--browser"],
                               "File Manager")  # Ubuntu
                userin.say("File Manager")
                return True
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                userin.say("Camera")
                return True
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                userin.say("Calendar")
                return True
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"],
                               "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                userin.say("Calculator")
                return True
            if h.check_noun_lemma("software") and h.check_text("center"):
                userin.execute(["plasma-discover"],
                               "Software Center")  # KDE neon
                userin.execute(["software-center"],
                               "Software Center")  # elementary OS & Ubuntu
                userin.say("Software Center")
                return True
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (
                h.check_lemma("lady") or h.check_lemma("woman")
                or h.check_lemma("girl")):
            config_file.update({'gender': 'female'},
                               Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "My Lady"
            userin.say("Pardon, " + user_prefix + ".")
            return True
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (
                h.check_lemma("sir") or h.check_lemma("man")
                or h.check_lemma("boy")):
            config_file.update({'gender': 'male'},
                               Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "Sir"
            userin.say("Pardon, " + user_prefix + ".")
            return True
        if h.check_lemma("call") and h.check_lemma("-PRON-"):
            title = ""
            for token in doc:
                if token.pos_ == "NOUN":
                    title += ' ' + token.text
            title = title.strip()
            callme_config = config_file.search(Query().datatype == 'callme')
            if callme_config:
                config_file.update({'title': title},
                                   Query().datatype == 'callme')
            else:
                config_file.insert({'datatype': 'callme', 'title': title})
            user_prefix = title
            userin.say("OK, " + user_prefix + ".")
            return True
        # only for The United States today but prepared for all countries. Also
        # only for celsius degrees today. --> by Radan Liska :-)
        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                weather = owm.weather_at_id(
                    reg.ids_for(city)[0][0]).get_weather()
                fmt = "The temperature in {} is {} degrees celsius"
                msg = fmt.format(city,
                                 weather.get_temperature('celsius')['temp'])
                userin.execute([" "], msg)
                userin.say(msg)
                return True
        if h.check_nth_lemma(0, "keyboard") or h.check_nth_lemma(0, "type"):
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    for character in com[n:]:
                        k.tap_key(character)
                    k.tap_key(" ")
            return True
        if h.directly_equal(["enter"]) or (h.check_adj_lemma("new")
                                           or h.check_noun_lemma("line")):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.tap_key(k.enter_key)
            return True
        if h.check_adj_lemma("new") and h.check_noun_lemma("tab"):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, 't'])
            return True
        if h.check_verb_lemma("switch") and h.check_noun_lemma("tab"):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, k.tab_key])
            return True
        if h.directly_equal(["CLOSE", "ESCAPE"]):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, 'w'])
                    k.tap_key(k.escape_key)
            return True
        if h.check_lemma("back") and h.max_word_count(4):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.alt_l_key, k.left_key])
            return True
        if h.check_lemma("forward") and h.max_word_count(4):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.alt_l_key, k.right_key])
            return True
        if h.check_text("swipe") or h.check_text("scroll"):
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(0, -5)
                return True
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(0, 5)
                return True
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(5, 0)
                return True
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(-5, 0)
                return True
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"]):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.tap_key(" ")
            return True
        if ((h.check_text("shut") and h.check_text("down")) or
            (h.check_text("power")
             and h.check_text("off"))) and h.check_text("computer"):
            userin.execute(["sudo", "poweroff"], "Shutting down", True, 3)
            return True
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(
                0, "bye") or (h.check_verb_lemma("see")
                              and h.check_noun_lemma("you")
                              and h.check_noun_lemma("later")):
            userin.say("Goodbye, " + user_prefix)
            # raise KeyboardInterrupt
            thread.interrupt_main()
            return True
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("wikipedia"):
            with nostderr():
                search_query = ""
                for token in doc:
                    if not (token.lemma_ == "search" or token.lemma_ == "find"
                            or token.lemma_ == "wikipedia" or token.is_stop):
                        search_query += ' ' + token.text
                search_query = search_query.strip()
                if search_query:
                    try:
                        wikiresult = wikipedia.search(search_query)
                        if len(wikiresult) == 0:
                            userin.say(
                                "Sorry, " + user_prefix +
                                ". But I couldn't find anything about " +
                                search_query + " in Wikipedia.")
                            return True
                        wikipage = wikipedia.page(wikiresult[0])
                        wikicontent = "".join([
                            i if ord(i) < 128 else ' '
                            for i in wikipage.content
                        ])
                        wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                        userin.execute(["sensible-browser", wikipage.url],
                                       search_query)
                        userin.say(wikicontent)
                        return True
                    except requests.exceptions.ConnectionError:
                        userin.execute([" "], "Wikipedia connection error.")
                        userin.say(
                            "Sorry, " + user_prefix +
                            ". But I'm unable to connect to Wikipedia servers."
                        )
                        return True
                    except wikipedia.exceptions.DisambiguationError as disambiguation:
                        USER_ANSWERING['status'] = True
                        USER_ANSWERING['for'] = 'wikipedia'
                        USER_ANSWERING['reason'] = 'disambiguation'
                        USER_ANSWERING['options'] = disambiguation.options[:3]
                        notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + disambiguation.options[
                            0]
                        message = user_prefix + ", there is a disambiguation. Which one of these you meant? " + disambiguation.options[
                            0]
                        for option in disambiguation.options[1:3]:
                            message += ", or " + option
                            notify += "\n - " + option
                        notify += '\nSay, for example: "THE FIRST ONE" to choose.'
                        userin.execute([" "], notify)
                        userin.say(message)
                        return True
                    except BaseException:
                        pass
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("youtube"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search"
                                or token.lemma_ == "find"
                                or token.lemma_ == "youtube" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        info = youtube_dl.YoutubeDL({}).extract_info(
                            'ytsearch:' + search_query,
                            download=False,
                            ie_key='YoutubeSearch')
                        if len(info['entries']) > 0:
                            youtube_title = info['entries'][0]['title']
                            youtube_url = "https://www.youtube.com/watch?v=%s" % (
                                info['entries'][0]['id'])
                            userin.execute(["sensible-browser", youtube_url],
                                           youtube_title)
                            youtube_title = "".join([
                                i if ord(i) < 128 else ' '
                                for i in youtube_title
                            ])
                        else:
                            youtube_title = "No video found, " + user_prefix + "."
                        userin.say(youtube_title)
                        time.sleep(5)
                        k = PyKeyboard()
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key('f')
                        return True
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("google") or h.check_lemma("web")
                or h.check_lemma("internet")) and not h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "google"
                                or token.lemma_ == "web" or token.lemma_
                                == "internet" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query
                        userin.execute(["sensible-browser", tab_url],
                                       search_query, True)
                        return True
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("google") or h.check_lemma("web")
                or h.check_lemma("internet")) and h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "google"
                                or token.lemma_ == "web"
                                or token.lemma_ == "internet"
                                or token.lemma_ == "image" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch"
                        userin.execute(["sensible-browser", tab_url],
                                       search_query, True)
                        return True

        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            userin.say(arithmetic_response)
        else:
            learnerresponse = learner.respond(com)
            if learnerresponse:
                userin.say(learnerresponse)
            else:
                if not omniscient.respond(com, not args["silent"], userin,
                                          user_prefix, args["server"]):
                    dc_response = dc.respond(com, user_prefix)
                    if dc_response:
                        userin.say(dc_response)
コード例 #4
0
    def compare(self, com, userin, user_prefix):
        """Method to dragonfire's command structures of directly executed command on command line ability.

        Args:
            com (str):                 User's command.
            userin:                    :class:`dragonfire.utilities.TextToAction` instance.
            user_prefix:               user's preferred titles.
        """

        doc = nlp(com)
        h = Helper(doc)
        if h.check_verb_lemma("open") or h.check_adj_lemma(
                "open") or h.check_verb_lemma("run") or h.check_verb_lemma(
                    "start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                return userin.say("Blender 3D computer graphics software")
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                return userin.say("Opening LibreOffice Draw")
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"],
                               "LibreOffice Impress")
                return userin.say("Opening LibreOffice Impress")
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                return userin.say("Opening LibreOffice Math")
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"],
                               "LibreOffice Writer")
                return userin.say("Opening LibreOffice Writer")
            if h.check_text("gimp") or (h.check_noun_lemma("photo") and
                                        (h.check_noun_lemma("editor")
                                         or h.check_noun_lemma("shop"))):
                userin.execute(["gimp"], "GIMP")
                return userin.say("Opening the photo editor software.")
            if h.check_text("inkscape") or (h.check_noun_lemma("vector")
                                            and h.check_noun_lemma("graphic")
                                            ) or (h.check_text("vectorial")
                                                  and h.check_text("drawing")):
                userin.execute(["inkscape"], "Inkscape")
                return userin.say("Opening the vectorial drawing software.")
            if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
                userin.execute(["libreoffice"], "LibreOffice")
                return userin.say("Opening LibreOffice")
            if h.check_text("kdenlive") or (h.check_noun_lemma("video")
                                            and h.check_noun_lemma("editor")):
                userin.execute(["kdenlive"], "Kdenlive")
                return userin.say("Opening the video editor software.")
            if h.check_noun_lemma("browser") or h.check_text(
                    "chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                return userin.say("Web browser")
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                return userin.say("Opening Steam Game Store")
            if h.check_text("files") or (h.check_noun_lemma("file")
                                         and h.check_noun_lemma("manager")):
                userin.execute(["dolphin"], "File Manager")  # KDE neon
                userin.execute(["pantheon-files"],
                               "File Manager")  # elementary OS
                userin.execute(["nautilus", "--browser"],
                               "File Manager")  # Ubuntu
                return userin.say("File Manager")
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                return userin.say("Camera")
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                return userin.say("Calendar")
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"],
                               "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                return userin.say("Calculator")
            if h.check_noun_lemma("software") and h.check_text("center"):
                userin.execute(["plasma-discover"],
                               "Software Center")  # KDE neon
                userin.execute(["software-center"],
                               "Software Center")  # elementary OS & Ubuntu
                return userin.say("Software Center")
            if h.check_noun_lemma("console"):  # for openin terminal.
                userin.execute(["konsole"], "Terminal")  # KDE neon
                userin.execute(["gnome-terminal"],
                               "Terminal")  # elementary OS & Ubuntu
                return userin.say("console")
        return None
コード例 #5
0
    def command(self, com):
        """Function that serves as the entry point for each one of the user commands.

        This function goes through these steps for each one of user's commands, respectively:

         - Search across the built-in commands via a simple if-else control flow.
         - Try to get a response from :func:`dragonfire.arithmetic.arithmetic_parse` function.
         - Try to get a response from :func:`dragonfire.learn.Learner.respond` method.
         - Try to get a answer from :func:`dragonfire.omniscient.Omniscient.respond` method.
         - Try to get a response from :func:`dragonfire.deepconv.DeepConversation.respond` method.

        Args:
            com (str):  User's command.

        Returns:
            str:  Response.
        """

        if not self.args["server"]:
            global config_file
            global e
            if (e.is_set()):  # System Tray Icon exit must trigger this
                exit(0)
        args = self.args
        userin = self.userin
        user_full_name = self.user_full_name
        user_prefix = self.user_prefix
        if self.testing:
            config_file = self.config_file

        if isinstance(com, str) and com:
            com = com.strip()
        else:
            return False

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)

        if args["verbose"]:
            userin.pretty_print_nlp_parsing_results(doc)

        if self.inactive and not (
                h.directly_equal(["dragonfire", "hey"]) or
            (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or
            (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire")
             and h.max_word_count(2))):
            return ""

        if USER_ANSWERING['status']:
            if com.startswith("FIRST") or com.startswith(
                    "THE FIRST") or com.startswith("SECOND") or com.startswith(
                        "THE SECOND") or com.startswith(
                            "THIRD") or com.startswith("THE THIRD"):
                USER_ANSWERING['status'] = False
                selection = None
                if com.startswith("FIRST") or com.startswith("THE FIRST"):
                    selection = 0
                elif com.startswith("SECOND") or com.startswith("THE SECOND"):
                    selection = 1
                elif com.startswith("THIRD") or com.startswith("THE THIRD"):
                    selection = 2

                if USER_ANSWERING['for'] == 'wikipedia':
                    with nostderr():
                        search_query = USER_ANSWERING['options'][selection]
                        try:
                            wikiresult = wikipedia.search(search_query)
                            if len(wikiresult) == 0:
                                userin.say(
                                    "Sorry, " + user_prefix +
                                    ". But I couldn't find anything about " +
                                    search_query + " in Wikipedia.")
                                return True
                            wikipage = wikipedia.page(wikiresult[0])
                            wikicontent = "".join([
                                i if ord(i) < 128 else ' '
                                for i in wikipage.content
                            ])
                            wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                            userin.execute(["sensible-browser", wikipage.url],
                                           search_query)
                            return userin.say(
                                wikicontent,
                                cmd=["sensible-browser", wikipage.url])
                        except requests.exceptions.ConnectionError:
                            userin.execute([" "],
                                           "Wikipedia connection error.")
                            return userin.say(
                                "Sorry, " + user_prefix +
                                ". But I'm unable to connect to Wikipedia servers."
                            )
                        except Exception:
                            return False

        if h.directly_equal([
                "dragonfire", "hey"
        ]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (
                h.check_nth_lemma(0, "dragon")
                and h.check_nth_lemma(1, "fire") and h.max_word_count(2)):
            self.inactive = False
            return userin.say(
                choice([
                    "Yes, " + user_prefix + ".", "Yes. I'm waiting.",
                    "What is your order?", "Ready for the orders!",
                    user_prefix.capitalize() + ", tell me your wish."
                ]))
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (
                h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            self.inactive = True
            userin.execute([
                "echo"
            ], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'"
                           )
            return userin.say("I'm going to sleep")
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut")
                                            and h.check_nth_lemma(-1, "up")):
            tts_kill()
            msg = "Dragonfire quiets."
            print(msg)
            return msg
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            return userin.execute([" "], "My name is Dragonfire.", True)
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            return userin.say(
                "I have a female voice but I don't have a gender identity. I'm a computer program, "
                + user_prefix + ".")
        if (h.check_wh_lemma("who")
                and h.check_text("I")) or (h.check_verb_lemma("say")
                                           and h.check_text("my")
                                           and h.check_lemma("name")):
            userin.execute([" "], user_full_name)
            return userin.say("Your name is " + user_full_name + ", " +
                              user_prefix + ".")
        if h.check_verb_lemma("open") or h.check_adj_lemma(
                "open") or h.check_verb_lemma("run") or h.check_verb_lemma(
                    "start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                return userin.say("Blender 3D computer graphics software")
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                return userin.say("Opening LibreOffice Draw")
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"],
                               "LibreOffice Impress")
                return userin.say("Opening LibreOffice Impress")
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                return userin.say("Opening LibreOffice Math")
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"],
                               "LibreOffice Writer")
                return userin.say("Opening LibreOffice Writer")
            if h.check_text("gimp") or (h.check_noun_lemma("photo") and
                                        (h.check_noun_lemma("editor")
                                         or h.check_noun_lemma("shop"))):
                userin.execute(["gimp"], "GIMP")
                return userin.say("Opening the photo editor software.")
            if h.check_text("inkscape") or (h.check_noun_lemma("vector")
                                            and h.check_noun_lemma("graphic")
                                            ) or (h.check_text("vectorial")
                                                  and h.check_text("drawing")):
                userin.execute(["inkscape"], "Inkscape")
                return userin.say("Opening the vectorial drawing software.")
            if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
                userin.execute(["libreoffice"], "LibreOffice")
                return userin.say("Opening LibreOffice")
            if h.check_text("kdenlive") or (h.check_noun_lemma("video")
                                            and h.check_noun_lemma("editor")):
                userin.execute(["kdenlive"], "Kdenlive")
                return userin.say("Opening the video editor software.")
            if h.check_noun_lemma("browser") or h.check_text(
                    "chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                return userin.say("Web browser")
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                return userin.say("Opening Steam Game Store")
            if h.check_text("files") or (h.check_noun_lemma("file")
                                         and h.check_noun_lemma("manager")):
                userin.execute(["dolphin"], "File Manager")  # KDE neon
                userin.execute(["pantheon-files"],
                               "File Manager")  # elementary OS
                userin.execute(["nautilus", "--browser"],
                               "File Manager")  # Ubuntu
                return userin.say("File Manager")
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                return userin.say("Camera")
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                return userin.say("Calendar")
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"],
                               "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                return userin.say("Calculator")
            if h.check_noun_lemma("software") and h.check_text("center"):
                userin.execute(["plasma-discover"],
                               "Software Center")  # KDE neon
                userin.execute(["software-center"],
                               "Software Center")  # elementary OS & Ubuntu
                return userin.say("Software Center")
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (
                h.check_lemma("lady") or h.check_lemma("woman")
                or h.check_lemma("girl")):
            config_file.update({'gender': 'female'},
                               Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "my lady"
            return userin.say("Pardon, " + user_prefix + ".")
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (
                h.check_lemma("sir") or h.check_lemma("man")
                or h.check_lemma("boy")):
            config_file.update({'gender': 'male'},
                               Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "sir"
            return userin.say("Pardon, " + user_prefix + ".")
        if h.check_lemma("call") and h.check_lemma("-PRON-"):
            title = ""
            for token in doc:
                if token.pos_ == "NOUN":
                    title += ' ' + token.text
            title = title.strip()
            if not args["server"]:
                callme_config = config_file.search(
                    Query().datatype == 'callme')
                if callme_config:
                    config_file.update({'title': title},
                                       Query().datatype == 'callme')
                else:
                    config_file.insert({'datatype': 'callme', 'title': title})
            user_prefix = title
            return userin.say("OK, " + user_prefix + ".")
        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                try:
                    weather = owm.weather_at_id(
                        reg.ids_for(city)[0][0]).get_weather()
                    fmt = "The temperature in {} is {} degrees celsius"
                    msg = fmt.format(
                        city,
                        weather.get_temperature('celsius')['temp'])
                    userin.execute([" "], msg)
                    return userin.say(msg)
                except IndexError:
                    msg = "Sorry, " + user_prefix + " but I couldn't find a city named " + city + " on the internet."
                    userin.execute([" "], msg)
                    return userin.say(msg)
        if (h.check_nth_lemma(0, "keyboard")
                or h.check_nth_lemma(0, "type")) and not args["server"]:
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        for character in com[n:]:
                            k.tap_key(character)
                        k.tap_key(" ")
            return "keyboard"
        if (h.directly_equal(["enter"]) or
            (h.check_adj_lemma("new")
             and h.check_noun_lemma("line"))) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(k.enter_key)
            return "enter"
        if h.check_adj_lemma("new") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 't'])
            return "new tab"
        if h.check_verb_lemma("switch") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, k.tab_key])
            return "switch tab"
        if h.directly_equal(["CLOSE", "ESCAPE"]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 'w'])
                        k.tap_key(k.escape_key)
            return "close"
        if h.check_lemma("back") and h.max_word_count(
                4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.left_key])
            return "back"
        if h.check_lemma("forward") and h.max_word_count(
                4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.right_key])
            return "forward"
        if (h.check_text("swipe")
                or h.check_text("scroll")) and not args["server"]:
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, -5)
                return "swipe left"
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, 5)
                return "swipe right"
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(5, 0)
                return "swipe up"
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(-5, 0)
                return "swipe down"
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"
                             ]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(" ")
            return "play"
        if ((h.check_text("shut") and h.check_text("down")) or
            (h.check_text("power") and h.check_text("off"))
            ) and h.check_text("computer") and not args["server"]:
            return userin.execute(["sudo", "poweroff"], "Shutting down", True,
                                  3)
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(
                0, "bye") or (h.check_verb_lemma("see") and h.check_text("you")
                              and h.check_adv_lemma("later")):
            response = userin.say("Goodbye, " + user_prefix)
            if not args["server"] and not self.testing:
                # raise KeyboardInterrupt
                thread.interrupt_main()
            return response
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("wikipedia"):
            with nostderr():
                search_query = ""
                for token in doc:
                    if not (token.lemma_ == "search" or token.lemma_ == "find"
                            or token.lemma_ == "wikipedia" or token.is_stop):
                        search_query += ' ' + token.text
                search_query = search_query.strip()
                if search_query:
                    try:
                        wikiresult = wikipedia.search(search_query)
                        if len(wikiresult) == 0:
                            userin.say(
                                "Sorry, " + user_prefix +
                                ". But I couldn't find anything about " +
                                search_query + " in Wikipedia.")
                            return True
                        wikipage = wikipedia.page(wikiresult[0])
                        wikicontent = "".join([
                            i if ord(i) < 128 else ' '
                            for i in wikipage.content
                        ])
                        wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                        userin.execute(["sensible-browser", wikipage.url],
                                       search_query)
                        return userin.say(
                            wikicontent,
                            cmd=["sensible-browser", wikipage.url])
                    except requests.exceptions.ConnectionError:
                        userin.execute([" "], "Wikipedia connection error.")
                        return userin.say(
                            "Sorry, " + user_prefix +
                            ". But I'm unable to connect to Wikipedia servers."
                        )
                    except wikipedia.exceptions.DisambiguationError as disambiguation:
                        USER_ANSWERING['status'] = True
                        USER_ANSWERING['for'] = 'wikipedia'
                        USER_ANSWERING['reason'] = 'disambiguation'
                        USER_ANSWERING['options'] = disambiguation.options[:3]
                        notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + disambiguation.options[
                            0]
                        msg = user_prefix + ", there is a disambiguation. Which one of these you meant? " + disambiguation.options[
                            0]
                        for option in disambiguation.options[1:3]:
                            msg += ", or " + option
                            notify += "\n - " + option
                        notify += '\nSay, for example: "THE FIRST ONE" to choose.'
                        userin.execute([" "], notify)
                        return userin.say(msg)
                    except BaseException:
                        pass
        if (h.check_lemma("search")
                or h.check_lemma("find")) and h.check_lemma("youtube"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search"
                                or token.lemma_ == "find"
                                or token.lemma_ == "youtube" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        info = youtube_dl.YoutubeDL({}).extract_info(
                            'ytsearch:' + search_query,
                            download=False,
                            ie_key='YoutubeSearch')
                        if len(info['entries']) > 0:
                            youtube_title = info['entries'][0]['title']
                            youtube_url = "https://www.youtube.com/watch?v=%s" % (
                                info['entries'][0]['id'])
                            userin.execute(["sensible-browser", youtube_url],
                                           youtube_title)
                            youtube_title = "".join([
                                i if ord(i) < 128 else ' '
                                for i in youtube_title
                            ])
                            response = userin.say(
                                youtube_title,
                                ["sensible-browser", youtube_url])
                        else:
                            youtube_title = "No video found, " + user_prefix + "."
                            response = userin.say(youtube_title)
                        k = PyKeyboard()
                        if not args["server"] and not self.testing:
                            time.sleep(5)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key('f')
                        return response
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("google") or h.check_lemma("web")
                or h.check_lemma("internet")) and not h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "google"
                                or token.lemma_ == "web" or token.lemma_
                                == "internet" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query
                        return userin.execute(["sensible-browser", tab_url],
                                              search_query, True)
        if (h.check_lemma("search") or h.check_lemma("find")) and (
                h.check_lemma("google") or h.check_lemma("web")
                or h.check_lemma("internet")) and h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_
                                == "find" or token.lemma_ == "google"
                                or token.lemma_ == "web"
                                or token.lemma_ == "internet"
                                or token.lemma_ == "image" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch"
                        return userin.execute(["sensible-browser", tab_url],
                                              search_query, True)

        original_com = com
        com = coref.resolve(com)
        if args["verbose"]:
            print("After Coref Resolution: " + com)
        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            return userin.say(arithmetic_response)
        else:
            learner_response = learner.respond(com)
            if learner_response:
                return userin.say(learner_response)
            else:
                omniscient_response = omniscient.respond(
                    com, not args["silent"], userin, user_prefix,
                    args["server"])
                if omniscient_response:
                    return omniscient_response
                else:
                    dc_response = dc.respond(original_com, user_prefix)
                    if dc_response:
                        return userin.say(dc_response)
コード例 #6
0
ファイル: takenote.py プロジェクト: peter3125/Dragonfire
    def takenote_compare1(self, com, note_taker, user_answering_note, userin,
                          user_prefix):
        """Method to dragonfire's first command struct of taking note ability.

        Args:
            com (str):                 User's command.
            note_taker (object):        note_taker class's object.
            user_answering_note:       User answering string array.
            userin:                    :class:`dragonfire.utilities.TextToAction` instance.
            user_prefix:               user's preferred titles.
        """

        doc = nlp(com)
        h = Helper(doc)
        if h.check_verb_lemma("add") or h.check_verb_lemma(
                "generate") or h.check_verb_lemma("create") or (
                    h.check_verb_lemma("take") and h.check_noun_lemma("note")
                ) or h.check_verb_lemma("remind"):
            if h.check_verb_lemma("do") or (  # FOR creating To Do list
                    h.check_verb_lemma("do") and h.check_noun_lemma("list")):
                takenote_query = ""
                for token in doc:
                    if not (token.lemma_ == "add" or token.lemma_ == "generate"
                            or token.lemma_ == "create" or token.lemma_ == "do"
                            or token.lemma_ == "list"
                            or token.lemma_ == "dragonfire" or token.is_stop):
                        takenote_query += ' ' + token.text
                takenote_query = takenote_query.strip()
                user_answering_note['status'] = True
                user_answering_note['isTodo'] = True
                if not takenote_query:  # when command come without note.
                    return userin.say(
                        choice([
                            "Okay, " + user_prefix + ". What is the name?",
                            "I'm listening for give a name to list, " +
                            user_prefix + ".", "Alright, " + user_prefix +
                            ". Please, say a list name.",
                            "Ready. What is the name of list?",
                            "Say a name for list."
                        ]))
                else:  # when command came with note.
                    user_answering_note['toDo_listname'] = ""
                    user_answering_note['toDo_listcount'] = 1
                    user_answering_note['note_keeper'] = takenote_query

                    return userin.say(
                        choice([
                            "1. item receipt. Give a name to the list, " +
                            user_prefix + "."
                        ]))

            if h.check_text("me") or h.check_noun_lemma(
                    "reminder"):  # FOR reminder
                takenote_query = ""
                for token in doc:
                    if not (token.lemma_ == "add" or token.lemma_ == "generate"
                            or token.lemma_ == "remind" or token.lemma_
                            == "create" or token.lemma_ == "reminder"
                            or token.lemma_ == "dragonfire" or token.is_stop):
                        takenote_query += ' ' + token.text
                takenote_query = takenote_query.strip()
                user_answering_note['status'] = True
                user_answering_note['isRemind'] = True
                if not takenote_query:  # when command came without note.
                    return userin.say(
                        choice([
                            "Understood. what is note?",
                            "Yes! I'm listening the note.", "Alright, " +
                            user_prefix + ". What will I remind?",
                            "Ready to record, " + user_prefix +
                            ". what is the note?",
                            "Okay, " + user_prefix + ". Please enter the note."
                        ]))
                else:  # when command came with note.
                    user_answering_note['note_keeper'] = takenote_query
                    return userin.say(
                        choice([
                            "It's Okay, " + user_prefix +
                            ". When will I remind?",
                            "Alright. When do you want to remember?",
                            "Alright, " + user_prefix +
                            ". What is the remind time?",
                            "Note taken. Give the remind time.", "I get it, " +
                            user_prefix + ". Please enter the remind time."
                        ]))

            if h.check_noun_lemma(
                    "note") or not h.check_noun_lemma(""):  # FOR taking note.
                takenote_query = ""
                for token in doc:
                    if not (token.lemma_ == "add" or token.lemma_ == "take" or
                            token.lemma_ == "note" or token.lemma_ == "create"
                            or token.lemma_ == "generate"
                            or token.lemma_ == "dragonfire" or token.is_stop):
                        takenote_query += ' ' + token.text
                takenote_query = takenote_query.strip()
                if not takenote_query:  # when command came without note.
                    user_answering_note['status'] = True
                    return userin.say(
                        choice([
                            "Yes, " + user_prefix + ".", "Yes. I'm listening",
                            "Alright, " + user_prefix + ".",
                            "Ready to record, " + user_prefix + ".",
                            "Keep going, " + user_prefix + "."
                        ]))
                else:  # when command came with note.
                    note_taker.db_upsert(takenote_query)
                    user_answering_note['status'] = False
                    return userin.say(
                        choice([
                            "The note taken", "The note was recorded",
                            "I get it"
                        ]) + choice([".", ", " + user_prefix + "."]))
        return None
コード例 #7
0
ファイル: __init__.py プロジェクト: igorstarki/Dragonfire
    def command(com, args, tw_user=None):

        global e
        if (e.is_set()):  # System Tray Icon exit must trigger this
            exit(0)

        if not com.strip() or not isinstance(com, str):
            return False

        global inactive
        global user_full_name
        global user_prefix
        global config_file

        userin.twitter_user = tw_user

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)

        if args["verbose"]:
            if len(doc) > 0:
                print("")
                print("{:12}  {:12}  {:12}  {:12} {:12}  {:12}  {:12}  {:12}".format("TEXT", "LEMMA", "POS", "TAG", "DEP", "SHAPE", "ALPHA", "STOP"))
                for token in doc:
                    print("{:12}  {:12}  {:12}  {:12} {:12}  {:12}  {:12}  {:12}".format(token.text, token.lemma_, token.pos_, token.tag_, token.dep_, token.shape_, str(token.is_alpha), str(token.is_stop)))
                print("")
            if len(list(doc.noun_chunks)) > 0:
                print("{:12}  {:12}  {:12}  {:12}".format("TEXT", "ROOT.TEXT", "ROOT.DEP_", "ROOT.HEAD.TEXT"))
                for chunk in doc.noun_chunks:
                    print("{:12}  {:12}  {:12}  {:12}".format(chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text))
                print("")

        if inactive and not (h.directly_equal(["dragonfire", "hey"]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire") and h.max_word_count(2))):
            return True

        if USER_ANSWERING['status']:
            if com.startswith("FIRST") or com.startswith("THE FIRST") or com.startswith("SECOND") or com.startswith("THE SECOND") or com.startswith("THIRD") or com.startswith("THE THIRD"):
                USER_ANSWERING['status'] = False
                selection = None
                if com.startswith("FIRST") or com.startswith("THE FIRST"):
                    selection = 0
                elif com.startswith("SECOND") or com.startswith("THE SECOND"):
                    selection = 1
                elif com.startswith("THIRD") or com.startswith("THE THIRD"):
                    selection = 2

                if USER_ANSWERING['for'] == 'wikipedia':
                    with nostderr():
                        search_query = USER_ANSWERING['options'][selection]
                        try:
                            wikiresult = wikipedia.search(search_query)
                            if len(wikiresult) == 0:
                                userin.say("Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.")
                                return True
                            wikipage = wikipedia.page(wikiresult[0])
                            wikicontent = "".join([i if ord(i) < 128 else ' ' for i in wikipage.content])
                            wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                            userin.execute(["sensible-browser", wikipage.url], search_query)
                            userin.say(wikicontent)
                            return True
                        except requests.exceptions.ConnectionError:
                            userin.execute([" "], "Wikipedia connection error.")
                            userin.say("Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers.")
                            return True
                        except Exception:
                            return True

        if h.directly_equal(["dragonfire", "hey"]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire") and h.max_word_count(2)):
            inactive = False
            userin.say(choice([
                "Yes, " + user_prefix + ".",
                "Yes. I'm waiting.",
                "What is your order?",
                "Ready for the orders!",
                user_prefix + ", tell me your wish."
            ]))
            return True
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            inactive = True
            userin.execute(["echo"], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'")
            userin.say("I'm going to sleep")
            return True
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut") and h.check_nth_lemma(-1, "up")):
            tts_kill()
            print("Dragonfire quiets.")
            return True
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            userin.execute([" "], "My name is Dragonfire.", True)
            return True
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            userin.say("I have a female voice but I don't have a gender identity. I'm a computer program, " + user_prefix + ".")
            return True
        if (h.check_wh_lemma("who") and h.check_text("I")) or (h.check_verb_lemma("say") and h.check_text("my") and check_lemma("name")):
            userin.execute([" "], user_full_name)
            userin.say("Your name is " + user_full_name + ", " + user_prefix + ".")
            return True
        if h.check_verb_lemma("open") or h.check_adj_lemma("open") or h.check_verb_lemma("run") or h.check_verb_lemma("start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                userin.say("Blender 3D computer graphics software")
                return True
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                userin.say("Opening LibreOffice Draw")
                return True
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"], "LibreOffice Impress")
                userin.say("Opening LibreOffice Impress")
                return True
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                userin.say("Opening LibreOffice Math")
                return True
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"], "LibreOffice Writer")
                userin.say("Opening LibreOffice Writer")
                return True
            if h.check_text("gimp") or (h.check_noun_lemma("photo") and (h.check_noun_lemma("editor") or h.check_noun_lemma("shop"))):
                userin.execute(["gimp"], "GIMP")
                userin.say("Opening the photo editor software.")
                return True
            if h.check_text("inkscape") or (h.check_noun_lemma("vector") and h.check_noun_lemma("graphic")) or (h.check_text("vectorial") and h.check_text("drawing")):
                userin.execute(["inkscape"], "Inkscape")
                userin.say("Opening the vectorial drawing software.")
                return True
            if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
                userin.execute(["libreoffice"], "LibreOffice")
                userin.say("Opening LibreOffice")
                return True
            if h.check_text("kdenlive") or (h.check_noun_lemma("video") and h.check_noun_lemma("editor")):
                userin.execute(["kdenlive"], "Kdenlive")
                userin.say("Opening the video editor software.")
                return True
            if h.check_noun_lemma("browser") or h.check_noun_lemma("chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                userin.say("Web browser")
                return True
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                userin.say("Opening Steam Game Store")
                return True
            if h.check_text("files") or (h.check_noun_lemma("file") and h.check_noun_lemma("manager")):
                userin.execute(["dolphin"], "File Manager")  # KDE neon
                userin.execute(["pantheon-files"], "File Manager")  # elementary OS
                userin.execute(["nautilus", "--browser"], "File Manager")  # Ubuntu
                userin.say("File Manager")
                return True
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                userin.say("Camera")
                return True
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                userin.say("Calendar")
                return True
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"], "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                userin.say("Calculator")
                return True
            if h.check_noun_lemma("software") and h.check_text("center"):
                userin.execute(["plasma-discover"], "Software Center")  # KDE neon
                userin.execute(["software-center"], "Software Center")  # elementary OS & Ubuntu
                userin.say("Software Center")
                return True
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (h.check_lemma("lady") or h.check_lemma("woman") or h.check_lemma("girl")):
            config_file.update({'gender': 'female'}, Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "My Lady"
            userin.say("Pardon, " + user_prefix + ".")
            return True
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (h.check_lemma("sir") or h.check_lemma("man") or h.check_lemma("boy")):
            config_file.update({'gender': 'male'}, Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "Sir"
            userin.say("Pardon, " + user_prefix + ".")
            return True
        if h.check_lemma("call") and h.check_lemma("-PRON-"):
            title = ""
            for token in doc:
                if token.pos_ == "NOUN":
                    title += ' ' + token.text
            title = title.strip()
            callme_config = config_file.search(Query().datatype == 'callme')
            if callme_config:
                config_file.update({'title': title}, Query().datatype == 'callme')
            else:
                config_file.insert({'datatype': 'callme', 'title': title})
            user_prefix = title
            userin.say("OK, " + user_prefix + ".")
            return True
        # only for The United States today but prepared for all countries. Also
        # only for celsius degrees today. --> by Radan Liska :-)
        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                weather = owm.weather_at_id(reg.ids_for(city)[0][0]).get_weather()
                fmt = "The temperature in {} is {} degrees celsius"
                msg = fmt.format(city, weather.get_temperature('celsius')['temp'])
                userin.execute([" "], msg)
                userin.say(msg)
                return True
        if h.check_nth_lemma(0, "keyboard") or h.check_nth_lemma(0, "type"):
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    for character in com[n:]:
                        k.tap_key(character)
                    k.tap_key(" ")
            return True
        if h.directly_equal(["enter"]) or (h.check_adj_lemma("new") or h.check_noun_lemma("line")):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.tap_key(k.enter_key)
            return True
        if h.check_adj_lemma("new") and h.check_noun_lemma("tab"):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, 't'])
            return True
        if h.check_verb_lemma("switch") and h.check_noun_lemma("tab"):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, k.tab_key])
            return True
        if h.directly_equal(["CLOSE", "ESCAPE"]):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.control_l_key, 'w'])
                    k.tap_key(k.escape_key)
            return True
        if h.check_lemma("back") and h.max_word_count(4):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.alt_l_key, k.left_key])
            return True
        if h.check_lemma("forward") and h.max_word_count(4):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.press_keys([k.alt_l_key, k.right_key])
            return True
        if h.check_text("swipe") or h.check_text("scroll"):
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(0, -5)
                return True
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(0, 5)
                return True
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(5, 0)
                return True
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        m.scroll(-5, 0)
                return True
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"]):
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    k.tap_key(" ")
            return True
        if ((h.check_text("shut") and h.check_text("down")) or (h.check_text("power") and h.check_text("off"))) and h.check_text("computer"):
            userin.execute(["sudo", "poweroff"], "Shutting down", True, 3)
            return True
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(0, "bye") or (h.check_verb_lemma("see") and h.check_noun_lemma("you") and h.check_noun_lemma("later")):
            userin.say("Goodbye, " + user_prefix)
            # raise KeyboardInterrupt
            thread.interrupt_main()
            return True
        if (h.check_lemma("search") or h.check_lemma("find")) and h.check_lemma("wikipedia"):
            with nostderr():
                search_query = ""
                for token in doc:
                    if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "wikipedia" or token.is_stop):
                        search_query += ' ' + token.text
                search_query = search_query.strip()
                if search_query:
                    try:
                        wikiresult = wikipedia.search(search_query)
                        if len(wikiresult) == 0:
                            userin.say("Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.")
                            return True
                        wikipage = wikipedia.page(wikiresult[0])
                        wikicontent = "".join([i if ord(i) < 128 else ' ' for i in wikipage.content])
                        wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                        userin.execute(["sensible-browser", wikipage.url], search_query)
                        userin.say(wikicontent)
                        return True
                    except requests.exceptions.ConnectionError:
                        userin.execute([" "], "Wikipedia connection error.")
                        userin.say("Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers.")
                        return True
                    except wikipedia.exceptions.DisambiguationError as disambiguation:
                        USER_ANSWERING['status'] = True
                        USER_ANSWERING['for'] = 'wikipedia'
                        USER_ANSWERING['reason'] = 'disambiguation'
                        USER_ANSWERING['options'] = disambiguation.options[:3]
                        notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + disambiguation.options[0]
                        message = user_prefix + ", there is a disambiguation. Which one of these you meant? " + disambiguation.options[0]
                        for option in disambiguation.options[1:3]:
                            message += ", or " + option
                            notify += "\n - " + option
                        notify += '\nSay, for example: "THE FIRST ONE" to choose.'
                        userin.execute([" "], notify)
                        userin.say(message)
                        return True
                    except BaseException:
                        pass
        if (h.check_lemma("search") or h.check_lemma("find")) and h.check_lemma("youtube"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "youtube" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        info = youtube_dl.YoutubeDL({}).extract_info('ytsearch:' + search_query, download=False, ie_key='YoutubeSearch')
                        if len(info['entries']) > 0:
                            youtube_title = info['entries'][0]['title']
                            youtube_url = "https://www.youtube.com/watch?v=%s" % (info['entries'][0]['id'])
                            userin.execute(["sensible-browser", youtube_url], youtube_title)
                            youtube_title = "".join([i if ord(i) < 128 else ' ' for i in youtube_title])
                        else:
                            youtube_title = "No video found, " + user_prefix + "."
                        userin.say(youtube_title)
                        time.sleep(5)
                        k = PyKeyboard()
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key(k.tab_key)
                        k.tap_key('f')
                        return True
        if (h.check_lemma("search") or h.check_lemma("find")) and (h.check_lemma("google") or h.check_lemma("web") or h.check_lemma("internet")) and not h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "google" or token.lemma_ == "web" or token.lemma_ == "internet" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query
                        userin.execute(["sensible-browser", tab_url], search_query, True)
                        return True
        if (h.check_lemma("search") or h.check_lemma("find")) and (h.check_lemma("google") or h.check_lemma("web") or h.check_lemma("internet")) and h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "google" or token.lemma_ == "web" or token.lemma_ == "internet" or token.lemma_ == "image" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch"
                        userin.execute(["sensible-browser", tab_url], search_query, True)
                        return True

        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            userin.say(arithmetic_response)
        else:
            learnerresponse = learner.respond(com)
            if learnerresponse:
                userin.say(learnerresponse)
            else:
                if not omniscient.respond(com, not args["silent"], userin, user_prefix, args["server"]):
                    dc_response = dc.respond(com, user_prefix)
                    if dc_response:
                        userin.say(dc_response)
コード例 #8
0
ファイル: __init__.py プロジェクト: ismlkrkmz/Dragonfire
    def command(self, com):
        """Function that serves as the entry point for each one of the user commands.

        This function goes through these steps for each one of user's commands, respectively:

         - Search across the built-in commands via a simple if-else control flow.
         - Try to get a response from :func:`dragonfire.arithmetic.arithmetic_parse` function.
         - Try to get a response from :func:`dragonfire.learn.Learner.respond` method.
         - Try to get a answer from :func:`dragonfire.omniscient.Omniscient.respond` method.
         - Try to get a response from :func:`dragonfire.deepconv.DeepConversation.respond` method.

        Args:
            com (str):  User's command.

        Returns:
            str:  Response.
        """

        if not self.args["server"]:
            global config_file
            global e
            if (e.is_set()):  # System Tray Icon exit must trigger this
                exit(0)
        args = self.args
        userin = self.userin
        user_full_name = self.user_full_name
        user_prefix = self.user_prefix
        if self.testing:
            config_file = self.config_file

        if isinstance(com, str) and com:
            com = com.strip()
        else:
            return False

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)

        if args["verbose"]:
            userin.pretty_print_nlp_parsing_results(doc)

        if self.inactive and not (h.directly_equal(["dragonfire", "hey"]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire") and h.max_word_count(2))):
            return ""

        if USER_ANSWERING['status']:
            if com.startswith("FIRST") or com.startswith("THE FIRST") or com.startswith("SECOND") or com.startswith("THE SECOND") or com.startswith("THIRD") or com.startswith("THE THIRD"):
                USER_ANSWERING['status'] = False
                selection = None
                if com.startswith("FIRST") or com.startswith("THE FIRST"):
                    selection = 0
                elif com.startswith("SECOND") or com.startswith("THE SECOND"):
                    selection = 1
                elif com.startswith("THIRD") or com.startswith("THE THIRD"):
                    selection = 2

                if USER_ANSWERING['for'] == 'wikipedia':
                    with nostderr():
                        search_query = USER_ANSWERING['options'][selection]
                        try:
                            wikiresult = wikipedia.search(search_query)
                            if len(wikiresult) == 0:
                                userin.say("Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.")
                                return True
                            wikipage = wikipedia.page(wikiresult[0])
                            wikicontent = "".join([i if ord(i) < 128 else ' ' for i in wikipage.content])
                            wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                            userin.execute(["sensible-browser", wikipage.url], search_query)
                            return userin.say(wikicontent, cmd=["sensible-browser", wikipage.url])
                        except requests.exceptions.ConnectionError:
                            userin.execute([" "], "Wikipedia connection error.")
                            return userin.say("Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers.")
                        except Exception:
                            return False

        if h.directly_equal(["dragonfire", "hey"]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire") and h.max_word_count(2)):
            self.inactive = False
            return userin.say(choice([
                "Yes, " + user_prefix + ".",
                "Yes. I'm waiting.",
                "What is your order?",
                "Ready for the orders!",
                user_prefix.capitalize() + ", tell me your wish."
            ]))
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            self.inactive = True
            userin.execute(["echo"], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'")
            return userin.say("I'm going to sleep")
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut") and h.check_nth_lemma(-1, "up")):
            tts_kill()
            msg = "Dragonfire quiets."
            print(msg)
            return msg
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            return userin.execute([" "], "My name is Dragonfire.", True)
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            return userin.say("I have a female voice but I don't have a gender identity. I'm a computer program, " + user_prefix + ".")
        if (h.check_wh_lemma("who") and h.check_text("I")) or (h.check_verb_lemma("say") and h.check_text("my") and h.check_lemma("name")):
            userin.execute([" "], user_full_name)
            return userin.say("Your name is " + user_full_name + ", " + user_prefix + ".")
        if h.check_verb_lemma("open") or h.check_adj_lemma("open") or h.check_verb_lemma("run") or h.check_verb_lemma("start") or h.check_verb_lemma("show"):
            if h.check_text("blender"):
                userin.execute(["blender"], "Blender")
                return userin.say("Blender 3D computer graphics software")
            if h.check_text("draw"):
                userin.execute(["libreoffice", "--draw"], "LibreOffice Draw")
                return userin.say("Opening LibreOffice Draw")
            if h.check_text("impress"):
                userin.execute(["libreoffice", "--impress"], "LibreOffice Impress")
                return userin.say("Opening LibreOffice Impress")
            if h.check_text("math"):
                userin.execute(["libreoffice", "--math"], "LibreOffice Math")
                return userin.say("Opening LibreOffice Math")
            if h.check_text("writer"):
                userin.execute(["libreoffice", "--writer"], "LibreOffice Writer")
                return userin.say("Opening LibreOffice Writer")
            if h.check_text("gimp") or (h.check_noun_lemma("photo") and (h.check_noun_lemma("editor") or h.check_noun_lemma("shop"))):
                userin.execute(["gimp"], "GIMP")
                return userin.say("Opening the photo editor software.")
            if h.check_text("inkscape") or (h.check_noun_lemma("vector") and h.check_noun_lemma("graphic")) or (h.check_text("vectorial") and h.check_text("drawing")):
                userin.execute(["inkscape"], "Inkscape")
                return userin.say("Opening the vectorial drawing software.")
            if h.check_noun_lemma("office") and h.check_noun_lemma("suite"):
                userin.execute(["libreoffice"], "LibreOffice")
                return userin.say("Opening LibreOffice")
            if h.check_text("kdenlive") or (h.check_noun_lemma("video") and h.check_noun_lemma("editor")):
                userin.execute(["kdenlive"], "Kdenlive")
                return userin.say("Opening the video editor software.")
            if h.check_noun_lemma("browser") or h.check_text("chrome") or h.check_text("firefox"):
                userin.execute(["sensible-browser"], "Web Browser")
                return userin.say("Web browser")
            if h.check_text("steam"):
                userin.execute(["steam"], "Steam")
                return userin.say("Opening Steam Game Store")
            if h.check_text("files") or (h.check_noun_lemma("file") and h.check_noun_lemma("manager")):
                userin.execute(["dolphin"], "File Manager")  # KDE neon
                userin.execute(["pantheon-files"], "File Manager")  # elementary OS
                userin.execute(["nautilus", "--browser"], "File Manager")  # Ubuntu
                return userin.say("File Manager")
            if h.check_noun_lemma("camera"):
                userin.execute(["kamoso"], "Camera")  # KDE neon
                userin.execute(["snap-photobooth"], "Camera")  # elementary OS
                userin.execute(["cheese"], "Camera")  # Ubuntu
                return userin.say("Camera")
            if h.check_noun_lemma("calendar"):
                userin.execute(["korganizer"], "Calendar")  # KDE neon
                userin.execute(["maya-calendar"], "Calendar")  # elementary OS
                userin.execute(["orage"], "Calendar")  # Ubuntu
                return userin.say("Calendar")
            if h.check_noun_lemma("calculator"):
                userin.execute(["kcalc"], "Calculator")  # KDE neon
                userin.execute(["pantheon-calculator"], "Calculator")  # elementary OS
                userin.execute(["gnome-calculator"], "Calculator")  # Ubuntu
                return userin.say("Calculator")
            if h.check_noun_lemma("software") and h.check_text("center"):
                userin.execute(["plasma-discover"], "Software Center")  # KDE neon
                userin.execute(["software-center"], "Software Center")  # elementary OS & Ubuntu
                return userin.say("Software Center")
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (h.check_lemma("lady") or h.check_lemma("woman") or h.check_lemma("girl")):
            config_file.update({'gender': 'female'}, Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "my lady"
            return userin.say("Pardon, " + user_prefix + ".")
        if h.check_lemma("be") and h.check_lemma("-PRON-") and (h.check_lemma("sir") or h.check_lemma("man") or h.check_lemma("boy")):
            config_file.update({'gender': 'male'}, Query().datatype == 'gender')
            config_file.remove(Query().datatype == 'callme')
            user_prefix = "sir"
            return userin.say("Pardon, " + user_prefix + ".")
        if h.check_lemma("call") and h.check_lemma("-PRON-"):
            title = ""
            for token in doc:
                if token.pos_ == "NOUN":
                    title += ' ' + token.text
            title = title.strip()
            if not args["server"]:
                callme_config = config_file.search(Query().datatype == 'callme')
                if callme_config:
                    config_file.update({'title': title}, Query().datatype == 'callme')
                else:
                    config_file.insert({'datatype': 'callme', 'title': title})
            user_prefix = title
            return userin.say("OK, " + user_prefix + ".")
        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                try:
                    weather = owm.weather_at_id(reg.ids_for(city)[0][0]).get_weather()
                    fmt = "The temperature in {} is {} degrees celsius"
                    msg = fmt.format(city, weather.get_temperature('celsius')['temp'])
                    userin.execute([" "], msg)
                    return userin.say(msg)
                except IndexError:
                    msg = "Sorry, " + user_prefix + " but I couldn't find a city named " + city + " on the internet."
                    userin.execute([" "], msg)
                    return userin.say(msg)
        if (h.check_nth_lemma(0, "keyboard") or h.check_nth_lemma(0, "type")) and not args["server"]:
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        for character in com[n:]:
                            k.tap_key(character)
                        k.tap_key(" ")
            return "keyboard"
        if (h.directly_equal(["enter"]) or (h.check_adj_lemma("new") and h.check_noun_lemma("line"))) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(k.enter_key)
            return "enter"
        if h.check_adj_lemma("new") and h.check_noun_lemma("tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 't'])
            return "new tab"
        if h.check_verb_lemma("switch") and h.check_noun_lemma("tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, k.tab_key])
            return "switch tab"
        if h.directly_equal(["CLOSE", "ESCAPE"]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 'w'])
                        k.tap_key(k.escape_key)
            return "close"
        if h.check_lemma("back") and h.max_word_count(4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.left_key])
            return "back"
        if h.check_lemma("forward") and h.max_word_count(4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.right_key])
            return "forward"
        if (h.check_text("swipe") or h.check_text("scroll")) and not args["server"]:
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, -5)
                return "swipe left"
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, 5)
                return "swipe right"
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(5, 0)
                return "swipe up"
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(-5, 0)
                return "swipe down"
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(" ")
            return "play"
        if ((h.check_text("shut") and h.check_text("down")) or (h.check_text("power") and h.check_text("off"))) and h.check_text("computer") and not args["server"]:
            return userin.execute(["sudo", "poweroff"], "Shutting down", True, 3)
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(0, "bye") or (h.check_verb_lemma("see") and h.check_text("you") and h.check_adv_lemma("later")):
            response = userin.say("Goodbye, " + user_prefix)
            if not args["server"] and not self.testing:
                # raise KeyboardInterrupt
                thread.interrupt_main()
            return response
        if (h.check_lemma("search") or h.check_lemma("find")) and h.check_lemma("wikipedia"):
            with nostderr():
                search_query = ""
                for token in doc:
                    if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "wikipedia" or token.is_stop):
                        search_query += ' ' + token.text
                search_query = search_query.strip()
                if search_query:
                    try:
                        wikiresult = wikipedia.search(search_query)
                        if len(wikiresult) == 0:
                            userin.say("Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.")
                            return True
                        wikipage = wikipedia.page(wikiresult[0])
                        wikicontent = "".join([i if ord(i) < 128 else ' ' for i in wikipage.content])
                        wikicontent = re.sub(r'\([^)]*\)', '', wikicontent)
                        userin.execute(["sensible-browser", wikipage.url], search_query)
                        return userin.say(wikicontent, cmd=["sensible-browser", wikipage.url])
                    except requests.exceptions.ConnectionError:
                        userin.execute([" "], "Wikipedia connection error.")
                        return userin.say("Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers.")
                    except wikipedia.exceptions.DisambiguationError as disambiguation:
                        USER_ANSWERING['status'] = True
                        USER_ANSWERING['for'] = 'wikipedia'
                        USER_ANSWERING['reason'] = 'disambiguation'
                        USER_ANSWERING['options'] = disambiguation.options[:3]
                        notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + disambiguation.options[0]
                        msg = user_prefix + ", there is a disambiguation. Which one of these you meant? " + disambiguation.options[0]
                        for option in disambiguation.options[1:3]:
                            msg += ", or " + option
                            notify += "\n - " + option
                        notify += '\nSay, for example: "THE FIRST ONE" to choose.'
                        userin.execute([" "], notify)
                        return userin.say(msg)
                    except BaseException:
                        pass
        if (h.check_lemma("search") or h.check_lemma("find")) and h.check_lemma("youtube"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "youtube" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        info = youtube_dl.YoutubeDL({}).extract_info('ytsearch:' + search_query, download=False, ie_key='YoutubeSearch')
                        if len(info['entries']) > 0:
                            youtube_title = info['entries'][0]['title']
                            youtube_url = "https://www.youtube.com/watch?v=%s" % (info['entries'][0]['id'])
                            userin.execute(["sensible-browser", youtube_url], youtube_title)
                            youtube_title = "".join([i if ord(i) < 128 else ' ' for i in youtube_title])
                            response = userin.say(youtube_title, ["sensible-browser", youtube_url])
                        else:
                            youtube_title = "No video found, " + user_prefix + "."
                            response = userin.say(youtube_title)
                        k = PyKeyboard()
                        if not args["server"] and not self.testing:
                            time.sleep(5)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key(k.tab_key)
                            k.tap_key('f')
                        return response
        if (h.check_lemma("search") or h.check_lemma("find")) and (h.check_lemma("google") or h.check_lemma("web") or h.check_lemma("internet")) and not h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "google" or token.lemma_ == "web" or token.lemma_ == "internet" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query
                        return userin.execute(["sensible-browser", tab_url], search_query, True)
        if (h.check_lemma("search") or h.check_lemma("find")) and (h.check_lemma("google") or h.check_lemma("web") or h.check_lemma("internet")) and h.check_lemma("image"):
            with nostdout():
                with nostderr():
                    search_query = ""
                    for token in doc:
                        if not (token.lemma_ == "search" or token.lemma_ == "find" or token.lemma_ == "google" or token.lemma_ == "web" or token.lemma_ == "internet" or token.lemma_ == "image" or token.is_stop):
                            search_query += ' ' + token.text
                    search_query = search_query.strip()
                    if search_query:
                        tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch"
                        return userin.execute(["sensible-browser", tab_url], search_query, True)

        original_com = com
        com = coref.resolve(com)
        if args["verbose"]:
            print("After Coref Resolution: " + com)
        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            return userin.say(arithmetic_response)
        else:
            learner_response = learner.respond(com)
            if learner_response:
                return userin.say(learner_response)
            else:
                omniscient_response = omniscient.respond(com, not args["silent"], userin, user_prefix, args["server"])
                if omniscient_response:
                    return omniscient_response
                else:
                    dc_response = dc.respond(original_com, user_prefix)
                    if dc_response:
                        return userin.say(dc_response)
コード例 #9
0
    def compare(self, com, args, testing):
        """Method to dragonfire's command structures of keyboard keys ability.

        Args:
            com (str):                 User's command.
            args:                      Command-line arguments.
        """

        self.testing = testing

        doc = nlp(com)
        h = Helper(doc)
        if (h.check_nth_lemma(0, "keyboard")
                or h.check_nth_lemma(0, "type")) and not args["server"]:
            n = len(doc[0].text) + 1
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        for character in com[n:]:
                            k.tap_key(character)
                        k.tap_key(" ")
            return "keyboard"
        if (h.directly_equal(["enter"]) or
            (h.check_adj_lemma("new")
             and h.check_noun_lemma("line"))) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(k.enter_key)
            return "enter"
        if h.check_adj_lemma("new") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 't'])
            return "new tab"
        if h.check_verb_lemma("switch") and h.check_noun_lemma(
                "tab") and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, k.tab_key])
            return "switch tab"
        if h.directly_equal(["CLOSE", "ESCAPE"]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.control_l_key, 'w'])
                        k.tap_key(k.escape_key)
            return "close"
        if h.check_lemma("back") and h.max_word_count(
                4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.left_key])
            return "back"
        if h.check_lemma("forward") and h.max_word_count(
                4) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.press_keys([k.alt_l_key, k.right_key])
            return "forward"
        if (h.check_text("swipe")
                or h.check_text("scroll")) and not args["server"]:
            if h.check_text("left"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, -5)
                return "swipe left"
            if h.check_text("right"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(0, 5)
                return "swipe right"
            if h.check_text("up"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(5, 0)
                return "swipe up"
            if h.check_text("down"):
                with nostdout():
                    with nostderr():
                        m = PyMouse()
                        if not self.testing:
                            m.scroll(-5, 0)
                return "swipe down"
        if h.directly_equal(["PLAY", "PAUSE", "SPACEBAR"
                             ]) and not args["server"]:
            with nostdout():
                with nostderr():
                    k = PyKeyboard()
                    if not self.testing:
                        k.tap_key(" ")
            return "play"
        return None
コード例 #10
0
    def command(self, com):
        """Function that serves as the entry point for each one of the user commands.

        This function goes through these steps for each one of user's commands, respectively:

         - Search across the built-in commands via a simple if-else control flow.
         - Try to get a response from :func:`dragonfire.arithmetic.arithmetic_parse` function.
         - Try to get a response from :func:`dragonfire.learn.Learner.respond` method.
         - Try to get a answer from :func:`dragonfire.omniscient.Omniscient.respond` method.
         - Try to get a response from :func:`dragonfire.deepconv.DeepConversation.respond` method.

        Args:
            com (str):  User's command.

        Returns:
            str:  Response.
        """

        if not self.args["server"]:
            global config_file
            global e
            if (e.is_set()):  # System Tray Icon exit must trigger this
                exit(0)
        args = self.args
        userin = self.userin
        user_full_name = self.user_full_name
        user_prefix = self.user_prefix
        if self.testing:
            config_file = self.config_file

        if isinstance(com, str) and com:
            com = com.strip()
        else:
            return False

        print("You: " + com.upper())
        doc = nlp(com)
        h = Helper(doc)

        if args["verbose"]:
            userin.pretty_print_nlp_parsing_results(doc)

        if self.inactive and not (
                h.directly_equal(["dragonfire", "hey"]) or
            (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or
            (h.check_nth_lemma(0, "dragon") and h.check_nth_lemma(1, "fire")
             and h.max_word_count(2))):
            return ""

        response = takeNoteCommand.takenote_compare2(
            com, noteTaker, USER_ANSWERING_NOTE, userin,
            user_prefix)  #take note command.
        if response:
            return response

        response = takeNoteCommand.getnote_compare2(com, noteTaker,
                                                    USER_ANSWERING_NOTE,
                                                    userin, user_prefix)
        if response:
            return response

        response = findInWikiCommand.second_compare(com, USER_ANSWERING_WIKI,
                                                    userin, user_prefix)
        if response:
            return response

        if h.directly_equal([
                "dragonfire", "hey"
        ]) or (h.check_verb_lemma("wake") and h.check_nth_lemma(-1, "up")) or (
                h.check_nth_lemma(0, "dragon")
                and h.check_nth_lemma(1, "fire") and h.max_word_count(2)):
            self.inactive = False
            return userin.say(
                choice([
                    "Yes, " + user_prefix + ".", "Yes. I'm waiting.",
                    "What is your order?", "Ready for the orders!",
                    user_prefix.capitalize() + ", tell me your wish."
                ]))
        if (h.check_verb_lemma("go") and h.check_noun_lemma("sleep")) or (
                h.check_verb_lemma("stop") and h.check_verb_lemma("listen")):
            self.inactive = True
            userin.execute([
                "echo"
            ], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'"
                           )
            return userin.say("I'm going to sleep")
        if h.directly_equal(["enough"]) or (h.check_verb_lemma("shut")
                                            and h.check_nth_lemma(-1, "up")):
            tts_kill()
            msg = "Dragonfire quiets."
            print(msg)
            return msg
        if h.check_wh_lemma("what") and h.check_deps_contains("your name"):
            return userin.execute([" "], "My name is Dragonfire.", True)
        if h.check_wh_lemma("what") and h.check_deps_contains("your gender"):
            return userin.say(
                "I have a female voice but I don't have a gender identity. I'm a computer program, "
                + user_prefix + ".")
        if (h.check_wh_lemma("who")
                and h.check_text("I")) or (h.check_verb_lemma("say")
                                           and h.check_text("my")
                                           and h.check_lemma("name")):
            userin.execute([" "], user_full_name)
            return userin.say("Your name is " + user_full_name + ", " +
                              user_prefix + ".")

        if (h.check_verb_lemma("what") and h.check_deps_contains("the time")
            ) or h.check_noun_lemma("time") or (
                h.check_verb_lemma("get") or h.check_verb_lemma("say")
                and h.check_deps_contains("the time")) or (
                    h.check_verb_lemma("what") and h.check_noun_lemma("time")
                    and h.check_text("it")):
            takenote_query = ""
            for token in doc:
                if not (token.lemma_ == "what" or token.lemma_ == "time"
                        or token.lemma_ == "get" or token.lemma_ == "say"
                        or token.lemma_ == "it" or token.is_stop):
                    takenote_query += ' ' + token.text
            takenote_query = takenote_query.strip()
            if not takenote_query:  # for filter of other sentences.
                atthemoment = datetime.datetime.now().strftime("%H:%M")
                return userin.say(atthemoment +
                                  choice([", " + user_prefix + ".", "."]))

        response = takeNoteCommand.getnote_compare1(com, noteTaker,
                                                    USER_ANSWERING_NOTE,
                                                    userin, user_prefix)
        if response:
            return response

        response = cliExecuteCommands.compare(com, userin, user_prefix)
        if response:
            return response

        response = takeNoteCommand.takenote_compare1(
            com, noteTaker, USER_ANSWERING_NOTE, userin,
            user_prefix)  #take note command
        if response:
            return response

        response = setUserTitleCommands.compare(com, args, userin, config_file)
        if response:
            return response

        if h.is_wh_question() and h.check_lemma("temperature"):
            city = ""
            for ent in doc.ents:
                if ent.label_ == "GPE":
                    city += ' ' + ent.text
            city = city.strip()
            if city:
                owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574")
                reg = owm.city_id_registry()
                try:
                    weather = owm.weather_at_id(
                        reg.ids_for(city)[0][0]).get_weather()
                    fmt = "The temperature in {} is {} degrees celsius"
                    msg = fmt.format(
                        city,
                        weather.get_temperature('celsius')['temp'])
                    userin.execute([" "], msg)
                    return userin.say(msg)
                except IndexError:
                    msg = "Sorry, " + user_prefix + " but I couldn't find a city named " + city + " on the internet."
                    userin.execute([" "], msg)
                    return userin.say(msg)

        response = keyboardCommands.compare(com, args, self.testing)
        if response:
            return response

        if ((h.check_text("shut") and h.check_text("down")) or
            (h.check_text("power") and h.check_text("off"))
            ) and h.check_text("computer") and not args["server"]:
            return userin.execute(["sudo", "poweroff"], "Shutting down", True,
                                  3)
        if h.check_nth_lemma(0, "goodbye") or h.check_nth_lemma(
                0, "bye") or (h.check_verb_lemma("see") and h.check_text("you")
                              and h.check_adv_lemma("later")):
            response = userin.say("Goodbye, " + user_prefix)
            if not args["server"] and not self.testing:
                # raise KeyboardInterrupt
                thread.interrupt_main()
            return response

        response = findInWikiCommand.first_compare(com, USER_ANSWERING_WIKI,
                                                   userin, user_prefix)
        if response:
            return response

        response = findInYoutubeCommand.compare(com, args, self.testing,
                                                userin, user_prefix)
        if response:
            return response

        response = findInBrowserCommand.compare_content(
            com, userin, user_prefix)
        if response:
            return response

        response = findInBrowserCommand.compare_image(com, userin, user_prefix)
        if response:
            return response

        original_com = com
        com = coref.resolve(com)
        if args["verbose"]:
            print("After Coref Resolution: " + com)
        arithmetic_response = arithmetic_parse(com)
        if arithmetic_response:
            return userin.say(arithmetic_response)
        else:
            learner_response = learner.respond(com)
            if learner_response:
                return userin.say(learner_response)
            else:
                omniscient_response = omniscient.respond(
                    com, not args["silent"], userin, user_prefix,
                    args["server"])
                if omniscient_response:
                    return omniscient_response
                else:
                    dc_response = dc.respond(original_com, user_prefix)
                    if dc_response:
                        return userin.say(dc_response)