คู่มือ REST API: สรุป PDF ด้วย Node.js + Ollama

คู่มือ REST API: สรุป PDF ด้วย Node.js + Ollama

ขั้นตอนที่ 1: ติดตั้งแพ็กเกจที่จำเป็น

เปิด Terminal แล้วพิมพ์คำสั่ง:

npm init -y
npm install express multer pdf-parse axios cors

ขั้นตอนที่ 2: เขียนไฟล์ server.js

สร้างไฟล์ชื่อ server.js แล้วใส่โค้ดด้านล่างนี้:


const express = require("express");
const multer = require("multer");
const axios = require("axios");
const cors = require("cors");
const fs = require("fs");
const pdfjsLib = require("pdfjs-dist");

const app = express();
const port = 3000;

app.use(cors());

const upload = multer({ dest: "uploads/" });

// 🔹 ฟังก์ชันเรียก Ollama
async function summarizeWithOllama(prompt, model = "llama3") {
    const response = await axios.post("http://localhost:11434/api/generate", {
        model,
        prompt,
        stream: false,
    });
    return response.data.response;
}

// 🔹 สรุปทั้งเล่ม
app.post("/summarize", upload.single("pdf"), async (req, res) => {
    if (!req.file) return res.status(400).json({ error: "กรุณาอัปโหลดไฟล์ PDF" });

    try {
        const buffer = fs.readFileSync(req.file.path);
        const data = new Uint8Array(buffer);
        const pdf = await pdfjsLib.getDocument({ data }).promise;

        let fullText = "";

        for (let i = 1; i <= pdf.numPages; i++) {
            const page = await pdf.getPage(i);
            const textContent = await page.getTextContent();
            const pageText = textContent.items.map(item => item.str).join(" ");
            fullText += `\n[หน้า ${i}]\n${pageText}\n`;
        }

        const prompt = `
สรุปเนื้อหา PDF ต่อไปนี้ให้กระชับ เข้าใจง่าย เป็นภาษาไทย:

${fullText}
`;

        const summary = await summarizeWithOllama(prompt);
        fs.unlinkSync(req.file.path);
        return res.json({ summary });
    } catch (error) {
        console.error("❌ Error:", error);
        return res.status(500).json({ error: "เกิดข้อผิดพลาดระหว่างสรุปทั้งเล่ม" });
    }
});

// 🔹 สรุปแยกหน้า
app.post("/summarize-by-page", upload.single("pdf"), async (req, res) => {
    if (!req.file) return res.status(400).json({ error: "กรุณาอัปโหลดไฟล์ PDF" });

    try {
        const buffer = fs.readFileSync(req.file.path);
        const data = new Uint8Array(buffer);
        const pdf = await pdfjsLib.getDocument({ data }).promise;

        let summaries = [];

        for (let i = 1; i <= pdf.numPages; i++) {
            const page = await pdf.getPage(i);
            const textContent = await page.getTextContent();
            const pageText = textContent.items.map(item => item.str).join(" ").trim();

            if (pageText.length === 0) continue;

            const prompt = `
สรุปเนื้อหาของหน้า ${i} ต่อไปนี้ให้กระชับ เข้าใจง่าย เป็นภาษาไทย:

${pageText}
`;

            const summary = await summarizeWithOllama(prompt);
            summaries.push({ page: i, summary });
        }

        fs.unlinkSync(req.file.path);
        return res.json({ totalPages: summaries.length, summaries });
    } catch (error) {
        console.error("❌ Error:", error);
        return res.status(500).json({ error: "เกิดข้อผิดพลาดระหว่างสรุปแต่ละหน้า" });
    }
});

app.listen(port, () => {
    console.log(`✅ PDF Summary API พร้อมที่ http://localhost:${port}`);
});


💡 อย่าลืมเปิด Ollama ด้วยคำสั่ง ollama run llama3 ก่อนใช้ API นี้

ขั้นตอนที่ 3: ทดสอบ API ด้วย Postman

  1. เปิด Postman
  2. ตั้งค่า Method เป็น POST
  3. URL: http://localhost:3000/summarize
  4. ไปที่แท็บ Body → เลือก form-data
  5. เพิ่ม field:
    • Key: pdf (เลือก type เป็น File)
    • Value: [เลือกไฟล์ PDF ของคุณ]
  6. กดปุ่ม Send

✅ ถ้าทุกอย่างถูกต้อง จะได้ JSON สรุปเนื้อหา PDF กลับมาแบบนี้:

{
  "summary": "นี่คือเนื้อหาสรุปจากไฟล์ PDF ที่คุณอัปโหลด..."
}

ข้อเสนอแนะเพิ่มเติม

  • หาก PDF ยาวเกินไป → ควรแบ่งเป็นหน้าแล้วสรุปทีละช่วง
  • สามารถปรับ Prompt ได้ตามบริบท เช่น: สรุปแบบวิชาการ, สไตล์พรีเซนต์
  • อยากได้ Web GUI, แปลง PDF เป็นไฟล์ใหม่ พร้อมสรุป? → สามารถต่อยอดได้

📥 Postman Collection

คุณสามารถ Import JSON ด้านล่างนี้เข้า Postman ได้โดย:

  1. เปิด Postman แล้วกด Import
  2. เลือกแท็บ Raw Text
  3. วางโค้ด JSON ด้านล่าง แล้วคลิก Continue
{
  "info": {
    "name": "Ollama PDF Summary",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    "_postman_id": "c42fd0ba-2621-49d5-bdd5-ollama-api-summary"
  },
  "item": [
    {
      "name": "สรุป PDF ด้วย Ollama",
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "formdata",
          "formdata": [
            {
              "key": "pdf",
              "type": "file",
              "src": ""
            }
          ]
        },
        "url": {
          "raw": "http://localhost:3000/summarize",
          "protocol": "http",
          "host": ["localhost"],
          "port": "3000",
          "path": ["summarize"]
        },
        "description": "อัปโหลด PDF แล้วให้ Node.js ส่งไปที่ Ollama (llama3) เพื่อสรุปเนื้อหาภาษาไทย"
      },
      "response": []
    }
  ]
}
📌 หลัง Import แล้ว:
  • เปิด request → แท็บ Body
  • เลือก form-data
  • กำหนด pdf เป็นประเภท File แล้วแนบ PDF ของคุณ
  • กด Send เพื่อรับสรุปจาก AI

Loading