Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / generate_places_db.py

generate_places_db.py256 lines · 8.9 KiBRaw
1#!/usr/bin/env python3
2"""Offline generator for the weather app's place-search catalogue.
3
4The city search lets the user pick from real GeoNames places rather than
5typing free text, so everything is compiled into the APK and no search
6makes a network request at runtime - the downloads below happen here, at
7build time, not on the device.
8
9One output, handled like the health catalogue:
10
11 weather/src/main/assets/places.db.br gitignored, plus a .meta.json
12
13Source: GeoNames `cities1000` (places with population >= 1000, ~170k rows),
14plus `admin1CodesASCII` and `countryInfo` for display names. The dump is
15CC-BY 4.0 (https://www.geonames.org/about.html); attribution ships in the
16app's about screen.
17
18 https://download.geonames.org/export/dump/cities1000.zip
19 https://download.geonames.org/export/dump/admin1CodesASCII.txt
20 https://download.geonames.org/export/dump/countryInfo.txt
21
22Schema mirrors the server's /wx/v1/search index byte-for-byte (same table
23names, same FTS columns, same ranking SQL in GeoDatabase.kt), so results
24match whether they come from the device or the server:
25
26 places(id, name, asciiname, latitude, longitude, country_code,
27 country_name, admin1, population, timezone)
28 places_fts(name, asciiname, alternates) - hidden alias column like the
29 health labs table: alternate names ("Bombay", "München" ASCII forms)
30 are searchable but the display name stays canonical.
31
32Ranking is exact-name, then prefix, then population, then bm25 - the same
33ORDER BY as the server. Kept byte-for-byte in step with GeoDatabase.kt so
34both resolve a query the same way.
35
36Unlike `generate_food_db.py`, this ships a finished SQLite database rather
37than a columnar file the app rebuilds. At ~170k rows the container and FTS
38index cost little more than the data, and shipping the database directly
39removes the whole on-device build step. Brotli, because the app already
40links a decoder for it.
41
42Usage
43-----
44 python3 scripts/generate_places_db.py # everything
45 python3 scripts/generate_places_db.py --keep-db # keep unpacked SQLite
46"""
47
48from __future__ import annotations
49
50import argparse
51import json
52import sqlite3
53import subprocess
54import sys
55import zipfile
56from pathlib import Path
57
58REPO_ROOT = Path(__file__).resolve().parent.parent
59ASSETS = REPO_ROOT / "weather" / "src" / "main" / "assets"
60
61CITIES_URL = "https://download.geonames.org/export/dump/cities1000.zip"
62ADMIN1_URL = "https://download.geonames.org/export/dump/admin1CodesASCII.txt"
63COUNTRY_URL = "https://download.geonames.org/export/dump/countryInfo.txt"
64
65CACHE_DIR = Path.home() / ".cache" / "geonames"
66CACHED_CITIES = CACHE_DIR / "cities1000.zip"
67CACHED_ADMIN1 = CACHE_DIR / "admin1CodesASCII.txt"
68CACHED_COUNTRY = CACHE_DIR / "countryInfo.txt"
69
70# Bumped in lockstep with SUPPORTED_SCHEMA_VERSION in GeoDatabase.kt.
71SCHEMA_VERSION = 1
72
73
74def mb(n: int) -> str:
75 return f"{n / 1_000_000:.1f} MB"
76
77
78def download(url: str, dest: Path) -> Path:
79 """Fetch `url` to `dest`, skipping the download if it is already cached."""
80 if dest.exists() and dest.stat().st_size > 0:
81 print(f" cached {dest} ({mb(dest.stat().st_size)})")
82 return dest
83 dest.parent.mkdir(parents=True, exist_ok=True)
84 print(f" fetching {url}")
85 subprocess.run(["curl", "-sSL", "--fail", "-o", str(dest), url], check=True)
86 print(f" saved {dest} ({mb(dest.stat().st_size)})")
87 return dest
88
89
90def load_admin1(path: Path) -> dict[str, str]:
91 """admin1 code ("US.CA") -> ASCII name ("California")."""
92 names: dict[str, str] = {}
93 for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
94 if not line.strip() or line.startswith("#"):
95 continue
96 cols = line.split("\t")
97 if len(cols) >= 2:
98 names[cols[0]] = cols[1]
99 return names
100
101
102def load_countries(path: Path) -> dict[str, str]:
103 """ISO code -> country name."""
104 names: dict[str, str] = {}
105 for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
106 if not line.strip() or line.startswith("#"):
107 continue
108 cols = line.split("\t")
109 if len(cols) > 4:
110 names[cols[0]] = cols[4]
111 return names
112
113
114def build_places(
115 cities_zip: Path,
116 admin1_names: dict[str, str],
117 country_names: dict[str, str],
118 conn: sqlite3.Connection,
119) -> int:
120 conn.execute(
121 """
122 CREATE TABLE places (
123 id INTEGER PRIMARY KEY,
124 name TEXT NOT NULL,
125 asciiname TEXT NOT NULL,
126 latitude REAL NOT NULL,
127 longitude REAL NOT NULL,
128 country_code TEXT NOT NULL DEFAULT '',
129 country_name TEXT NOT NULL DEFAULT '',
130 admin1 TEXT NOT NULL DEFAULT '',
131 population INTEGER NOT NULL DEFAULT 0,
132 timezone TEXT NOT NULL DEFAULT ''
133 )
134 """
135 )
136 conn.execute(
137 """
138 CREATE VIRTUAL TABLE places_fts USING fts5(
139 name, asciiname, alternates,
140 content='places', content_rowid='rowid'
141 )
142 """
143 )
144 rows: list[tuple] = []
145 with zipfile.ZipFile(cities_zip) as zf:
146 name = next(n for n in zf.namelist() if n.endswith(".txt"))
147 with zf.open(name) as handle:
148 for raw in handle:
149 line = raw.decode("utf-8", errors="replace").rstrip("\n")
150 if not line.strip():
151 continue
152 # geonameid, name, asciiname, alternatenames, lat, lon,
153 # feature class/code, country, cc2, admin1..4, population,
154 # elevation, dem, timezone, modification.
155 c = line.split("\t")
156 if len(c) < 18:
157 continue
158 try:
159 gid = int(c[0])
160 lat = float(c[4])
161 lon = float(c[5])
162 except ValueError:
163 continue
164 if gid == 0:
165 continue
166 cc = c[8]
167 admin1 = admin1_names.get(f"{cc}.{c[10]}", "")
168 country = country_names.get(cc, "")
169 try:
170 pop = int(c[14])
171 except ValueError:
172 pop = 0
173 tz = c[17] if len(c) > 17 else ""
174 rows.append(
175 (gid, c[1], c[2], lat, lon, cc, country, admin1, pop, tz,
176 c[3].replace(",", " "))
177 )
178 rows.sort(key=lambda r: (r[1].lower(), -r[8]))
179 conn.executemany(
180 "INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
181 [r[:10] for r in rows],
182 )
183 conn.executemany(
184 "INSERT INTO places_fts(rowid, name, asciiname, alternates) VALUES (?, ?, ?, ?)",
185 [(r[0], r[1], r[2], r[10]) for r in rows],
186 )
187 print(f" places {len(rows)} cities")
188 return len(rows)
189
190
191def build_catalog(db_path: Path) -> int:
192 cities_zip = download(CITIES_URL, CACHED_CITIES)
193 admin1_names = load_admin1(download(ADMIN1_URL, CACHED_ADMIN1))
194 country_names = load_countries(download(COUNTRY_URL, CACHED_COUNTRY))
195 db_path.parent.mkdir(parents=True, exist_ok=True)
196 db_path.unlink(missing_ok=True)
197 conn = sqlite3.connect(db_path)
198 try:
199 conn.execute("PRAGMA journal_mode = OFF")
200 conn.execute("PRAGMA synchronous = OFF")
201 count = build_places(cities_zip, admin1_names, country_names, conn)
202 # DELETE, not OFF: the app reopens the file read-only, which a journal
203 # mode of OFF does not survive cleanly.
204 conn.execute("PRAGMA journal_mode = DELETE")
205 conn.commit()
206 conn.execute("VACUUM")
207 conn.commit()
208 finally:
209 conn.close()
210 print(f" built {db_path} ({mb(db_path.stat().st_size)})")
211 return count
212
213
214def compress(src: Path, dest: Path) -> None:
215 try:
216 import brotli
217 except ImportError:
218 sys.exit("brotli is required to compress the asset: pip install brotli")
219 dest.parent.mkdir(parents=True, exist_ok=True)
220 dest.write_bytes(brotli.compress(src.read_bytes(), quality=11))
221 print(f" wrote {dest} ({mb(dest.stat().st_size)})")
222
223
224def main() -> None:
225 ap = argparse.ArgumentParser(description=__doc__)
226 ap.add_argument("--keep-db", action="store_true",
227 help="keep the uncompressed SQLite file next to the asset")
228 args = ap.parse_args()
229
230 print("Places (GeoNames cities1000)")
231 staging = ASSETS / "places.db"
232 count = build_catalog(staging)
233 compress(staging, ASSETS / "places.db.br")
234
235 meta = {
236 "schemaVersion": SCHEMA_VERSION,
237 "places": count,
238 "bytes": staging.stat().st_size,
239 "compressedBytes": (ASSETS / "places.db.br").stat().st_size,
240 "sources": {
241 "cities": CITIES_URL,
242 "admin1": ADMIN1_URL,
243 "country": COUNTRY_URL,
244 },
245 }
246 (ASSETS / "places.db.meta.json").write_text(
247 json.dumps(meta, indent=1) + "\n", newline="\n"
248 )
249 print(f" wrote {ASSETS / 'places.db.meta.json'}")
250
251 if not args.keep_db:
252 staging.unlink(missing_ok=True)
253
254
255if __name__ == "__main__":
256 main()