Class: FFI::Fasttext::Predictor

Inherits:
Object
  • Object
show all
Defined in:
lib/ffi/fasttext.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_name) ⇒ Predictor

Returns a new instance of Predictor.



81
82
83
84
# File 'lib/ffi/fasttext.rb', line 81

def initialize(model_name)
  @ptr = ::File.exist?(model_name) ? ::FFI::Fasttext.create(model_name) : ::FFI::Fasttext.create_from_url(model_name)
  raise "Error loading model" if @ptr.null?
end

Instance Method Details

#destroy!Object



86
87
88
89
# File 'lib/ffi/fasttext.rb', line 86

def destroy!
  ::FFI::Fasttext.destroy(@ptr) unless @ptr.nil?
  @ptr = nil
end

#predict(string, number_of_predictions = 1) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/ffi/fasttext.rb', line 91

def predict(string, number_of_predictions = 1)
  response_string, pointer = ::FFI::Fasttext.predict(@ptr, string, number_of_predictions)
  return [] unless response_string.size > 0

  response_array = []
  split_responses = response_string.split(" ")
  split_responses.each_slice(2) do |pair|
    next unless pair.first && pair.last

    response_array << [pair.first, pair.last.to_f]
  end

  response_array
ensure
  ::FFI::Fasttext.predict_string_free(pointer) unless pointer.nil?
end