]> git.openstreetmap.org Git - nominatim.git/blob - docs/develop/ICU-Tokenizer-Modules.md
docs: fix dangling links
[nominatim.git] / docs / develop / ICU-Tokenizer-Modules.md
1 # Writing custom sanitizer and token analysis modules for the ICU tokenizer
2
3 The [ICU tokenizer](../customize/Tokenizers.md#icu-tokenizer) provides a
4 highly customizable method to pre-process and normalize the name information
5 of the input data before it is added to the search index. It comes with a
6 selection of sanitizers and token analyzers which you can use to adapt your
7 installation to your needs. If the provided modules are not enough, you can
8 also provide your own implementations. This section describes the API
9 of sanitizers and token analysis.
10
11 !!! warning
12     This API is currently in early alpha status. While this API is meant to
13     be a public API on which other sanitizers and token analyzers may be
14     implemented, it is not guaranteed to be stable at the moment.
15
16
17 ## Using non-standard sanitizers and token analyzers
18
19 Sanitizer names (in the `step` property) and token analysis names (in the
20 `analyzer`) may refer to externally supplied modules. There are two ways
21 to include external modules: through a library or from the project directory.
22
23 To include a module from a library, use the absolute import path as name and
24 make sure the library can be found in your PYTHONPATH.
25
26 To use a custom module without creating a library, you can put the module
27 somewhere in your project directory and then use the relative path to the
28 file. Include the whole name of the file including the `.py` ending.
29
30 ## Custom sanitizer modules
31
32 A sanitizer module must export a single factory function `create` with the
33 following signature:
34
35 ``` python
36 def create(config: SanitizerConfig) -> Callable[[ProcessInfo], None]
37 ```
38
39 The function receives the custom configuration for the sanitizer and must
40 return a callable (function or class) that transforms the name and address
41 terms of a place. When a place is processed, then a `ProcessInfo` object
42 is created from the information that was queried from the database. This
43 object is sequentially handed to each configured sanitizer, so that each
44 sanitizer receives the result of processing from the previous sanitizer.
45 After the last sanitizer is finished, the resulting name and address lists
46 are forwarded to the token analysis module.
47
48 Sanitizer functions are instantiated once and then called for each place
49 that is imported or updated. They don't need to be thread-safe.
50 If multi-threading is used, each thread creates their own instance of
51 the function.
52
53 ### Sanitizer configuration
54
55 ::: nominatim.tokenizer.sanitizers.config.SanitizerConfig
56     rendering:
57         show_source: no
58         heading_level: 6
59
60 ### The main filter function of the sanitizer
61
62 The filter function receives a single object of type `ProcessInfo`
63 which has with three members:
64
65  * `place`: read-only information about the place being processed.
66    See PlaceInfo below.
67  * `names`: The current list of names for the place. Each name is a
68    PlaceName object.
69  * `address`: The current list of address names for the place. Each name
70    is a PlaceName object.
71
72 While the `place` member is provided for information only, the `names` and
73 `address` lists are meant to be manipulated by the sanitizer. It may add and
74 remove entries, change information within a single entry (for example by
75 adding extra attributes) or completely replace the list with a different one.
76
77 #### PlaceInfo - information about the place
78
79 ::: nominatim.data.place_info.PlaceInfo
80     rendering:
81         show_source: no
82         heading_level: 6
83
84
85 #### PlaceName - extended naming information
86
87 ::: nominatim.data.place_name.PlaceName
88     rendering:
89         show_source: no
90         heading_level: 6
91
92
93 ### Example: Filter for US street prefixes
94
95 The following sanitizer removes the directional prefixes from street names
96 in the US:
97
98 ``` python
99 import re
100
101 def _filter_function(obj):
102     if obj.place.country_code == 'us' \
103        and obj.place.rank_address >= 26 and obj.place.rank_address <= 27:
104         for name in obj.names:
105             name.name = re.sub(r'^(north|south|west|east) ',
106                                '',
107                                name.name,
108                                flags=re.IGNORECASE)
109
110 def create(config):
111     return _filter_function
112 ```
113
114 This is the most simple form of a sanitizer module. If defines a single
115 filter function and implements the required `create()` function by returning
116 the filter.
117
118 The filter function first checks if the object is interesting for the
119 sanitizer. Namely it checks if the place is in the US (through `country_code`)
120 and it the place is a street (a `rank_address` of 26 or 27). If the
121 conditions are met, then it goes through all available names and
122 removes any leading directional prefix using a simple regular expression.
123
124 Save the source code in a file in your project directory, for example as
125 `us_streets.py`. Then you can use the sanitizer in your `icu_tokenizer.yaml`:
126
127 ``` yaml
128 ...
129 sanitizers:
130     - step: us_streets.py
131 ...
132 ```
133
134 !!! warning
135     This example is just a simplified show case on how to create a sanitizer.
136     It is not really read for real-world use: while the sanitizer would
137     correcly transform `West 5th Street` into `5th Street`. it would also
138     shorten a simple `North Street` to `Street`.
139
140 For more sanitizer examples, have a look at the sanitizers provided by Nominatim.
141 They can be found in the directory
142 [`nominatim/tokenizer/sanitizers`](https://github.com/osm-search/Nominatim/tree/master/nominatim/tokenizer/sanitizers).
143
144
145 ## Custom token analysis module
146
147 ::: nominatim.tokenizer.token_analysis.base.AnalysisModule
148     rendering:
149         show_source: no
150         heading_level: 6
151
152
153 ::: nominatim.tokenizer.token_analysis.base.Analyzer
154     rendering:
155         show_source: no
156         heading_level: 6
157
158 ### Example: Creating acronym variants for long names
159
160 The following example of a token analysis module creates acronyms from
161 very long names and adds them as a variant:
162
163 ``` python
164 class AcronymMaker:
165     """ This class is the actual analyzer.
166     """
167     def __init__(self, norm, trans):
168         self.norm = norm
169         self.trans = trans
170
171
172     def get_canonical_id(self, name):
173         # In simple cases, the normalized name can be used as a canonical id.
174         return self.norm.transliterate(name.name).strip()
175
176
177     def compute_variants(self, name):
178         # The transliterated form of the name always makes up a variant.
179         variants = [self.trans.transliterate(name)]
180
181         # Only create acronyms from very long words.
182         if len(name) > 20:
183             # Take the first letter from each word to form the acronym.
184             acronym = ''.join(w[0] for w in name.split())
185             # If that leds to an acronym with at least three letters,
186             # add the resulting acronym as a variant.
187             if len(acronym) > 2:
188                 # Never forget to transliterate the variants before returning them.
189                 variants.append(self.trans.transliterate(acronym))
190
191         return variants
192
193 # The following two functions are the module interface.
194
195 def configure(rules, normalizer, transliterator):
196     # There is no configuration to parse and no data to set up.
197     # Just return an empty configuration.
198     return None
199
200
201 def create(normalizer, transliterator, config):
202     # Return a new instance of our token analysis class above.
203     return AcronymMaker(normalizer, transliterator)
204 ```
205
206 Given the name `Trans-Siberian Railway`, the code above would return the full
207 name `Trans-Siberian Railway` and the acronym `TSR` as variant, so that
208 searching would work for both.
209
210 ## Sanitizers vs. Token analysis - what to use for variants?
211
212 It is not always clear when to implement variations in the sanitizer and
213 when to write a token analysis module. Just take the acronym example
214 above: it would also have been possible to write a sanitizer which adds the
215 acronym as an additional name to the name list. The result would have been
216 similar. So which should be used when?
217
218 The most important thing to keep in mind is that variants created by the
219 token analysis are only saved in the word lookup table. They do not need
220 extra space in the search index. If there are many spelling variations, this
221 can mean quite a significant amount of space is saved.
222
223 When creating additional names with a sanitizer, these names are completely
224 independent. In particular, they can be fed into different token analysis
225 modules. This gives a much greater flexibility but at the price that the
226 additional names increase the size of the search index.
227