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