Class: GoogleSpeech::Transcriber

Inherits:
Object
  • Object
show all
Defined in:
lib/google_speech/transcriber.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :language         => 'en-US',
  :chunk_duration   => 5,
  :overlap          => 0.5,
  :max_results      => 1,
  :request_pause    => 1,
  :profanity_filter => true
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original_file, options = nil) ⇒ Transcriber



20
21
22
23
24
# File 'lib/google_speech/transcriber.rb', line 20

def initialize(original_file, options=nil)
  @original_file = original_file
  @options = DEFAULT_OPTIONS.merge(options || {})
  @results = []
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/google_speech/transcriber.rb', line 9

def options
  @options
end

#original_fileObject

Returns the value of attribute original_file.



9
10
11
# File 'lib/google_speech/transcriber.rb', line 9

def original_file
  @original_file
end

#resultsObject

Returns the value of attribute results.



9
10
11
# File 'lib/google_speech/transcriber.rb', line 9

def results
  @results
end

Instance Method Details

#extract_result(transcripts) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/google_speech/transcriber.rb', line 44

def extract_result(transcripts)
  results = transcripts.map{|t| result_from_transcript(t)}.compact

  return {:text => '', :confidence => 0} if results.size == 0

  t = results.collect {|t| t[:text] }.join(' ')
  c = results.inject(0.0) {|s, t| s.to_f + t[:confidence].to_f } / results.size.to_f
  c = 0 if c.nan? || c.infinite?

  { :text => t, :confidence => c }
end

#loggerObject



109
110
111
# File 'lib/google_speech/transcriber.rb', line 109

def logger
  GoogleSpeech.logger
end

#pfilterObject



61
62
63
# File 'lib/google_speech/transcriber.rb', line 61

def pfilter
  options[:profanity_filter] ? '1' : '0'
end

#result_from_transcript(transcript) ⇒ Object



56
57
58
59
# File 'lib/google_speech/transcriber.rb', line 56

def result_from_transcript(transcript)
  hyp = transcript['hypotheses'].first
  hyp ? { :text => hyp['utterance'], :confidence => hyp['confidence'] } : nil
end

#transcribeObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/google_speech/transcriber.rb', line 26

def transcribe
  chunk_factory = ChunkFactory.new(@original_file, options[:chunk_duration], options[:overlap])
  chunk_factory.each{ |chunk|
    result = chunk.to_hash
    transcript = transcribe_data(chunk.data)
    next unless transcript

    result = result.merge(extract_result(transcript))

    logger.debug "#{result[:start_time]}: #{(result[:confidence].to_f * 100).to_i}%: #{result[:text]}"

    @results << result

    sleep(options[:request_pause].to_i)
  }
  @results
end

#transcribe_data(data) ⇒ Object



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
# File 'lib/google_speech/transcriber.rb', line 65

def transcribe_data(data)
  params = {
    :path     => "/speech-api/v1/recognize",
    :query    => "xjerr=1&client=chromium&lang=#{options[:language]}&maxresults=#{options[:max_results].to_i}&pfilter=#{pfilter}",
    :body     => data,
    :method   => 'POST',
    :headers  => {
      'Content-Type'   => 'audio/x-flac; rate=8000',
      'Content-Length' => data.bytesize,
      'User-Agent'     => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36"
    }
  }
  retry_max = options[:retry_max] ? [options[:retry_max].to_i, 1].max : 3
  retry_count = 0
  result = nil
  url = "https://www.google.com:443#{params[:path]}"
  while(!result && retry_count < retry_max)
    retry_count += 1

    begin
      connection = Excon.new(url)
      response = connection.request(params)
      # puts "response: #{response.inspect}\n\n"
      # puts "response.body: #{response.body}\n\n"
      if response.status.to_s.start_with?('2')
        result = []
        if (response.body && response.body.size > 0)
          result = response.body.split("\n").collect{|b| JSON.parse(b)} rescue []
        end
      else
        logger.error "transcribe_data response unsuccessful, status: #{response.status}, response: #{response.inspect}"
        sleep(1) 
      end
    rescue StandardError => err
      #need to do something to retry this - use new a13g func for this.
      logger.error "transcribe_data retrycount(#{retry_count}): error: #{err.message}"
      sleep(1)
    end

  end

  result || []
end