Files
web-at-transit-mock/resource/tools/schedules-to-grouped.py
T
Bkk1234 656f65b41c แผนที่จาก GPKG + บทความ 6 ชิ้น + ลดความหนา footer
== แผนที่ / GIS ==
- qgis-to-web.py: อ่าน GPKG ได้ (--from gpkg) + เพิ่ม dream-Watcharapol
- เพิ่ม dream-*.geojson 6 ไฟล์ (เส้นทางที่เสนอ: บ้านภาชี · ชานเมืองอยุธยา · HSR · เมืองทองธานี · ปากเกร็ด · วัชรพล)
- map.js: ATMap.proposal() วาดเส้นจริงจาก geojson (ไม่ใช่เส้นตรง) · smoothFactor 0.5
  · coordOf() รับ coords=[lat,lng] · fitAll รับได้ทั้งจุดเดี่ยวและเส้น · setStyle บน featureGroup

== บทความ (blog) ==
- text3: ถ้าผมได้ออกแบบสายเดินรถเอง (จาก mydream.html) TH+EN
- text4: วิธีเดินทางไปสถานีรถไฟ และสนามบิน (จาก train-airplane.html) TH+EN
- text5/text6: โครงเปล่ารอเติมเนื้อหา (แสวงหา-โพธิ์ทอง · อำเภอเข้าเมือง)
- แผนที่ความฝัน: map.groups 3 กลุ่ม · คลิกเส้น/หมุด/แถวได้ · ป้ายที่มา
- ย่อหน้า: ระยะห่าง 20px + ย่อหน้าหน้าบรรทัด 1.5em

== ตารางเดินรถ ==
- เปลี่ยนชื่อคีย์ dir_* -> direction_* ทุกไฟล์ (backward-compat ในโค้ด)
- 1011: จุดย่อย 2 ทิศ + offsets [0,25,55]
- 954/2194: จุดย่อย station 8 + offsets
- refreshHighlights: วนข้ามวันเมื่อเลยเที่ยวสุดท้าย + ไฮเทลต์ชิปทุกจุด
- 8 other_stop.md: อัปเดตตรงข้อมูลจริง 8 รายการ

== i18n ==
- แยกไฟล์ต่อภาษา ui/locales/{th,en}.json + i18n.js = loader (ลด 28KB -> 6.5KB)
- resource/tools/check-i18n.py ตรวจคีย์ขาด/ซ้ำ
- ข้อความผู้สนับสนุนหน้าแรก + คำแปล EN

== UI ==
- ฝังฟอนต์ K2D (ui/vendor/fonts/) ออฟไลน์ 100%
- cache busting ?v=<SW VERSION> ทุกรูป (ui/imageurl.js)
- footer: ลดความหนา 468 -> 349px + line-height 1.5 กันสระ/วรรณยุกต์ซ้อน
- QR modal + ปุ่มคัดลอกลิงก์ · หน้าอัปเดตล่าสุดใน #/check
- credits: ขอขอบคุณภาพรถ 3 สาย

== เครื่องมือ ==
- bump-version.py · stamp-schedules.py · derive-times.py (จุดอ้างอิง ± นาที)
2026-10-05 03:55:09 +07:00

213 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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[] เวลาออกของจุดนี้
direction_note ถ้อยคำทิศเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
note เงื่อนไขเวลาเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
groups[] (อนาคต) ใช้เมื่อเวลาชุดเดียวกันแยกตามวัน เช่น 10:00 เฉพาะวันหยุด
กติกาการแยกทิศ (ยึดข้อมูลจริง):
- "จุดแยกทิศ" = จุดที่มี record หลายทิศ = จุดที่รถแยกทาง (เช่น สาย 101 จุด 2 ป่าโมก มีทั้ง 'ไปอยุธยา'/'ไปออ่างทอง')
- record ที่ไม่ระบุทิศ → ใช้ทิศของจุดแยกทิศที่อยู่ก่อนหน้าในลำดับ (จุดที่รถผ่านมาก่อน)
- สายที่ไม่ระบุทิศเลย → ทิศเดียว direction_id = "all"
หมายเหตุ: เลิกใช้ schedule_id (ไม่มีโค้ดไหนอ้างถึง) — กุญแจคือ route_id + direction_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]) → 'ออกจากต้นทาง' (direction_id = from-<station>)
- ไม่มี note + จุดอื่น → ทิศทางเดียว (direction_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["direction_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))
direction_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({
"direction_id": direction_id,
"direction_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['direction_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.get('direction_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())