]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/country_info.py
ef79a55afa290a8871e3120285b5363a3016f7cc
[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 json
11 import psycopg2.extras
12
13 from nominatim.db import utils as db_utils
14 from nominatim.db.connection import connect
15
16 class _CountryInfo:
17     """ Caches country-specific properties from the configuration file.
18     """
19
20     def __init__(self):
21         self._info = {}
22         self._key_prefix = 'name'
23
24
25     def load(self, config):
26         """ Load the country properties from the configuration files,
27             if they are not loaded yet.
28         """
29         if not self._info:
30             self._info = config.load_sub_configuration('country_settings.yaml')
31             # Convert languages into a list for simpler handling.
32             for prop in self._info.values():
33                 if 'languages' not in prop:
34                     prop['languages'] = []
35                 elif not isinstance(prop['languages'], list):
36                     prop['languages'] = [x.strip()
37                                          for x in prop['languages'].split(',')]
38                 if 'names' not in prop:
39                     prop['names'][self._key_prefix] = {}
40
41     def items(self):
42         """ Return tuples of (country_code, property dict) as iterable.
43         """
44         return self._info.items()
45
46     def key_prefix(self):
47         """ Return the prefix that will be attached to the keys of the country
48             names values when storing them in the database
49         """
50         return self._key_prefix
51
52
53 _COUNTRY_INFO = _CountryInfo()
54
55 def setup_country_config(config):
56     """ Load country properties from the configuration file.
57         Needs to be called before using any other functions in this
58         file.
59     """
60     _COUNTRY_INFO.load(config)
61
62
63 def iterate():
64     """ Iterate over country code and properties.
65     """
66     return _COUNTRY_INFO.items()
67
68
69 def setup_country_tables(dsn, sql_dir, ignore_partitions=False):
70     """ Create and populate the tables with basic static data that provides
71         the background for geocoding. Data is assumed to not yet exist.
72     """
73     db_utils.execute_file(dsn, sql_dir / 'country_osm_grid.sql.gz')
74
75     def add_prefix_to_keys(names, prefix):
76         return {prefix+':'+k: v for k, v in names.items()}
77
78     params = []
79     for ccode, props in _COUNTRY_INFO.items():
80         if ccode is not None and props is not None:
81             if ignore_partitions:
82                 partition = 0
83             else:
84                 partition = props.get('partition')
85             lang = props['languages'][0] if len(props['languages']) == 1 else None
86             name = add_prefix_to_keys(props.get('names')
87                  .get(_COUNTRY_INFO.key_prefix()), _COUNTRY_INFO.key_prefix())
88             name = json.dumps(name, ensure_ascii=False, separators=(', ', '=>'))
89             params.append((ccode, name[1:-1], lang, partition))
90     with connect(dsn) as conn:
91         with conn.cursor() as cur:
92             cur.execute(
93                 """ CREATE TABLE public.country_name (
94                         country_code character varying(2),
95                         name public.hstore,
96                         derived_name public.hstore,
97                         country_default_language_code text,
98                         partition integer
99                     ); """)
100             cur.execute_values(
101                 """ INSERT INTO public.country_name
102                     (country_code, name, country_default_language_code, partition) VALUES %s
103                 """, params)
104         conn.commit()
105
106
107 def create_country_names(conn, tokenizer, languages=None):
108     """ Add default country names to search index. `languages` is a comma-
109         separated list of language codes as used in OSM. If `languages` is not
110         empty then only name translations for the given languages are added
111         to the index.
112     """
113     if languages:
114         languages = languages.split(',')
115
116     def _include_key(key):
117         return key == _COUNTRY_INFO.key_prefix() or \
118                (key.startswith(_COUNTRY_INFO.key_prefix()+':') and
119             (not languages or key[len(_COUNTRY_INFO.key_prefix())+1:] in languages))
120
121     with conn.cursor() as cur:
122         psycopg2.extras.register_hstore(cur)
123         cur.execute("""SELECT country_code, name FROM country_name
124                        WHERE country_code is not null""")
125
126         with tokenizer.name_analyzer() as analyzer:
127             for code, name in cur:
128                 names = {'countrycode': code}
129                 if code == 'gb':
130                     names['short_name'] = 'UK'
131                 if code == 'us':
132                     names['short_name'] = 'United States'
133
134                 # country names (only in languages as provided)
135                 if name:
136                     names.update(((k, v) for k, v in name.items() if _include_key(k)))
137
138                 analyzer.add_country_names(code, names)
139
140     conn.commit()