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 · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
213 lines
12 KiB
Python
213 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""schedules.json: แบบแบน (30 record) → แบบ 2 ชั้น routes[] → directions[] → stops[]
|
||
|
||
*** ไม่ใช่ build step ของเว็บ *** — เครื่องมือเตรียมข้อมูล รันมือครั้งเดียว (รันซ้ำได้ ไม่ทำลายข้อมูล)
|
||
|
||
แนวคิด "มัดรวมตามสาย → ซอยย่อยตามจุด":
|
||
routes[] หนึ่งรายการต่อสาย (ผูกกับ routes.json ด้วย route_id)
|
||
station_order[] ลำดับจุดจอดตามที่รถวิ่ง (ตรวจกับพิกัดจริงเทียบปลายเส้น geojson แล้ว)
|
||
directions[] แกนทิศ — สายที่รถแยกทาง/วิ่ง 2 ทาง จะมีหลายทิศ
|
||
stops[] จุดจอดในทิศนั้น
|
||
station_id
|
||
times[] เวลาออกของจุดนี้
|
||
dir_note ถ้อยคำทิศเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
|
||
note เงื่อนไขเวลาเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
|
||
groups[] (อนาคต) ใช้เมื่อเวลาชุดเดียวกันแยกตามวัน เช่น 10:00 เฉพาะวันหยุด
|
||
|
||
กติกาการแยกทิศ (ยึดข้อมูลจริง):
|
||
- "จุดแยกทิศ" = จุดที่มี record หลายทิศ = จุดที่รถแยกทาง (เช่น สาย 101 จุด 2 ป่าโมก มีทั้ง 'ไปอยุธยา'/'ไปออ่างทอง')
|
||
- record ที่ไม่ระบุทิศ → ใช้ทิศของจุดแยกทิศที่อยู่ก่อนหน้าในลำดับ (จุดที่รถผ่านมาก่อน)
|
||
- สายที่ไม่ระบุทิศเลย → ทิศเดียว dir_id = "all"
|
||
|
||
หมายเหตุ: เลิกใช้ schedule_id (ไม่มีโค้ดไหนอ้างถึง) — กุญแจคือ route_id + dir_id + station_id
|
||
"""
|
||
import argparse
|
||
import json
|
||
import math
|
||
import sys
|
||
from collections import OrderedDict
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
DATA = ROOT / "resource" / "data"
|
||
SRC = DATA / "schedules.json"
|
||
ALL = "__all__" # กุญแจทิศ "ไม่แยกทิศ" (ใช้สตริงธรรมดา กันอักขระพิเศษ)
|
||
|
||
|
||
# ── เรขาคณิตเล็ก ๆ (ใช้ตรวจลำดับจุดจอดกับปลายเส้น) ──
|
||
def _hav(a, b):
|
||
R = 6371.0
|
||
p1, p2 = math.radians(a[1]), math.radians(b[1])
|
||
dp, dl = p2 - p1, math.radians(b[0] - a[0])
|
||
h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||
return 2 * R * math.asin(math.sqrt(h))
|
||
|
||
|
||
def stop_point(sid, stations):
|
||
st = stations.get(sid)
|
||
if not st:
|
||
return None
|
||
lat, lng = st.get("latitude"), st.get("longitude")
|
||
if lat in (None, "") or lng in (None, ""):
|
||
return None
|
||
try:
|
||
return (float(lng), float(lat))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def geo_ends(rid):
|
||
"""ปลายทั้งสองของเส้น (จุดแรก, จุดสุดท้าย) จาก geojson-web"""
|
||
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]
|
||
if not segs:
|
||
return None
|
||
return segs[0][0], segs[-1][-1]
|
||
|
||
|
||
def orient_order(rid, order, stations):
|
||
"""คืน station_order ที่ตรงกับทิศที่รถวิ่งจริง (เทียบพิกัดกับปลายเส้น) + ธงว่าสลับหรือไม่"""
|
||
if len(order) < 2:
|
||
return list(order), False
|
||
ends = geo_ends(rid)
|
||
if not ends:
|
||
return list(order), False
|
||
a, b = ends
|
||
pf, pl = stop_point(order[0], stations), stop_point(order[-1], stations)
|
||
if not (pf and pl):
|
||
return list(order), False
|
||
same = _hav(pf, a) + _hav(pl, b)
|
||
swap = _hav(pf, b) + _hav(pl, a)
|
||
if swap < same:
|
||
return list(reversed(order)), True
|
||
return list(order), False
|
||
|
||
|
||
# ── การแยกทิศ (ไม่เดา — ใช้ "ทิศทางที่ระบุ" (direction_note) และ "จุดต้นทาง" เท่านั้น) ──
|
||
def direction_of(rec, first_station):
|
||
"""ทิศของ record ตามข้อมูลที่ระบุไว้จริง
|
||
- มี direction_note → ทิศนั้น (แยกเป็น directions[] ของตัวเอง)
|
||
- ไม่มี note + เป็นจุดต้นทาง (station_order[0]) → 'ออกจากต้นทาง' (dir_id = from-<station>)
|
||
- ไม่มี note + จุดอื่น → ทิศทางเดียว (dir_id = "all")
|
||
ไม่พยายามเดาว่าจุดปลายทางอยู่ขาไหน (ข้อมูลเดิมขัดกันเอง — ต้องให้เจ้าของข้อมูลยืนยัน)
|
||
"""
|
||
label = rec.get("direction_note")
|
||
if label:
|
||
return ("label", label)
|
||
if rec["station_id"] == first_station:
|
||
return ("start", rec["station_id"])
|
||
return ("all", None)
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description="schedules.json: แบน → 2 ชั้น (routes → directions → stops)")
|
||
ap.add_argument("--check", action="store_true", help="แสดงผลลัพธ์ ไม่เขียนไฟล์")
|
||
ap.add_argument("--out", default=str(SRC), help="ไฟล์ปลายทาง (ค่าเริ่มต้น: ทับ schedules.json)")
|
||
args = ap.parse_args()
|
||
|
||
doc = json.loads(SRC.read_text(encoding="utf-8"))
|
||
if doc.get("schema") == 2:
|
||
print("ไฟล์เป็น schema 2 อยู่แล้ว — ไม่ต้องแปลง (รัน --force ไม่มี — แก้มือถ้าต้องการแปลงใหม่)")
|
||
return 0
|
||
records = doc.get("schedules") or []
|
||
routes = {str(r["route_id"]): r for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]}
|
||
stations = {x["station_id"]: x for x in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]}
|
||
|
||
by_route = OrderedDict()
|
||
for rec in records:
|
||
by_route.setdefault(str(rec["route_id"]), []).append(rec)
|
||
|
||
out_routes, warnings = [], []
|
||
n_dup = 0
|
||
for rid, recs in by_route.items():
|
||
raw_order = routes.get(rid, {}).get("station_ids") or []
|
||
order, flipped = orient_order(rid, raw_order, stations)
|
||
if flipped:
|
||
warnings.append(f"สาย {rid}: สลับ station_order ให้ตรงทิศที่รถวิ่งจริง (พิกัดบอกว่าเริ่มฝั่ง {order[0]})")
|
||
dirs = OrderedDict()
|
||
for rec in recs:
|
||
kind, val = direction_of(rec, order[0] if order else None)
|
||
key = (kind, val)
|
||
d = dirs.setdefault(key, {"recs": [], "label": val if kind == "label" else None})
|
||
d["recs"].append(rec)
|
||
|
||
dir_list = []
|
||
dir_seq = 1
|
||
for (kind, val), d in dirs.items():
|
||
stops = []
|
||
for rec in sorted(d["recs"], key=lambda r: r["station_id"]):
|
||
entry = {"station_id": rec["station_id"], "times": rec.get("departure_times") or []}
|
||
if rec.get("direction_note"):
|
||
entry["dir_note"] = rec["direction_note"]
|
||
if rec.get("schedule_note"):
|
||
entry["note"] = rec["schedule_note"]
|
||
stops.append(entry)
|
||
stops.sort(key=lambda x: (order.index(x["station_id"]) if x["station_id"] in order else 999))
|
||
dir_id = "all" if kind == "all" else (("from-%s" % val) if kind == "start" else "dir-%d" % dir_seq)
|
||
if kind == "label":
|
||
dir_seq += 1
|
||
dir_list.append({
|
||
"dir_id": dir_id,
|
||
"dir_label": d["label"],
|
||
"stops": stops,
|
||
})
|
||
n_dup += sum(len(s["times"]) for s in stops)
|
||
|
||
# เตือน: ทิศเดียวกันแต่จำนวนเที่ยวของแต่ละจุดไม่เท่ากัน (บ่งชี้ว่ายังแยกทิศไม่ครบ)
|
||
for dl in dir_list:
|
||
counts = {s["station_id"]: len(s["times"]) for s in dl["stops"] if s["times"]}
|
||
if len(set(counts.values())) > 1:
|
||
warnings.append(
|
||
f"สาย {rid} ทิศ '{dl['dir_label'] or 'ไม่แยกทิศ'}': จำนวนเที่ยวไม่เท่ากันข้ามจุด {counts} "
|
||
f"— อาจยังแยกทิศไม่ครบ (ต้องให้เจ้าของข้อมูลยืนยัน)")
|
||
|
||
# เตือนจุดจอดที่ไม่มีเวลา (ไม่สร้างข้อมูลปลอม — UI จะขึ้น "ยังไม่มีข้อมูล")
|
||
have = {s["station_id"] for dl in dir_list for s in dl["stops"]}
|
||
for sid in order:
|
||
if sid not in have:
|
||
warnings.append(f"สาย {rid}: จุดจอด station {sid} ยังไม่มีเวลาในไฟล์")
|
||
|
||
out_routes.append({"route_id": rid, "station_order": order, "directions": dir_list})
|
||
|
||
new = {"schema": 2, "routes": out_routes}
|
||
n_time = sum(len(s["times"]) for r in out_routes for d in r["directions"] for s in d["stops"])
|
||
n_distinct = sum(len(r.get("departure_times") or []) for r in records)
|
||
|
||
print(f"แปลง {len(records)} record → {len(out_routes)} สาย · "
|
||
f"{sum(len(r['directions']) for r in out_routes)} ทิศ · "
|
||
f"{sum(len(d['stops']) for r in out_routes for d in r['directions'])} จุด")
|
||
print(f"เที่ยวในข้อมูลเดิม (ไม่นับซ้ำ) = {n_distinct} · เก็บในโครงใหม่ = {n_time} "
|
||
f"(ส่วนต่าง {n_time - n_distinct} = จุดที่ถูกเก็บในหลายทิศ เช่นจุดแยกทิศ)")
|
||
|
||
print(f"\n{'สาย':<7}{'ทิศ':<24}{'จุด':<5}{'เที่ยว':<7}จุดจอดในทิศนั้น")
|
||
for r in out_routes:
|
||
for d in r["directions"]:
|
||
cells = ", ".join(f"{s['station_id']}×{len(s['times'])}" for s in d["stops"])
|
||
print(f"{r['route_id']:<7}{(d['dir_label'] or '(ไม่แยกทิศ)')[:22]:<24}{len(d['stops']):<5}"
|
||
f"{sum(len(s['times']) for s in d['stops']):<7}{cells}")
|
||
|
||
if warnings:
|
||
print(f"\nหมายเหตุ {len(warnings)} ข้อ:")
|
||
for w in warnings:
|
||
print(" -", w)
|
||
|
||
if args.check:
|
||
print("\n[--check] ไม่เขียนไฟล์")
|
||
return 0
|
||
|
||
Path(args.out).write_text(json.dumps(new, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||
print(f"\nเขียนแล้ว: {Path(args.out).name}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|