Class: Transformers::QuestionAnsweringArgumentHandler

Inherits:
ArgumentHandler show all
Defined in:
lib/transformers/pipelines/question_answering.rb

Instance Method Summary collapse

Instance Method Details

#call(*args, **kwargs) ⇒ Object



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
# File 'lib/transformers/pipelines/question_answering.rb', line 22

def call(*args, **kwargs)
  # Detect where the actual inputs are
  if args.any?
    if args.length == 1
      inputs = args[0]
    elsif args.length == 2 && args.all? { |el| el.is_a?(String) }
      inputs = [{question: args[0], context: args[1]}]
    else
      inputs = args.to_a
    end
  elsif kwargs.include?(:question) && kwargs.include?(:context)
    if kwargs[:question].is_a?(Array) && kwargs[:context].is_a?(String)
      inputs = kwargs[:question].map { |q| {question: q, context: kwargs[:context]} }
    elsif kwargs[:question].is_a?(Array) && kwargs[:context].is_a?(Array)
      if kwargs[:question].length != kwargs[:context].length
        raise ArgumentError, "Questions and contexts don't have the same lengths"
      end

      inputs = kwargs[:question].zip(kwargs[:context]).map { |q, c| {question: q, context: c} }
    elsif kwargs[:question].is_a?(String) && kwargs[:context].is_a?(String)
      inputs = [{question: kwargs[:question], context: kwargs[:context]}]
    else
      raise ArgumentError, "Arguments can't be understood"
    end
  else
    raise ArgumentError, "Unknown arguments #{kwargs}"
  end

  # Normalize inputs
  if inputs.is_a?(Hash)
    inputs = [inputs]
  elsif inputs.is_a?(Enumerable)
    # Copy to avoid overriding arguments
    inputs = inputs.to_a.dup
  else
    raise ArgumentError, "Invalid arguments #{kwargs}"
  end

  inputs.each_with_index do |item, i|
    inputs[i] = normalize(item)
  end

  inputs
end

#normalize(item) ⇒ Object

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/transformers/pipelines/question_answering.rb', line 3

def normalize(item)
  if item.is_a?(SquadExample)
    return item
  elsif item.is_a?(Hash)
    [:question, :context].each do |k|
      if !item.include?(k)
        raise KeyError, "You need to provide a dictionary with keys {question:..., context:...}"
      elsif item[k].nil?
        raise ArgumentError, "`#{k}` cannot be nil"
      elsif item[k].is_a?(String) && item[k].length == 0
        raise ArgumentError, "`#{k}` cannot be empty"
      end
    end

    return QuestionAnsweringPipeline.create_sample(**item)
  end
  raise ArgumentError, "#{item} argument needs to be of type (SquadExample, dict)"
end