wayfolio 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. wayfolio/__init__.py +3 -0
  2. wayfolio/__main__.py +4 -0
  3. wayfolio/basemap/__init__.py +23 -0
  4. wayfolio/basemap/amap_static.py +109 -0
  5. wayfolio/basemap/amap_tiles.py +191 -0
  6. wayfolio/basemap/osm_full.py +106 -0
  7. wayfolio/basemap/osm_tiles.py +184 -0
  8. wayfolio/basemap/provider.py +44 -0
  9. wayfolio/basemap/stub.py +110 -0
  10. wayfolio/basemap/vector.py +686 -0
  11. wayfolio/boundary.py +52 -0
  12. wayfolio/build.py +257 -0
  13. wayfolio/cache_admin.py +264 -0
  14. wayfolio/cli.py +777 -0
  15. wayfolio/config.py +175 -0
  16. wayfolio/crs.py +178 -0
  17. wayfolio/display.py +61 -0
  18. wayfolio/doctor.py +169 -0
  19. wayfolio/editor/__init__.py +1 -0
  20. wayfolio/editor/api.py +419 -0
  21. wayfolio/editor/boxes.py +182 -0
  22. wayfolio/editor/manager.py +390 -0
  23. wayfolio/editor/patch.py +171 -0
  24. wayfolio/editor/preview.py +300 -0
  25. wayfolio/editor/schema.py +306 -0
  26. wayfolio/editor/server.py +35 -0
  27. wayfolio/grid.py +200 -0
  28. wayfolio/i18n.py +289 -0
  29. wayfolio/icons.py +80 -0
  30. wayfolio/ir.py +123 -0
  31. wayfolio/labels.py +275 -0
  32. wayfolio/launcher.py +49 -0
  33. wayfolio/legend_mask.py +170 -0
  34. wayfolio/models.py +163 -0
  35. wayfolio/paths.py +56 -0
  36. wayfolio/place.py +67 -0
  37. wayfolio/planner.py +622 -0
  38. wayfolio/postprocess.py +82 -0
  39. wayfolio/resources/workspace/assets/amap-icons/README.md +90 -0
  40. wayfolio/resources/workspace/assets/amap-icons/badges/bus.png +0 -0
  41. wayfolio/resources/workspace/assets/amap-icons/badges/food.png +0 -0
  42. wayfolio/resources/workspace/assets/amap-icons/badges/line-label-pill.png +0 -0
  43. wayfolio/resources/workspace/assets/amap-icons/badges/line-m16.png +0 -0
  44. wayfolio/resources/workspace/assets/amap-icons/badges/line-m4.png +0 -0
  45. wayfolio/resources/workspace/assets/amap-icons/badges/line-m9.png +0 -0
  46. wayfolio/resources/workspace/assets/amap-icons/badges/metro.png +0 -0
  47. wayfolio/resources/workspace/assets/amap-icons/badges/parking.png +0 -0
  48. wayfolio/resources/workspace/assets/amap-icons/badges/shop.png +0 -0
  49. wayfolio/resources/workspace/assets/amap-icons/badges/sight.png +0 -0
  50. wayfolio/resources/workspace/assets/amap-icons/badges/station-16.png +0 -0
  51. wayfolio/resources/workspace/assets/amap-icons/badges/station-4-9-16.png +0 -0
  52. wayfolio/resources/workspace/assets/amap-icons/badges/station-4.png +0 -0
  53. wayfolio/resources/workspace/assets/amap-icons/badges/station-9.png +0 -0
  54. wayfolio/resources/workspace/assets/amap-icons/badges/toilet.png +0 -0
  55. wayfolio/resources/workspace/assets/amap-icons/lines/m16.png +0 -0
  56. wayfolio/resources/workspace/assets/amap-icons/lines/m4.png +0 -0
  57. wayfolio/resources/workspace/assets/amap-icons/lines/m6.png +0 -0
  58. wayfolio/resources/workspace/assets/amap-icons/lines/m9.png +0 -0
  59. wayfolio/resources/workspace/assets/amap-icons/manifest.yaml +89 -0
  60. wayfolio/resources/workspace/assets/amap-icons/source/fa6-bus.svg +1 -0
  61. wayfolio/resources/workspace/assets/amap-icons/source/fa6-food.svg +1 -0
  62. wayfolio/resources/workspace/assets/amap-icons/source/fa6-parking.svg +1 -0
  63. wayfolio/resources/workspace/assets/amap-icons/source/fa6-shop.svg +1 -0
  64. wayfolio/resources/workspace/assets/amap-icons/source/fa6-sight.svg +1 -0
  65. wayfolio/resources/workspace/assets/amap-icons/source/fa6-toilet.svg +1 -0
  66. wayfolio/resources/workspace/assets/amap-icons/source/fa6-train-subway.svg +1 -0
  67. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/bus.png +0 -0
  68. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/food.png +0 -0
  69. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/line-label-pill.png +0 -0
  70. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/metro.png +0 -0
  71. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/parking.png +0 -0
  72. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/shop.png +0 -0
  73. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/sight.png +0 -0
  74. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/station-16.png +0 -0
  75. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/station-4-9-16.png +0 -0
  76. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/station-4.png +0 -0
  77. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/station-9.png +0 -0
  78. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/badge/badges/toilet.png +0 -0
  79. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/bus.png +0 -0
  80. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/food.png +0 -0
  81. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/line-label-pill.png +0 -0
  82. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/metro.png +0 -0
  83. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/parking.png +0 -0
  84. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/shop.png +0 -0
  85. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/sight.png +0 -0
  86. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/station-16.png +0 -0
  87. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/station-4-9-16.png +0 -0
  88. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/station-4.png +0 -0
  89. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/station-9.png +0 -0
  90. wayfolio/resources/workspace/assets/amap-icons/themes/mediterranean_summer_plus/ring/badges/toilet.png +0 -0
  91. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/bus.png +0 -0
  92. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/food.png +0 -0
  93. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/line-label-pill.png +0 -0
  94. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/metro.png +0 -0
  95. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/parking.png +0 -0
  96. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/shop.png +0 -0
  97. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/sight.png +0 -0
  98. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/station-16.png +0 -0
  99. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/station-4-9-16.png +0 -0
  100. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/station-4.png +0 -0
  101. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/station-9.png +0 -0
  102. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/badge/badges/toilet.png +0 -0
  103. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/bus.png +0 -0
  104. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/food.png +0 -0
  105. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/line-label-pill.png +0 -0
  106. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/metro.png +0 -0
  107. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/parking.png +0 -0
  108. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/shop.png +0 -0
  109. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/sight.png +0 -0
  110. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/station-16.png +0 -0
  111. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/station-4-9-16.png +0 -0
  112. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/station-4.png +0 -0
  113. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/station-9.png +0 -0
  114. wayfolio/resources/workspace/assets/amap-icons/themes/midnight_blue/ring/badges/toilet.png +0 -0
  115. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/bus.png +0 -0
  116. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/food.png +0 -0
  117. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/line-label-pill.png +0 -0
  118. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/metro.png +0 -0
  119. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/parking.png +0 -0
  120. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/shop.png +0 -0
  121. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/sight.png +0 -0
  122. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/station-16.png +0 -0
  123. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/station-4-9-16.png +0 -0
  124. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/station-4.png +0 -0
  125. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/station-9.png +0 -0
  126. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/badge/badges/toilet.png +0 -0
  127. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/bus.png +0 -0
  128. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/food.png +0 -0
  129. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/line-label-pill.png +0 -0
  130. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/metro.png +0 -0
  131. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/parking.png +0 -0
  132. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/shop.png +0 -0
  133. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/sight.png +0 -0
  134. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/station-16.png +0 -0
  135. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/station-4-9-16.png +0 -0
  136. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/station-4.png +0 -0
  137. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/station-9.png +0 -0
  138. wayfolio/resources/workspace/assets/amap-icons/themes/paper_ink/ring/badges/toilet.png +0 -0
  139. wayfolio/resources/workspace/assets/beijing-subway-colors.json +53 -0
  140. wayfolio/resources/workspace/config/layers_booklet.yaml +19 -0
  141. wayfolio/resources/workspace/config/layers_poster.yaml +17 -0
  142. wayfolio/resources/workspace/config/paper_a0.yaml +12 -0
  143. wayfolio/resources/workspace/config/paper_a3.yaml +12 -0
  144. wayfolio/resources/workspace/config/paper_a4.yaml +12 -0
  145. wayfolio/resources/workspace/config/poi_layers.yaml +78 -0
  146. wayfolio/resources/workspace/config/source_regions.yaml +3 -0
  147. wayfolio/resources/workspace/config/style_default.yaml +29 -0
  148. wayfolio/resources/workspace/config/style_paper.yaml +34 -0
  149. wayfolio/resources/workspace/config/style_paper_b.yaml +13 -0
  150. wayfolio/resources/workspace/config/vector.yaml +9 -0
  151. wayfolio/resources/workspace/data/demo/boundary.geojson +38 -0
  152. wayfolio/resources/workspace/data/demo/card.yaml +17 -0
  153. wayfolio/resources/workspace/data/demo/display.yaml +38 -0
  154. wayfolio/resources/workspace/data/demo/footer.yaml +5 -0
  155. wayfolio/resources/workspace/data/demo/layout.yaml +224 -0
  156. wayfolio/resources/workspace/data/demo/legend.yaml +36 -0
  157. wayfolio/resources/workspace/data/demo/place.yaml +69 -0
  158. wayfolio/resources/workspace/data/demo/pois_amap.yaml +35 -0
  159. wayfolio/resources/workspace/data/demo/transit.yaml +3 -0
  160. wayfolio/resources/workspace/data/demo/transit_label.yaml +60 -0
  161. wayfolio/resources/workspace/data/demo/trip.yaml +8 -0
  162. wayfolio/resources/workspace/data/places.yaml +16 -0
  163. wayfolio/resources/workspace/themes/vector/mediterranean_summer_plus.json +33 -0
  164. wayfolio/resources/workspace/themes/vector/midnight_blue.json +35 -0
  165. wayfolio/resources/workspace/themes/vector/paper_ink.json +33 -0
  166. wayfolio/resources/workspace/typst/basemap.typ +23 -0
  167. wayfolio/resources/workspace/typst/basemap_book.typ +197 -0
  168. wayfolio/resources/workspace/typst/basemap_data.typ +65 -0
  169. wayfolio/resources/workspace/typst/components/.gitkeep +0 -0
  170. wayfolio/resources/workspace/typst/lib.typ +452 -0
  171. wayfolio/resources/workspace/typst/main.typ +26 -0
  172. wayfolio/resources/workspace/typst/poster.typ +540 -0
  173. wayfolio/resources/workspace/typst/poster_a3.typ +543 -0
  174. wayfolio/resources/workspace/typst/sample.typ +85 -0
  175. wayfolio/resources/workspace/typst/style_sheet.typ +165 -0
  176. wayfolio/routing.py +145 -0
  177. wayfolio/source.py +591 -0
  178. wayfolio/style.py +101 -0
  179. wayfolio/theme.py +183 -0
  180. wayfolio/theme_profiles.py +176 -0
  181. wayfolio/verify.py +86 -0
  182. wayfolio/workspace.py +37 -0
  183. wayfolio-0.1.0a1.dist-info/METADATA +289 -0
  184. wayfolio-0.1.0a1.dist-info/RECORD +188 -0
  185. wayfolio-0.1.0a1.dist-info/WHEEL +4 -0
  186. wayfolio-0.1.0a1.dist-info/entry_points.txt +2 -0
  187. wayfolio-0.1.0a1.dist-info/licenses/LICENSE +21 -0
  188. wayfolio-0.1.0a1.dist-info/licenses/NOTICE +27 -0
wayfolio/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """途册 Wayfolio —— 把公园与行程编译成可打印的地图册。"""
2
+
3
+ __version__ = "0.1.0a1"
wayfolio/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .launcher import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,23 @@
1
+ """底图 provider 集合。"""
2
+
3
+ from .provider import Basemap, Provider, effective_dpi, px_for
4
+ from .amap_static import AmapStaticProvider
5
+ from .amap_tiles import AmapTileProvider
6
+ from .osm_tiles import HOT_URL, OsmProvider
7
+ from .osm_full import OsmFullProvider
8
+ from .stub import StubProvider
9
+ from .vector import VectorProvider
10
+
11
+ __all__ = [
12
+ "Basemap",
13
+ "Provider",
14
+ "StubProvider",
15
+ "OsmProvider",
16
+ "HOT_URL",
17
+ "OsmFullProvider",
18
+ "VectorProvider",
19
+ "AmapStaticProvider",
20
+ "AmapTileProvider",
21
+ "px_for",
22
+ "effective_dpi",
23
+ ]
@@ -0,0 +1,109 @@
1
+ """高德静态图 provider(中文参考版,GCJ-02)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import httpx
11
+ from PIL import Image
12
+
13
+ from ..crs import BBox, bbox_to_mercator
14
+ from ..style import Style, apply_map_treatment
15
+ from .provider import Basemap
16
+
17
+ from ..paths import ROOT
18
+ CACHE = ROOT / "cache" / "basemap" / "amap"
19
+ WORLD = 2 * math.pi * 6378137.0
20
+ TILE = 256
21
+ MAX_ZOOM = 16 # 实测:scale=2 下 16 已是上限(约 0.92 m/px)
22
+
23
+
24
+ def _coverage(z: int) -> float:
25
+ """1024 逻辑像素在 zoom z 下覆盖的 Mercator 米数;scale=2 不改变覆盖。"""
26
+ return 1024 * WORLD / (TILE * 2**z)
27
+
28
+
29
+ class AmapStaticProvider:
30
+ name = "amap"
31
+
32
+ def __init__(self, key: str | None = None) -> None:
33
+ self.key = key or os.environ.get("AMAP_API_KEY_S") or os.environ.get("AMAP_KEY")
34
+ if not self.key:
35
+ raise ValueError("高德静态图需要 AMAP_API_KEY_S")
36
+
37
+ def fetch(
38
+ self,
39
+ bbox: BBox,
40
+ px: tuple[int, int],
41
+ dpi: float,
42
+ style: Style | None = None,
43
+ ) -> Basemap:
44
+ x0, y0, x1, y1 = bbox_to_mercator(bbox)
45
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
46
+ lon_c, lat_c = self._center_lonlat(cx, cy)
47
+
48
+ z = MAX_ZOOM
49
+ while z > 10 and _coverage(z) < max(x1 - x0, y1 - y0):
50
+ z -= 1
51
+ cov = _coverage(z)
52
+ span_px = 2048 # scale=2 的输出边长
53
+
54
+ left = span_px / 2 + (x0 - cx) / cov * span_px
55
+ right = span_px / 2 + (x1 - cx) / cov * span_px
56
+ top = span_px / 2 - (y1 - cy) / cov * span_px
57
+ bottom = span_px / 2 - (y0 - cy) / cov * span_px
58
+ left, right = max(0, left), min(span_px, right)
59
+ top, bottom = max(0, top), min(span_px, bottom)
60
+
61
+ key = hashlib.sha1(
62
+ f"{bbox.as_list()}|{px[0]}x{px[1]}|{z}".encode()
63
+ ).hexdigest()[:16]
64
+ CACHE.mkdir(parents=True, exist_ok=True)
65
+ path = CACHE / f"{key}.png"
66
+
67
+ if not path.exists():
68
+ resp = httpx.get(
69
+ "https://restapi.amap.com/v3/staticmap",
70
+ params={
71
+ "location": f"{lon_c:.6f},{lat_c:.6f}",
72
+ "zoom": str(z),
73
+ "size": "1024*1024",
74
+ "scale": "2",
75
+ "key": self.key,
76
+ },
77
+ timeout=30,
78
+ )
79
+ if not resp.headers.get("content-type", "").startswith("image/"):
80
+ raise ValueError(f"高德静态图失败:{resp.text[:120]}")
81
+ raw = CACHE / f"{key}-raw.png"
82
+ raw.write_bytes(resp.content)
83
+ img = Image.open(raw).convert("RGB")
84
+ img = img.crop((round(left), round(top), round(right), round(bottom)))
85
+ native_w = img.width
86
+ img = img.resize(px, Image.LANCZOS)
87
+ if style is not None:
88
+ img = apply_map_treatment(img, style)
89
+ img.save(path, optimize=True)
90
+ raw.unlink(missing_ok=True)
91
+ actual_dpi = native_w / (px[0] / dpi)
92
+ else:
93
+ img = Image.open(path)
94
+ actual_dpi = img.width / (px[0] / dpi)
95
+
96
+ return Basemap(
97
+ path=path,
98
+ bbox=bbox,
99
+ px=px,
100
+ dpi=round(actual_dpi, 1),
101
+ attribution="© 高德地图 · 参考版",
102
+ provider=self.name,
103
+ )
104
+
105
+ @staticmethod
106
+ def _center_lonlat(mx: float, my: float) -> tuple[float, float]:
107
+ lon = math.degrees(mx / 6378137.0)
108
+ lat = math.degrees(2 * math.atan(math.exp(my / 6378137.0)) - math.pi / 2)
109
+ return lon, lat
@@ -0,0 +1,191 @@
1
+ """高德栅格瓦片 provider(GCJ-02,中文注记):下载、缓存、拼接、裁切。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import os
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+ import numpy as np
13
+ from PIL import Image
14
+
15
+ from ..crs import BBox, bbox_to_mercator
16
+ from ..style import Style, apply_map_treatment
17
+ from .provider import Basemap
18
+
19
+ from ..paths import ROOT
20
+ TILE_CACHE = ROOT / "cache" / "basemap" / "amaptiles"
21
+ IMAGE_CACHE = ROOT / "cache" / "basemap" / "amapstyled"
22
+ DEFAULT_URL = "https://webrd0{s}.is.autonavi.com/appmaptile?lang={lang}&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
23
+ UA = "Mozilla/5.0 (wayfolio; personal map booklet)"
24
+
25
+ WORLD = 2 * math.pi * 6378137.0
26
+ TILE = 256
27
+
28
+
29
+ def _tile_x(lon: float, z: int) -> float:
30
+ return (lon + 180.0) / 360.0 * (2**z)
31
+
32
+
33
+ def _tile_y(lat: float, z: int) -> float:
34
+ rad = math.radians(lat)
35
+ n = math.log(math.tan(rad) + 1 / math.cos(rad))
36
+ return (1 - n / math.pi) / 2 * (2**z)
37
+
38
+
39
+ def choose_zoom(bbox: BBox, px: tuple[int, int], max_zoom: int = 18) -> int:
40
+ """选能覆盖目标像素密度的最粗 zoom(避免无谓下载)。"""
41
+ x0, _, x1, _ = bbox_to_mercator(bbox)
42
+ target_mpp = (x1 - x0) / px[0]
43
+ z = math.log2(WORLD / (TILE * target_mpp))
44
+ return max(1, min(max_zoom, math.ceil(z)))
45
+
46
+
47
+ def _is_flat_blue(tile: Image.Image) -> bool:
48
+ """高德对整块水面会返回单色瓦片,颜色常与相邻瓦片的水面不一致。"""
49
+ arr = np.asarray(tile)
50
+ spans = arr.max(axis=(0, 1)) - arr.min(axis=(0, 1))
51
+ if int(spans.max()) > 2:
52
+ return False
53
+ red, green, blue = (int(v) for v in arr[0, 0])
54
+ return blue > red + 20 and blue > green + 10
55
+
56
+
57
+ def _repair_flat_water(canvas: Image.Image, blocks: list[tuple[int, int]]) -> Image.Image:
58
+ """把单色水面瓦片统一到页面里真实水面的颜色,消掉方格接缝。"""
59
+ if not blocks:
60
+ return canvas
61
+ arr = np.array(canvas)
62
+ flat = np.zeros(arr.shape[:2], dtype=bool)
63
+ for left, top in blocks:
64
+ flat[top : top + TILE, left : left + TILE] = True
65
+ sample = arr[~flat]
66
+ if sample.shape[0] < 2000:
67
+ return canvas
68
+ step = max(1, sample.shape[0] // 200_000)
69
+ sample = sample[::step]
70
+ red, green, blue = (sample[:, c].astype(int) for c in range(3))
71
+ water = (blue > red + 15) & (blue > green + 8) & (blue > 140)
72
+ if water.sum() < 500:
73
+ return canvas
74
+ ref = np.median(sample[water], axis=0)
75
+ changed = False
76
+ for left, top in blocks:
77
+ colour = arr[top, left].astype(int)
78
+ if np.abs(colour - ref).max() > 4:
79
+ arr[top : top + TILE, left : left + TILE] = ref.astype(np.uint8)
80
+ changed = True
81
+ return Image.fromarray(arr) if changed else canvas
82
+
83
+
84
+ class AmapTileProvider:
85
+ name = "amap"
86
+
87
+ def __init__(self, url: str | None = None, pause: float = 0.15, lang: str = "zh_cn") -> None:
88
+ self.url = url or os.environ.get("WAYFOLIO_AMAP_TILE_URL", DEFAULT_URL)
89
+ self.lang = lang
90
+ self.name = "amap-en" if lang.startswith("en") else "amap"
91
+ self.pause = pause
92
+ self._n = 0
93
+ self._missing: list[tuple[int, int, int]] = []
94
+ self._client = httpx.Client(
95
+ timeout=20, headers={"User-Agent": UA}, follow_redirects=True
96
+ )
97
+
98
+ def _tile(self, z: int, x: int, y: int) -> Image.Image | None:
99
+ # 按语言分目录:lang=en 与 zh_cn 是两套瓦片,不能共用缓存
100
+ path = TILE_CACHE / self.lang / str(z) / str(x) / f"{y}.png"
101
+ if path.exists():
102
+ try:
103
+ return Image.open(path).convert("RGB")
104
+ except OSError:
105
+ path.unlink(missing_ok=True)
106
+ self._n += 1
107
+ url = self.url.format(z=z, x=x, y=y, s=1 + self._n % 4, lang=self.lang)
108
+ try:
109
+ resp = self._client.get(url)
110
+ if resp.status_code != 200 or not resp.headers.get(
111
+ "content-type", ""
112
+ ).startswith("image/"):
113
+ self._missing.append((z, x, y))
114
+ return None
115
+ path.parent.mkdir(parents=True, exist_ok=True)
116
+ path.write_bytes(resp.content)
117
+ time.sleep(self.pause)
118
+ return Image.open(path).convert("RGB")
119
+ except Exception: # noqa: BLE001 - 单块失败记录后由 fetch 统一报错
120
+ self._missing.append((z, x, y))
121
+ return None
122
+
123
+ def fetch(
124
+ self,
125
+ bbox: BBox,
126
+ px: tuple[int, int],
127
+ dpi: float,
128
+ style: Style | None = None,
129
+ zoom: int | None = None,
130
+ ) -> Basemap:
131
+ z = zoom if zoom is not None else choose_zoom(bbox, px)
132
+ z = max(1, min(18, z))
133
+ self._missing = []
134
+ wx0, wy1 = _tile_x(bbox.west, z), _tile_y(bbox.north, z)
135
+ wx1, wy0 = _tile_x(bbox.east, z), _tile_y(bbox.south, z)
136
+
137
+ tx0, ty0 = math.floor(wx0), math.floor(wy1)
138
+ tx1, ty1 = math.floor(wx1), math.floor(wy0)
139
+
140
+ cols, rows = tx1 - tx0 + 1, ty1 - ty0 + 1
141
+ canvas = Image.new("RGB", (cols * TILE, rows * TILE), "#F7F3EA")
142
+ flat_blocks: list[tuple[int, int]] = []
143
+ for ty in range(ty0, ty1 + 1):
144
+ for tx in range(tx0, tx1 + 1):
145
+ tile = self._tile(z, tx, ty)
146
+ if tile is not None:
147
+ position = ((tx - tx0) * TILE, (ty - ty0) * TILE)
148
+ canvas.paste(tile, position)
149
+ if _is_flat_blue(tile):
150
+ flat_blocks.append(position)
151
+ canvas = _repair_flat_water(canvas, flat_blocks)
152
+ if self._missing:
153
+ sample = "、".join(f"{z}/{x}/{y}" for z, x, y in self._missing[:3])
154
+ raise RuntimeError(
155
+ f"{len(self._missing)} 块高德瓦片下载失败({sample}…);"
156
+ "已下载的会留在缓存,重跑即可补齐"
157
+ )
158
+
159
+ # 把页面 bbox 的经纬度换成拼接图上的像素位置
160
+ left = (wx0 - tx0) * TILE
161
+ right = (wx1 - tx0) * TILE
162
+ top = (wy1 - ty0) * TILE
163
+ bottom = (wy0 - ty0) * TILE
164
+
165
+ crop = canvas.crop(
166
+ (round(left), round(top), round(right), round(bottom))
167
+ ).resize(px, Image.LANCZOS)
168
+ if style is not None:
169
+ crop = apply_map_treatment(crop, style)
170
+
171
+ tag = "" if style is None else f"-{style.name}"
172
+ key = hashlib.sha1(
173
+ f"{bbox.as_list()}|{px[0]}x{px[1]}|{z}|{self.url}|{self.lang}{tag}".encode()
174
+ ).hexdigest()[:16]
175
+ IMAGE_CACHE.mkdir(parents=True, exist_ok=True)
176
+ out = IMAGE_CACHE / f"amap-{key}.png"
177
+ crop.save(out, optimize=True)
178
+
179
+ attribution = (
180
+ "© AMap · personal use"
181
+ if self.lang.startswith("en")
182
+ else "© 高德地图 · 个人使用"
183
+ )
184
+ return Basemap(
185
+ path=out,
186
+ bbox=bbox,
187
+ px=px,
188
+ dpi=dpi,
189
+ attribution=attribution,
190
+ provider=self.name,
191
+ )
@@ -0,0 +1,106 @@
1
+ """OSM 全细节矢量底图:OpenFreeMap 底图 + Protomaps z15 中文标注。
2
+
3
+ 瓦片由 tools/osm_full/fetch_tiles.py 从 Protomaps 日构建里按 bbox 抽取,
4
+ 本 provider 只读本地瓦片,用 MapLibre + Chromium 渲成位图。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import subprocess
13
+ from pathlib import Path
14
+
15
+ from ..crs import BBox
16
+ from .provider import Basemap
17
+
18
+ from ..paths import ROOT
19
+ CACHE = ROOT / "cache" / "osm_full"
20
+ TILES = CACHE / "tiles"
21
+ TOOL = ROOT / "tools" / "vector" / "osm_full" / "render.cjs"
22
+
23
+
24
+ def _tile_range(bbox: BBox, z: int) -> tuple[int, int, int, int]:
25
+ n = 2**z
26
+
27
+ def tx(lon: float) -> int:
28
+ return int((lon + 180.0) / 360.0 * n)
29
+
30
+ def ty(lat: float) -> int:
31
+ rad = math.radians(lat)
32
+ return int((1 - math.asinh(math.tan(rad)) / math.pi) / 2 * n)
33
+
34
+ return tx(bbox.west), ty(bbox.north), tx(bbox.east), ty(bbox.south)
35
+
36
+
37
+ def _missing_tiles(bbox: BBox, min_zoom: int = 11, max_zoom: int = 15) -> list[tuple[int, int, int]]:
38
+ missing: list[tuple[int, int, int]] = []
39
+ for zoom in range(min_zoom, max_zoom + 1):
40
+ x0, y0, x1, y1 = _tile_range(bbox, zoom)
41
+ missing.extend(
42
+ (zoom, x, y)
43
+ for x in range(x0, x1 + 1)
44
+ for y in range(y0, y1 + 1)
45
+ if not (TILES / str(zoom) / str(x) / f"{y}.mvt").exists()
46
+ )
47
+ return missing
48
+
49
+
50
+ class OsmFullProvider:
51
+ name = "osm-full"
52
+
53
+ def __init__(self, style: str | None = None) -> None:
54
+ self.style = style
55
+
56
+ def fetch(
57
+ self,
58
+ bbox: BBox,
59
+ px: tuple[int, int],
60
+ dpi: float,
61
+ style=None,
62
+ ) -> Basemap:
63
+ missing = _missing_tiles(bbox)
64
+ if missing:
65
+ sample = "、".join(f"{z}/{x}/{y}" for z, x, y in missing[:3])
66
+ raise RuntimeError(
67
+ f"缺少 {len(missing)} 块 OSM 全细节瓦片({sample}…);"
68
+ "先运行 python tools/osm_full/fetch_tiles.py"
69
+ )
70
+
71
+ style_file = ROOT / "tools" / "vector" / "osm_full" / "hybrid2_style.json"
72
+ style_tag = hashlib.sha1(style_file.read_bytes()).hexdigest()[:8]
73
+ key = hashlib.sha1(
74
+ f"{bbox.as_list()}|{px[0]}x{px[1]}|{self.style or 'hybrid2'}|{style_tag}".encode()
75
+ ).hexdigest()[:16]
76
+ out = CACHE / "render" / f"{key}.png"
77
+ if not out.exists():
78
+ out.parent.mkdir(parents=True, exist_ok=True)
79
+ # 1028 CSS 宽适合 A4;A0 用 2000 宽把注记放大到可读
80
+ base = 1028 if px[0] <= 2400 else 2000
81
+ scale = px[0] / base
82
+ css_h = max(1, round(px[1] / scale))
83
+ cfg = {
84
+ "bbox": bbox.as_list(),
85
+ "cssWidth": base,
86
+ "cssHeight": css_h,
87
+ "scale": scale,
88
+ "out": str(out),
89
+ }
90
+ if self.style:
91
+ cfg["style"] = self.style
92
+ subprocess.run(
93
+ ["node", str(TOOL), json.dumps(cfg)],
94
+ check=True,
95
+ capture_output=True,
96
+ text=True,
97
+ )
98
+
99
+ return Basemap(
100
+ path=out,
101
+ bbox=bbox,
102
+ px=px,
103
+ dpi=dpi,
104
+ attribution="© OpenStreetMap contributors · Protomaps / OpenFreeMap",
105
+ provider=self.name,
106
+ )
@@ -0,0 +1,184 @@
1
+ """OSM 瓦片 provider:下载、缓存、拼接、按页面 bbox 裁切。
2
+
3
+ 默认走 tile.openstreetmap.de:它的样式内嵌中日韩字形,中文地名不会出现方块。
4
+ 缓存按瓦片主机分目录,换样式不会串味。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import math
11
+ import os
12
+ import time
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from io import BytesIO
15
+ from pathlib import Path
16
+ from urllib.parse import urlparse
17
+
18
+ import httpx
19
+ from PIL import Image
20
+
21
+ from ..crs import BBox, bbox_to_mercator
22
+ from ..style import Style, apply_map_treatment
23
+ from .provider import Basemap
24
+
25
+ from ..paths import ROOT
26
+ TILE_CACHE = ROOT / "cache" / "basemap" / "osm"
27
+ IMAGE_CACHE = ROOT / "cache" / "basemap" / "styled"
28
+ DEFAULT_URL = "https://tile.openstreetmap.de/{z}/{x}/{y}.png"
29
+ # HOT 样式只渲染本地名(中文),不带 osml10n 转写;标签比 .de 稀。
30
+ HOT_URL = "https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png"
31
+ UA = "wayfolio/0.0.1 (personal map booklet)"
32
+
33
+ WORLD = 2 * math.pi * 6378137.0
34
+ TILE = 256
35
+
36
+
37
+ def _tile_x(lon: float, z: int) -> float:
38
+ return (lon + 180.0) / 360.0 * (2**z)
39
+
40
+
41
+ def _tile_y(lat: float, z: int) -> float:
42
+ rad = math.radians(lat)
43
+ n = math.log(math.tan(rad) + 1 / math.cos(rad))
44
+ return (1 - n / math.pi) / 2 * (2**z)
45
+
46
+
47
+ def choose_zoom(bbox: BBox, px: tuple[int, int], max_zoom: int = 19) -> int:
48
+ """选能覆盖目标像素密度的最粗 zoom(避免无谓下载)。"""
49
+ x0, _, x1, _ = bbox_to_mercator(bbox)
50
+ target_mpp = (x1 - x0) / px[0]
51
+ z = math.log2(WORLD / (TILE * target_mpp))
52
+ return max(1, min(max_zoom, math.ceil(z)))
53
+
54
+
55
+ class OsmProvider:
56
+ name = "osm"
57
+
58
+ def __init__(
59
+ self,
60
+ url: str | None = None,
61
+ pause: float = 0.5,
62
+ name: str | None = None,
63
+ cache_key: str | None = None,
64
+ attribution: str | None = None,
65
+ max_zoom: int = 19,
66
+ timeout: float = 20,
67
+ shards: str = "a",
68
+ workers: int = 1,
69
+ ) -> None:
70
+ self.url = url or os.environ.get("WAYFOLIO_OSM_TILE_URL", DEFAULT_URL)
71
+ # 缓存目录默认按主机名;HOT 与 osmfr 同主机不同路径,需显式给 cache_key
72
+ self.style = cache_key or urlparse(self.url).netloc or "osm"
73
+ self.name = name or type(self).name
74
+ self.attribution = attribution or f"© OpenStreetMap contributors · {self.style}"
75
+ self.max_zoom = max_zoom
76
+ self.pause = pause
77
+ self.shards = shards or "a"
78
+ self.workers = max(1, workers)
79
+ self._n = 0
80
+ self._missing: list[tuple[int, int, int]] = []
81
+ self._client = httpx.Client(
82
+ timeout=timeout, headers={"User-Agent": UA}, follow_redirects=True
83
+ )
84
+
85
+ def _tile(self, z: int, x: int, y: int) -> Image.Image | None:
86
+ # 串行 + 0.5s 间隔 ≈ 2 req/s,符合 OSM 瓦片使用政策;缓存命中时不等待
87
+ path = TILE_CACHE / self.style / str(z) / str(x) / f"{y}.png"
88
+ if path.exists():
89
+ try:
90
+ return Image.open(path).convert("RGB")
91
+ except OSError:
92
+ path.unlink(missing_ok=True)
93
+ shard = self.shards[self._n % len(self.shards)]
94
+ self._n += 1
95
+ url = self.url.format(z=z, x=x, y=y, s=shard)
96
+ for attempt in range(1, 4):
97
+ try:
98
+ resp = self._client.get(url)
99
+ except Exception: # noqa: BLE001 - 网络抖动重试
100
+ time.sleep(1.5 * attempt)
101
+ continue
102
+ if resp.status_code == 200 and resp.headers.get(
103
+ "content-type", ""
104
+ ).startswith("image/"):
105
+ try:
106
+ tile = Image.open(BytesIO(resp.content)).convert("RGB")
107
+ except OSError:
108
+ time.sleep(1.5 * attempt)
109
+ continue
110
+ if tile.size != (TILE, TILE):
111
+ time.sleep(1.5 * attempt)
112
+ continue
113
+ path.parent.mkdir(parents=True, exist_ok=True)
114
+ path.write_bytes(resp.content)
115
+ time.sleep(self.pause)
116
+ return tile
117
+ # 429/503 是限流,退避久一点;其它错误也重试
118
+ time.sleep(5 * attempt if resp.status_code in (429, 503) else 1.5 * attempt)
119
+ self._missing.append((z, x, y))
120
+ return None
121
+
122
+ def fetch(
123
+ self,
124
+ bbox: BBox,
125
+ px: tuple[int, int],
126
+ dpi: float,
127
+ style: Style | None = None,
128
+ ) -> Basemap:
129
+ z = choose_zoom(bbox, px, max_zoom=self.max_zoom)
130
+ self._missing = []
131
+ wx0, wy1 = _tile_x(bbox.west, z), _tile_y(bbox.north, z)
132
+ wx1, wy0 = _tile_x(bbox.east, z), _tile_y(bbox.south, z)
133
+
134
+ tx0, ty0 = math.floor(wx0), math.floor(wy1)
135
+ tx1, ty1 = math.floor(wx1), math.floor(wy0)
136
+
137
+ cols, rows = tx1 - tx0 + 1, ty1 - ty0 + 1
138
+ canvas = Image.new("RGB", (cols * TILE, rows * TILE), "#F7F3EA")
139
+ positions = [(tx, ty) for ty in range(ty0, ty1 + 1) for tx in range(tx0, tx1 + 1)]
140
+ if self.workers > 1:
141
+ # 并发数 ≤2、每块间隔 pause,总速率仍受控(OSM 政策:≤2 线程 / ≤2 req/s)
142
+ with ThreadPoolExecutor(max_workers=self.workers) as pool:
143
+ tiles = list(pool.map(lambda pos: self._tile(z, pos[0], pos[1]), positions))
144
+ else:
145
+ tiles = [self._tile(z, tx, ty) for tx, ty in positions]
146
+ for (tx, ty), tile in zip(positions, tiles):
147
+ if tile is not None:
148
+ canvas.paste(tile, ((tx - tx0) * TILE, (ty - ty0) * TILE))
149
+
150
+ if self._missing:
151
+ sample = "、".join(f"{z}/{x}/{y}" for z, x, y in self._missing[:3])
152
+ raise RuntimeError(
153
+ f"{len(self._missing)} 块 OSM 瓦片下载失败({sample}…);"
154
+ "已下载的会留在缓存,重跑即可补齐"
155
+ )
156
+
157
+ # 把页面 bbox 的经纬度换成拼接图上的像素位置
158
+ left = (wx0 - tx0) * TILE
159
+ right = (wx1 - tx0) * TILE
160
+ top = (wy1 - ty0) * TILE
161
+ bottom = (wy0 - ty0) * TILE
162
+
163
+ crop = canvas.crop(
164
+ (round(left), round(top), round(right), round(bottom))
165
+ ).resize(px, Image.LANCZOS)
166
+ if style is not None:
167
+ crop = apply_map_treatment(crop, style)
168
+
169
+ tag = "" if style is None else f"-{style.name}"
170
+ key = hashlib.sha1(
171
+ f"{bbox.as_list()}|{px[0]}x{px[1]}|{z}|{self.url}{tag}".encode()
172
+ ).hexdigest()[:16]
173
+ IMAGE_CACHE.mkdir(parents=True, exist_ok=True)
174
+ out = IMAGE_CACHE / f"osm-{key}.png"
175
+ crop.save(out, optimize=True)
176
+
177
+ return Basemap(
178
+ path=out,
179
+ bbox=bbox,
180
+ px=px,
181
+ dpi=dpi,
182
+ attribution=self.attribution,
183
+ provider=self.name,
184
+ )
@@ -0,0 +1,44 @@
1
+ """底图 provider 接口与共用的像素尺寸计算。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Protocol
8
+
9
+ from ..crs import BBox
10
+ from ..grid import PaperProfile
11
+ from ..style import Style
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class Basemap:
16
+ path: Path
17
+ bbox: BBox
18
+ px: tuple[int, int]
19
+ dpi: float
20
+ attribution: str
21
+ provider: str
22
+
23
+
24
+ class Provider(Protocol):
25
+ name: str
26
+
27
+ def fetch(
28
+ self,
29
+ bbox: BBox,
30
+ px: tuple[int, int],
31
+ dpi: float,
32
+ style: Style | None = None,
33
+ ) -> Basemap: ...
34
+
35
+
36
+ def px_for(paper: PaperProfile, dpi: int = 150) -> tuple[int, int]:
37
+ """按版心尺寸与目标 DPI 算像素。"""
38
+ w = round(paper.content_w_mm / 25.4 * dpi)
39
+ h = round(paper.content_h_mm / 25.4 * dpi)
40
+ return w, h
41
+
42
+
43
+ def effective_dpi(paper: PaperProfile, px: tuple[int, int]) -> float:
44
+ return px[0] / (paper.content_w_mm / 25.4)