Class: RTesseract

Inherits:
Object
  • Object
show all
Defined in:
lib/rtesseract.rb,
lib/rtesseract/box.rb,
lib/rtesseract/mixed.rb,
lib/rtesseract/errors.rb,
lib/rtesseract/box_char.rb

Overview

Ruby wrapper for Tesseract OCR

Direct Known Subclasses

Box

Defined Under Namespace

Classes: Box, BoxChar, ConversionError, ErrorWithMemory, ImageNotSelectedError, Mixed, TempFilesNotRemovedError

Constant Summary collapse

OPTIONS =
%w(command lang psm processor debug clear_console_output options)
LANGUAGES =

Aliases to languages names

{
  'eng' => %w(en en-us english),
  'ita' => %w(it),
  'por' => %w(pt pt-br portuguese),
  'spa' => %w(sp)
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(src = '', options = {}) ⇒ RTesseract

Returns a new instance of RTesseract.



36
37
38
39
40
41
42
# File 'lib/rtesseract.rb', line 36

def initialize(src = '', options = {})
  command_line_options(options)
  @value, @x, @y, @w, @h = [nil]
  @processor = RTesseract.choose_processor!(@processor)
  @source = @processor.image?(src) ? src : Pathname.new(src)
  initialize_hook
end

Instance Attribute Details

#image_objectObject

Returns the value of attribute image_object.



19
20
21
# File 'lib/rtesseract.rb', line 19

def image_object
  @image_object
end

#langObject

Select the language

Languages

  • eng - English

  • deu - German

  • deu-f - German fraktur

  • fra - French

  • ita - Italian

  • nld - Dutch

  • por - Portuguese

  • spa - Spanish

  • vie - Vietnamese

Note: Make sure you have installed the language to tesseract



121
122
123
124
125
126
127
128
129
130
# File 'lib/rtesseract.rb', line 121

def lang
  language = "#{@lang}".strip.downcase
  LANGUAGES.each do |value, names|
    return " -l #{value} " if names.include? language
  end
  return " -l #{language} " if language.size > 0
  ''
rescue
  ''
end

#optionsObject

Returns the value of attribute options.



20
21
22
# File 'lib/rtesseract.rb', line 20

def options
  @options
end

#options_cmdObject

Returns the value of attribute options_cmd.



21
22
23
# File 'lib/rtesseract.rb', line 21

def options_cmd
  @options_cmd
end

#processorObject (readonly)

Returns the value of attribute processor.



24
25
26
# File 'lib/rtesseract.rb', line 24

def processor
  @processor
end

#psmObject

Page Segment Mode



133
134
135
136
137
# File 'lib/rtesseract.rb', line 133

def psm
  (@psm.nil? ? '' : " -psm #{@psm} ")
rescue
  ''
end

#sourceObject

Returns the value of attribute source.



25
26
27
# File 'lib/rtesseract.rb', line 25

def source
  @source
end

Class Method Details

.choose_processor!(processor) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/rtesseract.rb', line 231

def self.choose_processor!(processor)
  processor =
  if MiniMagickProcessor.a_name?(processor.to_s)
    MiniMagickProcessor
  elsif QuickMagickProcessor.a_name?(processor.to_s)
    QuickMagickProcessor
  elsif NoneProcessor.a_name?(processor.to_s)
    NoneProcessor
  else
    RMagickProcessor
  end
  processor.setup
  processor
end

.read(src = nil, options = {}) {|image| ... } ⇒ Object

Yields:



66
67
68
69
70
71
72
73
# File 'lib/rtesseract.rb', line 66

def self.read(src = nil, options = {})
  fail RTesseract::ImageNotSelectedError if src.nil?
  processor = RTesseract.choose_processor!(options.option(:processor, nil))
  image = processor.read_with_processor(src.to_s)
  yield(image)
  object = RTesseract.new('', options).from_blob(image.to_blob)
  object
end

Instance Method Details

#after_convert_hookObject



187
188
# File 'lib/rtesseract.rb', line 187

def after_convert_hook
end

#clear_console_outputObject

TODO: Clear console for MacOS or Windows



158
159
160
161
# File 'lib/rtesseract.rb', line 158

def clear_console_output
  return '' unless @clear_console_output
  return '2>/dev/null' if File.exist?('/dev/null') # Linux console clear
end

#command_line_options(options) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rtesseract.rb', line 47

def command_line_options(options)
  @options = options
  @command = @options.option(:command, default_command)
  @lang = @options.option(:lang, '')
  @psm = @options.option(:psm, nil)
  @processor = @options.option(:processor, 'rmagick')
  @debug = @options.option(:debug, false)
  @options_cmd = @options.option(:options, [])
  @options_cmd = [@options_cmd] unless @options_cmd.is_a?(Array)
  # Disable clear console if debug mode
  @clear_console_output = @debug ? false : options.option(:clear_console_output, true)
end

#configObject



142
143
144
145
146
# File 'lib/rtesseract.rb', line 142

def config
  @options ||= {}
  config_hook
  @options.map { |k, v| "#{k} #{v}" }.join("\n")
end

#config_fileObject



148
149
150
151
152
153
154
155
# File 'lib/rtesseract.rb', line 148

def config_file
  config_hook
  return '' if @options == {}
  conf = Tempfile.new('config')
  conf.write(config)
  conf.flush
  conf.path
end

#config_hookObject



139
140
# File 'lib/rtesseract.rb', line 139

def config_hook
end

#convertObject

Convert image to string



191
192
193
194
195
196
197
198
# File 'lib/rtesseract.rb', line 191

def convert
  convert_command
  after_convert_hook
  convert_text
  remove_file([@image, text_file_with_ext])
rescue => error
  raise RTesseract::ConversionError.new(error), error, caller
end

#convert_commandObject



179
180
181
# File 'lib/rtesseract.rb', line 179

def convert_command
  `#{@command} "#{image}" "#{text_file}" #{lang} #{psm} #{config_file} #{clear_console_output} #{@options_cmd.join(' ')}`
end

#convert_textObject



183
184
185
# File 'lib/rtesseract.rb', line 183

def convert_text
  @value = File.read(text_file_with_ext).to_s
end

#crop!(x, y, width, height) ⇒ Object

Crop image to convert



88
89
90
91
92
# File 'lib/rtesseract.rb', line 88

def crop!(x, y, width, height)
  @value = nil
  @x, @y, @w, @h = x.to_i, y.to_i, width.to_i, height.to_i
  self
end

#default_commandObject



60
61
62
63
64
# File 'lib/rtesseract.rb', line 60

def default_command
  TesseractBin::Executables[:tesseract] || 'tesseract'
rescue
  'tesseract'
end

#file_extObject



167
168
169
# File 'lib/rtesseract.rb', line 167

def file_ext
  '.txt'
end

#from_blob(blob, ext = '') ⇒ Object

Read image from memory blob



201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/rtesseract.rb', line 201

def from_blob(blob, ext = '')
  blob_file = Tempfile.new(['blob', ext], encoding: 'ascii-8bit')
  blob_file.binmode.write(blob)
  blob_file.rewind
  blob_file.flush
  self.source = blob_file.path
  convert
  remove_file([blob_file])
  self
rescue => error
  raise RTesseract::ConversionError.new(error), error, caller
end

#imageObject



163
164
165
# File 'lib/rtesseract.rb', line 163

def image
  (@image = @processor.image_to_tif(@source, @x, @y, @w, @h)).path
end

#initialize_hookObject



44
45
# File 'lib/rtesseract.rb', line 44

def initialize_hook
end

#readObject



75
76
77
78
79
80
# File 'lib/rtesseract.rb', line 75

def read
  image = @processor.read_with_processor(@source.to_s)
  new_image = yield(image)
  from_blob(new_image.to_blob, File.extname(@source.to_s))
  self
end

#remove_file(files = []) ⇒ Object

Remove files



95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/rtesseract.rb', line 95

def remove_file(files = [])
  files.each do |file|
    if file.is_a?(Tempfile)
      file.close
      file.unlink
    else
      File.unlink(file)
    end
  end
  true
rescue => error
  raise RTesseract::TempFilesNotRemovedError.new(error: error, files: files)
end

#text_fileObject



171
172
173
# File 'lib/rtesseract.rb', line 171

def text_file
  @text_file = Pathname.new(Dir.tmpdir).join("#{Time.now.to_f}#{rand(1500)}").to_s
end

#text_file_with_ext(ext = nil) ⇒ Object



175
176
177
# File 'lib/rtesseract.rb', line 175

def text_file_with_ext(ext = nil)
  [@text_file, ext || file_ext].join('')
end

#to_sObject

Output value



215
216
217
218
219
220
221
222
223
224
# File 'lib/rtesseract.rb', line 215

def to_s
  return @value if @value != nil

  if @processor.image?(@source) || @source.file?
    convert
    @value
  else
    fail RTesseract::ImageNotSelectedError.new(@source)
  end
end

#to_s_without_spacesObject

Remove spaces and break-lines



227
228
229
# File 'lib/rtesseract.rb', line 227

def to_s_without_spaces
  to_s.gsub(' ', '').gsub("\n", '').gsub("\r", '')
end