]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/icu_rule_loader.py
cb38cfdfb0da9e4ca3f79f09ab7d6812df4d5778
[nominatim.git] / nominatim / tokenizer / icu_rule_loader.py
1 """
2 Helper class to create ICU rules from a configuration file.
3 """
4 import importlib
5 import io
6 import json
7 import logging
8
9 from nominatim.config import flatten_config_list
10 from nominatim.db.properties import set_property, get_property
11 from nominatim.errors import UsageError
12 from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
13
14 LOG = logging.getLogger()
15
16 DBCFG_IMPORT_NORM_RULES = "tokenizer_import_normalisation"
17 DBCFG_IMPORT_TRANS_RULES = "tokenizer_import_transliteration"
18 DBCFG_IMPORT_ANALYSIS_RULES = "tokenizer_import_analysis_rules"
19
20
21 def _get_section(rules, section):
22     """ Get the section named 'section' from the rules. If the section does
23         not exist, raise a usage error with a meaningful message.
24     """
25     if section not in rules:
26         LOG.fatal("Section '%s' not found in tokenizer config.", section)
27         raise UsageError("Syntax error in tokenizer configuration file.")
28
29     return rules[section]
30
31
32 class ICURuleLoader:
33     """ Compiler for ICU rules from a tokenizer configuration file.
34     """
35
36     def __init__(self, config):
37         rules = config.load_sub_configuration('icu_tokenizer.yaml',
38                                               config='TOKENIZER_CONFIG')
39
40         self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
41         self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
42         self.analysis_rules = _get_section(rules, 'token-analysis')
43         self._setup_analysis()
44
45         # Load optional sanitizer rule set.
46         self.sanitizer_rules = rules.get('sanitizers', [])
47
48
49     def load_config_from_db(self, conn):
50         """ Get previously saved parts of the configuration from the
51             database.
52         """
53         self.normalization_rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
54         self.transliteration_rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
55         self.analysis_rules = json.loads(get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES))
56         self._setup_analysis()
57
58
59     def save_config_to_db(self, conn):
60         """ Save the part of the configuration that cannot be changed into
61             the database.
62         """
63         set_property(conn, DBCFG_IMPORT_NORM_RULES, self.normalization_rules)
64         set_property(conn, DBCFG_IMPORT_TRANS_RULES, self.transliteration_rules)
65         set_property(conn, DBCFG_IMPORT_ANALYSIS_RULES, json.dumps(self.analysis_rules))
66
67
68     def make_sanitizer(self):
69         """ Create a place sanitizer from the configured rules.
70         """
71         return PlaceSanitizer(self.sanitizer_rules)
72
73
74     def make_token_analysis(self):
75         """ Create a token analyser from the reviouly loaded rules.
76         """
77         return self.analysis[None].create(self.normalization_rules,
78                                           self.transliteration_rules)
79
80
81     def get_search_rules(self):
82         """ Return the ICU rules to be used during search.
83             The rules combine normalization and transliteration.
84         """
85         # First apply the normalization rules.
86         rules = io.StringIO()
87         rules.write(self.normalization_rules)
88
89         # Then add transliteration.
90         rules.write(self.transliteration_rules)
91         return rules.getvalue()
92
93
94     def get_normalization_rules(self):
95         """ Return rules for normalisation of a term.
96         """
97         return self.normalization_rules
98
99
100     def get_transliteration_rules(self):
101         """ Return the rules for converting a string into its asciii representation.
102         """
103         return self.transliteration_rules
104
105
106     def _setup_analysis(self):
107         """ Process the rules used for creating the various token analyzers.
108         """
109         self.analysis = {}
110
111         if not isinstance(self.analysis_rules, list):
112             raise UsageError("Configuration section 'token-analysis' must be a list.")
113
114         for section in self.analysis_rules:
115             name = section.get('id', None)
116             if name in self.analysis:
117                 if name is None:
118                     LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
119                 else:
120                     LOG.fatal("ICU tokenizer configuration has two token "
121                               "analyzers with id '%s'.", name)
122                 UsageError("Syntax error in ICU tokenizer config.")
123             self.analysis[name] = TokenAnalyzerRule(section, self.normalization_rules)
124
125
126     @staticmethod
127     def _cfg_to_icu_rules(rules, section):
128         """ Load an ICU ruleset from the given section. If the section is a
129             simple string, it is interpreted as a file name and the rules are
130             loaded verbatim from the given file. The filename is expected to be
131             relative to the tokenizer rule file. If the section is a list then
132             each line is assumed to be a rule. All rules are concatenated and returned.
133         """
134         content = _get_section(rules, section)
135
136         if content is None:
137             return ''
138
139         return ';'.join(flatten_config_list(content, section)) + ';'
140
141
142 class TokenAnalyzerRule:
143     """ Factory for a single analysis module. The class saves the configuration
144         and creates a new token analyzer on request.
145     """
146
147     def __init__(self, rules, normalization_rules):
148         # Find the analysis module
149         module_name = 'nominatim.tokenizer.token_analysis.' \
150                       + _get_section(rules, 'analyzer').replace('-', '_')
151         analysis_mod = importlib.import_module(module_name)
152         self._mod_create = analysis_mod.create
153
154         # Load the configuration.
155         self.config = analysis_mod.configure(rules, normalization_rules)
156
157
158     def create(self, normalization_rules, transliteration_rules):
159         """ Create an analyzer from the given rules.
160         """
161         return self._mod_create(normalization_rules,
162                                 transliteration_rules,
163                                 self.config)