#!/usr/bin/env python3 """Estimate which way a building faces, from OpenStreetMap geometry. ESTIMATE ONLY. The user must confirm with a compass on site: stand inside the main door looking out; that reading is the facing direction. Usage: python3 facing.py 51.5237 -0.1585 # building at / nearest to the point python3 facing.py 51.5237 -0.1585 --way 12345 # force a specific OSM building way id Method (in priority order): 1. entrance node tagged on the building outline (entrance=main preferred) -> outward normal of that wall 2. wall closest to the best nearby road -> outward normal of that wall 3. road perpendicular: perpendicular to the nearest road segment, pointing toward the road Bearings are TRUE north (local azimuthal equidistant projection). Magnetic bearing uses the NOAA World Magnetic Model via pygeomag when installed. Needs: pip install requests shapely pyproj (optional: pygeomag) Data: (c) OpenStreetMap contributors, ODbL, via Overpass API. """ import argparse, json, math, sys, time, datetime as dt import requests from shapely.geometry import Point, LineString, Polygon from shapely.ops import nearest_points, transform from pyproj import Transformer UA = "feng-shui-master-tools/1.0 (https://huggingface.co/Huiginn/feng-shui-master-tools)" import os as _os MIRRORS = ([_os.environ["OVERPASS_URL"]] if _os.environ.get("OVERPASS_URL") else []) + [ "https://overpass-api.de/api/interpreter", "https://overpass.kumi.systems/api/interpreter", "https://overpass.private.coffee/api/interpreter", "https://maps.mail.ru/osm/tools/overpass/api/interpreter"] SKIP = {"footway", "path", "cycleway", "steps", "corridor", "proposed", "construction", "platform", "bridleway", "elevator", "via_ferrata", "raceway", "bus_stop"} PENALTY = {"service": 12, "track": 12, "pedestrian": 8, "living_street": 2, "motorway": 8, "motorway_link": 10, "trunk_link": 6} DIRS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] def osm_api_bbox(lat, lon, radius): """Last-resort fallback: OSM editing API /map for a tiny bbox. Light, occasional use only.""" import xml.etree.ElementTree as ET dlat = radius / 111320.0; dlon = radius / (111320.0 * math.cos(math.radians(lat))) bbox = f"{lon - dlon:.6f},{lat - dlat:.6f},{lon + dlon:.6f},{lat + dlat:.6f}" r = requests.get("https://api.openstreetmap.org/api/0.6/map", params={"bbox": bbox}, headers={"User-Agent": UA}, timeout=40) r.raise_for_status() root = ET.fromstring(r.content) nodes, els = {}, [] for n in root.iter("node"): nodes[n.get("id")] = (float(n.get("lat")), float(n.get("lon"))) tags = {t.get("k"): t.get("v") for t in n.iter("tag")} if tags: els.append({"type": "node", "id": int(n.get("id")), "lat": nodes[n.get("id")][0], "lon": nodes[n.get("id")][1], "tags": tags}) for w in root.iter("way"): tags = {t.get("k"): t.get("v") for t in w.iter("tag")} geom = [{"lat": nodes[nd.get("ref")][0], "lon": nodes[nd.get("ref")][1]} if nd.get("ref") in nodes else None for nd in w.iter("nd")] els.append({"type": "way", "id": int(w.get("id")), "tags": tags, "geometry": geom, "nodes": [int(nd.get("ref")) for nd in w.iter("nd")]}) return {"elements": els} def overpass(query, fallback=None): """Try Overpass mirrors (main API is often overloaded), then the optional fallback().""" import hashlib, os cache = os.path.expanduser("~/.cache/property-check"); os.makedirs(cache, exist_ok=True) cpath = os.path.join(cache, "ovp-" + hashlib.sha1(query.encode()).hexdigest() + ".json") if os.path.exists(cpath) and time.time() - os.path.getmtime(cpath) < 7 * 86400: return json.load(open(cpath)), "cache" errs = [] for url in MIRRORS: try: r = requests.post(url, data={"data": query}, headers={"User-Agent": UA}, timeout=(8, 30)) if r.status_code == 200 and r.text.lstrip().startswith("{"): data = r.json() if data.get("remark", "").lower().startswith("runtime error"): errs.append(f"{url}: {data['remark'][:80]}"); continue json.dump(data, open(cpath, "w")) return data, url errs.append(f"{url}: HTTP {r.status_code}") except requests.RequestException as e: errs.append(f"{url}: {type(e).__name__}") if fallback: try: data = fallback() json.dump(data, open(cpath, "w")) return data, "https://api.openstreetmap.org/api/0.6/map (fallback)" except Exception as e: errs.append(f"OSM API fallback: {type(e).__name__}") raise RuntimeError("all OSM sources failed: " + "; ".join(errs)) def sector(b): return DIRS[int(((b % 360) + 22.5) // 45) % 8] def bearing(dx, dy): return math.degrees(math.atan2(dx, dy)) % 360 def angdiff(a, b): return abs((a - b + 180) % 360 - 180) def load(lat, lon, radius): q = f"""[out:json][timeout:50]; (way(around:{radius},{lat},{lon})["building"]; way(around:{radius + 60},{lat},{lon})["highway"]; node(around:{radius},{lat},{lon})["entrance"];); out tags geom;""" data, src = overpass(q, fallback=lambda: osm_api_bbox(lat, lon, radius + 60)) fwd = Transformer.from_crs("EPSG:4326", f"+proj=aeqd +lat_0={lat} +lon_0={lon} +units=m", always_xy=True) P = lambda lo, la: fwd.transform(lo, la) buildings, roads, entrances = [], [], [] for el in data.get("elements", []): t = el.get("tags", {}) if el["type"] == "node": entrances.append({"id": el["id"], "pt": Point(P(el["lon"], el["lat"])), "kind": t.get("entrance")}) continue coords = [P(g["lon"], g["lat"]) for g in el.get("geometry", []) if g] if "building" in t and len(coords) >= 4: poly = Polygon(coords) if poly.is_valid and poly.area > 5: buildings.append({"id": el["id"], "poly": poly, "tags": t}) elif t.get("highway") and t["highway"] not in SKIP and len(coords) >= 2: roads.append({"id": el["id"], "line": LineString(coords), "tags": t}) return buildings, roads, entrances, src def pick_building(buildings, way_id=None): if way_id: for b in buildings: if b["id"] == way_id: return b, 0.0 return None, None origin = Point(0, 0) inside = [b for b in buildings if b["poly"].contains(origin)] if inside: return min(inside, key=lambda b: b["poly"].area), 0.0 if not buildings: return None, None b = min(buildings, key=lambda b: b["poly"].distance(origin)) return b, b["poly"].distance(origin) def walls(poly): from shapely.geometry.polygon import orient ring = list(orient(poly, sign=1.0).exterior.coords) # counter-clockwise: outward normal = (dy, -dx) out = [] for (x1, y1), (x2, y2) in zip(ring, ring[1:]): L = math.hypot(x2 - x1, y2 - y1) if L < 1.0: continue nx, ny = (y2 - y1) / L, -(x2 - x1) / L out.append({"seg": LineString([(x1, y1), (x2, y2)]), "len": L, "normal": bearing(nx, ny), "mid": Point((x1 + x2) / 2, (y1 + y2) / 2)}) return out def road_candidates(poly, roads): c = [] for r in roads: d = r["line"].distance(poly) if d > 60: continue hw = r["tags"].get("highway") pb, pr = nearest_points(poly, r["line"]) # direction of road segment at the nearest point line = r["line"]; s = line.project(pr) a = line.interpolate(max(0, s - 5)); b = line.interpolate(min(line.length, s + 5)) road_dir = bearing(b.x - a.x, b.y - a.y) v = (pr.x - pb.x, pr.y - pb.y) if d > 0.5 else (pr.x - poly.centroid.x, pr.y - poly.centroid.y) toward = bearing(*v) perp = min(((road_dir + 90) % 360, (road_dir - 90) % 360), key=lambda x: angdiff(x, toward)) if r["tags"].get("bridge") or r["tags"].get("tunnel"): continue c.append({"way_id": r["id"], "highway": hw, "name": r["tags"].get("name"), "distance_m": round(d, 1), "score": d + PENALTY.get(hw, 0) - (3 if r["tags"].get("name") else 0), "road_perpendicular_deg": round(perp, 1)}) c.sort(key=lambda x: x["score"]) # keep one candidate per distinct direction (corner lots) uniq = [] for x in c: if all(angdiff(x["road_perpendicular_deg"], u["road_perpendicular_deg"]) > 30 for u in uniq): uniq.append(x) return uniq def declination(lat, lon): try: from pygeomag import GeoMag now = dt.date.today() year = now.year + (now.timetuple().tm_yday - 1) / 365.25 gm = GeoMag(high_resolution=True) if "high_resolution" in GeoMag.__init__.__code__.co_varnames else GeoMag() return round(gm.calculate(glat=lat, glon=lon, alt=0, time=year).d, 2), "NOAA WMM via pygeomag" except Exception as e: return None, f"declination unavailable ({type(e).__name__}); look it up at NOAA's magnetic field calculator" def main(): ap = argparse.ArgumentParser() ap.add_argument("lat", type=float); ap.add_argument("lon", type=float) ap.add_argument("--way", type=int, help="OSM building way id to use") ap.add_argument("--radius", type=int, default=60) a = ap.parse_args() out = {"input": [a.lat, a.lon], "accessed": time.strftime("%Y-%m-%d %H:%M %z")} try: buildings, roads, entrances, src = load(a.lat, a.lon, a.radius) except RuntimeError as e: print(json.dumps({"error": str(e), "fallback": "Ask the user for the facing, or estimate from satellite view and say so."})) sys.exit(2) out["source"] = src b, dist = pick_building(buildings, a.way) if not b: print(json.dumps({**out, "error": "no OSM building outline here; estimate from satellite view or ask the user"}, indent=2)) sys.exit(1) out["building"] = {"osm": f"https://www.openstreetmap.org/way/{b['id']}", "name": b["tags"].get("name"), "distance_from_point_m": round(dist, 1), "area_m2": round(b["poly"].area)} if dist > 15: out["warning"] = "point is not inside a building outline; the nearest building may be the wrong one" W = walls(b["poly"]) cands = road_candidates(b["poly"], roads) out["road_candidates"] = [{k: v for k, v in c.items() if k != "score"} for c in cands[:4]] result = None # 1. entrance nodes on the outline ents = [e for e in entrances if b["poly"].exterior.distance(e["pt"]) < 1.0] if ents: ents.sort(key=lambda e: 0 if e["kind"] == "main" else 1) e = ents[0] w = min(W, key=lambda w: w["seg"].distance(e["pt"])) result = {"method": f"OSM entrance node {e['id']} (entrance={e['kind']})", "facing_true_deg": round(w["normal"], 1), "confidence": "medium-high" if e["kind"] == "main" else "medium"} # 2. wall nearest best road, whose outward normal roughly points at that road if cands: best = cands[0] rline = next(r["line"] for r in roads if r["id"] == best["way_id"]) ok = [w for w in W if angdiff(w["normal"], best["road_perpendicular_deg"]) < 60 and w["len"] > 2] if ok: w = min(ok, key=lambda w: w["mid"].distance(rline) - 0.05 * w["len"]) wall = {"method": f"wall facing road way {best['way_id']} ({best.get('name') or best['highway']})", "facing_true_deg": round(w["normal"], 1), "road_perpendicular_deg": best["road_perpendicular_deg"], "confidence": "medium" if len(cands) == 1 or cands[1]["distance_m"] > best["distance_m"] + 8 else "low (more than one road frontage nearby: corner or through-lot)"} else: wall = {"method": f"road perpendicular, way {best['way_id']}", "facing_true_deg": best["road_perpendicular_deg"], "confidence": "low"} if result: result["cross_check_road_estimate_deg"] = wall["facing_true_deg"] if angdiff(result["facing_true_deg"], wall["facing_true_deg"]) > 45: result["note"] = "entrance and road frontage disagree; the house may face a yard/alley; verify on site" else: result = wall if not result: print(json.dumps({**out, "error": "no road within 60 m in OSM; cannot estimate"}, indent=2)) sys.exit(1) result["facing_sector"] = sector(result["facing_true_deg"]) d, dsrc = declination(a.lat, a.lon) if d is not None: result["magnetic_declination_deg"] = d result["facing_magnetic_deg"] = round((result["facing_true_deg"] - d) % 360, 1) result["declination_source"] = dsrc out["estimate"] = result out["verify"] = ("Estimate only. Confirm with a compass (phone compass away from metal/cars): stand inside the main door " "looking out. Compare the magnetic reading with facing_magnetic_deg. Satellite view is for visual " "confirmation only, not a measurement.") print(json.dumps(out, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()