From bd41866a3d54992313c84a7b2f5008753b22b0be Mon Sep 17 00:00:00 2001 From: NekoYume517 <3146527494@qq.com> Date: Sat, 14 Nov 2026 20:31:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=AD=A5=E8=A1=8C=E8=B7=9D=E7=A6=BB?= =?UTF-8?q?=E6=94=B9=E7=94=A8=E7=99=BE=E5=BA=A6=E8=BD=BB=E9=87=8F=E7=BA=A7?= =?UTF-8?q?=E8=B7=AF=E7=BA=BF=E8=A7=84=E5=88=92=EF=BC=88=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E9=81=93=E8=B7=AF=E8=B7=9D=E7=A6=BB=20+=20=E8=80=97=E6=97=B6?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 后端 - 新增 walk_route.py:调 directionlite/v1/walking,coord_type=gcj02(与上游车辆同坐标系) - AK 开了 SN 校验时自动带 timestamp 并按 SN 规则签名;官方样例与社区两种算法都实现, 211 时自动换另一种(实测:官方算法 + timestamp 可通过) - 结果按起终点(4 位小数)缓存 7 天;按 3 QPS 配额做 350ms 节流 - 没配 AK / 240 / 超时 / 配额用尽一律退回本地估算(直线 ×1.3,75 米/分钟),卡片不会空 - 新增 /api/walk_route(需登录,按 IP 60 次/分钟限流) - 管理端新增 /api/admin/route_key(GET 回显,SK 只给尾号)、POST 保存、POST 测试连通 ## 前端 - 车辆卡片:先显示直线估算,再异步换成真实道路距离与耗时 顺序:后端接口(有 AK 时,命中缓存最快)→ 浏览器端 BMapGL.WalkingRoute(现成浏览器 AK) → 都失败则保留直线估算。解析 SDK 返回的「1.6公里 / 23分钟」字符串。 - 管理后台顶部新增「🚶 步行路线 AK」按钮 + 配置弹窗(保存 / 测试连通 / 清空 SK) ## 配置 - server_config.json: baidu_route_ak / baidu_route_sk(已 gitignore) - 或环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK 实测(校内两点):直线 615 米 -> 百度 1015 米 / 868 秒(14.5 分钟)。 新增 tests/test_walk_route.py(15 条);全量 136 pytest + 29 node 通过。 --- .gitignore | 4 +- routes/admin.py | 43 +++++ routes/map_api.py | 34 ++++ scripts/probe_baidu_route.py | 52 ++++++ static/js/map.js | 101 ++++++++++++ templates/admin.html | 48 ++++++ tests/test_walk_route.py | 172 +++++++++++++++++++ walk_route.py | 311 +++++++++++++++++++++++++++++++++++ 8 files changed, 764 insertions(+), 1 deletion(-) create mode 100644 scripts/probe_baidu_route.py create mode 100644 tests/test_walk_route.py create mode 100644 walk_route.py diff --git a/.gitignore b/.gitignore index fc2041d..3da2218 100644 --- a/.gitignore +++ b/.gitignore @@ -26,4 +26,6 @@ update.zip *.crt *.ca-bundle token_config.txt -*.db \ No newline at end of file +*.db +artifacts/ +walk_cache.db diff --git a/routes/admin.py b/routes/admin.py index 2fd9c1f..c4bf098 100644 --- a/routes/admin.py +++ b/routes/admin.py @@ -397,6 +397,49 @@ def admin_api_save_token(): return jsonify({"rtn_code": 500, "message": "保存失败"}) +@bp.route("/api/admin/route_key", methods=["GET"]) +@admin_required +def admin_api_route_key(): + """步行路线规划用的百度 AK/SK(服务端密钥,SK 只回显尾号)。""" + import walk_route + return jsonify({"rtn_code": 0, "data": walk_route.masked_credentials()}) + + +@bp.route("/api/admin/route_key", methods=["POST"]) +@admin_required +def admin_api_route_key_save(): + """保存 AK/SK。sk 不传=保持原值,传空串=清空。""" + import walk_route + data = request.get_json() or {} + ak = str(data.get("ak") or "").strip() + sk = data.get("sk", None) + if sk is not None: + sk = str(sk).strip() + if not ak: + return jsonify({"rtn_code": 400, "message": "AK 不能为空(不需要可清空后关闭)"}) + if not walk_route.save_credentials(ak, sk): + return jsonify({"rtn_code": 500, "message": "保存失败"}) + return jsonify({"rtn_code": 0, "message": "百度步行路线 AK/SK 已保存", + "data": walk_route.masked_credentials()}) + + +@bp.route("/api/admin/route_key/test", methods=["POST"]) +@admin_required +def admin_api_route_key_test(): + """用当前 AK/SK 真打一次百度,返回距离/耗时或具体错误。""" + import walk_route + if not walk_route.is_enabled(): + return jsonify({"rtn_code": 400, "message": "还没配置 AK"}) + got = walk_route.get_walk_route(36.529440, 116.783740, + 36.534240, 116.787190, use_cache=False) + if got.get("source") == "baidu": + return jsonify({"rtn_code": 0, + "message": f"连通成功:{got['distance']} 米 / {got['duration']} 秒", + "data": got}) + return jsonify({"rtn_code": 500, + "message": f"百度返回失败(已退回估算):{got}"}) + + @bp.route("/api/admin/strict_mode", methods=["GET"]) @admin_required def admin_api_get_strict_mode(): diff --git a/routes/map_api.py b/routes/map_api.py index bfca75c..eadffda 100644 --- a/routes/map_api.py +++ b/routes/map_api.py @@ -266,6 +266,40 @@ def api_config(): }) +@bp.route("/api/walk_route") +def api_walk_route(): + """步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。 + + 参数:origin_lat/origin_lng/dest_lat/dest_lng,**全部 GCJ02** + (前端要把 BD09 的我方位置先转 GCJ02 再传)。 + 返回:{rtn_code:0, data:{distance, duration, source}} + source = baidu(实时)/ cache(命中缓存)/ estimate(百度不可用时的本地估算) + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401 + + from routes.auth import _client_ip + from rate_limit import hit as rl_hit + # 保护百度配额:同一 IP 每分钟 60 次(正常点卡片远低于此) + if not rl_hit(("walk_route", _client_ip()), 60, 60): + return jsonify({"rtn_code": 429, "message": "请求过于频繁,请稍后再试"}), 429 + + try: + o_lat = float(request.args.get("origin_lat")) + o_lng = float(request.args.get("origin_lng")) + d_lat = float(request.args.get("dest_lat")) + d_lng = float(request.args.get("dest_lng")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"}) + + import walk_route + data = walk_route.get_walk_route(o_lat, o_lng, d_lat, d_lng) + response = jsonify({"rtn_code": 0, "data": data}) + response.headers["Cache-Control"] = "private, max-age=60" + return response + + # ========== 校园地点(订阅下拉 / 地点解析标签) ========== @bp.route("/api/map/freshness") def api_map_freshness(): diff --git a/scripts/probe_baidu_route.py b/scripts/probe_baidu_route.py new file mode 100644 index 0000000..b20eaed --- /dev/null +++ b/scripts/probe_baidu_route.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""百度「步行路线规划(轻量)」连通性探针。 + +用法(把你的 AK/SK 填进来): + PowerShell: + $env:BAIDU_ROUTE_AK="你的AK"; $env:BAIDU_ROUTE_SK="你的SK" + python scripts/probe_baidu_route.py + bash: + BAIDU_ROUTE_AK=... BAIDU_ROUTE_SK=... python scripts/probe_baidu_route.py + +会依次尝试两种 SN 算法(官方样例 / 社区写法),打印谁通了、返回多少米多少秒。 +通了就把 AK/SK 写进 server_config.json: + { "baidu_route_ak": "...", "baidu_route_sk": "..." } +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import walk_route + +# 校内两点(GCJ02):学生公寓附近 -> 教学楼附近 +ORIGIN = (36.529440, 116.783740) +DEST = (36.534240, 116.787190) + + +def main(): + ak = walk_route.get_ak() + sk = walk_route.get_sk() + print(f"AK: {ak[:8] + '…' if ak else '(未配置)'} SK: {'已配置(' + str(len(sk)) + '位)' if sk else '(未配置)'}") + if not ak: + print("先设置 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK 再跑") + return 2 + + ok = False + for mode in ("official", "simple"): + try: + got = walk_route._call_baidu(ak, sk, *ORIGIN, *DEST, mode) + print(f"[{mode:8}] ✔ 通过 distance={got['distance']} 米 " + f"duration={got['duration']} 秒 ({got['duration'] / 60:.1f} 分钟)") + ok = True + except Exception as exc: + print(f"[{mode:8}] ✘ {exc}") + + print("\n结论:", "SN 算法可用,把 AK/SK 写进 server_config.json 即可。" if ok else + "两种算法都没通,检查 AK 是否开启了「步行路线规划(轻量)」、SK 是否正确、配额是否用尽。") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/static/js/map.js b/static/js/map.js index 84a9641..fb052f4 100644 --- a/static/js/map.js +++ b/static/js/map.js @@ -1274,6 +1274,103 @@ return R * c; } + + // ========== 步行路线精算(真实道路距离 + 耗时)========== + const _walkRouteCache = new Map(); // `${code}|${我的坐标}` -> {d, t} + + function parseWalkDistance(text) { + const s = String(text || ""); + const km = s.match(/([\d.]+)\s*公里/); + if (km) return Math.round(parseFloat(km[1]) * 1000); + const m = s.match(/([\d.]+)\s*米/); + return m ? Math.round(parseFloat(m[1])) : 0; + } + + function parseWalkDuration(text) { + const s = String(text || ""); + let sec = 0; + const h = s.match(/([\d.]+)\s*小时/); + const min = s.match(/([\d.]+)\s*分钟/); + if (h) sec += Math.round(parseFloat(h[1]) * 3600); + if (min) sec += Math.round(parseFloat(min[1]) * 60); + return sec; + } + + async function refineWalkRoute(bike) { + const bikeCode = String((bike && bike.code) || ""); + if (!bikeCode) return; + const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker) + ? autoLocationMarker.getPosition() : null; + if (!me || !bike.latitude || !bike.longitude) return; + + const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4); + + const apply = (distanceM, seconds) => { + if (!selectedBike || String(selectedBike.code) !== bikeCode) return; // 已换车 + const distEl = document.getElementById("card-distance"); + const walkEl = document.getElementById("card-walk"); + const metaLeft = document.getElementById("card-meta-left"); + if (!distEl || !walkEl || !metaLeft) return; + distEl.textContent = distanceM < 1000 + ? `步行 ${Math.round(distanceM)} 米` + : `步行 ${(distanceM / 1000).toFixed(1)} 公里`; + walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`; + metaLeft.hidden = false; + }; + + const cached = _walkRouteCache.get(key); + if (cached) { apply(cached.d, cached.t); return; } + + // ① 后端(百度 Web 服务 API,需服务端 AK + SK,结果服务端缓存 7 天) + try { + const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) + ? coordtransform.bd09togcj02(me.lng, me.lat) : null; + if (gcj) { + const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0] + + "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude; + const resp = await fetch(url, { + headers: { "Authorization": "Bearer " + authToken } + }); + const data = await resp.json(); + const d = data && data.data; + if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0 + && (d.source === "baidu" || d.source === "cache")) { + _walkRouteCache.set(key, { d: d.distance, t: d.duration }); + apply(d.distance, d.duration); + return; + } + } + } catch (e) { /* 忽略,走 SDK */ } + + // ② 浏览器端 JS API 步行规划(现成浏览器 AK,返回 "1.6公里"/"23分钟" 字符串) + try { + if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && map) { + const plan = await new Promise(resolve => { + let done = false; + const finish = v => { if (!done) { done = true; resolve(v); } }; + const walk = new BMapGL.WalkingRoute(map, { + renderOptions: { map: null, panel: null }, + onSearchComplete: res => { + if (!res || res.getStatus() !== 0) return finish(null); + try { + const p = res.getPlan(0); + const d = parseWalkDistance(p.getDistance()); + const t = parseWalkDuration(p.getDuration()); + finish(d > 0 && t > 0 ? { d: d, t: t } : null); + } catch (err) { finish(null); } + } + }); + walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude)); + setTimeout(() => finish(null), 8000); + }); + if (plan) { + _walkRouteCache.set(key, plan); + apply(plan.d, plan.t); + } + } + } catch (e) { /* 保留直线估算 */ } + } + // 根据当前模式筛选车辆 function getFilteredBikes() { const allBikes = Object.values(markersData); @@ -3438,6 +3535,10 @@ metaLeft.hidden = !distText; } + // 异步换成「真实道路距离 + 步行耗时」:先问后端(百度轻量级路线规划), + // 后端没配 AK 就退到浏览器端 JS API,两者都失败则保留上面的直线估算。 + refineWalkRoute(bike); + // 车辆类型角标(红车 / 大车 / 小车) const kind = getBikeKind(bike); const kindEl = document.getElementById("card-kind"); diff --git a/templates/admin.html b/templates/admin.html index cb4e17a..b63a4ea 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -86,6 +86,7 @@ tr:hover{background:#3a3a3c}

🔧 管理后台

+ 退出
@@ -919,6 +920,53 @@ async function saveToken(){ if(d.rtn_code===0&&s.rtn_code===0) closeModal(); } +/* ============ 百度步行路线 AK/SK(服务端密钥) ============ */ +async function openRouteKeyModal(){ + openModal(`

🚶 步行路线 AK/SK

+

卡片上的「步行 X 米 / 约 Y 分钟」用它算真实道路距离。
+ 需服务端 AK + 已开通「步行路线规划(轻量)」;开了 SN 校验的要配套 SK。

+
加载中…
`); + const d=await api('/api/admin/route_key'); + const cur=d.data||{}; + document.getElementById('rk-loading').innerHTML=` + + + + + + `; +} +async function saveRouteKey(){ + const ak=document.getElementById('rk-ak').value.trim(); + const skInput=document.getElementById('rk-sk').value.trim(); + const clear=document.getElementById('rk-clear').checked; + let sk=skInput; + if(clear) sk=''; + else if(!skInput) sk=undefined; // 不传 = 保持原值 + const body={ak}; if(sk!==undefined) body.sk=sk; + const d=await api('/api/admin/route_key',{method:'POST',body:JSON.stringify(body)}); + toast(d.rtn_code===0?'✅ '+d.message:'❌ '+d.message, d.rtn_code===0?'success':'error'); + if(d.rtn_code===0) closeModal(); +} +async function testRouteKey(){ + const ak=document.getElementById('rk-ak').value.trim(); + const skInput=document.getElementById('rk-sk').value.trim(); + const clear=document.getElementById('rk-clear').checked; + // 先保存再测,避免测的是旧值 + const body={ak}; if(clear) body.sk=''; else if(skInput) body.sk=skInput; + const saved=await api('/api/admin/route_key',{method:'POST',body:JSON.stringify(body)}); + if(saved.rtn_code!==0){ toast('❌ '+saved.message,'error'); return; } + toast('已保存,正在测试…','success'); + const d=await api('/api/admin/route_key/test',{method:'POST',body:'{}'}); + toast((d.rtn_code===0?'✅ ':'❌ ')+d.message, d.rtn_code===0?'success':'error'); +} + /* 启动 */ renderTabs(); switchTab('users'); diff --git a/tests/test_walk_route.py b/tests/test_walk_route.py new file mode 100644 index 0000000..f02336b --- /dev/null +++ b/tests/test_walk_route.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""步行路线:百度轻量级路线规划 + 缓存 + 估算兜底。""" +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +import walk_route + +ORIGIN = (36.529440, 116.783740) +DEST = (36.534240, 116.787190) + + +class EstimateTests(unittest.TestCase): + def test_straight_line_is_expanded_by_detour_factor(self): + got = walk_route.estimate(*ORIGIN, *DEST) + self.assertEqual("estimate", got["source"]) + # 直线约 615 米 -> 乘 1.3 绕行系数 + self.assertGreater(got["straight"], 550) + self.assertLess(got["straight"], 700) + self.assertAlmostEqual(got["distance"], got["straight"] * 1.3, delta=2) + # 75 米/分钟 + self.assertAlmostEqual(got["duration"], got["distance"] / 75 * 60, delta=2) + + def test_bad_input_never_raises(self): + for args in ((None, None, None, None), ("a", "b", "c", "d")): + self.assertEqual("none", walk_route.estimate(*args)["source"]) + + +class QueryAndSnTests(unittest.TestCase): + PARAMS = {"ak": "X", "origin": "36.5,116.7", "destination": "36.4,116.6", + "coord_type": "gcj02"} + + def test_without_sk_no_sn(self): + q = walk_route.build_query(self.PARAMS, "") + self.assertNotIn("sn=", q) + self.assertIn("coord_type=gcj02", q) + + def test_two_sn_modes_differ_and_are_deterministic(self): + a1 = walk_route.build_query(self.PARAMS, "SK", "official") + a2 = walk_route.build_query(self.PARAMS, "SK", "official") + b = walk_route.build_query(self.PARAMS, "SK", "simple") + self.assertEqual(a1, a2) + self.assertIn("sn=", a1) + self.assertIn("sn=", b) + self.assertNotEqual(a1.split("sn=")[1], b.split("sn=")[1]) + + def test_params_are_key_sorted(self): + q = walk_route.build_query(self.PARAMS, "") + keys = [part.split("=")[0] for part in q.split("&")] + self.assertEqual(sorted(keys), keys) + + +class GetWalkRouteTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.path = Path(self.tmp.name) / "walk_cache.db" + self.patches = [ + patch.object(walk_route, "CACHE_PATH", self.path), + patch.object(walk_route, "_cache_ready", [False]), + patch.object(walk_route, "_last_call_at", [0.0]), + patch.object(walk_route, "MIN_INTERVAL_SECONDS", 0.0), + ] + for p in self.patches: + p.start() + self.addCleanup(p.stop) + + def _ok(self): + resp = Mock() + resp.raise_for_status = Mock() + resp.json = Mock(return_value={"status": 0, "result": {"routes": [ + {"distance": 820, "duration": 640}]}}) + return resp + + def test_without_ak_returns_estimate_and_never_calls_bbox(self): + with patch.object(walk_route, "get_ak", return_value=""), \ + patch("walk_route.requests.get") as http: + got = walk_route.get_walk_route(*ORIGIN, *DEST) + self.assertEqual("estimate", got["source"]) + http.assert_not_called() + + def test_baidu_success_then_served_from_cache(self): + with patch.object(walk_route, "get_ak", return_value="AK"), \ + patch.object(walk_route, "get_sk", return_value=""), \ + patch("walk_route.requests.get", return_value=self._ok()) as http: + first = walk_route.get_walk_route(*ORIGIN, *DEST) + second = walk_route.get_walk_route(*ORIGIN, *DEST) + self.assertEqual("baidu", first["source"]) + self.assertEqual(820, first["distance"]) + self.assertEqual(640, first["duration"]) + self.assertEqual("cache", second["source"]) + self.assertEqual(1, http.call_count) # 第二次没再打百度 + + def test_coord_type_is_gcj02(self): + with patch.object(walk_route, "get_ak", return_value="AK"), \ + patch.object(walk_route, "get_sk", return_value=""), \ + patch("walk_route.requests.get", return_value=self._ok()) as http: + walk_route.get_walk_route(*ORIGIN, *DEST) + url = http.call_args[0][0] + self.assertIn("coord_type=gcj02", url) + self.assertIn("directionlite/v1/walking", url) + + def test_sn_failure_retries_the_other_mode(self): + bad = Mock() + bad.raise_for_status = Mock() + bad.json = Mock(return_value={"status": 211, "message": "APP SN校验失败"}) + with patch.object(walk_route, "get_ak", return_value="AK"), \ + patch.object(walk_route, "get_sk", return_value="SK"), \ + patch.object(walk_route, "_SN_MODE", [None]), \ + patch("walk_route.requests.get", side_effect=[bad, self._ok()]) as http: + got = walk_route.get_walk_route(*ORIGIN, *DEST) + self.assertEqual("baidu", got["source"]) + self.assertEqual(2, http.call_count) # 官方算法失败后换了另一种 + + def test_app_disabled_falls_back_without_retry(self): + bad = Mock() + bad.raise_for_status = Mock() + bad.json = Mock(return_value={"status": 240, "message": "APP 服务被禁用"}) + with patch.object(walk_route, "get_ak", return_value="AK"), \ + patch.object(walk_route, "get_sk", return_value="SK"), \ + patch("walk_route.requests.get", return_value=bad) as http: + got = walk_route.get_walk_route(*ORIGIN, *DEST) + self.assertEqual("estimate", got["source"]) + self.assertEqual(1, http.call_count) # 240 不是 SN 问题,不重试 + + def test_network_error_falls_back(self): + with patch.object(walk_route, "get_ak", return_value="AK"), \ + patch.object(walk_route, "get_sk", return_value=""), \ + patch("walk_route.requests.get", side_effect=TimeoutError("boom")): + got = walk_route.get_walk_route(*ORIGIN, *DEST) + self.assertEqual("estimate", got["source"]) + self.assertGreater(got["distance"], 0) + + +class CredentialStorageTests(unittest.TestCase): + """管理端回显:SK 不能明文吐给前端。""" + + def test_masked_hides_sk(self): + with patch.object(walk_route, "get_ak", return_value="AK123"), \ + patch.object(walk_route, "get_sk", return_value="SK-abcdef1234"): + got = walk_route.masked_credentials() + self.assertEqual("AK123", got["ak"]) + self.assertTrue(got["sk_set"]) + self.assertEqual("1234", got["sk_tail"]) + self.assertNotIn("SK-abcdef", str(got)) + + def test_masked_when_empty(self): + with patch.object(walk_route, "get_ak", return_value=""), \ + patch.object(walk_route, "get_sk", return_value=""): + got = walk_route.masked_credentials() + self.assertFalse(got["enabled"]) + self.assertFalse(got["sk_set"]) + + +class DoublePrecisionCacheKeyTests(unittest.TestCase): + def test_nearby_points_share_a_cache_key(self): + a = walk_route._cache_key(36.529441, 116.783741, 36.534239, 116.787191) + b = walk_route._cache_key(36.529444, 116.783744, 36.534241, 116.787194) + self.assertEqual(a, b) # 10 米内视作同一对起终点 + + def test_far_points_differ(self): + a = walk_route._cache_key(36.5294, 116.7837, 36.5342, 116.7872) + b = walk_route._cache_key(36.5394, 116.7937, 36.5342, 116.7872) + self.assertNotEqual(a, b) + + +if __name__ == "__main__": + unittest.main() diff --git a/walk_route.py b/walk_route.py new file mode 100644 index 0000000..379b2a2 --- /dev/null +++ b/walk_route.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""百度「步行路线规划(轻量)」:真实道路距离 + 步行耗时。 + +为什么要它:卡片原来只会拿直线距离 ÷ 80 米/分钟估时间,绕楼绕围墙时明显偏乐观。 +百度轻量级路线规划接口(directionlite)直接给 `distance`(米)和 `duration`(秒), +且支持 `coord_type=gcj02` —— 正好和上游车辆坐标同一套,不用转换。 + +配额与限流(2026-11 实测控制台:0.5 万次/天,3 QPS): +- 结果按「起点+终点」四舍五入到 4 位小数(约 10 米)入库缓存 7 天; +- 进程内做 3 QPS 节流(保守取 350ms 间隔); +- 任何失败(没配 AK / 240 APP 服务被禁用 / 超时 / 配额耗尽)都退回本地估算, + 绝不让卡片空着。 + +配置(缺一即走估算): +- 环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK +- 或 server_config.json 里的 "baidu_route_ak" / "baidu_route_sk" +注意: +- 必须用**服务端**类型的 AK,且开通「步行路线规划(轻量)」; +- 页面里那个浏览器端 AK 调这个接口会返回 {"status":240,"message":"APP 服务被禁用"}(已实测); +- 若该 AK 在控制台开了「SN 校验」,请求必须带 sn(否则 211),所以需要配套的 SK, + 见 `_build_query()`。 +""" +import hashlib +import json +import math +import os +import sqlite3 +import threading +import time +from pathlib import Path +from urllib.parse import quote, quote_plus, urlencode + +import requests + +HOST = "https://api.map.baidu.com" +PATH = "/directionlite/v1/walking" +BASE_URL = HOST + PATH +CACHE_PATH = Path(__file__).parent / "walk_cache.db" +CACHE_TTL_SECONDS = 7 * 24 * 3600 +# 坐标精度:4 位小数 ≈ 11 米,够用且能显著提高缓存命中率 +COORD_PRECISION = 4 +# 3 QPS 配额,保守按 350ms 一次 +MIN_INTERVAL_SECONDS = 0.35 +REQUEST_TIMEOUT = 6 + +# 本地估算参数(百度不可用时兜底) +DETOUR_FACTOR = 1.3 # 直线 -> 道路的经验绕行系数 +WALK_METERS_PER_MIN = 75.0 # 4.5 km/h + +_lock = threading.Lock() +_last_call_at = [0.0] +_cache_ready = [False] + + +# ========== 配置 ========== + +def _server_config() -> dict: + try: + path = Path(__file__).parent / "server_config.json" + if path.exists(): + return json.loads(path.read_text("utf-8")) + except Exception: + pass + return {} + + +def get_ak() -> str: + """服务端 AK:环境变量优先,其次 server_config.json 的 baidu_route_ak。""" + env = (os.environ.get("BAIDU_ROUTE_AK") or "").strip() + if env: + return env + return str(_server_config().get("baidu_route_ak") or "").strip() + + +def get_sk() -> str: + """SN 校验用的 SK(私钥)。AK 未开 SN 校验时可以留空。""" + env = (os.environ.get("BAIDU_ROUTE_SK") or "").strip() + if env: + return env + return str(_server_config().get("baidu_route_sk") or "").strip() + + +def is_enabled() -> bool: + return bool(get_ak()) + + +def save_credentials(ak: str, sk: str = None) -> bool: + """把 AK/SK 写进 server_config.json(管理端弹窗用)。 + + sk 传 None 表示保持原值不动;传 "" 表示清空。 + """ + path = Path(__file__).parent / "server_config.json" + try: + cfg = {} + if path.exists(): + cfg = json.loads(path.read_text("utf-8")) or {} + cfg["baidu_route_ak"] = (ak or "").strip() + if sk is not None: + cfg["baidu_route_sk"] = (sk or "").strip() + path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8") + return True + except Exception as exc: + print(f"[步行路线] 保存 AK/SK 失败: {exc}") + return False + + +def masked_credentials() -> dict: + """给管理端回显用:AK 全量(管理员要看),SK 只回显尾 4 位。""" + ak = get_ak() + sk = get_sk() + return {"ak": ak, "sk_set": bool(sk), + "sk_tail": sk[-4:] if sk else "", "enabled": bool(ak)} + + +def build_query(params: dict, sk: str = "", mode: str = "official") -> str: + """按百度 SN 规则拼查询串。 + + 百度官方样例(geocoder/v2 那份)与社区常见写法算出的 sn 不一致, + 没有 SK 无法判定哪个对,所以两种都实现,由上层自动试: + - official:quote("path?query", safe=...) -> 追加 SK -> quote_plus -> md5 + - simple :urlencode(按 key 升序, safe="") -> md5("path?query" + SK) + """ + items = sorted((k, v) for k, v in params.items() if k != "sn") + if mode == "simple": + query = urlencode(items, encoding="utf-8", safe="") + if not sk: + return query + digest = hashlib.md5((PATH + "?" + query + sk).encode("utf-8")).hexdigest() + return query + "&sn=" + digest + + raw_query = "&".join(f"{k}={v}" for k, v in items) + encoded = quote(PATH + "?" + raw_query, safe="/:=&?#+!$,;'@()*[]") + query = encoded[len(PATH) + 1:] + if not sk: + return query + digest = hashlib.md5(quote_plus(encoded + sk).encode("utf-8")).hexdigest() + return query + "&sn=" + digest + + +# 记住哪种 SN 算法能通,避免每次先撞一次 211 +_SN_MODE = [None] + + +def _sn_modes(): + if _SN_MODE[0]: + other = "simple" if _SN_MODE[0] != "simple" else "official" + return [_SN_MODE[0], other] + return ["official", "simple"] + + +# ========== 缓存 ========== + +def _conn(): + conn = sqlite3.connect(CACHE_PATH, timeout=5) + if not _cache_ready[0]: + conn.execute(""" + CREATE TABLE IF NOT EXISTS walk_cache ( + key TEXT PRIMARY KEY, + distance_m INTEGER NOT NULL, + duration_s INTEGER NOT NULL, + created_at REAL NOT NULL + ) + """) + conn.commit() + _cache_ready[0] = True + return conn + + +def _cache_key(o_lat, o_lng, d_lat, d_lng) -> str: + p = COORD_PRECISION + return "%.*f,%.*f|%.*f,%.*f" % (p, o_lat, p, o_lng, p, d_lat, p, d_lng) + + +def _cache_get(key): + try: + conn = _conn() + row = conn.execute( + "SELECT distance_m, duration_s, created_at FROM walk_cache WHERE key = ?", + (key,)).fetchone() + conn.close() + if not row: + return None + if time.time() - float(row[2]) > CACHE_TTL_SECONDS: + return None + return {"distance": int(row[0]), "duration": int(row[1])} + except Exception as exc: + print(f"[步行路线] 读缓存失败: {exc}") + return None + + +def _cache_put(key, distance_m, duration_s): + try: + conn = _conn() + conn.execute( + "INSERT OR REPLACE INTO walk_cache (key, distance_m, duration_s, created_at) " + "VALUES (?, ?, ?, ?)", (key, int(distance_m), int(duration_s), time.time())) + conn.commit() + conn.close() + except Exception as exc: + print(f"[步行路线] 写缓存失败: {exc}") + + +# ========== 节流 ========== + +def _throttle(): + """全局 3 QPS 上限(百度给的并发就是 3)。""" + with _lock: + wait = _last_call_at[0] + MIN_INTERVAL_SECONDS - time.time() + if wait > 0: + time.sleep(wait) + _last_call_at[0] = time.time() + + +# ========== 估算兜底 ========== + +def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict: + """直线 → 道路经验估算。永远有返回值。""" + try: + lat1, lng1, lat2, lng2 = map(float, (origin_lat, origin_lng, dest_lat, dest_lng)) + except (TypeError, ValueError): + return {"distance": 0, "duration": 0, "source": "none"} + r = 6371000.0 + p1, p2 = math.radians(lat1), math.radians(lat2) + dphi = p2 - p1 + dlmb = math.radians(lng2 - lng1) + a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2 + straight = 2 * r * math.asin(math.sqrt(a)) + distance = int(round(straight * DETOUR_FACTOR)) + duration = int(round(max(distance, 1) / WALK_METERS_PER_MIN * 60)) + return {"distance": distance, "duration": duration, "straight": int(round(straight)), + "source": "estimate"} + + +# ========== 百度接口 ========== + +def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng, + mode="official") -> dict: + _throttle() + params = { + "ak": ak, + "origin": f"{origin_lat:.6f},{origin_lng:.6f}", + "destination": f"{dest_lat:.6f},{dest_lng:.6f}", + "coord_type": "gcj02", # 上游车辆坐标就是 GCJ02,不用转 + } + if sk: + # 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset) + params["timestamp"] = int(time.time()) + url = BASE_URL + "?" + build_query(params, sk, mode) + resp = requests.get(url, timeout=REQUEST_TIMEOUT) + resp.raise_for_status() + data = resp.json() + status = data.get("status") + if status != 0: + raise RuntimeError(f"status={status} message={data.get('message')}") + result = data.get("result") or {} + # directionlite 正常返回 result.routes[0].{distance,duration}; + # 少数版本把 distance/duration 直接挂在 result 上,一并兜住。 + route = (result.get("routes") or [{}])[0] + distance = route.get("distance", result.get("distance")) + duration = route.get("duration", result.get("duration")) + if distance is None or duration is None: + raise RuntimeError(f"返回缺字段: {str(data)[:200]}") + return {"distance": int(distance), "duration": int(duration)} + + +def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict: + """返回 {distance(米), duration(秒), source: baidu|cache|estimate}。 + + source=cache 也代表数据来自百度(命中缓存)。 + """ + try: + o_lat, o_lng = float(origin_lat), float(origin_lng) + d_lat, d_lng = float(dest_lat), float(dest_lng) + except (TypeError, ValueError): + return estimate(origin_lat, origin_lng, dest_lat, dest_lng) + + if not (math.isfinite(o_lat) and math.isfinite(o_lng) + and math.isfinite(d_lat) and math.isfinite(d_lng)): + return estimate(o_lat, o_lng, d_lat, d_lng) + + key = _cache_key(o_lat, o_lng, d_lat, d_lng) + if use_cache: + hit = _cache_get(key) + if hit: + return {**hit, "source": "cache"} + + ak = get_ak() + if not ak: + return estimate(o_lat, o_lng, d_lat, d_lng) + + sk = get_sk() + got = None + last_error = None + for mode in _sn_modes(): + try: + got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode) + _SN_MODE[0] = mode # 记住能通的算法 + break + except Exception as exc: + last_error = exc + text = str(exc) + # 只有 SN 相关错误才值得换算法重试,其余(配额/超时)直接退回估算 + if "211" not in text and "SN" not in text.upper(): + break + if got is None: + print(f"[步行路线] 百度调用失败,退回估算: {last_error}") + return estimate(o_lat, o_lng, d_lat, d_lng) + + _cache_put(key, got["distance"], got["duration"]) + return {**got, "source": "baidu"}