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