Files
2026-11-16 01:39:59 +07:00

134 lines
6.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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:]))