1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Module containing the SPWikiLoader class.
12 from collections.abc import Iterator
13 from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
14 from nominatim.tools.exec_utils import get_url
16 LOG = logging.getLogger()
17 class SPWikiLoader(Iterator):
19 Handles loading of special phrases from the wiki.
21 def __init__(self, config, languages=None):
24 # Compile the regex here to increase performances.
25 self.occurence_pattern = re.compile(
26 r'\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([^\|]+) *\|\| *([\-YN])'
28 self.languages = self._load_languages() if not languages else list(languages)
31 if not self.languages:
34 lang = self.languages.pop(0)
35 loaded_xml = self._get_wiki_content(lang)
36 LOG.warning('Importing phrases for lang: %s...', lang)
37 return self.parse_xml(loaded_xml)
39 def parse_xml(self, xml):
41 Parses XML content and extracts special phrases from it.
42 Return a list of SpecialPhrase.
44 # One match will be of format [label, class, type, operator, plural]
45 matches = self.occurence_pattern.findall(xml)
46 returned_phrases = set()
49 SpecialPhrase(match[0], match[1], match[2], match[3])
51 return returned_phrases
53 def _load_languages(self):
55 Get list of all languages from env config file
56 or default if there is no languages configured.
57 The system will extract special phrases only from all specified languages.
60 'af', 'ar', 'br', 'ca', 'cs', 'de', 'en', 'es',
61 'et', 'eu', 'fa', 'fi', 'fr', 'gl', 'hr', 'hu',
62 'ia', 'is', 'it', 'ja', 'mk', 'nl', 'no', 'pl',
63 'ps', 'pt', 'ru', 'sk', 'sl', 'sv', 'uk', 'vi']
64 return self.config.LANGUAGES.split(',') if self.config.LANGUAGES else default_languages
67 def _get_wiki_content(lang):
69 Request and return the wiki page's content
70 corresponding to special phrases for a given lang.
71 Requested URL Example :
72 https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/EN
74 url = 'https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/' \