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