modify landing page

This commit is contained in:
Bkk1234 committed 2026-11-16 01:39:59 +07:00
commit dd232b1c02
2599 files changed
+226992

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""แปลง ETo รายจังหวัด (ไฟล์ export จาก Excel) → data/climate/eto_by_region.json
ต้นทาง: open data/JSON/ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาค*.json
ปลายทาง: data/climate/eto_by_region.json (คีย์เต็มคำ, หน่วยอยู่ในชื่อคีย์)
ใช้: python tools/build_eto_data.py [--check]
หมายเหตุ: ไฟล์ต้นทางเป็น list ของ object ที่คีย์เป็น field2..field13 (แถวแรกเป็นหัวตาราง)
จึงต้องแมปตำแหน่งคอลัมน์ → ชื่อเดือน ไม่ใช่เดาชื่อคีย์
"""
import json
import os
import sys
SOURCE_DIR = os.path.join("open data", "JSON")
TARGET = os.path.join("data", "climate", "eto_by_region.json")
MONTH_KEYS = [
"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december",
]
# ไฟล์ต้นทาง → (region_id, label_th) เรียงตามลำดับที่ต้องการใน JSON
REGIONS = [
("north", "ภาคเหนือ", "ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาคเหนือ.json"),
("northeast", "ภาคอีสาน", "ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาคอีสาน.json"),
("central_west", "ภาคกลางและตะวันตก",
"ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาคกลางและตะวันตก.json"),
("east", "ภาคตะวันออก", "ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาคตะวันออก.json"),
("south", "ภาคใต้", "ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาคใต้.json"),
]
def to_number(value):
"""ค่าว่าง / '-' / None → None · ตัวเลข string → float"""
if isinstance(value, (int, float)):
return float(value)
text = str(value).strip()
if text in ("", "-", "–", "n/a", "NA"):
return None
try:
return float(text)
except ValueError:
return None
def build_region(region_id, label_th, filename):
path = os.path.join(SOURCE_DIR, filename)
with open(path, encoding="utf-8") as handle:
rows = json.load(handle)
provinces = []
skipped = []
for row in rows:
values = list(row.values())
name = str(values[0]).strip()
# ข้ามแถวหัวตาราง (ชื่อคอลัมน์แรกคือ "จังหวัด")
if name == "จังหวัด" or name == "":
continue
# ต้นฉบับใช้ *** ต่อท้ายชื่อจังหวัดที่ไม่มีสถานีวัด — ตัด marker ออก
clean_name = name.replace("*", "").strip()
monthly = {}
for index, month in enumerate(MONTH_KEYS):
raw = values[index + 1] if index + 1 < len(values) else None
monthly[month] = to_number(raw)
# แถวที่ไม่มีตัวเลขเลย (ต้นฉบับใส่ ".-" หรือเว้นว่าง) ไม่ใช่ข้อมูล → ไม่เก็บ
if all(value is None for value in monthly.values()):
skipped.append(clean_name)
continue
provinces.append({
"province_name_th": clean_name,
"monthly_eto_mm_per_day": monthly,
})
return {
"region_id": region_id,
"region_name_th": label_th,
"provinces": provinces,
}, skipped
def main(argv):
check_only = "--check" in argv
built = [build_region(*item) for item in REGIONS]
document = {
"schema_version": "1.0",
"description_th": "ปริมาณการใช้น้ำของพืชอ้างอิง (ETo) รายจังหวัด วิธี Penman-Monteith หน่วย มม./วัน",
"unit": "mm_per_day",
"source_reference": "open data/JSON/ปริมาณการใช้น้ำของพืชอ้างอิงโดยวิธีของ Penman Monteith ภาค*.json",
"note_th": "ยังไม่มีรหัสจังหวัดในต้นฉบับ — เพิ่ม province_code ภายหลังได้โดยไม่กระทบคีย์อื่น",
"regions": [region for region, _ in built],
}
text = json.dumps(document, ensure_ascii=False, indent=2) + "\n"
if check_only:
try:
with open(TARGET, encoding="utf-8") as handle:
current = handle.read()
except FileNotFoundError:
print("FAIL: ยังไม่มี %s" % TARGET)
return 1
if current == text:
print("OK: %s ตรงกับต้นทาง" % TARGET)
return 0
print("FAIL: %s ไม่ตรงกับต้นทาง (รันใหม่โดยไม่ใส่ --check)" % TARGET)
return 1
os.makedirs(os.path.dirname(TARGET), exist_ok=True)
with open(TARGET, "w", encoding="utf-8", newline="\n") as handle:
handle.write(text)
total = 0
for region, skipped in built:
count = len(region["provinces"])
total += count
print("%-14s %-22s %3d จังหวัด (ตัดออก %d: ไม่มีข้อมูลในต้นฉบับ)"
% (region["region_id"], region["region_name_th"], count, len(skipped)))
if skipped:
print(" ตัดออก: %s" % ", ".join(skipped))
print("รวม %d จังหวัด → %s" % (total, TARGET))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
"""ตรวจความสอดคล้องของ SPA/PWA แบบ static (ไม่ต้องเปิดเบราว์เซอร์)
ตรวจ:
1. ลิงก์ภายใน partial ต้องเป็น "#/..." เท่านั้น (ห้าม "#section" หรือ "./x.html")
2. ทุก route ใน router.js ต้องมีไฟล์ partial อยู่จริง และไฟล์ partial ที่มีต้องถูกอ้างใน router
3. ทุกไฟล์ใน PRECACHE ของ sw.js ต้องมีอยู่จริง
4. VERSION ของ sw.js / app/version.js / app/version.json / index.html ?v= ต้องตรงกัน
5. shell (index.html) ต้องมี <link rel="manifest">, theme-color, และสคริปต์ register
6. ไม่มีอีโมจิในไฟล์ที่ผู้ใช้เห็น (partial, css, js)
ใช้: python tools/check_app.py (exit 1 ถ้าเจอปัญหา)
"""
import json
import os
import re
import sys
import urllib.parse
PROBLEMS = []
NOTES = []
EMOJI = re.compile(
"[\U0001F300-\U0001FAFF\U00002600-\U000027BF\U0001F000-\U0001F0FF\U00002190-\U000021FF\U00002B00-\U00002BFF]"
)
# สัญลักษณ์ที่ยอมให้ใช้ (ลูกศร/ขีดคั่น/เครื่องหมายคำพูด) — ไม่นับเป็นอีโมจิ
ALLOWED_SYMBOLS = set("→←↑↓↔⇒⇐✓✔✗·–—«»…‰°±×÷")
def problem(message):
PROBLEMS.append(message)
def read(path):
with open(path, encoding="utf-8") as handle:
return handle.read()
def check_partial_links():
partial_dir = "partials"
for name in sorted(os.listdir(partial_dir)):
if not name.endswith(".html"):
continue
path = os.path.join(partial_dir, name)
body = read(path)
for match in re.finditer(r'href="([^"]+)"', body):
href = match.group(1)
if href.startswith(("#/", "http://", "https://", "mailto:", "tel:")):
continue
if href.startswith("#"):
problem("%s: ลิงก์ '%s' เป็น hash ธรรมดา (จะทำให้ router เปลี่ยนหน้า) — ใช้ '#/...'" % (path, href))
continue
if href.endswith(".html"):
problem("%s: ลิงก์ '%s' จะโหลดหน้าใหม่ — ใช้ '#/...'" % (path, href))
def check_routes():
router = read("app/router.js")
routes = re.findall(r"^\s*'?([a-z-]+)'?:\s*\{\s*partial:\s*'([^']+)'", router, re.MULTILINE)
declared = set()
for _name, partial in routes:
declared.add(partial)
if not os.path.exists(partial):
problem("router.js ชี้ %s ที่ไม่มีอยู่จริง" % partial)
for name in sorted(os.listdir("partials")):
if name.endswith(".html") and "partials/" + name not in declared:
NOTES.append("partials/%s ไม่มี route (เข้าถึงไม่ได้แต่ไม่พัง)" % name)
def check_precache():
sw = read("sw.js")
block = sw.split("const PRECACHE = [")[1].split("];")[0]
urls = re.findall(r'"([^"]+)"', block)
for url in urls:
path = urllib.parse.unquote(url.replace("./", "", 1))
if not os.path.exists(path):
problem("PRECACHE ชี้ไฟล์ที่ไม่มี: %s" % url)
NOTES.append("PRECACHE: %d ไฟล์" % len(urls))
def check_versions():
sw = re.search(r'const VERSION = "([^"]+)"', read("sw.js")).group(1)
version_js = re.search(r'window\.FARM_VERSION = "([^"]+)"', read("app/version.js")).group(1)
version_json = json.loads(read("app/version.json"))["version"]
shell = set(re.findall(r"\?v=([0-9][^\"&]*)", read("index.html")))
package = json.loads(read("package.json"))["version"]
versions = {"sw.js": sw, "app/version.js": version_js, "app/version.json": version_json,
"package.json": package}
for key, value in versions.items():
if value != sw:
problem("เวอร์ชันไม่ตรง: %s = %s แต่ sw.js = %s" % (key, value, sw))
if shell != {sw}:
problem("index.html ?v= = %s แต่ sw.js = %s" % (sorted(shell), sw))
NOTES.append("version: %s" % sw)
def check_shell():
shell = read("index.html")
for needle, label in [
('rel="manifest"', "ไม่มี <link rel=manifest>"),
('name="theme-color"', "ไม่มี meta theme-color"),
('app/pwa.js', "ไม่มีสคริปต์ app/pwa.js"),
('app/router.js', "ไม่มีสคริปต์ app/router.js"),
('id="view"', "ไม่มี <main id=view>"),
]:
if needle not in shell:
problem("index.html: %s" % label)
manifest = json.loads(read("manifest.json"))
for icon in manifest["icons"]:
if not os.path.exists(icon["src"]):
problem("manifest ชี้ไอคอนที่ไม่มี: %s" % icon["src"])
NOTES.append("manifest icons: %d" % len(manifest["icons"]))
def check_emoji():
targets = ["index.html", "sw.js", "manifest.json"]
for folder in ("partials", "app", "core", "assets/css"):
for name in os.listdir(folder):
if name.endswith((".html", ".js", ".css")):
targets.append(os.path.join(folder, name))
for path in targets:
for line_number, line in enumerate(read(path).splitlines(), 1):
hit = EMOJI.search(line)
if hit and hit.group(0) not in ALLOWED_SYMBOLS:
problem("%s:%d มีอีโมจิ: %s" % (path, line_number, line.strip()[:60]))
def main():
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
for check in (check_partial_links, check_routes, check_precache, check_versions, check_shell, check_emoji):
check()
for note in NOTES:
print(" · " + note)
if PROBLEMS:
print("\nพบปัญหา %d จุด:" % len(PROBLEMS))
for item in PROBLEMS:
print(" ✗ " + item)
return 1
print("\nOK — SPA/PWA ผ่านการตรวจ static ทั้งหมด")
return 0
if __name__ == "__main__":
sys.exit(main())
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""ตรวจความสมดุลของ tag ในไฟล์ HTML (ไม่ต้องพึ่ง dependency ภายนอก)
ใช้:
python tools/check_html_balance.py index.html
คืน exit code 1 ถ้าพบ tag ค้างหรือปิดเกิน · 0 ถ้าผ่าน
"""
import sys
from html.parser import HTMLParser
VOID_ELEMENTS = {
"area", "base", "br", "col", "embed", "hr", "img",
"input", "link", "meta", "param", "source", "track", "wbr",
}
class BalanceChecker(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = []
self.errors = []
def handle_starttag(self, tag, attrs):
if tag not in VOID_ELEMENTS:
self.stack.append((tag, self.getpos()))
def handle_startendtag(self, tag, attrs):
pass # <img /> ปิดในตัว
def handle_endtag(self, tag):
if tag in VOID_ELEMENTS:
return
if not self.stack:
self.errors.append("ปิด %s เกิน (บรรทัด %d)" % (tag, self.getpos()[0]))
return
open_tag, pos = self.stack[-1]
if open_tag == tag:
self.stack.pop()
else:
self.errors.append(
"ไม่ตรงกัน: เปิด <%s> ที่บรรทัด %d แต่ปิด </%s> ที่บรรทัด %d"
% (open_tag, pos[0], tag, self.getpos()[0])
)
def main(paths):
failed = False
for path in paths:
checker = BalanceChecker()
with open(path, encoding="utf-8") as handle:
checker.feed(handle.read())
print(path)
for tag, pos in checker.stack:
failed = True
print(" ค้าง: <%s> เปิดที่บรรทัด %d ไม่ปิด" % (tag, pos[0]))
for message in checker.errors:
failed = True
print(" " + message)
if not checker.stack and not checker.errors:
print(" OK — tag สมดุล")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:] or ["index.html"]))
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""สร้างไอคอน PWA จากโลโก้เดิมในโปรเจกต์
ต้นทาง: logo/logo ใหม่/2566-09-08 11-51-40.png (1500×1500, RGBA)
ปลายทาง: assets/icons/
icon-192.png 192×192 (any)
icon-512.png 512×512 (any)
icon-maskable-512.png 512×512 (maskable — โลโก้อยู่ใน 78% กลางเฟรม)
apple-touch-icon-180.png 180×180
ใช้: python tools/make_icons.py
"""
import os
from PIL import Image
SOURCE = os.path.join("logo", "logo ใหม่", "2566-09-08 11-51-40.png")
OUT_DIR = os.path.join("assets", "icons")
BACKGROUND = (255, 255, 255, 255) # ขาวทึบ (ไอคอนโปร่งใสมักแสดงผลเพี้ยนบน launcher)
MASKABLE_SAFE_RATIO = 0.78
def flatten(source, size, ratio=1.0):
"""ย่อ/ขยายโลโก้ให้อยู่กลางเฟรมจตุรัสบนพื้นทึบ"""
canvas = Image.new("RGBA", (size, size), BACKGROUND)
inner = int(size * ratio)
logo = source.copy()
logo.thumbnail((inner, inner), Image.LANCZOS)
offset = ((size - logo.width) // 2, (size - logo.height) // 2)
canvas.paste(logo, offset, logo)
return canvas.convert("RGB")
def main():
os.makedirs(OUT_DIR, exist_ok=True)
source = Image.open(SOURCE).convert("RGBA")
targets = [
("icon-192.png", 192, 1.0),
("icon-512.png", 512, 1.0),
("icon-maskable-512.png", 512, MASKABLE_SAFE_RATIO),
("apple-touch-icon-180.png", 180, 1.0),
]
for name, size, ratio in targets:
image = flatten(source, size, ratio)
path = os.path.join(OUT_DIR, name)
image.save(path, "PNG", optimize=True)
print("%-26s %sx%s %6.1f KB" % (name, image.width, image.height,
os.path.getsize(path) / 1024))
if __name__ == "__main__":
main()