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