แผนที่จาก 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 (จุดอ้างอิง ± นาที)
This commit is contained in:
Bkk1234 committed 2026-10-05 03:55:09 +07:00
1 parent 1cfaeb1526
commit 656f65b41c
109 files changed
+3335 -1225

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""bump-version.py — เพิ่มเวอร์ชันแอป (cache busting) ให้ตรงกันทุกที่ในคำสั่งเดียว
ทำอะไร:
1) ui/sw.js const VERSION = "..." ← ตัวจริง (cache-first ใช้ค่านี้)
2) ui/index.html <meta name="app-version" ...> ← ให้ ImgURL.of() ใช้
3) ui/index.html โลโก้/ไอคอน ?v=... (static) ← รูปที่ฝังใน HTML
วิธีใช้:
python resource/tools/bump-version.py # +1 รอบ (เช่น 2026.09.27.23 → .24)
python resource/tools/bump-version.py 2026.10.01 # ตั้งค่าเอง (จะได้ 2026.10.01.1)
python resource/tools/bump-version.py --show # แค่แสดงเวอร์ชันปัจจุบัน (ไม่เขียน)
python resource/tools/bump-version.py --sync # ไม่เพิ่มเลข แค่ทำให้ทุกที่ตรงกับ sw.js
หลังอัปรูป: รันคำสั่งนี้ แล้วให้ผู้ใช้กด Ctrl+Shift+R ครั้งเดียว = เห็นรูปใหม่ทั้งหมด
"""
import argparse
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
UI = ROOT / "ui"
SW = UI / "sw.js"
INDEX = UI / "index.html"
VER_RE = re.compile(r'const VERSION = "([^"]+)";')
def read_version():
m = VER_RE.search(SW.read_text(encoding="utf-8"))
if not m:
sys.exit("ไม่พบ const VERSION ใน ui/sw.js")
return m.group(1)
def next_version(cur, base=None):
"""cur = '2026.09.27.23' → '2026.09.27.24' · base='2026.10.01' → '2026.10.01.1'"""
if base:
m = re.match(r"^(\d{4}\.\d{2}\.\d{2})(?:\.(\d+))?$", base.strip())
if not m:
sys.exit(f"รูปแบบวันที่ไม่ถูกต้อง: {base} (ต้องเป็น YYYY.MM.DD)")
n = int(m.group(2) or 0) + 1
return f"{m.group(1)}.{n}"
parts = cur.split(".")
if len(parts) < 4 or not parts[-1].isdigit():
return cur + ".1"
return ".".join(parts[:-1] + [str(int(parts[-1]) + 1)])
def apply(ver, dry=False):
changed = []
# 1) sw.js
sw = SW.read_text(encoding="utf-8")
sw2 = VER_RE.sub(f'const VERSION = "{ver}";', sw, count=1)
if sw2 != sw:
if not dry:
SW.write_text(sw2, encoding="utf-8")
changed.append("ui/sw.js")
# 2) index.html — meta + โลโก้ static (?v=)
idx = INDEX.read_text(encoding="utf-8")
idx2 = re.sub(r'(<meta name="app-version" content=")[^"]*(">)', rf"\g<1>{ver}\g<2>", idx)
idx2 = re.sub(r'(\.image/icons/[^"?]+\.(?:png|jpg|jpeg|webp|svg))\?v=[^"&]*', rf"\g<1>?v={ver}", idx2)
if idx2 != idx:
if not dry:
INDEX.write_text(idx2, encoding="utf-8")
changed.append("ui/index.html")
return changed
def report(ver, changed, dry=False):
n_img = len(re.findall(r"\.image/[^\"]+\?v=", INDEX.read_text(encoding="utf-8")))
print(f"เวอร์ชัน: {ver}" + (" [dry-run]" if dry else ""))
print(f" แก้ไฟล์: {', '.join(changed) if changed else 'ไม่มี (ตรงกันอยู่แล้ว)'}")
print(f" รูป static ที่เติม ?v= ใน index.html: {n_img} จุด")
print(f" รูป dynamic (routes/qrcode/stations/stops): เติมอัตโนมัติผ่าน ImgURL.of()")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("base", nargs="?", help="วันที่ฐาน YYYY.MM.DD (ไม่ใส่ = เพิ่มเลขรอบเดิม)")
ap.add_argument("--show", action="store_true", help="แสดงเวอร์ชันปัจจุบัน")
ap.add_argument("--sync", action="store_true", help="ทำให้ทุกที่ตรงกับ sw.js (ไม่เพิ่มเลข)")
ap.add_argument("--check", action="store_true", help="ตรวจว่าทุกที่ตรงกันไหม (exit 1 ถ้าไม่ตรง)")
args = ap.parse_args()
cur = read_version()
if args.show:
print(f"เวอร์ชันปัจจุบัน: {cur}")
return 0
if args.check:
idx = INDEX.read_text(encoding="utf-8")
m = re.search(r'<meta name="app-version" content="([^"]*)"', idx)
meta = m.group(1) if m else None
logos = set(re.findall(r"\.image/icons/[^\"]+?\?v=([^\"&]+)", idx))
ok = (meta == cur) and (logos == {cur} or not logos)
print(f"sw.js VERSION = {cur}")
print(f"meta app-version= {meta} {'✓' if meta == cur else '✗ ไม่ตรง'}")
print(f"โลโก้ ?v= = {sorted(logos) or '-'} {'✓' if (logos == {cur} or not logos) else '✗ ไม่ตรง'}")
return 0 if ok else 1
ver = cur if args.sync else next_version(cur, args.base)
changed = apply(ver, dry=False)
report(ver, changed)
print("\nขั้นตอนถัดไป: ให้ผู้ใช้กด Ctrl+Shift+R ครั้งเดียว (รูปทั้งหมดจะโหลดใหม่)")
return 0
if __name__ == "__main__":
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""check-i18n.py — ตรวจความครบถ้วนของคำแปล (ui/locales/<lang>.json)
ตรวจ 5 เรื่อง:
1. คีย์ที่ขาดในภาษาใดภาษาหนึ่ง → ERROR (โหมดนั้นจะถอยไปใช้ภาษาตั้งต้น = คำไทยโผล่ในหน้า EN)
2. คีย์ซ้ำภายในไฟล์ภาษาเดียวกัน → ERROR (JSON เก็บตัวหลังเงียบ ๆ — เคยทำให้ค่าอังกฤษทับค่าไทย)
3. ไฟล์ภาษาไม่ตรงกับ SUPPORTED ใน i18n.js → ERROR
4. ค่าที่ว่างเปล่า → WARN (อาจตั้งใจ เช่น home.provincePrefix ของ EN)
5. คีย์ที่ไม่พบที่ใช้ → WARN (อาจใช้แบบไดนามิกก็ได้)
ใช้:
python resource/tools/check-i18n.py
python resource/tools/check-i18n.py --quiet (แสดงเฉพาะที่มีปัญหา)
"""
import json
import re
import sys
from pathlib import Path
R = Path(__file__).resolve().parents[2]
LOCALES = R / "ui/locales"
BASE = "th" # ภาษาตั้งต้น — ใช้เทียบว่าคีย์ครบไหม
quiet = "--quiet" in sys.argv
errors, warns = [], []
# ── 1) อ่านไฟล์ภาษาทั้งหมด (จับคีย์ซ้ำด้วย object_pairs_hook) ──
files = sorted(LOCALES.glob("*.json"))
if not files:
print(f"!! ไม่พบไฟล์ภาษาใน {LOCALES.relative_to(R)}")
sys.exit(1)
dicts, dups = {}, {}
for p in files:
lg = p.stem
found = []
def hook(pairs, _found=found):
seen = {}
for k, v in pairs:
if k in seen:
_found.append(k)
seen[k] = v
return seen
try:
dicts[lg] = json.loads(p.read_text(encoding="utf-8"), object_pairs_hook=hook)
except Exception as e:
errors.append((f"อ่านไฟล์ {p.name} ไม่ได้", [str(e)[:70]]))
continue
if found:
dups[lg] = found
langs = sorted(dicts)
if BASE not in dicts:
errors.append((f"ไม่พบภาษาตั้งต้น '{BASE}'", [str(l) for l in langs]))
# ── 2) ไฟล์ภาษาต้องตรงกับ SUPPORTED ใน i18n.js ──
src = (R / "ui/i18n.js").read_text(encoding="utf-8")
m = re.search(r"var SUPPORTED\s*=\s*\[([^\]]*)\]", src)
supported = re.findall(r"'([\w-]+)'", m.group(1)) if m else []
if supported and sorted(supported) != langs:
errors.append(("SUPPORTED ใน i18n.js ไม่ตรงกับไฟล์ภาษา",
[f"js={supported}", f"files={langs}"]))
# ── 3) คีย์ขาด / คีย์ซ้ำ ──
base_keys = list(dicts.get(BASE, {}))
for lg in langs:
if lg == BASE:
continue
missing = [k for k in base_keys if k not in dicts[lg]]
if missing:
errors.append((f"คีย์ขาดใน '{lg}' ({len(missing)})", missing))
extra = [k for k in dicts[lg] if k not in dicts[BASE]]
if extra:
warns.append((f"คีย์ที่มีใน '{lg}' แต่ไม่มีใน '{BASE}' ({len(extra)})", extra))
for lg in sorted(dups):
errors.append((f"คีย์ซ้ำในไฟล์ '{lg}.json' ({len(set(dups[lg]))})", sorted(set(dups[lg]))))
# ── 4) ค่าที่ว่างเปล่า ──
empty = [f"{lg}:{k}" for lg in langs for k, v in dicts[lg].items() if not str(v).strip()]
if empty:
warns.append((f"ค่าที่ว่างเปล่า ({len(empty)}) — อาจตั้งใจ", empty))
# ── 5) คีย์ที่ไม่พบที่ใช้ ──
# ตรงตัว: t('key') · data-i18n="key" · data-i18n-attr="attr:key"
# ไดนามิก: literal ที่ลงท้ายด้วย '.' เป็นคำนำหน้าคีย์ (เช่น 'check.day' + type)
used, all_lits = set(), set()
for f in list((R / "ui").rglob("*.js")) + list((R / "ui").rglob("*.html")):
if "vendor" in str(f) or f.name == "i18n.js":
continue
txt = f.read_text(encoding="utf-8", errors="ignore")
used |= set(re.findall(r"""tr?\('([\w.]+)'""", txt))
used |= set(re.findall(r'data-i18n(?:-n)?="([\w.]+)"', txt))
used |= set(re.findall(r'data-i18n-attr="[^":]+:([\w.]+)"', txt))
all_lits |= set(re.findall(r"'([\w.]{2,80})'", txt))
prefixes = {x for x in all_lits if x.endswith(".")}
unused = sorted(k for k in base_keys
if k not in used and k not in all_lits
and not any(k.startswith(p) for p in prefixes))
if unused:
warns.append((f"ไม่พบที่ใช้ ({len(unused)}) — อาจใช้แบบไดนามิกก็ได้", unused))
# ── รายงาน ──
if not quiet:
print("i18n: ui/locales/ · " + " · ".join(f"{lg}={len(dicts[lg])}" for lg in langs) +
f" · ภาษาตั้งต้น={BASE} · ไฟล์ที่ใช้จริง {LOCALES.relative_to(R)}")
for title, items in errors:
print(f"[ERROR] {title}: {', '.join(str(i) for i in items[:12])}" + (" …" if len(items) > 12 else ""))
for title, items in warns:
print(f"[WARN ] {title}: {', '.join(str(i) for i in items[:12])}" + (" …" if len(items) > 12 else ""))
if errors:
print(f"\nผลลัพธ์: ไม่ผ่าน — {len(errors)} เรื่องต้องแก้")
sys.exit(1)
print(f"\nผลลัพธ์: ผ่าน — ทุกคีย์มีครบทั้ง {len(langs)} ภาษา ไม่มีคีย์ซ้ำ" +
(f" (มี {len(warns)} คำเตือน)" if warns else ""))
sys.exit(0)
+2 -2
View File
@@ -72,7 +72,7 @@ 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 s["times"], d.get("direction_id")
return [], None
@@ -160,7 +160,7 @@ def main():
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")))
sig.setdefault(t, []).append((d.get("direction_id"), st["station_id"], st.get("derive")))
for times, who in sig.items():
if len(who) < 2:
continue
+107 -4
View File
@@ -8,6 +8,7 @@
แหล่งข้อมูล 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 (เส้นทางเดิม)
python resource/tools/qgis-to-web.py --from gpkg # อ่าน angthongtoanytrain/*.gpkg (เส้นทางที่เสนอ/ความฝัน)
ธงอื่น:
--check ตรวจเทียบกับไฟล์ปัจจุบัน ไม่เขียนไฟล์
@@ -29,7 +30,20 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
QDIR = ROOT / "resource" / "data" / "QGIS Project"
SRC_GEOJSON = QDIR / "GeoJSON-2"
SRC_GPKG = QDIR / "angthongtoanytrain" # เส้นทางที่เสนอ (ยังไม่มีจริง) — 1 ไฟล์ = 1 เส้นทาง
DST = ROOT / "resource" / "data" / "geojson-web"
# ── ตารางจับคู่ "ชื่อไฟล์ .gpkg → route_id" (เส้นทางที่เสนอ) ──────────────────
# route_id ต้องไม่ชนกับสายจริง (902/15/951/952/954/8/101/464/641/2194/324/1011/2231/999)
# ชื่อไฟล์ .gpkg เป็นภาษาไทยได้ — คีย์คือชื่อ stem (ไม่รวม .gpkg)
GPKG_MAP = {
"อ่างทอง-บ้านภาชี(สายสีแดงเข้ม)": "dream-banchang",
"อ่างทอง-รถไฟฟ้าชานเมืองอยุธยา(สายสีแดงเข้ม)": "dream-ayutthaya-redline",
"อ่างทอง-สถานีรถไฟความเร็วสูงอยุธยา": "dream-ayutthaya-hsr",
"อ่างทอง-เมืองทองธานี": "dream-muangthong",
"อ่างทอง-แยกปากเกร็ด": "dream-pakkret",
"อ่างทอง-วัชรพล": "dream-Watcharapol",
}
BBOX = (97.0, 103.0, 12.0, 17.5) # lng_min, lng_max, lat_min, lat_max
# ── ตารางจับคู่ "รหัสสาย → ไฟล์ .shp ในโปรเจกต์ QGIS" ─────────────────────────
@@ -112,6 +126,85 @@ def looks_like_utm(lines):
return max(abs(min(xs)), abs(max(xs))) > 1000
# ── อ่าน GeoPackage (.gpkg = SQLite) — ไม่ต้องพึ่ง GDAL/geopandas ──
def read_gpkg(path):
"""คืน (lines, srs_id, ชื่อชั้น) — รองรับ LineString/MultiLineString · พิกัด (lng, lat)
GPKG geometry blob = 'GP' + ver(1) + flags(1) + srs_id(4) + envelope(ตาม flags) + WKB"""
import sqlite3
con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
try:
cur = con.cursor()
row = cur.execute(
"SELECT table_name FROM gpkg_contents WHERE data_type='features' LIMIT 1").fetchone()
if not row:
return None, None, None
table = row[0]
srs = cur.execute("SELECT srs_id FROM gpkg_geometry_columns WHERE table_name=?",
(table,)).fetchone()
blob = cur.execute(f'SELECT geometry FROM "{table}" LIMIT 1').fetchone()[0]
finally:
con.close()
return _parse_gpkg_blob(blob), (srs[0] if srs else None), table
def _parse_gpkg_blob(blob):
"""ถอด WKB จาก GPKG blob → list ของเส้น; แต่ละเส้น = list ของ [lng, lat]"""
if not blob or blob[:2] != b"GP":
return []
flags = blob[3]
env = {0: 0, 1: 4, 2: 6, 3: 6, 4: 8}.get((flags >> 1) & 0x07, 0)
o = 8 + env * 8
order = blob[o]
E = "<" if order == 1 else ">"
gtype = struct.unpack(E + "I", blob[o + 1:o + 5])[0]
o += 5
lines = []
if gtype == 2: # LineString
n = struct.unpack(E + "I", blob[o:o + 4])[0]
o += 4
lines.append([list(struct.unpack(E + "dd", blob[o + 16 * i:o + 16 * i + 16]))
for i in range(n)])
elif gtype == 5: # MultiLineString
n = struct.unpack(E + "I", blob[o:o + 4])[0]
o += 4
for _ in range(n):
E2 = "<" if blob[o] == 1 else ">"
m = struct.unpack(E2 + "I", blob[o + 5:o + 9])[0]
o += 9
lines.append([list(struct.unpack(E2 + "dd", blob[o + 16 * i:o + 16 * i + 16]))
for i in range(m)])
o += 16 * m
return [l for l in lines if len(l) >= 2]
def from_gpkg(route_id):
"""คืน (features, รายงาน) จาก angthongtoanytrain/<ชื่อ>.gpkg ตาม GPKG_MAP"""
stem = next((k for k, v in GPKG_MAP.items() if v == route_id), None)
if stem is None:
return None, ["ไม่มีในตาราง GPKG_MAP — ข้าม"]
path = SRC_GPKG / f"{stem}.gpkg"
if not path.exists():
return None, [f"ไม่พบไฟล์ {path.name} (ชื่อเปลี่ยน? แก้ GPKG_MAP)"]
lines, srs, table = read_gpkg(path)
if not lines:
return None, ["ไม่มีเส้นในไฟล์ (หรือชนิด geometry ไม่รองรับ)"]
if srs not in (None, 4326):
return None, [f"SRS = {srs} (ไม่ใช่ EPSG:4326) — บันทึกใหม่ใน QGIS"]
if looks_like_utm(lines):
return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — บันทึกใหม่โดยตั้ง CRS = EPSG:4326"]
kept, dropped = clean_lines(lines)
if not kept:
return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"]
geom = ("MultiLineString" if len(kept) > 1 else "LineString")
feat = {"type": "Feature", "properties": {"route_id": route_id},
"geometry": {"type": geom, "coordinates": (kept if len(kept) > 1 else kept[0])}}
notes = [f"ชั้น '{table}' · srs={srs}"]
if dropped:
notes.append(f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ")
return [feat], notes
def from_shp(route_id):
"""คืน (features, รายงาน) จาก shapefile ตาม SHP_MAP"""
stem = SHP_MAP.get(route_id)
@@ -193,12 +286,14 @@ def targets(mode):
"""รายการ route_id ที่จะสร้าง (จากตาราง SHP_MAP หรือไฟล์ GeoJSON-2)"""
if mode == "shp":
return sorted(SHP_MAP)
if mode == "gpkg":
return sorted(GPKG_MAP.values())
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",
ap.add_argument("--from", dest="src", choices=["shp", "geojson", "gpkg"], default="shp",
help="แหล่งข้อมูล (ค่าเริ่มต้น shp)")
ap.add_argument("--check", action="store_true", help="ตรวจอย่างเดียว ไม่เขียนไฟล์")
ap.add_argument("--list", action="store_true", help="แสดงตารางจับคู่ + สถานะไฟล์")
@@ -216,7 +311,9 @@ def main():
return
from_shp_source = args.src == "shp"
label = "shapefile (QGIS Project/*.shp)" if from_shp_source else "GeoJSON-2/*.geojson"
label = {"shp": "shapefile (QGIS Project/*.shp)",
"geojson": "GeoJSON-2/*.geojson",
"gpkg": "angthongtoanytrain/*.gpkg (เส้นทางที่เสนอ)"}[args.src]
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)
@@ -224,8 +321,14 @@ def main():
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 args.src != "gpkg": # dream-* มี "-" ต้องคงไว้
rid = re.sub(r"[^0-9A-Za-z]", "", rid) or rid
if args.src == "shp":
feats, notes = from_shp(rid)
elif args.src == "gpkg":
feats, notes = from_gpkg(rid)
else:
feats, notes = from_geojson(rid)
if feats is None:
print(f"{rid:<8}{'-':<7}{'-':<10}ข้าม — {'; '.join(notes)}")
skipped += 1
+11 -11
View File
@@ -11,16 +11,16 @@
stops[] จุดจอดในทิศนั้น
station_id
times[] เวลาออกของจุดนี้
dir_note ถ้อยคำทิศเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
direction_note ถ้อยคำทิศเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
note เงื่อนไขเวลาเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง)
groups[] (อนาคต) ใช้เมื่อเวลาชุดเดียวกันแยกตามวัน เช่น 10:00 เฉพาะวันหยุด
กติกาการแยกทิศ (ยึดข้อมูลจริง):
- "จุดแยกทิศ" = จุดที่มี record หลายทิศ = จุดที่รถแยกทาง (เช่น สาย 101 จุด 2 ป่าโมก มีทั้ง 'ไปอยุธยา'/'ไปออ่างทอง')
- record ที่ไม่ระบุทิศ → ใช้ทิศของจุดแยกทิศที่อยู่ก่อนหน้าในลำดับ (จุดที่รถผ่านมาก่อน)
- สายที่ไม่ระบุทิศเลย → ทิศเดียว dir_id = "all"
- สายที่ไม่ระบุทิศเลย → ทิศเดียว direction_id = "all"
หมายเหตุ: เลิกใช้ schedule_id (ไม่มีโค้ดไหนอ้างถึง) — กุญแจคือ route_id + dir_id + station_id
หมายเหตุ: เลิกใช้ schedule_id (ไม่มีโค้ดไหนอ้างถึง) — กุญแจคือ route_id + direction_id + station_id
"""
import argparse
import json
@@ -95,8 +95,8 @@ def orient_order(rid, order, stations):
def direction_of(rec, first_station):
"""ทิศของ record ตามข้อมูลที่ระบุไว้จริง
- มี direction_note → ทิศนั้น (แยกเป็น directions[] ของตัวเอง)
- ไม่มี note + เป็นจุดต้นทาง (station_order[0]) → 'ออกจากต้นทาง' (dir_id = from-<station>)
- ไม่มี note + จุดอื่น → ทิศทางเดียว (dir_id = "all")
- ไม่มี note + เป็นจุดต้นทาง (station_order[0]) → 'ออกจากต้นทาง' (direction_id = from-<station>)
- ไม่มี note + จุดอื่น → ทิศทางเดียว (direction_id = "all")
ไม่พยายามเดาว่าจุดปลายทางอยู่ขาไหน (ข้อมูลเดิมขัดกันเอง — ต้องให้เจ้าของข้อมูลยืนยัน)
"""
label = rec.get("direction_note")
@@ -146,17 +146,17 @@ def main():
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"]
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))
dir_id = "all" if kind == "all" else (("from-%s" % val) if kind == "start" else "dir-%d" % dir_seq)
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({
"dir_id": dir_id,
"dir_label": d["label"],
"direction_id": direction_id,
"direction_label": d["label"],
"stops": stops,
})
n_dup += sum(len(s["times"]) for s in stops)
@@ -166,7 +166,7 @@ def main():
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"สาย {rid} ทิศ '{dl['direction_label'] or 'ไม่แยกทิศ'}': จำนวนเที่ยวไม่เท่ากันข้ามจุด {counts} "
f"— อาจยังแยกทิศไม่ครบ (ต้องให้เจ้าของข้อมูลยืนยัน)")
# เตือนจุดจอดที่ไม่มีเวลา (ไม่สร้างข้อมูลปลอม — UI จะขึ้น "ยังไม่มีข้อมูล")
@@ -191,7 +191,7 @@ def main():
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}"
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:
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""stamp-schedules.py — เติม/อัปเดตฟิลด์ "updated" (ISO YYYY-MM-DD) ใน scheduleslist/*.json
ที่มา: หน้า #/check แสดง "อัปเดตล่าสุด ... ที่แล้ว" โดยนับจากฟิลด์ "updated" ในไฟล์ตาราง
เบราว์เซอร์อ่าน Last-Modified ของไฟล์ไม่ได้ (CORS) → ต้องบันทึกวันลงในไฟล์เอง
หลักการ:
- วันที่ = mtime ของไฟล์จริง (เวลาแก้ไขล่าสุดบนดิสก์) แปลงเป็นเวลาไทย UTC+7
- --check : ดูอย่างเดียว ไม่เขียนอะไร (dry run)
- ไม่มี flag: เขียนไฟล์ที่ต้องแก้ (คง CRLF เดิมไว้)
ใช้:
python resource/tools/stamp-schedules.py --check
python resource/tools/stamp-schedules.py
"""
import datetime
import json
import re
import sys
from pathlib import Path
R = Path(__file__).resolve().parents[2]
D = R / "resource/data/scheduleslist"
TZ_OFFSET = datetime.timedelta(hours=7) # เวลาไทย
dry = "--check" in sys.argv
def today_th():
return (datetime.datetime.now(datetime.timezone.utc) + TZ_OFFSET).date()
def mtime_date(p):
return (datetime.datetime.fromtimestamp(p.stat().st_mtime, datetime.timezone.utc) + TZ_OFFSET).date()
def stamp_file(p):
"""เติม/แก้ 'updated' หลัง route_id · คงรูปแบบ/CRLF เดิม · คืน (old, new, changed)"""
raw = p.read_bytes()
eol = b"\r\n" if b"\r\n" in raw[:4000] else b"\n"
txt = raw.decode("utf-8")
d = json.loads(txt)
if not isinstance(d, dict) or "route_id" not in d:
return None, None, False
want = mtime_date(p).isoformat()
have = str(d.get("updated") or "")
if have == want:
return have, want, False
if re.search(r'^\s*"updated"\s*:\s*"[^"]*",\s*$', txt, re.M):
new = re.sub(r'(^\s*"updated"\s*:\s*")[^"]*(",\s*$)', lambda m: m.group(1) + want + m.group(2),
txt, count=1, flags=re.M)
else:
# แทรกหลังบรรทัด route_id (คงการเยื้องเดิม)
m = re.search(r'^(\s*)"route_id"\s*:\s*("[^"]*"\s*,?\s*)$', txt, re.M)
if not m:
return have, want, False
indent = m.group(1)
new = txt[:m.end(1) + len(m.group(0)) - len(m.group(0).lstrip())] # กันพลาด
ins = m.group(0) if m.group(0).rstrip().endswith(",") else m.group(0).rstrip() + ","
eol_s = eol.decode()
new = txt.replace(m.group(0), ins + eol_s + indent + '"updated": "' + want + '",', 1)
try:
json.loads(new)
except Exception as e:
print(f" !! JSON พังหลังแก้ — ข้ามไฟล์นี้ ({e})")
return have, want, False
if not dry:
p.write_bytes(new.encode("utf-8"))
return have, want, True
def main():
files = sorted(D.glob("schedules*.json"))
if not files:
print(f"ไม่พบไฟล์ใน {D}")
return 1
print(f"สแกน {len(files)} ไฟล์ · วันที่อ้างอิง = mtime ของไฟล์ (เวลาไทย UTC+7)")
print("ไฟล์ เดิม → ใหม่ สถานะ")
print("-" * 68)
n_chg = 0
for p in files:
old, new, changed = stamp_file(p)
if new is None:
print(f"{p.name:<24} (ไม่มี route_id — ข้าม)")
continue
mark = "แก้ไข" if changed else "ตรงแล้ว"
if changed:
n_chg += 1
print(f"{p.name:<24} {old or '(ไม่มี)':<12} → {new:<12} {mark}")
print("-" * 68)
if dry:
print(f"รวมจะแก้ {n_chg} ไฟล์ (dry run — ยังไม่เขียนจริง) · รันโดยไม่ใส่ --check เพื่อเขียน")
else:
print(f"เขียนแล้ว {n_chg} ไฟล์")
return 0
if __name__ == "__main__":
sys.exit(main())