]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/country_info.py
apply variants by languages
[nominatim.git] / nominatim / tools / country_info.py
1 """
2 Functions for importing and managing static country information.
3 """
4 import psycopg2.extras
5
6 from nominatim.db import utils as db_utils
7 from nominatim.db.connection import connect
8
9 class _CountryInfo:
10     """ Caches country-specific properties from the configuration file.
11     """
12
13     def __init__(self):
14         self._info = {}
15
16
17     def load(self, config):
18         """ Load the country properties from the configuration files,
19             if they are not loaded yet.
20         """
21         if not self._info:
22             self._info = config.load_sub_configuration('country_settings.yaml')
23             # Convert languages into a list for simpler handling.
24             for prop in self._info.values():
25                 if 'languages' not in prop:
26                     prop['languages'] = []
27                 elif not isinstance(prop['languages'], list):
28                     prop['languages'] = [x.strip()
29                                          for x in prop['languages'].split(',')]
30
31
32     def items(self):
33         """ Return tuples of (country_code, property dict) as iterable.
34         """
35         return self._info.items()
36
37
38 _COUNTRY_INFO = _CountryInfo()
39
40 def setup_country_config(config):
41     """ Load country properties from the configuration file.
42         Needs to be called before using any other functions in this
43         file.
44     """
45     _COUNTRY_INFO.load(config)
46
47
48 def iterate():
49     """ Iterate over country code and properties.
50     """
51     return _COUNTRY_INFO.items()
52
53
54 def setup_country_tables(dsn, sql_dir, ignore_partitions=False):
55     """ Create and populate the tables with basic static data that provides
56         the background for geocoding. Data is assumed to not yet exist.
57     """
58     db_utils.execute_file(dsn, sql_dir / 'country_name.sql')
59     db_utils.execute_file(dsn, sql_dir / 'country_osm_grid.sql.gz')
60
61     params = []
62     for ccode, props in _COUNTRY_INFO.items():
63         if ccode is not None and props is not None:
64             if ignore_partitions:
65                 partition = 0
66             else:
67                 partition = props.get('partition')
68             lang = props['languages'][0] if len(props['languages']) == 1 else None
69             params.append((ccode, partition, lang))
70
71     with connect(dsn) as conn:
72         with conn.cursor() as cur:
73             cur.execute_values(
74                 """ UPDATE country_name
75                     SET partition = part, country_default_language_code = lang
76                     FROM (VALUES %s) AS v (cc, part, lang)
77                     WHERE country_code = v.cc""", params)
78         conn.commit()
79
80
81 def create_country_names(conn, tokenizer, languages=None):
82     """ Add default country names to search index. `languages` is a comma-
83         separated list of language codes as used in OSM. If `languages` is not
84         empty then only name translations for the given languages are added
85         to the index.
86     """
87     if languages:
88         languages = languages.split(',')
89
90     def _include_key(key):
91         return key == 'name' or \
92                (key.startswith('name:') and (not languages or key[5:] in languages))
93
94     with conn.cursor() as cur:
95         psycopg2.extras.register_hstore(cur)
96         cur.execute("""SELECT country_code, name FROM country_name
97                        WHERE country_code is not null""")
98
99         with tokenizer.name_analyzer() as analyzer:
100             for code, name in cur:
101                 names = {'countrycode': code}
102                 if code == 'gb':
103                     names['short_name'] = 'UK'
104                 if code == 'us':
105                     names['short_name'] = 'United States'
106
107                 # country names (only in languages as provided)
108                 if name:
109                     names.update(((k, v) for k, v in name.items() if _include_key(k)))
110
111                 analyzer.add_country_names(code, names)
112
113     conn.commit()