- tools/extract.py: PDF 300 หน้า -> extracted/pages.json + crop ภาพ/ตาราง/สมการ 423 รูป (ถอด PUA วรรณยุกต์ไทย, รวมสระอำ, แยกหัวข้อที่ระดับ span) - tools/build.py: generator หน้า docs แบบ static (สารบัญซ้าย/เนื้อหา/ในหน้านี้) - index.html + chapters/ch01..10.html + css/docs.css + js/docs.js (ธีม K2D, ค้นหาเต็มเล่มผ่าน data/search.json, dark mode, drawer มือถือ) - README.md: วิธี build และข้อจำกัดที่รู้อยู่
505 lines
23 KiB
Python
505 lines
23 KiB
Python
"""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'<section class="doc-section" id="{sec["id"]}">',
|
||
f' <h2><a class="anchor" href="#{sec["id"]}">{esc(sec["title"])}</a>'
|
||
f'<span class="page-ref" title="หน้าในหนังสือ">น. {sec["page"]}</span></h2>']
|
||
for it in sec["items"]:
|
||
if it["type"] == "h3":
|
||
hid = it.get("id", "")
|
||
idattr = f' id="{hid}"' if hid else ""
|
||
out.append(f' <h3{idattr}>{esc(it["text"])}</h3>')
|
||
elif it["type"] == "p":
|
||
out.append(f' <p>{inline(it["text"])}</p>')
|
||
elif it["type"] == "figure":
|
||
cap = it["caption"]
|
||
out.append(' <figure>')
|
||
out.append(f' <img src="../{it["src"]}" width="{it["width"]}" height="{it["height"]}" '
|
||
f'loading="lazy" alt="{esc(cap or "ภาพประกอบ")}">')
|
||
if cap:
|
||
out.append(f' <figcaption>{esc(cap)}</figcaption>')
|
||
out.append(' </figure>')
|
||
out.append('</section>')
|
||
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'<span class="bullet">{t}</span>'
|
||
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 = ['<nav class="side-nav" aria-label="สารบัญ">']
|
||
for ch in chapters:
|
||
open_ = " open" if current and current["number"] == ch["number"] else ""
|
||
active = " is-active" if current and current["number"] == ch["number"] else ""
|
||
label = esc(re.sub(r"^บทที่\s*\d+\s*", "", ch["title"]))
|
||
out.append(f'<details class="nav-group{active}"{open_}>')
|
||
out.append(f' <summary><span class="nav-num">บทที่ {ch["number"]}</span>'
|
||
f'<span class="nav-title">{label}</span></summary>')
|
||
out.append(' <ul>')
|
||
for sec in ch["sections"]:
|
||
sec_active = ""
|
||
out.append(f' <li><a class="nav-link{sec_active}" href="../{ch["href"]}#{sec["id"]}">'
|
||
f'{esc(sec["title"])}</a></li>')
|
||
out.append(' </ul>')
|
||
out.append('</details>')
|
||
out.append('</nav>')
|
||
return "\n".join(out)
|
||
|
||
|
||
HEAD = """<!DOCTYPE html>
|
||
<html lang="th">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>{title}</title>
|
||
<meta name="description" content="{desc}">
|
||
<meta name="theme-color" content="#1e3a8a">
|
||
<link rel="icon" href="{root}assets/favicon.svg" type="image/svg+xml">
|
||
<link rel="stylesheet" href="{root}css/docs.css">
|
||
</head>
|
||
<body data-root="{root}">
|
||
<a class="skip" href="#main">ข้ามไปที่เนื้อหา</a>
|
||
<header class="topbar">
|
||
<button class="icon-btn only-mobile" id="navToggle" aria-label="เปิดสารบัญ" aria-expanded="false">
|
||
<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M3 6h18M3 12h18M3 18h18" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>
|
||
</button>
|
||
<a class="brand" href="{root}index.html">
|
||
<svg class="brand-mark" viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
|
||
<path d="M12 2.5c3.6 4.4 6.5 8 6.5 11.2A6.5 6.5 0 0 1 5.5 13.7C5.5 10.5 8.4 6.9 12 2.5Z" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
|
||
<path d="M9 14.4c1.6-1.2 3.4-1.2 5 0" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>
|
||
</svg>
|
||
<span class="brand-text"><strong>วิศวกรรมชลประทานเบื้องต้น</strong><small>02207211</small></span>
|
||
</a>
|
||
<div class="topbar-actions">
|
||
<button class="search-btn" id="searchOpen" aria-label="ค้นหาในตำรา">
|
||
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><circle cx="11" cy="11" r="6.5" fill="none" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.5 4.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
|
||
<span>ค้นหา</span><kbd>Ctrl K</kbd>
|
||
</button>
|
||
<button class="icon-btn" id="themeToggle" aria-label="สลับโหมดสว่าง/มืด" aria-pressed="false">
|
||
<svg class="i-sun" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><circle cx="12" cy="12" r="4.2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M12 2.6v2.2M12 19.2v2.2M2.6 12h2.2M19.2 12h2.2M5.4 5.4l1.6 1.6M17 17l1.6 1.6M18.6 5.4 17 7M7 17l-1.6 1.6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
|
||
<svg class="i-moon" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M20 14.5A8.2 8.2 0 0 1 9.5 4a8.4 8.4 0 1 0 10.5 10.5Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
|
||
</button>
|
||
</div>
|
||
</header>
|
||
"""
|
||
|
||
FOOT = """
|
||
<div class="scrim" id="scrim" hidden></div>
|
||
<div class="search-modal" id="searchModal" role="dialog" aria-modal="true" aria-labelledby="searchTitle" hidden>
|
||
<div class="search-head">
|
||
<h2 id="searchTitle" class="sr">ค้นหา</h2>
|
||
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><circle cx="11" cy="11" r="6.5" fill="none" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.5 4.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
|
||
<input id="searchInput" type="search" placeholder="พิมพ์คำค้น เช่น ความชื้น, ประสิทธิภาพการชลประทาน" autocomplete="off" aria-label="คำค้น">
|
||
<button class="icon-btn" id="searchClose" aria-label="ปิด"><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button>
|
||
</div>
|
||
<div class="search-results" id="searchResults"><p class="search-hint">พิมพ์อย่างน้อย 2 ตัวอักษร · ค้นทั้งเล่ม 10 บท</p></div>
|
||
</div>
|
||
<script src="{root}js/docs.js" defer></script>
|
||
</body>
|
||
</html>
|
||
"""
|
||
|
||
|
||
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 = ['<aside class="page-toc" aria-label="ในหน้านี้"><p class="page-toc-label">ในหน้านี้</p><ul>']
|
||
for sec in ch["sections"]:
|
||
aside.append(f' <li><a href="#{sec["id"]}">{esc(sec["title"])}</a></li>')
|
||
for it in sec["items"]:
|
||
if it["type"] == "h3":
|
||
hid = it.get("id") or sec["id"]
|
||
aside.append(f' <li class="sub"><a href="#{hid}">{esc(it["text"])}</a></li>')
|
||
aside.append('</ul></aside>')
|
||
|
||
pager = ['<nav class="pager" aria-label="บทก่อนหน้า/ถัดไป">']
|
||
if prev_ch:
|
||
pager.append(f'<a class="pager-link" href="{prev_ch["slug"]}.html"><span>← บทก่อนหน้า</span>'
|
||
f'<strong>{esc(prev_ch["title"])}</strong></a>')
|
||
if next_ch:
|
||
pager.append(f'<a class="pager-link next" href="{next_ch["slug"]}.html"><span>บทถัดไป →</span>'
|
||
f'<strong>{esc(next_ch["title"])}</strong></a>')
|
||
pager.append('</nav>')
|
||
|
||
body = f"""
|
||
<div class="layout">
|
||
<div class="side" id="side">{toc_html(chapters, ch)}</div>
|
||
<main id="main" class="main">
|
||
<article class="doc">
|
||
<p class="breadcrumb"><a href="../index.html">หน้าปกตำรา</a><span>/</span>บทที่ {ch["number"]}</p>
|
||
<h1 class="doc-title">{esc(ch["title"])}</h1>
|
||
<p class="doc-meta">หน้า {ch["page_start"]}–{ch["page_end"]} ในหนังสือ · {len(ch["sections"])} หัวข้อ</p>
|
||
{chapter_body(ch)}
|
||
{''.join(pager)}
|
||
</article>
|
||
</main>
|
||
{''.join(aside)}
|
||
</div>
|
||
"""
|
||
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"""
|
||
<li class="chapter-card">
|
||
<a href="{ch["href"]}">
|
||
<span class="card-num">บทที่ {ch["number"]}</span>
|
||
<span class="card-title">{esc(card_title)}</span>
|
||
<span class="card-meta">{len(ch["sections"])} หัวข้อ · หน้า {ch["page_start"]}–{ch["page_end"]}</span>
|
||
<span class="card-cta">อ่านบทนี้
|
||
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path d="M5 12h13M13 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||
</span>
|
||
</a>
|
||
</li>""")
|
||
|
||
body = f"""
|
||
<main id="main" class="home">
|
||
<section class="hero">
|
||
<div class="hero-copy">
|
||
<p class="eyebrow">ตำราออนไลน์ · {COURSE_CODE}</p>
|
||
<h1>{BOOK_TITLE}</h1>
|
||
<p class="hero-sub">{BOOK_SUBTITLE}</p>
|
||
<p class="hero-lead">เรียบเรียงเนื้อหาครบทั้ง {len(chapters)} บท จากต้นฉบับ {BOOK_TITLE} {BOOK_EDITION}
|
||
แปลงเป็นเว็บเอกสารที่ค้นหาได้ทุกย่อหน้า เลือกคัดลอกข้อความได้ และเปิดอ่านได้ทุกขนาดหน้าจอ</p>
|
||
<div class="hero-actions">
|
||
<a class="btn primary" href="chapters/{chapters[0]["slug"]}.html">เริ่มอ่านบทที่ 1</a>
|
||
<button class="btn ghost" id="searchOpenHero">ค้นหาคำในตำรา</button>
|
||
</div>
|
||
<dl class="stats">
|
||
<div><dt>บท</dt><dd>{len(chapters)}</dd></div>
|
||
<div><dt>หัวข้อ</dt><dd>{total_sec}</dd></div>
|
||
<div><dt>ภาพและตาราง</dt><dd>{total_fig}</dd></div>
|
||
</dl>
|
||
</div>
|
||
<figure class="hero-cover">
|
||
<img src="assets/cover.jpg" width="640" height="906" alt="หน้าปกตำรา {BOOK_TITLE}" loading="eager">
|
||
<figcaption>{BOOK_AUTHOR}</figcaption>
|
||
</figure>
|
||
</section>
|
||
|
||
<section class="chapters">
|
||
<h2>สารบัญ</h2>
|
||
<ul class="chapter-grid">{''.join(cards)}
|
||
</ul>
|
||
</section>
|
||
|
||
<section class="about">
|
||
<h2>เกี่ยวกับตำราเล่มนี้</h2>
|
||
<div class="about-grid">
|
||
<div>
|
||
<h3>เนื้อหา</h3>
|
||
<p>ครอบคลุมตั้งแต่ความหมายและขอบเขตงานวิศวกรรมชลประทาน ความสัมพันธ์ระหว่างดิน–น้ำ–พืช
|
||
ความต้องการน้ำของพืช การกำหนดการให้น้ำ วิธีการให้น้ำ การส่งน้ำ การระบายน้ำ
|
||
การควบคุมการส่งน้ำ ไปจนถึงพื้นฐานการออกแบบคลองส่งน้ำ</p>
|
||
</div>
|
||
<div>
|
||
<h3>รูปแบบเอกสาร</h3>
|
||
<p>ทุกหัวข้อมีเลขหน้าอ้างอิงถึงต้นฉบับ ภาพประกอบและสมการคงรูปแบบเดิมจากหนังสือ
|
||
ส่วนเนื้อความถูกแปลงเป็นข้อความจริงสำหรับการค้นหาและคัดลอก</p>
|
||
</div>
|
||
<div>
|
||
<h3>การใช้งาน</h3>
|
||
<p>กด <kbd>Ctrl</kbd> + <kbd>K</kbd> เพื่อค้นหาทั้งเล่ม ใช้สารบัญด้านซ้ายเพื่อข้ามบท
|
||
และสารบัญด้านขวาสำหรับข้ามหัวข้อภายในบทนั้น</p>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<footer class="home-foot">
|
||
<p>{BOOK_AUTHOR} · {BOOK_EDITION}</p>
|
||
<p>เอกสารอิเล็กทรอนิกส์เพื่อการเรียนการสอน · แปลงจากต้นฉบับ PDF</p>
|
||
</footer>
|
||
</main>
|
||
"""
|
||
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 = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">'
|
||
'<rect width="24" height="24" rx="6" fill="#1e3a8a"/>'
|
||
'<path d="M12 4.5c3 3.7 5.4 6.7 5.4 9.3a5.4 5.4 0 0 1-10.8 0c0-2.6 2.4-5.6 5.4-9.3Z" '
|
||
'fill="none" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></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()
|