Download explainer_map.py from Huiginn/feng-shui-master-tools: direct link, hf CLI and curl.
- Browser
- Download file 45 kB
-
https://huggingface.co/Huiginn/feng-shui-master-tools/resolve/main/explainer_map.py
- Command line
-
hf download hf://Huiginn/feng-shui-master-tools/explainer_map.py
-
curl -L -o explainer_map.py https://huggingface.co/Huiginn/feng-shui-master-tools/resolve/main/explainer_map.py
45 kB
| #!/usr/bin/env python3 | |
| """One explainer image (PNG) of everything computed for a property. | |
| Two steps: | |
| collect run the sibling scripts and merge their JSON (needs facing.py, road_pointing.py, | |
| landform_env.py, amenities.py, bat_trach.py in the same folder; missing ones are skipped) | |
| python3 explainer_map.py collect LAT LON [--facing DEG] [--birth YYYY-MM-DD --gender male|female] | |
| [--calendar vn] [--extra report.json] [--name "Label"] [--hazard-area "Hue City"] -o property.json | |
| render draw the PNG from that JSON (any part may be missing; its layer is simply omitted) | |
| python3 explainer_map.py render property.json -o map.png [--radius 300] [--hillshade] [--labels labels_xx.json] | |
| Labels are English by default; for another language pass a JSON with translated label keys | |
| (print the English keys with: python3 explainer_map.py labels). | |
| Input JSON schema (all keys optional except property.lat/lon): | |
| property: {lat, lon, name, address} | |
| facing: facing.py output (building.osm, estimate.facing_true_deg / facing_sector) | |
| road_pointing: road_pointing.py output (flags[], nearby_features[]) | |
| landform: landform_env.py output (wind, terrain, peaks_and_water, flow_proxy, form_school) | |
| amenities: amenities.py output (nearest{category: {name, osm, straight_m, route_m, minutes}}) | |
| bat_trach: bat_trach.py output (good_directions[], unfavourable_directions[]) | |
| hazards: {key: {level: very_low|low|medium|high|not_enough_data, label?, source?, accessed?}} | |
| scores: {feng_shui|natural_hazards|human_risks|planning|amenities|prices|cost_of_living: | |
| {score: 1-5 or null, confidence?, note?}} (null -> "not enough data") | |
| sources: [{name, url?, accessed?}] | |
| draft: true -> stamps "DRAFT / sample values" on the panel | |
| Base map: OpenStreetMap standard tiles (fallback: OSM Humanitarian tiles), softened; attribution printed on the image. | |
| Needs: pip install requests matplotlib pyproj shapely ; for non-Latin or accented labels, a font covering them (Noto Sans / DejaVu Sans). | |
| """ | |
| import argparse, io, json, math, os, subprocess, sys, time, hashlib, pathlib | |
| import requests | |
| 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"] | |
| 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)) | |
| HERE = pathlib.Path(__file__).resolve().parent | |
| CACHE = os.path.expanduser("~/.cache/property-check") | |
| os.makedirs(CACHE, exist_ok=True) | |
| DIRS8 = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] | |
| L = { | |
| "en": {"title": "Property explainer map", "facing": "Facing", "back": "back", "front": "front", "left": "left", "right": "right", | |
| "hv": "Black Tortoise (back)", "ct": "Vermilion Bird (front)", "tl": "Azure Dragon (left)", "bh": "White Tiger (right)", | |
| "higher": "higher", "lower": "lower", "level": "about level", "wind": "Wind (from)", "annual": "year", | |
| "seasons": {"DJF (Dec-Feb)": "Dec-Feb", "MAM (Mar-May)": "Mar-May", "JJA (Jun-Aug)": "Jun-Aug", "SON (Sep-Nov)": "Sep-Nov"}, | |
| "poi": "Shops/services within 300 m", "amen": "Nearest amenities", "min": "min", "haz": "Hazards (area level)", | |
| "scores": "7-area check", "src": "Sources", "nod": "not enough data", | |
| "lv": {"very_low": "very low", "low": "low", "medium": "medium", "high": "high", "not_enough_data": "no data"}, | |
| "areas": {"feng_shui": "Feng shui (belief)", "natural_hazards": "Natural hazards", "human_risks": "Human-made risks", | |
| "planning": "Rules & planning", "amenities": "Amenities", "prices": "Home prices", "cost_of_living": "Cost of living"}, | |
| "good": "favourable", "bad": "unfavourable", "bt": "Eight Mansions, belief", "rp": "road points here", "curve_out": "outer side of bend", | |
| "curve_in": "inner side of bend", "bridge": "bridge/flyover", "embrace": "embracing bend", "cut": "cutting bend", | |
| "front_road": "front road", "flow": "flow", "draft": "DRAFT - sample values", | |
| "cats": {"hospital": "Hospital", "clinic": "Clinic", "school": "School", "kindergarten": "Kindergarten", | |
| "market_supermarket": "Supermarket", "marketplace": "Market", "pharmacy": "Pharmacy", "park": "Park", | |
| "transit_stop": "Transit", "fuel": "Fuel"}, | |
| "feat": {"cemetery": "cemetery", "grave_yard": "graveyard", "hospital": "hospital", "substation": "power substation", | |
| "power_line": "power line", "place_of_worship": "worship", "funeral": "funeral home", "fuel": "fuel station"}, | |
| "haznames": {"FL": "River flood", "UF": "Urban flood", "CF": "Coastal flood", "EQ": "Earthquake", "LS": "Landslide", | |
| "TS": "Tsunami", "VA": "Volcano", "CY": "Cyclone", "DG": "Water scarcity", "EH": "Extreme heat", "WF": "Wildfire"}, | |
| "footer": "Feng shui = traditional belief, for reference. All values are estimates: verify on site and with the authorities.", | |
| "scale": "m", "terrain": "terrain", "lanes": "lanes", "sea": "sea", | |
| "conf": {"low": "conf. low", "medium": "conf. med", "high": "conf. high"}, | |
| "dirs": ["N", "NE", "E", "SE", "S", "SW", "W", "NW"], | |
| "legend": ["building", "facing", "road points at house", "water / flow", "front road", "prevailing wind", "sensitive neighbour"]} | |
| } | |
| LEVEL_COLOR = {"very_low": "#7fbf7b", "low": "#a6d96a", "medium": "#fdd36a", "high": "#f4a582", "not_enough_data": "#d9d9d9"} | |
| SCORE_COLOR = {1: "#f4a582", 2: "#fdd0a2", 3: "#fdd36a", 4: "#c7e9a0", 5: "#7fbf7b"} | |
| CAT_STYLE = {"hospital": ("H", "#d6604d"), "clinic": ("+", "#d6604d"), "school": ("S", "#4575b4"), "kindergarten": ("K", "#4575b4"), | |
| "market_supermarket": ("M", "#8c510a"), "marketplace": ("C", "#8c510a"), "pharmacy": ("P", "#1a9850"), | |
| "park": ("♣", "#1a9850"), "transit_stop": ("T", "#762a83"), "fuel": ("F", "#636363")} | |
| # ---------------- collect ---------------- | |
| def run_script(name, args): | |
| path = HERE / name | |
| if not path.exists(): | |
| print(f"skip {name}: not found next to explainer_map.py", file=sys.stderr); return None | |
| try: | |
| r = subprocess.run([sys.executable, str(path)] + [str(a) for a in args], capture_output=True, text=True, timeout=900) | |
| txt = r.stdout.strip() | |
| return json.loads(txt[txt.find("{"):]) if "{" in txt else None | |
| except Exception as e: | |
| print(f"warn {name}: {type(e).__name__}: {e}", file=sys.stderr); return None | |
| def thinkhazard(lat, lon, query=None): | |
| """Admin-level hazard levels from ThinkHazard (GFDRR). Hazard, not plot risk. | |
| query: admin-unit name to search (e.g. "Hue City"); otherwise names from reverse geocoding are tried.""" | |
| if query: | |
| try: | |
| hits = requests.get("https://thinkhazard.org/en/administrativedivision", params={"q": query}, timeout=30).json().get("data", []) | |
| except Exception: | |
| hits = [] | |
| if hits: | |
| return _th_report(hits[0]) | |
| try: | |
| r = requests.get("https://nominatim.openstreetmap.org/reverse", params={"lat": lat, "lon": lon, "format": "jsonv2", | |
| "zoom": 10, "accept-language": "en"}, headers={"User-Agent": UA}, timeout=20) | |
| a = r.json().get("address", {}) | |
| except Exception: | |
| return None | |
| names = [a.get(k) for k in ("city", "county", "city_district", "town", "state_district", "state", "province") if a.get(k)] | |
| country = (a.get("country") or "").lower().replace("viet nam", "vietnam") | |
| for q in names: | |
| q2 = q.replace("City", "").replace("Province", "").strip() | |
| try: | |
| time.sleep(1) | |
| hits = requests.get("https://thinkhazard.org/en/administrativedivision", params={"q": q2}, timeout=30).json().get("data", []) | |
| except Exception: | |
| continue | |
| hits = [h for h in hits if country and h.get("admin0", "").lower().replace("viet nam", "vietnam") in country] or [] | |
| if not hits: | |
| continue | |
| h = sorted(hits, key=lambda h: -len([k for k in ("admin1", "admin2") if h.get(k)]))[0] | |
| res = _th_report(h) | |
| if res: | |
| return res | |
| return None | |
| def _th_report(h): | |
| try: | |
| rep = requests.get(h["url"] + ".json", timeout=30).json() | |
| except Exception: | |
| return None | |
| lv = {"VLO": "very_low", "LOW": "low", "MED": "medium", "HIG": "high"} | |
| out = {} | |
| for item in rep: | |
| m = item["hazardtype"]["mnemonic"] | |
| out[m] = {"level": lv.get(item["hazardlevel"]["mnemonic"], "not_enough_data"), "source": "ThinkHazard", | |
| "accessed": time.strftime("%Y-%m-%d")} | |
| unit = " / ".join(h.get(k) for k in ("admin0", "admin1", "admin2") if h.get(k)) | |
| return {"levels": out, "unit": unit, "url": h["url"]} | |
| def collect(a): | |
| lat, lon = a.lat, a.lon | |
| data = {"property": {"lat": lat, "lon": lon, "name": a.name}, "sources": []} | |
| fac = run_script("facing.py", [lat, lon]) | |
| if fac and "estimate" in fac: | |
| data["facing"] = fac | |
| facing = a.facing if a.facing is not None else (fac or {}).get("estimate", {}).get("facing_true_deg") | |
| if a.facing is not None: | |
| data.setdefault("facing", {}).setdefault("estimate", {}) | |
| data["facing"]["estimate"].update(facing_true_deg=a.facing, method="given by user/compass") | |
| extra = ["--facing", facing] if facing is not None else [] | |
| data["road_pointing"] = run_script("road_pointing.py", [lat, lon] + extra) | |
| data["landform"] = run_script("landform_env.py", [lat, lon] + extra) | |
| data["amenities"] = run_script("amenities.py", [lat, lon, "--radius", 2000]) | |
| if a.birth and a.gender: | |
| data["bat_trach"] = run_script("bat_trach.py", ["--birth", a.birth, "--gender", a.gender] + (["--calendar", a.calendar] if a.calendar else [])) | |
| th = thinkhazard(lat, lon, a.hazard_area) | |
| if th: | |
| data["hazards"] = th["levels"] | |
| data["sources"].append({"name": f"ThinkHazard - {th['unit']} (admin-level hazard, not plot risk)", "url": th["url"], | |
| "accessed": time.strftime("%Y-%m-%d")}) | |
| for k, nm in (("facing", "OpenStreetMap via Overpass"), ("landform", "Open-Meteo ERA5 / Copernicus DEM; OSM"), | |
| ("amenities", "OSM + OSRM demo")): | |
| if data.get(k): | |
| data["sources"].append({"name": nm, "accessed": time.strftime("%Y-%m-%d")}) | |
| if a.extra: | |
| ext = json.load(open(a.extra)) | |
| for k, v in ext.items(): | |
| if isinstance(v, dict) and isinstance(data.get(k), dict): | |
| data[k].update(v) | |
| elif isinstance(v, list) and isinstance(data.get(k), list): | |
| data[k] += v | |
| else: | |
| data[k] = v | |
| data = {k: v for k, v in data.items() if v} | |
| json.dump(data, open(a.o, "w"), ensure_ascii=False, indent=1) | |
| print(json.dumps({"written": a.o, "parts": sorted(data.keys())})) | |
| # ---------------- render helpers ---------------- | |
| def merc(lon, lat): | |
| x = math.radians(lon) * 6378137.0 | |
| y = math.log(math.tan(math.pi / 4 + math.radians(lat) / 2)) * 6378137.0 | |
| return x, y | |
| def tile_xy(lon, lat, z): | |
| n = 2 ** z | |
| x = (lon + 180) / 360 * n | |
| y = (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n | |
| return x, y | |
| TILE_SOURCES = { | |
| "osm": ("https://tile.openstreetmap.org/{z}/{x}/{y}.png", "© OpenStreetMap contributors"), | |
| "hot": ("https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", "© OpenStreetMap contributors, tiles: Humanitarian OSM Team / OSM France"), | |
| "carto": ("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png", "© OpenStreetMap contributors © CARTO"), | |
| } | |
| TILE_ORDER = ["osm", "hot"] # CARTO basemaps now return an "API key required" watermark without a key | |
| def get_tile(z, x, y): | |
| """Light, cached use only (OSM tile usage policy: identifying User-Agent, no bulk downloads).""" | |
| for key in TILE_ORDER: | |
| tmpl, attr = TILE_SOURCES[key] | |
| url = tmpl.format(s="abc"[(x + y) % 3] if key == "hot" else "abcd"[(x + y) % 4], z=z, x=x, y=y) | |
| p = os.path.join(CACHE, "tile-" + hashlib.sha1(url.encode()).hexdigest() + ".png") | |
| if os.path.exists(p): | |
| return open(p, "rb").read(), attr | |
| try: | |
| r = requests.get(url, headers={"User-Agent": UA}, timeout=20) | |
| if r.status_code == 200 and r.content[:4] == b"\x89PNG": | |
| open(p, "wb").write(r.content) | |
| return r.content, attr | |
| except requests.RequestException: | |
| pass | |
| return None, None | |
| def basemap(ax, lat, lon, x0, x1, y0, y1, cx, cy): | |
| """Mosaic tiles covering the extent (mercator offsets relative to cx, cy).""" | |
| import matplotlib.image as mpimg | |
| span = max(x1 - x0, y1 - y0) | |
| z = max(3, min(19, int(round(math.log2(40075016 * 4 / span))))) # ~4 x 256-px tiles across | |
| def inv(mx, my): | |
| lo = math.degrees(mx / 6378137.0); la = math.degrees(2 * math.atan(math.exp(my / 6378137.0)) - math.pi / 2) | |
| return lo, la | |
| lo0, la0 = inv(cx + x0, cy + y0); lo1, la1 = inv(cx + x1, cy + y1) | |
| tx0, ty1 = tile_xy(lo0, la0, z); tx1, ty0 = tile_xy(lo1, la1, z) | |
| attr = None | |
| size = 40075016.686 / 2 ** z | |
| for tx in range(int(tx0), int(tx1) + 1): | |
| for ty in range(int(ty0), int(ty1) + 1): | |
| png, at = get_tile(z, tx, ty) | |
| if not png: | |
| continue | |
| attr = attr or at | |
| img = mpimg.imread(io.BytesIO(png), format="png") | |
| left = tx * size - 20037508.34 - cx; top = 20037508.34 - ty * size - cy | |
| ax.imshow(img, extent=(left, left + size, top - size, top), zorder=0, interpolation="lanczos") | |
| from matplotlib.patches import Rectangle | |
| ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="white", alpha=.5, zorder=0.5, ec="none")) # soften the base map | |
| return attr | |
| def fetch_geoms(ids, bbox): | |
| """ids: {'way': set, 'node': set, 'relation': set}. Returns {'way/1': {'lines': [[(lat,lon)...]], 'center': (lat,lon), 'tags': {}}}.""" | |
| q = "[out:json][timeout:90];" | |
| parts = [] | |
| for t in ("way", "relation"): | |
| if ids.get(t): | |
| parts.append(f"{t}(id:{','.join(map(str, sorted(ids[t])))});") | |
| s, w, n, e = bbox | |
| if parts: | |
| q += "(" + "".join(parts) + f");out tags geom({s:.6f},{w:.6f},{n:.6f},{e:.6f});" | |
| allp = [f"{t}(id:{','.join(map(str, sorted(v)))});" for t, v in ids.items() if v] | |
| if not allp: | |
| return {} | |
| q += "(" + "".join(allp) + ");out tags center;" | |
| try: | |
| data, _ = overpass(q) | |
| except RuntimeError as e: | |
| print(f"warn: geometry fetch failed ({e}); drawing by bearing/distance only", file=sys.stderr) | |
| return {} | |
| out = {} | |
| for el in data.get("elements", []): | |
| k = f"{el['type']}/{el['id']}"; d = out.setdefault(k, {"lines": [], "center": None, "tags": el.get("tags", {})}) | |
| if el["type"] == "node": | |
| d["center"] = (el["lat"], el["lon"]) | |
| if el.get("center"): | |
| d["center"] = (el["center"]["lat"], el["center"]["lon"]) | |
| if el.get("geometry"): | |
| d["lines"].append([(g["lat"], g["lon"]) for g in el["geometry"] if g]) | |
| for m in el.get("members", []) or []: | |
| if m.get("geometry"): | |
| d["lines"].append([(g["lat"], g["lon"]) for g in m["geometry"] if g]) | |
| return out | |
| def osm_ref(s): | |
| if not s: | |
| return None | |
| s = str(s).rstrip("/") | |
| parts = s.split("/") | |
| if len(parts) >= 2 and parts[-2] in ("way", "node", "relation") and parts[-1].isdigit(): | |
| return parts[-2], int(parts[-1]) | |
| return None | |
| def pick_font(text=""): | |
| """Prefer a static Noto Sans, then DejaVu Sans (bold, wide Latin/Greek/Cyrillic and symbols), then any Noto Sans that covers the label text.""" | |
| from matplotlib import font_manager as fm, ft2font | |
| files = fm.findSystemFonts() | |
| def rank(f): | |
| b = os.path.basename(f).lower() | |
| if b == "notosans-regular.ttf": return 0 | |
| if b == "dejavusans.ttf": return 1 | |
| if b.startswith("notosans-") and "italic" not in b: return 2 | |
| return 9 | |
| test = "".join(c for c in (text or "") if c.isalpha() and ord(c) > 127) or "éü" | |
| for f in sorted([f for f in files if rank(f) < 9], key=rank): | |
| try: | |
| ft = ft2font.FT2Font(f) | |
| if sum(1 for c in test if ft.get_char_index(ord(c))) >= 0.98 * len(test): | |
| for g in files: # register bold sibling if present | |
| if os.path.dirname(g) == os.path.dirname(f) and "bold" in os.path.basename(g).lower() and "oblique" not in g.lower() and "italic" not in g.lower(): | |
| fm.fontManager.addfont(g) | |
| fm.fontManager.addfont(f) | |
| return fm.FontProperties(fname=f).get_name(), f | |
| except Exception: | |
| continue | |
| return None, None | |
| # ---------------- render ---------------- | |
| def render(a): | |
| import matplotlib; matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from matplotlib.patches import Wedge, Polygon as MPoly, Circle, FancyArrowPatch, Rectangle | |
| import matplotlib.patheffects as pe | |
| D = json.load(open(a.input)); T = json.loads(json.dumps(L["en"])) | |
| if a.labels: # optional translation: JSON with any subset of the English keys (nested dicts merge) | |
| for k2, v2 in json.load(open(a.labels)).items(): | |
| if isinstance(v2, dict) and isinstance(T.get(k2), dict): | |
| T[k2].update(v2) | |
| else: | |
| T[k2] = v2 | |
| dirs = T["dirs"] | |
| fam, fpath = pick_font("".join(sorted(set(json.dumps(T, ensure_ascii=False) + json.dumps(D, ensure_ascii=False))))) | |
| if fam: | |
| plt.rcParams["font.family"] = fam | |
| else: | |
| print("warn: no installed font covers these labels; install Noto Sans (or the Noto font for that script) and re-run", file=sys.stderr) | |
| halo = [pe.withStroke(linewidth=3, foreground="white")] | |
| P = D["property"]; lat, lon = P["lat"], P["lon"] | |
| k = 1 / math.cos(math.radians(lat)); cx, cy = merc(lon, lat) | |
| R = a.radius * k | |
| xy = lambda la, lo: (merc(lo, la)[0] - cx, merc(lo, la)[1] - cy) | |
| off = lambda d, b: (d * k * math.sin(math.radians(b)), d * k * math.cos(math.radians(b))) | |
| fac = (D.get("facing") or {}).get("estimate", {}); F = fac.get("facing_true_deg") | |
| rp = D.get("road_pointing") or {}; lf = D.get("landform") or {}; am = (D.get("amenities") or {}).get("nearest") or {} | |
| pw = lf.get("peaks_and_water") or {}; flw = lf.get("flow_proxy") or {}; fs = lf.get("form_school") or {}; wnd = lf.get("wind") or {} | |
| fig = plt.figure(figsize=(10, 16), dpi=a.dpi) | |
| fig.patch.set_facecolor("white") | |
| W_IN, H_IN = 10, 16 | |
| mx0, my0, mw, mh = 0.02, 0.385, 0.96, 0.565 | |
| ax = fig.add_axes([mx0, my0, mw, mh]) | |
| aspect = (mw * W_IN) / (mh * H_IN) | |
| hx, hy = R * 1.12 * max(1, aspect), R * 1.12 * max(1, 1 / aspect) | |
| ax.set_xlim(-hx, hx); ax.set_ylim(-hy, hy); ax.set_aspect("equal"); ax.set_xticks([]); ax.set_yticks([]) | |
| # geometries by id | |
| ids = {"way": set(), "node": set(), "relation": set()} | |
| def want(ref): | |
| r = osm_ref(ref) | |
| if r: ids[r[0]].add(r[1]) | |
| want((D.get("facing") or {}).get("building", {}).get("osm")) | |
| for f in rp.get("flags", []) if isinstance(rp.get("flags"), list) else []: | |
| want(f.get("junction_node")); want(f.get("road")); want(f.get("osm")) | |
| for f in rp.get("nearby_features", []) or []: | |
| want(f.get("osm")) | |
| for w in pw.get("water", []) or []: | |
| want(w.get("osm")) | |
| for c in pw.get("coastline", []) or []: | |
| want(c.get("osm")) | |
| if flw.get("front_road"): want(flw["front_road"].get("osm")) | |
| for v in am.values(): want(v.get("osm")) | |
| dlat = hy / k / 111320 * 1.6; dlon = hx / k / (111320 * math.cos(math.radians(lat))) * 1.6 | |
| G = fetch_geoms(ids, (lat - dlat, lon - dlon, lat + dlat, lon + dlon)) | |
| g = lambda ref: G.get("/".join(map(str, osm_ref(ref)))) if osm_ref(ref) else None | |
| bgeo = g((D.get("facing") or {}).get("building", {}).get("osm")) | |
| bx, by = 0, 0 | |
| if bgeo and bgeo["lines"]: | |
| bpts = [xy(*p) for p in bgeo["lines"][0]] | |
| bx = sum(p[0] for p in bpts) / len(bpts); by = sum(p[1] for p in bpts) / len(bpts) | |
| attr = basemap(ax, lat, lon, -hx, hx, -hy, hy, cx, cy) | |
| if a.hillshade: | |
| try: | |
| import numpy as np | |
| from matplotlib.colors import LightSource | |
| n = 10; pts = [(lat + (j / (n - 1) - .5) * 2 * hy / k / 111320, lon + (i / (n - 1) - .5) * 2 * hx / k / (111320 * math.cos(math.radians(lat)))) | |
| for j in range(n) for i in range(n)] | |
| r = requests.get("https://api.open-meteo.com/v1/elevation", params={"latitude": ",".join(f"{p[0]:.5f}" for p in pts), | |
| "longitude": ",".join(f"{p[1]:.5f}" for p in pts)}, timeout=30).json()["elevation"] | |
| z = np.array(r, dtype=float).reshape(n, n)[::-1] | |
| if z.max() - z.min() > 3: | |
| hs = LightSource(azdeg=315, altdeg=45).hillshade(z, vert_exag=3, dx=2 * hx / n, dy=2 * hy / n) | |
| ax.imshow(hs, extent=(-hx, hx, -hy, hy), cmap="gray", alpha=0.25, zorder=1, interpolation="bicubic") | |
| except Exception as e: | |
| print(f"warn hillshade: {e}", file=sys.stderr) | |
| # water layers | |
| for w in pw.get("water", []) or []: | |
| geo = g(w.get("osm")) | |
| is_flow = "flow_toward_deg" in w | |
| if geo and geo["lines"]: | |
| for line in geo["lines"]: | |
| pts = [xy(*p) for p in line] | |
| if len(pts) < 2: continue | |
| xs, ys = zip(*pts) | |
| if is_flow: | |
| ax.plot(xs, ys, color="#2c7fb8", lw=3 if w["kind"] == "river" else 1.8, alpha=.85, zorder=3, solid_capstyle="round") | |
| step = max(1, len(pts) // 6) | |
| for i in range(step, len(pts) - 1, step): | |
| x0_, y0_ = pts[i - 1]; x1_, y1_ = pts[i] | |
| if abs(x1_) < hx and abs(y1_) < hy: | |
| ax.annotate("", xy=(x1_, y1_), xytext=(x0_ + (x1_ - x0_) * .2, y0_ + (y1_ - y0_) * .2), | |
| arrowprops=dict(arrowstyle="-|>", color="#08519c", lw=1.5, mutation_scale=16), zorder=4) | |
| elif line[0] == line[-1] and len(pts) > 3: | |
| ax.add_patch(MPoly(pts, closed=True, fc="#a6cee3", ec="#2c7fb8", lw=.8, alpha=.75, zorder=2)) | |
| else: | |
| ax.plot(xs, ys, color="#2c7fb8", lw=1.2, alpha=.7, zorder=2) | |
| if w.get("bend"): | |
| px, py = off(w["distance_m"], w["bearing_deg"]) | |
| if abs(px) < hx * .95 and abs(py) < hy * .95: | |
| ax.text(px, py, T["embrace"] if "INNER" in w["bend"] else T["cut"], color="#08519c", fontsize=9, ha="center", zorder=6, path_effects=halo) | |
| # front road | |
| fr = flw.get("front_road") | |
| if fr: | |
| geo = g(fr.get("osm")) | |
| if geo and geo["lines"]: | |
| for line in geo["lines"]: | |
| xs, ys = zip(*[xy(*p) for p in line]); ax.plot(xs, ys, color="#fe9929", lw=6, alpha=.55, zorder=3, solid_capstyle="round") | |
| allp = [xy(*p) for ln in geo["lines"] for p in ln] | |
| near = min(allp, key=lambda p: math.hypot(p[0] - bx, p[1] - by)) | |
| fb = math.radians(F if F is not None else 0) | |
| # label beside the road, away from the facing arrow: pick the road point ~0.4R from the building, sideways | |
| side = [p for p in allp if R * .3 < math.hypot(p[0] - bx, p[1] - by) < R * .6 | |
| and abs((math.degrees(math.atan2(p[0] - bx, p[1] - by)) - math.degrees(fb) + 180) % 360 - 180) > 50] | |
| mid = side[len(side) // 2] if side else (near[0] + R * .3 * math.sin(fb + 1.6), near[1] + R * .3 * math.cos(fb + 1.6)) | |
| txt = f"{T['front_road']}:\n{fr.get('name') or ''} ({fr['highway']}{', ' + str(fr['lanes']) + ' ' + T['lanes'] if fr.get('lanes') else ''})" | |
| ax.text(*mid, txt.replace(" ()", ""), fontsize=8.5, color="#993404", ha="center", va="bottom", zorder=7, path_effects=halo) | |
| # building + compass ring | |
| if bgeo and bgeo["lines"]: | |
| ax.add_patch(MPoly(bpts, closed=True, fc="#fdae61", ec="#d7301f", lw=2, alpha=.9, zorder=8)) | |
| else: | |
| ax.add_patch(Circle((0, 0), 6 * k, fc="#fdae61", ec="#d7301f", lw=2, zorder=8)) | |
| rr = R * .82 | |
| ax.add_patch(Circle((bx, by), rr, fill=False, ec="#525252", lw=1, ls=(0, (4, 3)), alpha=.7, zorder=5)) | |
| for i in range(16): | |
| b = i * 22.5; major = i % 2 == 0 | |
| x0_, y0_ = bx + rr * math.sin(math.radians(b)), by + rr * math.cos(math.radians(b)) | |
| x1_, y1_ = bx + rr * (1.04 if major else 1.02) * math.sin(math.radians(b)), by + rr * (1.04 if major else 1.02) * math.cos(math.radians(b)) | |
| ax.plot([x0_, x1_], [y0_, y1_], color="#525252", lw=1.2 if major else .7, zorder=5) | |
| if major: | |
| tx, ty = bx + rr * 1.10 * math.sin(math.radians(b)), by + rr * 1.10 * math.cos(math.radians(b)) | |
| ax.text(tx, ty, f"{dirs[i // 2]}\n{b:.0f}°", fontsize=8.5, ha="center", va="center", color="#252525", zorder=9, path_effects=halo, fontweight="bold") | |
| # bat trach sectors (belief) | |
| bt = D.get("bat_trach") | |
| if bt: | |
| for lst, col in ((bt.get("good_directions", []), "#1a9850"), (bt.get("unfavourable_directions", []), "#bf812d")): | |
| for d in lst: | |
| b = DIRS8.index(d["direction"]) * 45 | |
| ax.add_patch(Wedge((bx, by), rr * .62, 90 - b - 22, 90 - b + 22, width=rr * .1, fc=col, alpha=.28, ec="none", zorder=4)) | |
| tx, ty = bx + rr * .57 * math.sin(math.radians(b)), by + rr * .57 * math.cos(math.radians(b)) | |
| ax.text(tx, ty, d["name"], fontsize=7, ha="center", va="center", color=col, zorder=6, path_effects=halo) | |
| ax.text(bx, by - rr * .72, f"{T['bt']}: Kua {bt.get('kua')} · {T['good']} / {T['bad']}", fontsize=7.5, ha="center", | |
| color="#4d4d4d", zorder=6, path_effects=halo) | |
| # facing arrow | |
| if F is not None: | |
| ex, ey = bx + rr * .45 * math.sin(math.radians(F)), by + rr * .45 * math.cos(math.radians(F)) | |
| ax.add_patch(FancyArrowPatch((bx, by), (ex, ey), arrowstyle="simple,head_length=12,head_width=14,tail_width=5", | |
| color="#d7301f", zorder=10, alpha=.95)) | |
| ax.text(ex + (ex - bx) * .12, ey + (ey - by) * .12, f"{T['facing']} {F:.0f}° {dirs[int(((F % 360) + 22.5) // 45) % 8]}", | |
| fontsize=11, color="#b2182b", fontweight="bold", ha="center", va="center", zorder=11, path_effects=halo) | |
| # form school sides | |
| sides = fs.get("sides") or {} | |
| for key, lab, b in (("back", "hv", F + 180), ("front", "ct", F), ("left", "tl", F - 90), ("right", "bh", F + 90)): | |
| rel = ((sides.get(key) or {}).get("rel_elev_m") or {}) | |
| note = [] | |
| for dd in ("300m", "1000m"): | |
| v = rel.get(dd) | |
| if v is not None: | |
| note.append(f"{dd.replace('000m', ' km')}: {'+' if v >= 0 else ''}{v:.0f} m") | |
| txt = T[lab] + ("\n" + " · ".join(note) if note else "") | |
| tx, ty = bx + rr * .80 * math.sin(math.radians(b)), by + rr * .80 * math.cos(math.radians(b)) | |
| ax.text(tx, ty, txt, fontsize=8.5, ha="center", va="center", zorder=12, color="#3f007d", | |
| bbox=dict(boxstyle="round,pad=0.3", fc="#f2f0f7", ec="#807dba", alpha=.92)) | |
| # road flags (red rays) | |
| for f in rp.get("flags", []) if isinstance(rp.get("flags"), list) else []: | |
| if f["flag"] == "road_pointing": | |
| jn = g(f.get("junction_node")) | |
| if jn and jn["center"]: | |
| jx, jy = xy(*jn["center"]) | |
| else: | |
| jx, jy = bx + (f["distance_to_building_m"] + 10) * k * math.sin(math.radians(f["road_comes_from_bearing_deg"])), \ | |
| by + (f["distance_to_building_m"] + 10) * k * math.cos(math.radians(f["road_comes_from_bearing_deg"])) | |
| b = (f["road_comes_from_bearing_deg"] + 180) % 360; d = f["distance_to_building_m"] * k | |
| ax.annotate("", xy=(jx + d * math.sin(math.radians(b)), jy + d * math.cos(math.radians(b))), xytext=(jx, jy), | |
| arrowprops=dict(arrowstyle="-|>", color="#e31a1c", lw=2.2, ls="--", mutation_scale=18), zorder=9) | |
| lb = math.radians(f["road_comes_from_bearing_deg"]) | |
| ax.text(jx + R * .12 * math.sin(lb), jy + R * .12 * math.cos(lb), f"{T['rp']}\n{f.get('road_name') or f.get('highway')}", | |
| fontsize=8.5, color="#e31a1c", ha="center", va="center", zorder=12, path_effects=halo, fontweight="bold") | |
| elif f["flag"] == "road_curve": | |
| px, py = off(f["distance_m"] + 15, (F or 0) if False else 0) | |
| geo = g(f.get("road")) | |
| if geo and geo["lines"]: | |
| line = [xy(*p) for p in geo["lines"][0]] | |
| px, py = min(line, key=lambda p: math.hypot(p[0] - bx, p[1] - by)) | |
| ax.text(px, py, T["curve_out"] if "outer" in f["side"] else T["curve_in"], fontsize=8, color="#e31a1c" if "outer" in f["side"] else "#238b45", | |
| ha="center", zorder=9, path_effects=halo) | |
| elif f["flag"] == "bridge_or_flyover": | |
| px, py = off(f["distance_m"], f["bearing_from_building_deg"]) | |
| if abs(px) < hx and abs(py) < hy: | |
| ax.plot(px, py, marker="s", ms=9, color="#ae017e", zorder=9) | |
| ax.text(px, py, " " + T["bridge"], fontsize=8, color="#ae017e", va="center", zorder=9, path_effects=halo) | |
| # sensitive neighbours | |
| for f in rp.get("nearby_features", []) or []: | |
| geo = g(f.get("osm")) | |
| if geo and geo["center"]: | |
| px, py = xy(*geo["center"]) | |
| if abs(px) < hx and abs(py) < hy: | |
| ax.plot(px, py, marker="D", ms=8, mfc="#bdbdbd", mec="#525252", zorder=9) | |
| ax.text(px, py, f" {T['feat'].get(f['kind'], f['kind'])} {f['distance_m']} m", fontsize=7.5, color="#525252", va="center", zorder=9, path_effects=halo) | |
| # edge chips for off-map items (peaks, water, coast, amenities) | |
| placed = [] | |
| def edge(b, text, color): | |
| """Chip at the map edge in direction b; nudges along the edge to avoid overlapping earlier chips.""" | |
| for tries in range(12): | |
| t = min(hx / max(1e-9, abs(math.sin(math.radians(b)))), hy / max(1e-9, abs(math.cos(math.radians(b))))) * .9 | |
| ex, ey = t * math.sin(math.radians(b)), t * math.cos(math.radians(b)) | |
| if all(abs(ex - px) > hx * .55 or abs(ey - py) > hy * .07 for px, py in placed): | |
| break | |
| b += 9 if tries % 2 == 0 else -9 * (tries + 1) | |
| placed.append((ex, ey)) | |
| ax.annotate("", xy=(ex * 1.07, ey * 1.07), xytext=(ex * .97, ey * .97), arrowprops=dict(arrowstyle="-|>", color=color, lw=1.5), zorder=12) | |
| ax.text(ex * .93, ey * .93, text, fontsize=8, color=color, ha="center", va="center", zorder=12, | |
| bbox=dict(boxstyle="round,pad=0.2", fc="white", ec=color, alpha=.9)) | |
| shown = 0 | |
| for p in (pw.get("peaks_ridges") or [])[:3]: | |
| if p["distance_m"] * k > R: | |
| edge(p["bearing_deg"], f"▲ {p.get('name') or ''} {p.get('ele_m') or ''}{' m' if p.get('ele_m') else ''} · {p['distance_m'] / 1000:.1f} km".replace(" ", " "), "#6a3d9a") | |
| offw = [w for w in (pw.get("water") or []) if w.get("name") and w["distance_m"] * k > R] | |
| offw.sort(key=lambda w: (0 if w["kind"] in ("river", "canal") or "flow_toward_deg" in w else 1, w["distance_m"])) | |
| for w in offw[:3]: | |
| edge(w["bearing_deg"], f"≈ {w['name']} {w['distance_m']} m", "#2c7fb8") | |
| for c in pw.get("coastline") or []: | |
| if c["distance_m"] * k > R: | |
| edge(c["bearing_deg"], f"≈ {T['sea']} {c['distance_m']} m", "#2c7fb8") | |
| # wind arrow (annual dominant + strongest) | |
| if wnd.get("annual"): | |
| an = wnd["annual"] | |
| for key, ls in (("dominant_from", "-"), ("strong_wind_from", ":")): | |
| b = DIRS8.index(an[key]) * 45 | |
| sx, sy = bx + R * 1.0 * math.sin(math.radians(b)), by + R * 1.0 * math.cos(math.radians(b)) | |
| ex, ey = bx + R * .9 * math.sin(math.radians(b)) * .55, by + R * .9 * math.cos(math.radians(b)) * .55 | |
| ax.annotate("", xy=(ex, ey), xytext=(sx, sy), arrowprops=dict(arrowstyle="-|>", color="#41b6c4", lw=3 if ls == "-" else 2, | |
| ls=ls, mutation_scale=20, alpha=.8), zorder=7) | |
| b = DIRS8.index(an["dominant_from"]) * 45 | |
| ax.text(bx + R * 1.0 * math.sin(math.radians(b)), by + R * 1.0 * math.cos(math.radians(b)), | |
| f"{T['wind']} {dirs[DIRS8.index(an['dominant_from'])]} {an['dominant_pct']:.0f}%", fontsize=8.5, color="#0c7c8c", ha="center", zorder=12, path_effects=halo) | |
| # amenities | |
| for cat, v in am.items(): | |
| sym, col = CAT_STYLE.get(cat, ("•", "#333333")) | |
| geo = g(v.get("osm")) | |
| if geo and geo["center"]: | |
| px, py = xy(*geo["center"]) | |
| if abs(px) < hx * .97 and abs(py) < hy * .97: | |
| ax.add_patch(Circle((px, py), R * .035, fc=col, ec="white", lw=1.5, zorder=13)) | |
| ax.text(px, py, sym, color="white", fontsize=8, ha="center", va="center", fontweight="bold", zorder=14) | |
| from matplotlib.lines import Line2D | |
| LG = T["legend"] | |
| handles = [Line2D([], [], marker="s", ls="", mfc="#fdae61", mec="#d7301f", ms=9), Line2D([], [], color="#d7301f", lw=3), | |
| Line2D([], [], color="#e31a1c", lw=2, ls="--"), Line2D([], [], color="#2c7fb8", lw=3), Line2D([], [], color="#fe9929", lw=5, alpha=.6), | |
| Line2D([], [], color="#41b6c4", lw=3), Line2D([], [], marker="D", ls="", mfc="#bdbdbd", mec="#525252", ms=7)] | |
| lmd = D.get("landform") or {}; rpd = D.get("road_pointing") or {} | |
| show = [bool((D.get("facing") or {}).get("building")), True, bool(rpd.get("flags")), bool(lmd.get("peaks_and_water")), | |
| bool((lmd.get("flow_proxy") or {}).get("front_road")), bool(lmd.get("wind")), bool(rpd.get("nearby_features"))] | |
| keep = [(h, l) for h, l, sh in zip(handles, LG, show) if sh] | |
| ax.legend([h for h, _ in keep], [l for _, l in keep], loc="upper left", fontsize=7.5, framealpha=.9).set_zorder(20) | |
| # north arrow, scale bar, attribution | |
| ax.annotate("N", xy=(hx * .9, hy * .93), xytext=(hx * .9, hy * .78), ha="center", va="center", fontsize=13, fontweight="bold", | |
| arrowprops=dict(arrowstyle="-|>", color="black", lw=2, mutation_scale=22), zorder=15, path_effects=halo) | |
| nice = [10, 20, 50, 100, 200, 500, 1000, 2000] | |
| sb = max(n for n in nice if n * k <= hx * .5) | |
| x0_, y0_ = -hx * .92, -hy * .92 | |
| ax.add_patch(Rectangle((x0_, y0_), sb * k, hy * .012, fc="black", zorder=15)) | |
| ax.add_patch(Rectangle((x0_, y0_), sb * k / 2, hy * .012, fc="white", ec="black", zorder=15)) | |
| ax.text(x0_ + sb * k / 2, y0_ + hy * .03, f"{sb} m", ha="center", fontsize=9, zorder=15, path_effects=halo) | |
| ax.text(hx * .99, -hy * .99, (attr or "© OpenStreetMap contributors") + " · data © OpenStreetMap (ODbL)" + (", Open-Meteo" if lmd else ""), | |
| fontsize=6.5, ha="right", va="bottom", color="#404040", zorder=15, path_effects=halo) | |
| # title | |
| title = T["title"] + (f" · {P.get('name')}" if P.get("name") else "") | |
| fig.text(0.02, 0.985, title, fontsize=16, fontweight="bold", va="top") | |
| fig.text(0.02, 0.962, f"{lat:.5f}, {lon:.5f}" + (f" · {T['facing']} {F:.0f}° (true)" if F is not None else "") + | |
| (f" · {fac.get('method', '')[:60]}" if fac.get("method") else ""), fontsize=8.5, va="top", color="#525252") | |
| # ---- panels ---- | |
| # wind rose | |
| if wnd.get("annual"): | |
| axw = fig.add_axes([0.04, 0.205, 0.26, 0.15], projection="polar") | |
| axw.set_theta_zero_location("N"); axw.set_theta_direction(-1) | |
| ang = [math.radians(i * 45) for i in range(8)] | |
| axw.bar(ang, [wnd["annual"]["freq_pct"][d] for d in DIRS8], width=math.radians(38), color="#41b6c4", alpha=.75) | |
| axw.set_xticks(ang); axw.set_xticklabels(dirs, fontsize=8); axw.tick_params(axis="y", labelsize=6) | |
| axw.set_title(f"{T['wind']} · {wnd.get('period', '')[:4]}-{wnd.get('period', '')[-10:-6]}", fontsize=9, pad=12) | |
| seas = wnd.get("seasons") or {} | |
| lines = [f"{T['seasons'].get(s, s)}: {dirs[DIRS8.index(v['dominant_from'])]} {v['dominant_pct']:.0f}%" for s, v in seas.items()] | |
| fig.text(0.04, 0.186, " ".join(lines[:2]) + "\n" + " ".join(lines[2:]), fontsize=7.5, va="top", color="#0c7c8c") | |
| # POI by direction | |
| pois = flw.get("poi_within_300m_by_direction") | |
| if pois: | |
| axp = fig.add_axes([0.37, 0.19, 0.20, 0.13], projection="polar") | |
| axp.set_theta_zero_location("N"); axp.set_theta_direction(-1) | |
| ang = [math.radians(i * 45) for i in range(8)] | |
| axp.bar(ang, [pois.get(d, 0) for d in DIRS8], width=math.radians(38), color="#fe9929", alpha=.75) | |
| axp.set_xticks(ang); axp.set_xticklabels(dirs, fontsize=7); axp.tick_params(axis="y", labelsize=6) | |
| axp.set_title(T["poi"] + f" ({flw.get('poi_total', 0)})", fontsize=8.5, pad=10) | |
| # scores | |
| axs = fig.add_axes([0.60, 0.185, 0.38, 0.19]); axs.axis("off") | |
| axs.text(0, 1, T["scores"], fontsize=11, fontweight="bold", va="top", transform=axs.transAxes) | |
| sc = D.get("scores") or {} | |
| for i, key in enumerate(["feng_shui", "natural_hazards", "human_risks", "planning", "amenities", "prices", "cost_of_living"]): | |
| y = .86 - i * .12 | |
| v = sc.get(key) or {}; s = v.get("score") | |
| axs.text(0, y, T["areas"][key], fontsize=9, va="center", transform=axs.transAxes) | |
| col = SCORE_COLOR.get(s, "#d9d9d9") | |
| axs.add_patch(Rectangle((.66, y - .045), .32, .09, fc=col, ec="#969696", transform=axs.transAxes)) | |
| lab = f"{s}/5" if s else T["nod"] | |
| if s and v.get("confidence"): lab += f" · {T['conf'].get(v['confidence'], v['confidence'])}" | |
| axs.text(.82, y, lab, fontsize=8.5 if s else 7.5, ha="center", va="center", transform=axs.transAxes) | |
| if D.get("draft"): | |
| axs.text(.5, .4, T["draft"], fontsize=14, color="#bdbdbd", rotation=18, ha="center", va="center", transform=axs.transAxes, alpha=.8) | |
| # hazards | |
| hz = D.get("hazards") or {} | |
| axh = fig.add_axes([0.02, 0.071, 0.47, 0.09]); axh.axis("off") | |
| if hz: | |
| axh.text(0, 1, T["haz"], fontsize=11, fontweight="bold", va="top", transform=axh.transAxes) | |
| for i, (key, v) in enumerate(list(hz.items())[:12]): | |
| col_, row = i % 3, i // 3 | |
| x, y = col_ * .335, .70 - row * .225 | |
| lv = v.get("level", "not_enough_data") | |
| axh.add_patch(Rectangle((x, y - .085), .32, .17, fc=LEVEL_COLOR.get(lv, "#d9d9d9"), ec="white", transform=axh.transAxes, | |
| hatch="//" if lv == "not_enough_data" else None)) | |
| name = v.get("label") or T["haznames"].get(key, key) | |
| axh.text(x + .01, y, f"{name}: {T['lv'].get(lv, lv)}", fontsize=7.5, va="center", transform=axh.transAxes) | |
| # amenities list | |
| axa = fig.add_axes([0.51, 0.068, 0.47, 0.10]); axa.axis("off") | |
| if am: | |
| axa.text(0, 1, T["amen"], fontsize=11, fontweight="bold", va="top", transform=axa.transAxes) | |
| items = sorted(am.items(), key=lambda kv: kv[1].get("straight_m", 1e9))[:8] | |
| for i, (cat, v) in enumerate(items): | |
| sym, col = CAT_STYLE.get(cat, ("•", "#333333")); col_, row = i % 2, i // 2 | |
| x, y = col_ * .5, .76 - row * .2 | |
| axa.add_patch(Circle((x + .015, y), .022, fc=col, transform=axa.transAxes, clip_on=False)) | |
| axa.text(x + .015, y, sym, color="white", fontsize=6.5, ha="center", va="center", transform=axa.transAxes, fontweight="bold") | |
| dist = v.get("route_m") or v.get("straight_m"); mins = v.get("minutes") | |
| nm = (v.get("name") or "")[:16] | |
| axa.text(x + .045, y, f"{T['cats'].get(cat, cat)}: {nm} {dist} m" + (f" · {mins:.0f} {T['min']}" if mins else ""), | |
| fontsize=6.8, va="center", transform=axa.transAxes) | |
| # practical facts strip (from landform) + sources + footer | |
| srcs = D.get("sources") or [] | |
| stxt = T["src"] + ": " + "; ".join(f"{s['name']}" + (f" ({s['accessed']})" if s.get("accessed") else "") for s in srcs) | |
| if srcs: | |
| fig.text(0.02, 0.058, stxt[:400], fontsize=6.5, va="top", wrap=True, color="#404040") | |
| fig.add_artist(Rectangle((0, 0), 1, 0.03, transform=fig.transFigure, fc="#f0f0f0", ec="none")) | |
| fig.text(0.5, 0.015, T["footer"], fontsize=8.5, ha="center", va="center", color="#252525", wrap=True) | |
| fig.savefig(a.o, dpi=a.dpi) | |
| print(json.dumps({"png": a.o, "font": fpath, "tiles": attr, "geometries_fetched": len(G), | |
| "layers": [k for k in ("facing", "road_pointing", "landform", "amenities", "bat_trach", "hazards", "scores") if D.get(k)]})) | |
| def main(): | |
| ap = argparse.ArgumentParser(); sub = ap.add_subparsers(dest="cmd", required=True) | |
| c = sub.add_parser("collect"); c.add_argument("lat", type=float); c.add_argument("lon", type=float) | |
| c.add_argument("--facing", type=float); c.add_argument("--birth"); c.add_argument("--gender", choices=["male", "female"]) | |
| c.add_argument("--calendar", choices=["cn", "vn"]); c.add_argument("--extra"); c.add_argument("--name") | |
| c.add_argument("--hazard-area", help="ThinkHazard admin-unit name if the automatic match is wrong, e.g. 'Hue City'") | |
| c.add_argument("-o", required=True) | |
| r = sub.add_parser("render"); r.add_argument("input") | |
| r.add_argument("--labels", help="optional JSON of translated labels (any subset of the English keys); default English") | |
| r.add_argument("-o", required=True); r.add_argument("--radius", type=int, default=300); r.add_argument("--hillshade", action="store_true") | |
| r.add_argument("--dpi", type=int, default=150) | |
| sub.add_parser("labels") | |
| a = ap.parse_args() | |
| if a.cmd == "labels": | |
| print(json.dumps(L["en"], ensure_ascii=False, indent=1)) | |
| else: | |
| collect(a) if a.cmd == "collect" else render(a) | |
| if __name__ == "__main__": | |
| main() | |