Schedules — กติกา "จุดนี้ = เวลาจุดอ้างอิง ± n นาที"
- ฟิลด์ derive { from_station_id, offset_min } คำนวณที่ ui/partials/schedules.js (ท่อเดียว) รองรับอ้างจุดข้ามทิศ
- จุดย่อยของ "8 other_stop" ใช้ offsets_min จับคู่ตามลำดับ (เช่น ตลาดสามโก้ = ตลาดท่าช้าง +45 นาที)
- เครื่องมือ resource/tools/derive-times.py + ตาราง resource/data/derive-times.csv (--check / --audit ชี้จุดที่ควรตั้งกฎ)
- แยกตารางเป็นรายสาย: scheduleslist/schedules<route_id>.json และ schedules.json เป็นสารบัญ (โหลดแบบ lazy + cache)
- ตรวจจับวันทำงาน/วันหยุด + schema 3 (weekday/holiday → directions) · ไฟล์ข้อมูลเป็น CRLF ทั้งชุด
- ล้างค่าที่ไม่ใช่ HH:MM ที่ฝังใน times (ทำให้ KPI เพี้ยน) + กันค่าหลอกในตัวสรุปเวลา
UI
- หน้ารายละเอียดป้าย/ตารางเวลา ขับเคลื่อนด้วย JSON (stopDetail.init.js) · จุดขึ้นรถประจำทางอื่นๆ รองรับหลายจุดต่อสาย
- #/stops: แสดง 6 ป้ายแรก + ปุ่ม "แสดงป้ายทั้งหมด" (โหลดรูปเฉพาะที่แสดง) · ชิปสาย → #/routes/<route_id>
- หน้าแรก: ตัดตัวเลือก "ทุกสถานีในจังหวัดนี้" · ตัวกรองจังหวัด/สถานี + ปุ่มแชร์ (share URL)
- การ์ดติดต่อ: ไอคอน/ชื่อ/สีเปลี่ยนตามชนิด URL (Facebook / LINE / เว็บไซต์) + ปุ่มเปิดลิงก์จาก web_url
- รูปรองรับหลายนามสกุล (.jpg → .jpeg → .webp → .png) · ป้าย "ประมาณ" + หมายเหตุสำหรับตารางที่คำนวณ
- หน้าเครดิตเหลือ 3 หมวด · แก้ข้อความหมวดแผนที่ให้ตรงกับข้อมูลจริง
- แผนที่ Leaflet (vendor ในโปรเจกต์ ไม่ใช้ CDN): เส้นทาง + หมุด + ป๊อปอัป · แก้ CSS ที่ทำให้ SVG ยุบ 0x0
เครื่องมือและเอกสาร
- qgis-to-web.py อ่าน .shp ตรง → geojson-web (สร้างใหม่ 10 ไฟล์) + audit-geojson.py ตรวจ 3 ส่วน
- stop-km.py วัดระยะ กม. ตามเส้นจริง → stop-km.json · schedules-editor.html (แก้ทีละไฟล์ · มุมมองตารางแบบ Excel)
- AGENTS.md: กติกา derive · offsets_min · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
180 lines
9.6 KiB
Python
180 lines
9.6 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""วัดระยะทาง (กม. ตามเส้นทางจริง) ของทุกจุดจอด แล้วบันทึกลงไฟล์แยก resource/data/stop-km.json
|
|
|
|
ทำไมต้องแยกไฟล์: schedules.json เป็นไฟล์ที่ "คนแก้มือ" (ผ่าน Excel/เครื่องมือแก้ไข) — ถ้าเก็บค่าที่คำนวณไว้ในนั้น
|
|
พอผู้ใช้กดบันทึกทับจากสำเนาเก่า ค่าที่คำนวณก็หายทั้งชุด → จึงแยกไว้ต่างหาก (ไฟล์นี้เป็น generated)
|
|
|
|
ทำไมต้องมี: ระบบ "คำนวณเวลาจากต้นทาง" (ไม่ต้องทำตารางที่จุดกลางทาง) ต้องรู้ว่าจุดอยู่ กม. ที่เท่าไรของเส้น
|
|
การวัดทำใน Python ครั้งเดียว แล้วเก็บค่า km ไว้ในไฟล์ → หน้าเว็บไม่ต้องโหลด GIS เลย
|
|
|
|
การทำงาน:
|
|
1. อ่าน điểmจอดของแต่ละทิศใน schedules.json (เฉพาะที่มี station_id)
|
|
2. หาพิกัดจาก stations.json (จุดที่เป็น 'จุดขึ้นรถประจำทางอื่นๆ' → หาจาก 8 other_stop.json ตาม route_id)
|
|
3. วัด กม. จากต้นทางตามเส้น geojson-web/<route>.geojson (เลือกปลายที่ใกล้ "จุดที่มีเวลาอยู่แล้ว" ที่สุดเป็นต้นทาง)
|
|
4. เขียนฟิลด์ "km" กลับเข้า stop (ทับค่าเดิมถ้ามี) + รายงานจุดที่วัดไม่ได้
|
|
|
|
รัน: python resource/tools/stop-km.py # เขียนไฟล์
|
|
python resource/tools/stop-km.py --check # ดูผลก่อน ไม่เขียน
|
|
"""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
DATA = ROOT / "resource" / "data"
|
|
OFF_ROUTE_KM = 2.0 # ห่างจากเส้นเกินนี้ = แจ้ง (พิกัดอาจผิด)
|
|
|
|
|
|
def hav(a, b):
|
|
R = 6371.0
|
|
r = math.pi / 180
|
|
dlat = (b[1] - a[1]) * r
|
|
dlng = (b[0] - a[0]) * r
|
|
h = math.sin(dlat / 2) ** 2 + math.cos(a[1] * r) * math.cos(b[1] * r) * math.sin(dlng / 2) ** 2
|
|
return 2 * R * math.asin(math.sqrt(h))
|
|
|
|
|
|
def km_on_line(lines, p):
|
|
"""ระยะตามเส้นจากต้นเส้นถึงจุดที่ใกล้ p ที่สุด + ระยะห่างจากเส้น (กม.)"""
|
|
best = None
|
|
cum = 0.0
|
|
for line in lines:
|
|
for i in range(1, len(line)):
|
|
a, b = line[i - 1], line[i]
|
|
seg = hav(a, b)
|
|
lat0 = math.radians((a[1] + b[1]) / 2)
|
|
k = 111.32
|
|
ax, ay = a[0] * math.cos(lat0) * k, a[1] * k
|
|
bx, by = b[0] * math.cos(lat0) * k, b[1] * k
|
|
px, py = p[0] * math.cos(lat0) * k, p[1] * k
|
|
dx, dy = bx - ax, by - ay
|
|
L2 = dx * dx + dy * dy
|
|
t = 0.0 if not L2 else max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / L2))
|
|
dist = math.hypot(px - (ax + t * dx), py - (ay + t * dy))
|
|
if best is None or dist < best[0]:
|
|
best = (dist, cum + t * seg)
|
|
cum += seg
|
|
return best if best else (None, 0.0)
|
|
|
|
|
|
def load_lines(rid):
|
|
p = DATA / "geojson-web" / f"{rid}.geojson"
|
|
if not p.exists():
|
|
return None
|
|
g = json.loads(p.read_text(encoding="utf-8"))
|
|
segs = []
|
|
for f in g.get("features", []):
|
|
cs = f["geometry"]["coordinates"]
|
|
segs += [cs] if f["geometry"]["type"] == "LineString" else cs
|
|
segs = [s for s in segs if s]
|
|
return segs or None
|
|
|
|
|
|
def same_digits(a, b):
|
|
na = re.sub(r"\D", "", str(a))
|
|
nb = re.sub(r"\D", "", str(b))
|
|
return bool(na) and len(na) == len(nb) and sorted(na) == sorted(nb)
|
|
|
|
|
|
def other_for(rid, others, valid_ids):
|
|
"""จุดของสายนี้ใน 8 other_stop.json (รองรับรหัสเพี้ยน เช่น 1101 = 1011)"""
|
|
want = str(rid)
|
|
hit = [o for o in others if str(o["route_id"]) == want]
|
|
if hit:
|
|
return hit
|
|
for o in others:
|
|
fid = str(o["route_id"])
|
|
if fid in valid_ids:
|
|
continue
|
|
cands = [v for v in valid_ids if same_digits(v, fid)]
|
|
if len(cands) == 1 and cands[0] == want:
|
|
return [o]
|
|
return []
|
|
|
|
|
|
def point_of(sid, stations, others_by_route, rid):
|
|
st = stations.get(sid)
|
|
if not st:
|
|
return None, None
|
|
lat, lng = st.get("latitude"), st.get("longitude")
|
|
if not isinstance(lat, (int, float)) or not isinstance(lng, (int, float)):
|
|
# 'จุดขึ้นรถประจำทางอื่นๆ' → เอาจุดจริงของสายนั้น
|
|
for o in others_by_route.get(str(rid), []):
|
|
la, lo = o.get("latitude"), o.get("longitude")
|
|
if isinstance(la, (int, float)) and isinstance(lo, (int, float)):
|
|
return (float(lo), float(la)), o.get("station_name_th")
|
|
return None, (st.get("station_name_th") or "")
|
|
return (float(lng), float(lat)), (st.get("station_name_th") or "")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="วัด กม. จากต้นทางของทุกจุดจอด แล้วเขียนลง schedules.json")
|
|
ap.add_argument("--check", action="store_true", help="ไม่เขียนไฟล์ แค่รายงาน")
|
|
args = ap.parse_args()
|
|
|
|
doc = json.loads((DATA / "schedules.json").read_text(encoding="utf-8"))
|
|
stations = {s["station_id"]: s for s in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]}
|
|
others = json.loads((DATA / "8 other_stop.json").read_text(encoding="utf-8"))["other_stop"]
|
|
valid_ids = [str(r["route_id"]) for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]]
|
|
others_by_route = {}
|
|
for r in doc.get("routes", []):
|
|
others_by_route[str(r["route_id"])] = other_for(r["route_id"], others, valid_ids)
|
|
by_route = others_by_route
|
|
|
|
measured = skipped = offroute = 0
|
|
report = []
|
|
out = {}
|
|
for r in doc.get("routes", []):
|
|
rid = str(r["route_id"])
|
|
lines = load_lines(rid)
|
|
if not lines:
|
|
report.append((rid, "(ไม่มีไฟล์ geojson)", None, "—"))
|
|
continue
|
|
for d in r.get("directions", []):
|
|
for s in d.get("stops", []):
|
|
pt, name = point_of(s["station_id"], stations, by_route, rid)
|
|
if pt is None:
|
|
skipped += 1
|
|
report.append((rid, name or f"station {s['station_id']}", None, "ไม่มีพิกัด → วัดไม่ได้"))
|
|
pass
|
|
continue
|
|
dist, km = km_on_line(lines, pt)
|
|
out.setdefault(rid, {})[str(s["station_id"])] = round(km, 2)
|
|
measured += 1
|
|
if dist is not None and dist > OFF_ROUTE_KM:
|
|
offroute += 1
|
|
report.append((rid, name or f"station {s['station_id']}", out[rid][str(s["station_id"])], f"ห่างจากเส้น {dist:.1f} กม. (พิกัดอาจผิด)"))
|
|
print(f"วัดระยะได้ {measured} จุด · วัดไม่ได้ {skipped} จุด · ห่างเส้นเกิน {OFF_ROUTE_KM} กม. {offroute} จุด")
|
|
if report:
|
|
print("\nจุดที่ต้องดู:")
|
|
for rid, name, km, why in report:
|
|
kms = "—" if km is None else f"{km:g} กม."
|
|
print(f" สาย {rid:<5} {name[:34]:<36} {kms:<10} {why}")
|
|
|
|
if args.check:
|
|
print("\n[--check] ไม่เขียนไฟล์")
|
|
return 0
|
|
# เขียนไฟล์แยก (เรียงคีย์ให้อ่านง่าย)
|
|
ordered = {rid: out[rid] for rid in sorted(out, key=lambda x: (len(x), x))}
|
|
text = json.dumps(ordered, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n"
|
|
(DATA / "stop-km.json").write_text(text, encoding="utf-8", newline="")
|
|
# เก็บกวาด: ถ้า schedules.json ยังมีฟิลด์ km ค้างจากรุ่นก่อน ให้เอาออก (ไฟล์ผู้ใช้ต้องสะอาด)
|
|
if any("km" in s for r in doc.get("routes", []) for d in r.get("directions", []) for s in d.get("stops", [])):
|
|
for r in doc.get("routes", []):
|
|
for d in r.get("directions", []):
|
|
for st in d.get("stops", []):
|
|
st.pop("km", None)
|
|
clean = json.dumps(doc, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n"
|
|
(DATA / "schedules.json").write_text(clean, encoding="utf-8", newline="")
|
|
print("\nเก็บกวาด: ลบฟิลด์ km ที่ค้างใน schedules.json แล้ว (ไฟล์ผู้ใช้สะอาด)")
|
|
print("\nเขียนไฟล์แล้ว: resource/data/stop-km.json")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|