ตารางเวลาคำนวณได้ + หน้ารายละเอียดป้ายขับเคลื่อนด้วยข้อมูล + แผนที่ Leaflet

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 · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
This commit is contained in:
Bkk1234 committed 2026-09-30 03:25:18 +07:00
1 parent 88311326e6
commit 1cfaeb1526
91 files changed
+7560 -844

No files matched your search

Binary file not shown.
+220
View File
@@ -0,0 +1,220 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ตรวจสุขภาพข้อมูลเส้นทาง — QGIS → GeoJSON ที่เว็บใช้
รันจาก root ของโปรเจกต์:
python resource/tools/audit-geojson.py
ตรวจ 3 ส่วน:
A. ไฟล์ส่งออกใน QGIS Project (GeoJSON-2/3/4) — CRS · พิกัดว่าง/ซ้ำ/หลุดกรอบ · ความหยาบของเส้น
B. ข้อมูลที่เว็บใช้จริง (resource/data/geojson-web/) — สถิติ + "ปลายเส้นตรงกับจุดจอดไหม"
C. เทียบ shapefile (ต้นทาง QGIS) ↔ geojson-web (ว่าต้องรัน pipeline ไหม)
"""
import importlib.util
import json
import math
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
TOOL = Path(__file__).with_name("qgis-to-web.py")
QDIR = ROOT / "resource" / "data" / "QGIS Project"
WEB = ROOT / "resource" / "data" / "geojson-web"
DATA = ROOT / "resource" / "data"
BBOX = (97.0, 103.0, 12.0, 17.5)
JUMP_KM = 1.5
END_TOL_KM = 1.0
# ยืมตัวอ่าน shapefile + ตารางจับคู่จาก pipeline (DRY)
_spec = importlib.util.spec_from_file_location("q2w", TOOL)
q2w = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(q2w)
issues = []
def note(level, msg): issues.append((level, msg))
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 read_features(p):
txt = p.read_text(encoding="utf-8", errors="replace")
try:
d = json.loads(txt)
feats = list(d.get("features") or [])
if d.get("type") == "Feature" and "geometry" in d:
feats.append(d)
return feats, ("FeatureCollection" if "features" in d else "Feature")
except json.JSONDecodeError:
return [json.loads(l) for l in txt.splitlines() if l.strip()], "GeoJSONLines"
def lines_of(geom):
if not geom:
return []
t, cs = geom.get("type"), geom.get("coordinates") or []
if t == "LineString":
return [cs] if cs else []
if t == "MultiLineString":
return [l for l in cs if l]
return []
def audit_file(p):
feats, kind = read_features(p)
lines, empty = [], 0
for f in feats:
ls = lines_of(f.get("geometry"))
if not ls:
empty += 1
continue
lines += ls
pts = [c for l in lines for c in l]
if not pts:
return {"kind": kind, "feats": len(feats), "empty_feats": empty, "pts": 0}
jumps = [hav(l[i - 1], l[i]) for l in lines for i in range(1, len(l)) if hav(l[i - 1], l[i]) > JUMP_KM]
return {
"kind": kind, "feats": len(feats), "empty_feats": empty, "lines": len(lines), "pts": len(pts),
"km": sum(hav(l[i - 1], l[i]) for l in lines for i in range(1, len(l))),
"jumps": jumps, "max_jump": max(jumps) if jumps else 0.0,
"dups": sum(1 for l in lines for i in range(1, len(l)) if l[i] == l[i - 1]),
"out_of_box": sum(1 for c in pts if not (BBOX[0] < c[0] < BBOX[1] and BBOX[2] < c[1] < BBOX[3])),
"utm": max(abs(min(c[0] for c in pts)), abs(max(c[0] for c in pts))) > 1000,
"lines_pts": lines, "first": lines[0][0], "last": lines[-1][-1],
}
def table_header(title):
print("\n" + "=" * 104)
print(title)
print("=" * 104)
def stops_for(rid, routes, stations, others):
out = []
for sid in (routes.get(rid, {}).get("station_ids") or []):
s = stations.get(sid)
if s and s.get("latitude") not in (None, ""):
out.append((s["station_name_th"], float(s["longitude"]), float(s["latitude"])))
for o in others.get(rid, []):
out.append((o["station_name_th"] + "*", float(o["longitude"]), float(o["latitude"])))
return out
def main():
routes = {str(r["route_id"]): r for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]}
stations = {s["station_id"]: s for s in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]}
others = {}
op = DATA / "8 other_stop.json"
if op.exists():
for o in json.loads(op.read_text(encoding="utf-8")).get("other_stop", []):
others.setdefault(str(o["route_id"]), []).append(o)
# ── A. ไฟล์ส่งออกใน QGIS Project ──
table_header("A. ไฟล์ส่งออกใน QGIS Project (ต้นฉบับ — ยังไม่ได้เข้าสู่เว็บจนกว่าจะรัน pipeline)")
print(f"\n{'ไฟล์':<34}{'แบบ':<16}{'feat':<6}{'ว่าง':<6}{'จุด':<7}{'กม.':<8}{'ตัดตรง':<8}{'สูงสุด':<8}{'ซ้ำ':<5}{'นอกกรอบ':<9}CRS")
print("-" * 104)
for p in sorted(x for x in QDIR.rglob("*") if x.suffix.lower() in (".geojson", ".json") and x.suffix.lower() != ".qmd"):
st = audit_file(p)
rel = str(p.relative_to(QDIR))
if st["pts"] == 0:
print(f"{rel:<34}{st['kind']:<16}{st['feats']:<6}{st['empty_feats']:<6}{'0':<7}{'-':<8}{'-':<8}{'-':<8}{'-':<5}{'-':<9}⚠️ ไม่มีพิกัด")
continue
if st["utm"]:
note("ERROR", f"{rel}: พิกัดเป็น UTM — ต้องบันทึก/export ใหม่เป็น EPSG:4326")
if st["out_of_box"]:
note("WARN", f"{rel}: มี {st['out_of_box']} จุดหลุดกรอบประเทศไทย")
print(f"{rel:<34}{st['kind']:<16}{st['feats']:<6}{st['empty_feats']:<6}{st['pts']:<7}{st['km']:<8.1f}"
f"{len(st['jumps']):<8}{st['max_jump']:<8.1f}{st['dups']:<5}{st['out_of_box']:<9}{'UTM ❌' if st['utm'] else 'WGS84 ✓'}")
# ── B. ข้อมูลที่เว็บใช้จริง ──
table_header("B. ข้อมูลที่เว็บใช้จริง (resource/data/geojson-web/) — ชุดที่แผนที่โหลด")
print(f"\n{'สาย':<8}{'feat':<6}{'จุด':<7}{'กม.':<8}{'ตัดตรง':<8}{'สูงสุด':<8}ปลายเส้น ↔ จุดจอด (ห่างเกิน {END_TOL_KM} กม. = ⚠️)")
print("-" * 104)
for p in sorted(WEB.glob("*.geojson")):
rid = p.stem
st = audit_file(p)
if st["pts"] == 0:
print(f"{rid:<8}⚠️ ไม่มีพิกัด")
continue
cands = stops_for(rid, routes, stations, others)
ends = ""
if cands:
da, na = min((hav(st["first"], [c[1], c[2]]), c[0]) for c in cands)
db, nb = min((hav(st["last"], [c[1], c[2]]), c[0]) for c in cands)
ends = f"เริ่ม {na[:18]} {da:.1f} กม.{'✓' if da <= END_TOL_KM else '⚠️'} · จบ {nb[:18]} {db:.1f} กม.{'✓' if db <= END_TOL_KM else '⚠️'}"
if da > END_TOL_KM:
note("WARN", f"สาย {rid}: จุดเริ่มเส้นห่างจุดจอดที่ใกล้สุด {da:.1f} กม. ({na})")
if db > END_TOL_KM:
note("WARN", f"สาย {rid}: จุดจบเส้นห่างจุดจอดที่ใกล้สุด {db:.1f} กม. ({nb})")
if st["max_jump"] > 10:
note("WARN", f"สาย {rid}: ช่วงตัดตรงยาวสุด {st['max_jump']:.1f} กม. (เส้นหยาบ/ไม่เกาะถนน)")
print(f"{rid:<8}{st['feats']:<6}{st['pts']:<7}{st['km']:<8.1f}{len(st['jumps']):<8}{st['max_jump']:<8.1f}{ends}")
# ── C. sync shapefile ↔ geojson-web ──
table_header("C. ตรวจ sync: shapefile (QGIS) ↔ geojson-web (เว็บใช้)")
print(f"\n{'สาย':<8}{'shapefile':<40}{'shp: จุด/กม.':<18}{'web: จุด/กม.':<18}สถานะ")
print("-" * 104)
stale = []
for rid in sorted(q2w.SHP_MAP):
shp = QDIR / f"{q2w.SHP_MAP[rid]}.shp"
web = WEB / f"{rid}.geojson"
if not shp.exists():
print(f"{rid:<8}{q2w.SHP_MAP[rid][:38]:<40}{'—':<18}{'—':<18}⚠️ ไม่พบ shapefile (ชื่อเปลี่ยน?)")
note("WARN", f"สาย {rid}: ไม่พบ shapefile {shp.name} — ชื่ออาจเปลี่ยนใน QGIS")
continue
recs = q2w.read_shp(shp)
sl = [l for r in recs for l in r]
skm = sum(hav(l[i - 1], l[i]) for l in sl for i in range(1, len(l)))
sn = sum(len(l) for l in sl)
if web.exists():
wst = audit_file(web)
wn, wkm = wst["pts"], wst["km"]
else:
wn, wkm = 0, 0.0
same = abs(sn - wn) <= 5 and abs(skm - wkm) < 0.05
state = "ตรงกัน ✓" if same else "⚠️ ต้องรัน qgis-to-web.py"
if not same:
stale.append(rid)
print(f"{rid:<8}{shp.stem[:38]:<40}{f'{sn} / {skm:.1f}':<18}{f'{wn} / {wkm:.1f}':<18}{state}")
if stale:
note("WARN", f"geojson-web ไม่ตรงกับ shapefile {len(stale)} สาย ({', '.join(stale)}) → รัน `python resource/tools/qgis-to-web.py`")
else:
print("\n→ geojson-web ตรงกับ shapefile ทุกสาย ✓")
# ── ไฟล์ประกอบอื่น ──
csvs = [str(p.relative_to(QDIR)) for p in QDIR.rglob("*.csv")]
if csvs:
note("INFO", f"ไฟล์ .csv ในโฟลเดอร์ QGIS (น่าจะเป็นไฟล์ทดสอบ): {csvs}")
zips = [p.name for p in QDIR.glob("*.zip")]
if zips:
note("INFO", f"มี .zip สำเนาโฟลเดอร์: {zips}")
no_prj = [p.name for p in QDIR.glob("*.shp") if not p.with_suffix(".prj").exists()]
if no_prj:
note("WARN", f"shapefile ไม่มี .prj (CRS ไม่ทราบ): {no_prj}")
no_geom = sorted(set(routes) - {p.stem for p in WEB.glob("*.geojson")})
unused = sorted({p.stem for p in WEB.glob("*.geojson")} - set(routes))
if no_geom:
note("INFO", f"อยู่ใน routes.json แต่ไม่มี geometry: {no_geom}")
if unused:
note("INFO", f"มี geometry แต่ไม่อยู่ใน routes.json: {unused}")
print("\n" + "=" * 104)
print(f"สรุปประเด็น: {len(issues)} ข้อ")
for level in ("ERROR", "WARN", "INFO"):
ls = [m for lv, m in issues if lv == level]
if ls:
print(f"\n[{level}] {len(ls)} ข้อ")
for m in ls:
print(" -", m)
print(f"\nเกณฑ์: CRS ต้อง WGS84 · ตัดตรง >{JUMP_KM} กม. = หยาบเกินไป · ปลายเส้นห่างจุดจอด >{END_TOL_KM} กม. = ไม่ตรง")
return 1 if any(lv == "ERROR" for lv, _ in issues) else 0
if __name__ == "__main__":
sys.exit(main())
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""derive-times.py — เติมกฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" ให้ไฟล์สาย (resource/data/scheduleslist/)
แนวคิด: เขียนกฎครั้งเดียวเป็นตาราง (resource/data/derive-times.csv) แล้วรันสคริปต์นี้
→ เติมบล็อก "derive" ให้จุดเป้าหมาย + ลบเวลาที่คัดลอกมาทิ้ง (กันข้อมูลไม่ตรงกัน)
ไม่ต้องจดจำไวยากรณ์ JSON และไม่ต้องแก้ทีละสายด้วยมือ
ตาราง (CSV, คั่นด้วยจุลภาค — บรรทัดขึ้นต้น # = ความเห็น):
route_id, station_id, from_station_id, offset_min, note
902, 15, 6, 30, รอรถที่ 7-11 หน้ากินซ่า
วิธีใช้:
python resource/tools/derive-times.py --check # ดูว่าจะเปลี่ยนอะไร (ไม่เขียนไฟล์)
python resource/tools/derive-times.py # เขียนจริง
python resource/tools/derive-times.py --audit # ตรวจกฎ vs ไฟล์ (ไม่เขียน)
"""
import argparse
import csv
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DATA = ROOT / "resource" / "data"
SUB_DIR = DATA / "scheduleslist"
TABLE = DATA / "derive-times.csv"
def read_table(path=TABLE):
"""อ่านตารางกฎ → [{route_id, station_id, from_station_id, offset_min, note}]"""
if not path.exists():
return []
rows = []
with path.open(encoding="utf-8-sig") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
if parts[0].lower() == "route_id": # หัวตาราง
continue
if len(parts) < 4:
continue
rows.append({
"route_id": str(parts[0]),
"station_id": int(parts[1]),
"from_station_id": int(parts[2]),
"offset_min": int(parts[3]),
"note": (parts[4] if len(parts) > 4 else "").strip() or None,
})
return rows
def sub_path(rid):
return SUB_DIR / f"schedules{rid}.json"
def load_sub(rid):
"""คืน (ข้อมูล, ชนิดขึ้นบรรทัด) — อ่านเป็น bytes เพราะ Path.read_text() แปลง CRLF→LF ให้อัตโนมัติ
(ถ้าอ่านด้วย read_text() จะตรวจชนิดขึ้นบรรทัดผิด แล้วเขียนไฟล์เป็น LF ทั้งที่เดิม CRLF)"""
f = sub_path(rid)
if not f.exists():
return None, None
raw = f.read_bytes()
eol = "\r\n" if b"\r\n" in raw else "\n"
return json.loads(raw.decode("utf-8")), eol
def all_times(sub, station_id):
"""เวลาจริงของจุดนั้น (จากทุกทิศ)"""
for d in sub.get("directions", []):
for s in d.get("stops", []):
if int(s["station_id"]) == int(station_id) and (s.get("times") or []):
return s["times"], d.get("dir_id")
return [], None
def find_stop(sub, station_id):
"""คืน (ทิศ, จุด) ของจุดเป้าหมาย"""
for d in sub.get("directions", []):
for s in d.get("stops", []):
if int(s["station_id"]) == int(station_id):
return d, s
return None, None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true", help="dry run — ไม่เขียนไฟล์")
ap.add_argument("--audit", action="store_true", help="ตรวจกฎกับไฟล์ (ไม่เขียน)")
args = ap.parse_args()
rules = read_table()
if not rules:
print(f"ไม่พบกฎในตาราง {TABLE.relative_to(ROOT)} (หรือไฟล์ว่าง)")
return 0
print(f"กฎทั้งหมด: {len(rules)} ข้อ" + (" [--check = ไม่เขียนไฟล์]" if args.check else ""))
problems = 0
for r in rules:
rid = r["route_id"]
sub, eol = load_sub(rid)
if sub is None:
print(f" ✗ {rid}: ไม่พบไฟล์ {sub_path(rid).name}")
problems += 1
continue
src_times, src_dir = all_times(sub, r["from_station_id"])
d, stop = find_stop(sub, r["station_id"])
if stop is None:
print(f" ✗ {rid}: ไม่พบจุด {r['station_id']} ในไฟล์ (ต้องมีจุดก่อนจึงจะตั้งกฎได้)")
problems += 1
continue
if not src_times:
print(f" ✗ {rid}: จุดอ้างอิง {r['from_station_id']} ยังไม่มีเวลาจริง — คำนวณไม่ได้")
problems += 1
continue
had = len(stop.get("times") or [])
want = {"from_station_id": r["from_station_id"], "offset_min": r["offset_min"]}
if r["note"]:
want["note"] = r["note"]
already = stop.get("derive") == want and not had
if args.audit:
ok = already
print(f" {'✓' if ok else '✗'} {rid} จุด {r['station_id']} ← จุด {r['from_station_id']} "
f"{r['offset_min']:+d} นาที (ต้นทางมี {len(src_times)} เที่ยว"
+ (f" · ทิศ {src_dir}" if src_dir else "") + ")"
+ ("" if ok else f" — ไฟล์ยังไม่ตรง (มี times {had} · derive={stop.get('derive')})"))
if not ok:
problems += 1
continue
if already:
print(f" = {rid} จุด {r['station_id']}: ตั้งกฎไว้แล้ว ({r['offset_min']:+d} นาที) — ข้าม")
continue
print(f" → {rid} จุด {r['station_id']} ← จุด {r['from_station_id']} {r['offset_min']:+d} นาที"
+ (f" · ลบเวลาที่คัดลอกมา {had} เที่ยว" if had else ""))
if not args.check:
stop["derive"] = want
if had:
stop.pop("times", None) # ไม่เก็บเวลาซ้ำ — ให้เว็บคำนวณเสมอ
stop["times"] = []
txt = json.dumps(sub, ensure_ascii=False, indent=2)
if eol == "\r\n":
txt = txt.replace("\n", "\r\n")
sub_path(rid).write_text(txt + eol, encoding="utf-8", newline="")
if args.audit:
print(f"\nผลตรวจ: {len(rules) - problems}/{len(rules)} ตรงกัน" + (f" · ไม่ตรง {problems}" if problems else " ✓"))
print("\n— จุดที่ 'เวลาซ้ำกับอีกจุดในสายเดียวกัน' แต่ยังไม่มีกฎ (น่าจะต้องตั้ง derive) —")
cands = 0
for f in sorted(SUB_DIR.glob("schedules*.json")):
sub2, _ = load_sub(f.stem.replace("schedules", ""))
if not sub2:
continue
sig = {}
for d in sub2.get("directions", []):
for st in d.get("stops", []):
t = tuple(st.get("times") or [])
if t:
sig.setdefault(t, []).append((d.get("dir_id"), st["station_id"], st.get("derive")))
for times, who in sig.items():
if len(who) < 2:
continue
if any(w[2] for w in who): # มีกฎแล้วบางจุด → ถือว่าจัดการแล้ว
continue
cands += 1
print(f" · {sub2.get('route_id')}: " + " = ".join(f"จุด {w[1]} (ทิศ {w[0]})" for w in who)
+ f" · {len(times)} เที่ยวเท่ากันเป๊ะ → เลือกจุดอ้างอิง + ใส่ offset")
print(" (ไม่มี)" if not cands else f" รวม {cands} กลุ่ม")
else:
print(f"\n{'ตรวจแล้ว (ไม่เขียนไฟล์)' if args.check else 'เขียนไฟล์แล้ว'} · ปัญหา {problems} รายการ")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""รวมไฟล์ย่อย resource/data/scheduleslist/schedules<route_id>.json → schedules.json ไฟล์เดียว (schema 2)
ใช้เมื่อ: ต้องการย้อนกลับไปใช้ไฟล์เดียว (เช่น ส่งต่อ/สำรอง หรือโปรแกรมอื่นต้องการไฟล์รวม)
รัน: python resource/tools/merge-schedules.py # เขียน schedules.json (สำรองไฟล์เดิมเป็น .bak ก่อน)
python resource/tools/merge-schedules.py --check # ดูผลก่อน ไม่เขียน
"""
import argparse
import json
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DATA = ROOT / "resource" / "data"
LIST_DIR = DATA / "scheduleslist"
def jdump(o):
return json.dumps(o, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true")
args = ap.parse_args()
if not LIST_DIR.exists():
print("ไม่พบโฟลเดอร์ scheduleslist/"); return 1
files = sorted(LIST_DIR.glob("schedules*.json"),
key=lambda p: (len(p.stem.replace("schedules", "")), p.stem))
if not files:
print("ไม่พบไฟล์ย่อยใน scheduleslist/"); return 1
routes, bad = [], []
for f in files:
try:
d = json.loads(f.read_text(encoding="utf-8"))
except Exception as e:
bad.append((f.name, str(e)[:60])); continue
rid = d.get("route_id")
if rid is None:
rid = f.stem.replace("schedules", "")
routes.append({
"route_id": rid,
"station_order": d.get("station_order", []),
"directions": d.get("directions", []),
})
if bad:
print("ไฟล์ที่อ่านไม่ได้ (ข้าม):")
for n, e in bad:
print(f" {n}: {e}")
doc = {"schema": 2, "routes": routes}
trips = sum(len(s.get("times") or []) for r in routes for d in r["directions"] for s in (d.get("stops") or []))
stops = sum(len(d.get("stops") or []) for r in routes for d in r["directions"])
dirs = sum(len(r["directions"]) for r in routes)
print(f"รวมได้ {len(routes)} สาย · {dirs} ทิศ · {stops} จุด · {trips} เที่ยว")
if args.check:
print("[--check] ไม่เขียนไฟล์"); return 0
dst = DATA / "schedules.json"
if dst.exists():
shutil.copy2(dst, DATA / "schedules.json.bak")
print("สำรองไฟล์เดิมเป็น schedules.json.bak แล้ว")
dst.write_text(jdump(doc), encoding="utf-8", newline="")
print("เขียน schedules.json (ไฟล์เดียว) แล้ว")
return 0
if __name__ == "__main__":
sys.exit(main())
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""QGIS → GeoJSON สำหรับเว็บ (resource/data/geojson-web/)
*** ไม่ใช่ build step ของเว็บ *** — เว็บเป็น static (AGENTS.md ข้อ 1)
สคริปต์นี้เป็นเครื่องมือ "เตรียมข้อมูล" รันมือ หลังแก้เส้นทางใน QGIS
แหล่งข้อมูล 2 ทาง (ค่าเริ่มต้น = shapefile เพราะวิธีทำงานจริงคือแก้ใน QGIS แล้วกด Save):
python resource/tools/qgis-to-web.py # อ่าน <รหัสสาย>.shp ตามตาราง SHP_MAP (แนะนำ)
python resource/tools/qgis-to-web.py --from geojson # อ่าน GeoJSON-2/*.geojson (เส้นทางเดิม)
ธงอื่น:
--check ตรวจเทียบกับไฟล์ปัจจุบัน ไม่เขียนไฟล์
--list แสดงตารางจับคู่รหัสสาย ↔ ไฟล์ + สถานะ
กติกาที่บังคับ:
1. CRS ต้องเป็น WGS84 (EPSG:4326) — .prj ต้องบอก WGS84 และพิกัดต้องไม่ใช่ UTM (หลักล้าน)
2. จุดที่หลุดกรอบประเทศไทย (lng 97–103, lat 12–17.5) ถูกตัดออก
3. ปัดพิกัดเหลือ 5 ตำแหน่ง (แม่นยำ ~1 ม. พอสำหรับแผนที่)
4. 1 record ของ shapefile = 1 feature (MultiLineString) · properties = {"route_id": "<รหัส>"}
"""
import argparse
import json
import re
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
QDIR = ROOT / "resource" / "data" / "QGIS Project"
SRC_GEOJSON = QDIR / "GeoJSON-2"
DST = ROOT / "resource" / "data" / "geojson-web"
BBOX = (97.0, 103.0, 12.0, 17.5) # lng_min, lng_max, lat_min, lat_max
# ── ตารางจับคู่ "รหัสสาย → ไฟล์ .shp ในโปรเจกต์ QGIS" ─────────────────────────
# โปรเจกต์มีหลายเวอร์ชันต่อสาย — ตารางนี้ระบุตัวที่ป้อนเว็บ (ตรวจด้วยจุดเริ่ม/จุดจบ
# ของเส้นว่าเข้าคู่กันแล้ว) ถ้ามีการเปลี่ยนชื่อไฟล์ใน QGIS ต้องแก้ที่ตารางนี้
SHP_MAP = {
"8": "8 Bangkok-Chainat",
"15": "15 angthong-Bangkok-local",
"101": "101-Angthong-pamok-Ayuthaya",
"324": "324-Angthong-watpikungthong1",
"464": "464 -suphanburi-saraburi",
"641": "641-Angthong-lopburi1",
"902": "902",
"905": "905 bangkok-singburi",
"951": "951 Bangkok-wisead-suphanburi",
"952": "952 กรุงเทพ-วิเศษชัยชาญ",
"954": "954",
"1011": "1011",
"2194": "2194",
"2231": "2231",
"XXX1": "XXX อ่างทอง-วิเศษฯ",
"XXX2": "XXX ป่าโมก-ผักไห่",
}
# ── อ่าน shapefile (polyline = type 3, รองรับ multi-part / หลาย record) ──
def read_shp(path):
"""คืน list ของ record; แต่ละ record = list ของเส้น; แต่ละเส้น = list ของ [lng, lat]"""
b = path.read_bytes()
if len(b) < 100:
return []
recs, off = [], 100
while off + 8 <= len(b):
_, clen = struct.unpack(">ii", b[off:off + 8])
rec = b[off + 8:off + 8 + clen * 2]
off += 8 + clen * 2
if len(rec) < 44 or struct.unpack("<i", rec[:4])[0] != 3:
continue # ข้ามชนิดที่ไม่ใช่เส้น
nparts, npoints = struct.unpack("<ii", rec[36:44])
parts = struct.unpack("<%di" % nparts, rec[44:44 + 4 * nparts])
poff = 44 + 4 * nparts
pts = [struct.unpack("<dd", rec[poff + 16 * i:poff + 16 * i + 16]) for i in range(npoints)]
lines = []
for i in range(nparts):
a = parts[i]
z = parts[i + 1] if i + 1 < nparts else npoints
if pts[a:z]:
lines.append([[x, y] for x, y in pts[a:z]])
if lines:
recs.append(lines)
return recs
def prj_ok(path):
"""ตรวจ .prj ว่าเป็น WGS84 (ไม่ใช่ UTM/meters) — ไม่มี .prj = เตือนแต่ไปต่อ (มีตัวกรอง bbox อีกชั้น)"""
prj = path.with_suffix(".prj")
if not prj.exists():
return None # ไม่มีข้อมูล CRS
t = prj.read_text(encoding="utf-8", errors="replace")
if "UTM" in t or "Transverse_Mercator" in t:
return False
return "4326" in t or "WGS_1984" in t
# ── ตัวกรอง/ทำความสะอาด (ใช้ร่วมกันทั้งสองแหล่ง) ──
def clean_lines(lines):
lng0, lng1, lat0, lat1 = BBOX
kept, dropped = [], 0
for l in lines:
good = [c for c in l if lng0 < float(c[0]) < lng1 and lat0 < float(c[1]) < lat1]
if len(good) >= 2:
kept.append([[round(float(c[0]), 5), round(float(c[1]), 5)] for c in good])
else:
dropped += 1
return kept, dropped
def looks_like_utm(lines):
xs = [c[0] for l in lines for c in l] or [0]
return max(abs(min(xs)), abs(max(xs))) > 1000
def from_shp(route_id):
"""คืน (features, รายงาน) จาก shapefile ตาม SHP_MAP"""
stem = SHP_MAP.get(route_id)
if not stem:
return None, ["ไม่มีในตาราง SHP_MAP — ข้าม"]
path = QDIR / f"{stem}.shp"
if not path.exists():
return None, [f"ไม่พบไฟล์ {path.name} (ชื่อเปลี่ยน? แก้ SHP_MAP)"]
ok = prj_ok(path)
if ok is False:
return None, [f"CRS ของ {path.name} เป็น UTM — ต้องบันทึกใหม่เป็น EPSG:4326"]
recs = read_shp(path)
if not recs:
return None, ["shapefile ไม่มีเส้น (หรือพิกัดว่าง)"]
if looks_like_utm([l for r in recs for l in r]):
return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — บันทึกใหม่โดยตั้ง CRS = EPSG:4326"]
feats, dropped, pts = [], 0, 0
for rec in recs:
kept, d = clean_lines(rec)
dropped += d
if not kept:
continue
feats.append({"type": "Feature", "properties": {"route_id": route_id},
"geometry": {"type": "MultiLineString", "coordinates": kept}})
pts += sum(len(l) for l in kept)
if not feats:
return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"]
notes = [f"ไม่มี .prj (ไม่ทราบ CRS — ตรวจด้วยกรอบประเทศไทย)" if ok is None else ""]
if dropped:
notes.append(f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ")
return feats, [n for n in notes if n]
def from_geojson(route_id):
"""คืน (features, รายงาน) จาก GeoJSON-2/<รหัส>.geojson (เส้นทางเดิม)"""
path = SRC_GEOJSON / f"{route_id}.geojson"
if not path.exists():
return None, ["ไม่พบไฟล์ใน GeoJSON-2 — ข้าม"]
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as e:
return None, [f"อ่าน JSON ไม่ได้: {e}"]
feats_in = data.get("features", [])
all_lines = []
for f in feats_in:
g = f.get("geometry") or {}
cs = g.get("coordinates") or []
all_lines += ([cs] if g.get("type") == "LineString" else cs)
if not all_lines:
return None, ["ไม่มีพิกัดในไฟล์ (coordinates ว่าง) — ข้าม"]
if looks_like_utm([l for l in all_lines if l]):
return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — export ใหม่โดยตั้ง CRS = EPSG:4326"]
out, dropped = [], 0
for f in feats_in:
g = f.get("geometry") or {}
gtype, src = g.get("type"), []
cs = g.get("coordinates") or []
src = [cs] if gtype == "LineString" else cs
if gtype not in ("LineString", "MultiLineString") or not src:
continue
kept, d = clean_lines(src)
dropped += d
if not kept:
continue
if gtype == "LineString" and len(kept) > 1:
gtype = "MultiLineString"
out.append({"type": "Feature", "properties": {"route_id": route_id},
"geometry": {"type": gtype, "coordinates": kept[0] if gtype == "LineString" else kept}})
if not out:
return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"]
notes = [f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ"] if dropped else []
return out, notes
def targets(mode):
"""รายการ route_id ที่จะสร้าง (จากตาราง SHP_MAP หรือไฟล์ GeoJSON-2)"""
if mode == "shp":
return sorted(SHP_MAP)
return sorted(p.stem for p in SRC_GEOJSON.glob("*.geojson"))
def main():
ap = argparse.ArgumentParser(description="QGIS (shapefile/GeoJSON) → resource/data/geojson-web/")
ap.add_argument("--from", dest="src", choices=["shp", "geojson"], default="shp",
help="แหล่งข้อมูล (ค่าเริ่มต้น shp)")
ap.add_argument("--check", action="store_true", help="ตรวจอย่างเดียว ไม่เขียนไฟล์")
ap.add_argument("--list", action="store_true", help="แสดงตารางจับคู่ + สถานะไฟล์")
args = ap.parse_args()
ids = targets(args.src)
if args.list:
print(f"{'สาย':<8}{'ไฟล์ต้นทาง':<46}{'มีไฟล์':<8}{'.prj':<14}ไฟล์เว็บปัจจุบัน")
for rid in ids:
stem = SHP_MAP.get(rid, "")
p = QDIR / f"{stem}.shp"
prj = "WGS84 ✓" if prj_ok(p) is True else ("UTM ❌" if prj_ok(p) is False else "ไม่มี")
web = DST / f"{rid}.geojson"
print(f"{rid:<8}{stem[:44]:<46}{'มี' if p.exists() else '❌ ไม่มี':<8}{prj:<14}{'มี' if web.exists() else '—'}")
return
from_shp_source = args.src == "shp"
label = "shapefile (QGIS Project/*.shp)" if from_shp_source else "GeoJSON-2/*.geojson"
print(f"ต้นทาง : {label} ({len(ids)} สาย)")
print(f"ปลายทาง: {DST.relative_to(ROOT)}" + (" [--check: ไม่เขียนไฟล์]\n" if args.check else "\n"))
DST.mkdir(parents=True, exist_ok=True)
print(f"{'สาย':<8}{'จุด':<7}{'ไฟล์เดิม':<10}สถานะ")
written = skipped = unchanged = 0
for rid in ids:
rid = re.sub(r"[^0-9A-Za-z]", "", rid) or rid
feats, notes = (from_shp(rid) if from_shp_source else from_geojson(rid))
if feats is None:
print(f"{rid:<8}{'-':<7}{'-':<10}ข้าม — {'; '.join(notes)}")
skipped += 1
continue
out = DST / f"{rid}.geojson"
had_old = out.exists()
old_kb = f"{out.stat().st_size // 1024}KB" if had_old else "-"
payload = json.dumps({"type": "FeatureCollection", "features": feats},
ensure_ascii=False, separators=(",", ":"))
n = sum(len(l) for f in feats for l in
([f["geometry"]["coordinates"]] if f["geometry"]["type"] == "LineString" else f["geometry"]["coordinates"]))
same = had_old and out.read_text(encoding="utf-8").strip() == payload.strip()
if args.check:
state = "เหมือนเดิม ✓" if same else ("ต่างจากเดิม ⚠️" if had_old else "ไฟล์ใหม่")
print(f"{rid:<8}{n:<7}{old_kb:<10}{state}")
continue
if same:
print(f"{rid:<8}{n:<7}{old_kb:<10}ไม่เปลี่ยน — ข้ามการเขียน")
unchanged += 1
continue
out.write_text(payload, encoding="utf-8")
written += 1
print(f"{rid:<8}{n:<7}{old_kb:<10}เขียนแล้ว ({len(payload) // 1024}KB)"
+ (f" — {'; '.join(notes)}" if notes else ""))
print(f"\nสรุป: เขียน {written} · ไม่เปลี่ยน {unchanged} · ข้าม {skipped}"
+ (" (โหมด --check)" if args.check else ""))
if not args.check and written:
print("ขั้นถัดไป: เปิดเว็บกด Ctrl+Shift+R (ไฟล์ .geojson เป็น network-first — ไม่ต้อง bump VERSION)")
if __name__ == "__main__":
main()
+212
View File
@@ -0,0 +1,212 @@
#!/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())
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""แตก resource/data/schedules.json → resource/data/scheduleslist/schedules<route_id>.json (1 ไฟล์ = 1 เส้นทาง)
และเขียน schedules.json ให้เป็น "สารบัญ" (index) ชี้ไปไฟล์ย่อย
ทำไม: ไฟล์เดียวรวม 14 สายอ่านยาก/แก้ยาก และเวลาแก้ทีละสายต้องเปิดทั้งไฟล์ → แยกเป็นไฟล์ต่อสาย
รูปแบบไฟล์:
scheduleslist/schedules101.json = { "schema": 2, "route_id": "101", "generated_from": "schedules.json",
"station_order": [...], "directions": [ ... ] } (เนื้อในเหมือนเดิมเป๊ะ)
schedules.json (สารบัญ) = { "schema": 2, "index": true, "dir": "scheduleslist/",
"routes": [ { "route_id": "101", "file": "schedules101.json", ... } ] }
รัน: python resource/tools/split-schedules.py # เขียนไฟล์จริง
python resource/tools/split-schedules.py --check # ดูผลก่อน ไม่เขียน
หมายเหตุ: ถ้า schedules.json เป็นสารบัญอยู่แล้ว คำสั่งนี้จะไม่ทำอะไร (กันเขียนทับไฟล์ย่อย) — ใช้ merge-schedules.py ย้อนกลับ
"""
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DATA = ROOT / "resource" / "data"
LIST_DIR = DATA / "scheduleslist"
def jdump(obj):
return json.dumps(obj, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true")
args = ap.parse_args()
src = DATA / "schedules.json"
if not src.exists():
print("ไม่พบ schedules.json"); return 1
doc = json.loads(src.read_text(encoding="utf-8"))
if doc.get("index") or "directions" not in json.dumps(doc)[:200]:
if doc.get("index"):
print("schedules.json เป็นสารบัญอยู่แล้ว — ไม่ต้องแตกไฟล์ซ้ำ")
print("(ถ้าต้องการย้อนกลับเป็นไฟล์เดียว ใช้ resource/tools/merge-schedules.py)")
return 0
routes = doc.get("routes") or []
if not routes:
print("ไม่พบ routes[] ในไฟล์"); return 1
LIST_DIR.mkdir(exist_ok=True)
index_rows = []
for r in routes:
rid = str(r["route_id"])
sub = {
"schema": doc.get("schema", 2),
"route_id": r["route_id"],
"generated_from": "schedules.json",
"station_order": r.get("station_order", []),
"directions": r.get("directions", []),
}
fname = "schedules" + rid + ".json"
if not args.check:
(LIST_DIR / fname).write_text(jdump(sub), encoding="utf-8", newline="")
counts = {"n_directions": len(sub["directions"]),
"n_stops": sum(len(d.get("stops") or []) for d in sub["directions"]),
"n_trips": sum(len(s.get("times") or []) for d in sub["directions"] for s in (d.get("stops") or []))}
index_rows.append({"route_id": r["route_id"], "file": fname, **counts})
index = {
"schema": doc.get("schema", 2),
"index": True,
"note": "สารบัญชี้ไป scheduleslist/schedules<route_id>.json (1 ไฟล์ = 1 เส้นทาง) — แก้ไฟล์ย่อยนั้นโดยตรง หรือใช้ resource/data/schedules-editor.html",
"dir": "scheduleslist/",
"routes": index_rows,
}
if not args.check:
src.write_text(jdump(index), encoding="utf-8", newline="")
print(("ตรวจเท่านั้น: " if args.check else "เขียนแล้ว: ") + f"{len(index_rows)} ไฟล์ใน scheduleslist/ + สารบัญ schedules.json")
for row in index_rows:
print(f" {row['file']:<26} ทิศ {row['n_directions']:>2} · จุด {row['n_stops']:>2} · เที่ยว {row['n_trips']:>3}")
return 0
if __name__ == "__main__":
sys.exit(main())
+179
View File
@@ -0,0 +1,179 @@
#!/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())