-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeech.rb
More file actions
77 lines (58 loc) · 1.71 KB
/
Copy pathspeech.rb
File metadata and controls
77 lines (58 loc) · 1.71 KB
1
2
3
4
5
6
7
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
43
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
70
71
72
73
74
75
76
77
require "google/cloud/speech"
require 'rest-client'
require 'json'
require 'base64'
class Speech
attr_reader :api_key
def initialize api_key
@api_key = api_key
end
def recognize audio_url, language = 'en-US', encoding = 'linear16', bit_rate = 8000, max_alternatives = 3
url = "https://speech.googleapis.com/v1/speech:recognize?key=#{@api_key}"
resp = do_get_request audio_url
if resp.code == 200
content = fetch_content resp.file.path
params = {
config: {
encoding: encoding,
sampleRateHertz: bit_rate,
languageCode: language,
maxAlternatives: max_alternatives
},
audio: {
content: content
}
}
response = do_post_request url, params
if response.code == 200
transcript response.body
end
end
end
def transcript response
results = JSON.parse(response)
if results["results"] && results["results"].size > 0
result = {'confidence' => 0, 'transcript' => ''}
results["results"].first["alternatives"].each do |r|
result = r if result['confidence'] < r['confidence']
end
Logger.log "Result - transcript: #{result['transcript']}, confidence: #{result['confidence']}"
result
end
end
def fetch_content file
content = nil
begin
content = File.open(file, 'rb') { |f| Base64.strict_encode64(f.read) }
rescue Exception => e
puts "File #{file} doesn't exist"
end
content
end
def do_get_request url
RestClient::Request.execute(method: :get, url: url, raw_response: true)
end
def do_post_request url, params
RestClient.post(url, params.to_json, {content_type: :json, accept: :json})
end
end