Ejemplo n.º 1
0
def check_wordnik_key():
    """Check if the WordNik API is reachable."""
    global WORDNIK_API_KEY
    global WORDNIK_IS_LOADED
    global wn_api
    try:
        with open(CONFIG_FILE, 'r') as file:
            WORDNIK_API_KEY = json.load(file).get('wordnik_api_key')
        WORDNIK_IS_LOADED = bool(WORDNIK_API_KEY)
    except FileNotFoundError:
        WORDNIK_API_KEY = None
    if WORDNIK_API_KEY:
        try:
            wn_api = WordApi(
                swagger.ApiClient(WORDNIK_API_KEY, WORDNIK_API_URL))
        except NameError:
            WORDNIK_IS_LOADED = False
Ejemplo n.º 2
0
 def _load(self):
     self.api_key = self.config["apikey"]
     self.api_client = swagger.ApiClient(self.api_key,
                                         "http://api.wordnik.com/v4")
     self.word_api = WordApi(self.api_client)
     self.words_api = WordsApi(self.api_client)
Ejemplo n.º 3
0
class DictPlugin(PluginObject):
    # TODO: Reimplement wordnik api for async

    api_key = ""
    api_client = None
    word_api = None
    words_api = None

    config = None

    @property
    def urls(self):
        return self.plugins.get_plugin("URLs")

    def setup(self):
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/wordnik.yml")
        except Exception:
            self.logger.exception("Unable to load the configuration!")
            return self._disable_self()
        if not self.config.exists:
            self.logger.error("Unable to find the configuration at "
                              "config/plugins/wordnik.yml - Did you fill "
                              "it out?")
            return self._disable_self()
        if "apikey" not in self.config or not self.config["apikey"]:
            self.logger.error("Unable to find an API key; did you fill out the"
                              " config?")
            return self._disable_self()

        self._load()
        self.config.add_callback(self._load)

        self.commands.register_command("dict", self.dict_command,
                                       self, "wordnik.dict", default=True)
        self.commands.register_command("wotd", self.wotd_command,
                                       self, "wordnik.wotd", default=True)

    def _load(self):
        self.api_key = self.config["apikey"]
        self.api_client = swagger.ApiClient(self.api_key,
                                            "http://api.wordnik.com/v4")
        self.word_api = WordApi(self.api_client)
        self.words_api = WordsApi(self.api_client)

    def dict_command(self, protocol, caller, source, command, raw_args,
                     args):
        if len(args) < 1:
            caller.respond("Usage: {CHAR}dict <word to look up>")
        else:
            try:
                definition = self.get_definition(args[0])
                if not definition:
                    if isinstance(source, User):
                        caller.respond("%s | No definition found." % args[0])
                    else:
                        source.respond("%s | No definition found." % args[0])
                    return
                word = definition.word
                text = definition.text

                wiktionary_url = "http://en.wiktionary.org/wiki/%s" \
                                 % urllib.quote_plus(word)

                short_url = self.urls.tinyurl(wiktionary_url)
            except Exception as e:
                self.logger.exception("Error looking up word: %s" % args[0])
                caller.respond("Error getting definition: %s" % e)
            else:

                # Necessary attribution as per the Wordnik TOS
                if isinstance(source, User):
                    caller.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))
                else:
                    source.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))

    def wotd_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        try:
            wotd = self.get_wotd()
            definition = self.get_definition(wotd)
            if not definition:
                if isinstance(source, User):
                    caller.respond("%s | No definition found." % wotd)
                else:
                    source.respond("%s | No definition found." % wotd)
                return
            word = definition.word
            text = definition.text

            wiktionary_url = "http://en.wiktionary.org/wiki/%s" \
                             % urllib.quote_plus(word)

            short_url = self.urls.tinyurl(wiktionary_url)
        except Exception as e:
            self.logger.exception("Error looking up word of the day.")
            caller.respond("Error getting definition: %s" % e)
        else:

            # Necessary attribution as per the Wordnik TOS
            if isinstance(source, User):
                caller.respond("%s | %s (%s) - Provided by Wiktionary via "
                               "the Wordnik API" % (word, text, short_url))
            else:
                source.respond("%s | %s (%s) - Provided by Wiktionary via "
                               "the Wordnik API" % (word, text, short_url))

    def get_definition(self, word):
        result = self.word_api.getDefinitions(word, limit=1,
                                              sourceDictionaries="wiktionary")
        self.logger.trace("Data: %s" % result)
        if result:
            return result[0]
        return None

    def get_wotd(self):
        result = self.words_api.getWordOfTheDay()
        self.logger.trace("Data: %s" % result)
        return result.word
Ejemplo n.º 4
0
 def _load(self):
     self.api_key = self.config["apikey"]
     self.api_client = swagger.ApiClient(self.api_key,
                                         "http://api.wordnik.com/v4")
     self.word_api = WordApi(self.api_client)
     self.words_api = WordsApi(self.api_client)
Ejemplo n.º 5
0
class DictPlugin(plugin.PluginObject):

    api_key = ""
    api_client = None
    word_api = None
    words_api = None

    commands = None
    config = None
    plugman = None
    storage = None

    @property
    def urls(self):
        return self.plugman.get_plugin("URLs")

    def setup(self):
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/wordnik.yml")
        except Exception:
            self.logger.exception("Unable to load the configuration!")
            return self._disable_self()
        if not self.config.exists:
            self.logger.error("Unable to find the configuration at "
                              "config/plugins/wordnik.yml - Did you fill "
                              "it out?")
            return self._disable_self()
        if "apikey" not in self.config or not self.config["apikey"]:
            self.logger.error("Unable to find an API key; did you fill out the"
                              " config?")
            return self._disable_self()

        self._load()
        self.config.add_callback(self._load)

        self.plugman = PluginManager()

        self.commands = CommandManager()

        self.commands.register_command("dict",
                                       self.dict_command,
                                       self,
                                       "wordnik.dict",
                                       default=True)
        self.commands.register_command("wotd",
                                       self.wotd_command,
                                       self,
                                       "wordnik.wotd",
                                       default=True)

    def _load(self):
        self.api_key = self.config["apikey"]
        self.api_client = swagger.ApiClient(self.api_key,
                                            "http://api.wordnik.com/v4")
        self.word_api = WordApi(self.api_client)
        self.words_api = WordsApi(self.api_client)

    def dict_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        if len(args) < 1:
            caller.respond("Usage: {CHAR}dict <word to look up>")
        else:
            try:
                definition = self.get_definition(args[0])
                if not definition:
                    if isinstance(source, User):
                        caller.respond("%s | No definition found." % args[0])
                    else:
                        source.respond("%s | No definition found." % args[0])
                    return
                word = definition.word
                text = definition.text

                wiktionary_url = "http://en.wiktionary.org/wiki/%s" \
                                 % urllib.quote_plus(word)

                short_url = self.urls.tinyurl(wiktionary_url)
            except Exception as e:
                self.logger.exception("Error looking up word: %s" % args[0])
                caller.respond("Error getting definition: %s" % e)
            else:

                # Necessary attribution as per the Wordnik TOS
                if isinstance(source, User):
                    caller.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))
                else:
                    source.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))

    def wotd_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        try:
            wotd = self.get_wotd()
            definition = self.get_definition(wotd)
            if not definition:
                if isinstance(source, User):
                    caller.respond("%s | No definition found." % wotd)
                else:
                    source.respond("%s | No definition found." % wotd)
                return
            word = definition.word
            text = definition.text

            wiktionary_url = "http://en.wiktionary.org/wiki/%s" \
                             % urllib.quote_plus(word)

            short_url = self.urls.tinyurl(wiktionary_url)
        except Exception as e:
            self.logger.exception("Error looking up word of the day.")
            caller.respond("Error getting definition: %s" % e)
        else:

            # Necessary attribution as per the Wordnik TOS
            if isinstance(source, User):
                caller.respond("%s | %s (%s) - Provided by Wiktionary via "
                               "the Wordnik API" % (word, text, short_url))
            else:
                source.respond("%s | %s (%s) - Provided by Wiktionary via "
                               "the Wordnik API" % (word, text, short_url))

    def get_definition(self, word):
        result = self.word_api.getDefinitions(word,
                                              limit=1,
                                              sourceDictionaries="wiktionary")
        self.logger.trace("Data: %s" % result)
        if result:
            return result[0]
        return None

    def get_wotd(self):
        result = self.words_api.getWordOfTheDay()
        self.logger.trace("Data: %s" % result)
        return result.word
    def getrelatedwords(self):
        cursor = self.text.textCursor()
        print cursor.hasSelection()

        isConnected = 1
        req = urllib2.Request('http://www.google.com')
        try:
            urllib2.urlopen(req)
        except urllib2.URLError as e:
            print(e.reason)
            isConnected = 0

        if (isConnected == 0):
            print 'Please connect to Internet'
            self.statusbar.showMessage("Please connect to Internet.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Warning)
            msg.setInformativeText("Please connect to Internet.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()


        elif (cursor.hasSelection and QString(cursor.selectedText()).trimmed().length() >= 1 and isConnected):
            textSelected = cursor.selectedText()
            qString = QString(textSelected)
            d = QDialog(self)
            d.setGeometry(300, 200, 263, 195)
            d.setWindowTitle(textSelected)

            wordApi = WordApi(client)
            example = wordApi.getRelatedWords(qString.toLower())

            if example is not None:

                d.textedit = QtGui.QTextEdit(d)
                d.textedit.setPlainText("Related words of " + textSelected)
                d.textedit.setReadOnly(True)
                d.textedit.setAutoFillBackground(True)
                for index in xrange(len(example)):
                    if example[index].relationshipType == 'verb-form':
                        d.textedit.setFontItalic(True)
                        d.textedit.append('verb-form:')
                        d.textedit.setFontItalic(False)
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1)+". " + example[index].words[i])
                    elif example[index].relationshipType == 'hypernym':
                        d.textedit.append('\n hypernym:')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'cross-reference':
                        d.textedit.append('\n cross-reference:')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'variant':
                        d.textedit.append('\n variant:')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'synonym':
                        d.textedit.append('\n synonym:')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'rhyme':
                        d.textedit.append('\n rhyme:')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'unknown':
                        d.textedit.append('\n unknown')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                    if example[index].relationshipType == 'same-context':
                        d.textedit.append('\n same-context')
                        for i in xrange(len(example[index].words)):
                            d.textedit.append(str(i+1) + ". " + example[index].words[i])
                d.exec_()

            else:
                self.statusbar.showMessage("Sorry nothing found.")
                msg = QMessageBox(self)
                msg.setIcon(QMessageBox.Question)
                msg.setInformativeText("Sorry nithing found.")
                msg.setWindowTitle(textSelected)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()

        else:
            print 'no text selected'
            self.statusbar.showMessage("Please select a word or letter.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setInformativeText("Please select a word or a letter.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
    def gettopexample(self):
        cursor = self.text.textCursor()
        print cursor.hasSelection()

        isConnected = 1
        req = urllib2.Request('http://www.google.com')
        try:
            urllib2.urlopen(req)
        except urllib2.URLError as e:
            print(e.reason)
            isConnected = 0

        if (isConnected == 0):
            print 'Please connect to Internet'
            self.statusbar.showMessage("Please connect to Internet.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Warning)
            msg.setInformativeText("Please connect to Internet.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()


        elif (cursor.hasSelection and QString(cursor.selectedText()).trimmed().length() >= 1 and isConnected):
            textSelected = cursor.selectedText()
            qString = QString(textSelected)
            d = QDialog(self)
            d.setGeometry(300, 200, 263, 195)
            d.setWindowTitle(textSelected)

            wordApi = WordApi(client)
            example = wordApi.getTopExample(qString.toLower())

            if example is not None:
                print 'not none'

                d.textedit = QtGui.QTextEdit(d)
                d.textedit.setPlainText("Top Example: " + textSelected)
                d.textedit.setReadOnly(True)
                d.textedit.setAutoFillBackground(True)
                d.textedit.append(example.text)
                d.exec_()

            else:
                print 'Cannot be found'
                self.statusbar.showMessage("Sorry nothing found.")
                msg = QMessageBox(self)
                msg.setIcon(QMessageBox.Question)
                msg.setInformativeText("Sorry nothing found.")
                msg.setWindowTitle(textSelected)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()

        else:
            print 'no text selected'
            self.statusbar.showMessage("Please select a word or letter.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setInformativeText("Please select a word or a letter.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
    def search(self):
        print 'check search functiom def'
        cursor = self.text.textCursor()
        print cursor.hasSelection()

        isConnected = 1
        req = urllib2.Request('http://www.google.com')
        try: urllib2.urlopen(req)
        except urllib2.URLError as e:
            print(e.reason)
            isConnected = 0

        if(isConnected == 0):
            print 'Please connect to Internet'
            self.statusbar.showMessage("Please connect to Internet.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Warning)
            msg.setInformativeText("Please connect to Internet.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()


        elif (cursor.hasSelection and QString(cursor.selectedText()).trimmed().length()>=1 and isConnected):
            textSelected = cursor.selectedText()
            qString = QString(textSelected)
            d = QDialog(self)
            d.setGeometry(300,200,263,195)
            d.setWindowTitle(textSelected)

            wordApi = WordApi(client)
            example = wordApi.getDefinitions(qString.toLower())

            if example is not None:
                print 'not none'

                d.textedit = QtGui.QTextEdit(d)
                d.textedit.setPlainText(textSelected)
                d.textedit.setReadOnly(True)
                d.textedit.setAutoFillBackground(True)
                for index in xrange(len(example)):
                    if example[index].partOfSpeech == 'noun':
                        d.textedit.append('n. '+ example[index].text)
                    elif example[index].partOfSpeech == 'verb-transitive':
                        d.textedit.append('transitive v. '+ example[index].text)
                    elif example[index].partOfSpeech == 'phrasal-verb':
                        d.textedit.append('phrasal v. ' + example[index].text)
                    elif example[index].partOfSpeech == 'idiom':
                        d.textedit.append('idiom. ' + example[index].text)
                    elif example[index].partOfSpeech == 'adjective':
                        d.textedit.append('adj. ' + example[index].text)
                    else:
                        d.textedit.append(example[index].text)
                d.exec_()

            else:
                print 'Cannot be found'
                self.statusbar.showMessage("Please select a word or letter.")
                msg = QMessageBox(self)
                msg.setIcon(QMessageBox.Question)
                msg.setInformativeText("Sorry no defination found.")
                msg.setWindowTitle(textSelected)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()

        else:
            print 'no text selected'
            self.statusbar.showMessage("Please select a word or letter.")
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Information)
            msg.setInformativeText("Please select a word or a letter.")
            msg.setWindowTitle("Alert")
            msg.setStandardButtons(QMessageBox.Ok )
            msg.exec_()