--- name: chapter-notes-builder description: Turns an uploaded textbook chapter (PDF) into colour-coded revision notes in a fixed three-part layout — a blue "Chapter Insights" explainer, a green "Solutions" section (answers to the textbook's own questions) and a red "Practice Questions" section (all with answers) — delivered as a PDF and/or an editable Word file (the user chooses), optionally with the chapter's maps and diagrams copied in. Use whenever a student uploads a school textbook chapter and asks for notes, study notes, revision notes, a chapter summary, "notes like the last one", or a solved chapter. ALWAYS begin with the intake questions in section 1 — they are compulsory even when the host is in an auto-run / turbo / no-confirmation mode (Claude Code, Antigravity or any IDE agent); the first question lets the user switch this skill off. --- # Colour-Coded Chapter Notes Builder Produces one study document per chapter, identical in look and structure every time, so a student's notes for different chapters and subjects match. ``` Header strip Class | Subject | Unit/Book name Chapter title CH{n} – {TITLE} ┌ SECTION A : CHAPTER INSIGHTS (blue) explainer of the whole chapter ← always ├ SECTION B : SOLUTIONS (green) answers to the textbook's own questions ← if user wants └ SECTION C : PRACTICE QUESTIONS (red) MCQ · VSA · SA · LA · case studies, all solved ← if user wants ``` Colours belong to the **content type**, not the letter. If a section is switched off, the remaining sections are re-lettered (A, B, …) but keep their colours. --- ## 1. Intake — ask BEFORE doing any work > ### ⚠ MANDATORY EVEN IN TURBO / AUTO-RUN MODE > Some hosts (Claude Code with auto-accept, Antigravity or other IDE agents in "turbo", "auto-run", "YOLO", "no request/review" mode, or any headless run) are configured never to stop and ask. **This skill overrides that for the intake questions below — and only for them.** > * **Stop and ask the intake questions (Q1–Q5) before any other action** — before reading the PDF, running commands, writing files or building anything. The only thing you may do first is confirm the uploaded file exists. > * Use the host's ask-the-user tool if it has one (e.g. a question / multiple-choice tool). If it has none, **print the questions as a normal message and end your turn** with no further tool calls; the user's reply is your answer. Ending the turn is how you wait. > * **Never answer them yourself.** Auto-run mode, an empty reply, a timeout, or "continue" is **not** an answer and is **not** permission to use defaults. Defaults apply only if the user explicitly says "you decide" / "use defaults" / "all of it". > * Answers given earlier in the *same conversation* by the user may be reused (say so in one line). Do not infer answers from earlier sessions, file names or the mode itself. > * Everything else stays autonomous: no permission prompts, no "shall I proceed?", no clarifying questions about content, layout or wording — pick sensible choices and build. After the answers arrive, run to the end without stopping. ### Question 1 — ask it alone, first > **Do you want me to use my colour-coded notes format for this (blue explainer · green solutions · red practice questions), or should I skip this format and just handle your request normally?** > 1. Use the colour-coded notes format 2. Don't use it — deactivate this skill * Answer 2 → stop applying this skill completely. Say "Okay, I'll handle it normally" and carry on with the user's request using your usual behaviour. Ask nothing else from this skill. * Answer 1 → go on to the next step. * If the user's message already says plainly that they want this format (e.g. "make the notes in the usual colour format"), treat Q1 as answered "1" and don't ask it. ### Questions 2–5 — ask together in ONE message, numbered, each answerable with a digit or a word > **2. Textbook solutions** — Should I solve the textbook's own questions (the in-text prompts like "Let's Explore / Think About It" and the end-of-chapter questions)? Yes / No > > **3. Practice questions** — Do you want practice questions in the document? > 1. No practice questions > 2. AI-generated questions (MCQs, very short, short, long and case-study questions, all with answers) > 3. My own question bank — I'll upload or paste it and you integrate it into the document (with answers) > 4. Both — my bank plus AI-generated ones > > **4. Maps and figures** — Should I copy the maps, diagrams and figures from your PDF into the notes, next to the topics they explain? Yes / No > > **5. File format** — Do you want the finished notes as a PDF, a Word (.docx) file, or both? (Making and checking both uses more time and more of this conversation's budget, so pick one if you can.) > 1. PDF only 2. Word (.docx) only 3. Both Rules for intake * Use the host's tappable-choice / multiple-choice tool if it has one; otherwise a plain numbered message. Never more than these questions. * Skip any question the user has already answered in their message. If they reply "you decide" / "all", use the defaults: Q2 Yes · Q3 option 2 · Q4 Yes (only if the chapter actually has maps/figures) · Q5 PDF only. * If they pick Q3 option 3 or 4 and have not supplied the bank yet, ask them to attach or paste it, then wait. * After the answers, state the plan in ONE line ("Building: Insights + Solutions + AI practice questions + figures, as a PDF") and build. No further confirmation questions. | Q2 | Q3 | Result | |---|---|---| | No | No | Only the blue Insights section (banner: `CHAPTER INSIGHTS`, no letter) | | No | Yes | A (blue) + B (red) | | Yes | No | A (blue) + B (green) | | Yes | Yes | A (blue) + B (green) + C (red) | --- ## 2. Read the source completely 1. `pdfinfo` + `pdffonts` → page count and whether there is a text layer. Text layer present → `pdftotext -layout file.pdf out.txt`, then read **all** of it (compact whitespace: `sed -E 's/[[:space:]]+/ /g; /^ ?$/d'`). No text layer (scan) → render pages to PNG and read them visually / OCR. 2. The upload may have no `.pdf` extension: run `file` on it, copy to `name.pdf`, continue. 3. Note while reading: chapter number and title; the running header (unit/book name → right cell of the header strip; class and subject → left/middle); every heading and sub-heading; every margin glossary term; every box ("Let's Explore", "Think About It", "Don't Miss Out", "Let's Remember", caselets, quotes); every number, date, name; the "Before we move on" summary; the end-of-chapter questions; the list of figures (and their page numbers if Q4 = Yes). 4. Never invent facts. Every statement in the notes must trace to the chapter. Where a question needs outside knowledge (an example, a definition), keep it standard, grade-appropriate and consistent with the chapter. 5. Never invent personal details (student name, teacher name, phone number). The header strip uses only class, subject and unit/book name. 6. Match the book's spelling (British/Indian English → *colour, organise*) and its own terms. --- ## 3. Document specification (tool-agnostic) Page: **A4**, margins **0.625 in (900 twips)** all round. Font **Calibri**. Running header (centred, italic, 8 pt, grey `888888`, thin navy rule under it): "{Chapter title} — Notes". Footer: centred page number, 9 pt, `666666`. Each section starts on a new page; a section never starts with a blank page. ### Palette (use exactly) | Role | Hex | |---|---| | Chapter title, header strip rule, running-header rule | `16345C` navy | | Section A (Insights) banner & sub-headings | `1F6FB2` blue | | Section B (Solutions) banner & sub-headings | `2E8B57` green | | Section C (Practice) banner & sub-headings | `C0392B` red | | KEY TERM box | fill `DCEEF9`, border/title `1F6FB2` | | Facts / timeline / "Don't miss out" box | fill `FFF6D9`, border/title `E0A800` | | Case study / caselet / biography box | fill `FDECEA`, border/title `C0392B` | | Table header | fill `1F6FB2`, white bold text; zebra rows `FFFFFF` / `F2F7FC`; grid `AAAAAA` | | MCQ answer line | green `2E8B57` bold italic | | Figure caption | `555555` italic 9 pt | ### Type scale Chapter title 16 pt bold · section banner 13 pt bold white on colour (full-width one-cell table) · sub-heading 11.5 pt bold in section colour with a thin bottom rule · mini-heading 10.5 pt bold (green inside Section A) · body 10.5 pt · answers 10 pt · table text 9.5 pt · box title 10.5 pt bold in box colour, box text 10.5 pt. ### Components | Component | Look | |---|---| | Section banner | full-width coloured bar, white bold uppercase text: `SECTION A : CHAPTER INSIGHTS`, `SECTION B : SOLUTIONS`, `SECTION C : PRACTICE QUESTIONS` | | Boxes | single-cell table, 1 pt border, padded (≈ 0.1 in top/bottom, 0.15 in sides), bullet `▪`, title in caps on first line | | Body bullets | `●`, 0.3 in indent | | Bold | for key terms, numbers, dates, names (inline `**bold**` in the helper code) | | Question line | red/green/blue number matching the section colour, then the question | | Answer line | indented 0.18 in, bold-italic **Ans:** then the answer in 10 pt | | MCQ | question; options on one line as `(a) … (b) … (c) … (d) …`; then `Answer: (x)` | | Case study | scenario in a title-only red box, then `(i) (ii) (iii)` questions each followed by **Ans:** | | Two boxes/tables in a row | always put a small gap between them (`gap()`), otherwise they fuse | --- ## 4. Section A — CHAPTER INSIGHTS (blue, always present) A faithful, complete, easy-to-revise explainer of the chapter — not a shortened copy and not an essay. Order 1. `The Big Questions` (from the chapter opener) as bullets. 2. Numbered topics `1. … 2. …` following the chapter's own headings, in order. Each: a short paragraph with **bold** key ideas, then bullets/table/boxes as fits. Use mini-headings for sub-topics. 3. `Before We Move On …` — the chapter's summary points as bullets (last block). Map textbook features to components | Textbook feature | Notes component | |---|---| | Margin glossary term / definition | `KEY TERM(S)` blue box, placed right after the paragraph that uses the term | | "Don't Miss Out", fun facts, "Did you know", "Let's Remember" | yellow box (`DON'T MISS OUT`, `QUICK FACTS`, `DID YOU KNOW?`) | | Caselet, case study, biography, "heroes/heroines" panel | red box `CASE STUDY : {title}` / custom title, 3–5 bullets with the figures and outcome | | Timeline | yellow box `TIMELINE — KEY DATES`, each line **date:** event | | Comparison, classification, list of examples, formulas | blue-header table | | Process / flow chart | ordered mini-heading + bullets (or the figure itself if Q4 = Yes) | | Quotations | one short line inside the paragraph, attributed | | Activities ("Let's Explore" tasks) | do NOT put in Section A (they go to Section B if Q2 = Yes) | Rules: include every key definition, number, date, name, cause→effect and example the chapter gives; do not add outside material; no filler sentences; every box has a purpose. Typical length 4–7 pages. --- ## 5. Section B — SOLUTIONS (green; only if Q2 = Yes) **Only solutions.** No commentary, no study tips, no re-teaching. * Sub-headings use the book's own labels, in page order: e.g. `Let's Explore / Think About It / Don't Miss Out`, then `Questions and Activities (Page N)`. If the book has "Probe and Ponder", "Intext", "Keep the curiosity alive", etc., use those headings. * Each item: number, the question (trimmed, with `(Page N)`), then **Ans:** the solution. Multi-part questions (a)(b)(c) or I–V: answer every part, labelled. * Answer lengths: definition/recall 1 line; explain/why 2–4 sentences; discuss/analyse 4–6 sentences. Use the chapter's facts and wording level of the grade. * Open-ended, personal or local tasks (survey, interview, "your region", "your neighbourhood", draw/poster/story/role-play): give a short **model answer or outline** the student can adapt (headline + 4–5 timeline points; sample dialogue opening; story outline; research steps and headings). Never fabricate local data, statistics or sources about the student's own area. * "Discuss in groups / opinion" prompts: give a balanced answer with a reasonable stance and both sides. * Case-based textbook items (a caselet followed by questions): show the caselet in a one-line green-bordered/neutral reminder box if needed, then (a)(b)(c)… with answers. * If the chapter has no questions at all, skip Section B and tell the user in the chat reply. --- ## 6. Section C — PRACTICE QUESTIONS (red; only if Q3 ≠ 1) Sub-headings (in this order): `Multiple Choice Questions`, `Very Short Answer Questions`, `Short Answer Questions`, `Long Answer Questions`, `Case Study Based Questions`. **Every question has its solution** directly under it. ### Q3 = 2 (AI-generated) — defaults, adjustable if the user states other counts | Type | Count | Numbering | Solution style | |---|---|---|---| | MCQ | 15 | 1–15 | 4 options; `Answer: (x)` | | Very short answer | 10 | 16–25 | one line | | Short answer | 10 | 26–35 | 2–4 sentences | | Long answer | 5 | 36–40 | one solid paragraph (≈120–220 words) covering all points a 5-mark answer needs | | Case study | 3 | 41–43 | new scenario (2–4 lines) + (i)(ii)(iii), each answer 1–3 sentences | Quality rules * Spread questions across the **whole chapter** in the order of the topics; mix recall, understanding and application; include the chapter's key terms, dates, numbers and cause–effect links. * **Vary MCQ answer letters** — roughly equal use of a/b/c/d, no more than 5 of 15 on one letter, no obvious pattern. Distractors must be plausible and clearly wrong on checking the chapter. * Do not copy the textbook's own questions; do not repeat a question; no trick or opinion-only questions in MCQ/VSA. * Case-study scenarios are original, realistic and use ideas from the chapter (not a retelling of a chapter caselet). * Every answer must be correct against the chapter. After writing, re-check each MCQ key and each number/date. ### Q3 = 3 (user's own bank) * Keep the user's wording and order. Sort into the five sub-headings by the bank's own labels; if unlabeled, infer by format/marks and mention that in the chat reply. * If the bank includes answers, use them (tidy formatting only); if an answer contradicts the chapter, keep the user's version in the document and flag it in the chat reply. If no answers, write them (same styles as above). * Numbering continues across types as in the table (or the bank's own numbering if it has one — keep it consistent within the document). * Don't add AI-generated questions. ### Q3 = 4 (both) Within each sub-heading put the user's questions first, then AI-generated ones to bring the type up to the default count (never fewer than the user's own). Number continuously. --- ## 7. Figures — only if Q4 = Yes Goal: put the chapter's maps and important diagrams in the notes beside the explanation that uses them. What to include: maps (political/physical/route/thematic), diagrams, flow charts, graphs/charts, satellite or data images the text refers to, and any picture the text analyses closely. Skip decorative art, cartoon characters, portraits, stock photos. Typically 6–15 figures. How (needs code execution + the ability to look at images) 1. Find figure pages from the text layer (`Fig. n.n`) and render them: `pdftoppm -f P -l P -r 160 -png`. 2. **Crop rendered pages — do not use `pdfimages`**: labels on textbook maps are usually vector text drawn over the picture and would be lost. Use `crop_figures.py` (Appendix B): `auto_crop` finds the picture's tight edges; `manual_crop` for pictures with large white areas. 3. **Look at a contact sheet of every crop** before using it. Re-crop anything with clipped edges, missing legend/scale/compass, or stray caption text. Original captions are excluded from the crop; you add a clean caption instead. 4. Insert each figure at the topic it illustrates, centred, with the caption `Fig. {n}. {caption from the book, shortened}`. Size ≤ 540 px wide and ≤ 400 px tall (smaller for portrait maps); keep figure and caption together (`keepNext`). Annotated figures whose caption sits inside the picture (callout diagrams) go in without an added caption. 5. Re-check page flow after inserting: no table split by a figure unnecessarily, no near-empty pages caused by a figure; shrink figures slightly if needed. If figures can't be extracted (no code, or can't view images): add a grey `FIGURE — Fig. n.n, textbook p. N` placeholder box where each figure belongs and tell the user. --- ## 8. Build, check, deliver Build * With code execution: Node + `docx` (npm) using Appendix A, or an equivalent library. One script, content in arrays, one build call. The DOCX is always built first (`{Chapter_Title}_Notes.docx`); convert it to PDF with LibreOffice (`soffice --headless --convert-to pdf`) only if the user chose PDF or both — or temporarily, to check the pages, when they chose Word only. * Save tokens: build once, convert once, and only open the files the user asked for. Don't present, re-render or re-verify a format the user didn't choose. * Page breaks: give the first element of each new section `pageBreakBefore` (helper `pageBreakPara()`); never insert a stray empty paragraph or a page-break run before it (this produces blank pages). * Only `**bold**` inline markup exists in the helpers; single `*asterisks*` print literally — don't use them. Use plain text for foreign terms/diacritics (UTF-8 is fine). Check (render the PDF to images and look at the pages — at least the first page, every section's first page, every figure page and the last page; for a Word-only request render a temporary PDF just for this check and don't deliver it) - [ ] Colours and banners as specified; sections re-lettered correctly for the answers given - [ ] No blank pages, no clipped boxes/figures, no literal `**` or `*` - [ ] Boxes never touch each other; captions sit with their figures - [ ] Every chapter heading, glossary term and summary point is covered in Section A - [ ] Every textbook question solved (if Q2) · every practice question has a solution (if Q3) - [ ] MCQ keys verified and varied · numbers/dates match the chapter - [ ] No invented personal info or local data - [ ] The intake answers came from the user (or an explicit "you decide"), never from the mode or a guess Deliver * Deliver exactly what Q5 asked for: **PDF only**, **Word only**, or **both**. Name: `{Chapter_Title}_Notes.pdf` / `.docx`. Don't hand over the other format "just in case". * The chat reply is short: what's inside (sections and counts), assumptions made, and anything skipped (e.g. "no end-of-chapter questions found", "figure 1.7 not included"). No long recap of the notes. * Several chapters in one conversation: repeat the intake only if the user changes their preferences; otherwise reuse the same choices and say so in one line. --- ## 9. If you cannot run code * Produce the same structure as one self-contained **HTML** file (print-to-PDF ready) using the palette above as CSS variables — banners `div.banner`, boxes `div.box.term|fact|case` with `border:1.5px solid` and the fill colours, tables with the blue header — and tell the user to open it and "Print → Save as PDF". * If even that is impossible, output clean Markdown with the same section order and label boxes as `> **KEY TERM** …` blockquotes; say that colours need the file route. * Figures (Q4) need code + image access; otherwise use placeholders and tell the user. --- ## Appendix A — `helpers.js` (docx-js component library) Install: `npm install docx`. Save as `helpers.js`. ```js // helpers.js — component library for colour-coded chapter notes (docx-js) // Usage: const H = require("./helpers.js"); then push components into a `children` array // and call H.buildDoc(children, runningTitle, outPath). const { Document, Packer, Paragraph, TextRun, AlignmentType, ImageRun, Table, TableRow, TableCell, WidthType, BorderStyle, ShadingType, VerticalAlign, Header, Footer, PageNumber, LevelFormat } = require("docx"); const fs = require("fs"); const CONTENT_WIDTH = 10106; // A4 minus 900-twip margins const FONT = "Calibri"; const COLORS = { navy: "16345C", insights: "1F6FB2", // Section: Chapter Insights (blue) solutions: "2E8B57", // Section: Solutions (green) practice: "C0392B", // Section: Practice Questions (red) defFill: "DCEEF9", defBorder: "1F6FB2", // KEY TERM boxes factFill: "FFF6D9", factBorder: "E0A800", // facts / timeline boxes caseFill: "FDECEA", caseBorder: "C0392B", // case study boxes tableHeader: "1F6FB2", tableAlt: "F2F7FC", white: "FFFFFF", }; // Inline markup: **bold** only. Never use single asterisks (they print literally). function parseInline(text, opts = {}) { const parts = text.split(/(\*\*[^*]+\*\*)/g).filter(p => p.length > 0); return parts.map(p => (p.startsWith("**") && p.endsWith("**")) ? new TextRun({ text: p.slice(2, -2), bold: true, font: FONT, size: opts.size || 21, color: opts.color }) : new TextRun({ text: p, font: FONT, size: opts.size || 21, italics: opts.italics, color: opts.color })); } const bullet = (t) => new Paragraph({ numbering: { reference: "notes-bullets", level: 0 }, spacing: { after: 60 }, children: parseInline(t) }); const para = (t, o = {}) => new Paragraph({ spacing: { after: o.after !== undefined ? o.after : 140 }, children: parseInline(t, o) }); const spacer = (h = 60) => new Paragraph({ spacing: { after: h }, children: [] }); const gap = () => spacer(90); // put between two boxes/tables so they never touch const pageBreakPara = () => new Paragraph({ pageBreakBefore: true, children: [] }); // use THIS, not a PageBreak run (avoids blank pages) function chapterTitle(text, color = COLORS.navy) { return new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 120, after: 200 }, border: { bottom: { style: BorderStyle.SINGLE, size: 12, color } }, children: [new TextRun({ text, bold: true, size: 32, color, font: FONT })] }); } function sectionBanner(text, fill) { return new Table({ width: { size: CONTENT_WIDTH, type: WidthType.DXA }, columnWidths: [CONTENT_WIDTH], rows: [new TableRow({ children: [new TableCell({ width: { size: CONTENT_WIDTH, type: WidthType.DXA }, shading: { type: ShadingType.CLEAR, fill, color: "auto" }, verticalAlign: VerticalAlign.CENTER, margins: { top: 130, bottom: 130, left: 200, right: 200 }, children: [new Paragraph({ children: [new TextRun({ text, bold: true, size: 26, color: COLORS.white, font: FONT })] })] })] })] }); } const subHeading = (text, color, o = {}) => new Paragraph({ spacing: { before: o.before !== undefined ? o.before : 220, after: 100 }, border: { bottom: { style: BorderStyle.SINGLE, size: 4, color } }, keepNext: true, children: [new TextRun({ text, bold: true, size: 23, color, font: FONT })] }); const miniHeading = (text, color) => new Paragraph({ spacing: { before: 140, after: 60 }, keepNext: true, children: [new TextRun({ text, bold: true, size: 21, color, font: FONT })] }); // Coloured single-cell box. lines = array of strings (bullets by default). Empty lines => title-only box. function coloredBox({ title, titleColor, fill, border, lines, isBullets = true }) { const body = lines.map(l => isBullets ? new Paragraph({ numbering: { reference: "box-bullets", level: 0 }, spacing: { after: 50 }, children: parseInline(l) }) : new Paragraph({ spacing: { after: 60 }, children: parseInline(l) })); const b = (c) => ({ style: BorderStyle.SINGLE, size: 8, color: c }); const none = { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }; return new Table({ width: { size: CONTENT_WIDTH, type: WidthType.DXA }, columnWidths: [CONTENT_WIDTH], borders: { top: b(border), bottom: b(border), left: b(border), right: b(border), insideHorizontal: none, insideVertical: none }, rows: [new TableRow({ children: [new TableCell({ width: { size: CONTENT_WIDTH, type: WidthType.DXA }, shading: { type: ShadingType.CLEAR, fill, color: "auto" }, margins: { top: 140, bottom: 140, left: 220, right: 220 }, children: [new Paragraph({ spacing: { after: body.length ? 80 : 0 }, children: [new TextRun({ text: title, bold: true, size: 21, color: titleColor, font: FONT })] }), ...body] })] })] }); } // Convenience wrappers for the three box families const keyTerms = (lines, title = lines.length > 1 ? "KEY TERMS" : "KEY TERM") => coloredBox({ title, titleColor: COLORS.defBorder, fill: COLORS.defFill, border: COLORS.defBorder, lines }); const factBox = (title, lines) => coloredBox({ title, titleColor: COLORS.factBorder, fill: COLORS.factFill, border: COLORS.factBorder, lines }); const caseBox = (title, lines = [], isBullets = true) => coloredBox({ title, titleColor: COLORS.caseBorder, fill: COLORS.caseFill, border: COLORS.caseBorder, lines, isBullets }); function dataTable(headers, rows, widths, headerFill = COLORS.tableHeader) { const total = widths.reduce((a, b) => a + b, 0); const g = { style: BorderStyle.SINGLE, size: 4, color: "AAAAAA" }; const head = new TableRow({ tableHeader: true, children: headers.map((h, i) => new TableCell({ width: { size: widths[i], type: WidthType.DXA }, shading: { type: ShadingType.CLEAR, fill: headerFill, color: "auto" }, verticalAlign: VerticalAlign.CENTER, margins: { top: 90, bottom: 90, left: 110, right: 110 }, children: [new Paragraph({ children: [new TextRun({ text: h, bold: true, color: COLORS.white, size: 20, font: FONT })] })] })) }); const body = rows.map((r, ri) => new TableRow({ cantSplit: true, children: r.map((c, i) => new TableCell({ width: { size: widths[i], type: WidthType.DXA }, shading: { type: ShadingType.CLEAR, fill: ri % 2 === 0 ? COLORS.white : COLORS.tableAlt, color: "auto" }, margins: { top: 90, bottom: 90, left: 110, right: 110 }, children: [new Paragraph({ children: parseInline(c, { size: 19 }) })] })) })); return new Table({ width: { size: total, type: WidthType.DXA }, columnWidths: widths, borders: { top: g, bottom: g, left: g, right: g, insideHorizontal: g, insideVertical: g }, rows: [head, ...body] }); } // Question + answer. `num` may be a number, "(i)", "a", etc. `color` = section colour. function qBlock(num, q, a, color) { return [ new Paragraph({ keepNext: true, spacing: { before: 130, after: 40 }, children: [new TextRun({ text: `${num}. `, bold: true, color, font: FONT, size: 21 }), ...parseInline(q, { size: 21 })] }), new Paragraph({ spacing: { after: 90 }, indent: { left: 260 }, children: [new TextRun({ text: "Ans: ", bold: true, italics: true, font: FONT, size: 20 }), ...parseInline(a, { size: 20 })] }), ]; } // MCQ with answer line. options = array of strings, ans = "a".."d". VARY the correct letter across questions. function mcq(num, q, options, ans) { const opts = options.map((o, i) => `(${String.fromCharCode(97 + i)}) ${o}`).join(" "); return [ new Paragraph({ keepNext: true, spacing: { before: 110, after: 20 }, children: [new TextRun({ text: `${num}. `, bold: true, color: COLORS.practice, font: FONT, size: 21 }), ...parseInline(q, { size: 21 })] }), new Paragraph({ keepNext: true, spacing: { after: 20 }, indent: { left: 260 }, children: parseInline(opts, { size: 20 }) }), new Paragraph({ spacing: { after: 90 }, indent: { left: 260 }, children: [new TextRun({ text: `Answer: (${ans})`, bold: true, italics: true, color: COLORS.solutions, size: 19, font: FONT })] }), ]; } // Case study: scenario box (title-only) followed by (i)/(ii)/(iii) Q&A. parts = [[q, a], ...] function caseStudy(num, scenario, parts) { const out = [caseBox(`${num}. ${scenario}`)]; parts.forEach(([q, a], i) => out.push(...qBlock(["(i)", "(ii)", "(iii)", "(iv)", "(v)"][i], q, a, COLORS.caseBorder))); out.push(spacer(120)); return out; } // ---- Figures (only when the user asked for maps/diagrams from the PDF) ---- function imgSize(buf) { if (buf[0] === 0x89 && buf[1] === 0x50) return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20), type: "png" }; let i = 2; while (i < buf.length) { if (buf[i] !== 0xFF) { i++; continue; } const m = buf[i + 1]; if (m >= 0xC0 && m <= 0xCF && ![0xC4, 0xC8, 0xCC].includes(m)) return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5), type: "jpg" }; i += 2 + buf.readUInt16BE(i + 2); } throw new Error("Unsupported image"); } function figure(path, caption, maxW = 540, maxH = 400) { const buf = fs.readFileSync(path); const { w, h, type } = imgSize(buf); const s = Math.min(maxW / w, maxH / h, 1.5); const out = [new Paragraph({ alignment: AlignmentType.CENTER, keepNext: !!caption, spacing: { before: 100, after: caption ? 40 : 120 }, children: [new ImageRun({ type, data: buf, transformation: { width: Math.round(w * s), height: Math.round(h * s) } })] })]; if (caption) out.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { after: 140 }, children: [new TextRun({ text: caption, italics: true, size: 18, color: "555555", font: FONT })] })); return out; } // Used when a figure cannot be extracted: keeps the reader pointed at the textbook. const figurePlaceholder = (label) => coloredBox({ title: `FIGURE — ${label}`, titleColor: "555555", fill: "F2F2F2", border: "AAAAAA", lines: [], isBullets: false }); // Three-cell title strip: left = class, middle = subject, right = unit/book name (read from the textbook's running header) function headerRowTable(left, middle, right) { const none = { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }; const cell = (w, al, t) => new TableCell({ width: { size: w, type: WidthType.DXA }, margins: { bottom: 80 }, children: [new Paragraph({ alignment: al, children: [new TextRun({ text: t, bold: true, size: 20, font: FONT })] })] }); return new Table({ width: { size: CONTENT_WIDTH, type: WidthType.DXA }, columnWidths: [3369, 3368, 3369], borders: { top: none, bottom: { style: BorderStyle.SINGLE, size: 6, color: COLORS.navy }, left: none, right: none, insideHorizontal: none, insideVertical: none }, rows: [new TableRow({ children: [cell(3369, AlignmentType.LEFT, left), cell(3368, AlignmentType.CENTER, middle), cell(3369, AlignmentType.RIGHT, right)] })] }); } function buildDoc(children, runningTitle, outPath) { const doc = new Document({ numbering: { config: [ { reference: "notes-bullets", levels: [{ level: 0, format: LevelFormat.BULLET, text: "●", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 460, hanging: 260 } } } }] }, { reference: "box-bullets", levels: [{ level: 0, format: LevelFormat.BULLET, text: "▪", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 320, hanging: 220 } } } }] }] }, sections: [{ properties: { page: { margin: { top: 900, bottom: 900, left: 900, right: 900 } } }, headers: { default: new Header({ children: [new Paragraph({ border: { bottom: { style: BorderStyle.SINGLE, size: 4, color: COLORS.navy } }, alignment: AlignmentType.CENTER, children: [new TextRun({ text: runningTitle, size: 16, color: "888888", font: FONT, italics: true })] })] }) }, footers: { default: new Footer({ children: [new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ children: [PageNumber.CURRENT], size: 18, font: FONT, color: "666666" })] })] }) }, children }], styles: { default: { document: { run: { font: FONT, size: 21 } } } }, }); return Packer.toBuffer(doc).then(buf => { fs.writeFileSync(outPath, buf); console.log("written", outPath); }); } module.exports = { COLORS, CONTENT_WIDTH, parseInline, bullet, para, spacer, gap, pageBreakPara, chapterTitle, sectionBanner, subHeading, miniHeading, coloredBox, keyTerms, factBox, caseBox, dataTable, qBlock, mcq, caseStudy, figure, figurePlaceholder, headerRowTable, buildDoc }; ``` ## Appendix B — `crop_figures.py` (cutting figures out of the PDF) Needs `poppler-utils` (`pdftoppm`) and Python `pillow`, `numpy`. ```python #!/usr/bin/env python3 """crop_figures.py — cut maps/diagrams out of a textbook PDF (keeps vector labels because it crops RENDERED pages). Typical use (inside Python or as a script): 1. render_pages("chapter.pdf", [5, 9, 11], "figs") -> figs/p5.png ... 2. look at the pages (view them), then EITHER a) auto_crop("figs/p11.png", x_range=(60,1500), y_range=(200,1250)) # detects the picture's edges b) manual_crop("figs/p3.png", (95,90,500,360), scale=1414/700) # box taken from a downscaled preview 3. contact_sheet([...jpgs], "figs/check.jpg") and LOOK at it before using the crops. """ import subprocess, numpy as np from PIL import Image def render_pages(pdf, pages, outdir, dpi=160): import os; os.makedirs(outdir, exist_ok=True) for p in pages: subprocess.run(["pdftoppm", "-f", str(p), "-l", str(p), "-r", str(dpi), "-png", pdf, f"{outdir}/p{p}"], check=True) # pdftoppm zero-pads page numbers for long documents (p05-05.png etc.); normalise names import glob, re, shutil for f in glob.glob(f"{outdir}/p*-*.png"): m = re.match(rf"{outdir}/p(\d+)-(\d+)\.png", f) if m: shutil.move(f, f"{outdir}/p{int(m.group(2))}.png") def _longest_run(mask, gap=8): best, start, last = (0, 0), None, None for i, v in enumerate(mask): if v: if start is None: start = i last = i elif start is not None and i - last > gap: if last - start > best[1] - best[0]: best = (start, last) start = None if start is not None and last - start > best[1] - best[0]: best = (start, last) return best def auto_crop(page_png, x_range, y_range, row_thr=0.6, col_thr=0.6): """Search inside a generous box; return the tight bounding box of the dense (non-white) picture, excluding caption text. Lower the thresholds (0.35-0.45) for pictures with large white areas (ice caps, ellipse maps, legends).""" im = Image.open(page_png).convert("RGB"); a = np.array(im) x0, x1 = map(int, x_range); y0, y1 = map(int, y_range) nonwhite = (a[y0:y1, x0:x1].min(axis=2) < 225) r0, r1 = _longest_run(nonwhite.mean(axis=1) > row_thr) c0, c1 = _longest_run(nonwhite[r0:r1 + 1].mean(axis=0) > col_thr, gap=4) return im.crop((x0 + c0, y0 + r0, x0 + c1 + 1, y0 + r1 + 1)) def manual_crop(page_png, box, scale=1.0): im = Image.open(page_png).convert("RGB") return im.crop(tuple(int(v * scale) for v in box)) def save(img, path, quality=90): img.save(path, quality=quality) def contact_sheet(paths, out, cols=3, cell=(620, 520)): rows = (len(paths) + cols - 1) // cols sheet = Image.new("RGB", (cell[0] * cols, cell[1] * rows), "white") for i, p in enumerate(paths): im = Image.open(p); im.thumbnail((cell[0] - 8, cell[1] - 8)); sheet.paste(im, ((i % cols) * cell[0] + 4, (i // cols) * cell[1] + 4)) sheet.save(out, quality=85) ``` ## Appendix C — build-script skeleton ```js const H = require("./helpers.js"); const C = H.COLORS; const c = []; const WANT = { solutions: true, practice: "ai" /* "none" | "ai" | "bank" | "both" */, figures: true }; c.push(H.headerRowTable("Class VIII", "Social Science", "Unit or book name from the running header")); c.push(H.chapterTitle("CH4 – THE CHAPTER TITLE")); // ---- Section A (always) ---- c.push(H.sectionBanner("SECTION A : CHAPTER INSIGHTS", C.insights)); c.push(H.spacer(100)); c.push(H.subHeading("The Big Questions", C.insights, { before: 0 })); c.push(H.bullet("First big question?")); c.push(H.subHeading("1. First topic", C.insights)); c.push(H.para("Explanation with **key ideas in bold**.")); c.push(H.keyTerms(["**Term:** definition from the margin glossary."])); c.push(H.gap()); c.push(H.factBox("DON'T MISS OUT", ["A fun fact from the chapter."])); c.push(H.dataTable(["Type", "Example"], [["A", "x"], ["B", "y"]], [3000, 7106])); if (WANT.figures) c.push(...H.figure("figs/fig1_5.jpg", "Fig. 1.5. Caption from the book.", 520, 380)); c.push(H.subHeading("Before We Move On …", C.insights)); c.push(H.bullet("Summary point from the chapter.")); // ---- Section B (solutions) ---- if (WANT.solutions) { c.push(H.pageBreakPara()); c.push(H.sectionBanner("SECTION B : SOLUTIONS", C.solutions)); c.push(H.spacer(100)); c.push(H.subHeading("Let's Explore / Think About It", C.solutions, { before: 0 })); c.push(...H.qBlock(1, "Question text. (Page 7)", "Solution.", C.solutions)); c.push(H.subHeading("Questions and Activities (Page 19)", C.solutions)); c.push(...H.qBlock(1, "End-of-chapter question.", "Solution.", C.solutions)); } // ---- Practice questions (red) ---- if (WANT.practice !== "none") { c.push(H.pageBreakPara()); const letter = WANT.solutions ? "C" : "B"; c.push(H.sectionBanner(`SECTION ${letter} : PRACTICE QUESTIONS`, C.practice)); c.push(H.spacer(100)); c.push(H.subHeading("Multiple Choice Questions", C.practice, { before: 0 })); c.push(...H.mcq(1, "Question?", ["opt a", "opt b", "opt c", "opt d"], "c")); c.push(H.subHeading("Very Short Answer Questions", C.practice)); c.push(...H.qBlock(16, "Question?", "One-line answer.", C.practice)); c.push(H.subHeading("Short Answer Questions", C.practice)); c.push(...H.qBlock(26, "Question?", "Two to four sentences.", C.practice)); c.push(H.subHeading("Long Answer Questions", C.practice)); c.push(...H.qBlock(36, "Question?", "One solid paragraph.", C.practice)); c.push(H.subHeading("Case Study Based Questions", C.practice)); c.push(...H.caseStudy(41, "New scenario in 2–4 lines.", [["Sub-question (i)?", "Answer."], ["Sub-question (ii)?", "Answer."], ["Sub-question (iii)?", "Answer."]])); } H.buildDoc(c, "Chapter Title — Notes", "Chapter_Title_Notes.docx"); ``` Run: `node build.js` → then, only if the user wants a PDF (Q5 = PDF or both): `soffice --headless --convert-to pdf Chapter_Title_Notes.docx`.