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