~singpolyma/sgx-jmp

sgx-jmp/lib/rev_ai.rb -rw-r--r-- 1.9 KiB
4ace3417Stephen Paul Weber Log errors from rev.ai 8 days ago
                                                                                
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
78
79
80
81
82
# frozen_string_literal: true

require "em-http"
require "em_promise"
require "json"

class RevAi
	class Failed < StandardError; end

	def initialize(token: CONFIG[:rev_ai_token])
		@token = token
	end

	def stt(language, media_url, callback_url, **kwargs)
		req(
			:post,
			"https://api.rev.ai/speechtotext/v1/jobs",
			metadata: { media_url: media_url }.merge(kwargs).to_json,
			source_config: { url: media_url },
			notification_config: { url: callback_url },
			remove_disfluencies: language == "en",
			skip_diarization: true,
			language: language
		)
	end

	def stt_result(job)
		job = job["job"]
		return failed(job) if job["status"] == "failed"

		req(
			:get,
			"https://api.rev.ai/speechtotext/v1/jobs/#{job['id']}/transcript",
			accept: "text/plain"
		).then do |res|
			text = res.response.split("    ", 3)[2]&.strip.to_s
			job.merge("text" => text, "metadata" => JSON.parse(job["metadata"]))
		end
	end

	def language_id(media_url, callback_url, **kwargs)
		req(
			:post,
			"https://api.rev.ai/languageid/v1/jobs",
			metadata: { media_url: media_url }.merge(kwargs).to_json,
			source_config: { url: media_url },
			notification_config: { url: callback_url }
		)
	end

	def language_id_result(job)
		job = job["job"]
		return failed(job) if job["status"] == "failed"

		req(
			:get,
			"https://api.rev.ai/languageid/v1/jobs/#{job['id']}/result"
		).then do |res|
			json = JSON.parse(res.response)
			job.merge(json).merge("metadata" => JSON.parse(job["metadata"]))
		end
	end

protected

	def req(m, url, accept: nil, **kwargs)
		EM::HttpRequest.new(
			url, tls: { verify_peer: true }
		).public_send(
			"a#{m}",
			head: {
				"Authorization" => "Bearer #{@token}",
				"Content-Type" => "application/json",
				"Accept" => accept
			}, body: kwargs.to_json
		)
	end

	def failed(job)
		EMPromise.reject(Failed.new("#{job['failure']} #{job['failure_detail']}"))
	end
end