dotfiles

My personal dotfiles
git clone git://pcardensab.com/dotfiles
Log | Files | Refs | Submodules | README

deepl.lua (1887B)


      1 http_request = require("http.request")
      2 json = require("dkjson")
      3 
      4 
      5 DEEPL_API_KEY = os.getenv("DEEPL_API_KEY")
      6 overlay = mp.create_osd_overlay("ass-events")
      7 overlay.z = 10
      8 
      9 
     10 function show_translation_deepl()
     11 	local sub_text = mp.get_property('sub-text')
     12 	if sub_text and sub_text ~= "" then
     13 		local translated_text = translate_deepl(sub_text)
     14 		-- local translated_text = sub_text
     15 		local lines = {}
     16 
     17 		for line in translated_text:gmatch("[^\r\n]+") do
     18 			table.insert(lines, 1, '{\\an2}{\\1c&H00FFFF&}' .. line .. '')
     19 		end
     20 		for line in sub_text:gmatch("[^\r\n]+") do
     21 			table.insert(lines, 1, "{\\an2}\u{2000}")
     22 		end
     23 		table.insert(lines, 1, "")
     24 
     25 		overlay.data = table.concat(lines, "\n")
     26 		overlay:update()
     27 	else
     28 		print("No text to show")
     29 	end
     30 end
     31 
     32 
     33 function translate_deepl(source_text)
     34 	local req = http_request.new_from_uri('https://api-free.deepl.com/v2/translate')
     35 	req.headers:upsert(":method", "POST")
     36 	req.headers:upsert("content-type", "application/json")
     37 	req.headers:upsert("authorization", "DeepL-Auth-Key " .. DEEPL_API_KEY)
     38 
     39 	req:set_body(json.encode({
     40 		text = { source_text },
     41 		target_lang = "EN",
     42 		source_lang = "PT"
     43 	}))
     44 
     45 	local headers, stream = req:go()
     46 	if not headers then
     47 		error("Request failed")
     48 	end
     49 
     50 	body = json.decode(stream:get_body_as_string())
     51 	translated_text = json.encode(body["translations"][1]["text"])
     52 
     53 	return translated_text
     54 end
     55 
     56 
     57 function sub_ab_loop()
     58    local a = mp.get_property("sub-start")
     59    local b = mp.get_property("sub-end")
     60    local delay = mp.get_property_native("sub-delay")
     61    if a == nil or b == nil then return; end
     62    mp.set_property("ab-loop-a", a+delay-0.1)
     63    mp.set_property("ab-loop-b", b+delay)
     64 end
     65 
     66 
     67 mp.add_key_binding(nil, 'sub_ab_loop', sub_ab_loop)
     68 mp.add_key_binding(nil, 'show-translation-deepl', show_translation_deepl)
     69 
     70 mp.observe_property('sub-end', 'number', function (_, sub_end)
     71    overlay:remove()
     72 end)