-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlocal_input_source.rb
More file actions
216 lines (192 loc) · 8.08 KB
/
local_input_source.rb
File metadata and controls
216 lines (192 loc) · 8.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# frozen_string_literal: true
require 'stringio'
require 'marcel'
require 'fileutils'
require_relative '../../dependency'
require_relative '../../pdf' if Mindee::Dependency.heavy_available?
require_relative '../../image' if Mindee::Dependency.heavy_available?
module Mindee
module Input
# Document source handling.
module Source
# Mime types accepted by the server.
ALLOWED_MIME_TYPES = [
'application/pdf',
'image/heic',
'image/png',
'image/jpeg',
'image/tiff',
'image/webp',
].freeze
# Base class for loading documents.
class LocalInputSource
# @return [String]
attr_reader :filename
# @return [String]
attr_reader :file_mimetype
# @return [StringIO | File]
attr_reader :io_stream
# @param io_stream [StringIO, File]
# @param filename [String]
# @param repair_pdf [bool]
def initialize(io_stream, filename, repair_pdf: false)
@io_stream = io_stream
@filename = filename
@file_mimetype = if repair_pdf
Marcel::MimeType.for @io_stream
else
Marcel::MimeType.for @io_stream, name: @filename
end
if ALLOWED_MIME_TYPES.include? @file_mimetype
logger.debug("Loaded new input #{@filename} from #{self.class}")
return
end
if filename.end_with?('.pdf') && repair_pdf
fix_pdf!
logger.debug("Loaded new input #{@filename} from #{self.class}")
return if ALLOWED_MIME_TYPES.include? @file_mimetype
end
raise Error::MindeeMimeTypeError, @file_mimetype.to_s
end
# @deprecated See {#fix_pdf!} or {#self.fix_pdf} instead.
def rescue_broken_pdf(_)
fix_pdf!
end
# Shorthand for PDF mimetype validation.
def pdf?
@file_mimetype.to_s == 'application/pdf'
end
# Attempts to fix the PDF data in the file.
# @param maximum_offset [Integer] Maximum offset to look for the PDF header.
# @return [void]
# @raise [Mindee::Error::MindeePDFError]
def fix_pdf!(maximum_offset: 500)
@io_stream = LocalInputSource.fix_pdf(@io_stream, maximum_offset: maximum_offset)
@io_stream.rewind
@file_mimetype = Marcel::MimeType.for @io_stream
end
# Attempt to fix the PDF data in the given stream.
# @param stream [StringIO] The stream to fix.
# @param maximum_offset [Integer] Maximum offset to look for the PDF header.
# @return [StringIO] The fixed stream.
# @raise [Mindee::Error::MindeePDFError]
def self.fix_pdf(stream, maximum_offset: 500)
out_stream = StringIO.new
stream.gets('%PDF-')
raise Error::MindeePDFError if stream.eof? || stream.pos > maximum_offset
stream.pos = stream.pos - 5
out_stream << stream.read
end
# Cuts a PDF file according to provided options.
# @param options [PageOptions, nil] Page cutting/merge options:
#
# * `:page_indexes` Zero-based list of page indexes.
# * `:operation` Operation to apply on the document, given the `page_indexes specified:
# * `:KEEP_ONLY` - keep only the specified pages, and remove all others.
# * `:REMOVE` - remove the specified pages, and keep all others.
# * `:on_min_pages` Apply the operation only if document has at least this many pages.
def apply_page_options(options)
@io_stream.seek(0)
@io_stream = PDF::PDFProcessor.parse(@io_stream, options)
end
# @deprecated Use {#apply_page_options} instead.
# @see #apply_page_options
def process_pdf(options)
apply_page_options(options)
end
# Reads a document.
# @param close [bool]
# @return [Array<>]
def read_contents(close: true)
logger.debug("Reading data from: #{@filename}")
@io_stream.seek(0)
# Avoids needlessly re-packing some files
data = @io_stream.read
@io_stream.rewind
@io_stream.close if close
[data, { filename: Mindee::Input::Source.convert_to_unicode_escape(@filename) }]
end
# Write the file to a given path. Uses the initial file name by default.
# @param path [String] Path to write the file to.
def write_to_file(path)
t_path = if File.directory?(path || '') || path.to_s.end_with?('/')
File.join(path || '', @filename)
else
path
end
full_path = File.expand_path(t_path || '')
FileUtils.mkdir_p(File.dirname(full_path))
@io_stream.rewind
File.binwrite(full_path, @io_stream.read || '')
logger.debug("Wrote file successfully to #{full_path}")
@io_stream.rewind
end
# Returns the page count for a document.
# Defaults to one for images.
# @return [Integer]
def page_count
unless Mindee::Dependency.heavy_available?
raise NotImplementedError, Mindee::Dependency::MINDEE_LITE_LOAD_ERROR
end
return 1 unless pdf?
@io_stream.seek(0)
pdf_processor = Mindee::PDF::PDFProcessor.open_pdf(@io_stream)
pdf_processor.pages.size
end
# Compresses the file, according to the provided info.
# @param [Integer] quality Quality of the output file.
# @param [Integer, nil] max_width Maximum width (Ignored for PDFs).
# @param [Integer, nil] max_height Maximum height (Ignored for PDFs).
# @param [bool] force_source_text Whether to force the operation on PDFs with source text.
# This will attempt to re-render PDF text over the rasterized original. If disabled, ignored the operation.
# WARNING: this operation is strongly discouraged.
# @param [bool] disable_source_text If the PDF has source text, whether to re-apply it to the original or
# not. Needs force_source_text to work.
def compress!(quality: 85, max_width: nil, max_height: nil, force_source_text: false, disable_source_text: true)
unless Mindee::Dependency.heavy_available?
raise NotImplementedError, Mindee::Dependency::MINDEE_LITE_LOAD_ERROR
end
buffer = if pdf?
Mindee::PDF::PDFCompressor.compress_pdf(
@io_stream,
quality: quality,
force_source_text_compression: force_source_text,
disable_source_text: disable_source_text
)
else
Mindee::Image::ImageCompressor.compress_image(
@io_stream,
quality: quality,
max_width: max_width,
max_height: max_height
)
end
@io_stream = buffer
@io_stream.rewind
end
# Checks whether the file has source text if it is a pdf. `false` otherwise
# @return [bool] `true` if the file is a PDF and has source text.
def source_text?
unless Mindee::Dependency.heavy_available?
raise NotImplementedError, Mindee::Dependency::MINDEE_LITE_LOAD_ERROR
end
Mindee::PDF::PDFTools.source_text?(@io_stream)
end
end
# Replaces non-ASCII characters by their UNICODE escape sequence.
# Keeps other characters as is.
# @return A clean String.
def self.convert_to_unicode_escape(string)
unicode_escape_string = ''.dup
string.each_char do |char|
unicode_escape_string << if char.bytesize > 1
"\\u#{format('%04x', char.unpack1('U'))}"
else
char
end
end
unicode_escape_string
end
end
end
end