-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmap_print.py
More file actions
303 lines (259 loc) · 11.7 KB
/
Copy pathmap_print.py
File metadata and controls
303 lines (259 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
"""Print a square street-map slice on the S01 thermal printer.
Recreates the classic line-art "printed map" look: vector roads from
OpenStreetMap (via the Overpass API) drawn as black lines weighted by road
class, with the major streets labelled along their direction. No API key.
Location can be a search string (geocoded with Nominatim) or explicit
--lat/--lon. --radius is the half-width of the square in metres.
Examples:
python map_print.py "Old Street, London"
python map_print.py "Times Square, New York" --radius 600
python map_print.py --lat 40.7580 --lon -73.9855 --radius 500
python map_print.py "Old Street, London" --no-print
"""
from __future__ import annotations
import argparse
from datetime import datetime
import json
import math
from pathlib import Path
import subprocess
import sys
import urllib.parse
import urllib.request
from PIL import Image, ImageChops, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parent
WIDTH = 384
UA = "printer-map/1.0 (personal thermal printer project)"
OVERPASS_ENDPOINTS = [
"https://overpass-api.de/api/interpreter",
"https://overpass.kumi.systems/api/interpreter",
"https://maps.mail.ru/osm/tools/overpass/api/interpreter",
"https://overpass.openstreetmap.ru/api/interpreter",
]
BOLD_TTF = "C:/Windows/Fonts/consolab.ttf"
REG_TTF = "C:/Windows/Fonts/consola.ttf"
# highway class -> line width in px. Anything not listed is skipped.
ROAD_WIDTH = {
"motorway": 5, "motorway_link": 3,
"trunk": 5, "trunk_link": 3,
"primary": 4, "primary_link": 3,
"secondary": 4, "secondary_link": 2,
"tertiary": 3, "tertiary_link": 2,
"residential": 2, "unclassified": 2, "living_street": 2,
"pedestrian": 2, "service": 1,
"footway": 1, "path": 1, "cycleway": 1, "steps": 1,
}
# classes whose names we bother labelling (skip tiny service/foot paths)
LABEL_CLASSES = {
"motorway", "trunk", "primary", "secondary", "tertiary",
"residential", "unclassified", "living_street", "pedestrian",
}
def font(path: str, size: int):
try:
return ImageFont.truetype(path, size)
except OSError:
return ImageFont.load_default()
def http_get(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read()
def geocode(query: str) -> tuple[float, float, str]:
params = urllib.parse.urlencode({"q": query, "format": "json", "limit": 1})
data = json.loads(http_get(f"https://nominatim.openstreetmap.org/search?{params}"))
if not data:
raise SystemExit(f"Could not geocode {query!r}. Try a more specific place or use --lat/--lon.")
hit = data[0]
label = hit.get("display_name", query).split(",")[0]
return float(hit["lat"]), float(hit["lon"]), label
def fetch_roads(south: float, west: float, north: float, east: float) -> list[dict]:
query = (
"[out:json][timeout:25];"
f'(way["highway"]({south},{west},{north},{east}););'
"out geom;"
)
body = urllib.parse.urlencode({"data": query}).encode()
last_error: Exception | None = None
for attempt in range(2):
for endpoint in OVERPASS_ENDPOINTS:
try:
req = urllib.request.Request(endpoint, data=body, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=90) as resp:
return json.loads(resp.read())["elements"]
except Exception as exc: # noqa: BLE001 - try the next mirror
last_error = exc
print(f" Overpass mirror busy ({endpoint.split('/')[2]}): {exc}")
raise SystemExit(f"All Overpass mirrors failed: {last_error}. Try again in a moment.")
def polyline_midpoint(points: list[tuple[float, float]]) -> tuple[float, float, float]:
"""Return (x, y, angle_degrees) at the half-length point of a pixel polyline."""
seglen = [math.dist(points[i], points[i + 1]) for i in range(len(points) - 1)]
total = sum(seglen)
target = total / 2
run = 0.0
for i, length in enumerate(seglen):
if run + length >= target and length > 0:
t = (target - run) / length
(x0, y0), (x1, y1) = points[i], points[i + 1]
x = x0 + t * (x1 - x0)
y = y0 + t * (y1 - y0)
angle = math.degrees(math.atan2(-(y1 - y0), (x1 - x0)))
if angle > 90 or angle < -90:
angle += 180 # keep text upright
return x, y, angle
run += length
return points[0][0], points[0][1], 0.0
def draw_rotated_label(base: Image.Image, text: str, cx: float, cy: float, angle: float, fnt, bounds: tuple) -> tuple:
l, t, r, b = fnt.getbbox(text)
pad = 3
tw, th = (r - l) + 2 * pad, (b - t) + 2 * pad
tile = Image.new("L", (tw, th), 255)
ImageDraw.Draw(tile).text((pad - l, pad - t), text, fill=0, font=fnt)
rot = tile.rotate(angle, expand=True, resample=Image.BICUBIC, fillcolor=255)
ox, oy = int(cx - rot.width / 2), int(cy - rot.height / 2)
box = (ox, oy, ox + rot.width, oy + rot.height)
bx0, by0, bx1, by1 = bounds
if box[0] < bx0 or box[1] < by0 or box[2] > bx1 or box[3] > by1:
return None
region = base.crop(box)
base.paste(ImageChops.darker(region, rot), box)
return box
def boxes_overlap(a: tuple, b: tuple, pad: int = 2) -> bool:
return not (a[2] + pad < b[0] or b[2] + pad < a[0] or a[3] + pad < b[1] or b[3] + pad < a[1])
def render(
lat: float,
lon: float,
label: str,
radius: float,
roads: list[dict],
out: Path,
bottom_feed: int,
) -> None:
title_f = font(BOLD_TTF, 15)
sub_f = font(REG_TTF, 13)
label_f = font(REG_TTF, 11)
tiny_f = font(REG_TTF, 12)
margin = 8
size = WIDTH - 2 * margin # square map in px
header_h = 30
footer_h = 34
oy = header_h
content_h = header_h + size + footer_h
# square bounding box on the ground
dlat = radius / 111320.0
dlon = radius / (111320.0 * math.cos(math.radians(lat)))
lat_min, lat_max = lat - dlat, lat + dlat
lon_min, lon_max = lon - dlon, lon + dlon
def proj(plat: float, plon: float) -> tuple[float, float]:
x = margin + (plon - lon_min) / (lon_max - lon_min) * size
y = oy + (lat_max - plat) / (lat_max - lat_min) * size
return x, y
img = Image.new("L", (WIDTH, content_h + max(0, bottom_feed)), 255)
d = ImageDraw.Draw(img)
# --- draw roads (thin first, thick on top) ---
drawable = []
for way in roads:
if way.get("type") != "way" or "geometry" not in way:
continue
cls = way.get("tags", {}).get("highway")
w = ROAD_WIDTH.get(cls)
if not w:
continue
pts = [proj(p["lat"], p["lon"]) for p in way["geometry"]]
drawable.append((w, cls, way.get("tags", {}).get("name"), pts))
drawable.sort(key=lambda item: item[0])
for w, _cls, _name, pts in drawable:
if len(pts) >= 2:
d.line(pts, fill=0, width=w, joint="curve")
# --- street labels (one per name, no overlaps), clipped to the map square ---
map_rect = (margin, oy, margin + size, oy + size)
placed: list[tuple] = []
seen: set[str] = set()
# longest segments first so prominent roads win label space
labelable = sorted(
(item for item in drawable if item[1] in LABEL_CLASSES and item[2]),
key=lambda item: sum(math.dist(item[3][i], item[3][i + 1]) for i in range(len(item[3]) - 1)),
reverse=True,
)
for _w, _cls, name, pts in labelable:
if name in seen or len(pts) < 2:
continue
length = sum(math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1))
if length < 45:
continue
cx, cy, angle = polyline_midpoint(pts)
l, t, r, b = label_f.getbbox(name)
approx = (cx - (r - l) / 2, cy - (b - t) / 2, cx + (r - l) / 2, cy + (b - t) / 2)
if any(boxes_overlap(approx, pb) for pb in placed):
continue
box = draw_rotated_label(img, name, cx, cy, angle, label_f, map_rect)
if box:
placed.append(box)
seen.add(name)
# clear the header/footer strips so nothing bleeds into the chrome
d.rectangle((1, 1, WIDTH - 2, oy - 1), fill=255)
d.rectangle((1, oy + size + 1, WIDTH - 2, content_h - 2), fill=255)
# --- header ---
d.rectangle((0, 0, WIDTH - 1, content_h - 1), outline=0, width=2)
now = datetime.now()
date_str = now.strftime("%A %d %B %Y")
printed = "Printed at " + now.strftime("%I:%M%p").lstrip("0").lower()
d.text((margin, 8), date_str, fill=0, font=title_f)
pw = d.textlength(printed, font=sub_f)
d.text((WIDTH - margin - pw, 10), printed, fill=0, font=sub_f)
d.line((margin, header_h - 3, WIDTH - margin, header_h - 3), fill=0, width=1)
# --- footer: place label + scale bar ---
fy = content_h - footer_h + 6
d.line((margin, fy - 2, WIDTH - margin, fy - 2), fill=0, width=1)
d.text((margin, fy + 4), label[:26], fill=0, font=tiny_f)
meters_per_px = (2 * radius) / size
target_px = size / 4
nice = [50, 100, 150, 200, 250, 300, 500, 750, 1000, 1500, 2000]
bar_m = min(nice, key=lambda m: abs(m / meters_per_px - target_px))
bar_px = round(bar_m / meters_per_px)
bx1 = WIDTH - margin - bar_px
by = fy + 14
d.line((bx1, by, bx1 + bar_px, by), fill=0, width=2)
d.line((bx1, by - 4, bx1, by + 4), fill=0, width=2)
d.line((bx1 + bar_px, by - 4, bx1 + bar_px, by + 4), fill=0, width=2)
bar_lbl = f"{bar_m} m"
blw = d.textlength(bar_lbl, font=tiny_f)
d.text((bx1 + bar_px / 2 - blw / 2, fy + 1), bar_lbl, fill=0, font=tiny_f)
img.convert("1").save(out)
def print_image(path: Path, darkness: int) -> int:
python = ROOT / ".venv" / "Scripts" / "python.exe"
python = python if python.exists() else Path(sys.executable)
command = [str(python), str(ROOT / "s1_print.py"), "image", str(path), "--darkness", str(darkness)]
return subprocess.call(command, cwd=ROOT)
def main() -> int:
parser = argparse.ArgumentParser(description="Print a square street-map slice on the S01 thermal printer.")
parser.add_argument("query", nargs="?", default="Old Street, London", help="Place to map (geocoded).")
parser.add_argument("--lat", type=float, help="Center latitude (overrides query).")
parser.add_argument("--lon", type=float, help="Center longitude (overrides query).")
parser.add_argument("--radius", type=float, default=500, help="Half-width of the square in metres.")
parser.add_argument("--out", type=Path, default=None)
parser.add_argument("--darkness", type=int, choices=range(1, 6), default=3)
parser.add_argument("--bottom-feed", type=int, default=24)
parser.add_argument("--no-print", action="store_true")
args = parser.parse_args()
if (args.lat is None) != (args.lon is None):
parser.error("--lat and --lon must be given together.")
if args.lat is not None:
lat, lon, label = args.lat, args.lon, f"{args.lat:.4f}, {args.lon:.4f}"
else:
print(f"Geocoding {args.query!r} ...")
lat, lon, label = geocode(args.query)
print(f" center {lat:.5f}, {lon:.5f} radius {args.radius:.0f} m")
dlat = args.radius / 111320.0
dlon = args.radius / (111320.0 * math.cos(math.radians(lat)))
print("Fetching roads from Overpass ...")
roads = fetch_roads(lat - dlat, lon - dlon, lat + dlat, lon + dlon)
n_roads = sum(1 for r in roads if r.get("type") == "way")
print(f" {n_roads} road segments")
out = args.out or ROOT / f"map_{label.replace(' ', '_').replace('/', '_')[:24]}.png"
render(lat, lon, label, args.radius, roads, out, args.bottom_feed)
print(f"Wrote {out}")
if args.no_print:
return 0
return print_image(out, args.darkness)
if __name__ == "__main__":
raise SystemExit(main())