Upload 4 files
Browse files- Dockerfile +25 -0
- README.md +61 -4
- REQUIR~1.TXT +7 -0
- app.py +676 -0
Dockerfile
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
# geopandas/pyproj/rtree ship manylinux wheels, but osmnx still wants a C toolchain
|
| 4 |
+
# available for a couple of transitive builds on slim.
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 6 |
+
build-essential \
|
| 7 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
COPY app.py .
|
| 15 |
+
|
| 16 |
+
# HF Spaces run as a non-root user; only /tmp is writable.
|
| 17 |
+
ENV HOME=/tmp \
|
| 18 |
+
MPLCONFIGDIR=/tmp/mpl \
|
| 19 |
+
XDG_CACHE_HOME=/tmp/cache \
|
| 20 |
+
PORT=7860 \
|
| 21 |
+
PYTHONUNBUFFERED=1
|
| 22 |
+
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "4", "--timeout", "300", "app:app"]
|
README.md
CHANGED
|
@@ -1,10 +1,67 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Paper Route Planner
|
| 3 |
+
emoji: 📰
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
+
license: mit
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Paper Route Planner
|
| 13 |
+
|
| 14 |
+
Finds the **shortest closed route that covers every road, both sides** — the route you'd
|
| 15 |
+
drive or walk to put a paper on every doorstep.
|
| 16 |
+
|
| 17 |
+
## How to use it
|
| 18 |
+
|
| 19 |
+
1. **Drop your map screenshot** in the left panel. It stays in your browser — it's never
|
| 20 |
+
uploaded. It's a visual reference for matching the map.
|
| 21 |
+
2. **Type a ZIP code or address** and hit Find. The map jumps there.
|
| 22 |
+
3. **Click "Draw box"** and drag a rectangle around the neighborhood.
|
| 23 |
+
4. *Optional:* shift-click to set where you start and end.
|
| 24 |
+
5. **Solve route.**
|
| 25 |
+
|
| 26 |
+
You get the route drawn in travel order (blue → yellow), deadhead segments dashed red,
|
| 27 |
+
plus total distance, deadhead miles, efficiency, and turn-by-turn directions.
|
| 28 |
+
|
| 29 |
+
## Why it's optimal, not a guess
|
| 30 |
+
|
| 31 |
+
This is the **Directed Chinese Postman Problem**:
|
| 32 |
+
|
| 33 |
+
- Two-way street → **two required passes** (one per curb).
|
| 34 |
+
- One-way street → **one required pass**.
|
| 35 |
+
- Find the shortest closed walk covering every required pass.
|
| 36 |
+
|
| 37 |
+
Solved exactly:
|
| 38 |
+
|
| 39 |
+
1. Compute each intersection's imbalance (`out_degree − in_degree`).
|
| 40 |
+
2. **Min-cost flow** from deficit nodes to surplus nodes, cost = shortest-path distance.
|
| 41 |
+
This yields the cheapest set of passes to *repeat* ("deadhead").
|
| 42 |
+
3. Add those repeats — the graph is now Eulerian — and extract the Eulerian circuit.
|
| 43 |
+
|
| 44 |
+
That circuit is provably the shortest possible. The solver asserts full coverage before
|
| 45 |
+
returning anything.
|
| 46 |
+
|
| 47 |
+
## Notes
|
| 48 |
+
|
| 49 |
+
- Roads come from **OpenStreetMap** via Overpass. Coverage is only as good as OSM's data
|
| 50 |
+
for your area — check for missing new streets.
|
| 51 |
+
- Areas are capped at **25 sq mi / 6,000 passes**. A real paper route is well under 1 sq mi.
|
| 52 |
+
- Deadhead mileage is *unavoidable*, not a flaw — cul-de-sacs and dead ends force
|
| 53 |
+
backtracking by definition.
|
| 54 |
+
- Time estimates use crude constants (12 mph driving, 2.5 mph walking, stops included).
|
| 55 |
+
- This Space calls the public Overpass and Nominatim APIs. On a shared IP they occasionally
|
| 56 |
+
rate-limit; if a solve fails, wait a moment and retry.
|
| 57 |
+
|
| 58 |
+
## Deploy your own
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
git clone https://huggingface.co/spaces/<you>/paper-route-planner
|
| 62 |
+
cd paper-route-planner
|
| 63 |
+
# copy app.py, Dockerfile, requirements.txt, README.md in
|
| 64 |
+
git add . && git commit -m "Paper route planner" && git push
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
The Space builds itself from the Dockerfile. First build takes a few minutes (geopandas).
|
REQUIR~1.TXT
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask==3.0.3
|
| 2 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Paper Route Planner -- Hugging Face Space (Docker SDK).
|
| 4 |
+
|
| 5 |
+
Shortest closed route covering every road on BOTH sides -- the route you would
|
| 6 |
+
drive or walk to put a paper on every doorstep. Directed Chinese Postman Problem
|
| 7 |
+
solved exactly via min-cost flow (provably optimal, not a heuristic).
|
| 8 |
+
|
| 9 |
+
Runs on 0.0.0.0:$PORT (HF sets PORT=7860).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import traceback
|
| 14 |
+
|
| 15 |
+
import requests
|
| 16 |
+
from flask import Flask, jsonify, render_template_string, request
|
| 17 |
+
|
| 18 |
+
# HF Space containers only allow writes to /tmp -- point every cache there BEFORE
|
| 19 |
+
# osmnx/matplotlib get imported, or the app dies on boot with a permission error.
|
| 20 |
+
os.environ.setdefault("HOME", "/tmp")
|
| 21 |
+
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
|
| 22 |
+
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache")
|
| 23 |
+
|
| 24 |
+
from collections import defaultdict
|
| 25 |
+
|
| 26 |
+
import networkx as nx
|
| 27 |
+
import osmnx as ox
|
| 28 |
+
|
| 29 |
+
M_PER_MI = 1609.344
|
| 30 |
+
|
| 31 |
+
# Guard rails so a fat-fingered giant box doesn't hang the machine.
|
| 32 |
+
MAX_REQUIRED_PASSES = 6000
|
| 33 |
+
MAX_AREA_SQ_MI = 25.0
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RouteError(Exception):
|
| 37 |
+
"""Something the user can fix -- shown in the UI as a friendly message."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ---------------------------------------------------------------- load
|
| 41 |
+
def graph_from_bbox(north, south, east, west, walking=False, include_service=False):
|
| 42 |
+
net = "walk" if walking else "drive"
|
| 43 |
+
try:
|
| 44 |
+
G = ox.graph_from_bbox(
|
| 45 |
+
(min(west, east), min(south, north), max(west, east), max(south, north)),
|
| 46 |
+
network_type=net,
|
| 47 |
+
)
|
| 48 |
+
except Exception as exc:
|
| 49 |
+
raise RouteError(
|
| 50 |
+
"No road network found in that box. Try a slightly bigger area, "
|
| 51 |
+
f"or one that actually contains streets. ({exc})"
|
| 52 |
+
)
|
| 53 |
+
return _clean(G, include_service)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def graph_from_polygon(geojson_polygon, walking=False, include_service=False):
|
| 57 |
+
from shapely.geometry import shape
|
| 58 |
+
|
| 59 |
+
poly = shape(geojson_polygon)
|
| 60 |
+
net = "walk" if walking else "drive"
|
| 61 |
+
try:
|
| 62 |
+
G = ox.graph_from_polygon(poly, network_type=net)
|
| 63 |
+
except Exception as exc:
|
| 64 |
+
raise RouteError(f"No road network found in that area. ({exc})")
|
| 65 |
+
return _clean(G, include_service)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _clean(G, include_service):
|
| 69 |
+
# Alleys, driveways and parking aisles are not delivery streets.
|
| 70 |
+
if not include_service:
|
| 71 |
+
drop = [
|
| 72 |
+
(u, v, k)
|
| 73 |
+
for u, v, k, d in G.edges(keys=True, data=True)
|
| 74 |
+
if str(d.get("highway", "")).startswith("service")
|
| 75 |
+
or "driveway" in str(d.get("service", ""))
|
| 76 |
+
or "parking_aisle" in str(d.get("service", ""))
|
| 77 |
+
]
|
| 78 |
+
G.remove_edges_from(drop)
|
| 79 |
+
G.remove_nodes_from(list(nx.isolates(G)))
|
| 80 |
+
if G.number_of_edges() == 0:
|
| 81 |
+
raise RouteError("That area has no deliverable streets in OpenStreetMap.")
|
| 82 |
+
return G
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ---------------------------------------------------------------- both sides
|
| 86 |
+
def build_both_sides(G, walking=False):
|
| 87 |
+
"""One directed edge per required pass. Two-way street -> two passes."""
|
| 88 |
+
R = nx.MultiDiGraph()
|
| 89 |
+
R.graph["crs"] = G.graph.get("crs", "epsg:4326")
|
| 90 |
+
for n, d in G.nodes(data=True):
|
| 91 |
+
R.add_node(n, **d)
|
| 92 |
+
|
| 93 |
+
for u, v, k, d in G.edges(keys=True, data=True):
|
| 94 |
+
L = float(d.get("length", 0.0))
|
| 95 |
+
name = d.get("name", "unnamed road")
|
| 96 |
+
if isinstance(name, list):
|
| 97 |
+
name = name[0]
|
| 98 |
+
oneway = bool(d.get("oneway", False)) and not walking
|
| 99 |
+
|
| 100 |
+
R.add_edge(u, v, length=L, name=name, required=True)
|
| 101 |
+
if not oneway and not G.has_edge(v, u):
|
| 102 |
+
# Two-way street that OSM only stored one way -- add the return curb.
|
| 103 |
+
R.add_edge(v, u, length=L, name=name, required=True)
|
| 104 |
+
|
| 105 |
+
R.remove_nodes_from(list(nx.isolates(R)))
|
| 106 |
+
if R.number_of_edges() > MAX_REQUIRED_PASSES:
|
| 107 |
+
raise RouteError(
|
| 108 |
+
f"That area needs {R.number_of_edges():,} passes "
|
| 109 |
+
f"(limit {MAX_REQUIRED_PASSES:,}). Draw a smaller box -- "
|
| 110 |
+
"one neighborhood at a time."
|
| 111 |
+
)
|
| 112 |
+
return R
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------- solve
|
| 116 |
+
def solve_dcpp(R):
|
| 117 |
+
"""Returns (R_connected, EulerianGraph, repeat_edges)."""
|
| 118 |
+
if not nx.is_strongly_connected(R):
|
| 119 |
+
big = max(nx.strongly_connected_components(R), key=len)
|
| 120 |
+
excluded = R.number_of_nodes() - len(big)
|
| 121 |
+
R = R.subgraph(big).copy()
|
| 122 |
+
R.graph["excluded_nodes"] = excluded
|
| 123 |
+
else:
|
| 124 |
+
R.graph["excluded_nodes"] = 0
|
| 125 |
+
|
| 126 |
+
if R.number_of_edges() == 0:
|
| 127 |
+
raise RouteError("No connected road network in that area.")
|
| 128 |
+
|
| 129 |
+
# excess > 0 -> more ways OUT than IN -> node needs extra INBOUND passes.
|
| 130 |
+
# So every repeat path runs FROM a deficit node TO a surplus node.
|
| 131 |
+
imbalance = {n: R.out_degree(n) - R.in_degree(n) for n in R.nodes}
|
| 132 |
+
surplus = [n for n, b in imbalance.items() if b > 0]
|
| 133 |
+
deficit = [n for n, b in imbalance.items() if b < 0]
|
| 134 |
+
|
| 135 |
+
repeats = []
|
| 136 |
+
if surplus:
|
| 137 |
+
sp = {t: nx.single_source_dijkstra_path_length(R, t, weight="length") for t in deficit}
|
| 138 |
+
paths = {t: nx.single_source_dijkstra_path(R, t, weight="length") for t in deficit}
|
| 139 |
+
|
| 140 |
+
F = nx.DiGraph()
|
| 141 |
+
for n in surplus + deficit:
|
| 142 |
+
F.add_node(n, demand=imbalance[n]) # +ve consumes flow, -ve supplies it
|
| 143 |
+
for t in deficit:
|
| 144 |
+
for s in surplus:
|
| 145 |
+
if s in sp[t]:
|
| 146 |
+
F.add_edge(t, s, weight=int(round(sp[t][s])), capacity=R.number_of_nodes())
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
_, flow = nx.network_simplex(F)
|
| 150 |
+
except nx.NetworkXUnfeasible:
|
| 151 |
+
raise RouteError(
|
| 152 |
+
"Could not balance the network -- some streets are unreachable "
|
| 153 |
+
"(likely a one-way trap at the edge of the box). Try a bigger box."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
for t, targets in flow.items():
|
| 157 |
+
for s, units in targets.items():
|
| 158 |
+
for _ in range(units):
|
| 159 |
+
p = paths[t][s]
|
| 160 |
+
repeats += list(zip(p[:-1], p[1:]))
|
| 161 |
+
|
| 162 |
+
E = nx.MultiDiGraph(R)
|
| 163 |
+
for u, v in repeats:
|
| 164 |
+
d = min(R[u][v].values(), key=lambda x: x["length"])
|
| 165 |
+
E.add_edge(u, v, length=d["length"], name=d.get("name"), required=False)
|
| 166 |
+
return R, E, repeats
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def build_route(E, start_node=None):
|
| 170 |
+
if not nx.is_eulerian(E):
|
| 171 |
+
raise RouteError("Internal: graph did not become Eulerian.")
|
| 172 |
+
steps = []
|
| 173 |
+
for u, v, k in nx.eulerian_circuit(E, source=start_node, keys=True):
|
| 174 |
+
d = E[u][v][k]
|
| 175 |
+
steps.append(
|
| 176 |
+
{
|
| 177 |
+
"u": u,
|
| 178 |
+
"v": v,
|
| 179 |
+
"length": d["length"],
|
| 180 |
+
"name": d.get("name") or "unnamed road",
|
| 181 |
+
"deadhead": not d.get("required", True),
|
| 182 |
+
}
|
| 183 |
+
)
|
| 184 |
+
return steps
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ---------------------------------------------------------------- outputs
|
| 188 |
+
def compute_stats(R, steps, repeats):
|
| 189 |
+
required_m = sum(d["length"] for _, _, d in R.edges(data=True))
|
| 190 |
+
total_m = sum(s["length"] for s in steps)
|
| 191 |
+
dead_m = sum(s["length"] for s in steps if s["deadhead"])
|
| 192 |
+
|
| 193 |
+
by_road = defaultdict(float)
|
| 194 |
+
for s in steps:
|
| 195 |
+
if not s["deadhead"]:
|
| 196 |
+
by_road[s["name"]] += s["length"]
|
| 197 |
+
|
| 198 |
+
return {
|
| 199 |
+
"required_passes": R.number_of_edges(),
|
| 200 |
+
"streets": len(by_road),
|
| 201 |
+
"min_mi": required_m / M_PER_MI,
|
| 202 |
+
"deadhead_mi": dead_m / M_PER_MI,
|
| 203 |
+
"total_mi": total_m / M_PER_MI,
|
| 204 |
+
"efficiency_pct": required_m / total_m * 100 if total_m else 0,
|
| 205 |
+
"overhead_pct": dead_m / required_m * 100 if required_m else 0,
|
| 206 |
+
"repeats": len(repeats),
|
| 207 |
+
"steps": len(steps),
|
| 208 |
+
"drive_min": total_m / M_PER_MI / 12.0 * 60,
|
| 209 |
+
"walk_min": total_m / M_PER_MI / 2.5 * 60,
|
| 210 |
+
"excluded_nodes": R.graph.get("excluded_nodes", 0),
|
| 211 |
+
"longest": sorted(
|
| 212 |
+
[{"name": n, "mi": m / M_PER_MI} for n, m in by_road.items()],
|
| 213 |
+
key=lambda x: -x["mi"],
|
| 214 |
+
)[:15],
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def route_geojson(E, steps):
|
| 219 |
+
"""Each move as a LineString, tagged with its order so the map can color-ramp it."""
|
| 220 |
+
feats = []
|
| 221 |
+
for i, s in enumerate(steps):
|
| 222 |
+
feats.append(
|
| 223 |
+
{
|
| 224 |
+
"type": "Feature",
|
| 225 |
+
"geometry": {
|
| 226 |
+
"type": "LineString",
|
| 227 |
+
"coordinates": [
|
| 228 |
+
[E.nodes[s["u"]]["x"], E.nodes[s["u"]]["y"]],
|
| 229 |
+
[E.nodes[s["v"]]["x"], E.nodes[s["v"]]["y"]],
|
| 230 |
+
],
|
| 231 |
+
},
|
| 232 |
+
"properties": {
|
| 233 |
+
"order": i + 1,
|
| 234 |
+
"name": s["name"],
|
| 235 |
+
"mi": round(s["length"] / M_PER_MI, 3),
|
| 236 |
+
"deadhead": s["deadhead"],
|
| 237 |
+
},
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
return {"type": "FeatureCollection", "features": feats}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def turn_by_turn(steps):
|
| 244 |
+
"""Collapse consecutive moves on the same street into single instructions."""
|
| 245 |
+
out, cur = [], None
|
| 246 |
+
for s in steps:
|
| 247 |
+
if cur and cur["name"] == s["name"] and cur["deadhead"] == s["deadhead"]:
|
| 248 |
+
cur["mi"] += s["length"] / M_PER_MI
|
| 249 |
+
else:
|
| 250 |
+
if cur:
|
| 251 |
+
out.append(cur)
|
| 252 |
+
cur = {"name": s["name"], "mi": s["length"] / M_PER_MI, "deadhead": s["deadhead"]}
|
| 253 |
+
if cur:
|
| 254 |
+
out.append(cur)
|
| 255 |
+
for i, o in enumerate(out):
|
| 256 |
+
o["step"] = i + 1
|
| 257 |
+
o["mi"] = round(o["mi"], 2)
|
| 258 |
+
return out
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# ---------------------------------------------------------------- one-shot
|
| 262 |
+
def solve(G, walking=False, start_lat=None, start_lon=None):
|
| 263 |
+
"""Graph in, everything out. Verifies full coverage before returning."""
|
| 264 |
+
R = build_both_sides(G, walking)
|
| 265 |
+
R, E, repeats = solve_dcpp(R)
|
| 266 |
+
|
| 267 |
+
start = None
|
| 268 |
+
if start_lat is not None and start_lon is not None:
|
| 269 |
+
try:
|
| 270 |
+
start = ox.nearest_nodes(E, float(start_lon), float(start_lat))
|
| 271 |
+
except Exception:
|
| 272 |
+
start = None
|
| 273 |
+
|
| 274 |
+
steps = build_route(E, start)
|
| 275 |
+
|
| 276 |
+
# Hard guarantee: every required pass really is in the route.
|
| 277 |
+
used = defaultdict(int)
|
| 278 |
+
for s in steps:
|
| 279 |
+
used[(s["u"], s["v"])] += 1
|
| 280 |
+
missing = [(u, v) for u, v in R.edges() if used[(u, v)] < 1]
|
| 281 |
+
if missing:
|
| 282 |
+
raise RouteError(f"Internal: {len(missing)} required passes missing from route.")
|
| 283 |
+
|
| 284 |
+
return {
|
| 285 |
+
"stats": compute_stats(R, steps, repeats),
|
| 286 |
+
"geojson": route_geojson(E, steps),
|
| 287 |
+
"directions": turn_by_turn(steps),
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# Keep osmnx's HTTP cache in /tmp (the only writable path on a Space).
|
| 292 |
+
ox.settings.cache_folder = "/tmp/osmnx_cache"
|
| 293 |
+
ox.settings.use_cache = True
|
| 294 |
+
ox.settings.log_console = False
|
| 295 |
+
ox.settings.requests_timeout = 180
|
| 296 |
+
ox.settings.overpass_rate_limit = True
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# ============================================================ the page
|
| 300 |
+
PAGE = r'''<!DOCTYPE html>
|
| 301 |
+
<html lang="en">
|
| 302 |
+
<head>
|
| 303 |
+
<meta charset="utf-8">
|
| 304 |
+
<title>Paper Route Planner</title>
|
| 305 |
+
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
| 306 |
+
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
|
| 307 |
+
<style>
|
| 308 |
+
:root{--bg:#0f1115;--panel:#171a21;--line:#262b36;--txt:#e7eaf0;--dim:#98a1b3;--acc:#4f8cff;--ok:#2ecc71;--bad:#d7263d}
|
| 309 |
+
*{box-sizing:border-box}
|
| 310 |
+
body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--txt);height:100vh;display:flex;flex-direction:column}
|
| 311 |
+
header{padding:12px 18px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:16px}
|
| 312 |
+
h1{margin:0;font-size:16px;font-weight:650;letter-spacing:.2px}
|
| 313 |
+
.sub{color:var(--dim);font-size:12px}
|
| 314 |
+
main{flex:1;display:grid;grid-template-columns:340px 1fr 320px;min-height:0}
|
| 315 |
+
.pane{border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
|
| 316 |
+
.pane:last-child{border-right:0;border-left:1px solid var(--line);overflow-y:auto}
|
| 317 |
+
.hd{padding:10px 14px;font-size:11px;text-transform:uppercase;letter-spacing:.9px;color:var(--dim);border-bottom:1px solid var(--line)}
|
| 318 |
+
#drop{flex:1;margin:14px;border:2px dashed var(--line);border-radius:10px;display:flex;align-items:center;justify-content:center;text-align:center;color:var(--dim);cursor:pointer;overflow:hidden;position:relative;transition:.15s}
|
| 319 |
+
#drop:hover,#drop.hot{border-color:var(--acc);background:#4f8cff10}
|
| 320 |
+
#drop img{width:100%;height:100%;object-fit:contain}
|
| 321 |
+
#drop .ph{padding:24px}
|
| 322 |
+
#drop .ph b{color:var(--txt);display:block;margin-bottom:6px;font-size:15px}
|
| 323 |
+
#map{flex:1}
|
| 324 |
+
.ctl{padding:12px 14px;border-bottom:1px solid var(--line);display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
| 325 |
+
input[type=text]{flex:1;min-width:150px;background:#0b0d11;border:1px solid var(--line);color:var(--txt);padding:9px 11px;border-radius:7px;font-size:13px}
|
| 326 |
+
input[type=text]:focus{outline:0;border-color:var(--acc)}
|
| 327 |
+
button{background:var(--acc);color:#fff;border:0;padding:9px 15px;border-radius:7px;font-weight:600;cursor:pointer;font-size:13px}
|
| 328 |
+
button:hover{filter:brightness(1.12)}
|
| 329 |
+
button:disabled{opacity:.45;cursor:not-allowed}
|
| 330 |
+
button.sec{background:#252a35}
|
| 331 |
+
label.ck{display:flex;align-items:center;gap:6px;color:var(--dim);font-size:12px;cursor:pointer}
|
| 332 |
+
.msg{margin:14px;padding:11px 13px;border-radius:8px;font-size:13px;display:none}
|
| 333 |
+
.msg.err{display:block;background:#d7263d22;border:1px solid #d7263d55;color:#ffb3bd}
|
| 334 |
+
.msg.info{display:block;background:#4f8cff18;border:1px solid #4f8cff44;color:#bcd4ff}
|
| 335 |
+
.stat{padding:11px 14px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:baseline;gap:10px}
|
| 336 |
+
.stat span{color:var(--dim);font-size:12px}
|
| 337 |
+
.stat b{font-size:15px;font-variant-numeric:tabular-nums}
|
| 338 |
+
.stat.big b{font-size:24px;color:var(--acc)}
|
| 339 |
+
.stat.good b{color:var(--ok)}
|
| 340 |
+
.stat.warn b{color:var(--bad)}
|
| 341 |
+
.street{padding:6px 14px;display:flex;justify-content:space-between;font-size:12px;color:var(--dim);border-bottom:1px solid #1c2028}
|
| 342 |
+
.street b{color:var(--txt);font-variant-numeric:tabular-nums;font-weight:500}
|
| 343 |
+
.empty{padding:26px 16px;color:var(--dim);font-size:13px;text-align:center;line-height:1.7}
|
| 344 |
+
.legend{position:absolute;bottom:14px;left:14px;z-index:800;background:#171a21ee;border:1px solid var(--line);padding:9px 11px;border-radius:8px;font-size:11px;line-height:1.9;display:none}
|
| 345 |
+
.sw{display:inline-block;width:18px;height:3px;vertical-align:middle;margin-right:6px;border-radius:2px}
|
| 346 |
+
.spin{width:14px;height:14px;border:2px solid #ffffff44;border-top-color:#fff;border-radius:50%;display:inline-block;animation:s .7s linear infinite;vertical-align:-2px;margin-right:7px}
|
| 347 |
+
@keyframes s{to{transform:rotate(360deg)}}
|
| 348 |
+
.mapwrap{position:relative;flex:1;display:flex;min-height:0}
|
| 349 |
+
</style>
|
| 350 |
+
</head>
|
| 351 |
+
<body>
|
| 352 |
+
|
| 353 |
+
<header>
|
| 354 |
+
<h1>Paper Route Planner</h1>
|
| 355 |
+
<span class="sub">Shortest closed route covering every road — both sides — solved exactly (Directed Chinese Postman)</span>
|
| 356 |
+
</header>
|
| 357 |
+
|
| 358 |
+
<main>
|
| 359 |
+
<div class="pane">
|
| 360 |
+
<div class="hd">1 Drop your screenshot</div>
|
| 361 |
+
<div id="drop">
|
| 362 |
+
<div class="ph">
|
| 363 |
+
<b>Drag your map screenshot here</b>
|
| 364 |
+
Or click to choose a file.<br>
|
| 365 |
+
It stays on your machine — it's your visual reference for matching the map.
|
| 366 |
+
</div>
|
| 367 |
+
<input type="file" id="file" accept="image/*" hidden>
|
| 368 |
+
</div>
|
| 369 |
+
</div>
|
| 370 |
+
|
| 371 |
+
<div class="pane">
|
| 372 |
+
<div class="hd">2 Find the area, then drag a box around it</div>
|
| 373 |
+
<div class="ctl">
|
| 374 |
+
<input type="text" id="q" placeholder="ZIP code, address, or neighborhood...">
|
| 375 |
+
<button id="find" class="sec">Find</button>
|
| 376 |
+
</div>
|
| 377 |
+
<div class="ctl">
|
| 378 |
+
<button id="box" class="sec">Draw box</button>
|
| 379 |
+
<button id="clear" class="sec">Clear</button>
|
| 380 |
+
<label class="ck"><input type="checkbox" id="walking"> Walking (ignore one-ways)</label>
|
| 381 |
+
<label class="ck"><input type="checkbox" id="svc"> Include alleys</label>
|
| 382 |
+
<button id="solve" disabled>Solve route</button>
|
| 383 |
+
</div>
|
| 384 |
+
<div class="mapwrap">
|
| 385 |
+
<div id="map"></div>
|
| 386 |
+
<div class="legend" id="legend">
|
| 387 |
+
<span class="sw" style="background:#2860e6"></span>route start<br>
|
| 388 |
+
<span class="sw" style="background:#e6c85a"></span>route end<br>
|
| 389 |
+
<span class="sw" style="background:#d7263d"></span>deadhead (repeat pass)<br>
|
| 390 |
+
<span style="color:#98a1b3">Hover any segment for its step number.</span>
|
| 391 |
+
</div>
|
| 392 |
+
</div>
|
| 393 |
+
</div>
|
| 394 |
+
|
| 395 |
+
<div class="pane">
|
| 396 |
+
<div class="hd">3 Your route</div>
|
| 397 |
+
<div id="msg" class="msg"></div>
|
| 398 |
+
<div id="out">
|
| 399 |
+
<div class="empty">
|
| 400 |
+
Drop a screenshot, find the area,<br>draw a box, and hit <b>Solve route</b>.
|
| 401 |
+
</div>
|
| 402 |
+
</div>
|
| 403 |
+
</div>
|
| 404 |
+
</main>
|
| 405 |
+
|
| 406 |
+
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
| 407 |
+
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
|
| 408 |
+
<script>
|
| 409 |
+
// ---------- screenshot drop (reference only; never uploaded) ----------
|
| 410 |
+
const drop = document.getElementById('drop'), file = document.getElementById('file');
|
| 411 |
+
drop.onclick = () => file.click();
|
| 412 |
+
file.onchange = e => e.target.files[0] && show(e.target.files[0]);
|
| 413 |
+
['dragenter','dragover'].forEach(t => drop.addEventListener(t, e => {
|
| 414 |
+
e.preventDefault(); drop.classList.add('hot');
|
| 415 |
+
}));
|
| 416 |
+
['dragleave','drop'].forEach(t => drop.addEventListener(t, e => {
|
| 417 |
+
e.preventDefault(); drop.classList.remove('hot');
|
| 418 |
+
}));
|
| 419 |
+
drop.addEventListener('drop', e => {
|
| 420 |
+
const f = e.dataTransfer.files[0];
|
| 421 |
+
if (f && f.type.startsWith('image/')) show(f);
|
| 422 |
+
else msg('That file is not an image.', 'err');
|
| 423 |
+
});
|
| 424 |
+
function show(f){
|
| 425 |
+
const img = document.createElement('img');
|
| 426 |
+
img.src = URL.createObjectURL(f);
|
| 427 |
+
drop.innerHTML = ''; drop.appendChild(img);
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
// ---------- map ----------
|
| 431 |
+
const map = L.map('map').setView([39.83, -98.58], 4);
|
| 432 |
+
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
|
| 433 |
+
{maxZoom: 19, attribution: '© OpenStreetMap, © CARTO'}).addTo(map);
|
| 434 |
+
|
| 435 |
+
const drawn = new L.FeatureGroup().addTo(map);
|
| 436 |
+
let routeLayer = null, startMarker = null, bounds = null;
|
| 437 |
+
|
| 438 |
+
const rect = new L.Draw.Rectangle(map, {shapeOptions:{color:'#4f8cff', weight:2, fillOpacity:.06}});
|
| 439 |
+
document.getElementById('box').onclick = () => { drawn.clearLayers(); rect.enable(); };
|
| 440 |
+
|
| 441 |
+
map.on(L.Draw.Event.CREATED, e => {
|
| 442 |
+
drawn.clearLayers();
|
| 443 |
+
drawn.addLayer(e.layer);
|
| 444 |
+
const b = e.layer.getBounds();
|
| 445 |
+
bounds = {north:b.getNorth(), south:b.getSouth(), east:b.getEast(), west:b.getWest()};
|
| 446 |
+
document.getElementById('solve').disabled = false;
|
| 447 |
+
msg('Box set. Optionally shift-click the map to set where you start and end. Then Solve.', 'info');
|
| 448 |
+
});
|
| 449 |
+
|
| 450 |
+
map.on('click', e => {
|
| 451 |
+
if (!e.originalEvent.shiftKey) return;
|
| 452 |
+
if (startMarker) map.removeLayer(startMarker);
|
| 453 |
+
startMarker = L.marker(e.latlng).addTo(map).bindTooltip('Start / End').openTooltip();
|
| 454 |
+
});
|
| 455 |
+
|
| 456 |
+
document.getElementById('clear').onclick = () => {
|
| 457 |
+
drawn.clearLayers();
|
| 458 |
+
if (routeLayer) { map.removeLayer(routeLayer); routeLayer = null; }
|
| 459 |
+
if (startMarker) { map.removeLayer(startMarker); startMarker = null; }
|
| 460 |
+
bounds = null;
|
| 461 |
+
document.getElementById('solve').disabled = true;
|
| 462 |
+
document.getElementById('legend').style.display = 'none';
|
| 463 |
+
document.getElementById('out').innerHTML =
|
| 464 |
+
'<div class="empty">Draw a box and hit <b>Solve route</b>.</div>';
|
| 465 |
+
msg('');
|
| 466 |
+
};
|
| 467 |
+
|
| 468 |
+
// ---------- geocode ----------
|
| 469 |
+
const q = document.getElementById('q');
|
| 470 |
+
document.getElementById('find').onclick = find;
|
| 471 |
+
q.onkeydown = e => { if (e.key === 'Enter') find(); };
|
| 472 |
+
|
| 473 |
+
async function find(){
|
| 474 |
+
const term = q.value.trim();
|
| 475 |
+
if (!term) return;
|
| 476 |
+
msg('Looking up "' + term + '"...', 'info');
|
| 477 |
+
try {
|
| 478 |
+
const r = await fetch('/geocode?q=' + encodeURIComponent(term));
|
| 479 |
+
const d = await r.json();
|
| 480 |
+
if (!r.ok) return msg(d.error, 'err');
|
| 481 |
+
map.fitBounds([[d.bounds.south, d.bounds.west], [d.bounds.north, d.bounds.east]]);
|
| 482 |
+
if (map.getZoom() > 16) map.setZoom(16);
|
| 483 |
+
msg('Found ' + d.label + '. Now click <b>Draw box</b> and drag around your neighborhood.', 'info');
|
| 484 |
+
} catch (err) { msg('Lookup failed: ' + err, 'err'); }
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
// ---------- solve ----------
|
| 488 |
+
const solveBtn = document.getElementById('solve');
|
| 489 |
+
solveBtn.onclick = async () => {
|
| 490 |
+
if (!bounds) return;
|
| 491 |
+
const orig = solveBtn.innerHTML;
|
| 492 |
+
solveBtn.disabled = true;
|
| 493 |
+
solveBtn.innerHTML = '<span class="spin"></span>Solving...';
|
| 494 |
+
msg('Pulling roads from OpenStreetMap and solving. Bigger areas take a minute.', 'info');
|
| 495 |
+
|
| 496 |
+
const body = {
|
| 497 |
+
bounds: bounds,
|
| 498 |
+
walking: document.getElementById('walking').checked,
|
| 499 |
+
include_service: document.getElementById('svc').checked
|
| 500 |
+
};
|
| 501 |
+
if (startMarker) {
|
| 502 |
+
body.start_lat = startMarker.getLatLng().lat;
|
| 503 |
+
body.start_lon = startMarker.getLatLng().lng;
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
try {
|
| 507 |
+
const r = await fetch('/solve', {
|
| 508 |
+
method: 'POST',
|
| 509 |
+
headers: {'Content-Type': 'application/json'},
|
| 510 |
+
body: JSON.stringify(body)
|
| 511 |
+
});
|
| 512 |
+
const d = await r.json();
|
| 513 |
+
if (!r.ok) { msg(d.error, 'err'); return; }
|
| 514 |
+
render(d);
|
| 515 |
+
msg('');
|
| 516 |
+
} catch (err) {
|
| 517 |
+
msg('Solve failed: ' + err, 'err');
|
| 518 |
+
} finally {
|
| 519 |
+
solveBtn.disabled = false;
|
| 520 |
+
solveBtn.innerHTML = orig;
|
| 521 |
+
}
|
| 522 |
+
};
|
| 523 |
+
|
| 524 |
+
// ---------- render ----------
|
| 525 |
+
function render(d){
|
| 526 |
+
if (routeLayer) map.removeLayer(routeLayer);
|
| 527 |
+
const n = d.geojson.features.length;
|
| 528 |
+
|
| 529 |
+
routeLayer = L.geoJSON(d.geojson, {
|
| 530 |
+
style: f => {
|
| 531 |
+
const p = f.properties;
|
| 532 |
+
if (p.deadhead)
|
| 533 |
+
return {color:'#d7263d', weight:3, opacity:.95, dashArray:'6,8'};
|
| 534 |
+
const t = (p.order - 1) / Math.max(n - 1, 1);
|
| 535 |
+
const c = 'rgb(' + Math.round(40 + 200*t) + ',' + Math.round(90 + 100*t) + ',' +
|
| 536 |
+
Math.round(230 - 180*t) + ')';
|
| 537 |
+
return {color:c, weight:5, opacity:.85};
|
| 538 |
+
},
|
| 539 |
+
onEachFeature: (f, l) => {
|
| 540 |
+
const p = f.properties;
|
| 541 |
+
l.bindTooltip('#' + p.order + ' ' + p.name + ' — ' + p.mi + ' mi' +
|
| 542 |
+
(p.deadhead ? ' (deadhead, no delivery)' : ''));
|
| 543 |
+
}
|
| 544 |
+
}).addTo(map);
|
| 545 |
+
map.fitBounds(routeLayer.getBounds(), {padding:[24,24]});
|
| 546 |
+
document.getElementById('legend').style.display = 'block';
|
| 547 |
+
|
| 548 |
+
const s = d.stats;
|
| 549 |
+
const row = (label, val, cls) =>
|
| 550 |
+
'<div class="stat ' + (cls||'') + '"><span>' + label + '</span><b>' + val + '</b></div>';
|
| 551 |
+
|
| 552 |
+
let h = '';
|
| 553 |
+
h += row('Total route', s.total_mi.toFixed(2) + ' mi', 'big');
|
| 554 |
+
h += row('Delivering', s.min_mi.toFixed(2) + ' mi', 'good');
|
| 555 |
+
h += row('Deadhead (repeats)', s.deadhead_mi.toFixed(2) + ' mi', 'warn');
|
| 556 |
+
h += row('Efficiency', s.efficiency_pct.toFixed(1) + '%');
|
| 557 |
+
h += row('Overhead vs. minimum', '+' + s.overhead_pct.toFixed(1) + '%');
|
| 558 |
+
h += row('Streets covered', s.streets.toLocaleString());
|
| 559 |
+
h += row('Passes (both sides)', s.required_passes.toLocaleString());
|
| 560 |
+
h += row('Est. driving time', Math.round(s.drive_min) + ' min');
|
| 561 |
+
h += row('Est. walking time', Math.round(s.walk_min) + ' min');
|
| 562 |
+
if (s.excluded_nodes)
|
| 563 |
+
h += '<div class="msg info" style="display:block">' + s.excluded_nodes +
|
| 564 |
+
' intersection(s) were unreachable from the main network and left out.</div>';
|
| 565 |
+
|
| 566 |
+
h += '<div class="hd" style="margin-top:8px">Longest streets</div>';
|
| 567 |
+
s.longest.forEach(x => {
|
| 568 |
+
h += '<div class="street"><span>' + x.name + '</span><b>' + x.mi.toFixed(2) + ' mi</b></div>';
|
| 569 |
+
});
|
| 570 |
+
|
| 571 |
+
h += '<div class="hd" style="margin-top:8px">Directions</div>';
|
| 572 |
+
d.directions.forEach(x => {
|
| 573 |
+
h += '<div class="street"><span>' + x.step + '. ' +
|
| 574 |
+
(x.deadhead ? '<i style="color:#d7263d">(deadhead)</i> ' : '') +
|
| 575 |
+
x.name + '</span><b>' + x.mi.toFixed(2) + '</b></div>';
|
| 576 |
+
});
|
| 577 |
+
|
| 578 |
+
document.getElementById('out').innerHTML = h;
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
function msg(t, cls){
|
| 582 |
+
const m = document.getElementById('msg');
|
| 583 |
+
m.innerHTML = t || '';
|
| 584 |
+
m.className = 'msg' + (t ? ' ' + cls : '');
|
| 585 |
+
}
|
| 586 |
+
</script>
|
| 587 |
+
</body>
|
| 588 |
+
</html>
|
| 589 |
+
'''
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
# ============================================================ web app
|
| 593 |
+
app = Flask(__name__)
|
| 594 |
+
UA = {"User-Agent": "paper-route-planner (HF Space; personal delivery route tool)"}
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@app.route("/")
|
| 598 |
+
def index():
|
| 599 |
+
return render_template_string(PAGE)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
@app.route("/health")
|
| 603 |
+
def health():
|
| 604 |
+
return jsonify({"status": "ok"})
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
@app.route("/geocode")
|
| 608 |
+
def geocode():
|
| 609 |
+
q = (request.args.get("q") or "").strip()
|
| 610 |
+
if not q:
|
| 611 |
+
return jsonify({"error": "Type a ZIP code, address, or neighborhood."}), 400
|
| 612 |
+
try:
|
| 613 |
+
r = requests.get(
|
| 614 |
+
"https://nominatim.openstreetmap.org/search",
|
| 615 |
+
params={"q": q, "format": "json", "limit": 1, "countrycodes": "us"},
|
| 616 |
+
headers=UA,
|
| 617 |
+
timeout=20,
|
| 618 |
+
)
|
| 619 |
+
r.raise_for_status()
|
| 620 |
+
hits = r.json()
|
| 621 |
+
except Exception as exc:
|
| 622 |
+
return jsonify({"error": "Lookup failed: %s" % exc}), 502
|
| 623 |
+
|
| 624 |
+
if not hits:
|
| 625 |
+
return jsonify({"error": "Couldn't find '%s'. Try adding the city and state." % q}), 404
|
| 626 |
+
|
| 627 |
+
h = hits[0]
|
| 628 |
+
s, n, w, e = [float(x) for x in h["boundingbox"]] # nominatim order: S,N,W,E
|
| 629 |
+
return jsonify({
|
| 630 |
+
"label": h.get("display_name", q),
|
| 631 |
+
"lat": float(h["lat"]), "lon": float(h["lon"]),
|
| 632 |
+
"bounds": {"south": s, "north": n, "west": w, "east": e},
|
| 633 |
+
})
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
@app.route("/solve", methods=["POST"])
|
| 637 |
+
def solve_route():
|
| 638 |
+
d = request.get_json(force=True)
|
| 639 |
+
try:
|
| 640 |
+
b = d["bounds"]
|
| 641 |
+
area = _area_sq_mi(b)
|
| 642 |
+
if area > MAX_AREA_SQ_MI:
|
| 643 |
+
raise RouteError(
|
| 644 |
+
"That box is about %.0f sq mi -- too big to solve (limit %.0f). "
|
| 645 |
+
"Draw a smaller one; a paper route is usually well under 1 sq mi."
|
| 646 |
+
% (area, MAX_AREA_SQ_MI)
|
| 647 |
+
)
|
| 648 |
+
G = graph_from_bbox(
|
| 649 |
+
b["north"], b["south"], b["east"], b["west"],
|
| 650 |
+
walking=bool(d.get("walking")),
|
| 651 |
+
include_service=bool(d.get("include_service")),
|
| 652 |
+
)
|
| 653 |
+
return jsonify(solve(
|
| 654 |
+
G,
|
| 655 |
+
walking=bool(d.get("walking")),
|
| 656 |
+
start_lat=d.get("start_lat"),
|
| 657 |
+
start_lon=d.get("start_lon"),
|
| 658 |
+
))
|
| 659 |
+
except RouteError as exc:
|
| 660 |
+
return jsonify({"error": str(exc)}), 400
|
| 661 |
+
except Exception as exc:
|
| 662 |
+
traceback.print_exc()
|
| 663 |
+
return jsonify({"error": "Unexpected error: %s" % exc}), 500
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def _area_sq_mi(b):
|
| 667 |
+
import math
|
| 668 |
+
mid = math.radians((b["north"] + b["south"]) / 2)
|
| 669 |
+
h = (b["north"] - b["south"]) * 69.0
|
| 670 |
+
w = (b["east"] - b["west"]) * 69.0 * math.cos(mid)
|
| 671 |
+
return abs(h * w)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
if __name__ == "__main__":
|
| 675 |
+
port = int(os.environ.get("PORT", 7860))
|
| 676 |
+
app.run(host="0.0.0.0", port=port, debug=False)
|