"""Build an offline OSM address index. Public map data only, no customer data.""" import datetime,json,os,re,sqlite3,sys,time,unicodedata from pathlib import Path import osmium from shapely.geometry import LineString,Point,mapping from shapely.ops import polygonize,unary_union BASE=Path(sys.argv[1]) PBF=BASE/'region.osm.pbf' OUT=BASE/'addresses.build.sqlite3' if OUT.exists():OUT.unlink() db=sqlite3.connect(OUT) db.executescript(''' PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; CREATE TABLE addresses(id TEXT PRIMARY KEY,node_id INTEGER,street TEXT,house TEXT,city TEXT,label TEXT,lon REAL,lat REAL); CREATE INDEX addresses_node ON addresses(node_id); CREATE TABLE places(id TEXT PRIMARY KEY,name TEXT,aliases TEXT,kind TEXT,lon REAL,lat REAL); CREATE TABLE meta(key TEXT PRIMARY KEY,value TEXT); ''') def norm(s): return re.sub(r'[^a-zа-я0-9]+',' ',unicodedata.normalize('NFKC',str(s)).lower().replace('ё','е')).strip() def house(s):return re.sub(r'[^0-9а-яa-z/\-]','',str(s).lower().replace('ё','е').replace('корпус','к')) def address(kind,oid,t,nid,xy=None): hn=t.get('addr:housenumber','');st=t.get('addr:street','');city=t.get('addr:city') or t.get('addr:village') or t.get('addr:place') or '' if not hn or not (st or city):return label=', '.join(v for v in [city,st,hn] if v) db.execute('INSERT OR IGNORE INTO addresses VALUES(?,?,?,?,?,?,?,?)',(kind+str(oid),nid,norm(st),house(hn),norm(city),label,xy[0] if xy else None,xy[1] if xy else None)) class Ways(osmium.SimpleHandler): def __init__(self):super().__init__();self.ring=[];self.ring_ids=set();self.count=0 def way(self,w): t=w.tags if not len(w.nodes):return if t.get('addr:housenumber'):address('w',w.id,t,w.nodes[0].ref) ref=re.sub(r'[^AАaа0-9]','',t.get('ref','')).upper().replace('А','A') if ref=='A118' and t.get('highway') in ('motorway','trunk','primary'): refs=[n.ref for n in w.nodes];self.ring.append(refs);self.ring_ids.update(refs) print('READ_WAYS',flush=True) w=Ways();w.apply_file(str(PBF));db.commit() needed={row[0] for row in db.execute('SELECT node_id FROM addresses')} coords={} print('READ_NODES',len(needed),'KAD_WAYS',len(w.ring),flush=True) class Nodes(osmium.SimpleHandler): def node(self,n): if not n.location.valid():return x,y=n.location.lon,n.location.lat if n.id in w.ring_ids:coords[n.id]=(x,y) if n.id in needed:db.execute('UPDATE addresses SET lon=?,lat=? WHERE node_id=?',(x,y,n.id)) if not (27.7<=x<=33.5 and 58.4<=y<=61.3):return t=n.tags if t.get('addr:housenumber'):address('n',n.id,t,n.id,(x,y)) if t.get('place') in ('city','town','village','hamlet','suburb','isolated_dwelling') and t.get('name'): aliases=sorted(set(norm(v) for key in ['name','alt_name','old_name','official_name','name:ru'] for v in t.get(key,'').split(';') if v)) db.execute('INSERT OR IGNORE INTO places VALUES(?,?,?,?,?,?)',('n'+str(n.id),t['name'],json.dumps(aliases,ensure_ascii=False),t['place'],x,y)) Nodes().apply_file(str(PBF));db.commit() db.execute('DELETE FROM addresses WHERE lon IS NULL OR lon<27.7 OR lon>33.5 OR lat<58.4 OR lat>61.3') db.executescript('CREATE INDEX addresses_house ON addresses(house); CREATE INDEX addresses_city ON addresses(city); CREATE INDEX places_name ON places(name);') print('MAKE_KAD',len(coords),flush=True) lines=[LineString([coords[n] for n in refs]) for refs in w.ring if all(n in coords for n in refs)] polys=[p for p in polygonize(unary_union(lines)) if p.contains(Point(30.315,59.939))] if not polys:raise ValueError('NO_CLOSED_KAD_POLYGON') poly=max(polys,key=lambda p:p.area) if not (29.4