Class: BotFramework::Dialogs::LuisRecognizer

Inherits:
Object
  • Object
show all
Defined in:
lib/bot_framework/dialogs/luis_recognizer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(models) ⇒ LuisRecognizer

Returns a new instance of LuisRecognizer.



4
5
6
# File 'lib/bot_framework/dialogs/luis_recognizer.rb', line 4

def initialize(models)
  @models = { '*' => models }
end

Class Method Details

.recognize(utterance, model_uri) {|nil, , | ... } ⇒ Object

Yields:

  • (nil, , )


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
# File 'lib/bot_framework/dialogs/luis_recognizer.rb', line 44

def self.recognize(utterance, model_uri)
  uri = model_uri.strip
  uri += '&q=' unless uri.end_with? '&q='
  uri += URI.encode_www_form_component(utterance || '')
  result = JSON.parse HTTParty.get(uri).body
  # Symbolize keys
  result = result.each_with_object({}) { |(k, v), temp| temp[k.to_sym] = v; temp }
  result[:intents] ||= []
  result[:entities] ||= []
  if result[:topScoringIntent] && result[:intents].empty?
    result[:intents] << result[:topScoringIntent]
  end

  if result[:intents].length == 1 && (result[:intents].first[:score].is_a? Numeric)
    result[:intents].first[:score] = 1.0
  end
  # Symbolize keys
  result[:intents].map! do |intent|
    intent.each_with_object({}) { |(k, v), temp| temp[k.to_sym] = v; temp }
  end

  result[:entities].map! do |entity|
    entity.each_with_object({}) { |(k, v), temp| temp[k.to_sym] = v; temp }
  end
  yield nil, result[:intents], result[:entities]
end

Instance Method Details

#recognize(context) ⇒ Object



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
# File 'lib/bot_framework/dialogs/luis_recognizer.rb', line 8

def recognize(context)
  result = { score: 0.0, intent: nil }
  if context && context[:message] && context[:message][:text]
    utterance = context[:message][:text]
    locale = context[:locale] || '*'
    model = @models[locale] || @models['*']
    if model
      LuisRecognizer.recognize(utterance, model) do |error, intents, entities|
        if error
          yield 'Error', nil
        else
          result[:intents] = intents
          result[:entities] = entities

          top = intents.max { |intent| intent[score] }
          if top
            result[:score] = top[:score]
            result[:intent] = top[:intent]
            case top[:intent].downcase
            when 'builtin.intent.none'
            when 'none'
              result[:score] = 0.1
            end
          end
          yield nil, result
        end
        yield nil, result
      end
    else
      yield StandardError.new("Luis model not found for locale #{locale}"), nil
    end
  else
    yield nil, result
  end
end