Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- -- Open clipboard inserter
- -- -- Wait for unknown word and add it to anki through yomichan
- -- -- Select all the subtitle lines to add to the card.
- -- -- Ctrl + c
- -- -- Tab back to MPV and Ctrl + v
- -- -- Done. The lines, their respective Audio and the current paused image
- -- -- will be added to the back of the card.
- -- -- Ctrl + t will toggle clipboard inserter on and off.
- local utils = require 'mp.utils'
- local msg = require 'mp.msg'
- local subs = {}
- local enable_subs_to_clip = true
- local use_powershell_clipboard = nil
- ------------- User Config -------------
- -- Set these to match your field names in Anki
- local FRONT_FIELD = "Front"
- local SENTENCE_AUDIO_FIELD = "Sentence-Audio"
- local SENTENCE_FIELD = "Sentence"
- local IMAGE_FIELD = "Image"
- -- Anki collection media path. Ensure Anki username is correct.
- local prefix = utils.join_path(os.getenv('APPDATA'), [[Anki2\User 1\collection.media]])
- -- Optional padding and fade settings in seconds
- local AUDIO_CLIP_FADE = 0.2
- local AUDIO_CLIP_PADDING = 0.75
- ---------------------------------------
- local function clean(s)
- local newtext = string.gsub(s, "\n", "")
- newtext = string.gsub(newtext, "\r", "")
- return string.gsub(newtext, "^%s*(.-)%s*$", "%1")
- end
- local function get_name(s, e)
- return mp.get_property("filename"):gsub('%W','').. tostring(s) .. tostring(e)
- end
- local function get_clipboard()
- local res = utils.subprocess({ args = {
- 'powershell', '-NoProfile', '-Command', [[& {
- Trap {
- Write-Error -ErrorRecord $_
- Exit 1
- }
- $clip = ""
- if (Get-Command "Get-Clipboard" -errorAction SilentlyContinue) {
- $clip = Get-Clipboard -Raw -Format Text -TextFormatType UnicodeText
- } else {
- Add-Type -AssemblyName PresentationCore
- $clip = [Windows.Clipboard]::GetText()
- }
- $clip = $clip -Replace "`r",""
- $u8clip = [System.Text.Encoding]::UTF8.GetBytes($clip)
- [Console]::OpenStandardOutput().Write($u8clip, 0, $u8clip.Length)
- }]]
- } })
- if not res.error then
- return res.stdout
- end
- end
- local function powershell_set_clipboard(text)
- utils.subprocess({ args = {
- 'powershell', '-NoProfile', '-Command', [[Set-Clipboard -Value @"]] .. "\n" .. text .. "\n" .. [["@]]
- }})
- end
- local function cmd_set_clipboard(text)
- local cmd = 'echo ' .. text .. ' | clip';
- mp.command("run cmd /D /C " .. cmd);
- end
- local function determine_clip_type()
- powershell_set_clipboard([[Anacreon様]])
- use_powershell_clipboard = get_clipboard() == [[Anacreon様]]
- end
- local function record_sub(name, text)
- if text and mp.get_property_number('sub-start') and mp.get_property_number('sub-end') then
- local sub_delay = mp.get_property_native("sub-delay")
- local newtext = clean(text)
- if newtext == '' then
- return
- end
- subs[newtext] = { mp.get_property_number('sub-start') + sub_delay, mp.get_property_number('sub-end') + sub_delay }
- if enable_subs_to_clip then
- if use_powershell_clipboard == nil then
- determine_clip_type()
- end
- if use_powershell_clipboard then
- powershell_set_clipboard(newtext)
- else
- cmd_set_clipboard(newtext)
- end
- end
- end
- end
- local function create_audio(s, e)
- if s == nil or e == nil then
- return
- end
- local name = get_name(s, e)
- s = s - AUDIO_CLIP_PADDING
- local t = e - s + AUDIO_CLIP_PADDING
- local source = mp.get_property("path")
- local destination = utils.join_path(prefix, name .. '.mp3')
- mp.commandv(
- 'run',
- 'mpv',
- source,
- '--loop-file=no',
- '--video=no',
- '--no-ocopy-metadata',
- '--no-sub',
- '--audio-channels=1',
- string.format('--start=%.3f', s),
- string.format('--length=%.3f', t),
- string.format('--aid=%s', mp.get_property("aid")),
- string.format("--af-append=afade=t=in:curve=ipar:st=%.3f:d=%.3f", s, AUDIO_CLIP_FADE),
- string.format("--af-append=afade=t=out:curve=ipar:st=%.3f:d=%.3f", s + t - AUDIO_CLIP_FADE, AUDIO_CLIP_FADE),
- string.format('-o=%s', destination)
- )
- end
- local function create_screenshot(s, e)
- local source = mp.get_property("path")
- local img = utils.join_path(prefix, get_name(s,e) .. '.webp')
- mp.commandv(
- 'run',
- 'mpv',
- source,
- '--loop-file=no',
- '--audio=no',
- '--no-ocopy-metadata',
- '--no-sub',
- '--frames=1',
- '--ovc=libwebp',
- '--ovcopts-add=lossless=0',
- '--ovcopts-add=compression_level=6',
- '--ovcopts-add=preset=drawing',
- '--vf-add=scale=-2:480',
- string.format('--start=%.3f', mp.get_property_number("time-pos")),
- string.format('-o=%s', img)
- )
- end
- local function get(request)
- local args = {
- 'powershell', '-NoProfile', '-Command', [[& {
- $data = Invoke-RestMethod -Uri http://127.0.0.1:8765 -Method Post -ContentType 'application/json; charset=UTF-8' -Body @"]] .. "\n" .. request .. "\n" .. [["@ | ConvertTo-Json -Depth 10
- $u8data = [System.Text.Encoding]::UTF8.GetBytes($data)
- [Console]::OpenStandardOutput().Write($u8data, 0, $u8data.Length)
- }]]
- }
- local result = utils.subprocess({ args = args, cancellable = true, capture_stderr = true })
- print(result.stdout)
- print(result.stderr)
- return utils.parse_json(result.stdout)
- end
- local function add_to_last_added(ifield, afield, tfield)
- local noteid = math.max(unpack(get('{"action": "findNotes", "params": {"query": "added:1"}, "version": 6}')["result"]))
- local note = get('{"action": "notesInfo", "params": {"notes": ['.. noteid.. ']}, "version": 6}')
- ifield = string.gsub(ifield, "\"", "\\\"")
- afield = string.gsub(afield, "\"", "\\\"")
- tfield = string.gsub(tfield, "\"", "\\\"")
- if note ~= nil then
- get('{"action": "updateNoteFields", "version": 6, "params": {"note": {"id": ' .. noteid.. ', "fields": {"' .. SENTENCE_AUDIO_FIELD .. '": "' .. afield .. '","' .. SENTENCE_FIELD .. '": "' .. tfield .. '","' .. IMAGE_FIELD .. '": "' .. ifield .. '"} } } }')
- mp.osd_message("Updated note: " .. note["result"][1]["fields"][FRONT_FIELD]["value"], 3)
- msg.info("Updated note: " .. note["result"][1]["fields"][FRONT_FIELD]["value"])
- end
- end
- local function get_extract()
- local lines = get_clipboard()
- local e = 0
- local s = 0
- for line in lines:gmatch("[^\r\n]+") do
- line = clean(line)
- if subs[line]~= nil then
- msg.info(lines)
- if subs[line][1] ~= nil and subs[line][2] ~= nil then
- if s == 0 then
- s = subs[line][1]
- else
- s = math.min(s, subs[line][1])
- end
- e = math.max(e, subs[line][2])
- end
- end
- end
- if e ~= 0 then
- create_screenshot(s, e)
- create_audio(s, e)
- local ifield = '<img src='.. get_name(s,e) ..'.webp>'
- local afield = "[sound:".. get_name(s,e) .. ".mp3]"
- local tfield = string.gsub(string.gsub(lines,"\n+", "<br />"), "\r", "")
- add_to_last_added(ifield, afield, tfield)
- end
- end
- local function ex()
- pcall(get_extract)
- end
- local function rec(...)
- --pcall(record_sub, ...)
- record_sub(...)
- end
- local function toggle_sub_to_clipboard()
- enable_subs_to_clip = not enable_subs_to_clip
- mp.osd_message("Clipboard inserter " .. (enable_subs_to_clip and "activated" or "deactived"), 3)
- end
- mp.observe_property("sub-text", 'string', rec)
- mp.add_key_binding("ctrl+v", ex)
- mp.add_key_binding("ctrl+t", toggle_sub_to_clipboard)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement