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