UNPKG

n8n-nodes-extract-pdf

Version:

n8n node to extract text, images and tables from PDF with multilingual support, language detection and comprehensive test suite

188 lines (184 loc) 7.75 kB
"use strict"; /** * Module trích xuất bảng từ PDF * @author AI Assistant * @version 1.0.0 */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractTablesWithCamelot = exports.saveTableAsCsv = exports.extractTablesFromPdf = void 0; const fs = __importStar(require("fs")); const path = __importStar(require("path")); const os = __importStar(require("os")); const util_1 = require("util"); const exec = (0, util_1.promisify)(require('child_process').exec); /** * Trích xuất bảng từ PDF * @param pdfPath Đường dẫn đến file PDF * @param options Các tùy chọn trích xuất bảng * @returns Mảng kết quả trích xuất bảng cho mỗi trang */ async function extractTablesFromPdf(pdfPath, options = {}) { try { const startTime = Date.now(); const { pageRange, outputFormat = 'json', outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pdf_tables_')) } = options; // Giả lập kết quả trích xuất bảng // Trong dự án thực, sẽ sử dụng thư viện như tabula-py, pdf-table-extractor, hoặc gọi API // Kết quả trả về const results = []; // Số trang (giả lập) const pageCount = 5; // Xử lý từng trang for (let page = 1; page <= pageCount; page++) { // Bỏ qua nếu không thuộc pageRange if (pageRange && !pageRange.includes(page)) { continue; } // Giả lập bảng const tableCount = Math.floor(Math.random() * 3) + 1; // 1-3 bảng mỗi trang const tables = []; for (let t = 0; t < tableCount; t++) { const rowCount = Math.floor(Math.random() * 10) + 2; // 2-11 hàng const columnCount = Math.floor(Math.random() * 5) + 2; // 2-6 cột // Tạo dữ liệu bảng const rows = []; // Tạo tiêu đề const header = Array.from({ length: columnCount }, (_, i) => `Column ${i + 1}`); rows.push(header); // Tạo dữ liệu for (let r = 1; r < rowCount; r++) { const row = Array.from({ length: columnCount }, (_, i) => `Data ${r},${i + 1}`); rows.push(row); } // Thêm bảng tables.push({ rows, rowCount, columnCount, confidence: 0.75 + Math.random() * 0.2, bbox: { x: Math.random() * 100, y: Math.random() * 100, width: 400 + Math.random() * 200, height: rowCount * 30 + Math.random() * 50 } }); } // Thêm kết quả cho trang results.push({ page, tables, }); } // Thêm thông tin hiệu suất const endTime = Date.now(); results.forEach(result => { result.performance = { startTime, endTime, processingTime: (endTime - startTime) / 1000 }; }); return results; } catch (error) { if (error instanceof Error) { throw new Error(`Failed to extract tables from PDF: ${error.message}`); } throw new Error('An unknown error occurred during table extraction'); } } exports.extractTablesFromPdf = extractTablesFromPdf; /** * Lưu bảng dưới dạng CSV * @param table Bảng cần lưu * @param outputPath Đường dẫn đến file đầu ra */ async function saveTableAsCsv(table, outputPath) { try { // Chuyển đổi bảng thành chuỗi CSV const csvContent = table.rows .map(row => row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(',')) .join('\n'); // Lưu file await fs.promises.writeFile(outputPath, csvContent, 'utf8'); } catch (error) { if (error instanceof Error) { throw new Error(`Failed to save table as CSV: ${error.message}`); } throw new Error('An unknown error occurred while saving CSV file'); } } exports.saveTableAsCsv = saveTableAsCsv; /** * Trích xuất bảng từ file PDF sử dụng camelot-py (giả lập) * @param pdfPath Đường dẫn đến file PDF * @param pageRange Phạm vi trang cần trích xuất * @returns Kết quả trích xuất bảng */ async function extractTablesWithCamelot(pdfPath, pageRange) { try { // Mô phỏng việc gọi camelot-py từ Node.js // Trong thực tế, cần cài đặt và thiết lập Python + camelot-py const pythonScript = ` import camelot import json import sys pdf_path = "${pdfPath.replace(/\\/g, '\\\\')}" page_string = "${pageRange ? pageRange.join(',') : 'all'}" tables = camelot.read_pdf(pdf_path, pages=page_string, flavor='lattice') result = [] for i, table in enumerate(tables): table_data = { "page": table.page, "rows": table.data, "rowCount": len(table.data), "columnCount": len(table.data[0]) if len(table.data) > 0 else 0, "accuracy": table.accuracy, "whitespace": table.whitespace } result.append(table_data) print(json.dumps(result)) `; // Tạo file Python tạm const tempPythonFile = path.join(os.tmpdir(), `extract_tables_${Date.now()}.py`); await fs.promises.writeFile(tempPythonFile, pythonScript); // Thay vì thực thi file Python, trả về kết quả giả lập // Trong thực tế: const { stdout } = await exec(`python ${tempPythonFile}`); // Xóa file tạm await fs.promises.unlink(tempPythonFile); // Trả về kết quả giả lập return extractTablesFromPdf(pdfPath, { pageRange }); } catch (error) { if (error instanceof Error) { throw new Error(`Failed to extract tables with Camelot: ${error.message}`); } throw new Error('An unknown error occurred during table extraction with Camelot'); } } exports.extractTablesWithCamelot = extractTablesWithCamelot; //# sourceMappingURL=index.js.map