-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtranslate.lua
65 lines (50 loc) · 1.59 KB
/
translate.lua
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
local mp = require 'mp'
local logger = require 'logger' ('translate')
local version = require 'version'
local function text_ass()
return mp.get_property(version.is_greater('0.38.0') and 'sub-text/ass' or 'sub-text-ass')
end
---@class TranslationProvider
---@field translate fun(value: string): string | nil
---@field get_error fun(data: any): string
---@param provider TranslationProvider
---@param overlay table
---@param options table
return function (provider, overlay, options)
local avg = require 'modules.average' (options.defaultDelay, mp.get_time, options.sensitivity)
---@class Translator
local m = {}
function m.onSubChanged()
local value = text_ass()
if value == nil or value == '' then
overlay:hide()
return
end
avg:tick()
value = value:gsub('\\N', ' \\N '):gsub('\\n', ' \\n ')
logger.translator_input(value)
local ok, data = pcall(provider.translate, value)
if not ok then
return logger.error(provider.get_error(data))
end
if not data then
return logger.warning('Got empty response')
end
-- Remove occasional commas which is mostly wrong
data, _ = string.gsub(data, '[ \\Nn]+,', '')
-- Return dot on it's place.
data, _ = string.gsub(data, '[ \\Nn]+%.', '.')
local delay = options.actualDelay - avg:tick()
logger.debug('Applying sub-delay', -delay)
mp.set_property('sub-delay', -delay)
overlay:setTranslation(data, value)
logger.debug('Applying sub-delay', -delay)
logger.translator_output(data)
end
---@param delay number
function m.resetTicker(delay)
logger.debug('Resetting ticker to', delay)
avg:reset(delay)
end
return m
end