|
| 1 | +package parser |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/ledongthuc/pdf" |
| 8 | +) |
| 9 | + |
| 10 | +// ParsePDF parses a PDF file into a Document structure |
| 11 | +func ParsePDF(filepath string) (*Document, error) { |
| 12 | + f, r, err := pdf.Open(filepath) |
| 13 | + if err != nil { |
| 14 | + return nil, fmt.Errorf("failed to open PDF: %w", err) |
| 15 | + } |
| 16 | + defer f.Close() |
| 17 | + |
| 18 | + doc := &Document{} |
| 19 | + |
| 20 | + // Try to extract outline (bookmarks) first |
| 21 | + outline := r.Outline() |
| 22 | + if hasOutline(outline) { |
| 23 | + doc.Sections = parseOutline(outline) |
| 24 | + // Add page content as token estimates |
| 25 | + addPageTokens(r, doc) |
| 26 | + } else { |
| 27 | + // Fall back to page-based structure |
| 28 | + doc.Sections = parseByPage(r) |
| 29 | + } |
| 30 | + |
| 31 | + // Calculate total tokens |
| 32 | + for _, s := range doc.GetAllSections() { |
| 33 | + doc.TotalTokens += s.Tokens |
| 34 | + } |
| 35 | + |
| 36 | + return doc, nil |
| 37 | +} |
| 38 | + |
| 39 | +// hasOutline checks if the PDF has a meaningful outline structure |
| 40 | +func hasOutline(outline pdf.Outline) bool { |
| 41 | + return len(outline.Child) > 0 |
| 42 | +} |
| 43 | + |
| 44 | +// parseOutline extracts document structure from PDF bookmarks |
| 45 | +func parseOutline(outline pdf.Outline) []*Section { |
| 46 | + var sections []*Section |
| 47 | + |
| 48 | + for _, item := range outline.Child { |
| 49 | + section := outlineItemToSection(item, 1) |
| 50 | + sections = append(sections, section) |
| 51 | + } |
| 52 | + |
| 53 | + return sections |
| 54 | +} |
| 55 | + |
| 56 | +// outlineItemToSection converts a PDF outline item to a Section |
| 57 | +func outlineItemToSection(item pdf.Outline, level int) *Section { |
| 58 | + section := &Section{ |
| 59 | + Level: level, |
| 60 | + Title: strings.TrimSpace(item.Title), |
| 61 | + } |
| 62 | + |
| 63 | + // Process children recursively |
| 64 | + for _, child := range item.Child { |
| 65 | + childSection := outlineItemToSection(child, level+1) |
| 66 | + childSection.Parent = section |
| 67 | + section.Children = append(section.Children, childSection) |
| 68 | + } |
| 69 | + |
| 70 | + return section |
| 71 | +} |
| 72 | + |
| 73 | +// addPageTokens adds token estimates to outlined documents by reading all pages |
| 74 | +func addPageTokens(r *pdf.Reader, doc *Document) { |
| 75 | + numPages := r.NumPage() |
| 76 | + totalText := strings.Builder{} |
| 77 | + |
| 78 | + for i := 1; i <= numPages; i++ { |
| 79 | + page := r.Page(i) |
| 80 | + if page.V.IsNull() { |
| 81 | + continue |
| 82 | + } |
| 83 | + text, err := page.GetPlainText(nil) |
| 84 | + if err == nil { |
| 85 | + totalText.WriteString(text) |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + // Distribute tokens across top-level sections proportionally |
| 90 | + allText := totalText.String() |
| 91 | + totalTokens := estimateTokens(allText) |
| 92 | + |
| 93 | + if len(doc.Sections) > 0 && totalTokens > 0 { |
| 94 | + tokensPerSection := totalTokens / len(doc.Sections) |
| 95 | + for _, section := range doc.Sections { |
| 96 | + distributeTokens(section, tokensPerSection) |
| 97 | + } |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +// distributeTokens assigns token estimates to a section and its children |
| 102 | +func distributeTokens(section *Section, tokens int) { |
| 103 | + if len(section.Children) == 0 { |
| 104 | + section.Tokens = tokens |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + // Give parent a portion, distribute rest to children |
| 109 | + childCount := len(section.Children) |
| 110 | + perChild := tokens / (childCount + 1) |
| 111 | + section.Tokens = perChild |
| 112 | + |
| 113 | + for _, child := range section.Children { |
| 114 | + distributeTokens(child, perChild) |
| 115 | + } |
| 116 | + |
| 117 | + // Recalculate cumulative tokens |
| 118 | + calculateCumulativeTokens(section) |
| 119 | +} |
| 120 | + |
| 121 | +// parseByPage creates a page-based structure for PDFs without outlines |
| 122 | +func parseByPage(r *pdf.Reader) []*Section { |
| 123 | + numPages := r.NumPage() |
| 124 | + if numPages == 0 { |
| 125 | + return nil |
| 126 | + } |
| 127 | + |
| 128 | + var sections []*Section |
| 129 | + var hasContent bool |
| 130 | + |
| 131 | + for i := 1; i <= numPages; i++ { |
| 132 | + page := r.Page(i) |
| 133 | + if page.V.IsNull() { |
| 134 | + continue |
| 135 | + } |
| 136 | + |
| 137 | + text, err := page.GetPlainText(nil) |
| 138 | + if err != nil { |
| 139 | + continue |
| 140 | + } |
| 141 | + |
| 142 | + text = strings.TrimSpace(text) |
| 143 | + if text == "" { |
| 144 | + continue |
| 145 | + } |
| 146 | + |
| 147 | + hasContent = true |
| 148 | + section := &Section{ |
| 149 | + Level: 1, |
| 150 | + Title: fmt.Sprintf("Page %d", i), |
| 151 | + Content: text, |
| 152 | + Tokens: estimateTokens(text), |
| 153 | + LineStart: i, // Page number |
| 154 | + LineEnd: i, |
| 155 | + } |
| 156 | + sections = append(sections, section) |
| 157 | + } |
| 158 | + |
| 159 | + // If no text content was extracted, return a warning section |
| 160 | + if !hasContent && numPages > 0 { |
| 161 | + return []*Section{{ |
| 162 | + Level: 1, |
| 163 | + Title: fmt.Sprintf("(%d pages - no extractable text)", numPages), |
| 164 | + Content: "", |
| 165 | + Tokens: 0, |
| 166 | + LineStart: 1, |
| 167 | + LineEnd: numPages, |
| 168 | + }} |
| 169 | + } |
| 170 | + |
| 171 | + return sections |
| 172 | +} |
0 commit comments