Files
mapas-mentales/libro.ipynb
T

9.9 KiB

import { load } from "jsr:@std/dotenv";
import OpenAI from "jsr:@openai/openai";

const _ = await load({ export: true });
const openai = new OpenAI();
const safeName = (s: string) => s.replace(/[<>:"/\\|?*\x00-\x1F]/g, "_").trim();
const bookName =
  "Nmap Network Scanning Official Nmap Project Guide to Network Discovery and Security Scanning";
const ordinals = [
  "first",
  "second",
  "third",
  "fourth",
  "fifth",
  "sixth",
  "seventh",
  "eighth",
  "ninth",
  "tenth",
  "eleventh",
  "twelfth",
  "thirteenth",
  "fourteenth",
  "fifteenth",
  "sixteenth",
  "seventeenth",
  "eighteenth",
  "nineteenth",
  "twentieth",
];
import { PDFDocument } from "https://cdn.skypack.dev/pdf-lib@^1.11.1?dts";

const INPUT_PDF_PATH = `./books/${bookName}.pdf`;

type Bookmark = { title: string; page: number; level: number; endpage: number };
const bookmarks = await new Deno.Command("pdftk", {
  args: [
    INPUT_PDF_PATH,
    "dump_data",
    "output",
    "-",
  ],
}).output().then(
  (res) => new TextDecoder().decode(res.stdout),
).then((data) => {
  const lines = data.split("\n");
  let bookmarks = [];
  let currentBookmark: Partial<Bookmark> | null = null;

  for (const line of lines) {
    if (line.startsWith("BookmarkBegin")) {
      if (currentBookmark) {
        bookmarks.push(currentBookmark as Bookmark);
      }
      currentBookmark = {};
    } else if (line.startsWith("BookmarkTitle:")) {
      if (currentBookmark) {
        currentBookmark.title = line.replace("BookmarkTitle: ", "").trim();
      }
    } else if (line.startsWith("BookmarkLevel:")) {
      if (currentBookmark) {
        currentBookmark.level = parseInt(
          line.replace("BookmarkLevel: ", "").trim(),
        );
      }
    } else if (line.startsWith("BookmarkPageNumber:")) {
      if (currentBookmark) {
        currentBookmark.page = parseInt(
          line.replace("BookmarkPageNumber: ", "").trim(),
        );
      }
    }
  }
  if (currentBookmark) {
    bookmarks.push(currentBookmark as Bookmark);
  }

  bookmarks = bookmarks.filter((b) => b.level === 1).slice(8);

  for (let i = 0; i < bookmarks.length; i++) {
    const current = bookmarks[i] as Bookmark;
    const next = bookmarks[i + 1] as Bookmark | undefined;
    const currentPage = current.page ?? 0;
    const nextPage = next?.page ?? 0;
    current.endpage = nextPage
      ? Math.max(currentPage, nextPage - 1)
      : currentPage;
  }

  return bookmarks;
});
console.log(bookmarks);

const promises = [];
for (const [idx, ch] of bookmarks.entries()) {
  async function processChapter(idx: number, title: string, file: File) {
    const upload = await openai.files.create({
      file,
      purpose: "user_data",
    });

    const response = await openai.responses.create({
      model: "gpt-5.2",
      reasoning: { effort: "xhigh" },
      input: [{
        role: "user",
        content: [
          {
            type: "input_text",
            text:
              `A complete, exhaustive and very detailed mind map in markmap syntax of only and only this ${
                ordinals[idx]
              } chapter`,
          },
          { type: "input_file", file_id: upload.id },
        ],
      }],
      metadata: {
        chapter: title,
        ordinal: ordinals[idx],
      },
    });
    console.log(`Processing chapter: ${title} at ${response.id}`);

    await openai.files.delete(upload.id);

    const mindMapContent = response.output_text;
    await Deno.writeTextFile(
      `./mindmaps/${safeName(title)}.md`,
      mindMapContent,
    );

    console.log(`Finished processing chapter: ${title}`);
  }
  {
    // Split the chapter into a separate PDF file
    const pdfBytes = await Deno.readFile(INPUT_PDF_PATH);
    const pdfDoc = await PDFDocument.load(pdfBytes);
    const chapterPdf = await PDFDocument.create();

    const startPage = ch.page - 1; // zero-based index
    const endPage = ch.endpage - 1; // zero-based index

    const pagesToCopy = await chapterPdf.copyPages(
      pdfDoc,
      Array.from(
        { length: endPage - startPage + 1 },
        (_, i) => i + startPage,
      ),
    );

    type PdfPage =
      import("https://cdn.skypack.dev/pdf-lib@^1.11.1?dts").PDFPage;

    pagesToCopy.forEach((page: PdfPage): void => {
      chapterPdf.addPage(page);
    });

    const chapterPdfBytes = await chapterPdf.save();
    const chapterFile = new File(
      [chapterPdfBytes],
      `${safeName(ch.title)}.pdf`,
      { type: "application/pdf" },
    );
    promises.push(processChapter(idx, ch.title, chapterFile));
  }
}
await Promise.all(promises);
[
  { title: "01", level: 1, page: 27, endpage: 50 },
  { title: "02", level: 1, page: 51, endpage: 71 },
  { title: "03", level: 1, page: 72, endpage: 97 },
  { title: "04", level: 1, page: 98, endpage: 119 },
  { title: "05", level: 1, page: 120, endpage: 158 },
  { title: "06", level: 1, page: 159, endpage: 168 },
  { title: "07", level: 1, page: 169, endpage: 193 },
  { title: "08", level: 1, page: 194, endpage: 227 },
  { title: "09", level: 1, page: 228, endpage: 278 },
  { title: "10", level: 1, page: 279, endpage: 315 },
  { title: "11", level: 1, page: 316, endpage: 326 },
  { title: "12", level: 1, page: 327, endpage: 356 },
  { title: "13", level: 1, page: 357, endpage: 382 },
  { title: "14", level: 1, page: 383, endpage: 391 },
  { title: "15", level: 1, page: 392, endpage: 392 }
]
Processing chapter: 01
Processing chapter: 02
Processing chapter: 03
Processing chapter: 04
Processing chapter: 05
Processing chapter: 06
Processing chapter: 07
Processing chapter: 08
Processing chapter: 09
Processing chapter: 10
Processing chapter: 11
Processing chapter: 12
Processing chapter: 13
Processing chapter: 14
Processing chapter: 15
Finished processing chapter: 15
Finished processing chapter: 11
Finished processing chapter: 14
Finished processing chapter: 05
Finished processing chapter: 07
Finished processing chapter: 06
Finished processing chapter: 12
Finished processing chapter: 04
Finished processing chapter: 03
Finished processing chapter: 01
Finished processing chapter: 13
Finished processing chapter: 09
Finished processing chapter: 08
Finished processing chapter: 02
// delete all files from openai file storage
const userFiles = await openai.files.list({ purpose: "user_data" });
for (const file of userFiles.data) {
  await openai.files.delete(file.id);
}
{ object: "file", deleted: true, id: "file-X2CJi3gozhJniBURG2qfsm" }