#!/usr/bin/env python3 """Build an atomic, local OSM address/places index. Requires project-local osmium 4.2.0. Addresses on nodes and ways; no address interpolation or relation-only addresses. Usage: .local/geocoder-tools/venv/bin/python scripts/geocoder-import.py input.osm.pbf .local/geocoder """ import argparse, json, os, sqlite3, time, shutil, fcntl from pathlib import Path import osmium def build(source, target, minimum=1): target.mkdir(parents=True,exist_ok=True) lock=(target/'import.lock').open('a') fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) working=target/'addresses.build.sqlite'; cache=target/'nodes.build.cache' # Only these disposable build artifacts are replaced. The active index remains usable. working.unlink(missing_ok=True); cache.unlink(missing_ok=True) started=time.time(); total=0; skipped=0 def status(state,**extra): data={'state':state,'source':source.name,'count':total,'skipped':skipped,'started':started,'updated':time.time(),**extra} temp=target/'status.tmp';temp.write_text(json.dumps(data));temp.replace(target/'status.json') print(json.dumps(data),flush=True) status('indexing') db=sqlite3.connect(working) db.executescript('''PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-65536; PRAGMA temp_store=FILE; CREATE TABLE addresses (id INTEGER PRIMARY KEY, label TEXT NOT NULL, lat REAL NOT NULL, lng REAL NOT NULL, kind TEXT NOT NULL, search_text TEXT NOT NULL); CREATE VIRTUAL TABLE address_geo USING rtree(id,minLat,maxLat,minLng,maxLng); CREATE VIRTUAL TABLE address_search USING fts5(search_text,content='addresses',content_rowid='id',tokenize='unicode61 remove_diacritics 2'); CREATE TABLE metadata (key TEXT PRIMARY KEY,value TEXT NOT NULL); ''') batch=[] def flush(): if batch: db.executemany('INSERT INTO addresses VALUES (?,?,?,?,?,?)',batch) db.executemany('INSERT INTO address_geo VALUES (?,?,?,?,?)',[(r[0],r[2],r[2],r[3],r[3]) for r in batch]) db.executemany('INSERT INTO address_search(rowid,search_text) VALUES (?,?)',[(r[0],r[5]) for r in batch]) db.commit();batch.clear() try: # Disk cache avoids keeping the German node graph in RAM. It is deleted after import. processor=osmium.FileProcessor(str(source),entities=osmium.osm.NODE|osmium.osm.WAY).with_locations('sparse_file_array,'+str(cache)).with_filter(osmium.filter.KeyFilter('addr:housenumber','place')) last=time.time() for obj in processor: tags=obj.tags street=tags.get('addr:street') or tags.get('addr:place') number=tags.get('addr:housenumber') city=tags.get('addr:city') or '' postcode=tags.get('addr:postcode') or '' if street and number: label=', '.join(p for p in [street+' '+number,' '.join(p for p in [postcode,city] if p)] if p);kind='address' elif obj.is_node() and tags.get('place') in ['city','town','village','hamlet','suburb'] and tags.get('name'): label=tags['name'];kind='place' else: continue try: if obj.is_node(): lat,lng=obj.location.lat,obj.location.lon else: refs=list(obj.nodes) if refs and refs[0].ref==refs[-1].ref:refs=refs[:-1] if not refs or any(not n.location.valid() for n in refs):skipped+=1;continue lat=sum(n.lat for n in refs)/len(refs);lng=sum(n.lon for n in refs)/len(refs) except osmium.InvalidLocationError: skipped+=1;continue if not (47.2<=lat<=55.1 and 5.8<=lng<=15.1):continue total+=1 text=label.lower().replace('ß','ss') batch.append((total,label,lat,lng,kind,text)) if len(batch)>=5000:flush() if time.time()-last>30: status('indexing');last=time.time() if shutil.disk_usage(target).free<2*1024**3:raise RuntimeError('Less than 2 GiB free; import stopped to protect the running application') flush();status('checking') assert total>=minimum, 'Unexpectedly few address records' assert db.execute('PRAGMA quick_check').fetchone()[0]=='ok' assert db.execute('SELECT count(*) FROM address_geo').fetchone()[0]==total db.execute("INSERT INTO address_search(address_search,rank) VALUES('integrity-check',1)") db.executemany('INSERT INTO metadata VALUES (?,?)',[('source',source.name),('attribution','© OpenStreetMap contributors, ODbL 1.0'),('license','https://opendatacommons.org/licenses/odbl/1-0/'),('count',str(total)),('created',str(time.time()))]);db.commit();db.close() os.chmod(working,0o644);working.replace(target/'addresses.sqlite');status('ready') except Exception as error: status('failed',error=str(error));raise finally: db.close();cache.unlink(missing_ok=True) if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('source',type=Path);parser.add_argument('target',type=Path);parser.add_argument('--minimum',type=int,default=1) args=parser.parse_args();build(args.source,args.target,args.minimum)