feat(skills): add lawnb-pdf-download skill for saving LAWnB 주석서 pages as PDF
Scripts to probe a book's TOC, print each page-level item to PDF via the print popup, verify, merge per 대항목 and clean up temp files. Invoked only by /lawnb-pdf-download (disable-model-invocation). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
// List every book entry button on the LAWnB 주석서 main page with its sid.
|
||||
// The sid prefix (before "_") identifies the book; the suffix is a TOC node id.
|
||||
// Run (sandbox disabled): ego-browser nodejs < find_books.js
|
||||
const task = await taskSpace("lawnb find books " + Date.now());
|
||||
const page = task.page("p1");
|
||||
await page.goto("https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentMain/Jusuk", { timeout: 30000 });
|
||||
await page.waitForTimeout(3000);
|
||||
const rows = await page.evaluate(() => [...document.querySelectorAll('[onclick]')]
|
||||
.filter(e => /showOriginalView/.test(e.getAttribute('onclick')))
|
||||
.map((e, i) => i + ': ' + e.textContent.trim().replace(/\s+/g, ' ') + ' | ' + (e.getAttribute('onclick').match(/sid=([^']+)/) || [])[1]));
|
||||
console.log(rows.join('\n'));
|
||||
await task.finish({ keep: [] });
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Merge the individual PDFs of each group into one file, then (optionally) delete the temp files.
|
||||
|
||||
Usage: python3 -I merge_pdfs.py <config.json> (run with the sandbox disabled when dest is outside the working dir)
|
||||
|
||||
config.json = {
|
||||
"tmpDir": "/abs/tmp/dir", # where print_items.js wrote s{key}_{NN}_{label}.pdf
|
||||
"destDir": "/abs/destination/folder", # must already exist
|
||||
"prefix": "주석상법_제2편_", # final name = prefix + name + ".pdf"
|
||||
"groups": [["6", "제6장_중개업"], ["7", "제7장_위탁매매업"]], # [key, name] in the order wanted
|
||||
"deleteTmp": true # delete the temp PDFs after every group merged cleanly
|
||||
}
|
||||
A group with one file is copied. Page sums are compared with the merged file.
|
||||
Nothing is deleted unless every group merged with matching page counts and
|
||||
the number of merged inputs equals the number of files in tmpDir.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
cfg = json.load(open(sys.argv[1], encoding="utf-8"))
|
||||
T, D = cfg["tmpDir"], cfg["destDir"]
|
||||
|
||||
|
||||
def pages(p):
|
||||
out = subprocess.run(["pdfinfo", p], capture_output=True, text=True).stdout
|
||||
return int(re.search(r"Pages:\s+(\d+)", out).group(1))
|
||||
|
||||
|
||||
all_files = [f for f in os.listdir(T) if f.endswith(".pdf")]
|
||||
used, ok = 0, True
|
||||
for key, name in cfg["groups"]:
|
||||
pat = re.compile(r"s%s_(\d{2,})_" % re.escape(key))
|
||||
fs = sorted((f for f in all_files if pat.match(f)), key=lambda f: int(pat.match(f).group(1)))
|
||||
nums = [int(pat.match(f).group(1)) for f in fs]
|
||||
if nums != list(range(1, len(nums) + 1)):
|
||||
print("GAP in numbering for", key, nums[:10]); ok = False; continue
|
||||
paths = [os.path.join(T, f) for f in fs]
|
||||
out = os.path.join(D, cfg["prefix"] + name + ".pdf")
|
||||
if len(paths) == 1:
|
||||
shutil.copyfile(paths[0], out)
|
||||
else:
|
||||
subprocess.run(["pdfunite"] + paths + [out], check=True)
|
||||
s, m = sum(pages(p) for p in paths), pages(out)
|
||||
used += len(paths)
|
||||
flag = "OK" if s == m else "MISMATCH(inputs %d)" % s
|
||||
ok &= (s == m)
|
||||
print(f"{name} | {len(paths)}건 | {m}쪽 {flag}")
|
||||
|
||||
if cfg.get("deleteTmp") and ok and used == len(all_files):
|
||||
for f in all_files:
|
||||
os.remove(os.path.join(T, f))
|
||||
os.rmdir(T)
|
||||
print("temp deleted:", len(all_files), "files")
|
||||
else:
|
||||
print("temp NOT deleted (used %d of %d files, ok=%s)" % (used, len(all_files), ok))
|
||||
@@ -0,0 +1,100 @@
|
||||
// Print LAWnB 주석서 TOC pages to PDF, one file per page-level item.
|
||||
// Render with render.py, then run (sandbox must be disabled):
|
||||
// ego-browser nodejs < rendered.js
|
||||
//
|
||||
// CFG = {
|
||||
// task: "unique task space name",
|
||||
// bookUrl: "https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentView?sid=<BOOK>_<anyNodeId>",
|
||||
// rootRegex: "^제2장 계약", // TOC node whose DIRECT children are the 대항목
|
||||
// groups: [ {key: "2", match: "^제2절"}, {key: "t", match: "^\\[총설\\]$"} ],
|
||||
// tmpDir: "/abs/path/ending/with/slash/", // scratch dir for individual PDFs
|
||||
// waitMs: 4500 // optional; wait after selecting a page
|
||||
// }
|
||||
// Each group = every page-level anchor (href id with exactly two parts) found
|
||||
// anywhere under the matching child <li>, in TOC order. Files are written as
|
||||
// s{key}_{NN}_{label}.pdf (NN = 01.. in TOC order; label = 총설 | 제N조 | 부칙 | [제목] | X)
|
||||
// Files that already exist are skipped, so a crashed or timed-out run can be
|
||||
// started again unchanged.
|
||||
const CFG = __CFG__;
|
||||
const task = await taskSpace(CFG.task);
|
||||
const page = task.page("p1");
|
||||
const fs = await import("node:fs/promises");
|
||||
await fs.mkdir(CFG.tmpDir, { recursive: true });
|
||||
const WAIT = CFG.waitMs || 4500;
|
||||
await page.goto(CFG.bookUrl, { timeout: 30000 });
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
const groups = await page.evaluate((cfg) => {
|
||||
const ownText = (li) => { const a = li.querySelector(':scope > a'); return a ? a.innerText.trim() : [...li.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join(''); };
|
||||
const root = [...document.querySelectorAll('li')].find(li => new RegExp(cfg.rootRegex).test(ownText(li)));
|
||||
if (!root) return { __error: 'root not found: ' + cfg.rootRegex };
|
||||
const ol = root.querySelector(':scope > ol, :scope > ul');
|
||||
const out = {};
|
||||
for (const li of ol.children) {
|
||||
const t = ownText(li);
|
||||
for (const g of cfg.groups) {
|
||||
if (out[g.key] || !new RegExp(g.match).test(t)) continue;
|
||||
out[g.key] = [...li.querySelectorAll('a')]
|
||||
.filter(x => /showTargetContent\('[^'|]+\|\d+\|R1'\)/.test(x.getAttribute('href') || ''))
|
||||
.map(x => ({ t: x.innerText.trim(), h: x.getAttribute('href') }));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}, CFG);
|
||||
if (groups.__error) throw new Error(groups.__error);
|
||||
|
||||
const label = (t) => {
|
||||
if (t === '[총설]') return '총설';
|
||||
const m = t.match(/^제\d+조(?:의\d+)?/);
|
||||
if (m) return m[0];
|
||||
if (/^부칙/.test(t)) return '부칙';
|
||||
const g = t.match(/^\[([^\]:]+)/);
|
||||
return g ? g[1].replace(/\s+/g, '') : 'X';
|
||||
};
|
||||
const norm = (s) => s.replace(/\s+/g, '').replace(/[\[\]]/g, '');
|
||||
let lastTxt = "";
|
||||
|
||||
async function printOne(h, title, outPath) {
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
if (attempt > 1) { await page.goto(CFG.bookUrl, { timeout: 30000 }); await page.waitForTimeout(3000); }
|
||||
await page.evaluate((h) => { doc.showTargetContent(h.match(/showTargetContent\('([^']+)'\)/)[1]); }, h);
|
||||
await page.waitForTimeout(WAIT + attempt * 1000); // too short a wait prints the previous page
|
||||
await page.click("#pring_set", { label: "인쇄 버튼 클릭" });
|
||||
await page.waitForTimeout(1500);
|
||||
const btn = await page.evaluate(() => [...document.querySelectorAll('button')]
|
||||
.filter(e => /^인쇄$/.test(e.innerText.trim()) && e.offsetParent)
|
||||
.map(e => { const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }));
|
||||
const popupP = page.waitForEvent("popup", { timeout: 15000 + attempt * 5000 });
|
||||
await page.mouse.click(btn[0].x, btn[0].y, { label: "레이어 인쇄 버튼" });
|
||||
const p2 = await popupP; // ContentPrintView popup
|
||||
await page.waitForTimeout(2500);
|
||||
const txt = await p2.evaluate(() => document.body.innerText);
|
||||
const titleOk = title === '[총설]' ? txt.includes('[총설]') : norm(txt).includes(norm(title).slice(0, 10));
|
||||
const ok = titleOk && txt !== lastTxt; // identical text = stale previous page
|
||||
if (!ok && attempt < 3) { console.log(" mismatch/stale, retry", title); await p2.close(); continue; }
|
||||
const r = await p2.cdp("Page.printToPDF", { printBackground: true, preferCSSPageSize: true });
|
||||
await fs.writeFile(outPath, Buffer.from(r.data, "base64"));
|
||||
lastTxt = txt;
|
||||
console.log(ok ? "saved" : "SAVED-UNVERIFIED", outPath.split('/').pop(), "|", title, "|", (await fs.stat(outPath)).size);
|
||||
await p2.close();
|
||||
return true;
|
||||
} catch (e) { console.log(" retry", title, attempt, String(e).slice(0, 80)); }
|
||||
}
|
||||
console.log("FAIL", title);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const g of CFG.groups) {
|
||||
const items = groups[g.key];
|
||||
if (!items) { console.log("NO MATCH for group", g.key, g.match); continue; }
|
||||
console.log("GROUP", g.key, items.length);
|
||||
let n = 0;
|
||||
for (const it of items) {
|
||||
n++;
|
||||
const pth = CFG.tmpDir + "s" + g.key + "_" + String(n).padStart(2, '0') + "_" + label(it.t) + ".pdf";
|
||||
try { await fs.stat(pth); continue; } catch (e) { /* not there yet */ }
|
||||
await printOne(it.h, it.t, pth);
|
||||
}
|
||||
}
|
||||
console.log(await task.finish({ keep: [] }));
|
||||
@@ -0,0 +1,31 @@
|
||||
// Dump the TOC subtree under one node of a LAWnB 주석서 book.
|
||||
// Render with render.py (CFG = {bookUrl, rootRegex}) and run:
|
||||
// ego-browser nodejs < rendered.js (sandbox must be disabled)
|
||||
//
|
||||
// Output: one line per TOC node. "pages" = number of page-level anchors
|
||||
// (href id has exactly two parts) under that child. Roman-numeral sub-headings
|
||||
// (three-part ids) are NOT pages; they are sections of the page above them.
|
||||
const CFG = __CFG__;
|
||||
const task = await taskSpace("lawnb probe " + Date.now());
|
||||
const page = task.page("p1");
|
||||
await page.goto(CFG.bookUrl, { timeout: 30000 });
|
||||
await page.waitForTimeout(3500);
|
||||
const lines = await page.evaluate((cfg) => {
|
||||
const ownText = (li) => { const a = li.querySelector(':scope > a'); return a ? a.innerText.trim() : [...li.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join(''); };
|
||||
const root = [...document.querySelectorAll('li')].find(li => new RegExp(cfg.rootRegex).test(ownText(li)));
|
||||
if (!root) return ['ROOT NOT FOUND for ' + cfg.rootRegex];
|
||||
const isPage = (x) => /showTargetContent\('[^'|]+\|\d+\|R1'\)/.test(x.getAttribute('href') || '');
|
||||
const out = [];
|
||||
const walk = (li, d, maxDepth) => {
|
||||
const a = li.querySelector(':scope > a');
|
||||
const t = ownText(li);
|
||||
const pages = [...li.querySelectorAll('a')].filter(isPage).length;
|
||||
out.push(' '.repeat(d) + (t || '(no text)') + (a ? '' : ' [group: no link]') + ' pages=' + pages);
|
||||
const ol = li.querySelector(':scope > ol, :scope > ul');
|
||||
if (ol && d < maxDepth) [...ol.children].forEach(c => walk(c, d + 1, maxDepth));
|
||||
};
|
||||
walk(root, 0, cfg.depth || 1);
|
||||
return out;
|
||||
}, CFG);
|
||||
console.log(lines.join('\n'));
|
||||
await task.finish({ keep: [] });
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject a JSON config into a script template and write the result.
|
||||
|
||||
ego-browser scripts do not inherit environment variables or argv, so every
|
||||
input has to be written into the script text. This helper replaces the
|
||||
literal token __CFG__ in a template with the JSON config.
|
||||
|
||||
Usage:
|
||||
python3 render.py <template.js> <config.json> <output.js>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
template, cfg_path, out_path = sys.argv[1:4]
|
||||
cfg = json.load(open(cfg_path, encoding="utf-8"))
|
||||
src = open(template, encoding="utf-8").read()
|
||||
assert "__CFG__" in src, "template has no __CFG__ placeholder"
|
||||
open(out_path, "w", encoding="utf-8").write(src.replace("__CFG__", json.dumps(cfg, ensure_ascii=False)))
|
||||
print("rendered", out_path)
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check the individual PDFs written by print_items.js.
|
||||
|
||||
Usage: python3 -I verify_pdfs.py <tmpDir>
|
||||
|
||||
Reports: file count, duplicate files (same hash = a stale page was printed
|
||||
twice), articles whose first heading does not match the file label, empty
|
||||
PDFs, and the first heading + page count of every non-article file
|
||||
(총설 / 전론 / 후론 ...) so a human can eyeball them.
|
||||
Exit status 1 when anything is wrong.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
tmp = sys.argv[1]
|
||||
files = sorted(f for f in os.listdir(tmp) if f.endswith(".pdf"))
|
||||
bad = 0
|
||||
|
||||
|
||||
def text(path):
|
||||
return subprocess.run(["pdftotext", path, "-"], capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def pages(path):
|
||||
out = subprocess.run(["pdfinfo", path], capture_output=True, text=True).stdout
|
||||
return int(re.search(r"Pages:\s+(\d+)", out).group(1))
|
||||
|
||||
|
||||
seen = {}
|
||||
for f in files:
|
||||
h = hashlib.md5(open(os.path.join(tmp, f), "rb").read()).hexdigest()
|
||||
if h in seen:
|
||||
print("DUPLICATE", f, "==", seen[h])
|
||||
bad = 1
|
||||
seen[h] = f
|
||||
print("files:", len(files))
|
||||
|
||||
for f in files:
|
||||
p = os.path.join(tmp, f)
|
||||
m = re.match(r"s.+?_(\d{2,})_(.+)\.pdf$", f)
|
||||
lab = m.group(2)
|
||||
lines = [l.strip() for l in text(p).split("\n") if l.strip()]
|
||||
if not lines:
|
||||
print("EMPTY", f)
|
||||
bad = 1
|
||||
continue
|
||||
if re.match(r"제\d+조(의\d+)?$", lab):
|
||||
if not any(re.match(re.escape(lab) + r"(\s|\[|$)", l) for l in lines[:14]):
|
||||
print("MISMATCH", f, "| first lines:", lines[2:4])
|
||||
bad = 1
|
||||
else:
|
||||
head = next((l for l in lines[2:14] if l), "")
|
||||
print(f"{f} | {pages(p)}쪽 | {' / '.join(lines[2:4])[:80]}")
|
||||
sys.exit(bad)
|
||||
Reference in New Issue
Block a user