|
| 1 | +package cc.unitmesh.devins.document |
| 2 | + |
| 3 | +import io.github.oshai.kotlinlogging.KotlinLogging |
| 4 | +import org.apache.pdfbox.Loader |
| 5 | +import org.apache.pdfbox.pdmodel.PDDocument |
| 6 | +import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem |
| 7 | +import org.apache.pdfbox.text.PDFTextStripper |
| 8 | +import java.io.File |
| 9 | + |
| 10 | +private val logger = KotlinLogging.logger {} |
| 11 | + |
| 12 | +/** |
| 13 | + * Apache PDFBox-based document parser for JVM platform |
| 14 | + */ |
| 15 | +class PdfDocumentParser : DocumentParserService { |
| 16 | + private var currentContent: String? = null |
| 17 | + private var currentChunks: List<DocumentChunk> = emptyList() |
| 18 | + |
| 19 | + override fun getDocumentContent(): String? = currentContent |
| 20 | + |
| 21 | + override suspend fun parse(file: DocumentFile, content: String): DocumentTreeNode { |
| 22 | + logger.info { "=== Starting PDFBox Parse ===" } |
| 23 | + logger.info { "File: ${file.path}" } |
| 24 | + |
| 25 | + val result = try { |
| 26 | + val pdfFile = File(file.path) |
| 27 | + if (!pdfFile.exists()) { |
| 28 | + throw IllegalArgumentException("File not found: ${file.path}") |
| 29 | + } |
| 30 | + |
| 31 | + Loader.loadPDF(pdfFile).use { document -> |
| 32 | + // Extract full text |
| 33 | + val stripper = PDFTextStripper() |
| 34 | + val fullText = stripper.getText(document) |
| 35 | + currentContent = fullText.trim() |
| 36 | + |
| 37 | + logger.info { "Extracted ${fullText.length} characters" } |
| 38 | + |
| 39 | + // Build chunks by page |
| 40 | + currentChunks = buildPageChunks(document, file.path) |
| 41 | + logger.info { "Created ${currentChunks.size} document chunks" } |
| 42 | + |
| 43 | + // Extract TOC |
| 44 | + val toc = extractTOC(document) |
| 45 | + logger.info { "Extracted ${toc.size} TOC items" } |
| 46 | + |
| 47 | + logger.info { "=== Parse Complete ===" } |
| 48 | + |
| 49 | + file.copy( |
| 50 | + toc = toc, |
| 51 | + metadata = file.metadata.copy( |
| 52 | + parseStatus = ParseStatus.PARSED, |
| 53 | + chapterCount = toc.size, |
| 54 | + totalPages = document.numberOfPages, |
| 55 | + mimeType = "application/pdf", |
| 56 | + formatType = DocumentFormatType.PDF |
| 57 | + ) |
| 58 | + ) |
| 59 | + } |
| 60 | + } catch (e: Exception) { |
| 61 | + logger.error { "Failed to parse PDF: ${e.message}" } |
| 62 | + file.copy( |
| 63 | + metadata = file.metadata.copy( |
| 64 | + parseStatus = ParseStatus.PARSE_FAILED |
| 65 | + ) |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + return result |
| 70 | + } |
| 71 | + |
| 72 | + override suspend fun queryHeading(keyword: String): List<DocumentChunk> { |
| 73 | + return currentChunks.filter { |
| 74 | + it.chapterTitle?.contains(keyword, ignoreCase = true) == true || |
| 75 | + it.content.contains(keyword, ignoreCase = true) |
| 76 | + }.sortedByDescending { |
| 77 | + // Relevance scoring: title match > content match |
| 78 | + when { |
| 79 | + it.chapterTitle?.equals(keyword, ignoreCase = true) == true -> 10 |
| 80 | + it.chapterTitle?.contains(keyword, ignoreCase = true) == true -> 5 |
| 81 | + else -> 1 |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + override suspend fun queryChapter(chapterId: String): DocumentChunk? { |
| 87 | + return currentChunks.find { |
| 88 | + it.anchor == chapterId || it.anchor == "#$chapterId" |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + private fun buildPageChunks(document: PDDocument, documentPath: String): List<DocumentChunk> { |
| 93 | + val chunks = mutableListOf<DocumentChunk>() |
| 94 | + val stripper = PDFTextStripper() |
| 95 | + |
| 96 | + for (pageIndex in 0 until document.numberOfPages) { |
| 97 | + stripper.startPage = pageIndex + 1 |
| 98 | + stripper.endPage = pageIndex + 1 |
| 99 | + |
| 100 | + try { |
| 101 | + val pageText = stripper.getText(document).trim() |
| 102 | + if (pageText.isNotEmpty()) { |
| 103 | + chunks.add( |
| 104 | + DocumentChunk( |
| 105 | + documentPath = documentPath, |
| 106 | + chapterTitle = "Page ${pageIndex + 1}", |
| 107 | + content = pageText, |
| 108 | + anchor = "#page-${pageIndex + 1}", |
| 109 | + page = pageIndex + 1, |
| 110 | + position = PositionMetadata( |
| 111 | + documentPath = documentPath, |
| 112 | + formatType = DocumentFormatType.PDF, |
| 113 | + position = DocumentPosition.PageRange(pageIndex + 1, pageIndex + 1) |
| 114 | + ) |
| 115 | + ) |
| 116 | + ) |
| 117 | + } |
| 118 | + } catch (e: Exception) { |
| 119 | + logger.warn { "Failed to extract text from page ${pageIndex + 1}: ${e.message}" } |
| 120 | + } |
| 121 | + } |
| 122 | + return chunks |
| 123 | + } |
| 124 | + |
| 125 | + private fun extractTOC(document: PDDocument): List<TOCItem> { |
| 126 | + val outline = document.documentCatalog.documentOutline ?: return emptyList() |
| 127 | + val toc = mutableListOf<TOCItem>() |
| 128 | + |
| 129 | + var currentItem = outline.firstChild |
| 130 | + while (currentItem != null) { |
| 131 | + processOutlineItem(currentItem, 1, toc) |
| 132 | + currentItem = currentItem.nextSibling |
| 133 | + } |
| 134 | + |
| 135 | + return toc |
| 136 | + } |
| 137 | + |
| 138 | + private fun processOutlineItem(item: PDOutlineItem, level: Int, list: MutableList<TOCItem>) { |
| 139 | + val title = item.title ?: "Untitled" |
| 140 | + val children = mutableListOf<TOCItem>() |
| 141 | + |
| 142 | + var child = item.firstChild |
| 143 | + while (child != null) { |
| 144 | + processOutlineItem(child, level + 1, children) |
| 145 | + child = child.nextSibling |
| 146 | + } |
| 147 | + |
| 148 | + list.add(TOCItem( |
| 149 | + level = level, |
| 150 | + title = title, |
| 151 | + anchor = "#${title.lowercase().replace(Regex("[^a-z0-9]+"), "-")}", |
| 152 | + children = children |
| 153 | + )) |
| 154 | + } |
| 155 | +} |
0 commit comments