-
Notifications
You must be signed in to change notification settings - Fork 5
/
wikipedia_searcher.py
82 lines (68 loc) · 3.08 KB
/
wikipedia_searcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import logging
from kalliope.core.NeuronModule import NeuronModule, InvalidParameterException
import wikipedia
logging.basicConfig()
logger = logging.getLogger("kalliope")
class Wikipedia_searcher(NeuronModule):
def __init__(self, **kwargs):
# we don't need the TTS cache for this neuron
cache = kwargs.get('cache', None)
if cache is None:
cache = False
kwargs["cache"] = cache
super(Wikipedia_searcher, self).__init__(**kwargs)
# get parameters form the neuron
self.query = kwargs.get('query', None)
self.language = kwargs.get('language', None)
self.sentences = kwargs.get('sentences', None)
self.may_refer = None
self.returncode = None
self.message = None
# check parameters
if self._is_parameters_ok():
# set the language
wikipedia.set_lang(self.language)
# do the summary search
try:
summary = wikipedia.summary(self.query, auto_suggest=True, sentences=self.sentences)
# if we are here, no exception raised, we got a summary
self.returncode = "SummaryFound"
except wikipedia.exceptions.DisambiguationError as e:
# Exception raised when a page resolves to a Disambiguation page.
# The options property contains a list of titles of Wikipedia pages that the query may refer to.
self.may_refer = e.options
# Removing duplicates in lists.
self.may_refer = list(set(self.may_refer))
self.returncode = "DisambiguationError"
summary = ""
except wikipedia.exceptions.PageError:
# Exception raised when no Wikipedia matched a query.
self.returncode = "PageError"
summary = ""
self.message = {
"summary": summary,
"may_refer": self.may_refer,
"returncode": self.returncode
}
logger.debug("Wikipedia returned message: %s" % str(self.message))
self.say(self.message)
def _is_parameters_ok(self):
"""
Check if received parameters are ok to perform operations in the neuron
:return: true if parameters are ok, raise an exception otherwise
.. raises:: InvalidParameterException
"""
if self.query is None or self.query == "":
raise InvalidParameterException("Wikipedia needs a query")
if self.language is None:
raise InvalidParameterException("Wikipedia needs a language")
valid_language = wikipedia.languages().keys()
if self.language not in valid_language:
raise InvalidParameterException("Wikipedia needs a valid language: %s" % valid_language)
if self.sentences is not None:
try:
self.sentences = int(self.sentences)
except ValueError:
# Handle the exception
raise InvalidParameterException("Number of sentences must be an integer")
return True