2 Module containing the SPWikiLoader class.
6 from collections.abc import Iterator
7 from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
8 from nominatim.tools.exec_utils import get_url
10 LOG = logging.getLogger()
11 class SPWikiLoader(Iterator):
13 Handles loading of special phrases from the wiki.
15 def __init__(self, config, languages=None):
16 if languages is not None and not isinstance(languages, list):
17 raise TypeError('The \'languages\' parameter should be of type list.')
20 #Compile the regex here to increase performances.
21 self.occurence_pattern = re.compile(
22 r'\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([\-YN])'
24 self.languages = self._load_languages() if not languages else languages
27 if not self.languages:
30 lang = self.languages.pop(0)
31 loaded_xml = self._get_wiki_content(lang)
32 LOG.warning('Importing phrases for lang: %s...', lang)
33 return self.parse_xml(loaded_xml)
35 def parse_xml(self, xml):
37 Parses XML content and extracts special phrases from it.
38 Return a list of SpecialPhrase.
40 #One match will be of format [label, class, type, operator, plural]
41 matches = self.occurence_pattern.findall(xml)
42 returned_phrases = set()
45 SpecialPhrase(match[0], match[1], match[2], match[3])
47 return returned_phrases
49 def _load_languages(self):
51 Get list of all languages from env config file
52 or default if there is no languages configured.
53 The system will extract special phrases only from all specified languages.
56 'af', 'ar', 'br', 'ca', 'cs', 'de', 'en', 'es',
57 'et', 'eu', 'fa', 'fi', 'fr', 'gl', 'hr', 'hu',
58 'ia', 'is', 'it', 'ja', 'mk', 'nl', 'no', 'pl',
59 'ps', 'pt', 'ru', 'sk', 'sl', 'sv', 'uk', 'vi']
60 return self.config.LANGUAGES.split(',') if self.config.LANGUAGES else default_languages
63 def _get_wiki_content(lang):
65 Request and return the wiki page's content
66 corresponding to special phrases for a given lang.
67 Requested URL Example :
68 https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/EN
70 url = 'https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/' + lang.upper() # pylint: disable=line-too-long