]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tokenizer_legacy_icu.py
switch to a more flexible variant description format
[nominatim.git] / test / python / test_tokenizer_legacy_icu.py
1 """
2 Tests for Legacy ICU tokenizer.
3 """
4 import shutil
5 import yaml
6
7 import pytest
8
9 from nominatim.tokenizer import legacy_icu_tokenizer
10 from nominatim.tokenizer.icu_name_processor import ICUNameProcessorRules
11 from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
12 from nominatim.db import properties
13
14
15 @pytest.fixture
16 def test_config(def_config, tmp_path):
17     def_config.project_dir = tmp_path / 'project'
18     def_config.project_dir.mkdir()
19
20     sqldir = tmp_path / 'sql'
21     sqldir.mkdir()
22     (sqldir / 'tokenizer').mkdir()
23     (sqldir / 'tokenizer' / 'legacy_icu_tokenizer.sql').write_text("SELECT 'a'")
24     shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
25                 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
26
27     def_config.lib_dir.sql = sqldir
28
29     return def_config
30
31
32 @pytest.fixture
33 def tokenizer_factory(dsn, tmp_path, property_table,
34                       sql_preprocessor, place_table, word_table):
35     (tmp_path / 'tokenizer').mkdir()
36
37     def _maker():
38         return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
39
40     return _maker
41
42
43 @pytest.fixture
44 def db_prop(temp_db_conn):
45     def _get_db_property(name):
46         return properties.get_property(temp_db_conn, name)
47
48     return _get_db_property
49
50
51 @pytest.fixture
52 def analyzer(tokenizer_factory, test_config, monkeypatch,
53              temp_db_with_extensions, tmp_path):
54     sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_icu_tokenizer.sql'
55     sql.write_text("SELECT 'a';")
56
57     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
58     tok = tokenizer_factory()
59     tok.init_new_db(test_config)
60     monkeypatch.undo()
61
62     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
63                      variants=('~gasse -> gasse', 'street => st', )):
64         cfgfile = tmp_path / 'analyser_test_config.yaml'
65         with cfgfile.open('w') as stream:
66             cfgstr = {'normalization' : list(norm),
67                        'transliteration' : list(trans),
68                        'variants' : [ {'words': list(variants)}]}
69             yaml.dump(cfgstr, stream)
70         tok.naming_rules = ICUNameProcessorRules(loader=ICURuleLoader(cfgfile))
71
72         return tok.name_analyzer()
73
74     return _mk_analyser
75
76
77 @pytest.fixture
78 def getorcreate_full_word(temp_db_cursor):
79     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
80                                                  norm_term TEXT, lookup_terms TEXT[],
81                                                  OUT full_token INT,
82                                                  OUT partial_tokens INT[])
83   AS $$
84 DECLARE
85   partial_terms TEXT[] = '{}'::TEXT[];
86   term TEXT;
87   term_id INTEGER;
88   term_count INTEGER;
89 BEGIN
90   SELECT min(word_id) INTO full_token
91     FROM word WHERE word = norm_term and class is null and country_code is null;
92
93   IF full_token IS NULL THEN
94     full_token := nextval('seq_word');
95     INSERT INTO word (word_id, word_token, word, search_name_count)
96       SELECT full_token, ' ' || lookup_term, norm_term, 0 FROM unnest(lookup_terms) as lookup_term;
97   END IF;
98
99   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
100     term := trim(term);
101     IF NOT (ARRAY[term] <@ partial_terms) THEN
102       partial_terms := partial_terms || term;
103     END IF;
104   END LOOP;
105
106   partial_tokens := '{}'::INT[];
107   FOR term IN SELECT unnest(partial_terms) LOOP
108     SELECT min(word_id), max(search_name_count) INTO term_id, term_count
109       FROM word WHERE word_token = term and class is null and country_code is null;
110
111     IF term_id IS NULL THEN
112       term_id := nextval('seq_word');
113       term_count := 0;
114       INSERT INTO word (word_id, word_token, search_name_count)
115         VALUES (term_id, term, 0);
116     END IF;
117
118     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
119         partial_tokens := partial_tokens || term_id;
120     END IF;
121   END LOOP;
122 END;
123 $$
124 LANGUAGE plpgsql;
125                               """)
126
127
128 @pytest.fixture
129 def getorcreate_hnr_id(temp_db_cursor):
130     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
131                               RETURNS INTEGER AS $$
132                                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
133
134
135 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
136     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
137
138     tok = tokenizer_factory()
139     tok.init_new_db(test_config)
140
141     assert db_prop(legacy_icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
142     assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) is not None
143
144
145 def test_init_word_table(tokenizer_factory, test_config, place_row, word_table):
146     place_row(names={'name' : 'Test Area', 'ref' : '52'})
147     place_row(names={'name' : 'No Area'})
148     place_row(names={'name' : 'Holzstrasse'})
149
150     tok = tokenizer_factory()
151     tok.init_new_db(test_config)
152
153     assert word_table.get_partial_words() == {('test', 1), ('52', 1),
154                                               ('no', 1), ('area', 2),
155                                               ('holzstrasse', 1), ('holzstr', 1),
156                                               ('holz', 1), ('strasse', 1),
157                                               ('str', 1)}
158
159
160 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
161     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
162     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '90300')
163     tok = tokenizer_factory()
164     tok.init_new_db(test_config)
165     monkeypatch.undo()
166
167     tok = tokenizer_factory()
168     tok.init_from_project()
169
170     assert tok.naming_rules is not None
171     assert tok.term_normalization == ':: lower();'
172     assert tok.max_word_frequency == '90300'
173
174
175 def test_update_sql_functions(db_prop, temp_db_cursor,
176                               tokenizer_factory, test_config, table_factory,
177                               monkeypatch):
178     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
179     tok = tokenizer_factory()
180     tok.init_new_db(test_config)
181     monkeypatch.undo()
182
183     assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
184
185     table_factory('test', 'txt TEXT')
186
187     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
188     func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
189
190     tok.update_sql_functions(test_config)
191
192     test_content = temp_db_cursor.row_set('SELECT * FROM test')
193     assert test_content == set((('1133', ), ))
194
195
196 def test_normalize_postcode(analyzer):
197     with analyzer() as anl:
198         anl.normalize_postcode('123') == '123'
199         anl.normalize_postcode('ab-34 ') == 'AB-34'
200         anl.normalize_postcode('38 Б') == '38 Б'
201
202
203 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
204     table_factory('location_postcode', 'postcode TEXT',
205                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
206
207     with analyzer() as anl:
208         anl.update_postcodes_from_db()
209
210     assert word_table.count() == 3
211     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
212
213
214 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
215     table_factory('location_postcode', 'postcode TEXT',
216                   content=(('1234',), ('45BC', ), ('XX45', )))
217     word_table.add_postcode(' 1234', '1234')
218     word_table.add_postcode(' 5678', '5678')
219
220     with analyzer() as anl:
221         anl.update_postcodes_from_db()
222
223     assert word_table.count() == 3
224     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
225
226
227 def test_update_special_phrase_empty_table(analyzer, word_table):
228     with analyzer() as anl:
229         anl.update_special_phrases([
230             ("König  bei", "amenity", "royal", "near"),
231             ("Könige ", "amenity", "royal", "-"),
232             ("street", "highway", "primary", "in")
233         ], True)
234
235     assert word_table.get_special() \
236                == {(' KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
237                    (' KÖNIGE', 'Könige', 'amenity', 'royal', None),
238                    (' STREET', 'street', 'highway', 'primary', 'in')}
239
240
241 def test_update_special_phrase_delete_all(analyzer, word_table):
242     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
243     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
244
245     assert word_table.count_special() == 2
246
247     with analyzer() as anl:
248         anl.update_special_phrases([], True)
249
250     assert word_table.count_special() == 0
251
252
253 def test_update_special_phrases_no_replace(analyzer, word_table):
254     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
255     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
256
257     assert word_table.count_special() == 2
258
259     with analyzer() as anl:
260         anl.update_special_phrases([], False)
261
262     assert word_table.count_special() == 2
263
264
265 def test_update_special_phrase_modify(analyzer, word_table):
266     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
267     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
268
269     assert word_table.count_special() == 2
270
271     with analyzer() as anl:
272         anl.update_special_phrases([
273             ('prison', 'amenity', 'prison', 'in'),
274             ('bar', 'highway', 'road', '-'),
275             ('garden', 'leisure', 'garden', 'near')
276         ], True)
277
278     assert word_table.get_special() \
279                == {(' PRISON', 'prison', 'amenity', 'prison', 'in'),
280                    (' BAR', 'bar', 'highway', 'road', None),
281                    (' GARDEN', 'garden', 'leisure', 'garden', 'near')}
282
283
284 def test_add_country_names_new(analyzer, word_table):
285     with analyzer() as anl:
286         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
287
288     assert word_table.get_country() == {('es', ' ESPAGÑA'), ('es', ' SPAIN')}
289
290
291 def test_add_country_names_extend(analyzer, word_table):
292     word_table.add_country('ch', ' SCHWEIZ')
293
294     with analyzer() as anl:
295         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
296
297     assert word_table.get_country() == {('ch', ' SCHWEIZ'), ('ch', ' SUISSE')}
298
299
300 class TestPlaceNames:
301
302     @pytest.fixture(autouse=True)
303     def setup(self, analyzer, getorcreate_full_word):
304         with analyzer() as anl:
305             self.analyzer = anl
306             yield anl
307
308
309     def expect_name_terms(self, info, *expected_terms):
310         tokens = self.analyzer.get_word_token_info(expected_terms)
311         for token in tokens:
312             assert token[2] is not None, "No token for {0}".format(token)
313
314         assert eval(info['names']) == set((t[2] for t in tokens))
315
316
317     def test_simple_names(self):
318         info = self.analyzer.process_place({'name': {'name': 'Soft bAr', 'ref': '34'}})
319
320         self.expect_name_terms(info, '#Soft bAr', '#34','Soft', 'bAr', '34')
321
322
323     @pytest.mark.parametrize('sep', [',' , ';'])
324     def test_names_with_separator(self, sep):
325         info = self.analyzer.process_place({'name': {'name': sep.join(('New York', 'Big Apple'))}})
326
327         self.expect_name_terms(info, '#New York', '#Big Apple',
328                                      'new', 'york', 'big', 'apple')
329
330
331     def test_full_names_with_bracket(self):
332         info = self.analyzer.process_place({'name': {'name': 'Houseboat (left)'}})
333
334         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
335                                      'houseboat', 'left')
336
337
338     def test_country_name(self, word_table):
339         info = self.analyzer.process_place({'name': {'name': 'Norge'},
340                                            'country_feature': 'no'})
341
342         self.expect_name_terms(info, '#norge', 'norge')
343         assert word_table.get_country() == {('no', ' NORGE')}
344
345
346 class TestPlaceAddress:
347
348     @pytest.fixture(autouse=True)
349     def setup(self, analyzer, getorcreate_full_word):
350         with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
351             self.analyzer = anl
352             yield anl
353
354
355     def process_address(self, **kwargs):
356         return self.analyzer.process_place({'address': kwargs})
357
358
359     def name_token_set(self, *expected_terms):
360         tokens = self.analyzer.get_word_token_info(expected_terms)
361         for token in tokens:
362             assert token[2] is not None, "No token for {0}".format(token)
363
364         return set((t[2] for t in tokens))
365
366
367     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
368     def test_process_place_postcode(self, word_table, pcode):
369         self.process_address(postcode=pcode)
370
371         assert word_table.get_postcodes() == {pcode, }
372
373
374     @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
375     def test_process_place_bad_postcode(self, word_table, pcode):
376         self.process_address(postcode=pcode)
377
378         assert not word_table.get_postcodes()
379
380
381     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
382     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
383         info = self.process_address(housenumber=hnr)
384
385         assert info['hnr'] == hnr.upper()
386         assert info['hnr_tokens'] == "{-1}"
387
388
389     def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
390         info = self.process_address(conscriptionnumber='1; 2;3')
391
392         assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
393         assert info['hnr_tokens'] == "{-1,-2,-3}"
394
395
396     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
397         info = self.process_address(housenumber='134',
398                                     conscriptionnumber='134',
399                                     streetnumber='99a')
400
401         assert set(info['hnr'].split(';')) == set(('134', '99A'))
402         assert info['hnr_tokens'] == "{-1,-2}"
403
404
405     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
406         info = self.process_address(housenumber="45")
407         assert info['hnr_tokens'] == "{-1}"
408
409         info = self.process_address(housenumber="46")
410         assert info['hnr_tokens'] == "{-2}"
411
412         info = self.process_address(housenumber="41;45")
413         assert eval(info['hnr_tokens']) == {-1, -3}
414
415         info = self.process_address(housenumber="41")
416         assert eval(info['hnr_tokens']) == {-3}
417
418
419     def test_process_place_street(self):
420         info = self.process_address(street='Grand Road')
421
422         assert eval(info['street']) == self.name_token_set('#GRAND ROAD')
423
424
425     def test_process_place_street_empty(self):
426         info = self.process_address(street='🜵')
427
428         assert 'street' not in info
429
430
431     def test_process_place_place(self):
432         info = self.process_address(place='Honu Lulu')
433
434         assert eval(info['place_search']) == self.name_token_set('#HONU LULU',
435                                                                  'HONU', 'LULU')
436         assert eval(info['place_match']) == self.name_token_set('#HONU LULU')
437
438
439     def test_process_place_place_empty(self):
440         info = self.process_address(place='🜵')
441
442         assert 'place_search' not in info
443         assert 'place_match' not in info
444
445
446     def test_process_place_address_terms(self):
447         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
448                                     suburb='Zwickau', street='Hauptstr',
449                                     full='right behind the church')
450
451         city_full = self.name_token_set('#ZWICKAU')
452         city_all = self.name_token_set('#ZWICKAU', 'ZWICKAU')
453         state_full = self.name_token_set('#SACHSEN')
454         state_all = self.name_token_set('#SACHSEN', 'SACHSEN')
455
456         result = {k: [eval(v[0]), eval(v[1])] for k,v in info['addr'].items()}
457
458         assert result == {'city': [city_all, city_full],
459                           'suburb': [city_all, city_full],
460                           'state': [state_all, state_full]}
461
462
463     def test_process_place_address_terms_empty(self):
464         info = self.process_address(country='de', city=' ', street='Hauptstr',
465                                     full='right behind the church')
466
467         assert 'addr' not in info
468