"""Build the static documentation site from extracted/pages.json.
python tools/build.py
Produces
index.html cover + chapter grid
chapters/chNN.html one page per chapter (sections as anchors)
data/nav.json chapter/section tree used by search + sidebar
data/search.json full-text search index (section level)
assets/cover.jpg book cover rendered from page 1
"""
from __future__ import annotations
import html
import json
import re
import shutil
from pathlib import Path
import pymupdf as fitz
ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "extracted" / "pages.json"
PDF = Path(r"C:\Users\BANK\Downloads\Documents\Intro-Irri-Eng.pdf")
CHAPTER_DIR = ROOT / "chapters"
BOOK_TITLE = "วิศวกรรมชลประทานเบื้องต้น"
BOOK_SUBTITLE = "Introduction to Irrigation Engineering"
COURSE_CODE = "02207211"
BOOK_AUTHOR = "ภาควิชาวิศวกรรมชลประทาน มหาวิทยาลัยเกษตรศาสตร์"
BOOK_EDITION = "พิมพ์ครั้งที่ 10 · พ.ศ. 2558"
# --------------------------------------------------------------------- utils
def esc(text: str) -> str:
return html.escape(text, quote=False)
def clean(text: str) -> str:
text = (text or "").replace("\u2022", "•").replace("\n", " ")
text = re.sub(r"\s+", " ", text).strip()
# "2.7การหา…" -> "2.7 การหา…" (some chapters lost the space after the number)
text = re.sub(r"^(\d+(?:\.\d+)*)(?=[^\d\s.])", r"\1 ", text)
return text
def slug_section(index: int, title: str) -> str:
m = re.match(r"^(\d+(?:\.\d+)*)\.?\s", title)
if m:
return "s" + m.group(1).replace(".", "-")
return f"sec-{index}"
def is_noise(item) -> bool:
if item["type"] != "p":
return False
t = clean(item.get("text", ""))
if len(t) < 3:
return True
if re.fullmatch(r"[\d\s.\-–]+", t):
return True
return False
# ----------------------------------------------------------------- structure
def toc_titles(data):
"""Chapter titles as printed in the book's own table of contents."""
titles = {}
for page in data["pages"][:8]:
for it in page["items"]:
if it["type"] not in ("p", "h2", "h3", "h1"):
continue
text = clean(it.get("text", ""))
m = re.match(r"^บทที่\s*(\d+)\s*(.+)$", text)
if not m:
continue
body = m.group(2).strip()
if len(body) < 3 or re.fullmatch(r"[\d.]+", body):
continue
titles.setdefault(int(m.group(1)), body)
return titles
def load_payload():
data = json.loads(SRC.read_text(encoding="utf-8"))
chapters = []
bookmarks = [t for t in data["toc"] if t["level"] == 2 and t["page"] > 0]
bookmarks.sort(key=lambda t: t["page"])
starts = [t["page"] for t in bookmarks]
for idx, bm in enumerate(bookmarks):
start = bm["page"]
end = starts[idx + 1] if idx + 1 < len(bookmarks) else data["page_count"] + 1
pages = [p for p in data["pages"] if start <= p["page"] < end]
chapters.append(build_chapter(idx + 1, pages, start, end - 1))
printed = toc_titles(data)
for ch in chapters:
extra = printed.get(ch["number"], "")
if extra and len(extra) > len(re.sub(r"^บทที่\s*\d+\s*", "", ch["title"])):
ch["title"] = f'บทที่ {ch["number"]} {extra}'
return data, chapters
def build_chapter(number, pages, page_start, page_end):
title_parts, sections, current = [], [], None
items = [it for p in pages for it in p["items"]]
# chapter title = leading h1/p run before the first numbered section
for it in items:
if it["type"] == "h1":
title_parts.append(clean(it["text"]))
continue
if it["type"] == "p" and len(title_parts) < 3 and not sections \
and not re.match(r"^\d", clean(it.get("text", ""))):
title_parts.append(clean(it["text"]))
continue
break
rest = items[len(title_parts):]
sec_no = 0
for it in rest:
t = it["type"]
if t in ("h2", "h1"):
sec_no += 1
current = {
"id": slug_section(sec_no, clean(it["text"])),
"title": clean(it["text"]),
"page": it.get("page", page_start),
"items": [],
}
sections.append(current)
continue
if t == "h3":
if current is None:
sec_no += 1
current = {"id": f"sec-{sec_no}", "title": "บทนำ", "page": it.get("page", page_start), "items": []}
sections.append(current)
current["items"].append({"type": "h3", "text": clean(it["text"]),
"id": f'{current["id"]}-h{sum(1 for x in current["items"] if x["type"] == "h3") + 1}'})
continue
if t == "caption":
continue
if t == "figure":
if current is None:
sec_no += 1
current = {"id": f"sec-{sec_no}", "title": "ภาพประกอบ", "page": it.get("page", page_start), "items": []}
sections.append(current)
current["items"].append({
"type": "figure",
"src": "../../../" if False else it["src"],
"width": it.get("width", 800),
"height": it.get("height", 600),
"caption": clean(it.get("caption", "")),
})
continue
if is_noise(it):
continue
if current is None:
sec_no += 1
current = {"id": f"sec-{sec_no}", "title": "บทนำ", "page": it.get("page", page_start), "items": []}
sections.append(current)
current["items"].append({"type": "p", "text": clean(it["text"])})
title = " ".join(dict.fromkeys(title_parts)) or f"บทที่ {number}"
if not title.startswith("บทที่"):
title = f"บทที่ {number} {title}"
# tidy: a stray "บทที่ N" line or a figure-only prologue is not a section
cleaned = []
for sec in sections:
if re.fullmatch(r"บทที่\s*\d+", sec["title"]):
if cleaned:
cleaned[-1]["items"].extend(sec["items"])
continue
if sec["title"] == "ภาพประกอบ" and not cleaned:
sec["title"] = "บทนำ"
cleaned.append(sec)
sections = cleaned
for i, sec in enumerate(sections):
if not sec["title"]:
sec["title"] = f"หัวข้อ {i + 1}"
num = number
return {
"number": num,
"slug": f"ch{num:02d}",
"href": f"chapters/ch{num:02d}.html",
"title": title,
"page_start": page_start,
"page_end": page_end,
"sections": sections,
}
# ---------------------------------------------------------------------- html
def section_html(sec):
out = [f' {inline(it["text"])}{esc(sec["title"])}'
f'น. {sec["page"]}
']
for it in sec["items"]:
if it["type"] == "h3":
hid = it.get("id", "")
idattr = f' id="{hid}"' if hid else ""
out.append(f' {esc(it["text"])}
')
elif it["type"] == "p":
out.append(f' ')
if cap:
out.append(f'
พิมพ์อย่างน้อย 2 ตัวอักษร · ค้นทั้งเล่ม 10 บท
ตำราออนไลน์ · {COURSE_CODE}
{BOOK_SUBTITLE}
เรียบเรียงเนื้อหาครบทั้ง {len(chapters)} บท จากต้นฉบับ {BOOK_TITLE} {BOOK_EDITION} แปลงเป็นเว็บเอกสารที่ค้นหาได้ทุกย่อหน้า เลือกคัดลอกข้อความได้ และเปิดอ่านได้ทุกขนาดหน้าจอ
ครอบคลุมตั้งแต่ความหมายและขอบเขตงานวิศวกรรมชลประทาน ความสัมพันธ์ระหว่างดิน–น้ำ–พืช ความต้องการน้ำของพืช การกำหนดการให้น้ำ วิธีการให้น้ำ การส่งน้ำ การระบายน้ำ การควบคุมการส่งน้ำ ไปจนถึงพื้นฐานการออกแบบคลองส่งน้ำ
ทุกหัวข้อมีเลขหน้าอ้างอิงถึงต้นฉบับ ภาพประกอบและสมการคงรูปแบบเดิมจากหนังสือ ส่วนเนื้อความถูกแปลงเป็นข้อความจริงสำหรับการค้นหาและคัดลอก
กด Ctrl + K เพื่อค้นหาทั้งเล่ม ใช้สารบัญด้านซ้ายเพื่อข้ามบท และสารบัญด้านขวาสำหรับข้ามหัวข้อภายในบทนั้น