Class: SwarmSDK::Tools::DocumentConverters::PdfConverter
- Inherits:
-
BaseConverter
- Object
- BaseConverter
- SwarmSDK::Tools::DocumentConverters::PdfConverter
show all
- Defined in:
- lib/swarm_sdk/tools/document_converters/pdf_converter.rb
Overview
Converts PDF documents to text with image extraction
Class Method Summary
collapse
Instance Method Summary
collapse
available?, gem_available?
Class Method Details
.extensions ⇒ Object
17
18
19
|
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 17
def extensions
[".pdf"]
end
|
13
14
15
|
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 13
def format_name
"PDF"
end
|
.gem_name ⇒ Object
9
10
11
|
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 9
def gem_name
"pdf-reader"
end
|
Instance Method Details
#convert(file_path) ⇒ String, RubyLLM::Content
Convert a PDF document to text/content
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 25
def convert(file_path)
unless self.class.available?
return unsupported_format_reminder(self.class.format_name, self.class.gem_name)
end
begin
require "pdf-reader"
require "tmpdir"
require "fileutils"
reader = PDF::Reader.new(file_path)
output = []
output << "PDF Document: #{File.basename(file_path)}"
output << "=" * 60
output << "Pages: #{reader.page_count}"
output << ""
image_paths = ::.(reader, file_path)
reader.pages.each_with_index do |page, index|
output << "Page #{index + 1}:"
output << "-" * 60
text = page.text.strip
output << (text.empty? ? "(No text content on this page)" : text)
output << ""
end
text_content = output.join("\n")
if image_paths.any?
content = RubyLLM::Content.new(text_content)
image_paths.each do |image_path|
content.add_attachment(image_path)
end
content
else
text_content
end
rescue PDF::Reader::MalformedPDFError => e
error("PDF file is malformed: #{e.message}")
rescue PDF::Reader::UnsupportedFeatureError => e
error("PDF contains unsupported features: #{e.message}")
rescue StandardError => e
error("Failed to parse PDF file: #{e.message}")
end
end
|