intro-irre: แปลงตำราวิศวกรรมชลประทานเบื้องต้นเป็นเว็บเอกสาร 10 บท

- 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 และข้อจำกัดที่รู้อยู่
This commit is contained in:
Bkk1234 committed 2026-11-19 01:34:49 +07:00
1 parent 22c28f0708
commit 4f74a509d5
454 files changed
+21280

No files matched your search

+504
View File
@@ -0,0 +1,504 @@
"""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()
+439
View File
@@ -0,0 +1,439 @@
"""Extract structured content from the source PDF of "วิศวกรรมชลประทานเบื้องต้น".
The book is typeset with legacy Thai fonts (AngsanaNew / EucrosiaUPC). Two of
its chapters reflow text so that a heading shares its line with the prose that
follows it, so headings are cut on *span* boundaries (bold run at line start),
not on lines.
Equations, rules-drawn tables and pictures cannot be linearised faithfully, so
each of those graphic bands is rendered as a JPEG crop and put back into the
reading order where it belongs.
Outputs
extracted/pages.json one record per page, items in reading order
assets/figures/*.jpg cropped figures / tables / equations
Usage
python tools/extract.py [--pdf PATH]
"""
from __future__ import annotations
import argparse
import json
import re
import statistics
import unicodedata
from pathlib import Path
import pymupdf as fitz
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_PDF = Path(r"C:\Users\BANK\Downloads\Documents\Intro-Irri-Eng.pdf")
FIG_DIR = ROOT / "assets" / "figures"
TOP_MARGIN = 62.0 # above this line = running header
BOTTOM_MARGIN = 808.0 # below this line = footer
CONTENT_X0, CONTENT_X1 = 72.0, 526.0
CONTENT_W = CONTENT_X1 - CONTENT_X0
MATH_CHARS = set("=×÷∴π√∑∫≥≤±²³·∝≠≈γλΔ∂")
HEADING_RE = re.compile(r"^(บทที่\s*\d+|\d+(?:\.\d+)*\.?)\s*\S")
CHAPTER_RE = re.compile(r"^บทที่\s*\d+")
CAPTION_RE = re.compile(r"^(รูปที่|ตารางที่|ภาพที่)\s*\d")
THAI_RE = re.compile(r"[\u0e00-\u0e7f]")
THAI_RUN = re.compile(r"[\u0e00-\u0e7f]{20,}")
PUA_MAP = {
"\uf70a": "\u0e48", # ่
"\uf70b": "\u0e49", # ้
"\uf706": "\u0e49", # ้ (bold subset of the same face)
"\uf714": "\u0e49", # ้
"\uf715": "\u0e53", # ๊
"\uf708": "\u0e4b", # ๋
"\uf712": "\u0e47", # ็
"\uf70e": "\u0e4c", # ์
"\uf701": "\u0e34", # ิ
"\uf702": "\u0e35", # ี
"\uf710": "\u0e31", # ั
"\uf0a7": "\u2022", # bullet
}
def norm(text: str) -> str:
"""Repair legacy-Thai artefacts (subset fonts use PUA code points)."""
text = unicodedata.normalize("NFC", text)
for src, dst in PUA_MAP.items():
text = text.replace(src, dst)
text = text.replace("\u0e4d\u0e32", "\u0e33").replace("\u200b", "")
text = re.sub(r"[ \t\u00a0]+", " ", text)
return text.strip()
# ------------------------------------------------------------------ primitives
def read_lines(page):
"""Text lines of the content area, tagged with their source block."""
lines = []
for bno, block in enumerate(page.get_text("dict")["blocks"]):
if block["type"] != 0:
continue
bb = block["bbox"]
if bb[3] < TOP_MARGIN or bb[1] > BOTTOM_MARGIN:
continue
for line in block["lines"]:
spans = []
for s in line["spans"]:
if not s["text"]:
continue
spans.append({
"text": s["text"],
"size": round(s["size"], 1),
"bold": bool(s["flags"] & 16) or "bold" in s["font"].lower(),
})
if not "".join(s["text"] for s in spans).strip():
continue
sizes = [s["size"] for s in spans]
lines.append({
"block": bno,
"spans": spans,
"text": norm("".join(s["text"] for s in spans)),
"size": max(sizes),
"min_size": min(sizes),
"bold": any(s["bold"] for s in spans),
"x0": round(line["bbox"][0], 1),
"y0": round(line["bbox"][1], 1),
"x1": round(line["bbox"][2], 1),
"y1": round(line["bbox"][3], 1),
})
lines.sort(key=lambda l: (round(l["y0"] / 4), l["x0"]))
return merge_fragments(lines)
def merge_fragments(lines):
"""LaTeX breaks a line around wide spaces — glue the pieces back."""
merged, cur = [], None
for l in lines:
if cur and cur["block"] == l["block"] and abs(l["y0"] - cur["y0"]) < 3 and l["x0"] - cur["x1"] < 40:
gap = " " if (cur["spans"][-1]["text"].endswith(" ") or l["spans"][0]["text"].startswith(" ")) else ""
joined = cur["text"] + gap + l["text"]
cur["spans"] = cur["spans"] + l["spans"]
cur["text"] = norm(joined)
cur["x1"] = max(cur["x1"], l["x1"])
cur["y1"] = max(cur["y1"], l["y1"])
cur["min_size"] = min(cur["min_size"], l["min_size"])
cur["bold"] = cur["bold"] or l["bold"]
else:
if cur:
merged.append(cur)
cur = dict(l)
if cur:
merged.append(cur)
return merged
def body_size(lines):
"""The text size that carries most of the characters on the page."""
counter = {}
for l in lines:
key = round(l["size"], 1)
counter[key] = counter.get(key, 0) + len(l["text"])
return max(counter.items(), key=lambda kv: kv[1])[0] if counter else 16.0
def split_bold_head(line):
"""Return (head_text, rest_text) where head is the leading bold run."""
head, i = [], 0
spans = line["spans"]
while i < len(spans) and (spans[i]["bold"] or not spans[i]["text"].strip()):
head.append(spans[i])
i += 1
if i == 0:
return "", line["text"]
head_text = norm("".join(s["text"] for s in head))
rest_text = norm("".join(s["text"] for s in spans[i:]))
return head_text, rest_text
def heading_of(line, body):
"""(level, heading_text, rest_text) when the line opens with a heading."""
head, rest = split_bold_head(line)
if not head:
# unfussy chapters: the heading is not bold, it is a short numbered line
m = HEADING_RE.match(line["text"])
if m:
num = m.group(1).rstrip(".")
parts = num.split(".")
if ("." in num and len(parts) >= 2
and parts[0].isdigit() and 1 <= int(parts[0]) <= 15
and parts[1].isdigit() and int(parts[1]) >= 1
and len(line["text"]) <= 45 and line["text"].count(" ") <= 3
and line["size"] >= body * 0.98):
rest_text = line["text"][m.end(1):].strip()
if len(rest_text) >= 12 and THAI_RE.search(rest_text):
return (3 if num.count(".") >= 2 else 2), line["text"], ""
return None
if len(head) > 140:
return None
if CAPTION_RE.match(head) or "=" in head:
return None
full_bold = not rest
if CHAPTER_RE.match(head) and (line["size"] >= body * 1.2 or full_bold):
return 1, head, rest
m = HEADING_RE.match(head)
if not m:
return None
num = m.group(1).rstrip(".")
if "." not in num:
return None
if not (full_bold or line["size"] >= body * 1.02):
return None
level = 3 if num.count(".") >= 2 else 2
return level, head, rest
# ------------------------------------------------------------------- graphics
def graphic_rects(page):
rects = []
for block in page.get_text("dict")["blocks"]:
if block["type"] != 1:
continue
r = fitz.Rect(block["bbox"])
if r.y1 >= TOP_MARGIN and r.y0 <= BOTTOM_MARGIN and r.width > 6 and r.height > 6:
rects.append(r)
for dr in page.get_drawings():
r = fitz.Rect(dr["rect"])
if r.y1 < TOP_MARGIN or r.y0 > BOTTOM_MARGIN:
continue
if r.width < 6 and r.height < 6:
continue
rects.append(r)
return rects
def merge_rects(rects, vgap=20.0, hgap=40.0):
items = [{"rect": fitz.Rect(r)} for r in rects]
changed = True
while changed:
changed = False
out = []
while items:
cur = items.pop(0)
again = True
while again:
again = False
for i, other in enumerate(items):
a, b = cur["rect"], other["rect"]
vy = not (b.y0 > a.y1 + vgap or b.y1 < a.y0 - vgap)
vx = not (b.x0 > a.x1 + hgap or b.x1 < a.x0 - hgap)
if vy and vx:
cur["rect"] = a | b
items.pop(i)
again = changed = True
break
out.append(cur)
items = out
return [it["rect"] for it in items]
def formula_block_rects(page):
"""Display equations: their own block, maths glyphs, no running prose."""
out = []
for block in page.get_text("dict")["blocks"]:
if block["type"] != 0:
continue
bb = block["bbox"]
if bb[3] < TOP_MARGIN or bb[1] > BOTTOM_MARGIN:
continue
text = norm("".join(s["text"] for l in block["lines"] for s in l["spans"]))
if not text:
continue
text_len = len(text)
size = min((s["size"] for l in block["lines"] for s in l["spans"]), default=16)
maths = sum(1 for ch in text if ch in MATH_CHARS)
prose = len(THAI_RUN.findall(text)) >= 1 or text_len > 170
if prose:
continue
if maths >= 1 or size < 13.0 or (bb[3] - bb[1] < 40 and text_len < 45):
out.append(fitz.Rect(bb))
return out
def absorb_into_bands(bands, lines, used, body):
"""Pull narrow text lines (table cells, equation operands, sub-labels) into bands."""
for band in bands:
grown = fitz.Rect(band.x0 - 10, band.y0 - 14, band.x1 + 10, band.y1 + 12)
for i, l in enumerate(lines):
if i in used:
continue
if (l["x1"] - l["x0"]) > CONTENT_W * 0.86:
continue # full justified prose line
if CAPTION_RE.match(l["text"]) or heading_of(l, body):
continue
cx, cy = (l["x0"] + l["x1"]) / 2, (l["y0"] + l["y1"]) / 2
if grown.contains(fitz.Point(cx, cy)):
used.add(i)
band |= fitz.Rect(l["x0"], l["y0"], l["x1"], l["y1"])
def render_band(page, rect, path):
zoom = min(2.4, max(1.6, 1100.0 / max(rect.width, 1)))
pix = page.get_pixmap(clip=fitz.Rect(rect), matrix=fitz.Matrix(zoom, zoom))
pix.save(str(path), jpg_quality=90)
return pix.width, pix.height
# --------------------------------------------------------------------- per page
def extract_page(page, pno):
lines = read_lines(page)
body = body_size(lines)
used = set()
rects = graphic_rects(page) + formula_block_rects(page)
bands = merge_rects(rects)
bands = [b for b in bands if b.height >= 10 and b.width >= 24]
absorb_into_bands(bands, lines, used, body)
margin = statistics.mode([round(l["x0"]) for l in lines]) if lines else CONTENT_X0
wide = [l["x1"] for l in lines if (l["x1"] - l["x0"]) > CONTENT_W * 0.5]
right = statistics.mode([round(v) for v in wide]) if wide else CONTENT_X1
items, para, para_y = [], [], []
para_block = [None]
prev_y1 = [0.0]
def flush():
if not para:
return
text = join_lines(para)
if text:
items.append({"type": "p", "text": text, "y": para_y[0]})
para.clear()
para_y.clear()
para_block[0] = None
for i, l in enumerate(lines):
if i in used:
continue
head = heading_of(l, body)
if head:
level, head_text, rest = head
flush()
items.append({"type": f"h{level}", "text": head_text, "y": l["y0"], "yb": l["y1"]})
if rest:
para.append(rest)
para_y.append(l["y0"])
para_block[0] = l["block"]
prev_y1[0] = l["y1"]
continue
if CAPTION_RE.match(l["text"]):
flush()
items.append({"type": "caption", "text": l["text"], "y": l["y0"], "yb": l["y1"]})
continue
if para and para_block[0] != l["block"]:
flush()
if para and (l["y0"] - prev_y1[0] > 9 or l["x0"] > margin + 12):
flush()
if para and re.match(r"^[•\-–]\s", l["text"]):
flush() # list item starts its own block
para.append(l["text"])
para_y.append(l["y0"])
para_block[0] = l["block"]
prev_y1[0] = l["y1"]
flush()
for b in bands:
items.append({"type": "figure", "rect": b, "y": b.y0})
items.sort(key=lambda it: (it["y"], 0 if it["type"] == "figure" else 1))
return finish_items(page, pno, items)
def finish_items(page, pno, items):
# merge a caption into the figure it describes
out = []
i = 0
while i < len(items):
it = items[i]
if it["type"] == "caption":
prev_fig = out[-1] if out and out[-1]["type"] == "figure" else None
next_fig = items[i + 1] if i + 1 < len(items) and items[i + 1]["type"] == "figure" else None
if prev_fig and it["y"] - prev_fig["rect"].y1 < 70:
prev_fig.setdefault("caption", it["text"])
i += 1
continue
if next_fig and next_fig["rect"].y0 - it["y"] < 70:
next_fig.setdefault("caption", it["text"])
i += 1
continue
out.append(it)
i += 1
final, fig_no = [], 0
for it in out:
if it["type"] == "figure":
fig_no += 1
name = f"p{pno + 1:03d}-{fig_no}.jpg"
w, h = render_band(page, it["rect"], FIG_DIR / name)
final.append({
"type": "figure",
"src": f"assets/figures/{name}",
"width": w,
"height": h,
"caption": it.get("caption", ""),
"page": pno + 1,
})
continue
if it["type"] == "h1" and final and final[-1]["type"] == "h1":
final[-1]["text"] = f'{final[-1]["text"]} {it["text"]}'.strip()
continue
final.append({"type": it["type"], "text": it.get("text", ""), "page": pno + 1})
return final
def join_lines(parts):
buf = ""
for t in parts:
t = t.strip()
if not t:
continue
if not buf:
buf = t
elif re.search(r"[A-Za-z0-9)\]]$", buf) and re.match(r"^[A-Za-z0-9(]", t):
buf = f"{buf} {t}"
else:
buf += t
return re.sub(r"\s+", " ", buf).strip()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--pdf", default=str(DEFAULT_PDF))
args = ap.parse_args()
if FIG_DIR.exists():
for f in FIG_DIR.glob("*"):
f.unlink()
FIG_DIR.mkdir(parents=True, exist_ok=True)
doc = fitz.open(args.pdf)
pages = []
for pno in range(doc.page_count):
pages.append({"page": pno + 1, "items": extract_page(doc[pno], pno)})
if (pno + 1) % 50 == 0:
print(f" … {pno + 1}/{doc.page_count}")
toc = [{"level": lvl, "title": norm(t), "page": pg} for lvl, t, pg in doc.get_toc()]
payload = {"source": Path(args.pdf).name, "page_count": doc.page_count, "toc": toc, "pages": pages}
out = ROOT / "extracted" / "pages.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
kinds = {}
for p in pages:
for it in p["items"]:
kinds[it["type"]] = kinds.get(it["type"], 0) + 1
print(f"pages={doc.page_count} items={kinds} -> {out}")
if __name__ == "__main__":
main()