#!/usr/bin/env python3 # -*- coding: utf-8 -*- """รวมไฟล์ย่อย resource/data/scheduleslist/schedules.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())