#!/usr/bin/env python3 """ Route Em -- Hugging Face Space (Docker SDK). Shortest closed route covering every road on BOTH sides. Directed Chinese Postman, solved exactly by min-cost flow. Serves on 0.0.0.0:$PORT (HF sets PORT=7860). """ import os import traceback import requests from flask import Flask, jsonify, render_template_string, request # HF Space containers only allow writes to /tmp. Set this BEFORE osmnx imports, # or the app dies on boot with a permission error. os.environ.setdefault("HOME", "/tmp") os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl") os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache") from collections import defaultdict import networkx as nx import osmnx as ox M_PER_MI = 1609.344 # Guard rails so a fat-fingered giant box doesn't hang the machine. MAX_REQUIRED_PASSES = 6000 MAX_AREA_SQ_MI = 25.0 class RouteError(Exception): """Something the user can fix -- shown in the UI as a friendly message.""" # ---------------------------------------------------------------- area guards def bbox_area_sq_mi(b): import math mid = math.radians((b["north"] + b["south"]) / 2) h = (b["north"] - b["south"]) * 69.0 w = (b["east"] - b["west"]) * 69.0 * math.cos(mid) return abs(h * w) def polygon_area_sq_mi(geojson_polygon): """Rough but adequate: scale degrees to miles at the polygon's latitude.""" import math from shapely.geometry import shape poly = shape(geojson_polygon) mid = math.radians(poly.centroid.y) return abs(poly.area) * 69.0 * (69.0 * math.cos(mid)) # ---------------------------------------------------------------- load def graph_from_bbox(north, south, east, west, walking=False, include_service=False): net = "walk" if walking else "drive" try: G = ox.graph_from_bbox( (min(west, east), min(south, north), max(west, east), max(south, north)), network_type=net, ) except Exception as exc: raise RouteError( "No road network found in that box. Try a slightly bigger area, " f"or one that actually contains streets. ({exc})" ) return _clean(G, include_service) def graph_from_polygon(geojson_polygon, walking=False, include_service=False): from shapely.geometry import shape poly = shape(geojson_polygon) net = "walk" if walking else "drive" try: G = ox.graph_from_polygon(poly, network_type=net) except Exception as exc: raise RouteError(f"No road network found in that area. ({exc})") return _clean(G, include_service) def _clean(G, include_service): # Alleys, driveways and parking aisles are not delivery streets. if not include_service: drop = [ (u, v, k) for u, v, k, d in G.edges(keys=True, data=True) if str(d.get("highway", "")).startswith("service") or "driveway" in str(d.get("service", "")) or "parking_aisle" in str(d.get("service", "")) ] G.remove_edges_from(drop) G.remove_nodes_from(list(nx.isolates(G))) if G.number_of_edges() == 0: raise RouteError("That area has no deliverable streets in OpenStreetMap.") return G # ---------------------------------------------------------------- both sides def build_both_sides(G, walking=False): """One directed edge per required pass. Two-way street -> two passes.""" R = nx.MultiDiGraph() R.graph["crs"] = G.graph.get("crs", "epsg:4326") for n, d in G.nodes(data=True): R.add_node(n, **d) for u, v, k, d in G.edges(keys=True, data=True): L = float(d.get("length", 0.0)) name = d.get("name", "unnamed road") if isinstance(name, list): name = name[0] oneway = bool(d.get("oneway", False)) and not walking R.add_edge(u, v, length=L, name=name, required=True) if not oneway and not G.has_edge(v, u): # Two-way street that OSM only stored one way -- add the return curb. R.add_edge(v, u, length=L, name=name, required=True) R.remove_nodes_from(list(nx.isolates(R))) if R.number_of_edges() > MAX_REQUIRED_PASSES: raise RouteError( f"That area needs {R.number_of_edges():,} passes " f"(limit {MAX_REQUIRED_PASSES:,}). Draw a smaller box -- " "one neighborhood at a time." ) return R # ---------------------------------------------------------------- solve def solve_dcpp(R): """Returns (R_connected, EulerianGraph, repeat_edges).""" if not nx.is_strongly_connected(R): big = max(nx.strongly_connected_components(R), key=len) excluded = R.number_of_nodes() - len(big) R = R.subgraph(big).copy() R.graph["excluded_nodes"] = excluded else: R.graph["excluded_nodes"] = 0 if R.number_of_edges() == 0: raise RouteError("No connected road network in that area.") # excess > 0 -> more ways OUT than IN -> node needs extra INBOUND passes. # So every repeat path runs FROM a deficit node TO a surplus node. imbalance = {n: R.out_degree(n) - R.in_degree(n) for n in R.nodes} surplus = [n for n, b in imbalance.items() if b > 0] deficit = [n for n, b in imbalance.items() if b < 0] repeats = [] if surplus: sp = {t: nx.single_source_dijkstra_path_length(R, t, weight="length") for t in deficit} paths = {t: nx.single_source_dijkstra_path(R, t, weight="length") for t in deficit} F = nx.DiGraph() for n in surplus + deficit: F.add_node(n, demand=imbalance[n]) # +ve consumes flow, -ve supplies it for t in deficit: for s in surplus: if s in sp[t]: F.add_edge(t, s, weight=int(round(sp[t][s])), capacity=R.number_of_nodes()) try: _, flow = nx.network_simplex(F) except nx.NetworkXUnfeasible: raise RouteError( "Could not balance the network -- some streets are unreachable " "(likely a one-way trap at the edge of the box). Try a bigger box." ) for t, targets in flow.items(): for s, units in targets.items(): for _ in range(units): p = paths[t][s] repeats += list(zip(p[:-1], p[1:])) E = nx.MultiDiGraph(R) for u, v in repeats: d = min(R[u][v].values(), key=lambda x: x["length"]) E.add_edge(u, v, length=d["length"], name=d.get("name"), required=False) return R, E, repeats def build_route(E, start_node=None): if not nx.is_eulerian(E): raise RouteError("Internal: graph did not become Eulerian.") steps = [] for u, v, k in nx.eulerian_circuit(E, source=start_node, keys=True): d = E[u][v][k] steps.append( { "u": u, "v": v, "length": d["length"], "name": d.get("name") or "unnamed road", "deadhead": not d.get("required", True), } ) return steps # ---------------------------------------------------------------- pair helper def _pair(u, v): """Stable key for the physical street between two nodes (both directions share it).""" return "%s_%s" % (min(u, v), max(u, v)) # ---------------------------------------------------------------- drive-each-street-once def solve_cpp_once(G, walking=False): """Undirected Chinese Postman: cover every street ONCE, minimal driving. Returns (U_required_undirected, E_eulerian, repeat_edges).""" U = nx.MultiGraph() U.graph["crs"] = G.graph.get("crs", "epsg:4326") for n, d in G.nodes(data=True): U.add_node(n, **d) seen = set() for u, v, k, d in G.edges(keys=True, data=True): if (v, u, k) in seen: # reverse of an already-added two-way street continue seen.add((u, v, k)) name = d.get("name", "unnamed road") if isinstance(name, list): name = name[0] U.add_edge(u, v, length=float(d.get("length", 0.0)), name=name, required=True) U.remove_nodes_from(list(nx.isolates(U))) if U.number_of_edges() == 0: raise RouteError("That area has no deliverable streets in OpenStreetMap.") if not nx.is_connected(U): U = U.subgraph(max(nx.connected_components(U), key=len)).copy() if U.number_of_edges() > MAX_REQUIRED_PASSES: raise RouteError( "That area needs %d street passes (limit %d). Draw a smaller area." % (U.number_of_edges(), MAX_REQUIRED_PASSES)) # make it Eulerian: min-weight matching of odd-degree nodes, duplicate those paths import itertools odd = [n for n, deg in U.degree() if deg % 2 == 1] E = nx.MultiGraph(U) repeats = [] if odd: dist, path = {}, {} for o in odd: dl, pp = nx.single_source_dijkstra(U, o, weight="length") dist[o], path[o] = dl, pp K = nx.Graph() for a, b in itertools.combinations(odd, 2): if b in dist[a]: K.add_edge(a, b, weight=dist[a][b]) for a, b in nx.min_weight_matching(K): p = path[a][b] for x, y in zip(p[:-1], p[1:]): seg = min(U[x][y].values(), key=lambda e: e["length"]) E.add_edge(x, y, length=seg["length"], name=seg.get("name"), required=False) repeats.append((x, y)) return U, E, repeats # ---------------------------------------------------------------- outputs def compute_stats(R, steps, repeats): total_m = sum(s["length"] for s in steps) required_m = sum(s["length"] for s in steps if not s["deadhead"]) dead_m = sum(s["length"] for s in steps if s["deadhead"]) by_road = defaultdict(float) for s in steps: if not s["deadhead"]: by_road[s["name"]] += s["length"] return { "required_passes": sum(1 for s in steps if not s["deadhead"]), "streets": len(by_road), "min_mi": required_m / M_PER_MI, "deadhead_mi": dead_m / M_PER_MI, "total_mi": total_m / M_PER_MI, "efficiency_pct": required_m / total_m * 100 if total_m else 0, "overhead_pct": dead_m / required_m * 100 if required_m else 0, "repeats": len(repeats), "steps": len(steps), "drive_min": total_m / M_PER_MI / 12.0 * 60, "walk_min": total_m / M_PER_MI / 2.5 * 60, "excluded_nodes": R.graph.get("excluded_nodes", 0), "longest": sorted( [{"name": n, "mi": m / M_PER_MI} for n, m in by_road.items()], key=lambda x: -x["mi"], )[:15], } def route_geojson(E, steps): """Each move as a LineString, tagged with its order so the map can color-ramp it.""" feats = [] for i, s in enumerate(steps): feats.append( { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [E.nodes[s["u"]]["x"], E.nodes[s["u"]]["y"]], [E.nodes[s["v"]]["x"], E.nodes[s["v"]]["y"]], ], }, "properties": { "order": i + 1, "name": s["name"], "mi": round(s["length"] / M_PER_MI, 3), "deadhead": s["deadhead"], "pair": s.get("pair"), "needed": s.get("needed", 1), }, } ) return {"type": "FeatureCollection", "features": feats} def turn_by_turn(steps): """Collapse consecutive moves on the same street into single instructions.""" out, cur = [], None for s in steps: if cur and cur["name"] == s["name"] and cur["deadhead"] == s["deadhead"]: cur["mi"] += s["length"] / M_PER_MI else: if cur: out.append(cur) cur = {"name": s["name"], "mi": s["length"] / M_PER_MI, "deadhead": s["deadhead"]} if cur: out.append(cur) for i, o in enumerate(out): o["step"] = i + 1 o["mi"] = round(o["mi"], 2) return out # ---------------------------------------------------------------- one-shot def solve(G, walking=False, start_lat=None, start_lon=None, coverage="both"): """Graph in, everything out. Verifies full coverage before returning. coverage="once" : drive every street a single time (minimal driving). coverage="figure8" : drive the whole efficient loop ONE way, then the SAME loop in reverse -- a there-and-back so you cover the opposite side of every street on the way back. Predictable, no zig-zag. coverage="optimal" : shortest-distance route that still covers both directions of every two-way street (directed Chinese Postman). Least total miles, but interleaves the two sides so it doubles back a lot. """ if coverage == "optimal" or coverage == "both": # directed both-sides, minimum total distance (the original solver) R = build_both_sides(G, walking) R, E, repeats = solve_dcpp(R) else: # both "once" and "figure8" start from the efficient single-pass loop R, E, repeats = solve_cpp_once(G, walking) R.graph.setdefault("excluded_nodes", 0) start = None if start_lat is not None and start_lon is not None: try: start = ox.nearest_nodes(E, float(start_lon), float(start_lat)) except Exception: start = None steps = build_route(E, start) if coverage == "figure8": # append the same loop reversed: swap each move's direction, reverse order. back = [ {"u": s["v"], "v": s["u"], "length": s["length"], "name": s["name"], "deadhead": s["deadhead"]} for s in reversed(steps) ] steps = steps + back # required passes per street, counted straight from the final route needed = defaultdict(int) for s in steps: if not s["deadhead"]: needed[_pair(s["u"], s["v"])] += 1 for s in steps: pk = _pair(s["u"], s["v"]) s["pair"] = pk s["needed"] = 0 if s["deadhead"] else needed.get(pk, 1) # Hard guarantee: every required street is covered at least what the graph asks for. need_ct = defaultdict(int) for u, v in R.edges(): need_ct[_pair(u, v)] += 1 have = defaultdict(int) for s in steps: if not s["deadhead"]: have[s["pair"]] += 1 short = [p for p, c in need_ct.items() if have[p] < c] if short: raise RouteError("Internal: %d streets not fully covered." % len(short)) return { "coverage": coverage, "stats": compute_stats(R, steps, repeats), "geojson": route_geojson(E, steps), "directions": turn_by_turn(steps), } # Keep osmnx's HTTP cache in /tmp -- the only writable path on a Space. ox.settings.cache_folder = "/tmp/osmnx_cache" ox.settings.use_cache = True ox.settings.log_console = False ox.settings.requests_timeout = 180 ox.settings.overpass_rate_limit = True # ============================================================ the page PAGE = r''' Route Em

Route Em

The shortest driving loop that covers every street in your area
1  Drop your screenshot
Drag your map screenshot here Or click to choose a file.
It stays on your machine — it's your reference for matching the map.
2  Find the area, then outline it
Leg 1
—
—
3  Your route
Drop a screenshot, find the area,
outline it, and hit Solve route.
''' # ============================================================ web app app = Flask(__name__) UA = {"User-Agent": "route-em/1.0 (personal delivery route tool)"} @app.route("/") def index(): return render_template_string(PAGE) @app.route("/health") def health(): return jsonify({"status": "ok"}) @app.route("/geocode") def geocode(): q = (request.args.get("q") or "").strip() if not q: return jsonify({"error": "Type a ZIP code, address, or neighborhood."}), 400 try: r = requests.get( "https://nominatim.openstreetmap.org/search", params={"q": q, "format": "json", "limit": 1, "countrycodes": "us"}, headers=UA, timeout=20, ) r.raise_for_status() hits = r.json() except Exception as exc: return jsonify({"error": "Lookup failed: %s" % exc}), 502 if not hits: return jsonify({"error": "Couldn't find '%s'. Try adding the city and state." % q}), 404 h = hits[0] s, n, w, e = [float(x) for x in h["boundingbox"]] # nominatim order: S,N,W,E return jsonify({ "label": h.get("display_name", q), "lat": float(h["lat"]), "lon": float(h["lon"]), "bounds": {"south": s, "north": n, "west": w, "east": e}, }) @app.route("/solve", methods=["POST"]) def solve_route(): """Accepts either {"kind":"bbox","bounds":{...}} or {"kind":"polygon","polygon":{geojson}}.""" d = request.get_json(force=True) walking = bool(d.get("walking")) service = bool(d.get("include_service")) try: if d.get("kind") == "polygon" or "polygon" in d: poly = d["polygon"] area = polygon_area_sq_mi(poly) _check_area(area) G = graph_from_polygon(poly, walking=walking, include_service=service) else: b = d["bounds"] _check_area(bbox_area_sq_mi(b)) G = graph_from_bbox(b["north"], b["south"], b["east"], b["west"], walking=walking, include_service=service) return jsonify(solve(G, walking=walking, coverage=d.get("coverage", "both"), start_lat=d.get("start_lat"), start_lon=d.get("start_lon"))) except RouteError as exc: return jsonify({"error": str(exc)}), 400 except Exception as exc: traceback.print_exc() return jsonify({"error": "Unexpected error: %s" % exc}), 500 def _check_area(area): if area > MAX_AREA_SQ_MI: raise RouteError( "That area is about %.0f sq mi -- too big to solve (limit %.0f). " "Outline something smaller; a paper route is usually well under 1 sq mi." % (area, MAX_AREA_SQ_MI) ) if __name__ == "__main__": app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), debug=False)