#!/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())