File size: 9,477 Bytes
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170e15c
 
 
 
 
 
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cd6178
 
 
 
 
402daee
6cd6178
 
 
 
 
 
 
 
 
 
 
 
a1d9d40
6cd6178
 
 
402daee
 
 
 
 
 
 
 
 
 
 
170e15c
402daee
 
 
 
 
 
 
 
170e15c
 
 
 
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170e15c
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1d9d40
 
 
 
 
 
 
 
 
 
 
 
 
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170e15c
 
402daee
 
 
 
 
 
170e15c
 
402daee
 
 
 
 
 
 
 
 
 
 
170e15c
 
 
 
 
402daee
 
 
 
 
 
170e15c
843d438
402daee
e559e5b
843d438
 
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
--[[

  ReaSpeechWorker.lua - Speech transcription worker

]]--

ReaSpeechWorker = Polo {}

function ReaSpeechWorker:init()
  assert(self.requests, 'missing requests')
  assert(self.responses, 'missing responses')
  assert(self.logs, 'missing logs')

  self.active_job = nil
  self.pending_jobs = {}
  self.job_count = 0
end

function ReaSpeechWorker:react()
  local time = reaper.time_precise()
  local fs = self:interval_functions()
  for i = 1, #fs do
    app:trap(function ()
      fs[i]:react(time)
    end)
  end
end

function ReaSpeechWorker:interval_functions()
  if self._interval_functions then
    return self._interval_functions
  end

  self._interval_functions = {
    IntervalFunction.new(0.3, function () self:react_handle_request() end),
    IntervalFunction.new(0.5, function () self:react_handle_jobs() end),
  }

  return self._interval_functions
end

-- Handle next request
function ReaSpeechWorker:react_handle_request()
  local request = table.remove(self.requests, 1)
  if request then
    self:handle_request(request)
  end
end

-- Make progress on jobs
function ReaSpeechWorker:react_handle_jobs()
  if self.active_job then
    self:check_active_job()
    return
  end

  local pending_job = table.remove(self.pending_jobs, 1)
  if pending_job then
    self.active_job = pending_job
    self:start_active_job()
  elseif self.job_count ~= 0 then
    app:log('Processing finished')
    self.job_count = 0
  end
end

function ReaSpeechWorker:progress()
  local job_count = self.job_count
  if job_count == 0 then
    return nil
  end

  local pending_job_count = #self.pending_jobs

  local active_job_progress = 0

  -- the active job adds 1 to the total count, and if we can know the progress
  -- then we can use that fraction
  if self.active_job then
    if self.active_job.job and self.active_job.job.progress then
      local progress = self.active_job.job.progress
      active_job_progress = (progress.current / progress.total)
    end

    pending_job_count = pending_job_count + 1
  end

  local completed_job_count = job_count + active_job_progress - pending_job_count
  return completed_job_count / job_count
end

function ReaSpeechWorker:status()
  if self.active_job and self.active_job.job then
    return self.active_job.job.job_status
  end
end

function ReaSpeechWorker:cancel()
  if self.active_job then
    if self.active_job.job and self.active_job.job.job_id then
      self:cancel_job(self.active_job.job.job_id)
    end
    self.active_job = nil
  end
  self.pending_jobs = {}
  self.job_count = 0
end

function ReaSpeechWorker:cancel_job(job_id)
  local url_path = "jobs/" .. job_id
  ReaSpeechAPI:fetch_json(url_path, 'DELETE', function(error_message)
    self:handle_error(self.active_job, error_message)
  end)
end

function ReaSpeechWorker:get_job_status(job_id, retry_count)
  retry_count = retry_count or 0
  local max_retries = 5
  local retry_delay = 1  * (2 ^ retry_count)  -- Exponential backoff

  local url_path = "jobs/" .. job_id

  ReaSpeechAPI:fetch_json(url_path, 'GET', function(error_message)
      if error_message:match("500") and retry_count < max_retries then
          app:debug("Got 500 error, retrying in " .. retry_delay .. " seconds. Retry " .. (retry_count + 1) .. " of " .. max_retries)
          reaper.defer(function()
              self:get_job_status(job_id, retry_count + 1)
          end)
      else
          self:handle_error(self.active_job, error_message)
          self.active_job = nil
      end
  end, function(response)
    
      if self:handle_job_status(self.active_job, response) then
          self.active_job = nil
      end
  end)
end

function ReaSpeechWorker:handle_request(request)
  app:log('Processing speech...')
  self.job_count = #request.jobs

  local data = {
    task = request.translate and 'translate' or 'transcribe',
    output = 'json',
    use_async = 'true',
    vad_filter = request.vad_filter and 'true' or 'false',
    word_timestamps = 'true',
    model_name = request.model_name,
  }

  if request.language and request.language ~= '' then
    data.language = request.language
  end

  if request.hotwords and request.hotwords ~= '' then
    data.hotwords = request.hotwords
  end

  if request.initial_prompt and request.initial_prompt ~= '' then
    data.initial_prompt = request.initial_prompt
  end

  local seen_path = {}
  for _, job in pairs(request.jobs) do
    if not seen_path[job.path] then
      seen_path[job.path] = true
      table.insert(self.pending_jobs, {job = job, data = data})
    end
  end
end

-- May return true if the job has completed and should no longer be active
function ReaSpeechWorker:handle_job_status(active_job, response)
  app:debug('Active job: ' .. dump(active_job))
  app:debug('Status: ' .. dump(response))

  if response.error then
    table.insert(self.responses, { error = response.error })
    return true
  end

  active_job.job.job_id = response.job_id
  active_job.job.job_status = response.job_status

  if not response.job_status then
    return false
  end

  if response.job_status == 'SUCCESS' then
    local transcript_url_path = response.job_result.url_path
    response._job = active_job.job
    active_job.transcript_output_file, active_job.transcript_output_sentinel_file = ReaSpeechAPI:fetch_large(transcript_url_path)
    -- Job completion depends on non-blocking download of transcript
    return false
  elseif response.job_status == 'FAILURE' then
    self:handle_error(active_job, response.job_result.error)
    return true
  end

  if response.job_result and response.job_result.progress then
    active_job.job.progress = response.job_result.progress
  end

  return false
end

function ReaSpeechWorker:handle_response(active_job, response)
  response._job = active_job.job
  table.insert(self.responses, response)
end

function ReaSpeechWorker:handle_error(_active_job, error_message)
  table.insert(self.responses, { error = error_message })
end

function ReaSpeechWorker:start_active_job()
  if not self.active_job then
    return
  end

  local active_job = self.active_job
  local output_file, sentinel_file = ReaSpeechAPI:post_request('/asr', active_job.data, active_job.job.path)

  if output_file then
    active_job.request_output_file = output_file
    active_job.request_output_sentinel_file = sentinel_file
  else
    self.active_job = nil
  end
end

function ReaSpeechWorker:check_active_job()
  if not self.active_job then return end

  local active_job = self.active_job

  if active_job.request_output_file then
    self:check_active_job_request_output_file()
  end

  if active_job.transcript_output_file then
    self:check_active_job_transcript_output_file()
  else
    self:check_active_job_status()
  end
end

function ReaSpeechWorker:check_active_job_status()
  if not self.active_job then return end
  local active_job = self.active_job
  if not active_job.job.job_id then return end

  ReaSpeechAPI:fetch_json("jobs/" .. active_job.job.job_id, 'GET',
      function(error_message)
          -- Error handler
          self:handle_error(active_job, error_message)
          self.active_job = nil
      end,
      function(response)
          -- Success handler
          if self:handle_job_status(active_job, response) then
              self.active_job = nil
          end
      end
  )
end

ReaSpeechWorker.check_sentinel = function(filename)
  local sentinel = io.open(filename, 'r')

  if not sentinel then
    return false
  end

  sentinel:close()
  return true
end

function ReaSpeechWorker:handle_response_json(output_file, sentinel_file, success_f, fail_f)
  if not self.check_sentinel(sentinel_file) then
    return
  end

  local f = io.open(output_file, 'r')
  if not f then
    fail_f("Couldn't open output file: " .. tostring(output_file))
    Tempfile:remove(sentinel_file)
    return
  end

  local http_status, body = ReaSpeechAPI.http_status_and_body(f)
  f:close()

  if http_status == -1 then
    app:debug(body .. ", trying again later")
    return
  end

  if http_status ~= 200 then
    local msg = "Server responded with status " .. http_status
    fail_f(msg)
    app:log(msg)
    app:debug(body)
    return
  end

  if #body < 1 then
    fail_f("Empty response from server")
    return
  end

  local response = nil
  if app:trap(function ()
    response = json.decode(body)
  end) then
    success_f(response)
  else
    fail_f("Error parsing response JSON")
    return
  end
  -- remove tempfiles only on success, moved for debugging purposes only!
  Tempfile:remove(output_file)
  Tempfile:remove(sentinel_file)
end

function ReaSpeechWorker:check_active_job_request_output_file()
  local active_job = self.active_job

  self:handle_response_json(
    active_job.request_output_file,
    active_job.request_output_sentinel_file,
    function(response)
      if self:handle_job_status(active_job, response) then
        self.active_job = nil
      end
    end,
    function(error_message)
      self:handle_error(active_job, error_message)
      self.active_job = nil
    end
  )
end

function ReaSpeechWorker:check_active_job_transcript_output_file()
  local active_job = self.active_job

  self:handle_response_json(
    active_job.transcript_output_file,
    active_job.transcript_output_sentinel_file,
    function(response)
      self:handle_response(active_job, response)
      self.active_job = nil
    end,
    function(error_message)
      self:handle_error(active_job, error_message)
      self.active_job = nil
    end
  )
end