Coverage for geoparser/gazetteer/artifact.py: 100%

94 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1""" 

2Gazetteer artifact: the canonical, self-contained SQLite file per gazetteer. 

3 

4An artifact is produced by the build pipeline and is immutable afterwards. It 

5has a fixed schema shared by every gazetteer: 

6 

7- ``metadata``: key/value pairs (schema version, gazetteer name, CRS, ...) 

8- ``feature``: one row per feature (identifier, source, JSON data, WKB geometry) 

9- ``name``: searchable names, one row per (feature, name) 

10- ``name_fts``: FTS5 index over names (external content on ``name``) 

11- ``name_soundex``: phonetic codes for fuzzy candidate retrieval 

12 

13This module owns the artifact schema (used by the build pipeline) and the 

14read-only runtime access layer (used by the Gazetteer class). 

15""" 

16 

17from __future__ import annotations 

18 

19import os 

20import sqlite3 

21import threading 

22import typing as t 

23from pathlib import Path 

24 

25from appdirs import user_data_dir 

26 

27from geoparser.db.functions import levenshtein, soundex 

28from geoparser.gazetteer.feature import Feature 

29 

30# Bump when the artifact schema changes; artifacts with a different version 

31# must be rebuilt. 

32SCHEMA_VERSION = "1" 

33 

34ARTIFACT_SUFFIX = ".db" 

35 

36FTS_TOKENIZER = "unicode61 remove_diacritics 2 tokenchars '.'" 

37 

38# Base tables created before data is emitted. Search structures (FTS, soundex, 

39# indexes) are created afterwards, once all rows are in place. 

40BASE_SCHEMA = [ 

41 """ 

42 CREATE TABLE metadata ( 

43 key TEXT PRIMARY KEY, 

44 value TEXT 

45 ) 

46 """, 

47 """ 

48 CREATE TABLE feature ( 

49 id INTEGER PRIMARY KEY, 

50 identifier TEXT NOT NULL, 

51 source TEXT NOT NULL, 

52 data TEXT NOT NULL, 

53 geometry BLOB 

54 ) 

55 """, 

56 """ 

57 CREATE TABLE name ( 

58 id INTEGER PRIMARY KEY, 

59 feature_id INTEGER NOT NULL REFERENCES feature(id), 

60 text TEXT NOT NULL 

61 ) 

62 """, 

63] 

64 

65SEARCH_SCHEMA = [ 

66 "CREATE UNIQUE INDEX idx_feature_identifier ON feature(identifier)", 

67 "CREATE INDEX idx_name_feature_id ON name(feature_id)", 

68 f""" 

69 CREATE VIRTUAL TABLE name_fts USING fts5( 

70 text, 

71 content='name', 

72 content_rowid='id', 

73 tokenize="{FTS_TOKENIZER}" 

74 ) 

75 """, 

76 "INSERT INTO name_fts(rowid, text) SELECT id, text FROM name", 

77 """ 

78 CREATE TABLE name_soundex ( 

79 id INTEGER PRIMARY KEY, 

80 code TEXT 

81 ) 

82 """, 

83 "INSERT INTO name_soundex(id, code) SELECT id, soundex(text) FROM name", 

84 "CREATE INDEX idx_name_soundex_code ON name_soundex(code)", 

85] 

86 

87 

88def gazetteers_dir() -> Path: 

89 """ 

90 Return the directory holding installed gazetteer artifacts. 

91 

92 Defaults to the user data directory; can be overridden with the 

93 ``GEOPARSER_GAZETTEERS_DIR`` environment variable. 

94 

95 Returns: 

96 Path to the gazetteers directory 

97 """ 

98 override = os.getenv("GEOPARSER_GAZETTEERS_DIR") 

99 if override: 

100 return Path(override) 

101 return Path(user_data_dir("geoparser", "")) / "gazetteers" 

102 

103 

104def artifact_path(gazetteer_name: str) -> Path: 

105 """ 

106 Return the artifact path for a gazetteer name. 

107 

108 Args: 

109 gazetteer_name: Name of the gazetteer 

110 

111 Returns: 

112 Path where the gazetteer's artifact is (or will be) installed 

113 """ 

114 return gazetteers_dir() / f"{gazetteer_name}{ARTIFACT_SUFFIX}" 

115 

116 

117def list_artifacts() -> t.List[str]: 

118 """ 

119 List the names of installed gazetteers. 

120 

121 Returns: 

122 Sorted list of gazetteer names with an installed artifact 

123 """ 

124 directory = gazetteers_dir() 

125 if not directory.exists(): 

126 return [] 

127 return sorted( 

128 path.stem for path in directory.glob(f"*{ARTIFACT_SUFFIX}") if path.is_file() 

129 ) 

130 

131 

132def register_functions(connection: sqlite3.Connection) -> None: 

133 """ 

134 Register the fuzzy matching functions on a SQLite connection. 

135 

136 Args: 

137 connection: SQLite connection to register functions on 

138 """ 

139 connection.create_function("soundex", 1, soundex, deterministic=True) 

140 connection.create_function("levenshtein", 2, levenshtein, deterministic=True) 

141 

142 

143class GazetteerArtifact: 

144 """ 

145 Read-only access to an installed gazetteer artifact. 

146 

147 Connections are opened read-only and per thread; the artifact file is 

148 never modified after the build. 

149 """ 

150 

151 _FEATURE_COLUMNS = "f.id, f.identifier, f.source, f.data, f.geometry" 

152 

153 def __init__(self, path: t.Union[str, Path]): 

154 """ 

155 Open a gazetteer artifact. 

156 

157 Args: 

158 path: Path to the artifact file 

159 

160 Raises: 

161 FileNotFoundError: If the artifact file does not exist 

162 RuntimeError: If the artifact has an incompatible schema version 

163 """ 

164 self.path = Path(path) 

165 if not self.path.exists(): 

166 raise FileNotFoundError(f"Gazetteer artifact not found: {self.path}") 

167 self._local = threading.local() 

168 self.metadata = self._read_metadata() 

169 version = self.metadata.get("schema_version") 

170 if version != SCHEMA_VERSION: 

171 raise RuntimeError( 

172 f"Gazetteer artifact {self.path} has schema version {version!r}, " 

173 f"but this version of geoparser requires {SCHEMA_VERSION!r}. " 

174 "Please reinstall the gazetteer." 

175 ) 

176 

177 @property 

178 def name(self) -> str: 

179 """Name of the gazetteer stored in this artifact.""" 

180 return self.metadata["name"] 

181 

182 @property 

183 def crs(self) -> str: 

184 """Coordinate reference system of the artifact's geometries.""" 

185 return self.metadata["crs"] 

186 

187 def _connection(self) -> sqlite3.Connection: 

188 """Return the read-only SQLite connection for the current thread.""" 

189 connection = getattr(self._local, "connection", None) 

190 if connection is None: 

191 connection = sqlite3.connect( 

192 f"file:{self.path}?mode=ro", uri=True, check_same_thread=False 

193 ) 

194 register_functions(connection) 

195 self._local.connection = connection 

196 return connection 

197 

198 def _read_metadata(self) -> t.Dict[str, str]: 

199 try: 

200 rows = ( 

201 self._connection().execute("SELECT key, value FROM metadata").fetchall() 

202 ) 

203 except sqlite3.DatabaseError as error: 

204 raise RuntimeError( 

205 f"File {self.path} is not a valid gazetteer artifact: {error}" 

206 ) from error 

207 return dict(rows) 

208 

209 def _features_from_rows(self, rows: t.Iterable[t.Tuple]) -> t.List[Feature]: 

210 return [ 

211 Feature( 

212 artifact=self, 

213 id=row[0], 

214 identifier=row[1], 

215 source=row[2], 

216 data=row[3], 

217 geometry=row[4], 

218 ) 

219 for row in rows 

220 ] 

221 

222 def find(self, identifier: str) -> t.Optional[Feature]: 

223 """ 

224 Find a feature by its identifier. 

225 

226 Args: 

227 identifier: The identifier value of the feature to find 

228 

229 Returns: 

230 Feature object if found, None otherwise 

231 """ 

232 row = ( 

233 self._connection() 

234 .execute( 

235 f"SELECT {self._FEATURE_COLUMNS} FROM feature f WHERE f.identifier = ?", 

236 (str(identifier),), 

237 ) 

238 .fetchone() 

239 ) 

240 if row is None: 

241 return None 

242 return self._features_from_rows([row])[0] 

243 

244 def get_feature_names(self, feature_id: int) -> t.List[str]: 

245 """ 

246 Get all names of a feature. 

247 

248 Args: 

249 feature_id: Internal feature id 

250 

251 Returns: 

252 List of name strings 

253 """ 

254 rows = ( 

255 self._connection() 

256 .execute( 

257 "SELECT text FROM name WHERE feature_id = ? ORDER BY id", 

258 (feature_id,), 

259 ) 

260 .fetchall() 

261 ) 

262 return [row[0] for row in rows] 

263 

264 def search_exact(self, name: str, limit: int = 10000) -> t.List[Feature]: 

265 """ 

266 Find features with a name exactly matching the query. 

267 

268 Uses the FTS index for case- and diacritics-insensitive matching, then 

269 keeps only names of exactly the query's length so token matches on 

270 substrings are excluded. 

271 

272 Args: 

273 name: Name string to search for 

274 limit: Maximum number of results to return 

275 

276 Returns: 

277 List of matching features 

278 """ 

279 rows = ( 

280 self._connection() 

281 .execute( 

282 f""" 

283 SELECT {self._FEATURE_COLUMNS} 

284 FROM name_fts 

285 JOIN name n ON n.id = name_fts.rowid 

286 JOIN feature f ON f.id = n.feature_id 

287 WHERE name_fts MATCH ? AND length(n.text) = ? 

288 GROUP BY f.id 

289 LIMIT ? 

290 """, 

291 (f'"{name}"', len(name), limit), 

292 ) 

293 .fetchall() 

294 ) 

295 return self._features_from_rows(rows) 

296 

297 def _search_tiered( 

298 self, matched_sql: str, parameters: t.Tuple, limit: int, tiers: int 

299 ) -> t.List[Feature]: 

300 """ 

301 Run a per-name match query and keep the best score tiers per feature. 

302 

303 The match query must yield ``(feature_id, score)`` rows (lower scores 

304 are better). It is materialized because SQLite only allows FTS 

305 auxiliary functions like bm25 in the immediate full-text query. 

306 """ 

307 rows = ( 

308 self._connection() 

309 .execute( 

310 f""" 

311 WITH matched AS MATERIALIZED ({matched_sql}), 

312 scored AS ( 

313 SELECT feature_id, min(score) AS score 

314 FROM matched 

315 GROUP BY feature_id 

316 ORDER BY score ASC 

317 LIMIT ? 

318 ), 

319 tiered AS ( 

320 SELECT feature_id, score, 

321 dense_rank() OVER (ORDER BY score ASC) AS tier 

322 FROM scored 

323 ) 

324 SELECT {self._FEATURE_COLUMNS} 

325 FROM feature f 

326 JOIN tiered t ON f.id = t.feature_id 

327 WHERE t.tier <= ? 

328 ORDER BY t.score ASC, f.id ASC 

329 """, 

330 (*parameters, limit, tiers), 

331 ) 

332 .fetchall() 

333 ) 

334 return self._features_from_rows(rows) 

335 

336 def search_phrase( 

337 self, name: str, limit: int = 10000, tiers: int = 1 

338 ) -> t.List[Feature]: 

339 """ 

340 Find features whose names contain the query as a contiguous phrase. 

341 

342 Candidates are scored with BM25 (lower is better) and grouped into 

343 rank tiers; only the best ``tiers`` tiers are returned. 

344 

345 Args: 

346 name: Name string to search for 

347 limit: Maximum number of candidates to score 

348 tiers: Number of rank tiers to include 

349 

350 Returns: 

351 List of matching features, best matches first 

352 """ 

353 matched_sql = """ 

354 SELECT n.feature_id AS feature_id, bm25(name_fts) AS score 

355 FROM name_fts 

356 JOIN name n ON n.id = name_fts.rowid 

357 WHERE name_fts MATCH ? 

358 """ 

359 return self._search_tiered(matched_sql, (f'"{name}"',), limit, tiers) 

360 

361 def search_partial( 

362 self, name: str, limit: int = 10000, tiers: int = 1 

363 ) -> t.List[Feature]: 

364 """ 

365 Find features whose names match some of the query tokens. 

366 

367 Tokens are combined with OR for loose matching; candidates are scored 

368 with BM25 and grouped into rank tiers. 

369 

370 Args: 

371 name: Name string to search for 

372 limit: Maximum number of candidates to score 

373 tiers: Number of rank tiers to include 

374 

375 Returns: 

376 List of matching features, best matches first 

377 """ 

378 query = " OR ".join( 

379 f'"{token.strip()}"' for token in name.split() if token.strip() 

380 ) 

381 matched_sql = """ 

382 SELECT n.feature_id AS feature_id, bm25(name_fts) AS score 

383 FROM name_fts 

384 JOIN name n ON n.id = name_fts.rowid 

385 WHERE name_fts MATCH ? 

386 """ 

387 return self._search_tiered(matched_sql, (query,), limit, tiers) 

388 

389 def search_fuzzy( 

390 self, name: str, limit: int = 10000, tiers: int = 1 

391 ) -> t.List[Feature]: 

392 """ 

393 Find features with names that sound like the query. 

394 

395 Uses Soundex codes for candidate retrieval and Levenshtein edit 

396 distance for ranking; candidates are grouped into distance tiers. 

397 

398 Args: 

399 name: Name string to search for 

400 limit: Maximum number of candidates to score 

401 tiers: Number of distance tiers to include 

402 

403 Returns: 

404 List of matching features, closest matches first 

405 """ 

406 matched_sql = """ 

407 SELECT n.feature_id AS feature_id, levenshtein(?, n.text) AS score 

408 FROM name_soundex s 

409 JOIN name n ON n.id = s.id 

410 WHERE s.code = soundex(?) 

411 """ 

412 return self._search_tiered(matched_sql, (name, name), limit, tiers) 

413 

414 def count_features(self) -> int: 

415 """Return the number of features in the artifact.""" 

416 return self._connection().execute("SELECT count(*) FROM feature").fetchone()[0] 

417 

418 def count_names(self) -> int: 

419 """Return the number of names in the artifact.""" 

420 return self._connection().execute("SELECT count(*) FROM name").fetchone()[0] 

421 

422 def close(self) -> None: 

423 """Close the current thread's connection, if any.""" 

424 connection = getattr(self._local, "connection", None) 

425 if connection is not None: 

426 connection.close() 

427 self._local.connection = None