"""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'
', f'

{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'

{inline(it["text"])}

') elif it["type"] == "figure": cap = it["caption"] out.append('
') out.append(f' {esc(cap or ') if cap: out.append(f'
{esc(cap)}
') out.append('
') out.append('
') return "\n".join(out) def inline(text: str) -> str: """Escape, then turn bullet runs into list markup.""" t = esc(text) if t.startswith("• ") or t.startswith("- "): return f'{t}' return t def chapter_body(ch): parts = [] for sec in ch["sections"]: parts.append(section_html(sec)) return "\n".join(parts) def toc_html(chapters, current=None): out = ['') return "\n".join(out) HEAD = """ {title}
วิศวกรรมชลประทานเบื้องต้น02207211
""" FOOT = """ """ def page_shell(title, desc, root, body, aside=""): return HEAD.format(title=esc(title), desc=esc(desc), root=root) + body + aside + FOOT.format(root=root) def build_chapter_page(ch, chapters, prev_ch, next_ch): aside = ['') pager = ['') body = f"""
{toc_html(chapters, ch)}

{esc(ch["title"])}

หน้า {ch["page_start"]}–{ch["page_end"]} ในหนังสือ · {len(ch["sections"])} หัวข้อ

{chapter_body(ch)} {''.join(pager)}
{''.join(aside)}
""" title = f'{ch["title"]} · {BOOK_TITLE}' return page_shell(title, ch["title"], "../", body) def build_index(chapters): total_sec = sum(len(c["sections"]) for c in chapters) total_fig = sum(1 for c in chapters for s in c["sections"] for i in s["items"] if i["type"] == "figure") cards = [] for ch in chapters: card_title = re.sub(r"^บทที่\s*\d+\s*", "", ch["title"]) cards.append(f"""
  • บทที่ {ch["number"]} {esc(card_title)} {len(ch["sections"])} หัวข้อ · หน้า {ch["page_start"]}–{ch["page_end"]} อ่านบทนี้
  • """) body = f"""

    ตำราออนไลน์ · {COURSE_CODE}

    {BOOK_TITLE}

    {BOOK_SUBTITLE}

    เรียบเรียงเนื้อหาครบทั้ง {len(chapters)} บท จากต้นฉบับ {BOOK_TITLE} {BOOK_EDITION} แปลงเป็นเว็บเอกสารที่ค้นหาได้ทุกย่อหน้า เลือกคัดลอกข้อความได้ และเปิดอ่านได้ทุกขนาดหน้าจอ

    เริ่มอ่านบทที่ 1
    บท
    {len(chapters)}
    หัวข้อ
    {total_sec}
    ภาพและตาราง
    {total_fig}
    หน้าปกตำรา {BOOK_TITLE}
    {BOOK_AUTHOR}

    สารบัญ

    เกี่ยวกับตำราเล่มนี้

    เนื้อหา

    ครอบคลุมตั้งแต่ความหมายและขอบเขตงานวิศวกรรมชลประทาน ความสัมพันธ์ระหว่างดิน–น้ำ–พืช ความต้องการน้ำของพืช การกำหนดการให้น้ำ วิธีการให้น้ำ การส่งน้ำ การระบายน้ำ การควบคุมการส่งน้ำ ไปจนถึงพื้นฐานการออกแบบคลองส่งน้ำ

    รูปแบบเอกสาร

    ทุกหัวข้อมีเลขหน้าอ้างอิงถึงต้นฉบับ ภาพประกอบและสมการคงรูปแบบเดิมจากหนังสือ ส่วนเนื้อความถูกแปลงเป็นข้อความจริงสำหรับการค้นหาและคัดลอก

    การใช้งาน

    กด Ctrl + K เพื่อค้นหาทั้งเล่ม ใช้สารบัญด้านซ้ายเพื่อข้ามบท และสารบัญด้านขวาสำหรับข้ามหัวข้อภายในบทนั้น

    """ return page_shell(f"{BOOK_TITLE} · {BOOK_SUBTITLE}", "ตำราออนไลน์ วิศวกรรมชลประทานเบื้องต้น 10 บท", "", body) # --------------------------------------------------------------------- assets def write_search(chapters, data_size): entries = [] for ch in chapters: for sec in ch["sections"]: for it in sec["items"]: if it["type"] != "p": continue entries.append({ "u": f'{ch["href"]}#{sec["id"]}', "c": f'บทที่ {ch["number"]}', "s": sec["title"], "p": sec["page"], "x": it["text"][:260], }) out = ROOT / "data" / "search.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(entries, ensure_ascii=False), encoding="utf-8") return len(entries) def write_nav(chapters): tree = [{"n": c["number"], "t": c["title"], "u": c["href"], "s": [{"t": s["title"], "u": f'{c["href"]}#{s["id"]}'} for s in c["sections"]]} for c in chapters] out = ROOT / "data" / "nav.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(tree, ensure_ascii=False, indent=1), encoding="utf-8") def write_cover(): if not PDF.exists(): return doc = fitz.open(PDF) page = doc[0] rect = page.rect zoom = 640 / rect.width pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom)) path = ROOT / "assets" / "cover.jpg" path.parent.mkdir(parents=True, exist_ok=True) pix.save(str(path), jpg_quality=88) def write_favicon(): svg = ('' '' '') (ROOT / "assets").mkdir(parents=True, exist_ok=True) (ROOT / "assets" / "favicon.svg").write_text(svg, encoding="utf-8") def main(): data, chapters = load_payload() CHAPTER_DIR.mkdir(exist_ok=True) for i, ch in enumerate(chapters): prev_ch = chapters[i - 1] if i > 0 else None next_ch = chapters[i + 1] if i + 1 < len(chapters) else None html_text = build_chapter_page(ch, chapters, prev_ch, next_ch) (CHAPTER_DIR / f'{ch["slug"]}.html').write_text(html_text, encoding="utf-8") (ROOT / "index.html").write_text(build_index(chapters), encoding="utf-8") write_nav(chapters) n = write_search(chapters, data["page_count"]) write_cover() write_favicon() total_p = sum(1 for c in chapters for s in c["sections"] for i in s["items"] if i["type"] == "p") total_f = sum(1 for c in chapters for s in c["sections"] for i in s["items"] if i["type"] == "figure") print(f"chapters={len(chapters)} sections={sum(len(c['sections']) for c in chapters)} " f"paragraphs={total_p} figures={total_f} search_entries={n}") if __name__ == "__main__": main()