Class: SwarmSDK::Tools::DocumentConverters::DocxConverter
- Inherits:
-
BaseConverter
- Object
- BaseConverter
- SwarmSDK::Tools::DocumentConverters::DocxConverter
show all
- Defined in:
- lib/swarm_sdk/tools/document_converters/docx_converter.rb
Overview
Converts DOCX 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/docx_converter.rb', line 17
def extensions
[".docx", ".doc"]
end
|
13
14
15
|
# File 'lib/swarm_sdk/tools/document_converters/docx_converter.rb', line 13
def format_name
"DOCX"
end
|
.gem_name ⇒ Object
9
10
11
|
# File 'lib/swarm_sdk/tools/document_converters/docx_converter.rb', line 9
def gem_name
"docx"
end
|
Instance Method Details
#convert(file_path) ⇒ String, RubyLLM::Content
Convert a DOCX 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
# File 'lib/swarm_sdk/tools/document_converters/docx_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
if File.extname(file_path).downcase == ".doc"
return error("DOC format is not supported. Please convert to DOCX first.")
end
begin
require "docx"
require "tmpdir"
doc = Docx::Document.open(file_path)
image_paths = ::.(doc, file_path)
output = []
output << "Document: #{File.basename(file_path)}"
output << "=" * 60
output << ""
paragraphs = doc.paragraphs.map(&:text).reject(&:empty?)
if paragraphs.empty? && doc.tables.empty?
output << "(Document is empty - no paragraphs or tables)"
else
output += paragraphs
if doc.tables.any?
output << ""
output << "Tables:"
output << "-" * 60
doc.tables.each_with_index do |table, idx|
output << ""
output << "Table #{idx + 1} (#{table.row_count} rows × #{table.column_count} columns):"
table.rows.each do |row|
output << row.cells.map(&:text).join(" | ")
end
end
end
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 Zip::Error => e
error("Invalid or corrupted DOCX file: #{e.message}")
rescue Errno::ENOENT => e
error("File not found or missing document.xml: #{e.message}")
rescue StandardError => e
error("Failed to parse DOCX file: #{e.message}")
end
end
|